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": ";;;; Copyright 2016 Peter Stephens. All Rights Reserved.\r\n;;;;\r\n;;;; Licensed unde", "end": 36, "score": 0.9997149109840393, "start": 22, "tag": "NAME", "value": "Peter Stephens" }, { "context": " [2])) [0 :chapter-idx])))\r\n (is (= [:Job :Jeremiah :Matthew] (vec (map :id (<? (b/book [17 23 39])))", "end": 2119, "score": 0.9945633411407471, "start": 2111, "tag": "NAME", "value": "Jeremiah" }, { "context": ":chapter-idx])))\r\n (is (= [:Job :Jeremiah :Matthew] (vec (map :id (<? (b/book [17 23 39]))))))\r\n ", "end": 2128, "score": 0.9929410815238953, "start": 2121, "tag": "NAME", "value": "Matthew" }, { "context": "ting \"Pure functional model\"\r\n (let [gen {:id :Geneis\r\n :idx 0\r\n :chapter", "end": 2329, "score": 0.6952642202377319, "start": 2325, "tag": "NAME", "value": "Gene" }, { "context": " \"Pure functional model\"\r\n (let [gen {:id :Geneis\r\n :idx 0\r\n :chapter-c", "end": 2331, "score": 0.6181720495223999, "start": 2329, "tag": "USERNAME", "value": "is" }, { "context": " :chapter-idx 0}\r\n exo {:id :Exodus\r\n :idx 1\r\n :chapter-c", "end": 2445, "score": 0.7640621066093445, "start": 2439, "tag": "NAME", "value": "Exodus" }, { "context": "5])))\r\n (is (thrown? js/Error (b/chapter m [\"John\"])))\r\n (is (= [0 2 3] (vec (map :idx (b/chap", "end": 3206, "score": 0.9977746605873108, "start": 3202, "tag": "NAME", "value": "John" }, { "context": "ting \"Pure functional model\"\r\n (let [gen {:id :Geneis\r\n :idx 0\r\n :chapter-c", "end": 3901, "score": 0.9209657311439514, "start": 3895, "tag": "NAME", "value": "Geneis" }, { "context": " :chapter-idx 0}\r\n exo {:id :Exodus\r\n :idx 1\r\n :chapter-c", "end": 4015, "score": 0.9017496109008789, "start": 4009, "tag": "NAME", "value": "Exodus" }, { "context": "Ps 46:10\")\r\n\r\n (is\r\n (= [\"And that Jacob obeyed his father and his mother, and was gone to", "end": 7893, "score": 0.9947690963745117, "start": 7888, "tag": "NAME", "value": "Jacob" } ]
src/test/browser/bible/coretests.cljs
pstephens/kingjames.bible
23
;;;; Copyright 2016 Peter Stephens. All Rights Reserved. ;;;; ;;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;;; you may not use this file except in compliance with the License. ;;;; You may obtain a copy of the License at ;;;; ;;;; http://www.apache.org/licenses/LICENSE-2.0 ;;;; ;;;; Unless required by applicable law or agreed to in writing, software ;;;; distributed under the License is distributed on an "AS IS" BASIS, ;;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;;; See the License for the specific language governing permissions and ;;;; limitations under the License. (ns test.browser.bible.coretests (:require-macros [bible.macros :refer [<?]] [cljs.core.async.macros :refer [go]]) (:require [bible.core :as b] [bible.helpers] [cljs.core.async :refer [<!]] [cljs.test :refer-macros [async deftest testing is]])) (deftest book (testing "Pure functional model" (let [m {"B" {:books [{:id :Genesis :idx 0 :chapter-cnt 50 :chapter-idx 0} {:id :Exodus :idx 1 :chapter-cnt 40 :chapter-idx 50} {:id :Leviticus :idx 2 :chapter-cnt 27 :chapter-idx 90}]}}] (is (= :Genesis (get-in (b/book m [0]) [0 :id]))) (is (= :Leviticus (get-in (b/book m [2]) [0 :id]))) (is (thrown? js/Error (b/book m [-1]))) (is (thrown? js/Error (b/book m [3]))) (is (= [:Genesis :Exodus :Leviticus] (vec (map :id (b/book m [0 1 2]))))) (is (= [:Leviticus :Genesis :Exodus] (vec (map :id (b/book m [2 0 1]))))))) (testing "I/O against resource" (async done (go (is (= :Genesis (get-in (<? (b/book [0])) [0 :id]))) (is (= 65 (get-in (<? (b/book [65])) [0 :idx]))) (is (= 150 (get-in (<? (b/book [18])) [0 :chapter-cnt]))) (is (= 90 (get-in (<? (b/book [2])) [0 :chapter-idx]))) (is (= [:Job :Jeremiah :Matthew] (vec (map :id (<? (b/book [17 23 39])))))) (is (thrown? js/Error (<? (b/book [75 39])))) (done))))) (deftest chapter (testing "Pure functional model" (let [gen {:id :Geneis :idx 0 :chapter-cnt 2 :chapter-idx 0} exo {:id :Exodus :idx 1 :chapter-cnt 3 :chapter-idx 2} m {"B" {:books [gen exo] :chapters [{:idx 0 :book gen :verse-cnt 31 :verse-idx 0} {:idx 1 :book gen :verse-cnt 25 :verse-idx 31} {:idx 2 :book exo :verse-cnt 22 :verse-idx 56} {:idx 3 :book exo :verse-cnt 25 :verse-idx 78} {:idx 4 :book exo :verse-cnt 22 :verse-idx 103}]}}] (is (= 0 (get-in (b/chapter m [0]) [0 :idx]))) (is (= 3 (get-in (b/chapter m [3]) [0 :idx]))) (is (thrown? js/Error (b/chapter m [-1]))) (is (thrown? js/Error (b/chapter m [5]))) (is (thrown? js/Error (b/chapter m ["John"]))) (is (= [0 2 3] (vec (map :idx (b/chapter m [0 2 3]))))) (is (= [4 3 1] (vec (map :idx (b/chapter m [4 3 1]))))))) (testing "I/O against resource" (async done (go (is (= 0 (get-in (<? (b/chapter [0])) [0 :idx]))) (is (= 13 (get-in (<? (b/chapter [437])) [0 :verse-cnt]))) (is (= 56 (get-in (<? (b/chapter [2])) [0 :verse-idx]))) (is (= :Jude (get-in (<? (b/chapter [1166])) [0 :book :id]))) (is (= [50 52 54] (vec (map :idx (<? (b/chapter [50 52 54])))))) (is (thrown? js/Error (<? (b/chapter [1300])))) (done))))) (deftest verse (testing "Pure functional model" (let [gen {:id :Geneis :idx 0 :chapter-cnt 2 :chapter-idx 0} exo {:id :Exodus :idx 1 :chapter-cnt 3 :chapter-idx 2} b {:books [gen exo] :chapters [{:idx 0 :book gen :verse-cnt 4 :verse-idx 0} {:idx 1 :book gen :verse-cnt 5 :verse-idx 4} {:idx 2 :book exo :verse-cnt 3 :verse-idx 9} {:idx 3 :book exo :verse-cnt 1 :verse-idx 12} {:idx 4 :book exo :verse-cnt 3 :verse-idx 13}] :partition-size 2} v0 ["V1" "V2"] v1 ["V3" "V4"] v2 ["V5" "V6"] v3 ["V7" "V8"] v4 ["V9" "V10"] v5 ["V11" "V12"] v6 ["V13" "V14"] v7 ["V15" "V16"] m {"B" b "V00" v0 "V01" v1 "V02" v2 "V03" v3 "V04" v4 "V05" v5 "V06" v6 "V07" v7}] (is (= "V1" (get-in (b/verse m [0]) [0 :content]))) (is (= "V6" (get-in (b/verse m [5]) [0 :content]))) (is (= "V16" (get-in (b/verse m [15]) [0 :content]))) (is (thrown? js/Error (b/verse m [25]))) (is (thrown? js/Error (b/verse m [-1]))) (is (= ["V2" "V7" "V15"] (->> (b/verse m [1 6 14]) (map :content) (vec)))) (is (= ["V7" "V15" "V2"] (->> (b/verse m [6 14 1]) (map :content) (vec)))) (is (thrown? js/Error (b/verse m [5 6 -1]))) (is (= 3 (get-in (b/verse m [12]) [0 :chapter :idx]))) (is (= 4 (get-in (b/verse m [13]) [0 :chapter :idx]))) (is (= 0 (get-in (b/verse m [0]) [0 :chapter :idx]))) (is (= 4 (get-in (b/verse m [15]) [0 :chapter :idx]))) (is (thrown? js/Error (b/verse m [16]))) (is (= 0 (get-in (b/verse m [0]) [0 :idx]))) (is (= 7 (get-in (b/verse m [7]) [0 :idx]))) (is (= 15 (get-in (b/verse m [15]) [0 :idx]))))) (testing "I/O against resource" (async done (go (is (= "And God said, Let there be a firmament in the midst of the waters, and let it divide the waters from the waters." (get-in (<? (b/verse [5])) [0 :content])) ":content Gen 1:5") (is (= "The grace of our Lord Jesus Christ [be] with you all. Amen." (get-in (<? (b/verse [31230])) [0 :content])) ":content Rev 22:21") (is (= "And he shewed me a pure river of water of life, clear as crystal, proceeding out of the throne of God and of the Lamb." (get-in (<? (b/verse [31210])) [0 :content])) ":content Rev 22:1") (is (= "And there shall in no wise enter into it any thing that defileth, neither [whatsoever] worketh abomination, or [maketh] a lie: but they which are written in the Lamb's book of life." (get-in (<? (b/verse [31209])) [0 :content])) ":content Rev 21:27") (is (= "Be still, and know that I [am] God: I will be exalted among the heathen, I will be exalted in the earth." (get-in (<? (b/verse [14665])) [0 :content])) ":content Ps 46:10") (is (= 0 (get-in (<? (b/verse [5])) [0 :chapter :idx])) ":chapter Gen 1:5") (is (= 1188 (get-in (<? (b/verse [31230])) [0 :chapter :idx])) ":chapter Rev 22:21") (is (= 1188 (get-in (<? (b/verse [31210])) [0 :chapter :idx])) ":chapter Rev 22:1") (is (= 1187 (get-in (<? (b/verse [31209])) [0 :chapter :idx])) ":chapter Rev 21:27") (is (= 523 (get-in (<? (b/verse [14665])) [0 :chapter :idx])) ":chapter Ps 46:10") (is (= 5 (get-in (<? (b/verse [5])) [0 :idx])) ":idx Gen 1:5") (is (= 31230 (get-in (<? (b/verse [31230])) [0 :idx])) ":idx Rev 22:21") (is (= 31210 (get-in (<? (b/verse [31210])) [0 :idx])) ":idx Rev 22:1") (is (= 31209 (get-in (<? (b/verse [31209])) [0 :idx])) ":idx Rev 21:27") (is (= 14665 (get-in (<? (b/verse [14665])) [0 :idx])) ":idx Ps 46:10") (is (= ["And that Jacob obeyed his father and his mother, and was gone to Padanaram;" "And Esau seeing that the daughters of Canaan pleased not Isaac his father;"] (->> (<? (b/verse [780 781])) (map :content) (vec))) "Fetch across partition boundaries.") (is (thrown? js/Error (<? (b/verse [31231])))) (done)))))
46834
;;;; Copyright 2016 <NAME>. All Rights Reserved. ;;;; ;;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;;; you may not use this file except in compliance with the License. ;;;; You may obtain a copy of the License at ;;;; ;;;; http://www.apache.org/licenses/LICENSE-2.0 ;;;; ;;;; Unless required by applicable law or agreed to in writing, software ;;;; distributed under the License is distributed on an "AS IS" BASIS, ;;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;;; See the License for the specific language governing permissions and ;;;; limitations under the License. (ns test.browser.bible.coretests (:require-macros [bible.macros :refer [<?]] [cljs.core.async.macros :refer [go]]) (:require [bible.core :as b] [bible.helpers] [cljs.core.async :refer [<!]] [cljs.test :refer-macros [async deftest testing is]])) (deftest book (testing "Pure functional model" (let [m {"B" {:books [{:id :Genesis :idx 0 :chapter-cnt 50 :chapter-idx 0} {:id :Exodus :idx 1 :chapter-cnt 40 :chapter-idx 50} {:id :Leviticus :idx 2 :chapter-cnt 27 :chapter-idx 90}]}}] (is (= :Genesis (get-in (b/book m [0]) [0 :id]))) (is (= :Leviticus (get-in (b/book m [2]) [0 :id]))) (is (thrown? js/Error (b/book m [-1]))) (is (thrown? js/Error (b/book m [3]))) (is (= [:Genesis :Exodus :Leviticus] (vec (map :id (b/book m [0 1 2]))))) (is (= [:Leviticus :Genesis :Exodus] (vec (map :id (b/book m [2 0 1]))))))) (testing "I/O against resource" (async done (go (is (= :Genesis (get-in (<? (b/book [0])) [0 :id]))) (is (= 65 (get-in (<? (b/book [65])) [0 :idx]))) (is (= 150 (get-in (<? (b/book [18])) [0 :chapter-cnt]))) (is (= 90 (get-in (<? (b/book [2])) [0 :chapter-idx]))) (is (= [:Job :<NAME> :<NAME>] (vec (map :id (<? (b/book [17 23 39])))))) (is (thrown? js/Error (<? (b/book [75 39])))) (done))))) (deftest chapter (testing "Pure functional model" (let [gen {:id :<NAME>is :idx 0 :chapter-cnt 2 :chapter-idx 0} exo {:id :<NAME> :idx 1 :chapter-cnt 3 :chapter-idx 2} m {"B" {:books [gen exo] :chapters [{:idx 0 :book gen :verse-cnt 31 :verse-idx 0} {:idx 1 :book gen :verse-cnt 25 :verse-idx 31} {:idx 2 :book exo :verse-cnt 22 :verse-idx 56} {:idx 3 :book exo :verse-cnt 25 :verse-idx 78} {:idx 4 :book exo :verse-cnt 22 :verse-idx 103}]}}] (is (= 0 (get-in (b/chapter m [0]) [0 :idx]))) (is (= 3 (get-in (b/chapter m [3]) [0 :idx]))) (is (thrown? js/Error (b/chapter m [-1]))) (is (thrown? js/Error (b/chapter m [5]))) (is (thrown? js/Error (b/chapter m ["<NAME>"]))) (is (= [0 2 3] (vec (map :idx (b/chapter m [0 2 3]))))) (is (= [4 3 1] (vec (map :idx (b/chapter m [4 3 1]))))))) (testing "I/O against resource" (async done (go (is (= 0 (get-in (<? (b/chapter [0])) [0 :idx]))) (is (= 13 (get-in (<? (b/chapter [437])) [0 :verse-cnt]))) (is (= 56 (get-in (<? (b/chapter [2])) [0 :verse-idx]))) (is (= :Jude (get-in (<? (b/chapter [1166])) [0 :book :id]))) (is (= [50 52 54] (vec (map :idx (<? (b/chapter [50 52 54])))))) (is (thrown? js/Error (<? (b/chapter [1300])))) (done))))) (deftest verse (testing "Pure functional model" (let [gen {:id :<NAME> :idx 0 :chapter-cnt 2 :chapter-idx 0} exo {:id :<NAME> :idx 1 :chapter-cnt 3 :chapter-idx 2} b {:books [gen exo] :chapters [{:idx 0 :book gen :verse-cnt 4 :verse-idx 0} {:idx 1 :book gen :verse-cnt 5 :verse-idx 4} {:idx 2 :book exo :verse-cnt 3 :verse-idx 9} {:idx 3 :book exo :verse-cnt 1 :verse-idx 12} {:idx 4 :book exo :verse-cnt 3 :verse-idx 13}] :partition-size 2} v0 ["V1" "V2"] v1 ["V3" "V4"] v2 ["V5" "V6"] v3 ["V7" "V8"] v4 ["V9" "V10"] v5 ["V11" "V12"] v6 ["V13" "V14"] v7 ["V15" "V16"] m {"B" b "V00" v0 "V01" v1 "V02" v2 "V03" v3 "V04" v4 "V05" v5 "V06" v6 "V07" v7}] (is (= "V1" (get-in (b/verse m [0]) [0 :content]))) (is (= "V6" (get-in (b/verse m [5]) [0 :content]))) (is (= "V16" (get-in (b/verse m [15]) [0 :content]))) (is (thrown? js/Error (b/verse m [25]))) (is (thrown? js/Error (b/verse m [-1]))) (is (= ["V2" "V7" "V15"] (->> (b/verse m [1 6 14]) (map :content) (vec)))) (is (= ["V7" "V15" "V2"] (->> (b/verse m [6 14 1]) (map :content) (vec)))) (is (thrown? js/Error (b/verse m [5 6 -1]))) (is (= 3 (get-in (b/verse m [12]) [0 :chapter :idx]))) (is (= 4 (get-in (b/verse m [13]) [0 :chapter :idx]))) (is (= 0 (get-in (b/verse m [0]) [0 :chapter :idx]))) (is (= 4 (get-in (b/verse m [15]) [0 :chapter :idx]))) (is (thrown? js/Error (b/verse m [16]))) (is (= 0 (get-in (b/verse m [0]) [0 :idx]))) (is (= 7 (get-in (b/verse m [7]) [0 :idx]))) (is (= 15 (get-in (b/verse m [15]) [0 :idx]))))) (testing "I/O against resource" (async done (go (is (= "And God said, Let there be a firmament in the midst of the waters, and let it divide the waters from the waters." (get-in (<? (b/verse [5])) [0 :content])) ":content Gen 1:5") (is (= "The grace of our Lord Jesus Christ [be] with you all. Amen." (get-in (<? (b/verse [31230])) [0 :content])) ":content Rev 22:21") (is (= "And he shewed me a pure river of water of life, clear as crystal, proceeding out of the throne of God and of the Lamb." (get-in (<? (b/verse [31210])) [0 :content])) ":content Rev 22:1") (is (= "And there shall in no wise enter into it any thing that defileth, neither [whatsoever] worketh abomination, or [maketh] a lie: but they which are written in the Lamb's book of life." (get-in (<? (b/verse [31209])) [0 :content])) ":content Rev 21:27") (is (= "Be still, and know that I [am] God: I will be exalted among the heathen, I will be exalted in the earth." (get-in (<? (b/verse [14665])) [0 :content])) ":content Ps 46:10") (is (= 0 (get-in (<? (b/verse [5])) [0 :chapter :idx])) ":chapter Gen 1:5") (is (= 1188 (get-in (<? (b/verse [31230])) [0 :chapter :idx])) ":chapter Rev 22:21") (is (= 1188 (get-in (<? (b/verse [31210])) [0 :chapter :idx])) ":chapter Rev 22:1") (is (= 1187 (get-in (<? (b/verse [31209])) [0 :chapter :idx])) ":chapter Rev 21:27") (is (= 523 (get-in (<? (b/verse [14665])) [0 :chapter :idx])) ":chapter Ps 46:10") (is (= 5 (get-in (<? (b/verse [5])) [0 :idx])) ":idx Gen 1:5") (is (= 31230 (get-in (<? (b/verse [31230])) [0 :idx])) ":idx Rev 22:21") (is (= 31210 (get-in (<? (b/verse [31210])) [0 :idx])) ":idx Rev 22:1") (is (= 31209 (get-in (<? (b/verse [31209])) [0 :idx])) ":idx Rev 21:27") (is (= 14665 (get-in (<? (b/verse [14665])) [0 :idx])) ":idx Ps 46:10") (is (= ["And that <NAME> obeyed his father and his mother, and was gone to Padanaram;" "And Esau seeing that the daughters of Canaan pleased not Isaac his father;"] (->> (<? (b/verse [780 781])) (map :content) (vec))) "Fetch across partition boundaries.") (is (thrown? js/Error (<? (b/verse [31231])))) (done)))))
true
;;;; Copyright 2016 PI:NAME:<NAME>END_PI. All Rights Reserved. ;;;; ;;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;;; you may not use this file except in compliance with the License. ;;;; You may obtain a copy of the License at ;;;; ;;;; http://www.apache.org/licenses/LICENSE-2.0 ;;;; ;;;; Unless required by applicable law or agreed to in writing, software ;;;; distributed under the License is distributed on an "AS IS" BASIS, ;;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;;; See the License for the specific language governing permissions and ;;;; limitations under the License. (ns test.browser.bible.coretests (:require-macros [bible.macros :refer [<?]] [cljs.core.async.macros :refer [go]]) (:require [bible.core :as b] [bible.helpers] [cljs.core.async :refer [<!]] [cljs.test :refer-macros [async deftest testing is]])) (deftest book (testing "Pure functional model" (let [m {"B" {:books [{:id :Genesis :idx 0 :chapter-cnt 50 :chapter-idx 0} {:id :Exodus :idx 1 :chapter-cnt 40 :chapter-idx 50} {:id :Leviticus :idx 2 :chapter-cnt 27 :chapter-idx 90}]}}] (is (= :Genesis (get-in (b/book m [0]) [0 :id]))) (is (= :Leviticus (get-in (b/book m [2]) [0 :id]))) (is (thrown? js/Error (b/book m [-1]))) (is (thrown? js/Error (b/book m [3]))) (is (= [:Genesis :Exodus :Leviticus] (vec (map :id (b/book m [0 1 2]))))) (is (= [:Leviticus :Genesis :Exodus] (vec (map :id (b/book m [2 0 1]))))))) (testing "I/O against resource" (async done (go (is (= :Genesis (get-in (<? (b/book [0])) [0 :id]))) (is (= 65 (get-in (<? (b/book [65])) [0 :idx]))) (is (= 150 (get-in (<? (b/book [18])) [0 :chapter-cnt]))) (is (= 90 (get-in (<? (b/book [2])) [0 :chapter-idx]))) (is (= [:Job :PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI] (vec (map :id (<? (b/book [17 23 39])))))) (is (thrown? js/Error (<? (b/book [75 39])))) (done))))) (deftest chapter (testing "Pure functional model" (let [gen {:id :PI:NAME:<NAME>END_PIis :idx 0 :chapter-cnt 2 :chapter-idx 0} exo {:id :PI:NAME:<NAME>END_PI :idx 1 :chapter-cnt 3 :chapter-idx 2} m {"B" {:books [gen exo] :chapters [{:idx 0 :book gen :verse-cnt 31 :verse-idx 0} {:idx 1 :book gen :verse-cnt 25 :verse-idx 31} {:idx 2 :book exo :verse-cnt 22 :verse-idx 56} {:idx 3 :book exo :verse-cnt 25 :verse-idx 78} {:idx 4 :book exo :verse-cnt 22 :verse-idx 103}]}}] (is (= 0 (get-in (b/chapter m [0]) [0 :idx]))) (is (= 3 (get-in (b/chapter m [3]) [0 :idx]))) (is (thrown? js/Error (b/chapter m [-1]))) (is (thrown? js/Error (b/chapter m [5]))) (is (thrown? js/Error (b/chapter m ["PI:NAME:<NAME>END_PI"]))) (is (= [0 2 3] (vec (map :idx (b/chapter m [0 2 3]))))) (is (= [4 3 1] (vec (map :idx (b/chapter m [4 3 1]))))))) (testing "I/O against resource" (async done (go (is (= 0 (get-in (<? (b/chapter [0])) [0 :idx]))) (is (= 13 (get-in (<? (b/chapter [437])) [0 :verse-cnt]))) (is (= 56 (get-in (<? (b/chapter [2])) [0 :verse-idx]))) (is (= :Jude (get-in (<? (b/chapter [1166])) [0 :book :id]))) (is (= [50 52 54] (vec (map :idx (<? (b/chapter [50 52 54])))))) (is (thrown? js/Error (<? (b/chapter [1300])))) (done))))) (deftest verse (testing "Pure functional model" (let [gen {:id :PI:NAME:<NAME>END_PI :idx 0 :chapter-cnt 2 :chapter-idx 0} exo {:id :PI:NAME:<NAME>END_PI :idx 1 :chapter-cnt 3 :chapter-idx 2} b {:books [gen exo] :chapters [{:idx 0 :book gen :verse-cnt 4 :verse-idx 0} {:idx 1 :book gen :verse-cnt 5 :verse-idx 4} {:idx 2 :book exo :verse-cnt 3 :verse-idx 9} {:idx 3 :book exo :verse-cnt 1 :verse-idx 12} {:idx 4 :book exo :verse-cnt 3 :verse-idx 13}] :partition-size 2} v0 ["V1" "V2"] v1 ["V3" "V4"] v2 ["V5" "V6"] v3 ["V7" "V8"] v4 ["V9" "V10"] v5 ["V11" "V12"] v6 ["V13" "V14"] v7 ["V15" "V16"] m {"B" b "V00" v0 "V01" v1 "V02" v2 "V03" v3 "V04" v4 "V05" v5 "V06" v6 "V07" v7}] (is (= "V1" (get-in (b/verse m [0]) [0 :content]))) (is (= "V6" (get-in (b/verse m [5]) [0 :content]))) (is (= "V16" (get-in (b/verse m [15]) [0 :content]))) (is (thrown? js/Error (b/verse m [25]))) (is (thrown? js/Error (b/verse m [-1]))) (is (= ["V2" "V7" "V15"] (->> (b/verse m [1 6 14]) (map :content) (vec)))) (is (= ["V7" "V15" "V2"] (->> (b/verse m [6 14 1]) (map :content) (vec)))) (is (thrown? js/Error (b/verse m [5 6 -1]))) (is (= 3 (get-in (b/verse m [12]) [0 :chapter :idx]))) (is (= 4 (get-in (b/verse m [13]) [0 :chapter :idx]))) (is (= 0 (get-in (b/verse m [0]) [0 :chapter :idx]))) (is (= 4 (get-in (b/verse m [15]) [0 :chapter :idx]))) (is (thrown? js/Error (b/verse m [16]))) (is (= 0 (get-in (b/verse m [0]) [0 :idx]))) (is (= 7 (get-in (b/verse m [7]) [0 :idx]))) (is (= 15 (get-in (b/verse m [15]) [0 :idx]))))) (testing "I/O against resource" (async done (go (is (= "And God said, Let there be a firmament in the midst of the waters, and let it divide the waters from the waters." (get-in (<? (b/verse [5])) [0 :content])) ":content Gen 1:5") (is (= "The grace of our Lord Jesus Christ [be] with you all. Amen." (get-in (<? (b/verse [31230])) [0 :content])) ":content Rev 22:21") (is (= "And he shewed me a pure river of water of life, clear as crystal, proceeding out of the throne of God and of the Lamb." (get-in (<? (b/verse [31210])) [0 :content])) ":content Rev 22:1") (is (= "And there shall in no wise enter into it any thing that defileth, neither [whatsoever] worketh abomination, or [maketh] a lie: but they which are written in the Lamb's book of life." (get-in (<? (b/verse [31209])) [0 :content])) ":content Rev 21:27") (is (= "Be still, and know that I [am] God: I will be exalted among the heathen, I will be exalted in the earth." (get-in (<? (b/verse [14665])) [0 :content])) ":content Ps 46:10") (is (= 0 (get-in (<? (b/verse [5])) [0 :chapter :idx])) ":chapter Gen 1:5") (is (= 1188 (get-in (<? (b/verse [31230])) [0 :chapter :idx])) ":chapter Rev 22:21") (is (= 1188 (get-in (<? (b/verse [31210])) [0 :chapter :idx])) ":chapter Rev 22:1") (is (= 1187 (get-in (<? (b/verse [31209])) [0 :chapter :idx])) ":chapter Rev 21:27") (is (= 523 (get-in (<? (b/verse [14665])) [0 :chapter :idx])) ":chapter Ps 46:10") (is (= 5 (get-in (<? (b/verse [5])) [0 :idx])) ":idx Gen 1:5") (is (= 31230 (get-in (<? (b/verse [31230])) [0 :idx])) ":idx Rev 22:21") (is (= 31210 (get-in (<? (b/verse [31210])) [0 :idx])) ":idx Rev 22:1") (is (= 31209 (get-in (<? (b/verse [31209])) [0 :idx])) ":idx Rev 21:27") (is (= 14665 (get-in (<? (b/verse [14665])) [0 :idx])) ":idx Ps 46:10") (is (= ["And that PI:NAME:<NAME>END_PI obeyed his father and his mother, and was gone to Padanaram;" "And Esau seeing that the daughters of Canaan pleased not Isaac his father;"] (->> (<? (b/verse [780 781])) (map :content) (vec))) "Fetch across partition boundaries.") (is (thrown? js/Error (<? (b/verse [31231])))) (done)))))
[ { "context": " schema :facts\n [{:db/id 1\n :person/name \"Shmi Skywalker\"\n :person/children 9 ;\"Anakin Skywalker\"\n ", "end": 915, "score": 0.9998528361320496, "start": 901, "tag": "NAME", "value": "Shmi Skywalker" }, { "context": "/name \"Shmi Skywalker\"\n :person/children 9 ;\"Anakin Skywalker\"\n :person/gender \"female\"}\n {:db/id 2\n ", "end": 960, "score": 0.9941280484199524, "start": 944, "tag": "NAME", "value": "Anakin Skywalker" }, { "context": "nder \"female\"}\n {:db/id 2\n :person/name \"Cliegg Lars\"\n :person/children 5 ;\"Owen Lars\"\n :per", "end": 1039, "score": 0.9994297027587891, "start": 1028, "tag": "NAME", "value": "Cliegg Lars" }, { "context": "son/name \"Cliegg Lars\"\n :person/children 5 ;\"Owen Lars\"\n :person/gender \"male\"}\n {:db/id 3\n ", "end": 1077, "score": 0.9717597961425781, "start": 1068, "tag": "NAME", "value": "Owen Lars" }, { "context": "gender \"male\"}\n {:db/id 3\n :person/name \"Ruwee Naberrie\"\n :person/children 9 ;\"Padme Amadala\"\n ", "end": 1157, "score": 0.9998864531517029, "start": 1143, "tag": "NAME", "value": "Ruwee Naberrie" }, { "context": "/name \"Ruwee Naberrie\"\n :person/children 9 ;\"Padme Amadala\"\n :person/gender \"male\"}\n {:db/id 4\n ", "end": 1199, "score": 0.9995104670524597, "start": 1186, "tag": "NAME", "value": "Padme Amadala" }, { "context": "gender \"male\"}\n {:db/id 4\n :person/name \"Jobal Naberrie\"\n :person/children 9 ;\"Padme Amidala\"\n ", "end": 1279, "score": 0.9998834729194641, "start": 1265, "tag": "NAME", "value": "Jobal Naberrie" }, { "context": "/name \"Jobal Naberrie\"\n :person/children 9 ;\"Padme Amidala\"\n :person/gender \"female\"}\n {:db/id 5\n ", "end": 1321, "score": 0.9995735287666321, "start": 1308, "tag": "NAME", "value": "Padme Amidala" }, { "context": "nder \"female\"}\n {:db/id 5\n :person/name \"Owen Lars\"\n :person/ancestor 2; \"Cliegg Lars\"\n :p", "end": 1398, "score": 0.9998377561569214, "start": 1389, "tag": "NAME", "value": "Owen Lars" }, { "context": "erson/name \"Owen Lars\"\n :person/ancestor 2; \"Cliegg Lars\"\n :person/children 11; \"Luke Skywalker\"\n ", "end": 1438, "score": 0.8086884021759033, "start": 1427, "tag": "NAME", "value": "Cliegg Lars" }, { "context": "stor 2; \"Cliegg Lars\"\n :person/children 11; \"Luke Skywalker\"\n :person/gender \"male\"}\n {:db/id 6\n ", "end": 1482, "score": 0.9835150837898254, "start": 1468, "tag": "NAME", "value": "Luke Skywalker" }, { "context": "gender \"male\"}\n {:db/id 6\n :person/name \"Beru Lars\"\n :person/children 11; \"Luke Skywalker\"\n ", "end": 1557, "score": 0.9998590350151062, "start": 1548, "tag": "NAME", "value": "Beru Lars" }, { "context": "rson/name \"Beru Lars\"\n :person/children 11; \"Luke Skywalker\"\n :person/gender \"female\"}\n {:db/id 7\n ", "end": 1601, "score": 0.9711510539054871, "start": 1587, "tag": "NAME", "value": "Luke Skywalker" }, { "context": "nder \"female\"}\n {:db/id 7\n :person/name \"Bail Organa\"\n :person/children 13; \"Princess Leia\"\n ", "end": 1680, "score": 0.9998896718025208, "start": 1669, "tag": "NAME", "value": "Bail Organa" }, { "context": "on/name \"Bail Organa\"\n :person/children 13; \"Princess Leia\"\n :person/gender \"male\"}\n {:db/id 8\n ", "end": 1723, "score": 0.9998214840888977, "start": 1710, "tag": "NAME", "value": "Princess Leia" }, { "context": "gender \"male\"}\n {:db/id 8\n :person/name \"Breha Organa\"\n :person/children 13; \"Princess Leia\"\n ", "end": 1801, "score": 0.9998874664306641, "start": 1789, "tag": "NAME", "value": "Breha Organa" }, { "context": "n/name \"Breha Organa\"\n :person/children 13; \"Princess Leia\"\n :person/gender \"female\"}\n {:db/id 9\n ", "end": 1844, "score": 0.9998550415039062, "start": 1831, "tag": "NAME", "value": "Princess Leia" }, { "context": "nder \"female\"}\n {:db/id 9\n :person/name \"Anakin Skywalker\"\n :person/ancestor 1; \"Shmi Skywalker\"\n ", "end": 1928, "score": 0.9998875856399536, "start": 1912, "tag": "NAME", "value": "Anakin Skywalker" }, { "context": "ame \"Anakin Skywalker\"\n :person/ancestor 1; \"Shmi Skywalker\"\n :person/children [11 13]\n :person/gen", "end": 1971, "score": 0.8493366837501526, "start": 1957, "tag": "NAME", "value": "Shmi Skywalker" }, { "context": "ender \"male\"}\n {:db/id 10\n :person/name \"Padme Amadala\"\n :person/ancestor [3 4]\n :person/child", "end": 2082, "score": 0.9998899698257446, "start": 2069, "tag": "NAME", "value": "Padme Amadala" }, { "context": "der \"female\"}\n {:db/id 11\n :person/name \"Luke Skywalker\"\n :person/ancestor [5 6 9 10]\n :person/", "end": 2225, "score": 0.9998584389686584, "start": 2211, "tag": "NAME", "value": "Luke Skywalker" }, { "context": "n/ancestor [5 6 9 10]\n :person/children 15; \"Ben Skywalker\"\n :person/gender \"male\"}\n {:db/id 12\n ", "end": 2302, "score": 0.9995992183685303, "start": 2289, "tag": "NAME", "value": "Ben Skywalker" }, { "context": "ender \"male\"}\n {:db/id 12\n :person/name \"Mara Jade\"\n :person/children 15; \"Ben Skywalker\"\n ", "end": 2378, "score": 0.9998635053634644, "start": 2369, "tag": "NAME", "value": "Mara Jade" }, { "context": "rson/name \"Mara Jade\"\n :person/children 15; \"Ben Skywalker\"\n :person/gender \"female\"}\n {:db/id 13\n ", "end": 2421, "score": 0.9997109770774841, "start": 2408, "tag": "NAME", "value": "Ben Skywalker" }, { "context": "der \"female\"}\n {:db/id 13\n :person/name \"Princess Leia\"\n :person/ancestor [7 8 9 10]\n :person/", "end": 2503, "score": 0.9998739361763, "start": 2490, "tag": "NAME", "value": "Princess Leia" }, { "context": "der \"female\"}\n {:db/id 14\n :person/name \"Han Solo\"\n :person/children [16 17 18]\n :person/", "end": 2648, "score": 0.9998722076416016, "start": 2640, "tag": "NAME", "value": "Han Solo" }, { "context": "ender \"male\"}\n {:db/id 15\n :person/name \"Ben Skywalker\"\n :person/ancestor [11 12]\n :person/gen", "end": 2762, "score": 0.9998116493225098, "start": 2749, "tag": "NAME", "value": "Ben Skywalker" }, { "context": "ender \"male\"}\n {:db/id 16\n :person/name \"Jaina Solo\"\n :person/ancestor [13 14]\n :person/gen", "end": 2870, "score": 0.9998788833618164, "start": 2860, "tag": "NAME", "value": "Jaina Solo" }, { "context": "der \"female\"}\n {:db/id 17\n :person/name \"Jacen Solo\"\n :person/ancestor [13 14]\n :person/gen", "end": 2980, "score": 0.9998548626899719, "start": 2970, "tag": "NAME", "value": "Jacen Solo" }, { "context": "ender \"male\"}\n {:db/id 18\n :person/name \"Anakin Solo\"\n :person/ancestor [13 14]\n :person/gen", "end": 3089, "score": 0.9998036623001099, "start": 3078, "tag": "NAME", "value": "Anakin Solo" }, { "context": " [13 14]\n :person/gender \"male\"}]))\n\n\n;; Find Luke's father + step-dad\n(c/println (d/q '[:find ?dad\n", "end": 3168, "score": 0.9944741725921631, "start": 3164, "tag": "NAME", "value": "Luke" }, { "context": " :where\n [?e1 :person/name \"Luke Skywalker\"]\n [?e2 :person/children ?e1]\n ", "end": 3294, "score": 0.9998257160186768, "start": 3280, "tag": "NAME", "value": "Luke Skywalker" }, { "context": "gender \"male\"]]\n @test-atom))\n\n;; Find Luke's mom (step-mom too)\n(c/println (d/q '[:find ?ste", "end": 3470, "score": 0.9921742677688599, "start": 3466, "tag": "NAME", "value": "Luke" }, { "context": " :where\n [?e1 :person/name \"Luke Skywalker\"]\n [?e2 :person/children ?e1]\n ", "end": 3602, "score": 0.9998094439506531, "start": 3588, "tag": "NAME", "value": "Luke Skywalker" }, { "context": "om))\n\n;; FIXME: correct the other examples here\n;; Luke has one grandpa + a step-grandpa\n(c/println (d/q ", "end": 3822, "score": 0.9914092421531677, "start": 3818, "tag": "NAME", "value": "Luke" }, { "context": " :where\n [?e1 :person/name \"Luke Skywalker\"]\n [?e2 :person/children ?e1]\n ", "end": 3965, "score": 0.9998018741607666, "start": 3951, "tag": "NAME", "value": "Luke Skywalker" }, { "context": "dd-facts! test-atom\n {:db/id 19\n :person/name \"Chewbacca\"\n :person/ancestor 20}\n {:db/id 9\n :person/a", "end": 4709, "score": 0.9998286962509155, "start": 4700, "tag": "NAME", "value": "Chewbacca" }, { "context": "person/children 22}\n {:db/id 22\n :person/name \"Jar Jar Binks\"\n :person/gender \"male\"})\n\n;; Try reloading the", "end": 5842, "score": 0.9994202852249146, "start": 5829, "tag": "NAME", "value": "Jar Jar Binks" } ]
examples/star-wars/datascript.cljs
greenyouse/multco
6
(ns examples.star-wars.datascript (:require [cljs.core :as c] ;crazy repl issues because of datscript namespacing [datascript :as d] [multco.core :as m])) ;; Do a datascript schema like normal. (def schema {:person/name {} :person/ancestor {:db/cardinality :db.cardinality/many :db/valueType :db.type/ref} :person/children {:db/cardinality :db.cardinality/many :db/valueType :db.type/ref} :person/gender {}}) ;; This serves as a default set of datums. Any subsequent additions ;; or retractions will be saved and override this set of datums. ;; This allows a program to store its info persistently! ;; For reference: http://www.chartgeek.com/star-wars-family-tree/ ;; (it takes the place of datascript's conn) (def test-atom (m/datascript-atom "test" "datascript-test" schema :facts [{:db/id 1 :person/name "Shmi Skywalker" :person/children 9 ;"Anakin Skywalker" :person/gender "female"} {:db/id 2 :person/name "Cliegg Lars" :person/children 5 ;"Owen Lars" :person/gender "male"} {:db/id 3 :person/name "Ruwee Naberrie" :person/children 9 ;"Padme Amadala" :person/gender "male"} {:db/id 4 :person/name "Jobal Naberrie" :person/children 9 ;"Padme Amidala" :person/gender "female"} {:db/id 5 :person/name "Owen Lars" :person/ancestor 2; "Cliegg Lars" :person/children 11; "Luke Skywalker" :person/gender "male"} {:db/id 6 :person/name "Beru Lars" :person/children 11; "Luke Skywalker" :person/gender "female"} {:db/id 7 :person/name "Bail Organa" :person/children 13; "Princess Leia" :person/gender "male"} {:db/id 8 :person/name "Breha Organa" :person/children 13; "Princess Leia" :person/gender "female"} {:db/id 9 :person/name "Anakin Skywalker" :person/ancestor 1; "Shmi Skywalker" :person/children [11 13] :person/gender "male"} {:db/id 10 :person/name "Padme Amadala" :person/ancestor [3 4] :person/children [11 13] :person/gender "female"} {:db/id 11 :person/name "Luke Skywalker" :person/ancestor [5 6 9 10] :person/children 15; "Ben Skywalker" :person/gender "male"} {:db/id 12 :person/name "Mara Jade" :person/children 15; "Ben Skywalker" :person/gender "female"} {:db/id 13 :person/name "Princess Leia" :person/ancestor [7 8 9 10] :person/children [16 17 18] :person/gender "female"} {:db/id 14 :person/name "Han Solo" :person/children [16 17 18] :person/gender "male"} {:db/id 15 :person/name "Ben Skywalker" :person/ancestor [11 12] :person/gender "male"} {:db/id 16 :person/name "Jaina Solo" :person/ancestor [13 14] :person/gender "female"} {:db/id 17 :person/name "Jacen Solo" :person/ancestor [13 14] :person/gender "male"} {:db/id 18 :person/name "Anakin Solo" :person/ancestor [13 14] :person/gender "male"}])) ;; Find Luke's father + step-dad (c/println (d/q '[:find ?dad :where [?e1 :person/name "Luke Skywalker"] [?e2 :person/children ?e1] [?e2 :person/name ?dad] [?e2 :person/gender "male"]] @test-atom)) ;; Find Luke's mom (step-mom too) (c/println (d/q '[:find ?step-mom :where [?e1 :person/name "Luke Skywalker"] [?e2 :person/children ?e1] [?e2 :person/name ?step-mom] [?e2 :person/gender "female"]] @test-atom)) ;; FIXME: correct the other examples here ;; Luke has one grandpa + a step-grandpa (c/println (d/q '[:find ?grandpa :where [?e1 :person/name "Luke Skywalker"] [?e2 :person/children ?e1] [?e2 :person/ancestor ?e3] [?e3 :person/name ?grandpa] [?e3 :person/gender "male"]] @test-atom)) ;; let's find all the father-children relations (c/println (d/q '[:find ?father ?child :where [?e1 :person/name ?child] [?e1 :person/gender "male"] [?e2 :person/children ?e1] [?e2 :person/name ?father] [?e2 :person/gender "male"]] @test-atom)) ;; Now let's add more datums to our database and see how the changes are ;; reflected in the queries (m/add-facts! test-atom {:db/id 19 :person/name "Chewbacca" :person/ancestor 20} {:db/id 9 :person/ancestor 20} {:db/id 20 :person/name "???" :person/children [19 9]}) ; chewie and anakin ;; So now we have unknown fathers in our data (c/println (d/q '[:find ?dad ?child :where [?e1 :person/name ?child] [?e2 :person/children ?e1] [?e2 :person/name ?dad] [?e2 :person/name "???"]] @test-atom)) ;; Let's get rid of that and go back to the default (m/rm-facts! test-atom [:db.fn/retractEntity 19] [:db.fn/retractEntity 20]) ;; Double-check that the datums are gone (c/println (d/q '[:find ?dad ?child :where [?e1 :person/name ?child] [?e2 :person/children ?e1] [?e2 :person/name ?dad] [?e2 :person/name "???"]] @test-atom)) ;; What if we only care about one relationship and want to delete ;; everything else? Just reset the database: (m/reset-facts! test-atom {:db/id 21 :person/name "???" :person/children 22} {:db/id 22 :person/name "Jar Jar Binks" :person/gender "male"}) ;; Try reloading the page and evaluting test-atom and the relations above ;; it. Now check to see if the change we made persisted. ;; Is Jar Jar really the only thing we have? (c/println (d/q '[:find ?ppl :where [?e1 :person/name ?ppl]] @test-atom)) ;; Yup, Jar Jar is the only thing in there (oh no) and everything worked! ;; If you want to delete this experiment do: (m/clear! test-atom) ;; and here's how to delete the entire database: (m/rm-db test-atom)
58378
(ns examples.star-wars.datascript (:require [cljs.core :as c] ;crazy repl issues because of datscript namespacing [datascript :as d] [multco.core :as m])) ;; Do a datascript schema like normal. (def schema {:person/name {} :person/ancestor {:db/cardinality :db.cardinality/many :db/valueType :db.type/ref} :person/children {:db/cardinality :db.cardinality/many :db/valueType :db.type/ref} :person/gender {}}) ;; This serves as a default set of datums. Any subsequent additions ;; or retractions will be saved and override this set of datums. ;; This allows a program to store its info persistently! ;; For reference: http://www.chartgeek.com/star-wars-family-tree/ ;; (it takes the place of datascript's conn) (def test-atom (m/datascript-atom "test" "datascript-test" schema :facts [{:db/id 1 :person/name "<NAME>" :person/children 9 ;"<NAME>" :person/gender "female"} {:db/id 2 :person/name "<NAME>" :person/children 5 ;"<NAME>" :person/gender "male"} {:db/id 3 :person/name "<NAME>" :person/children 9 ;"<NAME>" :person/gender "male"} {:db/id 4 :person/name "<NAME>" :person/children 9 ;"<NAME>" :person/gender "female"} {:db/id 5 :person/name "<NAME>" :person/ancestor 2; "<NAME>" :person/children 11; "<NAME>" :person/gender "male"} {:db/id 6 :person/name "<NAME>" :person/children 11; "<NAME>" :person/gender "female"} {:db/id 7 :person/name "<NAME>" :person/children 13; "<NAME>" :person/gender "male"} {:db/id 8 :person/name "<NAME>" :person/children 13; "<NAME>" :person/gender "female"} {:db/id 9 :person/name "<NAME>" :person/ancestor 1; "<NAME>" :person/children [11 13] :person/gender "male"} {:db/id 10 :person/name "<NAME>" :person/ancestor [3 4] :person/children [11 13] :person/gender "female"} {:db/id 11 :person/name "<NAME>" :person/ancestor [5 6 9 10] :person/children 15; "<NAME>" :person/gender "male"} {:db/id 12 :person/name "<NAME>" :person/children 15; "<NAME>" :person/gender "female"} {:db/id 13 :person/name "<NAME>" :person/ancestor [7 8 9 10] :person/children [16 17 18] :person/gender "female"} {:db/id 14 :person/name "<NAME>" :person/children [16 17 18] :person/gender "male"} {:db/id 15 :person/name "<NAME>" :person/ancestor [11 12] :person/gender "male"} {:db/id 16 :person/name "<NAME>" :person/ancestor [13 14] :person/gender "female"} {:db/id 17 :person/name "<NAME>" :person/ancestor [13 14] :person/gender "male"} {:db/id 18 :person/name "<NAME>" :person/ancestor [13 14] :person/gender "male"}])) ;; Find <NAME>'s father + step-dad (c/println (d/q '[:find ?dad :where [?e1 :person/name "<NAME>"] [?e2 :person/children ?e1] [?e2 :person/name ?dad] [?e2 :person/gender "male"]] @test-atom)) ;; Find <NAME>'s mom (step-mom too) (c/println (d/q '[:find ?step-mom :where [?e1 :person/name "<NAME>"] [?e2 :person/children ?e1] [?e2 :person/name ?step-mom] [?e2 :person/gender "female"]] @test-atom)) ;; FIXME: correct the other examples here ;; <NAME> has one grandpa + a step-grandpa (c/println (d/q '[:find ?grandpa :where [?e1 :person/name "<NAME>"] [?e2 :person/children ?e1] [?e2 :person/ancestor ?e3] [?e3 :person/name ?grandpa] [?e3 :person/gender "male"]] @test-atom)) ;; let's find all the father-children relations (c/println (d/q '[:find ?father ?child :where [?e1 :person/name ?child] [?e1 :person/gender "male"] [?e2 :person/children ?e1] [?e2 :person/name ?father] [?e2 :person/gender "male"]] @test-atom)) ;; Now let's add more datums to our database and see how the changes are ;; reflected in the queries (m/add-facts! test-atom {:db/id 19 :person/name "<NAME>" :person/ancestor 20} {:db/id 9 :person/ancestor 20} {:db/id 20 :person/name "???" :person/children [19 9]}) ; chewie and anakin ;; So now we have unknown fathers in our data (c/println (d/q '[:find ?dad ?child :where [?e1 :person/name ?child] [?e2 :person/children ?e1] [?e2 :person/name ?dad] [?e2 :person/name "???"]] @test-atom)) ;; Let's get rid of that and go back to the default (m/rm-facts! test-atom [:db.fn/retractEntity 19] [:db.fn/retractEntity 20]) ;; Double-check that the datums are gone (c/println (d/q '[:find ?dad ?child :where [?e1 :person/name ?child] [?e2 :person/children ?e1] [?e2 :person/name ?dad] [?e2 :person/name "???"]] @test-atom)) ;; What if we only care about one relationship and want to delete ;; everything else? Just reset the database: (m/reset-facts! test-atom {:db/id 21 :person/name "???" :person/children 22} {:db/id 22 :person/name "<NAME>" :person/gender "male"}) ;; Try reloading the page and evaluting test-atom and the relations above ;; it. Now check to see if the change we made persisted. ;; Is Jar Jar really the only thing we have? (c/println (d/q '[:find ?ppl :where [?e1 :person/name ?ppl]] @test-atom)) ;; Yup, Jar Jar is the only thing in there (oh no) and everything worked! ;; If you want to delete this experiment do: (m/clear! test-atom) ;; and here's how to delete the entire database: (m/rm-db test-atom)
true
(ns examples.star-wars.datascript (:require [cljs.core :as c] ;crazy repl issues because of datscript namespacing [datascript :as d] [multco.core :as m])) ;; Do a datascript schema like normal. (def schema {:person/name {} :person/ancestor {:db/cardinality :db.cardinality/many :db/valueType :db.type/ref} :person/children {:db/cardinality :db.cardinality/many :db/valueType :db.type/ref} :person/gender {}}) ;; This serves as a default set of datums. Any subsequent additions ;; or retractions will be saved and override this set of datums. ;; This allows a program to store its info persistently! ;; For reference: http://www.chartgeek.com/star-wars-family-tree/ ;; (it takes the place of datascript's conn) (def test-atom (m/datascript-atom "test" "datascript-test" schema :facts [{:db/id 1 :person/name "PI:NAME:<NAME>END_PI" :person/children 9 ;"PI:NAME:<NAME>END_PI" :person/gender "female"} {:db/id 2 :person/name "PI:NAME:<NAME>END_PI" :person/children 5 ;"PI:NAME:<NAME>END_PI" :person/gender "male"} {:db/id 3 :person/name "PI:NAME:<NAME>END_PI" :person/children 9 ;"PI:NAME:<NAME>END_PI" :person/gender "male"} {:db/id 4 :person/name "PI:NAME:<NAME>END_PI" :person/children 9 ;"PI:NAME:<NAME>END_PI" :person/gender "female"} {:db/id 5 :person/name "PI:NAME:<NAME>END_PI" :person/ancestor 2; "PI:NAME:<NAME>END_PI" :person/children 11; "PI:NAME:<NAME>END_PI" :person/gender "male"} {:db/id 6 :person/name "PI:NAME:<NAME>END_PI" :person/children 11; "PI:NAME:<NAME>END_PI" :person/gender "female"} {:db/id 7 :person/name "PI:NAME:<NAME>END_PI" :person/children 13; "PI:NAME:<NAME>END_PI" :person/gender "male"} {:db/id 8 :person/name "PI:NAME:<NAME>END_PI" :person/children 13; "PI:NAME:<NAME>END_PI" :person/gender "female"} {:db/id 9 :person/name "PI:NAME:<NAME>END_PI" :person/ancestor 1; "PI:NAME:<NAME>END_PI" :person/children [11 13] :person/gender "male"} {:db/id 10 :person/name "PI:NAME:<NAME>END_PI" :person/ancestor [3 4] :person/children [11 13] :person/gender "female"} {:db/id 11 :person/name "PI:NAME:<NAME>END_PI" :person/ancestor [5 6 9 10] :person/children 15; "PI:NAME:<NAME>END_PI" :person/gender "male"} {:db/id 12 :person/name "PI:NAME:<NAME>END_PI" :person/children 15; "PI:NAME:<NAME>END_PI" :person/gender "female"} {:db/id 13 :person/name "PI:NAME:<NAME>END_PI" :person/ancestor [7 8 9 10] :person/children [16 17 18] :person/gender "female"} {:db/id 14 :person/name "PI:NAME:<NAME>END_PI" :person/children [16 17 18] :person/gender "male"} {:db/id 15 :person/name "PI:NAME:<NAME>END_PI" :person/ancestor [11 12] :person/gender "male"} {:db/id 16 :person/name "PI:NAME:<NAME>END_PI" :person/ancestor [13 14] :person/gender "female"} {:db/id 17 :person/name "PI:NAME:<NAME>END_PI" :person/ancestor [13 14] :person/gender "male"} {:db/id 18 :person/name "PI:NAME:<NAME>END_PI" :person/ancestor [13 14] :person/gender "male"}])) ;; Find PI:NAME:<NAME>END_PI's father + step-dad (c/println (d/q '[:find ?dad :where [?e1 :person/name "PI:NAME:<NAME>END_PI"] [?e2 :person/children ?e1] [?e2 :person/name ?dad] [?e2 :person/gender "male"]] @test-atom)) ;; Find PI:NAME:<NAME>END_PI's mom (step-mom too) (c/println (d/q '[:find ?step-mom :where [?e1 :person/name "PI:NAME:<NAME>END_PI"] [?e2 :person/children ?e1] [?e2 :person/name ?step-mom] [?e2 :person/gender "female"]] @test-atom)) ;; FIXME: correct the other examples here ;; PI:NAME:<NAME>END_PI has one grandpa + a step-grandpa (c/println (d/q '[:find ?grandpa :where [?e1 :person/name "PI:NAME:<NAME>END_PI"] [?e2 :person/children ?e1] [?e2 :person/ancestor ?e3] [?e3 :person/name ?grandpa] [?e3 :person/gender "male"]] @test-atom)) ;; let's find all the father-children relations (c/println (d/q '[:find ?father ?child :where [?e1 :person/name ?child] [?e1 :person/gender "male"] [?e2 :person/children ?e1] [?e2 :person/name ?father] [?e2 :person/gender "male"]] @test-atom)) ;; Now let's add more datums to our database and see how the changes are ;; reflected in the queries (m/add-facts! test-atom {:db/id 19 :person/name "PI:NAME:<NAME>END_PI" :person/ancestor 20} {:db/id 9 :person/ancestor 20} {:db/id 20 :person/name "???" :person/children [19 9]}) ; chewie and anakin ;; So now we have unknown fathers in our data (c/println (d/q '[:find ?dad ?child :where [?e1 :person/name ?child] [?e2 :person/children ?e1] [?e2 :person/name ?dad] [?e2 :person/name "???"]] @test-atom)) ;; Let's get rid of that and go back to the default (m/rm-facts! test-atom [:db.fn/retractEntity 19] [:db.fn/retractEntity 20]) ;; Double-check that the datums are gone (c/println (d/q '[:find ?dad ?child :where [?e1 :person/name ?child] [?e2 :person/children ?e1] [?e2 :person/name ?dad] [?e2 :person/name "???"]] @test-atom)) ;; What if we only care about one relationship and want to delete ;; everything else? Just reset the database: (m/reset-facts! test-atom {:db/id 21 :person/name "???" :person/children 22} {:db/id 22 :person/name "PI:NAME:<NAME>END_PI" :person/gender "male"}) ;; Try reloading the page and evaluting test-atom and the relations above ;; it. Now check to see if the change we made persisted. ;; Is Jar Jar really the only thing we have? (c/println (d/q '[:find ?ppl :where [?e1 :person/name ?ppl]] @test-atom)) ;; Yup, Jar Jar is the only thing in there (oh no) and everything worked! ;; If you want to delete this experiment do: (m/clear! test-atom) ;; and here's how to delete the entire database: (m/rm-db test-atom)
[ { "context": "t [entity-type \"outputs\"\n entity-name \"test\"\n outputs (resources/read-resource \"", "end": 2955, "score": 0.8360868096351624, "start": 2951, "tag": "NAME", "value": "test" } ]
api/test/wfl/integration/rawls_test.clj
broadinstitute/wfl
15
(ns wfl.integration.rawls-test (:require [clojure.test :refer [deftest is testing use-fixtures]] [wfl.service.firecloud :as firecloud] [wfl.service.rawls :as rawls] [wfl.tools.fixtures :as fixtures] [wfl.tools.resources :as resources] [wfl.util :as util]) (:import [clojure.lang ExceptionInfo])) ;; A known TDR Dev snapshot ID (def snapshot-id "7cb392d8-949b-419d-b40b-d039617d2fc7") (let [new-env {"WFL_FIRECLOUD_URL" "https://firecloud-orchestration.dsde-dev.broadinstitute.org"}] (use-fixtures :once (fixtures/temporary-environment new-env))) (deftest test-snapshot-references (fixtures/with-temporary-workspace "general-dev-billing-account/test-workspace" "hornet-eng" (fn [workspace] (letfn [(make-reference [snapshot-name] (rawls/create-snapshot-reference workspace snapshot-id snapshot-name)) (verify-reference [[{:keys [attributes metadata] :as _reference} snapshot-names]] (is (= "DATA_REPO_SNAPSHOT" (:resourceType metadata))) (is (= snapshot-id (:snapshot attributes))) (is (= snapshot-names (:name metadata)))) (verify-references [references snapshot-names] (->> (map list references snapshot-names) (run! verify-reference)))] (let [names ["snapshot1" "snapshot2"] reference-ids (testing "Create" (let [references (map make-reference names)] (verify-references references names) (map #(get-in % [:metadata :resourceId]) references)))] (testing "Get" (let [references (map #(rawls/get-snapshot-reference workspace %) reference-ids)] (verify-references references names))) (testing "Get all for snapshot id" (let [[_first _second & rest :as references] (rawls/get-snapshot-references-for-snapshot-id workspace snapshot-id 10)] (is (empty? rest)) (verify-references references names))) (testing "Create or get" (let [reference (rawls/create-or-get-snapshot-reference workspace snapshot-id (first names))] (verify-reference [reference (first names)]))) (testing "Create already exists" (is (thrown-with-msg? ExceptionInfo #"clj-http: status 409" (make-reference (first names)))))))))) (deftest test-batch-upsert-entities (let [entity-type "outputs" entity-name "test" outputs (resources/read-resource "sarscov2_illumina_full/outputs.edn")] (fixtures/with-temporary-workspace "general-dev-billing-account/test-workspace" "hornet-eng" (fn [workspace] (rawls/batch-upsert workspace [[entity-type entity-name outputs]]) (let [[{:keys [name attributes]} & _] (util/poll #(not-empty (firecloud/list-entities workspace entity-type)))] (is (= name entity-name) "The test entity was not created") (is (= (util/map-vals #(if (map? %) (:items %) %) attributes) (into {} (filter second outputs)))))))))
81558
(ns wfl.integration.rawls-test (:require [clojure.test :refer [deftest is testing use-fixtures]] [wfl.service.firecloud :as firecloud] [wfl.service.rawls :as rawls] [wfl.tools.fixtures :as fixtures] [wfl.tools.resources :as resources] [wfl.util :as util]) (:import [clojure.lang ExceptionInfo])) ;; A known TDR Dev snapshot ID (def snapshot-id "7cb392d8-949b-419d-b40b-d039617d2fc7") (let [new-env {"WFL_FIRECLOUD_URL" "https://firecloud-orchestration.dsde-dev.broadinstitute.org"}] (use-fixtures :once (fixtures/temporary-environment new-env))) (deftest test-snapshot-references (fixtures/with-temporary-workspace "general-dev-billing-account/test-workspace" "hornet-eng" (fn [workspace] (letfn [(make-reference [snapshot-name] (rawls/create-snapshot-reference workspace snapshot-id snapshot-name)) (verify-reference [[{:keys [attributes metadata] :as _reference} snapshot-names]] (is (= "DATA_REPO_SNAPSHOT" (:resourceType metadata))) (is (= snapshot-id (:snapshot attributes))) (is (= snapshot-names (:name metadata)))) (verify-references [references snapshot-names] (->> (map list references snapshot-names) (run! verify-reference)))] (let [names ["snapshot1" "snapshot2"] reference-ids (testing "Create" (let [references (map make-reference names)] (verify-references references names) (map #(get-in % [:metadata :resourceId]) references)))] (testing "Get" (let [references (map #(rawls/get-snapshot-reference workspace %) reference-ids)] (verify-references references names))) (testing "Get all for snapshot id" (let [[_first _second & rest :as references] (rawls/get-snapshot-references-for-snapshot-id workspace snapshot-id 10)] (is (empty? rest)) (verify-references references names))) (testing "Create or get" (let [reference (rawls/create-or-get-snapshot-reference workspace snapshot-id (first names))] (verify-reference [reference (first names)]))) (testing "Create already exists" (is (thrown-with-msg? ExceptionInfo #"clj-http: status 409" (make-reference (first names)))))))))) (deftest test-batch-upsert-entities (let [entity-type "outputs" entity-name "<NAME>" outputs (resources/read-resource "sarscov2_illumina_full/outputs.edn")] (fixtures/with-temporary-workspace "general-dev-billing-account/test-workspace" "hornet-eng" (fn [workspace] (rawls/batch-upsert workspace [[entity-type entity-name outputs]]) (let [[{:keys [name attributes]} & _] (util/poll #(not-empty (firecloud/list-entities workspace entity-type)))] (is (= name entity-name) "The test entity was not created") (is (= (util/map-vals #(if (map? %) (:items %) %) attributes) (into {} (filter second outputs)))))))))
true
(ns wfl.integration.rawls-test (:require [clojure.test :refer [deftest is testing use-fixtures]] [wfl.service.firecloud :as firecloud] [wfl.service.rawls :as rawls] [wfl.tools.fixtures :as fixtures] [wfl.tools.resources :as resources] [wfl.util :as util]) (:import [clojure.lang ExceptionInfo])) ;; A known TDR Dev snapshot ID (def snapshot-id "7cb392d8-949b-419d-b40b-d039617d2fc7") (let [new-env {"WFL_FIRECLOUD_URL" "https://firecloud-orchestration.dsde-dev.broadinstitute.org"}] (use-fixtures :once (fixtures/temporary-environment new-env))) (deftest test-snapshot-references (fixtures/with-temporary-workspace "general-dev-billing-account/test-workspace" "hornet-eng" (fn [workspace] (letfn [(make-reference [snapshot-name] (rawls/create-snapshot-reference workspace snapshot-id snapshot-name)) (verify-reference [[{:keys [attributes metadata] :as _reference} snapshot-names]] (is (= "DATA_REPO_SNAPSHOT" (:resourceType metadata))) (is (= snapshot-id (:snapshot attributes))) (is (= snapshot-names (:name metadata)))) (verify-references [references snapshot-names] (->> (map list references snapshot-names) (run! verify-reference)))] (let [names ["snapshot1" "snapshot2"] reference-ids (testing "Create" (let [references (map make-reference names)] (verify-references references names) (map #(get-in % [:metadata :resourceId]) references)))] (testing "Get" (let [references (map #(rawls/get-snapshot-reference workspace %) reference-ids)] (verify-references references names))) (testing "Get all for snapshot id" (let [[_first _second & rest :as references] (rawls/get-snapshot-references-for-snapshot-id workspace snapshot-id 10)] (is (empty? rest)) (verify-references references names))) (testing "Create or get" (let [reference (rawls/create-or-get-snapshot-reference workspace snapshot-id (first names))] (verify-reference [reference (first names)]))) (testing "Create already exists" (is (thrown-with-msg? ExceptionInfo #"clj-http: status 409" (make-reference (first names)))))))))) (deftest test-batch-upsert-entities (let [entity-type "outputs" entity-name "PI:NAME:<NAME>END_PI" outputs (resources/read-resource "sarscov2_illumina_full/outputs.edn")] (fixtures/with-temporary-workspace "general-dev-billing-account/test-workspace" "hornet-eng" (fn [workspace] (rawls/batch-upsert workspace [[entity-type entity-name outputs]]) (let [[{:keys [name attributes]} & _] (util/poll #(not-empty (firecloud/list-entities workspace entity-type)))] (is (= name entity-name) "The test entity was not created") (is (= (util/map-vals #(if (map? %) (:items %) %) attributes) (into {} (filter second outputs)))))))))
[ { "context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li", "end": 111, "score": 0.9998083114624023, "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.999823808670044, "start": 113, "tag": "NAME", "value": "Christian Murray" } ]
editor/tasks/leiningen/ref_doc.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 leiningen.ref-doc "Copy/download ref-doc and unzip." (:require [clojure.java.io :as io] [clojure.string :as str] [leiningen.util.http-cache :as http-cache]) (:import (java.util.zip ZipFile))) (defn- delete-dir "Delete a directory and its contents." [path] (let [dir (io/file path)] (when (.exists dir) (doseq [file (reverse (file-seq dir))] (io/delete-file file))))) (defn- unzip "Takes the path to a zipfile `source` and unzips it to target-dir." [source target-dir] (with-open [zip (ZipFile. (io/file source))] (doseq [entry (enumeration-seq (.entries zip))] (let [entryname (.getName entry) filename (.getName (io/file entryname)) dest (io/file target-dir filename)] (when (str/ends-with? filename ".sdoc") (io/copy (.getInputStream zip entry) dest)))))) (defn- ref-doc-zip "Get the ref-doc.zip from either S3 archive or DYNAMO_HOME." [archive sha] (if sha (http-cache/download (format "https://%s/archive/%s/engine/share/ref-doc.zip" archive sha)) (io/file (format "%s/share/ref-doc.zip" (get (System/getenv) "DYNAMO_HOME"))))) (defn ref-doc [project & [git-sha]] (let [out-path "resources/doc"] (delete-dir out-path) (.mkdirs (io/file out-path)) (let [sha (or git-sha (:engine project)) archive-domain (get project :archive-domain)] (unzip (ref-doc-zip archive-domain sha) out-path))))
52058
;; 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 leiningen.ref-doc "Copy/download ref-doc and unzip." (:require [clojure.java.io :as io] [clojure.string :as str] [leiningen.util.http-cache :as http-cache]) (:import (java.util.zip ZipFile))) (defn- delete-dir "Delete a directory and its contents." [path] (let [dir (io/file path)] (when (.exists dir) (doseq [file (reverse (file-seq dir))] (io/delete-file file))))) (defn- unzip "Takes the path to a zipfile `source` and unzips it to target-dir." [source target-dir] (with-open [zip (ZipFile. (io/file source))] (doseq [entry (enumeration-seq (.entries zip))] (let [entryname (.getName entry) filename (.getName (io/file entryname)) dest (io/file target-dir filename)] (when (str/ends-with? filename ".sdoc") (io/copy (.getInputStream zip entry) dest)))))) (defn- ref-doc-zip "Get the ref-doc.zip from either S3 archive or DYNAMO_HOME." [archive sha] (if sha (http-cache/download (format "https://%s/archive/%s/engine/share/ref-doc.zip" archive sha)) (io/file (format "%s/share/ref-doc.zip" (get (System/getenv) "DYNAMO_HOME"))))) (defn ref-doc [project & [git-sha]] (let [out-path "resources/doc"] (delete-dir out-path) (.mkdirs (io/file out-path)) (let [sha (or git-sha (:engine project)) archive-domain (get project :archive-domain)] (unzip (ref-doc-zip archive-domain sha) out-path))))
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 leiningen.ref-doc "Copy/download ref-doc and unzip." (:require [clojure.java.io :as io] [clojure.string :as str] [leiningen.util.http-cache :as http-cache]) (:import (java.util.zip ZipFile))) (defn- delete-dir "Delete a directory and its contents." [path] (let [dir (io/file path)] (when (.exists dir) (doseq [file (reverse (file-seq dir))] (io/delete-file file))))) (defn- unzip "Takes the path to a zipfile `source` and unzips it to target-dir." [source target-dir] (with-open [zip (ZipFile. (io/file source))] (doseq [entry (enumeration-seq (.entries zip))] (let [entryname (.getName entry) filename (.getName (io/file entryname)) dest (io/file target-dir filename)] (when (str/ends-with? filename ".sdoc") (io/copy (.getInputStream zip entry) dest)))))) (defn- ref-doc-zip "Get the ref-doc.zip from either S3 archive or DYNAMO_HOME." [archive sha] (if sha (http-cache/download (format "https://%s/archive/%s/engine/share/ref-doc.zip" archive sha)) (io/file (format "%s/share/ref-doc.zip" (get (System/getenv) "DYNAMO_HOME"))))) (defn ref-doc [project & [git-sha]] (let [out-path "resources/doc"] (delete-dir out-path) (.mkdirs (io/file out-path)) (let [sha (or git-sha (:engine project)) archive-domain (get project :archive-domain)] (unzip (ref-doc-zip archive-domain sha) out-path))))
[ { "context": "ls\n (let [data-set \"data-set\"\n write-key \"write-key\"\n prune-nils (fn pn [m]\n ", "end": 22951, "score": 0.5896604061126709, "start": 22945, "tag": "KEY", "value": "write-" } ]
test/clj_honeycomb/core_test.clj
conormcd/clj-honeycomb
17
(ns clj-honeycomb.core-test (:require [clojure.data.json :as json] [clojure.spec.alpha :as s] [clojure.spec.gen.alpha :as gen] [clojure.spec.test.alpha :refer (check with-instrument-disabled)] [clojure.test :refer (are deftest is testing)] [stub-http.core :as stub-http] [clj-honeycomb.core :as honeycomb] [clj-honeycomb.fixtures :refer (kitchen-sink-realized make-kitchen-sink use-fixtures)] [clj-honeycomb.testing-utils :refer (no-op-client recording-client validate-events)]) (:import (clojure.lang ExceptionInfo) (stub_http.core NanoFakeServer) (io.honeycomb.libhoney Event EventPostProcessor HoneyClient Options ResponseObserver TransportOptions ValueSupplier) (io.honeycomb.libhoney.responses ClientRejected ServerAccepted ServerRejected Unknown))) (use-fixtures) (defn- event->fields "A helper to extract the fields from an event while avoiding NPEs and ensuring that we get a legit Clojure map out at the end." [^Event event] (when event (into {} (.getFields event)))) (deftest client-options-random-generations (doseq [co (gen/sample (s/gen :clj-honeycomb.core/client-options))] (is (instance? Options (#'honeycomb/client-options co))))) (deftest client-options-works (testing "It fails when it's missing both data-set and write-key" (try (#'honeycomb/client-options {}) (catch ExceptionInfo e (is (:clojure.spec.alpha/problems (ex-data e)))))) (testing "It fails when it's missing data-set" (try (#'honeycomb/client-options {:write-key "foo"}) (catch ExceptionInfo e (is (:clojure.spec.alpha/problems (ex-data e)))))) (testing "It fails when it's missing write-key" (try (#'honeycomb/client-options {:data-set "foo"}) (catch ExceptionInfo e (is (:clojure.spec.alpha/problems (ex-data e)))))) (testing "Minimum viable arguments" (let [^Options options (#'honeycomb/client-options {:data-set "data-set" :write-key "write-key"})] (is (= "https://api.honeycomb.io/" (str (.getApiHost options)))) (is (= "data-set" (.getDataset options))) (is (nil? (.getEventPostProcessor options))) (is (= {} (.getGlobalFields options))) (is (= {} (.getGlobalDynamicFields options))) (is (= 1 (.getSampleRate options))) (is (= "write-key" (.getWriteKey options))))) (testing "Can set API host" (let [^Options options (#'honeycomb/client-options {:api-host "https://localhost:12345/" :data-set "data-set" :write-key "write-key"})] (is (= "https://localhost:12345/" (str (.getApiHost options)))) (is (= "data-set" (.getDataset options))) (is (nil? (.getEventPostProcessor options))) (is (= {} (.getGlobalFields options))) (is (= {} (.getGlobalDynamicFields options))) (is (= 1 (.getSampleRate options))) (is (= "write-key" (.getWriteKey options))))) (testing "Can set Event Post Processor" (let [epp (reify EventPostProcessor (process [_this _event-data] nil)) ^Options options (#'honeycomb/client-options {:data-set "data-set" :event-post-processor epp :write-key "write-key"})] (is (= "https://api.honeycomb.io/" (str (.getApiHost options)))) (is (= "data-set" (.getDataset options))) (is (= epp (.getEventPostProcessor options))) (is (= {} (.getGlobalFields options))) (is (= {} (.getGlobalDynamicFields options))) (is (= 1 (.getSampleRate options))) (is (= "write-key" (.getWriteKey options))))) (testing "Can set global fields" (let [^Options options (#'honeycomb/client-options {:data-set "data-set" :global-fields {:foo 1} :write-key "write-key"})] (is (= "https://api.honeycomb.io/" (str (.getApiHost options)))) (is (= "data-set" (.getDataset options))) (is (nil? (.getEventPostProcessor options))) (is (= {"foo" 1} (.getGlobalFields options))) (is (= {} (.getGlobalDynamicFields options))) (is (= 1 (.getSampleRate options))) (is (= "write-key" (.getWriteKey options))))) (testing "Can set global dynamic fields" (let [^Options options (#'honeycomb/client-options {:data-set "data-set" :global-fields {:foo (delay 42)} :write-key "write-key"})] (is (= "https://api.honeycomb.io/" (str (.getApiHost options)))) (is (= "data-set" (.getDataset options))) (is (nil? (.getEventPostProcessor options))) (is (= {} (.getGlobalFields options))) (let [dynamic-fields (.getGlobalDynamicFields options)] (is (= 1 (count dynamic-fields))) (is (get dynamic-fields "foo")) (is (instance? ValueSupplier (get dynamic-fields "foo"))) (is (= 42 (.supply ^ValueSupplier (get dynamic-fields "foo"))))) (is (= 1 (.getSampleRate options))) (is (= "write-key" (.getWriteKey options))))) (testing "Can set sample rate" (let [^Options options (#'honeycomb/client-options {:data-set "data-set" :sample-rate 42 :write-key "write-key"})] (is (= "https://api.honeycomb.io/" (str (.getApiHost options)))) (is (= "data-set" (.getDataset options))) (is (nil? (.getEventPostProcessor options))) (is (= {} (.getGlobalFields options))) (is (= {} (.getGlobalDynamicFields options))) (is (= 42 (.getSampleRate options))) (is (= "write-key" (.getWriteKey options)))))) (deftest transport-options-random-generations (doseq [to (gen/sample (s/gen :clj-honeycomb.core/transport-options))] (is (instance? TransportOptions (#'honeycomb/transport-options to))))) (deftest transport-options-works ; By hardcoding these transport options here, this test will also detect ; changes in the underlying libhoney-java library. (let [default-transport-options {:additionalUserAgent "" :batchSize 50 :batchTimeoutMillis 100 :bufferSize 8192 :connectTimeout 0 :connectionRequestTimeout 0 :ioThreadCount 4 :maxConnections 200 :maxHttpConnectionsPerApiHost 100 :maxPendingBatchRequests 250 :maximumHttpRequestShutdownWait 2000 :queueCapacity 10000 :socketTimeout 3000} checks-out (fn [expected input] (let [^TransportOptions to (#'honeycomb/transport-options input)] (and (instance? TransportOptions to) (integer? (.getIoThreadCount to)) (pos? (.getIoThreadCount to)) (= (-> to bean (dissoc :class :ioThreadCount)) (dissoc expected :ioThreadCount)))))] (are [input expected] (checks-out expected input) {} default-transport-options {:additional-user-agent "foo"} (assoc default-transport-options :additionalUserAgent "foo") {:batch-size 100} (assoc default-transport-options :batchSize 100) {:batch-timeout-millis 200} (assoc default-transport-options :batchTimeoutMillis 200) {:buffer-size 1024} (assoc default-transport-options :bufferSize 1024) {:connection-request-timeout 1} (assoc default-transport-options :connectionRequestTimeout 1) {:connect-timeout 1} (assoc default-transport-options :connectTimeout 1) {:io-thread-count 1} (assoc default-transport-options :ioThreadCount 1) {:max-connections 100} (assoc default-transport-options :maxConnections 100) {:max-connections-per-api-host 150} (assoc default-transport-options :maxHttpConnectionsPerApiHost 150) {:maximum-http-request-shutdown-wait 1000} (assoc default-transport-options :maximumHttpRequestShutdownWait 1000) {:maximum-pending-batch-requests 125} (assoc default-transport-options :maxPendingBatchRequests 125) {:queue-capacity 1000} (assoc default-transport-options :queueCapacity 1000) {:socket-timeout 1000} (assoc default-transport-options :socketTimeout 1000)))) (deftest response-observer-works (let [client-rejected (reify ClientRejected) server-accepted (reify ServerAccepted) server-rejected (reify ServerRejected) unknown (reify Unknown)] (testing "It still works OK if there are no actual handlers" (let [^ResponseObserver ro (#'honeycomb/response-observer {})] (.onClientRejected ro client-rejected) (.onServerAccepted ro server-accepted) (.onServerRejected ro server-rejected) (.onUnknown ro unknown))) (testing "Each function works as expected" (let [^ResponseObserver ro (#'honeycomb/response-observer {:on-client-rejected (fn [cr] (is (= cr client-rejected))) :on-server-accepted (fn [sa] (is (= sa server-accepted))) :on-server-rejected (fn [sr] (is (= sr server-rejected))) :on-unknown (fn [u] (is (= u unknown)))})] (.onClientRejected ro client-rejected) (.onServerAccepted ro server-accepted) (.onServerRejected ro server-rejected) (.onUnknown ro unknown))) (testing "Randomly generated values work" (check `honeycomb/response-observer)))) (deftest client-works (testing "Without a ResponseObserver" (with-open [client (honeycomb/client {:data-set "data-set" :write-key "write-key"})] (is (instance? HoneyClient client)))) (testing "With a ResponseObserver" (with-open [client (honeycomb/client {:data-set "data-set" :response-observer {:on-unknown (fn [_] nil)} :write-key "write-key"})] (is (instance? HoneyClient client)))) (testing "With empty transport options" (with-open [client (honeycomb/client {:data-set "data-set" :transport-options {} :write-key "write-key"})] (is (instance? HoneyClient client)))) (testing "With non-empty transport options" (with-open [client (honeycomb/client {:data-set "data-set" :transport-options {:batch-size 10} :write-key "write-key"})] (is (instance? HoneyClient client)))) (testing "We can add an event pre-processor" (with-open [client (honeycomb/client {:data-set "data-set" :event-pre-processor (fn [event-data options] [event-data options]) :write-key "write-key"})] (is (instance? HoneyClient client))))) (deftest init-and-initialized?-works (testing "Initialize with a map" (is (nil? @#'honeycomb/*client*)) (is (not (honeycomb/initialized?))) (when (nil? @#'honeycomb/*client*) (try (let [options {:data-set "data-set" :write-key "write-key"}] (with-open [client (honeycomb/client options)] (is (not (honeycomb/initialized?))) (is (= (bean client) (bean (honeycomb/init options)))) (is (= (bean client) (bean @#'honeycomb/*client*))) (is (honeycomb/initialized?)))) (finally (alter-var-root #'honeycomb/*client* (constantly nil))))) (is (not (honeycomb/initialized?))) (is (nil? @#'honeycomb/*client*))) (testing "Initialize with a client" (is (nil? @#'honeycomb/*client*)) (is (not (honeycomb/initialized?))) (when (nil? @#'honeycomb/*client*) (try (let [options {:data-set "data-set" :write-key "write-key"}] (with-open [client (honeycomb/client options)] (is (not (honeycomb/initialized?))) (is (= client (honeycomb/init client))) (is (= client @#'honeycomb/*client*)) (is (honeycomb/initialized?)))) (finally (alter-var-root #'honeycomb/*client* (constantly nil))))) (is (not (honeycomb/initialized?))) (is (nil? @#'honeycomb/*client*))) (testing "The argument must be a client or a map" (with-instrument-disabled (is (thrown? IllegalArgumentException (honeycomb/init nil)))))) (deftest create-event-works (with-open [honeycomb-client (honeycomb/client {:data-set "data-set" :write-key "write-key"})] (testing "Empty event" (let [^Event event (#'honeycomb/create-event honeycomb-client {} {})] (is (= "https://api.honeycomb.io/" (str (.getApiHost event)))) (is (= "data-set" (.getDataset event))) (is (= {} (event->fields event))) (is (= {} (.getMetadata event))) (is (= 1 (.getSampleRate event))) (is (nil? (.getTimestamp event))) (is (= "write-key" (.getWriteKey event))))) (testing "Fields get realized properly and infinite/lazy things don't block." (let [^Event event (#'honeycomb/create-event honeycomb-client {:nil nil :string "string" :integer 42 :float Math/E :fraction 22/7 :atom (atom 3) :delay (delay 4)} {})] (is (= "https://api.honeycomb.io/" (str (.getApiHost event)))) (is (= "data-set" (.getDataset event))) (is (= {"nil" nil "string" "string" "integer" 42 "float" Math/E "fraction" (float 22/7) "atom" 3 "delay" 4} (event->fields event))) (is (= {} (.getMetadata event))) (is (= 1 (.getSampleRate event))) (is (nil? (.getTimestamp event))) (is (= "write-key" (.getWriteKey event))))) (testing "Options get set on the event" (let [^Event event (#'honeycomb/create-event honeycomb-client {} {:api-host "https://localhost:123/" :data-set "foo" :metadata {:event-id 42} :sample-rate 3 :timestamp 123456 :write-key "bar"})] (is (= "https://localhost:123/" (str (.getApiHost event)))) (is (= "foo" (.getDataset event))) (is (= {} (event->fields event))) (is (= {:event-id 42} (.getMetadata event))) (is (= 3 (.getSampleRate event))) (is (= 123456 (.getTimestamp event))) (is (= "bar" (.getWriteKey event))))) (testing "Event pre-processor runs" (with-open [client (honeycomb/client {:data-set "data-set" :event-pre-processor (fn [event-data options] [(assoc event-data :integer 1) options]) :write-key "write-key"})] (let [^Event event (#'honeycomb/create-event client {:nil nil :string "string" :integer 42 :float Math/E :fraction 22/7 :atom (atom 3) :delay (delay 4)} {})] (is (= "https://api.honeycomb.io/" (str (.getApiHost event)))) (is (= "data-set" (.getDataset event))) (is (= {"nil" nil "string" "string" "integer" 1 "float" Math/E "fraction" (float 22/7) "atom" 3 "delay" 4} (event->fields event))) (is (= {} (.getMetadata event))) (is (= 1 (.getSampleRate event))) (is (nil? (.getTimestamp event))) (is (= "write-key" (.getWriteKey event)))))))) (deftest send-works (testing "One argument" (testing "requires a client from init first" (binding [honeycomb/*client* nil] (is (thrown? IllegalStateException (honeycomb/send {:foo "bar"}))))) (testing "works when there's a global client set" (validate-events (fn [] (honeycomb/send {:foo "bar"})) (fn [events errors] (is (empty? errors)) (is (= 1 (count events))) (is (= {"foo" "bar"} (event->fields (first events)))))))) (testing "Two arguments works" (let [events (atom [])] (with-open [client (recording-client events {:data-set "data-set" :write-key "write-key"})] (honeycomb/send client {:foo "bar"})) (is (= 1 (count @events))) (is (= {"foo" "bar"} (event->fields (first @events)))))) (testing "Three arguments works" (let [events (atom [])] (with-open [client (recording-client events {:data-set "data-set" :write-key "write-key"})] (honeycomb/send client {:foo "bar"} {:pre-sampled true})) (is (= 1 (count @events))) (is (= {"foo" "bar"} (event->fields (first @events)))))) (testing "Global fields get sent" (let [dynamic-field (atom 1) events (atom [])] (with-open [client (recording-client events {:data-set "data-set" :global-fields {:dynamic dynamic-field :static "static"} :write-key "write-key"})] (honeycomb/send client {:foo "bar"}) (swap! dynamic-field inc) (honeycomb/send client {:foo "bar"})) (is (= [{"dynamic" 1 "foo" "bar" "static" "static"} {"dynamic" 2 "foo" "bar" "static" "static"}] (map event->fields @events))))) (testing "Randomly generated send options" (doseq [send-options (gen/sample (s/gen :clj-honeycomb.core/send-options))] (validate-events (fn [] (honeycomb/send {:foo "bar"} send-options)) (fn [events errors] (if (empty? errors) (do (is (= 1 (count events))) (is (= {"foo" "bar"} (event->fields (first events))))) (do (is (= 1 (count errors))) (is (instance? ClientRejected (first errors))) (is (= "NOT_SAMPLED" (str (.getReason ^ClientRejected (first errors))))))))))) (testing "Random everything" (doseq [client-options (gen/sample (s/gen :clj-honeycomb.core/client-options))] (doseq [send-options (gen/sample (s/gen :clj-honeycomb.core/send-options))] (let [events (atom [])] (with-open [client (recording-client events client-options)] (honeycomb/send client {:foo "bar"} send-options)) (cond (= 0 (count @events)) (is (or (< 1 (or (:sample-rate client-options) 1)) (< 1 (or (:sample-rate send-options) 1)))) (= 1 (count @events)) (is (contains? (event->fields (first @events)) "foo")) :else (is (empty? @events)))))))) (defn- capture-honeycomb-http-calls [data-set expected-calls timeout-ms f] (with-open [^NanoFakeServer http-server (stub-http/start! {(str "/1/batch/" data-set) {:status 200 :body ""}})] (f (:uri http-server)) (let [deadline (+ (System/nanoTime) (* timeout-ms 1e6))] (loop [] (let [recordings (->> http-server :routes deref (mapcat :recordings) (map #(update-in % [:request :body "postData"] json/read-str)))] (cond (= expected-calls (count recordings)) recordings (< expected-calls (count recordings)) (do (is (= expected-calls (count recordings))) recordings) (> expected-calls (count recordings)) (if (< deadline (System/nanoTime)) (throw (ex-info "Deadline exceeded when waiting for replies" {})) (do (Thread/sleep 100) (recur))))))))) (deftest send-makes-the-expected-http-calls (let [data-set "data-set" write-key "write-key" prune-nils (fn pn [m] (if (map? m) (->> m (remove (comp nil? val)) (map (fn [[k v]] [k (pn v)])) (into {})) m))] (-> (capture-honeycomb-http-calls data-set 1 10000 (fn [uri] (with-open [client (honeycomb/client {:api-host uri :data-set data-set :write-key write-key})] (honeycomb/send client (make-kitchen-sink))))) ((fn [requests] (let [request (:request (first requests))] (is (= "POST" (:method request))) (is (= (str "/1/batch/" data-set) (:path request))) (is (= write-key (-> request :headers :x-honeycomb-team))) (is (= 1 (count (get-in request [:body "postData"])))) (let [body (first (get-in request [:body "postData"]))] (is (= 1 (get body "samplerate"))) (let [data (atom (get body "data")) expected (atom (prune-nils kitchen-sink-realized))] ; Make sure they have the same keys (is (= (sort (keys @expected)) (sort (keys @data)))) ; Check each key in turn so that the errors are more readable (doseq [[k v] @expected] (if (instance? Throwable v) (do (is (= "An exception" (get-in @data [(name k) "message"]))) (is (get-in @data [(name k) "stackTrace"]))) (is (= v (get @data (name k)))))))))))))) (deftest send-pre-sampled-makes-the-expected-http-calls (let [data-set "data-set" write-key "write-key"] (-> (capture-honeycomb-http-calls data-set 1 10000 (fn [uri] (with-open [client (honeycomb/client {:api-host uri :data-set data-set :write-key write-key})] (honeycomb/send client {:foo "bar"} {:pre-sampled true})))) ((fn [requests] (let [request (:request (first requests))] (is (= "POST" (:method request))) (is (= (str "/1/batch/" data-set) (:path request))) (is (= write-key (-> request :headers :x-honeycomb-team))) (is (= 1 (count (get-in request [:body "postData"])))) (let [body (first (get-in request [:body "postData"]))] (is (= 1 (get body "samplerate"))) (is (= {"foo" "bar"} (get body "data")))))))))) (deftest generate-trace-id-works (check `honeycomb/generate-trace-id)) (deftest generate-span-id-works (check `honeycomb/generate-span-id)) (deftest with-event-works (testing "Code that doesn't throw still returns AND sends the event" (validate-events (fn [] (is (= :foo (honeycomb/with-event {:foo "foo"} {} (honeycomb/add-to-event {:bar "bar"}) (Thread/sleep 100) (honeycomb/add-to-event :baz "baz") :foo)))) (fn [events errors] (is (empty? errors)) (is (= 1 (count events))) (let [event-data (some->> events first event->fields)] (is (= {"foo" "foo" "bar" "bar" "baz" "baz"} (dissoc event-data "durationMs"))) (is (< 100 (get event-data "durationMs" -1))))))) (testing "Code that throws both throws AND sends the event" (validate-events (fn [] (is (thrown? Exception (honeycomb/with-event {:foo "foo"} {} (honeycomb/add-to-event {:bar "bar"}) (honeycomb/add-to-event :baz "baz") (throw (Exception. "An exception")))))) (fn [events errors] (is (empty? errors)) (is (= 1 (count events))) (let [event-data (some->> events first event->fields)] (is (= {"foo" "foo" "bar" "bar" "baz" "baz"} (dissoc event-data "exception" "durationMs"))) (is (some-> (get event-data "durationMs") pos?)) (is (instance? Exception (get event-data "exception"))))))) (testing "with-event can generate trace spans" (let [trace-id (honeycomb/generate-trace-id)] (testing "The bare minimum" (validate-events (fn [] (is (= :body-value (honeycomb/with-event {:foo "bar" :traceId trace-id} {} :body-value)))) (fn [events errors] (is (= 1 (count events))) (when-let [event (->> events (map event->fields) first)] (is (some? (get event "id"))) (is (float? (get event "durationMs"))) (is (= {"traceId" trace-id "parentId" nil "foo" "bar"} (dissoc event "durationMs" "id")))) (is (empty? errors))))) (testing "Specifying an ID" (validate-events (fn [] (is (= :body-value (honeycomb/with-event {:foo "bar" :id "some-id" :traceId trace-id} {} :body-value)))) (fn [events errors] (is (= 1 (count events))) (when-let [event (->> events (map event->fields) first)] (is (float? (get event "durationMs"))) (is (= {"traceId" trace-id "parentId" nil "foo" "bar" "id" "some-id"} (dissoc event "durationMs")))) (is (empty? errors))))) (testing "Nested events create parent-child spans" (validate-events (fn [] (is (= :body-value (honeycomb/with-event {:foo "bar" :traceId trace-id} {} (honeycomb/with-event {:baz "quux"} {} :body-value))))) (fn [events errors] (let [events (map event->fields events)] (is (= 2 (count events))) (is (every? some? (map #(get % "id") events))) (is (every? float? (map #(get % "durationMs") events))) (is (= [{"traceId" trace-id "baz" "quux"} {"traceId" trace-id "foo" "bar"}] (map #(dissoc % "id" "parentId" "durationMs") events))) (is (nil? (get (last events) "parentId"))) (is (some? (get (first events) "parentId"))) (is (= (get (first events) "parentId") (get (last events) "id")))) (is (empty? errors))))) (testing "Nested events create parent-child spans with with-trace-id" (validate-events (fn [] (is (= :body-value (honeycomb/with-trace-id trace-id (honeycomb/with-event {:foo "bar"} {} (honeycomb/with-event {:baz "quux"} {} :body-value)))))) (fn [events errors] (let [events (map event->fields events)] (is (= 2 (count events))) (is (every? some? (map #(get % "id") events))) (is (every? float? (map #(get % "durationMs") events))) (is (= [{"traceId" trace-id "baz" "quux"} {"traceId" trace-id "foo" "bar"}] (map #(dissoc % "id" "parentId" "durationMs") events))) (is (nil? (get (last events) "parentId"))) (is (some? (get (first events) "parentId"))) (is (= (get (first events) "parentId") (get (last events) "id")))) (is (empty? errors))))) (testing "It's possible to create non-enclosing parent-child relationships" (let [x-id (honeycomb/generate-span-id)] (validate-events (fn [] (honeycomb/with-trace-id trace-id (honeycomb/with-event {:doing "X" :id x-id} {} (Thread/sleep 50)) (honeycomb/with-event {:doing "Y" :parentId x-id} {} (Thread/sleep 50)))) (fn [events errors] (let [events (map event->fields events)] (is (every? some? (map #(get % "id") events))) (is (= [{"traceId" trace-id "doing" "X" "parentId" nil} {"traceId" trace-id "doing" "Y" "parentId" (get (first events) "id")}] (map #(dissoc % "durationMs" "id") events)))) (is (empty? errors))))))))) (deftest live-test-against-honeycomb ; This has no assertions. It's here purely so that we can generate some known ; events and inspect them in the Honeycomb.io UI to detect unexpected ; serialisation issues. (let [data-set (System/getenv "HONEYCOMB_DATA_SET") write-key (System/getenv "HONEYCOMB_WRITE_KEY") kitchen-sink (make-kitchen-sink)] (when (and data-set write-key) (testing "The primitives work" (with-open [client (honeycomb/client {:data-set data-set :write-key write-key})] (honeycomb/send client kitchen-sink))) (testing "Using init and with-event works" (let [original-client @#'honeycomb/*client*] (try (honeycomb/init {:data-set data-set :write-key write-key}) (honeycomb/with-event {:foo "foo"} {} (honeycomb/add-to-event {:bar "bar"}) (honeycomb/add-to-event :baz "baz")) (finally (alter-var-root #'honeycomb/*client* (constantly original-client))))))))) (deftest nonsense-tests-just-to-cover-spec ; We need to call explain-data on these to ensure that the macroexpanded form ; generated by s/keys is covered properly. (s/explain-data :clj-honeycomb.core/create-event-options {:foo {:bar :baz}}) (s/explain-data :clj-honeycomb.core/response-observer {:foo {:bar :baz}}) (s/explain-data :clj-honeycomb.core/send-options {:foo {:bar :baz}}) (s/explain-data :clj-honeycomb.core/transport-options {:foo {:bar :baz}}))
55668
(ns clj-honeycomb.core-test (:require [clojure.data.json :as json] [clojure.spec.alpha :as s] [clojure.spec.gen.alpha :as gen] [clojure.spec.test.alpha :refer (check with-instrument-disabled)] [clojure.test :refer (are deftest is testing)] [stub-http.core :as stub-http] [clj-honeycomb.core :as honeycomb] [clj-honeycomb.fixtures :refer (kitchen-sink-realized make-kitchen-sink use-fixtures)] [clj-honeycomb.testing-utils :refer (no-op-client recording-client validate-events)]) (:import (clojure.lang ExceptionInfo) (stub_http.core NanoFakeServer) (io.honeycomb.libhoney Event EventPostProcessor HoneyClient Options ResponseObserver TransportOptions ValueSupplier) (io.honeycomb.libhoney.responses ClientRejected ServerAccepted ServerRejected Unknown))) (use-fixtures) (defn- event->fields "A helper to extract the fields from an event while avoiding NPEs and ensuring that we get a legit Clojure map out at the end." [^Event event] (when event (into {} (.getFields event)))) (deftest client-options-random-generations (doseq [co (gen/sample (s/gen :clj-honeycomb.core/client-options))] (is (instance? Options (#'honeycomb/client-options co))))) (deftest client-options-works (testing "It fails when it's missing both data-set and write-key" (try (#'honeycomb/client-options {}) (catch ExceptionInfo e (is (:clojure.spec.alpha/problems (ex-data e)))))) (testing "It fails when it's missing data-set" (try (#'honeycomb/client-options {:write-key "foo"}) (catch ExceptionInfo e (is (:clojure.spec.alpha/problems (ex-data e)))))) (testing "It fails when it's missing write-key" (try (#'honeycomb/client-options {:data-set "foo"}) (catch ExceptionInfo e (is (:clojure.spec.alpha/problems (ex-data e)))))) (testing "Minimum viable arguments" (let [^Options options (#'honeycomb/client-options {:data-set "data-set" :write-key "write-key"})] (is (= "https://api.honeycomb.io/" (str (.getApiHost options)))) (is (= "data-set" (.getDataset options))) (is (nil? (.getEventPostProcessor options))) (is (= {} (.getGlobalFields options))) (is (= {} (.getGlobalDynamicFields options))) (is (= 1 (.getSampleRate options))) (is (= "write-key" (.getWriteKey options))))) (testing "Can set API host" (let [^Options options (#'honeycomb/client-options {:api-host "https://localhost:12345/" :data-set "data-set" :write-key "write-key"})] (is (= "https://localhost:12345/" (str (.getApiHost options)))) (is (= "data-set" (.getDataset options))) (is (nil? (.getEventPostProcessor options))) (is (= {} (.getGlobalFields options))) (is (= {} (.getGlobalDynamicFields options))) (is (= 1 (.getSampleRate options))) (is (= "write-key" (.getWriteKey options))))) (testing "Can set Event Post Processor" (let [epp (reify EventPostProcessor (process [_this _event-data] nil)) ^Options options (#'honeycomb/client-options {:data-set "data-set" :event-post-processor epp :write-key "write-key"})] (is (= "https://api.honeycomb.io/" (str (.getApiHost options)))) (is (= "data-set" (.getDataset options))) (is (= epp (.getEventPostProcessor options))) (is (= {} (.getGlobalFields options))) (is (= {} (.getGlobalDynamicFields options))) (is (= 1 (.getSampleRate options))) (is (= "write-key" (.getWriteKey options))))) (testing "Can set global fields" (let [^Options options (#'honeycomb/client-options {:data-set "data-set" :global-fields {:foo 1} :write-key "write-key"})] (is (= "https://api.honeycomb.io/" (str (.getApiHost options)))) (is (= "data-set" (.getDataset options))) (is (nil? (.getEventPostProcessor options))) (is (= {"foo" 1} (.getGlobalFields options))) (is (= {} (.getGlobalDynamicFields options))) (is (= 1 (.getSampleRate options))) (is (= "write-key" (.getWriteKey options))))) (testing "Can set global dynamic fields" (let [^Options options (#'honeycomb/client-options {:data-set "data-set" :global-fields {:foo (delay 42)} :write-key "write-key"})] (is (= "https://api.honeycomb.io/" (str (.getApiHost options)))) (is (= "data-set" (.getDataset options))) (is (nil? (.getEventPostProcessor options))) (is (= {} (.getGlobalFields options))) (let [dynamic-fields (.getGlobalDynamicFields options)] (is (= 1 (count dynamic-fields))) (is (get dynamic-fields "foo")) (is (instance? ValueSupplier (get dynamic-fields "foo"))) (is (= 42 (.supply ^ValueSupplier (get dynamic-fields "foo"))))) (is (= 1 (.getSampleRate options))) (is (= "write-key" (.getWriteKey options))))) (testing "Can set sample rate" (let [^Options options (#'honeycomb/client-options {:data-set "data-set" :sample-rate 42 :write-key "write-key"})] (is (= "https://api.honeycomb.io/" (str (.getApiHost options)))) (is (= "data-set" (.getDataset options))) (is (nil? (.getEventPostProcessor options))) (is (= {} (.getGlobalFields options))) (is (= {} (.getGlobalDynamicFields options))) (is (= 42 (.getSampleRate options))) (is (= "write-key" (.getWriteKey options)))))) (deftest transport-options-random-generations (doseq [to (gen/sample (s/gen :clj-honeycomb.core/transport-options))] (is (instance? TransportOptions (#'honeycomb/transport-options to))))) (deftest transport-options-works ; By hardcoding these transport options here, this test will also detect ; changes in the underlying libhoney-java library. (let [default-transport-options {:additionalUserAgent "" :batchSize 50 :batchTimeoutMillis 100 :bufferSize 8192 :connectTimeout 0 :connectionRequestTimeout 0 :ioThreadCount 4 :maxConnections 200 :maxHttpConnectionsPerApiHost 100 :maxPendingBatchRequests 250 :maximumHttpRequestShutdownWait 2000 :queueCapacity 10000 :socketTimeout 3000} checks-out (fn [expected input] (let [^TransportOptions to (#'honeycomb/transport-options input)] (and (instance? TransportOptions to) (integer? (.getIoThreadCount to)) (pos? (.getIoThreadCount to)) (= (-> to bean (dissoc :class :ioThreadCount)) (dissoc expected :ioThreadCount)))))] (are [input expected] (checks-out expected input) {} default-transport-options {:additional-user-agent "foo"} (assoc default-transport-options :additionalUserAgent "foo") {:batch-size 100} (assoc default-transport-options :batchSize 100) {:batch-timeout-millis 200} (assoc default-transport-options :batchTimeoutMillis 200) {:buffer-size 1024} (assoc default-transport-options :bufferSize 1024) {:connection-request-timeout 1} (assoc default-transport-options :connectionRequestTimeout 1) {:connect-timeout 1} (assoc default-transport-options :connectTimeout 1) {:io-thread-count 1} (assoc default-transport-options :ioThreadCount 1) {:max-connections 100} (assoc default-transport-options :maxConnections 100) {:max-connections-per-api-host 150} (assoc default-transport-options :maxHttpConnectionsPerApiHost 150) {:maximum-http-request-shutdown-wait 1000} (assoc default-transport-options :maximumHttpRequestShutdownWait 1000) {:maximum-pending-batch-requests 125} (assoc default-transport-options :maxPendingBatchRequests 125) {:queue-capacity 1000} (assoc default-transport-options :queueCapacity 1000) {:socket-timeout 1000} (assoc default-transport-options :socketTimeout 1000)))) (deftest response-observer-works (let [client-rejected (reify ClientRejected) server-accepted (reify ServerAccepted) server-rejected (reify ServerRejected) unknown (reify Unknown)] (testing "It still works OK if there are no actual handlers" (let [^ResponseObserver ro (#'honeycomb/response-observer {})] (.onClientRejected ro client-rejected) (.onServerAccepted ro server-accepted) (.onServerRejected ro server-rejected) (.onUnknown ro unknown))) (testing "Each function works as expected" (let [^ResponseObserver ro (#'honeycomb/response-observer {:on-client-rejected (fn [cr] (is (= cr client-rejected))) :on-server-accepted (fn [sa] (is (= sa server-accepted))) :on-server-rejected (fn [sr] (is (= sr server-rejected))) :on-unknown (fn [u] (is (= u unknown)))})] (.onClientRejected ro client-rejected) (.onServerAccepted ro server-accepted) (.onServerRejected ro server-rejected) (.onUnknown ro unknown))) (testing "Randomly generated values work" (check `honeycomb/response-observer)))) (deftest client-works (testing "Without a ResponseObserver" (with-open [client (honeycomb/client {:data-set "data-set" :write-key "write-key"})] (is (instance? HoneyClient client)))) (testing "With a ResponseObserver" (with-open [client (honeycomb/client {:data-set "data-set" :response-observer {:on-unknown (fn [_] nil)} :write-key "write-key"})] (is (instance? HoneyClient client)))) (testing "With empty transport options" (with-open [client (honeycomb/client {:data-set "data-set" :transport-options {} :write-key "write-key"})] (is (instance? HoneyClient client)))) (testing "With non-empty transport options" (with-open [client (honeycomb/client {:data-set "data-set" :transport-options {:batch-size 10} :write-key "write-key"})] (is (instance? HoneyClient client)))) (testing "We can add an event pre-processor" (with-open [client (honeycomb/client {:data-set "data-set" :event-pre-processor (fn [event-data options] [event-data options]) :write-key "write-key"})] (is (instance? HoneyClient client))))) (deftest init-and-initialized?-works (testing "Initialize with a map" (is (nil? @#'honeycomb/*client*)) (is (not (honeycomb/initialized?))) (when (nil? @#'honeycomb/*client*) (try (let [options {:data-set "data-set" :write-key "write-key"}] (with-open [client (honeycomb/client options)] (is (not (honeycomb/initialized?))) (is (= (bean client) (bean (honeycomb/init options)))) (is (= (bean client) (bean @#'honeycomb/*client*))) (is (honeycomb/initialized?)))) (finally (alter-var-root #'honeycomb/*client* (constantly nil))))) (is (not (honeycomb/initialized?))) (is (nil? @#'honeycomb/*client*))) (testing "Initialize with a client" (is (nil? @#'honeycomb/*client*)) (is (not (honeycomb/initialized?))) (when (nil? @#'honeycomb/*client*) (try (let [options {:data-set "data-set" :write-key "write-key"}] (with-open [client (honeycomb/client options)] (is (not (honeycomb/initialized?))) (is (= client (honeycomb/init client))) (is (= client @#'honeycomb/*client*)) (is (honeycomb/initialized?)))) (finally (alter-var-root #'honeycomb/*client* (constantly nil))))) (is (not (honeycomb/initialized?))) (is (nil? @#'honeycomb/*client*))) (testing "The argument must be a client or a map" (with-instrument-disabled (is (thrown? IllegalArgumentException (honeycomb/init nil)))))) (deftest create-event-works (with-open [honeycomb-client (honeycomb/client {:data-set "data-set" :write-key "write-key"})] (testing "Empty event" (let [^Event event (#'honeycomb/create-event honeycomb-client {} {})] (is (= "https://api.honeycomb.io/" (str (.getApiHost event)))) (is (= "data-set" (.getDataset event))) (is (= {} (event->fields event))) (is (= {} (.getMetadata event))) (is (= 1 (.getSampleRate event))) (is (nil? (.getTimestamp event))) (is (= "write-key" (.getWriteKey event))))) (testing "Fields get realized properly and infinite/lazy things don't block." (let [^Event event (#'honeycomb/create-event honeycomb-client {:nil nil :string "string" :integer 42 :float Math/E :fraction 22/7 :atom (atom 3) :delay (delay 4)} {})] (is (= "https://api.honeycomb.io/" (str (.getApiHost event)))) (is (= "data-set" (.getDataset event))) (is (= {"nil" nil "string" "string" "integer" 42 "float" Math/E "fraction" (float 22/7) "atom" 3 "delay" 4} (event->fields event))) (is (= {} (.getMetadata event))) (is (= 1 (.getSampleRate event))) (is (nil? (.getTimestamp event))) (is (= "write-key" (.getWriteKey event))))) (testing "Options get set on the event" (let [^Event event (#'honeycomb/create-event honeycomb-client {} {:api-host "https://localhost:123/" :data-set "foo" :metadata {:event-id 42} :sample-rate 3 :timestamp 123456 :write-key "bar"})] (is (= "https://localhost:123/" (str (.getApiHost event)))) (is (= "foo" (.getDataset event))) (is (= {} (event->fields event))) (is (= {:event-id 42} (.getMetadata event))) (is (= 3 (.getSampleRate event))) (is (= 123456 (.getTimestamp event))) (is (= "bar" (.getWriteKey event))))) (testing "Event pre-processor runs" (with-open [client (honeycomb/client {:data-set "data-set" :event-pre-processor (fn [event-data options] [(assoc event-data :integer 1) options]) :write-key "write-key"})] (let [^Event event (#'honeycomb/create-event client {:nil nil :string "string" :integer 42 :float Math/E :fraction 22/7 :atom (atom 3) :delay (delay 4)} {})] (is (= "https://api.honeycomb.io/" (str (.getApiHost event)))) (is (= "data-set" (.getDataset event))) (is (= {"nil" nil "string" "string" "integer" 1 "float" Math/E "fraction" (float 22/7) "atom" 3 "delay" 4} (event->fields event))) (is (= {} (.getMetadata event))) (is (= 1 (.getSampleRate event))) (is (nil? (.getTimestamp event))) (is (= "write-key" (.getWriteKey event)))))))) (deftest send-works (testing "One argument" (testing "requires a client from init first" (binding [honeycomb/*client* nil] (is (thrown? IllegalStateException (honeycomb/send {:foo "bar"}))))) (testing "works when there's a global client set" (validate-events (fn [] (honeycomb/send {:foo "bar"})) (fn [events errors] (is (empty? errors)) (is (= 1 (count events))) (is (= {"foo" "bar"} (event->fields (first events)))))))) (testing "Two arguments works" (let [events (atom [])] (with-open [client (recording-client events {:data-set "data-set" :write-key "write-key"})] (honeycomb/send client {:foo "bar"})) (is (= 1 (count @events))) (is (= {"foo" "bar"} (event->fields (first @events)))))) (testing "Three arguments works" (let [events (atom [])] (with-open [client (recording-client events {:data-set "data-set" :write-key "write-key"})] (honeycomb/send client {:foo "bar"} {:pre-sampled true})) (is (= 1 (count @events))) (is (= {"foo" "bar"} (event->fields (first @events)))))) (testing "Global fields get sent" (let [dynamic-field (atom 1) events (atom [])] (with-open [client (recording-client events {:data-set "data-set" :global-fields {:dynamic dynamic-field :static "static"} :write-key "write-key"})] (honeycomb/send client {:foo "bar"}) (swap! dynamic-field inc) (honeycomb/send client {:foo "bar"})) (is (= [{"dynamic" 1 "foo" "bar" "static" "static"} {"dynamic" 2 "foo" "bar" "static" "static"}] (map event->fields @events))))) (testing "Randomly generated send options" (doseq [send-options (gen/sample (s/gen :clj-honeycomb.core/send-options))] (validate-events (fn [] (honeycomb/send {:foo "bar"} send-options)) (fn [events errors] (if (empty? errors) (do (is (= 1 (count events))) (is (= {"foo" "bar"} (event->fields (first events))))) (do (is (= 1 (count errors))) (is (instance? ClientRejected (first errors))) (is (= "NOT_SAMPLED" (str (.getReason ^ClientRejected (first errors))))))))))) (testing "Random everything" (doseq [client-options (gen/sample (s/gen :clj-honeycomb.core/client-options))] (doseq [send-options (gen/sample (s/gen :clj-honeycomb.core/send-options))] (let [events (atom [])] (with-open [client (recording-client events client-options)] (honeycomb/send client {:foo "bar"} send-options)) (cond (= 0 (count @events)) (is (or (< 1 (or (:sample-rate client-options) 1)) (< 1 (or (:sample-rate send-options) 1)))) (= 1 (count @events)) (is (contains? (event->fields (first @events)) "foo")) :else (is (empty? @events)))))))) (defn- capture-honeycomb-http-calls [data-set expected-calls timeout-ms f] (with-open [^NanoFakeServer http-server (stub-http/start! {(str "/1/batch/" data-set) {:status 200 :body ""}})] (f (:uri http-server)) (let [deadline (+ (System/nanoTime) (* timeout-ms 1e6))] (loop [] (let [recordings (->> http-server :routes deref (mapcat :recordings) (map #(update-in % [:request :body "postData"] json/read-str)))] (cond (= expected-calls (count recordings)) recordings (< expected-calls (count recordings)) (do (is (= expected-calls (count recordings))) recordings) (> expected-calls (count recordings)) (if (< deadline (System/nanoTime)) (throw (ex-info "Deadline exceeded when waiting for replies" {})) (do (Thread/sleep 100) (recur))))))))) (deftest send-makes-the-expected-http-calls (let [data-set "data-set" write-key "<KEY>key" prune-nils (fn pn [m] (if (map? m) (->> m (remove (comp nil? val)) (map (fn [[k v]] [k (pn v)])) (into {})) m))] (-> (capture-honeycomb-http-calls data-set 1 10000 (fn [uri] (with-open [client (honeycomb/client {:api-host uri :data-set data-set :write-key write-key})] (honeycomb/send client (make-kitchen-sink))))) ((fn [requests] (let [request (:request (first requests))] (is (= "POST" (:method request))) (is (= (str "/1/batch/" data-set) (:path request))) (is (= write-key (-> request :headers :x-honeycomb-team))) (is (= 1 (count (get-in request [:body "postData"])))) (let [body (first (get-in request [:body "postData"]))] (is (= 1 (get body "samplerate"))) (let [data (atom (get body "data")) expected (atom (prune-nils kitchen-sink-realized))] ; Make sure they have the same keys (is (= (sort (keys @expected)) (sort (keys @data)))) ; Check each key in turn so that the errors are more readable (doseq [[k v] @expected] (if (instance? Throwable v) (do (is (= "An exception" (get-in @data [(name k) "message"]))) (is (get-in @data [(name k) "stackTrace"]))) (is (= v (get @data (name k)))))))))))))) (deftest send-pre-sampled-makes-the-expected-http-calls (let [data-set "data-set" write-key "write-key"] (-> (capture-honeycomb-http-calls data-set 1 10000 (fn [uri] (with-open [client (honeycomb/client {:api-host uri :data-set data-set :write-key write-key})] (honeycomb/send client {:foo "bar"} {:pre-sampled true})))) ((fn [requests] (let [request (:request (first requests))] (is (= "POST" (:method request))) (is (= (str "/1/batch/" data-set) (:path request))) (is (= write-key (-> request :headers :x-honeycomb-team))) (is (= 1 (count (get-in request [:body "postData"])))) (let [body (first (get-in request [:body "postData"]))] (is (= 1 (get body "samplerate"))) (is (= {"foo" "bar"} (get body "data")))))))))) (deftest generate-trace-id-works (check `honeycomb/generate-trace-id)) (deftest generate-span-id-works (check `honeycomb/generate-span-id)) (deftest with-event-works (testing "Code that doesn't throw still returns AND sends the event" (validate-events (fn [] (is (= :foo (honeycomb/with-event {:foo "foo"} {} (honeycomb/add-to-event {:bar "bar"}) (Thread/sleep 100) (honeycomb/add-to-event :baz "baz") :foo)))) (fn [events errors] (is (empty? errors)) (is (= 1 (count events))) (let [event-data (some->> events first event->fields)] (is (= {"foo" "foo" "bar" "bar" "baz" "baz"} (dissoc event-data "durationMs"))) (is (< 100 (get event-data "durationMs" -1))))))) (testing "Code that throws both throws AND sends the event" (validate-events (fn [] (is (thrown? Exception (honeycomb/with-event {:foo "foo"} {} (honeycomb/add-to-event {:bar "bar"}) (honeycomb/add-to-event :baz "baz") (throw (Exception. "An exception")))))) (fn [events errors] (is (empty? errors)) (is (= 1 (count events))) (let [event-data (some->> events first event->fields)] (is (= {"foo" "foo" "bar" "bar" "baz" "baz"} (dissoc event-data "exception" "durationMs"))) (is (some-> (get event-data "durationMs") pos?)) (is (instance? Exception (get event-data "exception"))))))) (testing "with-event can generate trace spans" (let [trace-id (honeycomb/generate-trace-id)] (testing "The bare minimum" (validate-events (fn [] (is (= :body-value (honeycomb/with-event {:foo "bar" :traceId trace-id} {} :body-value)))) (fn [events errors] (is (= 1 (count events))) (when-let [event (->> events (map event->fields) first)] (is (some? (get event "id"))) (is (float? (get event "durationMs"))) (is (= {"traceId" trace-id "parentId" nil "foo" "bar"} (dissoc event "durationMs" "id")))) (is (empty? errors))))) (testing "Specifying an ID" (validate-events (fn [] (is (= :body-value (honeycomb/with-event {:foo "bar" :id "some-id" :traceId trace-id} {} :body-value)))) (fn [events errors] (is (= 1 (count events))) (when-let [event (->> events (map event->fields) first)] (is (float? (get event "durationMs"))) (is (= {"traceId" trace-id "parentId" nil "foo" "bar" "id" "some-id"} (dissoc event "durationMs")))) (is (empty? errors))))) (testing "Nested events create parent-child spans" (validate-events (fn [] (is (= :body-value (honeycomb/with-event {:foo "bar" :traceId trace-id} {} (honeycomb/with-event {:baz "quux"} {} :body-value))))) (fn [events errors] (let [events (map event->fields events)] (is (= 2 (count events))) (is (every? some? (map #(get % "id") events))) (is (every? float? (map #(get % "durationMs") events))) (is (= [{"traceId" trace-id "baz" "quux"} {"traceId" trace-id "foo" "bar"}] (map #(dissoc % "id" "parentId" "durationMs") events))) (is (nil? (get (last events) "parentId"))) (is (some? (get (first events) "parentId"))) (is (= (get (first events) "parentId") (get (last events) "id")))) (is (empty? errors))))) (testing "Nested events create parent-child spans with with-trace-id" (validate-events (fn [] (is (= :body-value (honeycomb/with-trace-id trace-id (honeycomb/with-event {:foo "bar"} {} (honeycomb/with-event {:baz "quux"} {} :body-value)))))) (fn [events errors] (let [events (map event->fields events)] (is (= 2 (count events))) (is (every? some? (map #(get % "id") events))) (is (every? float? (map #(get % "durationMs") events))) (is (= [{"traceId" trace-id "baz" "quux"} {"traceId" trace-id "foo" "bar"}] (map #(dissoc % "id" "parentId" "durationMs") events))) (is (nil? (get (last events) "parentId"))) (is (some? (get (first events) "parentId"))) (is (= (get (first events) "parentId") (get (last events) "id")))) (is (empty? errors))))) (testing "It's possible to create non-enclosing parent-child relationships" (let [x-id (honeycomb/generate-span-id)] (validate-events (fn [] (honeycomb/with-trace-id trace-id (honeycomb/with-event {:doing "X" :id x-id} {} (Thread/sleep 50)) (honeycomb/with-event {:doing "Y" :parentId x-id} {} (Thread/sleep 50)))) (fn [events errors] (let [events (map event->fields events)] (is (every? some? (map #(get % "id") events))) (is (= [{"traceId" trace-id "doing" "X" "parentId" nil} {"traceId" trace-id "doing" "Y" "parentId" (get (first events) "id")}] (map #(dissoc % "durationMs" "id") events)))) (is (empty? errors))))))))) (deftest live-test-against-honeycomb ; This has no assertions. It's here purely so that we can generate some known ; events and inspect them in the Honeycomb.io UI to detect unexpected ; serialisation issues. (let [data-set (System/getenv "HONEYCOMB_DATA_SET") write-key (System/getenv "HONEYCOMB_WRITE_KEY") kitchen-sink (make-kitchen-sink)] (when (and data-set write-key) (testing "The primitives work" (with-open [client (honeycomb/client {:data-set data-set :write-key write-key})] (honeycomb/send client kitchen-sink))) (testing "Using init and with-event works" (let [original-client @#'honeycomb/*client*] (try (honeycomb/init {:data-set data-set :write-key write-key}) (honeycomb/with-event {:foo "foo"} {} (honeycomb/add-to-event {:bar "bar"}) (honeycomb/add-to-event :baz "baz")) (finally (alter-var-root #'honeycomb/*client* (constantly original-client))))))))) (deftest nonsense-tests-just-to-cover-spec ; We need to call explain-data on these to ensure that the macroexpanded form ; generated by s/keys is covered properly. (s/explain-data :clj-honeycomb.core/create-event-options {:foo {:bar :baz}}) (s/explain-data :clj-honeycomb.core/response-observer {:foo {:bar :baz}}) (s/explain-data :clj-honeycomb.core/send-options {:foo {:bar :baz}}) (s/explain-data :clj-honeycomb.core/transport-options {:foo {:bar :baz}}))
true
(ns clj-honeycomb.core-test (:require [clojure.data.json :as json] [clojure.spec.alpha :as s] [clojure.spec.gen.alpha :as gen] [clojure.spec.test.alpha :refer (check with-instrument-disabled)] [clojure.test :refer (are deftest is testing)] [stub-http.core :as stub-http] [clj-honeycomb.core :as honeycomb] [clj-honeycomb.fixtures :refer (kitchen-sink-realized make-kitchen-sink use-fixtures)] [clj-honeycomb.testing-utils :refer (no-op-client recording-client validate-events)]) (:import (clojure.lang ExceptionInfo) (stub_http.core NanoFakeServer) (io.honeycomb.libhoney Event EventPostProcessor HoneyClient Options ResponseObserver TransportOptions ValueSupplier) (io.honeycomb.libhoney.responses ClientRejected ServerAccepted ServerRejected Unknown))) (use-fixtures) (defn- event->fields "A helper to extract the fields from an event while avoiding NPEs and ensuring that we get a legit Clojure map out at the end." [^Event event] (when event (into {} (.getFields event)))) (deftest client-options-random-generations (doseq [co (gen/sample (s/gen :clj-honeycomb.core/client-options))] (is (instance? Options (#'honeycomb/client-options co))))) (deftest client-options-works (testing "It fails when it's missing both data-set and write-key" (try (#'honeycomb/client-options {}) (catch ExceptionInfo e (is (:clojure.spec.alpha/problems (ex-data e)))))) (testing "It fails when it's missing data-set" (try (#'honeycomb/client-options {:write-key "foo"}) (catch ExceptionInfo e (is (:clojure.spec.alpha/problems (ex-data e)))))) (testing "It fails when it's missing write-key" (try (#'honeycomb/client-options {:data-set "foo"}) (catch ExceptionInfo e (is (:clojure.spec.alpha/problems (ex-data e)))))) (testing "Minimum viable arguments" (let [^Options options (#'honeycomb/client-options {:data-set "data-set" :write-key "write-key"})] (is (= "https://api.honeycomb.io/" (str (.getApiHost options)))) (is (= "data-set" (.getDataset options))) (is (nil? (.getEventPostProcessor options))) (is (= {} (.getGlobalFields options))) (is (= {} (.getGlobalDynamicFields options))) (is (= 1 (.getSampleRate options))) (is (= "write-key" (.getWriteKey options))))) (testing "Can set API host" (let [^Options options (#'honeycomb/client-options {:api-host "https://localhost:12345/" :data-set "data-set" :write-key "write-key"})] (is (= "https://localhost:12345/" (str (.getApiHost options)))) (is (= "data-set" (.getDataset options))) (is (nil? (.getEventPostProcessor options))) (is (= {} (.getGlobalFields options))) (is (= {} (.getGlobalDynamicFields options))) (is (= 1 (.getSampleRate options))) (is (= "write-key" (.getWriteKey options))))) (testing "Can set Event Post Processor" (let [epp (reify EventPostProcessor (process [_this _event-data] nil)) ^Options options (#'honeycomb/client-options {:data-set "data-set" :event-post-processor epp :write-key "write-key"})] (is (= "https://api.honeycomb.io/" (str (.getApiHost options)))) (is (= "data-set" (.getDataset options))) (is (= epp (.getEventPostProcessor options))) (is (= {} (.getGlobalFields options))) (is (= {} (.getGlobalDynamicFields options))) (is (= 1 (.getSampleRate options))) (is (= "write-key" (.getWriteKey options))))) (testing "Can set global fields" (let [^Options options (#'honeycomb/client-options {:data-set "data-set" :global-fields {:foo 1} :write-key "write-key"})] (is (= "https://api.honeycomb.io/" (str (.getApiHost options)))) (is (= "data-set" (.getDataset options))) (is (nil? (.getEventPostProcessor options))) (is (= {"foo" 1} (.getGlobalFields options))) (is (= {} (.getGlobalDynamicFields options))) (is (= 1 (.getSampleRate options))) (is (= "write-key" (.getWriteKey options))))) (testing "Can set global dynamic fields" (let [^Options options (#'honeycomb/client-options {:data-set "data-set" :global-fields {:foo (delay 42)} :write-key "write-key"})] (is (= "https://api.honeycomb.io/" (str (.getApiHost options)))) (is (= "data-set" (.getDataset options))) (is (nil? (.getEventPostProcessor options))) (is (= {} (.getGlobalFields options))) (let [dynamic-fields (.getGlobalDynamicFields options)] (is (= 1 (count dynamic-fields))) (is (get dynamic-fields "foo")) (is (instance? ValueSupplier (get dynamic-fields "foo"))) (is (= 42 (.supply ^ValueSupplier (get dynamic-fields "foo"))))) (is (= 1 (.getSampleRate options))) (is (= "write-key" (.getWriteKey options))))) (testing "Can set sample rate" (let [^Options options (#'honeycomb/client-options {:data-set "data-set" :sample-rate 42 :write-key "write-key"})] (is (= "https://api.honeycomb.io/" (str (.getApiHost options)))) (is (= "data-set" (.getDataset options))) (is (nil? (.getEventPostProcessor options))) (is (= {} (.getGlobalFields options))) (is (= {} (.getGlobalDynamicFields options))) (is (= 42 (.getSampleRate options))) (is (= "write-key" (.getWriteKey options)))))) (deftest transport-options-random-generations (doseq [to (gen/sample (s/gen :clj-honeycomb.core/transport-options))] (is (instance? TransportOptions (#'honeycomb/transport-options to))))) (deftest transport-options-works ; By hardcoding these transport options here, this test will also detect ; changes in the underlying libhoney-java library. (let [default-transport-options {:additionalUserAgent "" :batchSize 50 :batchTimeoutMillis 100 :bufferSize 8192 :connectTimeout 0 :connectionRequestTimeout 0 :ioThreadCount 4 :maxConnections 200 :maxHttpConnectionsPerApiHost 100 :maxPendingBatchRequests 250 :maximumHttpRequestShutdownWait 2000 :queueCapacity 10000 :socketTimeout 3000} checks-out (fn [expected input] (let [^TransportOptions to (#'honeycomb/transport-options input)] (and (instance? TransportOptions to) (integer? (.getIoThreadCount to)) (pos? (.getIoThreadCount to)) (= (-> to bean (dissoc :class :ioThreadCount)) (dissoc expected :ioThreadCount)))))] (are [input expected] (checks-out expected input) {} default-transport-options {:additional-user-agent "foo"} (assoc default-transport-options :additionalUserAgent "foo") {:batch-size 100} (assoc default-transport-options :batchSize 100) {:batch-timeout-millis 200} (assoc default-transport-options :batchTimeoutMillis 200) {:buffer-size 1024} (assoc default-transport-options :bufferSize 1024) {:connection-request-timeout 1} (assoc default-transport-options :connectionRequestTimeout 1) {:connect-timeout 1} (assoc default-transport-options :connectTimeout 1) {:io-thread-count 1} (assoc default-transport-options :ioThreadCount 1) {:max-connections 100} (assoc default-transport-options :maxConnections 100) {:max-connections-per-api-host 150} (assoc default-transport-options :maxHttpConnectionsPerApiHost 150) {:maximum-http-request-shutdown-wait 1000} (assoc default-transport-options :maximumHttpRequestShutdownWait 1000) {:maximum-pending-batch-requests 125} (assoc default-transport-options :maxPendingBatchRequests 125) {:queue-capacity 1000} (assoc default-transport-options :queueCapacity 1000) {:socket-timeout 1000} (assoc default-transport-options :socketTimeout 1000)))) (deftest response-observer-works (let [client-rejected (reify ClientRejected) server-accepted (reify ServerAccepted) server-rejected (reify ServerRejected) unknown (reify Unknown)] (testing "It still works OK if there are no actual handlers" (let [^ResponseObserver ro (#'honeycomb/response-observer {})] (.onClientRejected ro client-rejected) (.onServerAccepted ro server-accepted) (.onServerRejected ro server-rejected) (.onUnknown ro unknown))) (testing "Each function works as expected" (let [^ResponseObserver ro (#'honeycomb/response-observer {:on-client-rejected (fn [cr] (is (= cr client-rejected))) :on-server-accepted (fn [sa] (is (= sa server-accepted))) :on-server-rejected (fn [sr] (is (= sr server-rejected))) :on-unknown (fn [u] (is (= u unknown)))})] (.onClientRejected ro client-rejected) (.onServerAccepted ro server-accepted) (.onServerRejected ro server-rejected) (.onUnknown ro unknown))) (testing "Randomly generated values work" (check `honeycomb/response-observer)))) (deftest client-works (testing "Without a ResponseObserver" (with-open [client (honeycomb/client {:data-set "data-set" :write-key "write-key"})] (is (instance? HoneyClient client)))) (testing "With a ResponseObserver" (with-open [client (honeycomb/client {:data-set "data-set" :response-observer {:on-unknown (fn [_] nil)} :write-key "write-key"})] (is (instance? HoneyClient client)))) (testing "With empty transport options" (with-open [client (honeycomb/client {:data-set "data-set" :transport-options {} :write-key "write-key"})] (is (instance? HoneyClient client)))) (testing "With non-empty transport options" (with-open [client (honeycomb/client {:data-set "data-set" :transport-options {:batch-size 10} :write-key "write-key"})] (is (instance? HoneyClient client)))) (testing "We can add an event pre-processor" (with-open [client (honeycomb/client {:data-set "data-set" :event-pre-processor (fn [event-data options] [event-data options]) :write-key "write-key"})] (is (instance? HoneyClient client))))) (deftest init-and-initialized?-works (testing "Initialize with a map" (is (nil? @#'honeycomb/*client*)) (is (not (honeycomb/initialized?))) (when (nil? @#'honeycomb/*client*) (try (let [options {:data-set "data-set" :write-key "write-key"}] (with-open [client (honeycomb/client options)] (is (not (honeycomb/initialized?))) (is (= (bean client) (bean (honeycomb/init options)))) (is (= (bean client) (bean @#'honeycomb/*client*))) (is (honeycomb/initialized?)))) (finally (alter-var-root #'honeycomb/*client* (constantly nil))))) (is (not (honeycomb/initialized?))) (is (nil? @#'honeycomb/*client*))) (testing "Initialize with a client" (is (nil? @#'honeycomb/*client*)) (is (not (honeycomb/initialized?))) (when (nil? @#'honeycomb/*client*) (try (let [options {:data-set "data-set" :write-key "write-key"}] (with-open [client (honeycomb/client options)] (is (not (honeycomb/initialized?))) (is (= client (honeycomb/init client))) (is (= client @#'honeycomb/*client*)) (is (honeycomb/initialized?)))) (finally (alter-var-root #'honeycomb/*client* (constantly nil))))) (is (not (honeycomb/initialized?))) (is (nil? @#'honeycomb/*client*))) (testing "The argument must be a client or a map" (with-instrument-disabled (is (thrown? IllegalArgumentException (honeycomb/init nil)))))) (deftest create-event-works (with-open [honeycomb-client (honeycomb/client {:data-set "data-set" :write-key "write-key"})] (testing "Empty event" (let [^Event event (#'honeycomb/create-event honeycomb-client {} {})] (is (= "https://api.honeycomb.io/" (str (.getApiHost event)))) (is (= "data-set" (.getDataset event))) (is (= {} (event->fields event))) (is (= {} (.getMetadata event))) (is (= 1 (.getSampleRate event))) (is (nil? (.getTimestamp event))) (is (= "write-key" (.getWriteKey event))))) (testing "Fields get realized properly and infinite/lazy things don't block." (let [^Event event (#'honeycomb/create-event honeycomb-client {:nil nil :string "string" :integer 42 :float Math/E :fraction 22/7 :atom (atom 3) :delay (delay 4)} {})] (is (= "https://api.honeycomb.io/" (str (.getApiHost event)))) (is (= "data-set" (.getDataset event))) (is (= {"nil" nil "string" "string" "integer" 42 "float" Math/E "fraction" (float 22/7) "atom" 3 "delay" 4} (event->fields event))) (is (= {} (.getMetadata event))) (is (= 1 (.getSampleRate event))) (is (nil? (.getTimestamp event))) (is (= "write-key" (.getWriteKey event))))) (testing "Options get set on the event" (let [^Event event (#'honeycomb/create-event honeycomb-client {} {:api-host "https://localhost:123/" :data-set "foo" :metadata {:event-id 42} :sample-rate 3 :timestamp 123456 :write-key "bar"})] (is (= "https://localhost:123/" (str (.getApiHost event)))) (is (= "foo" (.getDataset event))) (is (= {} (event->fields event))) (is (= {:event-id 42} (.getMetadata event))) (is (= 3 (.getSampleRate event))) (is (= 123456 (.getTimestamp event))) (is (= "bar" (.getWriteKey event))))) (testing "Event pre-processor runs" (with-open [client (honeycomb/client {:data-set "data-set" :event-pre-processor (fn [event-data options] [(assoc event-data :integer 1) options]) :write-key "write-key"})] (let [^Event event (#'honeycomb/create-event client {:nil nil :string "string" :integer 42 :float Math/E :fraction 22/7 :atom (atom 3) :delay (delay 4)} {})] (is (= "https://api.honeycomb.io/" (str (.getApiHost event)))) (is (= "data-set" (.getDataset event))) (is (= {"nil" nil "string" "string" "integer" 1 "float" Math/E "fraction" (float 22/7) "atom" 3 "delay" 4} (event->fields event))) (is (= {} (.getMetadata event))) (is (= 1 (.getSampleRate event))) (is (nil? (.getTimestamp event))) (is (= "write-key" (.getWriteKey event)))))))) (deftest send-works (testing "One argument" (testing "requires a client from init first" (binding [honeycomb/*client* nil] (is (thrown? IllegalStateException (honeycomb/send {:foo "bar"}))))) (testing "works when there's a global client set" (validate-events (fn [] (honeycomb/send {:foo "bar"})) (fn [events errors] (is (empty? errors)) (is (= 1 (count events))) (is (= {"foo" "bar"} (event->fields (first events)))))))) (testing "Two arguments works" (let [events (atom [])] (with-open [client (recording-client events {:data-set "data-set" :write-key "write-key"})] (honeycomb/send client {:foo "bar"})) (is (= 1 (count @events))) (is (= {"foo" "bar"} (event->fields (first @events)))))) (testing "Three arguments works" (let [events (atom [])] (with-open [client (recording-client events {:data-set "data-set" :write-key "write-key"})] (honeycomb/send client {:foo "bar"} {:pre-sampled true})) (is (= 1 (count @events))) (is (= {"foo" "bar"} (event->fields (first @events)))))) (testing "Global fields get sent" (let [dynamic-field (atom 1) events (atom [])] (with-open [client (recording-client events {:data-set "data-set" :global-fields {:dynamic dynamic-field :static "static"} :write-key "write-key"})] (honeycomb/send client {:foo "bar"}) (swap! dynamic-field inc) (honeycomb/send client {:foo "bar"})) (is (= [{"dynamic" 1 "foo" "bar" "static" "static"} {"dynamic" 2 "foo" "bar" "static" "static"}] (map event->fields @events))))) (testing "Randomly generated send options" (doseq [send-options (gen/sample (s/gen :clj-honeycomb.core/send-options))] (validate-events (fn [] (honeycomb/send {:foo "bar"} send-options)) (fn [events errors] (if (empty? errors) (do (is (= 1 (count events))) (is (= {"foo" "bar"} (event->fields (first events))))) (do (is (= 1 (count errors))) (is (instance? ClientRejected (first errors))) (is (= "NOT_SAMPLED" (str (.getReason ^ClientRejected (first errors))))))))))) (testing "Random everything" (doseq [client-options (gen/sample (s/gen :clj-honeycomb.core/client-options))] (doseq [send-options (gen/sample (s/gen :clj-honeycomb.core/send-options))] (let [events (atom [])] (with-open [client (recording-client events client-options)] (honeycomb/send client {:foo "bar"} send-options)) (cond (= 0 (count @events)) (is (or (< 1 (or (:sample-rate client-options) 1)) (< 1 (or (:sample-rate send-options) 1)))) (= 1 (count @events)) (is (contains? (event->fields (first @events)) "foo")) :else (is (empty? @events)))))))) (defn- capture-honeycomb-http-calls [data-set expected-calls timeout-ms f] (with-open [^NanoFakeServer http-server (stub-http/start! {(str "/1/batch/" data-set) {:status 200 :body ""}})] (f (:uri http-server)) (let [deadline (+ (System/nanoTime) (* timeout-ms 1e6))] (loop [] (let [recordings (->> http-server :routes deref (mapcat :recordings) (map #(update-in % [:request :body "postData"] json/read-str)))] (cond (= expected-calls (count recordings)) recordings (< expected-calls (count recordings)) (do (is (= expected-calls (count recordings))) recordings) (> expected-calls (count recordings)) (if (< deadline (System/nanoTime)) (throw (ex-info "Deadline exceeded when waiting for replies" {})) (do (Thread/sleep 100) (recur))))))))) (deftest send-makes-the-expected-http-calls (let [data-set "data-set" write-key "PI:KEY:<KEY>END_PIkey" prune-nils (fn pn [m] (if (map? m) (->> m (remove (comp nil? val)) (map (fn [[k v]] [k (pn v)])) (into {})) m))] (-> (capture-honeycomb-http-calls data-set 1 10000 (fn [uri] (with-open [client (honeycomb/client {:api-host uri :data-set data-set :write-key write-key})] (honeycomb/send client (make-kitchen-sink))))) ((fn [requests] (let [request (:request (first requests))] (is (= "POST" (:method request))) (is (= (str "/1/batch/" data-set) (:path request))) (is (= write-key (-> request :headers :x-honeycomb-team))) (is (= 1 (count (get-in request [:body "postData"])))) (let [body (first (get-in request [:body "postData"]))] (is (= 1 (get body "samplerate"))) (let [data (atom (get body "data")) expected (atom (prune-nils kitchen-sink-realized))] ; Make sure they have the same keys (is (= (sort (keys @expected)) (sort (keys @data)))) ; Check each key in turn so that the errors are more readable (doseq [[k v] @expected] (if (instance? Throwable v) (do (is (= "An exception" (get-in @data [(name k) "message"]))) (is (get-in @data [(name k) "stackTrace"]))) (is (= v (get @data (name k)))))))))))))) (deftest send-pre-sampled-makes-the-expected-http-calls (let [data-set "data-set" write-key "write-key"] (-> (capture-honeycomb-http-calls data-set 1 10000 (fn [uri] (with-open [client (honeycomb/client {:api-host uri :data-set data-set :write-key write-key})] (honeycomb/send client {:foo "bar"} {:pre-sampled true})))) ((fn [requests] (let [request (:request (first requests))] (is (= "POST" (:method request))) (is (= (str "/1/batch/" data-set) (:path request))) (is (= write-key (-> request :headers :x-honeycomb-team))) (is (= 1 (count (get-in request [:body "postData"])))) (let [body (first (get-in request [:body "postData"]))] (is (= 1 (get body "samplerate"))) (is (= {"foo" "bar"} (get body "data")))))))))) (deftest generate-trace-id-works (check `honeycomb/generate-trace-id)) (deftest generate-span-id-works (check `honeycomb/generate-span-id)) (deftest with-event-works (testing "Code that doesn't throw still returns AND sends the event" (validate-events (fn [] (is (= :foo (honeycomb/with-event {:foo "foo"} {} (honeycomb/add-to-event {:bar "bar"}) (Thread/sleep 100) (honeycomb/add-to-event :baz "baz") :foo)))) (fn [events errors] (is (empty? errors)) (is (= 1 (count events))) (let [event-data (some->> events first event->fields)] (is (= {"foo" "foo" "bar" "bar" "baz" "baz"} (dissoc event-data "durationMs"))) (is (< 100 (get event-data "durationMs" -1))))))) (testing "Code that throws both throws AND sends the event" (validate-events (fn [] (is (thrown? Exception (honeycomb/with-event {:foo "foo"} {} (honeycomb/add-to-event {:bar "bar"}) (honeycomb/add-to-event :baz "baz") (throw (Exception. "An exception")))))) (fn [events errors] (is (empty? errors)) (is (= 1 (count events))) (let [event-data (some->> events first event->fields)] (is (= {"foo" "foo" "bar" "bar" "baz" "baz"} (dissoc event-data "exception" "durationMs"))) (is (some-> (get event-data "durationMs") pos?)) (is (instance? Exception (get event-data "exception"))))))) (testing "with-event can generate trace spans" (let [trace-id (honeycomb/generate-trace-id)] (testing "The bare minimum" (validate-events (fn [] (is (= :body-value (honeycomb/with-event {:foo "bar" :traceId trace-id} {} :body-value)))) (fn [events errors] (is (= 1 (count events))) (when-let [event (->> events (map event->fields) first)] (is (some? (get event "id"))) (is (float? (get event "durationMs"))) (is (= {"traceId" trace-id "parentId" nil "foo" "bar"} (dissoc event "durationMs" "id")))) (is (empty? errors))))) (testing "Specifying an ID" (validate-events (fn [] (is (= :body-value (honeycomb/with-event {:foo "bar" :id "some-id" :traceId trace-id} {} :body-value)))) (fn [events errors] (is (= 1 (count events))) (when-let [event (->> events (map event->fields) first)] (is (float? (get event "durationMs"))) (is (= {"traceId" trace-id "parentId" nil "foo" "bar" "id" "some-id"} (dissoc event "durationMs")))) (is (empty? errors))))) (testing "Nested events create parent-child spans" (validate-events (fn [] (is (= :body-value (honeycomb/with-event {:foo "bar" :traceId trace-id} {} (honeycomb/with-event {:baz "quux"} {} :body-value))))) (fn [events errors] (let [events (map event->fields events)] (is (= 2 (count events))) (is (every? some? (map #(get % "id") events))) (is (every? float? (map #(get % "durationMs") events))) (is (= [{"traceId" trace-id "baz" "quux"} {"traceId" trace-id "foo" "bar"}] (map #(dissoc % "id" "parentId" "durationMs") events))) (is (nil? (get (last events) "parentId"))) (is (some? (get (first events) "parentId"))) (is (= (get (first events) "parentId") (get (last events) "id")))) (is (empty? errors))))) (testing "Nested events create parent-child spans with with-trace-id" (validate-events (fn [] (is (= :body-value (honeycomb/with-trace-id trace-id (honeycomb/with-event {:foo "bar"} {} (honeycomb/with-event {:baz "quux"} {} :body-value)))))) (fn [events errors] (let [events (map event->fields events)] (is (= 2 (count events))) (is (every? some? (map #(get % "id") events))) (is (every? float? (map #(get % "durationMs") events))) (is (= [{"traceId" trace-id "baz" "quux"} {"traceId" trace-id "foo" "bar"}] (map #(dissoc % "id" "parentId" "durationMs") events))) (is (nil? (get (last events) "parentId"))) (is (some? (get (first events) "parentId"))) (is (= (get (first events) "parentId") (get (last events) "id")))) (is (empty? errors))))) (testing "It's possible to create non-enclosing parent-child relationships" (let [x-id (honeycomb/generate-span-id)] (validate-events (fn [] (honeycomb/with-trace-id trace-id (honeycomb/with-event {:doing "X" :id x-id} {} (Thread/sleep 50)) (honeycomb/with-event {:doing "Y" :parentId x-id} {} (Thread/sleep 50)))) (fn [events errors] (let [events (map event->fields events)] (is (every? some? (map #(get % "id") events))) (is (= [{"traceId" trace-id "doing" "X" "parentId" nil} {"traceId" trace-id "doing" "Y" "parentId" (get (first events) "id")}] (map #(dissoc % "durationMs" "id") events)))) (is (empty? errors))))))))) (deftest live-test-against-honeycomb ; This has no assertions. It's here purely so that we can generate some known ; events and inspect them in the Honeycomb.io UI to detect unexpected ; serialisation issues. (let [data-set (System/getenv "HONEYCOMB_DATA_SET") write-key (System/getenv "HONEYCOMB_WRITE_KEY") kitchen-sink (make-kitchen-sink)] (when (and data-set write-key) (testing "The primitives work" (with-open [client (honeycomb/client {:data-set data-set :write-key write-key})] (honeycomb/send client kitchen-sink))) (testing "Using init and with-event works" (let [original-client @#'honeycomb/*client*] (try (honeycomb/init {:data-set data-set :write-key write-key}) (honeycomb/with-event {:foo "foo"} {} (honeycomb/add-to-event {:bar "bar"}) (honeycomb/add-to-event :baz "baz")) (finally (alter-var-root #'honeycomb/*client* (constantly original-client))))))))) (deftest nonsense-tests-just-to-cover-spec ; We need to call explain-data on these to ensure that the macroexpanded form ; generated by s/keys is covered properly. (s/explain-data :clj-honeycomb.core/create-event-options {:foo {:bar :baz}}) (s/explain-data :clj-honeycomb.core/response-observer {:foo {:bar :baz}}) (s/explain-data :clj-honeycomb.core/send-options {:foo {:bar :baz}}) (s/explain-data :clj-honeycomb.core/transport-options {:foo {:bar :baz}}))
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 29, "score": 0.99981290102005, "start": 18, "tag": "NAME", "value": "Rich Hickey" } ]
ext/clojure-clojurescript-bef56a7/samples/twitterbuzz/src/twitterbuzz/showgraph.cljs
yokolet/clementine
35
; Copyright (c) Rich Hickey. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns twitterbuzz.showgraph (:require [twitterbuzz.core :as buzz] [twitterbuzz.layout :as layout] [twitterbuzz.dom-helpers :as dom] [twitterbuzz.timeline :as timeline] [goog.events :as events] [goog.style :as style] [goog.math.Coordinate :as Coordinate] [goog.ui.HoverCard :as HoverCard] [goog.graphics.Font :as Font] [goog.graphics.Stroke :as Stroke] [goog.graphics.SolidFill :as SolidFill] [goog.graphics :as graphics])) ; Drawing configuration (def avatar-size 32) ; used for both x and y dimensions of avatars ; fail whale ;(def default-avatar "http://farm3.static.flickr.com/2562/4140195522_e207b97280_s.jpg") ; google+ silhouette (def default-avatar "http://ssl.gstatic.com/s2/profiles/images/silhouette48.png") (defn debug [_]) ;(defn debug [a] (str "t: " (:t a) " score: " (:best-score a))) ; BAD HACK: don't change globals like this -- find a better way: ;(set! anim/TIMEOUT 500) (def edge-stroke (graphics/Stroke. 1 "#009")) (def g (doto (graphics/createGraphics "100%" "100%") (.render (dom/get-element :network)))) (def font (graphics/Font. 12 "Arial")) (def fill (graphics/SolidFill. "#f00")) (defn unit-to-pixel [unit-arg canvas-size] (+ (* unit-arg (- canvas-size avatar-size)) (/ avatar-size 2))) (defn log [& args] (js/console.log (apply pr-str args))) (def avatar-hover (doto (goog.ui/HoverCard. (js-obj)) ; svg IMAGE tags don't work here (.setElement (dom/get-element :avatar-hover)))) (defn hide-tooltip [event] (.setVisible avatar-hover false)) (defn attach-tooltip [img canvas-offset px py tweet] (events/listen img events/EventType.MOUSEOUT hide-tooltip) (events/listen img events/EventType.MOUSEOVER (fn [event] (hide-tooltip event) (.setPosition avatar-hover (goog.ui/Tooltip.CursorTooltipPosition. (Coordinate/sum (goog.math/Coordinate. px py) canvas-offset))) (dom/remove-children :avatar-hover-body) (dom/append (dom/get-element :avatar-hover-body) (timeline/timeline-element tweet)) (.triggerForElement avatar-hover img)))) (defn draw-graph [{:keys [locs mentions]} text] (let [canvas-size (. g (getPixelSize)) canvas-offset (style/getPageOffset (dom/get-element :network))] (. g (clear)) ; Draw mention edges (doseq [[username {ux1 :x, uy1 :y}] locs :let [x1 (unit-to-pixel ux1 (.-width canvas-size)) y1 (unit-to-pixel uy1 (.-height canvas-size))] [mention-name mention-count] (:mentions (get mentions username))] (when-let [{ux2 :x, uy2 :y} (get locs mention-name)] (let [x2 (unit-to-pixel ux2 (.-width canvas-size)) y2 (unit-to-pixel uy2 (.-height canvas-size))] (.drawPath g (-> (. g (createPath)) (.moveTo x1 y1) (.lineTo x2 y2)) edge-stroke nil)))) ; Draw avatar nodes (doseq [[username {:keys [x y] :as foo}] locs] ;(log (pr-str foo)) (let [px (- (unit-to-pixel x (.-width canvas-size)) (/ avatar-size 2)) py (- (unit-to-pixel y (.-height canvas-size)) (/ avatar-size 2)) user (get mentions username) image-url (get user :image-url default-avatar) img (.drawImage g px py avatar-size avatar-size image-url)] (attach-tooltip img canvas-offset px py {:profile_image_url image-url :text (:last-tweet user) :from_user (:username user)}))) (let [text (if (empty? locs) "No locations to graph" text)] (when text (.drawTextOnLine g text 5 20 (.-width canvas-size) 20 "left" font nil fill))))) (def graph-data (atom nil)) ;; Register event listeners. (buzz/register :graph-update (fn [data] (reset! graph-data data) (draw-graph (layout/radial data) nil))) (events/listen (dom/get-element :network) events/EventType.CLICK #(draw-graph (layout/radial @graph-data) nil)) (buzz/register :track-clicked #(. g (clear)))
11740
; Copyright (c) <NAME>. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns twitterbuzz.showgraph (:require [twitterbuzz.core :as buzz] [twitterbuzz.layout :as layout] [twitterbuzz.dom-helpers :as dom] [twitterbuzz.timeline :as timeline] [goog.events :as events] [goog.style :as style] [goog.math.Coordinate :as Coordinate] [goog.ui.HoverCard :as HoverCard] [goog.graphics.Font :as Font] [goog.graphics.Stroke :as Stroke] [goog.graphics.SolidFill :as SolidFill] [goog.graphics :as graphics])) ; Drawing configuration (def avatar-size 32) ; used for both x and y dimensions of avatars ; fail whale ;(def default-avatar "http://farm3.static.flickr.com/2562/4140195522_e207b97280_s.jpg") ; google+ silhouette (def default-avatar "http://ssl.gstatic.com/s2/profiles/images/silhouette48.png") (defn debug [_]) ;(defn debug [a] (str "t: " (:t a) " score: " (:best-score a))) ; BAD HACK: don't change globals like this -- find a better way: ;(set! anim/TIMEOUT 500) (def edge-stroke (graphics/Stroke. 1 "#009")) (def g (doto (graphics/createGraphics "100%" "100%") (.render (dom/get-element :network)))) (def font (graphics/Font. 12 "Arial")) (def fill (graphics/SolidFill. "#f00")) (defn unit-to-pixel [unit-arg canvas-size] (+ (* unit-arg (- canvas-size avatar-size)) (/ avatar-size 2))) (defn log [& args] (js/console.log (apply pr-str args))) (def avatar-hover (doto (goog.ui/HoverCard. (js-obj)) ; svg IMAGE tags don't work here (.setElement (dom/get-element :avatar-hover)))) (defn hide-tooltip [event] (.setVisible avatar-hover false)) (defn attach-tooltip [img canvas-offset px py tweet] (events/listen img events/EventType.MOUSEOUT hide-tooltip) (events/listen img events/EventType.MOUSEOVER (fn [event] (hide-tooltip event) (.setPosition avatar-hover (goog.ui/Tooltip.CursorTooltipPosition. (Coordinate/sum (goog.math/Coordinate. px py) canvas-offset))) (dom/remove-children :avatar-hover-body) (dom/append (dom/get-element :avatar-hover-body) (timeline/timeline-element tweet)) (.triggerForElement avatar-hover img)))) (defn draw-graph [{:keys [locs mentions]} text] (let [canvas-size (. g (getPixelSize)) canvas-offset (style/getPageOffset (dom/get-element :network))] (. g (clear)) ; Draw mention edges (doseq [[username {ux1 :x, uy1 :y}] locs :let [x1 (unit-to-pixel ux1 (.-width canvas-size)) y1 (unit-to-pixel uy1 (.-height canvas-size))] [mention-name mention-count] (:mentions (get mentions username))] (when-let [{ux2 :x, uy2 :y} (get locs mention-name)] (let [x2 (unit-to-pixel ux2 (.-width canvas-size)) y2 (unit-to-pixel uy2 (.-height canvas-size))] (.drawPath g (-> (. g (createPath)) (.moveTo x1 y1) (.lineTo x2 y2)) edge-stroke nil)))) ; Draw avatar nodes (doseq [[username {:keys [x y] :as foo}] locs] ;(log (pr-str foo)) (let [px (- (unit-to-pixel x (.-width canvas-size)) (/ avatar-size 2)) py (- (unit-to-pixel y (.-height canvas-size)) (/ avatar-size 2)) user (get mentions username) image-url (get user :image-url default-avatar) img (.drawImage g px py avatar-size avatar-size image-url)] (attach-tooltip img canvas-offset px py {:profile_image_url image-url :text (:last-tweet user) :from_user (:username user)}))) (let [text (if (empty? locs) "No locations to graph" text)] (when text (.drawTextOnLine g text 5 20 (.-width canvas-size) 20 "left" font nil fill))))) (def graph-data (atom nil)) ;; Register event listeners. (buzz/register :graph-update (fn [data] (reset! graph-data data) (draw-graph (layout/radial data) nil))) (events/listen (dom/get-element :network) events/EventType.CLICK #(draw-graph (layout/radial @graph-data) nil)) (buzz/register :track-clicked #(. g (clear)))
true
; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns twitterbuzz.showgraph (:require [twitterbuzz.core :as buzz] [twitterbuzz.layout :as layout] [twitterbuzz.dom-helpers :as dom] [twitterbuzz.timeline :as timeline] [goog.events :as events] [goog.style :as style] [goog.math.Coordinate :as Coordinate] [goog.ui.HoverCard :as HoverCard] [goog.graphics.Font :as Font] [goog.graphics.Stroke :as Stroke] [goog.graphics.SolidFill :as SolidFill] [goog.graphics :as graphics])) ; Drawing configuration (def avatar-size 32) ; used for both x and y dimensions of avatars ; fail whale ;(def default-avatar "http://farm3.static.flickr.com/2562/4140195522_e207b97280_s.jpg") ; google+ silhouette (def default-avatar "http://ssl.gstatic.com/s2/profiles/images/silhouette48.png") (defn debug [_]) ;(defn debug [a] (str "t: " (:t a) " score: " (:best-score a))) ; BAD HACK: don't change globals like this -- find a better way: ;(set! anim/TIMEOUT 500) (def edge-stroke (graphics/Stroke. 1 "#009")) (def g (doto (graphics/createGraphics "100%" "100%") (.render (dom/get-element :network)))) (def font (graphics/Font. 12 "Arial")) (def fill (graphics/SolidFill. "#f00")) (defn unit-to-pixel [unit-arg canvas-size] (+ (* unit-arg (- canvas-size avatar-size)) (/ avatar-size 2))) (defn log [& args] (js/console.log (apply pr-str args))) (def avatar-hover (doto (goog.ui/HoverCard. (js-obj)) ; svg IMAGE tags don't work here (.setElement (dom/get-element :avatar-hover)))) (defn hide-tooltip [event] (.setVisible avatar-hover false)) (defn attach-tooltip [img canvas-offset px py tweet] (events/listen img events/EventType.MOUSEOUT hide-tooltip) (events/listen img events/EventType.MOUSEOVER (fn [event] (hide-tooltip event) (.setPosition avatar-hover (goog.ui/Tooltip.CursorTooltipPosition. (Coordinate/sum (goog.math/Coordinate. px py) canvas-offset))) (dom/remove-children :avatar-hover-body) (dom/append (dom/get-element :avatar-hover-body) (timeline/timeline-element tweet)) (.triggerForElement avatar-hover img)))) (defn draw-graph [{:keys [locs mentions]} text] (let [canvas-size (. g (getPixelSize)) canvas-offset (style/getPageOffset (dom/get-element :network))] (. g (clear)) ; Draw mention edges (doseq [[username {ux1 :x, uy1 :y}] locs :let [x1 (unit-to-pixel ux1 (.-width canvas-size)) y1 (unit-to-pixel uy1 (.-height canvas-size))] [mention-name mention-count] (:mentions (get mentions username))] (when-let [{ux2 :x, uy2 :y} (get locs mention-name)] (let [x2 (unit-to-pixel ux2 (.-width canvas-size)) y2 (unit-to-pixel uy2 (.-height canvas-size))] (.drawPath g (-> (. g (createPath)) (.moveTo x1 y1) (.lineTo x2 y2)) edge-stroke nil)))) ; Draw avatar nodes (doseq [[username {:keys [x y] :as foo}] locs] ;(log (pr-str foo)) (let [px (- (unit-to-pixel x (.-width canvas-size)) (/ avatar-size 2)) py (- (unit-to-pixel y (.-height canvas-size)) (/ avatar-size 2)) user (get mentions username) image-url (get user :image-url default-avatar) img (.drawImage g px py avatar-size avatar-size image-url)] (attach-tooltip img canvas-offset px py {:profile_image_url image-url :text (:last-tweet user) :from_user (:username user)}))) (let [text (if (empty? locs) "No locations to graph" text)] (when text (.drawTextOnLine g text 5 20 (.-width canvas-size) 20 "left" font nil fill))))) (def graph-data (atom nil)) ;; Register event listeners. (buzz/register :graph-update (fn [data] (reset! graph-data data) (draw-graph (layout/radial data) nil))) (events/listen (dom/get-element :network) events/EventType.CLICK #(draw-graph (layout/radial @graph-data) nil)) (buzz/register :track-clicked #(. g (clear)))
[ { "context": " :placeholder \"user@example.com\"\n :input-cla", "end": 2003, "score": 0.9999078512191772, "start": 1987, "tag": "EMAIL", "value": "user@example.com" }, { "context": " :placeholder \"your password\"\n :input-", "end": 2463, "score": 0.9965919256210327, "start": 2450, "tag": "PASSWORD", "value": "your password" }, { "context": " :placeholder \"user@example.com\"\n :input-cla", "end": 7009, "score": 0.9999101758003235, "start": 6993, "tag": "EMAIL", "value": "user@example.com" }, { "context": " :placeholder \"Your password\"\n ", "end": 7556, "score": 0.7391564846038818, "start": 7552, "tag": "PASSWORD", "value": "Your" } ]
src/syntereen/hix/auth/views.cljs
bombaywalla/hix
5
(ns syntereen.hix.auth.views (:require [reagent.core :as reagent] [re-frame.core :as rf] [fork.core :as fork] [vlad.core :as v] [syntereen.hix.router :as router] [syntereen.hix.common.forms :as forms] [syntereen.hix.common.views :as views] ) ) ;; -- Login ------------------------------------------------------------------- ;; ;; TODO: Should really be in a validation namespace (def email-regex #"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,63}$") (defn is-email ([] (is-email {})) ([error-data] (v/predicate #(nil? (re-matches email-regex %)) (merge {:type :vlad.core/is-email} error-data)))) (defmethod v/english-translation :vlad.core/is-email [{:keys [name]}] (str name " must be a syntactically valid email address.")) (def login-form-validator-spec (v/join (v/attr ["email"] (v/chain (v/present) (is-email))) (v/attr ["password"] (v/chain (v/present))) )) (defn login-form-validator [values] (v/field-errors login-form-validator-spec values)) (defn login-form [login-denied] [fork/form {:path :login-form :form-id "login-form" :validation login-form-validator :prevent-default? true :clean-on-unmount? true :on-submit #(rf/dispatch [:login (:values %)]) } (fn [{:keys [values form-id errors touched handle-change handle-blur submitting? handle-submit] :as props}] [:form {:id form-id :on-submit handle-submit} [:div [forms/email-input-view props {:name "email" :label "Email" :placeholder "user@example.com" :input-class (when login-denied "is-danger")}] (when (touched "email") [:p.help.is-danger (views/get-error-msg errors "email")]) (when login-denied [:p.help.is-danger "Email or password is incorrect."]) [forms/password-input-view props {:name "password" :label "Password" :placeholder "your password" :input-class (when login-denied "is-danger")}] (when (touched "password") [:p.help.is-danger (views/get-error-msg errors "password")]) (when login-denied [:p.help.is-danger "Email or password is incorrect."]) [:div] ] [:div.field.is-grouped.is-grouped-centered [:div.control [:button.button.is-primary.is-medium.is-fullwidth {:type "submit"} "Login"]] ]])]) (defn login [] (let [errors @(rf/subscribe [:errors]) login-errors (:login errors) login-denied (= 400 (:status login-errors)) ;; TODO: handle 500, 0, -1 statuses as well ] [:div [:section.section [:div.container [:div.columns.is-centered [:div.column.is-one-third-desktop.is-half-tablet [:div.card [:div.card-content ;; (when login-errors (views/errors-list login-errors)) (login-form login-denied) [:br] [:p.help "By logging in, you agree to the " [:a {:href "#"} "terms of service."]] ; TODO: Fix this URL [:p.has-text-centered [:a {:href (router/url-for :request-password-reset)} "Forgot your password?"]] [:p.has-text-centered [:a {:href (router/url-for :register)} "Don't have an account?"]]]]]]]]])) ;; -- Register ---------------------------------------------------------------- ;; (defn register-form-spec [passwd] (v/join (v/attr ["full-name"] (v/chain (v/present))) ; TODO: need more (v/attr ["email"] (v/chain (v/present) (is-email))) (v/attr ["password"] (v/chain (v/present) (v/join (v/length-in 3 128) ; TODO: Should be longer than 12 (v/matches #"^.*[a-z].*$" {:message "Password must contain at least one lower-case letter."}) (v/matches #"^.*[A-Z].*$" {:message "Password must contain at least one upper-case letter."}) (v/matches #"^.*[0-9].*$" {:message "Password must contain at least one digit."}) ))) (v/attr ["confirm-password"] (v/chain (v/present) (v/join (v/length-in 3 128) ; TODO: Should be longer than 12 (v/matches #"^.*[a-z].*$" {:mesage "Password must contain at least one lower-case letter."}) (v/matches #"^.*[A-Z].*$" {:mesage "Password must contain at least one upper-case letter."}) (v/matches #"^.*[0-9].*$" {:message "Password must contain at least one digit."}) (v/equals-value passwd {:message "Confirm password must match password."}) ))) (v/attr ["agree"] (v/equals-value true {:message "You must accept the terms of service."})) )) ;; v/present only seems to work on strings. It should really be non-nil or non-empty string. ;; ;; v/field-errors throws a NPE if one or more of the errors does not have a :selector field. ;; Since the v/equals-field is not associated with a field, the :selector is not there. (defn register-form-validator [values] (v/field-errors (register-form-spec (get values "password")) values)) (defn register-form [email-taken invalid-password] [fork/form {:path :register-form :form-id "register-form" :validation register-form-validator :prevent-default? true :clean-on-unmount? true :on-submit #(rf/dispatch [:register-user (dissoc (dissoc (:values %) "confirm-password") "agree")]) } (fn [{:keys [values form-id errors touched handle-change handle-blur submitting? handle-submit] :as props}] [:form {:id form-id :on-submit handle-submit} [:div [forms/input-view props {:name "full-name" :label "Full name" :placeholder "Your full name" }] (when (touched "full-name") [:p.help.is-danger (views/get-error-msg errors "full-name")]) [forms/email-input-view props {:name "email" :label "Email" :placeholder "user@example.com" :input-class (when email-taken "is-danger")}] [:p.help "We will email you a to verify the email address."] (when (touched "email") [:p.help.is-danger (views/get-error-msg errors "email")]) (when email-taken [:p.help.is-danger "Email already taken."]) ;TODO: Ick. Wording needs to be better. [forms/password-input-view props {:name "password" :label "Password" :placeholder "Your password" :input-class (when invalid-password "is-danger")}] [:p.help "Please pick a strong password (12+chars, lower, upper, digit, special char)."] (when (touched "password") [:p.help.is-danger (views/get-error-msg errors "password")]) (when invalid-password [:p.help.is-danger "Password is invalid (does not follow requirements)."]) [forms/password-input-view props {:name "confirm-password" :label "Confirm password" :placeholder "Repeat your password" :input-class (when invalid-password "is-danger")}] (when (touched "confirm-password") [:p.help.is-danger (views/get-error-msg errors "confirm-password")]) (when invalid-password [:p.help.is-danger "Password is invalid (does not follow requirements)."]) [:div] ] [forms/checkbox-input-view props {:name "agree" :text (list " I agree to the " [:a {:href "#"} "terms of service."])}] ; TODO: fix the href (when (touched "agree") [:p.help.is-danger (views/get-error-msg errors "agree")]) ; TODO: Fix vlad to allow customized, and then, i18n error messages. [:div.field.is-grouped.is-grouped-centered [:div.control [:button.button.is-primary.is-medium.is-fullwidth {:type "submit"} "Sign up"]] ]])]) (defn register [] (let [errors @(rf/subscribe [:errors]) register-errors (:register-user errors) client-error? (= 400 (:status register-errors)) error-code (:error-code (:errors (:response register-errors))) email-taken (= error-code "user-exists") password-invalid (and client-error? (not email-taken)) ; TODO: hacky. improve. ;; TODO: handle 500, 0, -1 statuses as well ] [:div [:section.section [:div.container [:div.columns.is-centered [:div.column.is-half [:div.card [:div.card-content ;; (when register-errors (views/errors-list register-errors)) (register-form email-taken password-invalid) [:br] [:p.has-text-centered [:a {:href (router/url-for :request-password-reset)} "Forgot your password?"]] [:p.has-text-centered [:a {:href (router/url-for :login)} "Already have an account?"]]]]]]]]]))
72061
(ns syntereen.hix.auth.views (:require [reagent.core :as reagent] [re-frame.core :as rf] [fork.core :as fork] [vlad.core :as v] [syntereen.hix.router :as router] [syntereen.hix.common.forms :as forms] [syntereen.hix.common.views :as views] ) ) ;; -- Login ------------------------------------------------------------------- ;; ;; TODO: Should really be in a validation namespace (def email-regex #"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,63}$") (defn is-email ([] (is-email {})) ([error-data] (v/predicate #(nil? (re-matches email-regex %)) (merge {:type :vlad.core/is-email} error-data)))) (defmethod v/english-translation :vlad.core/is-email [{:keys [name]}] (str name " must be a syntactically valid email address.")) (def login-form-validator-spec (v/join (v/attr ["email"] (v/chain (v/present) (is-email))) (v/attr ["password"] (v/chain (v/present))) )) (defn login-form-validator [values] (v/field-errors login-form-validator-spec values)) (defn login-form [login-denied] [fork/form {:path :login-form :form-id "login-form" :validation login-form-validator :prevent-default? true :clean-on-unmount? true :on-submit #(rf/dispatch [:login (:values %)]) } (fn [{:keys [values form-id errors touched handle-change handle-blur submitting? handle-submit] :as props}] [:form {:id form-id :on-submit handle-submit} [:div [forms/email-input-view props {:name "email" :label "Email" :placeholder "<EMAIL>" :input-class (when login-denied "is-danger")}] (when (touched "email") [:p.help.is-danger (views/get-error-msg errors "email")]) (when login-denied [:p.help.is-danger "Email or password is incorrect."]) [forms/password-input-view props {:name "password" :label "Password" :placeholder "<PASSWORD>" :input-class (when login-denied "is-danger")}] (when (touched "password") [:p.help.is-danger (views/get-error-msg errors "password")]) (when login-denied [:p.help.is-danger "Email or password is incorrect."]) [:div] ] [:div.field.is-grouped.is-grouped-centered [:div.control [:button.button.is-primary.is-medium.is-fullwidth {:type "submit"} "Login"]] ]])]) (defn login [] (let [errors @(rf/subscribe [:errors]) login-errors (:login errors) login-denied (= 400 (:status login-errors)) ;; TODO: handle 500, 0, -1 statuses as well ] [:div [:section.section [:div.container [:div.columns.is-centered [:div.column.is-one-third-desktop.is-half-tablet [:div.card [:div.card-content ;; (when login-errors (views/errors-list login-errors)) (login-form login-denied) [:br] [:p.help "By logging in, you agree to the " [:a {:href "#"} "terms of service."]] ; TODO: Fix this URL [:p.has-text-centered [:a {:href (router/url-for :request-password-reset)} "Forgot your password?"]] [:p.has-text-centered [:a {:href (router/url-for :register)} "Don't have an account?"]]]]]]]]])) ;; -- Register ---------------------------------------------------------------- ;; (defn register-form-spec [passwd] (v/join (v/attr ["full-name"] (v/chain (v/present))) ; TODO: need more (v/attr ["email"] (v/chain (v/present) (is-email))) (v/attr ["password"] (v/chain (v/present) (v/join (v/length-in 3 128) ; TODO: Should be longer than 12 (v/matches #"^.*[a-z].*$" {:message "Password must contain at least one lower-case letter."}) (v/matches #"^.*[A-Z].*$" {:message "Password must contain at least one upper-case letter."}) (v/matches #"^.*[0-9].*$" {:message "Password must contain at least one digit."}) ))) (v/attr ["confirm-password"] (v/chain (v/present) (v/join (v/length-in 3 128) ; TODO: Should be longer than 12 (v/matches #"^.*[a-z].*$" {:mesage "Password must contain at least one lower-case letter."}) (v/matches #"^.*[A-Z].*$" {:mesage "Password must contain at least one upper-case letter."}) (v/matches #"^.*[0-9].*$" {:message "Password must contain at least one digit."}) (v/equals-value passwd {:message "Confirm password must match password."}) ))) (v/attr ["agree"] (v/equals-value true {:message "You must accept the terms of service."})) )) ;; v/present only seems to work on strings. It should really be non-nil or non-empty string. ;; ;; v/field-errors throws a NPE if one or more of the errors does not have a :selector field. ;; Since the v/equals-field is not associated with a field, the :selector is not there. (defn register-form-validator [values] (v/field-errors (register-form-spec (get values "password")) values)) (defn register-form [email-taken invalid-password] [fork/form {:path :register-form :form-id "register-form" :validation register-form-validator :prevent-default? true :clean-on-unmount? true :on-submit #(rf/dispatch [:register-user (dissoc (dissoc (:values %) "confirm-password") "agree")]) } (fn [{:keys [values form-id errors touched handle-change handle-blur submitting? handle-submit] :as props}] [:form {:id form-id :on-submit handle-submit} [:div [forms/input-view props {:name "full-name" :label "Full name" :placeholder "Your full name" }] (when (touched "full-name") [:p.help.is-danger (views/get-error-msg errors "full-name")]) [forms/email-input-view props {:name "email" :label "Email" :placeholder "<EMAIL>" :input-class (when email-taken "is-danger")}] [:p.help "We will email you a to verify the email address."] (when (touched "email") [:p.help.is-danger (views/get-error-msg errors "email")]) (when email-taken [:p.help.is-danger "Email already taken."]) ;TODO: Ick. Wording needs to be better. [forms/password-input-view props {:name "password" :label "Password" :placeholder "<PASSWORD> password" :input-class (when invalid-password "is-danger")}] [:p.help "Please pick a strong password (12+chars, lower, upper, digit, special char)."] (when (touched "password") [:p.help.is-danger (views/get-error-msg errors "password")]) (when invalid-password [:p.help.is-danger "Password is invalid (does not follow requirements)."]) [forms/password-input-view props {:name "confirm-password" :label "Confirm password" :placeholder "Repeat your password" :input-class (when invalid-password "is-danger")}] (when (touched "confirm-password") [:p.help.is-danger (views/get-error-msg errors "confirm-password")]) (when invalid-password [:p.help.is-danger "Password is invalid (does not follow requirements)."]) [:div] ] [forms/checkbox-input-view props {:name "agree" :text (list " I agree to the " [:a {:href "#"} "terms of service."])}] ; TODO: fix the href (when (touched "agree") [:p.help.is-danger (views/get-error-msg errors "agree")]) ; TODO: Fix vlad to allow customized, and then, i18n error messages. [:div.field.is-grouped.is-grouped-centered [:div.control [:button.button.is-primary.is-medium.is-fullwidth {:type "submit"} "Sign up"]] ]])]) (defn register [] (let [errors @(rf/subscribe [:errors]) register-errors (:register-user errors) client-error? (= 400 (:status register-errors)) error-code (:error-code (:errors (:response register-errors))) email-taken (= error-code "user-exists") password-invalid (and client-error? (not email-taken)) ; TODO: hacky. improve. ;; TODO: handle 500, 0, -1 statuses as well ] [:div [:section.section [:div.container [:div.columns.is-centered [:div.column.is-half [:div.card [:div.card-content ;; (when register-errors (views/errors-list register-errors)) (register-form email-taken password-invalid) [:br] [:p.has-text-centered [:a {:href (router/url-for :request-password-reset)} "Forgot your password?"]] [:p.has-text-centered [:a {:href (router/url-for :login)} "Already have an account?"]]]]]]]]]))
true
(ns syntereen.hix.auth.views (:require [reagent.core :as reagent] [re-frame.core :as rf] [fork.core :as fork] [vlad.core :as v] [syntereen.hix.router :as router] [syntereen.hix.common.forms :as forms] [syntereen.hix.common.views :as views] ) ) ;; -- Login ------------------------------------------------------------------- ;; ;; TODO: Should really be in a validation namespace (def email-regex #"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,63}$") (defn is-email ([] (is-email {})) ([error-data] (v/predicate #(nil? (re-matches email-regex %)) (merge {:type :vlad.core/is-email} error-data)))) (defmethod v/english-translation :vlad.core/is-email [{:keys [name]}] (str name " must be a syntactically valid email address.")) (def login-form-validator-spec (v/join (v/attr ["email"] (v/chain (v/present) (is-email))) (v/attr ["password"] (v/chain (v/present))) )) (defn login-form-validator [values] (v/field-errors login-form-validator-spec values)) (defn login-form [login-denied] [fork/form {:path :login-form :form-id "login-form" :validation login-form-validator :prevent-default? true :clean-on-unmount? true :on-submit #(rf/dispatch [:login (:values %)]) } (fn [{:keys [values form-id errors touched handle-change handle-blur submitting? handle-submit] :as props}] [:form {:id form-id :on-submit handle-submit} [:div [forms/email-input-view props {:name "email" :label "Email" :placeholder "PI:EMAIL:<EMAIL>END_PI" :input-class (when login-denied "is-danger")}] (when (touched "email") [:p.help.is-danger (views/get-error-msg errors "email")]) (when login-denied [:p.help.is-danger "Email or password is incorrect."]) [forms/password-input-view props {:name "password" :label "Password" :placeholder "PI:PASSWORD:<PASSWORD>END_PI" :input-class (when login-denied "is-danger")}] (when (touched "password") [:p.help.is-danger (views/get-error-msg errors "password")]) (when login-denied [:p.help.is-danger "Email or password is incorrect."]) [:div] ] [:div.field.is-grouped.is-grouped-centered [:div.control [:button.button.is-primary.is-medium.is-fullwidth {:type "submit"} "Login"]] ]])]) (defn login [] (let [errors @(rf/subscribe [:errors]) login-errors (:login errors) login-denied (= 400 (:status login-errors)) ;; TODO: handle 500, 0, -1 statuses as well ] [:div [:section.section [:div.container [:div.columns.is-centered [:div.column.is-one-third-desktop.is-half-tablet [:div.card [:div.card-content ;; (when login-errors (views/errors-list login-errors)) (login-form login-denied) [:br] [:p.help "By logging in, you agree to the " [:a {:href "#"} "terms of service."]] ; TODO: Fix this URL [:p.has-text-centered [:a {:href (router/url-for :request-password-reset)} "Forgot your password?"]] [:p.has-text-centered [:a {:href (router/url-for :register)} "Don't have an account?"]]]]]]]]])) ;; -- Register ---------------------------------------------------------------- ;; (defn register-form-spec [passwd] (v/join (v/attr ["full-name"] (v/chain (v/present))) ; TODO: need more (v/attr ["email"] (v/chain (v/present) (is-email))) (v/attr ["password"] (v/chain (v/present) (v/join (v/length-in 3 128) ; TODO: Should be longer than 12 (v/matches #"^.*[a-z].*$" {:message "Password must contain at least one lower-case letter."}) (v/matches #"^.*[A-Z].*$" {:message "Password must contain at least one upper-case letter."}) (v/matches #"^.*[0-9].*$" {:message "Password must contain at least one digit."}) ))) (v/attr ["confirm-password"] (v/chain (v/present) (v/join (v/length-in 3 128) ; TODO: Should be longer than 12 (v/matches #"^.*[a-z].*$" {:mesage "Password must contain at least one lower-case letter."}) (v/matches #"^.*[A-Z].*$" {:mesage "Password must contain at least one upper-case letter."}) (v/matches #"^.*[0-9].*$" {:message "Password must contain at least one digit."}) (v/equals-value passwd {:message "Confirm password must match password."}) ))) (v/attr ["agree"] (v/equals-value true {:message "You must accept the terms of service."})) )) ;; v/present only seems to work on strings. It should really be non-nil or non-empty string. ;; ;; v/field-errors throws a NPE if one or more of the errors does not have a :selector field. ;; Since the v/equals-field is not associated with a field, the :selector is not there. (defn register-form-validator [values] (v/field-errors (register-form-spec (get values "password")) values)) (defn register-form [email-taken invalid-password] [fork/form {:path :register-form :form-id "register-form" :validation register-form-validator :prevent-default? true :clean-on-unmount? true :on-submit #(rf/dispatch [:register-user (dissoc (dissoc (:values %) "confirm-password") "agree")]) } (fn [{:keys [values form-id errors touched handle-change handle-blur submitting? handle-submit] :as props}] [:form {:id form-id :on-submit handle-submit} [:div [forms/input-view props {:name "full-name" :label "Full name" :placeholder "Your full name" }] (when (touched "full-name") [:p.help.is-danger (views/get-error-msg errors "full-name")]) [forms/email-input-view props {:name "email" :label "Email" :placeholder "PI:EMAIL:<EMAIL>END_PI" :input-class (when email-taken "is-danger")}] [:p.help "We will email you a to verify the email address."] (when (touched "email") [:p.help.is-danger (views/get-error-msg errors "email")]) (when email-taken [:p.help.is-danger "Email already taken."]) ;TODO: Ick. Wording needs to be better. [forms/password-input-view props {:name "password" :label "Password" :placeholder "PI:PASSWORD:<PASSWORD>END_PI password" :input-class (when invalid-password "is-danger")}] [:p.help "Please pick a strong password (12+chars, lower, upper, digit, special char)."] (when (touched "password") [:p.help.is-danger (views/get-error-msg errors "password")]) (when invalid-password [:p.help.is-danger "Password is invalid (does not follow requirements)."]) [forms/password-input-view props {:name "confirm-password" :label "Confirm password" :placeholder "Repeat your password" :input-class (when invalid-password "is-danger")}] (when (touched "confirm-password") [:p.help.is-danger (views/get-error-msg errors "confirm-password")]) (when invalid-password [:p.help.is-danger "Password is invalid (does not follow requirements)."]) [:div] ] [forms/checkbox-input-view props {:name "agree" :text (list " I agree to the " [:a {:href "#"} "terms of service."])}] ; TODO: fix the href (when (touched "agree") [:p.help.is-danger (views/get-error-msg errors "agree")]) ; TODO: Fix vlad to allow customized, and then, i18n error messages. [:div.field.is-grouped.is-grouped-centered [:div.control [:button.button.is-primary.is-medium.is-fullwidth {:type "submit"} "Sign up"]] ]])]) (defn register [] (let [errors @(rf/subscribe [:errors]) register-errors (:register-user errors) client-error? (= 400 (:status register-errors)) error-code (:error-code (:errors (:response register-errors))) email-taken (= error-code "user-exists") password-invalid (and client-error? (not email-taken)) ; TODO: hacky. improve. ;; TODO: handle 500, 0, -1 statuses as well ] [:div [:section.section [:div.container [:div.columns.is-centered [:div.column.is-half [:div.card [:div.card-content ;; (when register-errors (views/errors-list register-errors)) (register-form email-taken password-invalid) [:br] [:p.has-text-centered [:a {:href (router/url-for :request-password-reset)} "Forgot your password?"]] [:p.has-text-centered [:a {:href (router/url-for :login)} "Already have an account?"]]]]]]]]]))
[ { "context": "-------------------------------\n;;\n;;\n;; Author: PLIQUE Guillaume (Yomguithereal)\n;; Version: 0.1\n;;\n(ns clj-fuzz", "end": 218, "score": 0.9998538494110107, "start": 202, "tag": "NAME", "value": "PLIQUE Guillaume" }, { "context": "------------\n;;\n;;\n;; Author: PLIQUE Guillaume (Yomguithereal)\n;; Version: 0.1\n;;\n(ns clj-fuzzy.jaro-winkler-", "end": 233, "score": 0.9994239807128906, "start": 220, "tag": "USERNAME", "value": "Yomguithereal" } ]
test/clj_fuzzy/jaro_winkler_test.clj
sooheon/clj-fuzzy
222
;; ------------------------------------------------------------------- ;; clj-fuzzy Jaro Winkler Distance Tests ;; ------------------------------------------------------------------- ;; ;; ;; Author: PLIQUE Guillaume (Yomguithereal) ;; Version: 0.1 ;; (ns clj-fuzzy.jaro-winkler-test (:require [clojure.test :refer :all] [clj-fuzzy.jaro-winkler :refer :all])) (deftest jaro-test (is (= 1.0 (jaro "Duane" "Duane"))) (is (= 0.8222222222222223 (jaro "Dwayne" "Duane"))) (is (= 0.9444444444444443 (jaro "Martha" "Marhta"))) (is (= 0.7666666666666666 (jaro "Dixon" "Dicksonx"))) (is (= 0.4166666666666667 (jaro "Duane" "Freakishlylongstring"))) (let [s1 "xxx1" s2 "y123"] (is (= (jaro s1 s2) (jaro s2 s1))))) (deftest jaro-winkler-test (is (= 1.0 (jaro "Duane" "Duane"))) (is (= 0.8400000000000001 (jaro-winkler "Dwayne" "Duane"))) (is (= 0.961111111111111 (jaro-winkler "Martha" "Marhta"))) (is (= 0.8133333333333332 (jaro-winkler "Dixon" "Dicksonx"))) (is (= 0.4166666666666667 (jaro-winkler "Duane" "Freakishlylongstring"))))
101020
;; ------------------------------------------------------------------- ;; clj-fuzzy Jaro Winkler Distance Tests ;; ------------------------------------------------------------------- ;; ;; ;; Author: <NAME> (Yomguithereal) ;; Version: 0.1 ;; (ns clj-fuzzy.jaro-winkler-test (:require [clojure.test :refer :all] [clj-fuzzy.jaro-winkler :refer :all])) (deftest jaro-test (is (= 1.0 (jaro "Duane" "Duane"))) (is (= 0.8222222222222223 (jaro "Dwayne" "Duane"))) (is (= 0.9444444444444443 (jaro "Martha" "Marhta"))) (is (= 0.7666666666666666 (jaro "Dixon" "Dicksonx"))) (is (= 0.4166666666666667 (jaro "Duane" "Freakishlylongstring"))) (let [s1 "xxx1" s2 "y123"] (is (= (jaro s1 s2) (jaro s2 s1))))) (deftest jaro-winkler-test (is (= 1.0 (jaro "Duane" "Duane"))) (is (= 0.8400000000000001 (jaro-winkler "Dwayne" "Duane"))) (is (= 0.961111111111111 (jaro-winkler "Martha" "Marhta"))) (is (= 0.8133333333333332 (jaro-winkler "Dixon" "Dicksonx"))) (is (= 0.4166666666666667 (jaro-winkler "Duane" "Freakishlylongstring"))))
true
;; ------------------------------------------------------------------- ;; clj-fuzzy Jaro Winkler Distance Tests ;; ------------------------------------------------------------------- ;; ;; ;; Author: PI:NAME:<NAME>END_PI (Yomguithereal) ;; Version: 0.1 ;; (ns clj-fuzzy.jaro-winkler-test (:require [clojure.test :refer :all] [clj-fuzzy.jaro-winkler :refer :all])) (deftest jaro-test (is (= 1.0 (jaro "Duane" "Duane"))) (is (= 0.8222222222222223 (jaro "Dwayne" "Duane"))) (is (= 0.9444444444444443 (jaro "Martha" "Marhta"))) (is (= 0.7666666666666666 (jaro "Dixon" "Dicksonx"))) (is (= 0.4166666666666667 (jaro "Duane" "Freakishlylongstring"))) (let [s1 "xxx1" s2 "y123"] (is (= (jaro s1 s2) (jaro s2 s1))))) (deftest jaro-winkler-test (is (= 1.0 (jaro "Duane" "Duane"))) (is (= 0.8400000000000001 (jaro-winkler "Dwayne" "Duane"))) (is (= 0.961111111111111 (jaro-winkler "Martha" "Marhta"))) (is (= 0.8133333333333332 (jaro-winkler "Dixon" "Dicksonx"))) (is (= 0.4166666666666667 (jaro-winkler "Duane" "Freakishlylongstring"))))
[ { "context": " EXERCISES =====\n\n\n(def hashmap1 (hash-map :name \"matija\" :age 23))\n(def hashset1 (hash-set \"lukovic\" \"luk", "end": 2529, "score": 0.9972648620605469, "start": 2523, "tag": "NAME", "value": "matija" } ]
fonclojure/src/com/matija/symettrizer.clj
matija94/show-me-the-code
1
(ns com.matija.symettrizer) (def asym-hobbit-body-parts [{:name "head" :size 3} {:name "left-eye" :size 1} {:name "left-ear" :size 1} {:name "mouth" :size 1} {:name "nose" :size 1} {:name "neck" :size 2} {:name "left-shoulder" :size 3} {:name "left-upper-arm" :size 3} {:name "chest" :size 10} {:name "back" :size 10} {:name "left-forearm" :size 3} {:name "abdomen" :size 6} {:name "left-kidney" :size 1} {:name "left-hand" :size 2} {:name "left-knee" :size 2} {:name "left-thigh" :size 4} {:name "left-lower-leg" :size 3} {:name "left-achilles" :size 1} {:name "left-foot" :size 2}]) (defn matching-part [part] {:name (clojure.string/replace (:name part) #"^left-" "right-") :size (:size part)}) (defn symmetrize-body-parts "Expects a seq of maps that have a :name and :size" [asym-body-parts] (loop [remaining-asym-parts asym-body-parts final-body-parts []] (if (empty? remaining-asym-parts) final-body-parts (let [[part & remaining] remaining-asym-parts] (recur remaining (into final-body-parts (set [part (matching-part part)]))))))) (defn symmetrize-body-parts-reduce-distinct "Expects a seq of maps that have a :name and :size" [asym-body-parts] (reduce (fn [final-body-parts part] (into final-body-parts (set [part (matching-part part)]))) [] asym-body-parts)) (defn hit "Pick body part randomly. The bigger the part is the bigger chance is for it being hit" [asym-body-parts] (let [sym-parts (symmetrize-body-parts-reduce-distinct asym-body-parts) body-part-size-sum (reduce + (map :size sym-parts)) target (rand body-part-size-sum)] (loop [[part & remaining] sym-parts accumulated-size (:size part)] (if (> accumulated-size target) part (recur remaining (+ accumulated-size (:size (first remaining)))))))) (def hits (hit asym-hobbit-body-parts)) ; ===== EXERCISES ===== (def hashmap1 (hash-map :name "matija" :age 23)) (def hashset1 (hash-set "lukovic" "lukovic")) (def mylist(list 1 1 2 3 4)) (defn decmaker [num] (fn [num1] (- num1 num))) (defn mapset "Works likes a map but returning set instead of list" [f coll] (set (map f coll))) (defn mapset-loop [f coll] (loop [remaining coll res #{}] (if (empty? remaining) res (let [[head & tail] remaining] (recur tail (conj res (f head))))))) (defn make-alien-body-part "Make 5 parts of each if part == (eye | arm | leg)" ([n res part] (if (re-matches #".*(eye|arm|leg)" (:name part)) (into res (repeat n part)) (conj res part))) ([res part] (make-alien-body-part 5 res part))) (defn alien-symmetrize-body-parts "Symmetrize body parts such that there are five eyes, arms and legs" [body-parts] (reduce make-alien-body-part [] body-parts)) (println hits) (println (alien-symmetrize-body-parts asym-hobbit-body-parts)) (println (map inc mylist)) (println (mapset inc mylist)) (println (mapset-loop inc mylist)) (println (fn [x] x)) (def v (vector 1 2 3)) (def z (update v 1 #(+ 1 %))) (println z) (def s #{1 3 5}) (println (contains? s 1))
109478
(ns com.matija.symettrizer) (def asym-hobbit-body-parts [{:name "head" :size 3} {:name "left-eye" :size 1} {:name "left-ear" :size 1} {:name "mouth" :size 1} {:name "nose" :size 1} {:name "neck" :size 2} {:name "left-shoulder" :size 3} {:name "left-upper-arm" :size 3} {:name "chest" :size 10} {:name "back" :size 10} {:name "left-forearm" :size 3} {:name "abdomen" :size 6} {:name "left-kidney" :size 1} {:name "left-hand" :size 2} {:name "left-knee" :size 2} {:name "left-thigh" :size 4} {:name "left-lower-leg" :size 3} {:name "left-achilles" :size 1} {:name "left-foot" :size 2}]) (defn matching-part [part] {:name (clojure.string/replace (:name part) #"^left-" "right-") :size (:size part)}) (defn symmetrize-body-parts "Expects a seq of maps that have a :name and :size" [asym-body-parts] (loop [remaining-asym-parts asym-body-parts final-body-parts []] (if (empty? remaining-asym-parts) final-body-parts (let [[part & remaining] remaining-asym-parts] (recur remaining (into final-body-parts (set [part (matching-part part)]))))))) (defn symmetrize-body-parts-reduce-distinct "Expects a seq of maps that have a :name and :size" [asym-body-parts] (reduce (fn [final-body-parts part] (into final-body-parts (set [part (matching-part part)]))) [] asym-body-parts)) (defn hit "Pick body part randomly. The bigger the part is the bigger chance is for it being hit" [asym-body-parts] (let [sym-parts (symmetrize-body-parts-reduce-distinct asym-body-parts) body-part-size-sum (reduce + (map :size sym-parts)) target (rand body-part-size-sum)] (loop [[part & remaining] sym-parts accumulated-size (:size part)] (if (> accumulated-size target) part (recur remaining (+ accumulated-size (:size (first remaining)))))))) (def hits (hit asym-hobbit-body-parts)) ; ===== EXERCISES ===== (def hashmap1 (hash-map :name "<NAME>" :age 23)) (def hashset1 (hash-set "lukovic" "lukovic")) (def mylist(list 1 1 2 3 4)) (defn decmaker [num] (fn [num1] (- num1 num))) (defn mapset "Works likes a map but returning set instead of list" [f coll] (set (map f coll))) (defn mapset-loop [f coll] (loop [remaining coll res #{}] (if (empty? remaining) res (let [[head & tail] remaining] (recur tail (conj res (f head))))))) (defn make-alien-body-part "Make 5 parts of each if part == (eye | arm | leg)" ([n res part] (if (re-matches #".*(eye|arm|leg)" (:name part)) (into res (repeat n part)) (conj res part))) ([res part] (make-alien-body-part 5 res part))) (defn alien-symmetrize-body-parts "Symmetrize body parts such that there are five eyes, arms and legs" [body-parts] (reduce make-alien-body-part [] body-parts)) (println hits) (println (alien-symmetrize-body-parts asym-hobbit-body-parts)) (println (map inc mylist)) (println (mapset inc mylist)) (println (mapset-loop inc mylist)) (println (fn [x] x)) (def v (vector 1 2 3)) (def z (update v 1 #(+ 1 %))) (println z) (def s #{1 3 5}) (println (contains? s 1))
true
(ns com.matija.symettrizer) (def asym-hobbit-body-parts [{:name "head" :size 3} {:name "left-eye" :size 1} {:name "left-ear" :size 1} {:name "mouth" :size 1} {:name "nose" :size 1} {:name "neck" :size 2} {:name "left-shoulder" :size 3} {:name "left-upper-arm" :size 3} {:name "chest" :size 10} {:name "back" :size 10} {:name "left-forearm" :size 3} {:name "abdomen" :size 6} {:name "left-kidney" :size 1} {:name "left-hand" :size 2} {:name "left-knee" :size 2} {:name "left-thigh" :size 4} {:name "left-lower-leg" :size 3} {:name "left-achilles" :size 1} {:name "left-foot" :size 2}]) (defn matching-part [part] {:name (clojure.string/replace (:name part) #"^left-" "right-") :size (:size part)}) (defn symmetrize-body-parts "Expects a seq of maps that have a :name and :size" [asym-body-parts] (loop [remaining-asym-parts asym-body-parts final-body-parts []] (if (empty? remaining-asym-parts) final-body-parts (let [[part & remaining] remaining-asym-parts] (recur remaining (into final-body-parts (set [part (matching-part part)]))))))) (defn symmetrize-body-parts-reduce-distinct "Expects a seq of maps that have a :name and :size" [asym-body-parts] (reduce (fn [final-body-parts part] (into final-body-parts (set [part (matching-part part)]))) [] asym-body-parts)) (defn hit "Pick body part randomly. The bigger the part is the bigger chance is for it being hit" [asym-body-parts] (let [sym-parts (symmetrize-body-parts-reduce-distinct asym-body-parts) body-part-size-sum (reduce + (map :size sym-parts)) target (rand body-part-size-sum)] (loop [[part & remaining] sym-parts accumulated-size (:size part)] (if (> accumulated-size target) part (recur remaining (+ accumulated-size (:size (first remaining)))))))) (def hits (hit asym-hobbit-body-parts)) ; ===== EXERCISES ===== (def hashmap1 (hash-map :name "PI:NAME:<NAME>END_PI" :age 23)) (def hashset1 (hash-set "lukovic" "lukovic")) (def mylist(list 1 1 2 3 4)) (defn decmaker [num] (fn [num1] (- num1 num))) (defn mapset "Works likes a map but returning set instead of list" [f coll] (set (map f coll))) (defn mapset-loop [f coll] (loop [remaining coll res #{}] (if (empty? remaining) res (let [[head & tail] remaining] (recur tail (conj res (f head))))))) (defn make-alien-body-part "Make 5 parts of each if part == (eye | arm | leg)" ([n res part] (if (re-matches #".*(eye|arm|leg)" (:name part)) (into res (repeat n part)) (conj res part))) ([res part] (make-alien-body-part 5 res part))) (defn alien-symmetrize-body-parts "Symmetrize body parts such that there are five eyes, arms and legs" [body-parts] (reduce make-alien-body-part [] body-parts)) (println hits) (println (alien-symmetrize-body-parts asym-hobbit-body-parts)) (println (map inc mylist)) (println (mapset inc mylist)) (println (mapset-loop inc mylist)) (println (fn [x] x)) (def v (vector 1 2 3)) (def z (update v 1 #(+ 1 %))) (println z) (def s #{1 3 5}) (println (contains? s 1))
[ { "context": "ceb1\")\n\n(def sample-group\n {\"mbox\" \"mailto:sample.group@example.com\"\n \"name\" \"Sample Group\"\n \"objectType\" \"", "end": 254, "score": 0.9999173283576965, "start": 230, "tag": "EMAIL", "value": "sample.group@example.com" }, { "context": "ectType\" \"Group\"\n \"member\" [{\"mbox\" \"mailto:agent2@example.com\"\n \"name\" \"Agent 2\"}\n ", "end": 362, "score": 0.9999163746833801, "start": 344, "tag": "EMAIL", "value": "agent2@example.com" }, { "context": "name\" \"Agent 2\"}\n {\"mbox\" \"mailto:agent2@example.com\"\n \"name\" \"Agent 2\"}\n ", "end": 451, "score": 0.9999144673347473, "start": 433, "tag": "EMAIL", "value": "agent2@example.com" }, { "context": "name\" \"Agent 2\"}\n {\"mbox\" \"mailto:agent1@example.com\"\n \"name\" \"Agent 1\"}]})\n\n(def sam", "end": 540, "score": 0.9999000430107117, "start": 522, "tag": "EMAIL", "value": "agent1@example.com" }, { "context": "\n(def sample-group-dissoc\n {\"mbox\" \"mailto:sample.group@example.com\"\n \"name\" \"Sample Group\"\n \"objectType\" \"", "end": 655, "score": 0.999886691570282, "start": 631, "tag": "EMAIL", "value": "sample.group@example.com" }, { "context": "ectType\" \"Group\"\n \"member\" [{\"mbox\" \"mailto:agent2@example.com\"\n \"name\" \"Agent 2\"}\n ", "end": 763, "score": 0.999910831451416, "start": 745, "tag": "EMAIL", "value": "agent2@example.com" }, { "context": "name\" \"Agent 2\"}\n {\"mbox\" \"mailto:agent1@example.com\"\n \"name\" \"Agent 1\"}]})\n\n(def sam", "end": 852, "score": 0.9998867511749268, "start": 834, "tag": "EMAIL", "value": "agent1@example.com" } ]
src/test/lrsql/util/statement_test.clj
ccasey3/lrsql
28
(ns lrsql.util.statement-test (:require [clojure.test :refer [deftest testing is]] [lrsql.util.statement :as su])) (def sample-id "030e001f-b32a-4361-b701-039a3d9fceb1") (def sample-group {"mbox" "mailto:sample.group@example.com" "name" "Sample Group" "objectType" "Group" "member" [{"mbox" "mailto:agent2@example.com" "name" "Agent 2"} {"mbox" "mailto:agent2@example.com" "name" "Agent 2"} {"mbox" "mailto:agent1@example.com" "name" "Agent 1"}]}) (def sample-group-dissoc {"mbox" "mailto:sample.group@example.com" "name" "Sample Group" "objectType" "Group" "member" [{"mbox" "mailto:agent2@example.com" "name" "Agent 2"} {"mbox" "mailto:agent1@example.com" "name" "Agent 1"}]}) (def sample-verb {"id" "http://adlnet.gov/expapi/verbs/answered" "display" {"en-US" "answered"}}) (def sample-verb-dissoc {"id" "http://adlnet.gov/expapi/verbs/answered"}) (def sample-activity {"id" "http://www.example.com/tincan/activities/multipart" "objectType" "Activity" "definition" {"name" {"en-US" "Multi Part Activity"} "description" {"en-US" "Multi Part Activity Description"}}}) (def sample-activity-dissoc {"id" "http://www.example.com/tincan/activities/multipart" "objectType" "Activity"}) (deftest statements-equal-test (testing "statement equality" (is (su/statement-equal? {"id" sample-id "actor" sample-group-dissoc "verb" sample-verb-dissoc "object" sample-activity-dissoc "context" {"instructor" sample-group-dissoc "team" sample-group-dissoc "contextActivities" {"category" [sample-activity-dissoc] "parent" [sample-activity-dissoc] "grouping" [sample-activity-dissoc] "other" [sample-activity-dissoc]}}} {"id" sample-id "actor" sample-group "verb" sample-verb "object" sample-activity "context" {"instructor" sample-group "team" sample-group "contextActivities" {"category" [sample-activity] "parent" [sample-activity] "grouping" [sample-activity] "other" [sample-activity]}}})) (is (su/statement-equal? {"id" sample-id "actor" sample-group "verb" sample-verb "object" sample-activity "context" {"instructor" sample-group "team" sample-group "contextActivities" {"category" [sample-activity] "parent" [sample-activity] "grouping" [sample-activity] "other" [sample-activity]}}} {"id" sample-id "actor" sample-group "verb" sample-verb "object" sample-activity "context" {"instructor" sample-group "team" sample-group "contextActivities" {"category" [sample-activity sample-activity] "parent" [sample-activity sample-activity] "grouping" [sample-activity sample-activity] "other" [sample-activity sample-activity]}}})) (testing "(with SubStatement)" (is (su/statement-equal? {"id" sample-id "actor" sample-group-dissoc "verb" sample-verb-dissoc "object" {"objectType" "SubStatement" "actor" sample-group-dissoc "verb" sample-verb-dissoc "object" sample-activity-dissoc "context" {"instructor" sample-group-dissoc "team" sample-group-dissoc "contextActivities" {"category" [sample-activity-dissoc] "parent" [sample-activity-dissoc] "grouping" [sample-activity-dissoc] "other" [sample-activity-dissoc]}}}} {"id" sample-id "actor" sample-group "verb" sample-verb "object" {"objectType" "SubStatement" "actor" sample-group "verb" sample-verb "object" sample-activity "context" {"instructor" sample-group "team" sample-group "contextActivities" {"category" [sample-activity sample-activity] "parent" [sample-activity sample-activity] "grouping" [sample-activity sample-activity] "other" [sample-activity sample-activity]}}}})) (is (su/statement-equal? {"id" sample-id "actor" sample-group "verb" sample-verb "object" {"objectType" "SubStatement" "actor" sample-group "verb" sample-verb "object" sample-activity "context" {"instructor" sample-group "team" sample-group "contextActivities" {"category" [sample-activity] "parent" [sample-activity] "grouping" [sample-activity] "other" [sample-activity]}}}} {"id" sample-id "actor" sample-group "verb" sample-verb "object" {"objectType" "SubStatement" "actor" sample-group "verb" sample-verb "object" sample-activity "context" {"instructor" sample-group "team" sample-group "contextActivities" {"category" [sample-activity sample-activity] "parent" [sample-activity sample-activity] "grouping" [sample-activity sample-activity] "other" [sample-activity sample-activity]}}}})))))
4883
(ns lrsql.util.statement-test (:require [clojure.test :refer [deftest testing is]] [lrsql.util.statement :as su])) (def sample-id "030e001f-b32a-4361-b701-039a3d9fceb1") (def sample-group {"mbox" "mailto:<EMAIL>" "name" "Sample Group" "objectType" "Group" "member" [{"mbox" "mailto:<EMAIL>" "name" "Agent 2"} {"mbox" "mailto:<EMAIL>" "name" "Agent 2"} {"mbox" "mailto:<EMAIL>" "name" "Agent 1"}]}) (def sample-group-dissoc {"mbox" "mailto:<EMAIL>" "name" "Sample Group" "objectType" "Group" "member" [{"mbox" "mailto:<EMAIL>" "name" "Agent 2"} {"mbox" "mailto:<EMAIL>" "name" "Agent 1"}]}) (def sample-verb {"id" "http://adlnet.gov/expapi/verbs/answered" "display" {"en-US" "answered"}}) (def sample-verb-dissoc {"id" "http://adlnet.gov/expapi/verbs/answered"}) (def sample-activity {"id" "http://www.example.com/tincan/activities/multipart" "objectType" "Activity" "definition" {"name" {"en-US" "Multi Part Activity"} "description" {"en-US" "Multi Part Activity Description"}}}) (def sample-activity-dissoc {"id" "http://www.example.com/tincan/activities/multipart" "objectType" "Activity"}) (deftest statements-equal-test (testing "statement equality" (is (su/statement-equal? {"id" sample-id "actor" sample-group-dissoc "verb" sample-verb-dissoc "object" sample-activity-dissoc "context" {"instructor" sample-group-dissoc "team" sample-group-dissoc "contextActivities" {"category" [sample-activity-dissoc] "parent" [sample-activity-dissoc] "grouping" [sample-activity-dissoc] "other" [sample-activity-dissoc]}}} {"id" sample-id "actor" sample-group "verb" sample-verb "object" sample-activity "context" {"instructor" sample-group "team" sample-group "contextActivities" {"category" [sample-activity] "parent" [sample-activity] "grouping" [sample-activity] "other" [sample-activity]}}})) (is (su/statement-equal? {"id" sample-id "actor" sample-group "verb" sample-verb "object" sample-activity "context" {"instructor" sample-group "team" sample-group "contextActivities" {"category" [sample-activity] "parent" [sample-activity] "grouping" [sample-activity] "other" [sample-activity]}}} {"id" sample-id "actor" sample-group "verb" sample-verb "object" sample-activity "context" {"instructor" sample-group "team" sample-group "contextActivities" {"category" [sample-activity sample-activity] "parent" [sample-activity sample-activity] "grouping" [sample-activity sample-activity] "other" [sample-activity sample-activity]}}})) (testing "(with SubStatement)" (is (su/statement-equal? {"id" sample-id "actor" sample-group-dissoc "verb" sample-verb-dissoc "object" {"objectType" "SubStatement" "actor" sample-group-dissoc "verb" sample-verb-dissoc "object" sample-activity-dissoc "context" {"instructor" sample-group-dissoc "team" sample-group-dissoc "contextActivities" {"category" [sample-activity-dissoc] "parent" [sample-activity-dissoc] "grouping" [sample-activity-dissoc] "other" [sample-activity-dissoc]}}}} {"id" sample-id "actor" sample-group "verb" sample-verb "object" {"objectType" "SubStatement" "actor" sample-group "verb" sample-verb "object" sample-activity "context" {"instructor" sample-group "team" sample-group "contextActivities" {"category" [sample-activity sample-activity] "parent" [sample-activity sample-activity] "grouping" [sample-activity sample-activity] "other" [sample-activity sample-activity]}}}})) (is (su/statement-equal? {"id" sample-id "actor" sample-group "verb" sample-verb "object" {"objectType" "SubStatement" "actor" sample-group "verb" sample-verb "object" sample-activity "context" {"instructor" sample-group "team" sample-group "contextActivities" {"category" [sample-activity] "parent" [sample-activity] "grouping" [sample-activity] "other" [sample-activity]}}}} {"id" sample-id "actor" sample-group "verb" sample-verb "object" {"objectType" "SubStatement" "actor" sample-group "verb" sample-verb "object" sample-activity "context" {"instructor" sample-group "team" sample-group "contextActivities" {"category" [sample-activity sample-activity] "parent" [sample-activity sample-activity] "grouping" [sample-activity sample-activity] "other" [sample-activity sample-activity]}}}})))))
true
(ns lrsql.util.statement-test (:require [clojure.test :refer [deftest testing is]] [lrsql.util.statement :as su])) (def sample-id "030e001f-b32a-4361-b701-039a3d9fceb1") (def sample-group {"mbox" "mailto:PI:EMAIL:<EMAIL>END_PI" "name" "Sample Group" "objectType" "Group" "member" [{"mbox" "mailto:PI:EMAIL:<EMAIL>END_PI" "name" "Agent 2"} {"mbox" "mailto:PI:EMAIL:<EMAIL>END_PI" "name" "Agent 2"} {"mbox" "mailto:PI:EMAIL:<EMAIL>END_PI" "name" "Agent 1"}]}) (def sample-group-dissoc {"mbox" "mailto:PI:EMAIL:<EMAIL>END_PI" "name" "Sample Group" "objectType" "Group" "member" [{"mbox" "mailto:PI:EMAIL:<EMAIL>END_PI" "name" "Agent 2"} {"mbox" "mailto:PI:EMAIL:<EMAIL>END_PI" "name" "Agent 1"}]}) (def sample-verb {"id" "http://adlnet.gov/expapi/verbs/answered" "display" {"en-US" "answered"}}) (def sample-verb-dissoc {"id" "http://adlnet.gov/expapi/verbs/answered"}) (def sample-activity {"id" "http://www.example.com/tincan/activities/multipart" "objectType" "Activity" "definition" {"name" {"en-US" "Multi Part Activity"} "description" {"en-US" "Multi Part Activity Description"}}}) (def sample-activity-dissoc {"id" "http://www.example.com/tincan/activities/multipart" "objectType" "Activity"}) (deftest statements-equal-test (testing "statement equality" (is (su/statement-equal? {"id" sample-id "actor" sample-group-dissoc "verb" sample-verb-dissoc "object" sample-activity-dissoc "context" {"instructor" sample-group-dissoc "team" sample-group-dissoc "contextActivities" {"category" [sample-activity-dissoc] "parent" [sample-activity-dissoc] "grouping" [sample-activity-dissoc] "other" [sample-activity-dissoc]}}} {"id" sample-id "actor" sample-group "verb" sample-verb "object" sample-activity "context" {"instructor" sample-group "team" sample-group "contextActivities" {"category" [sample-activity] "parent" [sample-activity] "grouping" [sample-activity] "other" [sample-activity]}}})) (is (su/statement-equal? {"id" sample-id "actor" sample-group "verb" sample-verb "object" sample-activity "context" {"instructor" sample-group "team" sample-group "contextActivities" {"category" [sample-activity] "parent" [sample-activity] "grouping" [sample-activity] "other" [sample-activity]}}} {"id" sample-id "actor" sample-group "verb" sample-verb "object" sample-activity "context" {"instructor" sample-group "team" sample-group "contextActivities" {"category" [sample-activity sample-activity] "parent" [sample-activity sample-activity] "grouping" [sample-activity sample-activity] "other" [sample-activity sample-activity]}}})) (testing "(with SubStatement)" (is (su/statement-equal? {"id" sample-id "actor" sample-group-dissoc "verb" sample-verb-dissoc "object" {"objectType" "SubStatement" "actor" sample-group-dissoc "verb" sample-verb-dissoc "object" sample-activity-dissoc "context" {"instructor" sample-group-dissoc "team" sample-group-dissoc "contextActivities" {"category" [sample-activity-dissoc] "parent" [sample-activity-dissoc] "grouping" [sample-activity-dissoc] "other" [sample-activity-dissoc]}}}} {"id" sample-id "actor" sample-group "verb" sample-verb "object" {"objectType" "SubStatement" "actor" sample-group "verb" sample-verb "object" sample-activity "context" {"instructor" sample-group "team" sample-group "contextActivities" {"category" [sample-activity sample-activity] "parent" [sample-activity sample-activity] "grouping" [sample-activity sample-activity] "other" [sample-activity sample-activity]}}}})) (is (su/statement-equal? {"id" sample-id "actor" sample-group "verb" sample-verb "object" {"objectType" "SubStatement" "actor" sample-group "verb" sample-verb "object" sample-activity "context" {"instructor" sample-group "team" sample-group "contextActivities" {"category" [sample-activity] "parent" [sample-activity] "grouping" [sample-activity] "other" [sample-activity]}}}} {"id" sample-id "actor" sample-group "verb" sample-verb "object" {"objectType" "SubStatement" "actor" sample-group "verb" sample-verb "object" sample-activity "context" {"instructor" sample-group "team" sample-group "contextActivities" {"category" [sample-activity sample-activity] "parent" [sample-activity sample-activity] "grouping" [sample-activity sample-activity] "other" [sample-activity sample-activity]}}}})))))
[ { "context": "\")\n (h/div\n (h/a\n :href \"https://github.com/thedavidmeister/boot-github-pages\"\n \"Deployed to Github Pages ", "end": 215, "score": 0.998136579990387, "start": 200, "tag": "USERNAME", "value": "thedavidmeister" }, { "context": "-github-pages\"\n \"Deployed to Github Pages using David Meister's Github Pages Boot task!\"))\n (h/div\n (str \"Bu", "end": 284, "score": 0.9971795082092285, "start": 271, "tag": "NAME", "value": "David Meister" } ]
hoplon-demo/pages/index.cljs
thedavidmeister/boot-github-pages
0
(ns ^{:hoplon/page "index.html"} pages.index (:require [hoplon.core :as h])) (goog-define build-id "") (h/html (h/body (h/div "Hello world!") (h/div (h/a :href "https://github.com/thedavidmeister/boot-github-pages" "Deployed to Github Pages using David Meister's Github Pages Boot task!")) (h/div (str "Build id: " build-id))))
48185
(ns ^{:hoplon/page "index.html"} pages.index (:require [hoplon.core :as h])) (goog-define build-id "") (h/html (h/body (h/div "Hello world!") (h/div (h/a :href "https://github.com/thedavidmeister/boot-github-pages" "Deployed to Github Pages using <NAME>'s Github Pages Boot task!")) (h/div (str "Build id: " build-id))))
true
(ns ^{:hoplon/page "index.html"} pages.index (:require [hoplon.core :as h])) (goog-define build-id "") (h/html (h/body (h/div "Hello world!") (h/div (h/a :href "https://github.com/thedavidmeister/boot-github-pages" "Deployed to Github Pages using PI:NAME:<NAME>END_PI's Github Pages Boot task!")) (h/div (str "Build id: " build-id))))
[ { "context": "d on clojure-control.\"\n :url \"https://github.com/killme2008/clj.monitor\"\n :author \"dennis zhuang(killme2008@", "end": 152, "score": 0.9992356300354004, "start": 142, "tag": "USERNAME", "value": "killme2008" }, { "context": "s://github.com/killme2008/clj.monitor\"\n :author \"dennis zhuang(killme2008@gmail.com)\"\n :dependencies [[org.cloj", "end": 190, "score": 0.9998518228530884, "start": 177, "tag": "NAME", "value": "dennis zhuang" }, { "context": "/killme2008/clj.monitor\"\n :author \"dennis zhuang(killme2008@gmail.com)\"\n :dependencies [[org.clojure/clojure \"1.3.0\"]\n", "end": 211, "score": 0.9999284744262695, "start": 191, "tag": "EMAIL", "value": "killme2008@gmail.com" } ]
project.clj
killme2008/clj.monitor
3
(defproject clj.monitor "1.0.0-beta" :description "Monitoring applications in clojure based on clojure-control." :url "https://github.com/killme2008/clj.monitor" :author "dennis zhuang(killme2008@gmail.com)" :dependencies [[org.clojure/clojure "1.3.0"] [control "0.3.8"] [com.draines/postal "1.6.0"] [org.quartz-scheduler/quartz "2.1.4"] [org.clojure/tools.logging "0.2.3"] [clj-redis "0.0.12"]] :dev-dependencies [[log4j/log4j "1.2.16"] [lein-autodoc "0.9.0"] [org.slf4j/slf4j-log4j12 "1.5.6"]] :profiles {:dev {:resources-path ["dev"]}})
37269
(defproject clj.monitor "1.0.0-beta" :description "Monitoring applications in clojure based on clojure-control." :url "https://github.com/killme2008/clj.monitor" :author "<NAME>(<EMAIL>)" :dependencies [[org.clojure/clojure "1.3.0"] [control "0.3.8"] [com.draines/postal "1.6.0"] [org.quartz-scheduler/quartz "2.1.4"] [org.clojure/tools.logging "0.2.3"] [clj-redis "0.0.12"]] :dev-dependencies [[log4j/log4j "1.2.16"] [lein-autodoc "0.9.0"] [org.slf4j/slf4j-log4j12 "1.5.6"]] :profiles {:dev {:resources-path ["dev"]}})
true
(defproject clj.monitor "1.0.0-beta" :description "Monitoring applications in clojure based on clojure-control." :url "https://github.com/killme2008/clj.monitor" :author "PI:NAME:<NAME>END_PI(PI:EMAIL:<EMAIL>END_PI)" :dependencies [[org.clojure/clojure "1.3.0"] [control "0.3.8"] [com.draines/postal "1.6.0"] [org.quartz-scheduler/quartz "2.1.4"] [org.clojure/tools.logging "0.2.3"] [clj-redis "0.0.12"]] :dev-dependencies [[log4j/log4j "1.2.16"] [lein-autodoc "0.9.0"] [org.slf4j/slf4j-log4j12 "1.5.6"]] :profiles {:dev {:resources-path ["dev"]}})
[ { "context": "))\n\n(def MrBill { :profile_id \"299277\" :username \"qa@artstor.org\" :institution_ids [\"1000\"] })\n(def Will { :profil", "end": 750, "score": 0.9999313354492188, "start": 736, "tag": "EMAIL", "value": "qa@artstor.org" }, { "context": "titution_ids [\"1000\"] })\n(def Will { :profile_id \"Will\" :username \"will@artstor.org\" :institution_ids [\"", "end": 810, "score": 0.9706740379333496, "start": 806, "tag": "NAME", "value": "Will" }, { "context": "00\"] })\n(def Will { :profile_id \"Will\" :username \"will@artstor.org\" :institution_ids [\"2000\"] })\n(def Professor { :p", "end": 839, "score": 0.9999292492866516, "start": 823, "tag": "EMAIL", "value": "will@artstor.org" }, { "context": "\n(def Professor { :profile_id \"123456\" :username \"prof@artstor.org\" :institution_ids [\"10001\"] })\n(def BadDog { :pro", "end": 935, "score": 0.9999303221702576, "start": 919, "tag": "EMAIL", "value": "prof@artstor.org" }, { "context": " })\n(def BadDog { :profile_id \"111111\" :username \"woof@artstor.org\" :institution_ids [\"1234567\"] })\n\n\n\n\n\n(deftest au", "end": 1029, "score": 0.9999289512634277, "start": 1013, "tag": "EMAIL", "value": "woof@artstor.org" }, { "context": "ith-db config\n (testing \"Performing can MrBill write authorization test\"\n (let [canDo ", "end": 1729, "score": 0.6402263641357422, "start": 1725, "tag": "NAME", "value": "Bill" }, { "context": "\n (let [canDo (auth/user-action-allowed? MrBill :write 123)]\n (println \"Does MrBill k", "end": 1812, "score": 0.6563673615455627, "start": 1806, "tag": "NAME", "value": "MrBill" }, { "context": "MrBill :write 123)]\n (println \"Does MrBill know how to write==\" canDo)\n (is canD", "end": 1860, "score": 0.6543192863464355, "start": 1856, "tag": "NAME", "value": "Bill" }, { "context": " (let [canDo (auth/user-action-allowed? MrBill :admin 123)]\n (println \"Does MrBill", "end": 2076, "score": 0.46710553765296936, "start": 2072, "tag": "NAME", "value": "Bill" }, { "context": " :access [{:entity_type 100 :entity_identifier \"Will\" :access_type 200},{:entity_type 100 :entity_iden", "end": 4437, "score": 0.892280638217926, "start": 4433, "tag": "NAME", "value": "Will" }, { "context": "config\n (testing \"Performing can Admin (MrBill) update access object authorization test\"\n ", "end": 4698, "score": 0.8379502892494202, "start": 4696, "tag": "NAME", "value": "Mr" }, { "context": "nfig\n (testing \"Performing can Admin (MrBill) update access object authorization test\"\n ", "end": 4702, "score": 0.6315783858299255, "start": 4698, "tag": "NAME", "value": "Bill" }, { "context": " (let [canDo (auth/can-change-group-access? MrBill 123)]\n (println \"Is MrBill allowed ", "end": 4807, "score": 0.46878546476364136, "start": 4803, "tag": "NAME", "value": "Bill" }, { "context": "p-access? MrBill 123)]\n (println \"Is MrBill allowed to update==\" canDo)\n (i", "end": 4844, "score": 0.6706874370574951, "start": 4842, "tag": "NAME", "value": "Mr" }, { "context": "ccess? MrBill 123)]\n (println \"Is MrBill allowed to update==\" canDo)\n (is ca", "end": 4848, "score": 0.48807501792907715, "start": 4844, "tag": "NAME", "value": "Bill" }, { "context": "g\n (testing \"Performing can Write only (Will) update access object authorization test\"\n ", "end": 4977, "score": 0.9222232103347778, "start": 4973, "tag": "NAME", "value": "Will" }, { "context": " (let [canDo (auth/can-change-group-access? Will 123)]\n (println \"Is Will allowed to", "end": 5080, "score": 0.5145515203475952, "start": 5076, "tag": "NAME", "value": "Will" }, { "context": "oup-access? Will 123)]\n (println \"Is Will allowed to update when he should not==\" canDo)\n ", "end": 5119, "score": 0.8492733836174011, "start": 5115, "tag": "NAME", "value": "Will" }, { "context": "ound-group-access Will)]\n (println \"Will's filtered group==\" filtered-group)\n ", "end": 5504, "score": 0.6430003046989441, "start": 5500, "tag": "NAME", "value": "Will" }, { "context": " :access) [{:access_type 200, :entity_identifier \"Will\", :entity_type 100}])))))\n\n (with-db config\n ", "end": 5632, "score": 0.9424440860748291, "start": 5628, "tag": "NAME", "value": "Will" }, { "context": "ith-db config\n (testing \"Performing does MrBill's Admin access object have Everything in it\"\n ", "end": 5721, "score": 0.9782363772392273, "start": 5715, "tag": "NAME", "value": "MrBill" }, { "context": "erce-group-based-on-access-type found-group-access MrBill)]\n (println \"MrBill's filtered grou", "end": 5932, "score": 0.7692590951919556, "start": 5926, "tag": "NAME", "value": "MrBill" }, { "context": "nd-group-access MrBill)]\n (println \"MrBill's filtered group==\" filtered-group)\n ", "end": 5966, "score": 0.9655553102493286, "start": 5960, "tag": "NAME", "value": "MrBill" }, { "context": " {:access_type 100, :entity_identifier \"Sai\", :entity_type 100}\n ", "end": 6207, "score": 0.9970821738243103, "start": 6204, "tag": "NAME", "value": "Sai" }, { "context": " {:access_type 200, :entity_identifier \"Will\", :entity_type 100}\n ", "end": 6319, "score": 0.9996422529220581, "start": 6315, "tag": "NAME", "value": "Will" }, { "context": " {:access_type 300, :entity_identifier \"Artstor\", :entity_type 200}])))))\n\n (with-db config\n ", "end": 6547, "score": 0.9988880157470703, "start": 6540, "tag": "NAME", "value": "Artstor" } ]
test/artstor_group_service/auth_test.clj
ithaka/artstor-group-service-os
0
(ns artstor-group-service.auth-test (:require [clojure.test :refer :all] [artstor-group-service.auth :as auth] [artstor-group-service.repository :as repo] [ragtime.jdbc :as jdbc] [ragtime.repl :refer [migrate rollback]] [environ.core :refer [env]] [schema.core :as s] [artstor-group-service.user :as user])) (def config {:datastore (jdbc/sql-database {:connection-uri (env :artstor-group-db-url)}) :migrations (jdbc/load-resources "test-migrations")}) (defmacro with-db [conf & body] `(do (migrate ~conf) (try ~@body (finally (rollback ~conf "001"))))) (def MrBill { :profile_id "299277" :username "qa@artstor.org" :institution_ids ["1000"] }) (def Will { :profile_id "Will" :username "will@artstor.org" :institution_ids ["2000"] }) (def Professor { :profile_id "123456" :username "prof@artstor.org" :institution_ids ["10001"] }) (def BadDog { :profile_id "111111" :username "woof@artstor.org" :institution_ids ["1234567"] }) (deftest authorization-test (with-db config (testing "Performing can MrBill read authorization test" (let [canRead (auth/user-action-allowed? MrBill :read 123)] (println "Does MrBill know how to read==" canRead) (is canRead) ))) (with-db config (testing "Performing can MrBill read his own Public Group test" (let [canRead (auth/user-action-allowed? MrBill :read 294484)] (println "Does MrBill know how to read his own public group==" canRead) (is canRead) ))) (with-db config (testing "Performing can MrBill write authorization test" (let [canDo (auth/user-action-allowed? MrBill :write 123)] (println "Does MrBill know how to write==" canDo) (is canDo) ))) (with-db config (testing "Performing can MrBill delete authorization test" (let [canDo (auth/user-action-allowed? MrBill :admin 123)] (println "Does MrBill know how to delete==" canDo) (is canDo) ))) (with-db config (testing "Performing can Professor write authorization test" (let [canDo (auth/user-action-allowed? Professor :write 123)] (println "Is Professor allowed to write==" canDo) (is (false? canDo)) ))) (with-db config (testing "Performing can Professor read group shared at institution level" (let [canDo (auth/user-action-allowed? Professor :read 123)] (println "Is Professor allowed to read group123==" canDo) (is canDo) ))) (with-db config (testing "Performing can Professor read MrBill's Public Group test" (let [canRead (auth/user-action-allowed? Professor :read 294484)] (println "Does Professor know how to read MrBill's public group==" canRead) (is canRead) ))) (with-db config (testing "Performing can Professor can delete authorization test" (let [canDo (auth/user-action-allowed? Professor :write 123)] (println "Is Professor allowed to delete==" canDo) (is (false? canDo)) ))) (with-db config (testing "Performing can BadDog write authorization test" (let [canDo (auth/user-action-allowed? BadDog :write 123)] (println "Is BadDog allowed to write==" canDo) (is (false? canDo)) ))) (with-db config (testing "Performing can BadDog read authorization test" (let [canDo (auth/user-action-allowed? BadDog :read 123)] (println "Is BadDog allowed to read group123==" canDo) (is (false? canDo)) ))) (with-db config (testing "Performing can BadDog can delete authorization test" (let [canDo (auth/user-action-allowed? BadDog :write 123)] (println "Is BadDog allowed to delete==" canDo) (is (false? canDo)) )))) ;;[{:keys [profile_id institution_ids]} action-type group-id] (def my-group-changes {:name "New Group Name" :description "Fun!" :sequence_number 100 :access [{:entity_type 100 :entity_identifier "Will" :access_type 200},{:entity_type 100 :entity_identifier "299277" :access_type 300}] :items ["objectid3" "objectid4"] :tags ["tag1" "tag2"]}) (deftest access-object-authorization-test (with-db config (testing "Performing can Admin (MrBill) update access object authorization test" (let [canDo (auth/can-change-group-access? MrBill 123)] (println "Is MrBill allowed to update==" canDo) (is canDo)))) (with-db config (testing "Performing can Write only (Will) update access object authorization test" (let [canDo (auth/can-change-group-access? Will 123)] (println "Is Will allowed to update when he should not==" canDo) (is (not canDo))))) (with-db config (testing "Performing does Will's access object only have Will's stuff in it" (let [found-group-access (repo/find-group-by-id 123) filtered-group (auth/coerce-group-based-on-access-type found-group-access Will)] (println "Will's filtered group==" filtered-group) (is (= (filtered-group :access) [{:access_type 200, :entity_identifier "Will", :entity_type 100}]))))) (with-db config (testing "Performing does MrBill's Admin access object have Everything in it" (let [found-group-access (repo/find-group-by-id 123) filtered-group (auth/coerce-group-based-on-access-type found-group-access MrBill)] (println "MrBill's filtered group==" filtered-group) (is (= (filtered-group :access) [{:access_type 300, :entity_identifier "299277", :entity_type 100} {:access_type 100, :entity_identifier "Sai", :entity_type 100} {:access_type 200, :entity_identifier "Will", :entity_type 100} {:access_type 100, :entity_identifier "10001", :entity_type 200} {:access_type 300, :entity_identifier "Artstor", :entity_type 200}]))))) (with-db config (testing "Performing does Professor's access object only have Institution stuff in it" (let [found-group-access (repo/find-group-by-id 123) filtered-group (auth/coerce-group-based-on-access-type found-group-access Professor)] (println "Professor's filtered group==" filtered-group) (is (= (filtered-group :access) [{:access_type 100, :entity_identifier "10001", :entity_type 200}]))))) )
105671
(ns artstor-group-service.auth-test (:require [clojure.test :refer :all] [artstor-group-service.auth :as auth] [artstor-group-service.repository :as repo] [ragtime.jdbc :as jdbc] [ragtime.repl :refer [migrate rollback]] [environ.core :refer [env]] [schema.core :as s] [artstor-group-service.user :as user])) (def config {:datastore (jdbc/sql-database {:connection-uri (env :artstor-group-db-url)}) :migrations (jdbc/load-resources "test-migrations")}) (defmacro with-db [conf & body] `(do (migrate ~conf) (try ~@body (finally (rollback ~conf "001"))))) (def MrBill { :profile_id "299277" :username "<EMAIL>" :institution_ids ["1000"] }) (def Will { :profile_id "<NAME>" :username "<EMAIL>" :institution_ids ["2000"] }) (def Professor { :profile_id "123456" :username "<EMAIL>" :institution_ids ["10001"] }) (def BadDog { :profile_id "111111" :username "<EMAIL>" :institution_ids ["1234567"] }) (deftest authorization-test (with-db config (testing "Performing can MrBill read authorization test" (let [canRead (auth/user-action-allowed? MrBill :read 123)] (println "Does MrBill know how to read==" canRead) (is canRead) ))) (with-db config (testing "Performing can MrBill read his own Public Group test" (let [canRead (auth/user-action-allowed? MrBill :read 294484)] (println "Does MrBill know how to read his own public group==" canRead) (is canRead) ))) (with-db config (testing "Performing can Mr<NAME> write authorization test" (let [canDo (auth/user-action-allowed? <NAME> :write 123)] (println "Does Mr<NAME> know how to write==" canDo) (is canDo) ))) (with-db config (testing "Performing can MrBill delete authorization test" (let [canDo (auth/user-action-allowed? Mr<NAME> :admin 123)] (println "Does MrBill know how to delete==" canDo) (is canDo) ))) (with-db config (testing "Performing can Professor write authorization test" (let [canDo (auth/user-action-allowed? Professor :write 123)] (println "Is Professor allowed to write==" canDo) (is (false? canDo)) ))) (with-db config (testing "Performing can Professor read group shared at institution level" (let [canDo (auth/user-action-allowed? Professor :read 123)] (println "Is Professor allowed to read group123==" canDo) (is canDo) ))) (with-db config (testing "Performing can Professor read MrBill's Public Group test" (let [canRead (auth/user-action-allowed? Professor :read 294484)] (println "Does Professor know how to read MrBill's public group==" canRead) (is canRead) ))) (with-db config (testing "Performing can Professor can delete authorization test" (let [canDo (auth/user-action-allowed? Professor :write 123)] (println "Is Professor allowed to delete==" canDo) (is (false? canDo)) ))) (with-db config (testing "Performing can BadDog write authorization test" (let [canDo (auth/user-action-allowed? BadDog :write 123)] (println "Is BadDog allowed to write==" canDo) (is (false? canDo)) ))) (with-db config (testing "Performing can BadDog read authorization test" (let [canDo (auth/user-action-allowed? BadDog :read 123)] (println "Is BadDog allowed to read group123==" canDo) (is (false? canDo)) ))) (with-db config (testing "Performing can BadDog can delete authorization test" (let [canDo (auth/user-action-allowed? BadDog :write 123)] (println "Is BadDog allowed to delete==" canDo) (is (false? canDo)) )))) ;;[{:keys [profile_id institution_ids]} action-type group-id] (def my-group-changes {:name "New Group Name" :description "Fun!" :sequence_number 100 :access [{:entity_type 100 :entity_identifier "<NAME>" :access_type 200},{:entity_type 100 :entity_identifier "299277" :access_type 300}] :items ["objectid3" "objectid4"] :tags ["tag1" "tag2"]}) (deftest access-object-authorization-test (with-db config (testing "Performing can Admin (<NAME> <NAME>) update access object authorization test" (let [canDo (auth/can-change-group-access? Mr<NAME> 123)] (println "Is <NAME> <NAME> allowed to update==" canDo) (is canDo)))) (with-db config (testing "Performing can Write only (<NAME>) update access object authorization test" (let [canDo (auth/can-change-group-access? <NAME> 123)] (println "Is <NAME> allowed to update when he should not==" canDo) (is (not canDo))))) (with-db config (testing "Performing does Will's access object only have Will's stuff in it" (let [found-group-access (repo/find-group-by-id 123) filtered-group (auth/coerce-group-based-on-access-type found-group-access Will)] (println "<NAME>'s filtered group==" filtered-group) (is (= (filtered-group :access) [{:access_type 200, :entity_identifier "<NAME>", :entity_type 100}]))))) (with-db config (testing "Performing does <NAME>'s Admin access object have Everything in it" (let [found-group-access (repo/find-group-by-id 123) filtered-group (auth/coerce-group-based-on-access-type found-group-access <NAME>)] (println "<NAME>'s filtered group==" filtered-group) (is (= (filtered-group :access) [{:access_type 300, :entity_identifier "299277", :entity_type 100} {:access_type 100, :entity_identifier "<NAME>", :entity_type 100} {:access_type 200, :entity_identifier "<NAME>", :entity_type 100} {:access_type 100, :entity_identifier "10001", :entity_type 200} {:access_type 300, :entity_identifier "<NAME>", :entity_type 200}]))))) (with-db config (testing "Performing does Professor's access object only have Institution stuff in it" (let [found-group-access (repo/find-group-by-id 123) filtered-group (auth/coerce-group-based-on-access-type found-group-access Professor)] (println "Professor's filtered group==" filtered-group) (is (= (filtered-group :access) [{:access_type 100, :entity_identifier "10001", :entity_type 200}]))))) )
true
(ns artstor-group-service.auth-test (:require [clojure.test :refer :all] [artstor-group-service.auth :as auth] [artstor-group-service.repository :as repo] [ragtime.jdbc :as jdbc] [ragtime.repl :refer [migrate rollback]] [environ.core :refer [env]] [schema.core :as s] [artstor-group-service.user :as user])) (def config {:datastore (jdbc/sql-database {:connection-uri (env :artstor-group-db-url)}) :migrations (jdbc/load-resources "test-migrations")}) (defmacro with-db [conf & body] `(do (migrate ~conf) (try ~@body (finally (rollback ~conf "001"))))) (def MrBill { :profile_id "299277" :username "PI:EMAIL:<EMAIL>END_PI" :institution_ids ["1000"] }) (def Will { :profile_id "PI:NAME:<NAME>END_PI" :username "PI:EMAIL:<EMAIL>END_PI" :institution_ids ["2000"] }) (def Professor { :profile_id "123456" :username "PI:EMAIL:<EMAIL>END_PI" :institution_ids ["10001"] }) (def BadDog { :profile_id "111111" :username "PI:EMAIL:<EMAIL>END_PI" :institution_ids ["1234567"] }) (deftest authorization-test (with-db config (testing "Performing can MrBill read authorization test" (let [canRead (auth/user-action-allowed? MrBill :read 123)] (println "Does MrBill know how to read==" canRead) (is canRead) ))) (with-db config (testing "Performing can MrBill read his own Public Group test" (let [canRead (auth/user-action-allowed? MrBill :read 294484)] (println "Does MrBill know how to read his own public group==" canRead) (is canRead) ))) (with-db config (testing "Performing can MrPI:NAME:<NAME>END_PI write authorization test" (let [canDo (auth/user-action-allowed? PI:NAME:<NAME>END_PI :write 123)] (println "Does MrPI:NAME:<NAME>END_PI know how to write==" canDo) (is canDo) ))) (with-db config (testing "Performing can MrBill delete authorization test" (let [canDo (auth/user-action-allowed? MrPI:NAME:<NAME>END_PI :admin 123)] (println "Does MrBill know how to delete==" canDo) (is canDo) ))) (with-db config (testing "Performing can Professor write authorization test" (let [canDo (auth/user-action-allowed? Professor :write 123)] (println "Is Professor allowed to write==" canDo) (is (false? canDo)) ))) (with-db config (testing "Performing can Professor read group shared at institution level" (let [canDo (auth/user-action-allowed? Professor :read 123)] (println "Is Professor allowed to read group123==" canDo) (is canDo) ))) (with-db config (testing "Performing can Professor read MrBill's Public Group test" (let [canRead (auth/user-action-allowed? Professor :read 294484)] (println "Does Professor know how to read MrBill's public group==" canRead) (is canRead) ))) (with-db config (testing "Performing can Professor can delete authorization test" (let [canDo (auth/user-action-allowed? Professor :write 123)] (println "Is Professor allowed to delete==" canDo) (is (false? canDo)) ))) (with-db config (testing "Performing can BadDog write authorization test" (let [canDo (auth/user-action-allowed? BadDog :write 123)] (println "Is BadDog allowed to write==" canDo) (is (false? canDo)) ))) (with-db config (testing "Performing can BadDog read authorization test" (let [canDo (auth/user-action-allowed? BadDog :read 123)] (println "Is BadDog allowed to read group123==" canDo) (is (false? canDo)) ))) (with-db config (testing "Performing can BadDog can delete authorization test" (let [canDo (auth/user-action-allowed? BadDog :write 123)] (println "Is BadDog allowed to delete==" canDo) (is (false? canDo)) )))) ;;[{:keys [profile_id institution_ids]} action-type group-id] (def my-group-changes {:name "New Group Name" :description "Fun!" :sequence_number 100 :access [{:entity_type 100 :entity_identifier "PI:NAME:<NAME>END_PI" :access_type 200},{:entity_type 100 :entity_identifier "299277" :access_type 300}] :items ["objectid3" "objectid4"] :tags ["tag1" "tag2"]}) (deftest access-object-authorization-test (with-db config (testing "Performing can Admin (PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI) update access object authorization test" (let [canDo (auth/can-change-group-access? MrPI:NAME:<NAME>END_PI 123)] (println "Is PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI allowed to update==" canDo) (is canDo)))) (with-db config (testing "Performing can Write only (PI:NAME:<NAME>END_PI) update access object authorization test" (let [canDo (auth/can-change-group-access? PI:NAME:<NAME>END_PI 123)] (println "Is PI:NAME:<NAME>END_PI allowed to update when he should not==" canDo) (is (not canDo))))) (with-db config (testing "Performing does Will's access object only have Will's stuff in it" (let [found-group-access (repo/find-group-by-id 123) filtered-group (auth/coerce-group-based-on-access-type found-group-access Will)] (println "PI:NAME:<NAME>END_PI's filtered group==" filtered-group) (is (= (filtered-group :access) [{:access_type 200, :entity_identifier "PI:NAME:<NAME>END_PI", :entity_type 100}]))))) (with-db config (testing "Performing does PI:NAME:<NAME>END_PI's Admin access object have Everything in it" (let [found-group-access (repo/find-group-by-id 123) filtered-group (auth/coerce-group-based-on-access-type found-group-access PI:NAME:<NAME>END_PI)] (println "PI:NAME:<NAME>END_PI's filtered group==" filtered-group) (is (= (filtered-group :access) [{:access_type 300, :entity_identifier "299277", :entity_type 100} {:access_type 100, :entity_identifier "PI:NAME:<NAME>END_PI", :entity_type 100} {:access_type 200, :entity_identifier "PI:NAME:<NAME>END_PI", :entity_type 100} {:access_type 100, :entity_identifier "10001", :entity_type 200} {:access_type 300, :entity_identifier "PI:NAME:<NAME>END_PI", :entity_type 200}]))))) (with-db config (testing "Performing does Professor's access object only have Institution stuff in it" (let [found-group-access (repo/find-group-by-id 123) filtered-group (auth/coerce-group-based-on-access-type found-group-access Professor)] (println "Professor's filtered group==" filtered-group) (is (= (filtered-group :access) [{:access_type 100, :entity_identifier "10001", :entity_type 200}]))))) )
[ { "context": "6 {\r\n input.col.s6 first_name \"Etunimi\"\r\n input.col.s6 second_name \"S", "end": 4244, "score": 0.9996573328971863, "start": 4237, "tag": "NAME", "value": "Etunimi" }, { "context": "i\"\r\n input.col.s6 second_name \"Sukunimi\"\r\n }\r\n div.co.s6 {\r", "end": 4301, "score": 0.9995540380477905, "start": 4293, "tag": "NAME", "value": "Sukunimi" }, { "context": "6 {\r\n input.col.s8 first_name \"Katuosoite\"\r\n input.col.s4 second_name \"P", "end": 4407, "score": 0.9997241497039795, "start": 4397, "tag": "NAME", "value": "Katuosoite" }, { "context": "e\"\r\n input.col.s4 second_name \"Postinro\"\r\n }\r\n }\r\n d", "end": 4464, "score": 0.9995524883270264, "start": 4456, "tag": "NAME", "value": "Postinro" }, { "context": " {\r\n input card_title 'Kortin otsikko'\r\n }\r\n ", "end": 4861, "score": 0.9960366487503052, "start": 4847, "tag": "NAME", "value": "Kortin otsikko" }, { "context": "\r\nabout, it's worth fixing.\"` \r\n i \"-\" Rob Pike\r\n }\r\n }\r\n}", "end": 9862, "score": 0.9995353817939758, "start": 9854, "tag": "NAME", "value": "Rob Pike" } ]
compiler/test_slides.clj
terotests/Ranger
6
Import "JinxProcess.clj" Import "DOMLib.clj" class appmain { ; creating a process and so on.. ; it all should be really easy... static fn createElement:JinxProcess ( into:HTMLElement what:HTMLElement ) { def newElem (clone what) return (process 'element' (process.attr 'background' '1') (process.attr 'persistent' '1') (process (process.attr 'exit' 'true') (task.call { remove_dom newElem }) ) (task.call { add into newElem }) ) } static fn elementProcess:JinxProcess ( into:HTMLElement what:HTMLElement ) { def newElem (clone what) return (process 'element' (task.wait 1.33) (task.call { add into newElem }) (task.wait 1.33) ; TODO: how could exit process be "slow" (process (process.attr 'exit' 'true') (task.call { print "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" print "Exit handler was called --> calling process done" remove_dom newElem ; process.done(ctx) }) ) (task.wait 1.33) (task.call { print "before exit..." process.done(ctx) }) (task.wait 0.5) ; something to be called when process exits... ) } static fn main() { print "Loaded..." ; def nn (create_element 'div') def elem (find_element_by_attr 'data-comp-id' 'otsikko.yleinen') def card1 (unwrap (find_element_by_attr 'data-comp-id' 'samplecard')) def playg (unwrap (find_element_by_attr 'data-comp-id' 'playground')) def cnt 0 ; with react ; --> there is a state ; --> you render that state into screen ; --> you see the results. if(!null? elem) { def e (unwrap elem) def p (process 'test' (process.attr 'persistent' '1') (process "test" (process.attr 'background' 'true') (process.attr 'loop' 'true') (task.call { cnt = cnt + 1 text e ('seconds passed: ' + cnt) if(cnt == 6) { process.done(ctx) } }) (task.wait 1.001) ; push a new process into the existing process... (appmain.createElement(playg card1)) ) (process (process.attr 'exit' 'true') (task.call { print "**************************************************" print "the main process exits now" }) ) (task.wait 30.0) ) def ctx (new JinxProcessCtx) p.start(ctx) } } } plugin.ui @noinfix(true) { page "First Test" "material2" { h1 "Simple page" } page "First Test" "material1" { navbar { ul.right.hide-on-med-and-down { li (a '#' 'Menu item 1') li (a '#' 'Menu item 2') li (a '#' 'Menu item 3') } } div.container { h1@(otsikko.yleinen) "Hello World" div.row.s12@(playground) { } div.row.s12 { div.col.s6 { input.col.s6 first_name "Etunimi" input.col.s6 second_name "Sukunimi" } div.co.s6 { input.col.s8 first_name "Katuosoite" input.col.s4 second_name "Postinro" } } div.row.s12@(cards.obiwan) { div.col.s4@(samplecard) { card { div.card-image { img@(main.img) "https://i.imgflip.com/b62tb.jpg" } card-content { input card_title 'Kortin otsikko' } } } div.col.s4 { card { div.card-image { img@(main.img) "https://i.imgflip.com/b62tb.jpg" } card-content { p.card-title "Hello!" p "Here is some content to the card!!!" } } } div.col.s4 { card { div.card-image { img@(main.img) "https://i.imgflip.com/b62tb.jpg" } card-content { p.card-title "Hello!" p "Here is some content to the card!!!" } } } } button.floating (icon menu) button.floating (icon edit) card.blue-grey { div.card-content { p.card-title "Hello!" "Here is some content to the card!!!" div { button.floating (icon menu) button.floating (icon edit) } } } div.chip ( "Cool!" (icon.close 'close')) table { thead "Eka" "Toka" "Kolmas" tr 1 2 ( (b NOTE:) 'This works OK!!!') tr 4 5 6 tr 7 8 ( (div.chip 'hoo!!') ) } ul.collection { li.collection-item "Row 1" li.collection-item "Row 2" li.collection-item "Row 3" } div.row { button "OK" button "Fail" } } footer { div.container { div.row { p "here some text" } } div.footer-copyright { p "(C) ACME Ltd." } } } } plugin.file 'README.md' ' # Hello World from the file plugin ' plugin.md 'MDTEST.md' { ## Hello World table { tr 1 2 ( (b NOTE:) 'This works OK!!!') tr 4 5 6 tr 7 8 9 } code.javascript ` function foo() { } ` } plugin.md 'MDTEST2.md' @noinfix(true) { h1 @id('start') "Good to have some content" a 'http://www.yle.fi' 'Uuutiset' # Level 1 (i 'information') for you p 'Never leave home without it' ## Level 2 ### Level 3 pre 'Some code could be here' p { So each page must have introduction or perhaps even more... button "OK" } ul { li 'list item 1' li 'list item 2' } b '*) please notice these subleties...' p 'OK so here some more' ol { li 'second row with some more items' } pre ' for list item:string i { } ' p (button "OK") table { thead 'First items' ( (i 'Very') 'important ' things) 'the rest' tr 'here is one cell' 'here is second' 'AND here is the third' tr (Something here) (Something here) { 'I just wanted to create a longer subsection over here now' (p 'not because it is important though...') } tr "third row" '' '' } h1 @id("end") "Good to have some content" p { So each page must have introduction or perhaps even more... button "OK" } ul { li 'list item 1' li 'list item 2' } b '*) please notice these subleties...' p 'OK so here some more' ol { li 'second row with some more items' } pre ' for list item:string i { } ' p (button "OK") } plugin.slides @noinfix(true) { presentation "Testi presis" "reveal_test.html" { slide { h1 "Ranger" } slide { slide { h1 "Supports" table { tr 'JavaScript' 'Go' 'PHP' tr 'Scala' 'C#' 'Java' tr 'C++' 'TypeScript' 'Swift' } p.fragment '+ plugins' } } slide { quote `"We made a deliberate decision: no warnings. If it's worth complaining about, it's worth fixing."` i "-" Rob Pike } } }
36227
Import "JinxProcess.clj" Import "DOMLib.clj" class appmain { ; creating a process and so on.. ; it all should be really easy... static fn createElement:JinxProcess ( into:HTMLElement what:HTMLElement ) { def newElem (clone what) return (process 'element' (process.attr 'background' '1') (process.attr 'persistent' '1') (process (process.attr 'exit' 'true') (task.call { remove_dom newElem }) ) (task.call { add into newElem }) ) } static fn elementProcess:JinxProcess ( into:HTMLElement what:HTMLElement ) { def newElem (clone what) return (process 'element' (task.wait 1.33) (task.call { add into newElem }) (task.wait 1.33) ; TODO: how could exit process be "slow" (process (process.attr 'exit' 'true') (task.call { print "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" print "Exit handler was called --> calling process done" remove_dom newElem ; process.done(ctx) }) ) (task.wait 1.33) (task.call { print "before exit..." process.done(ctx) }) (task.wait 0.5) ; something to be called when process exits... ) } static fn main() { print "Loaded..." ; def nn (create_element 'div') def elem (find_element_by_attr 'data-comp-id' 'otsikko.yleinen') def card1 (unwrap (find_element_by_attr 'data-comp-id' 'samplecard')) def playg (unwrap (find_element_by_attr 'data-comp-id' 'playground')) def cnt 0 ; with react ; --> there is a state ; --> you render that state into screen ; --> you see the results. if(!null? elem) { def e (unwrap elem) def p (process 'test' (process.attr 'persistent' '1') (process "test" (process.attr 'background' 'true') (process.attr 'loop' 'true') (task.call { cnt = cnt + 1 text e ('seconds passed: ' + cnt) if(cnt == 6) { process.done(ctx) } }) (task.wait 1.001) ; push a new process into the existing process... (appmain.createElement(playg card1)) ) (process (process.attr 'exit' 'true') (task.call { print "**************************************************" print "the main process exits now" }) ) (task.wait 30.0) ) def ctx (new JinxProcessCtx) p.start(ctx) } } } plugin.ui @noinfix(true) { page "First Test" "material2" { h1 "Simple page" } page "First Test" "material1" { navbar { ul.right.hide-on-med-and-down { li (a '#' 'Menu item 1') li (a '#' 'Menu item 2') li (a '#' 'Menu item 3') } } div.container { h1@(otsikko.yleinen) "Hello World" div.row.s12@(playground) { } div.row.s12 { div.col.s6 { input.col.s6 first_name "<NAME>" input.col.s6 second_name "<NAME>" } div.co.s6 { input.col.s8 first_name "<NAME>" input.col.s4 second_name "<NAME>" } } div.row.s12@(cards.obiwan) { div.col.s4@(samplecard) { card { div.card-image { img@(main.img) "https://i.imgflip.com/b62tb.jpg" } card-content { input card_title '<NAME>' } } } div.col.s4 { card { div.card-image { img@(main.img) "https://i.imgflip.com/b62tb.jpg" } card-content { p.card-title "Hello!" p "Here is some content to the card!!!" } } } div.col.s4 { card { div.card-image { img@(main.img) "https://i.imgflip.com/b62tb.jpg" } card-content { p.card-title "Hello!" p "Here is some content to the card!!!" } } } } button.floating (icon menu) button.floating (icon edit) card.blue-grey { div.card-content { p.card-title "Hello!" "Here is some content to the card!!!" div { button.floating (icon menu) button.floating (icon edit) } } } div.chip ( "Cool!" (icon.close 'close')) table { thead "Eka" "Toka" "Kolmas" tr 1 2 ( (b NOTE:) 'This works OK!!!') tr 4 5 6 tr 7 8 ( (div.chip 'hoo!!') ) } ul.collection { li.collection-item "Row 1" li.collection-item "Row 2" li.collection-item "Row 3" } div.row { button "OK" button "Fail" } } footer { div.container { div.row { p "here some text" } } div.footer-copyright { p "(C) ACME Ltd." } } } } plugin.file 'README.md' ' # Hello World from the file plugin ' plugin.md 'MDTEST.md' { ## Hello World table { tr 1 2 ( (b NOTE:) 'This works OK!!!') tr 4 5 6 tr 7 8 9 } code.javascript ` function foo() { } ` } plugin.md 'MDTEST2.md' @noinfix(true) { h1 @id('start') "Good to have some content" a 'http://www.yle.fi' 'Uuutiset' # Level 1 (i 'information') for you p 'Never leave home without it' ## Level 2 ### Level 3 pre 'Some code could be here' p { So each page must have introduction or perhaps even more... button "OK" } ul { li 'list item 1' li 'list item 2' } b '*) please notice these subleties...' p 'OK so here some more' ol { li 'second row with some more items' } pre ' for list item:string i { } ' p (button "OK") table { thead 'First items' ( (i 'Very') 'important ' things) 'the rest' tr 'here is one cell' 'here is second' 'AND here is the third' tr (Something here) (Something here) { 'I just wanted to create a longer subsection over here now' (p 'not because it is important though...') } tr "third row" '' '' } h1 @id("end") "Good to have some content" p { So each page must have introduction or perhaps even more... button "OK" } ul { li 'list item 1' li 'list item 2' } b '*) please notice these subleties...' p 'OK so here some more' ol { li 'second row with some more items' } pre ' for list item:string i { } ' p (button "OK") } plugin.slides @noinfix(true) { presentation "Testi presis" "reveal_test.html" { slide { h1 "Ranger" } slide { slide { h1 "Supports" table { tr 'JavaScript' 'Go' 'PHP' tr 'Scala' 'C#' 'Java' tr 'C++' 'TypeScript' 'Swift' } p.fragment '+ plugins' } } slide { quote `"We made a deliberate decision: no warnings. If it's worth complaining about, it's worth fixing."` i "-" <NAME> } } }
true
Import "JinxProcess.clj" Import "DOMLib.clj" class appmain { ; creating a process and so on.. ; it all should be really easy... static fn createElement:JinxProcess ( into:HTMLElement what:HTMLElement ) { def newElem (clone what) return (process 'element' (process.attr 'background' '1') (process.attr 'persistent' '1') (process (process.attr 'exit' 'true') (task.call { remove_dom newElem }) ) (task.call { add into newElem }) ) } static fn elementProcess:JinxProcess ( into:HTMLElement what:HTMLElement ) { def newElem (clone what) return (process 'element' (task.wait 1.33) (task.call { add into newElem }) (task.wait 1.33) ; TODO: how could exit process be "slow" (process (process.attr 'exit' 'true') (task.call { print "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" print "Exit handler was called --> calling process done" remove_dom newElem ; process.done(ctx) }) ) (task.wait 1.33) (task.call { print "before exit..." process.done(ctx) }) (task.wait 0.5) ; something to be called when process exits... ) } static fn main() { print "Loaded..." ; def nn (create_element 'div') def elem (find_element_by_attr 'data-comp-id' 'otsikko.yleinen') def card1 (unwrap (find_element_by_attr 'data-comp-id' 'samplecard')) def playg (unwrap (find_element_by_attr 'data-comp-id' 'playground')) def cnt 0 ; with react ; --> there is a state ; --> you render that state into screen ; --> you see the results. if(!null? elem) { def e (unwrap elem) def p (process 'test' (process.attr 'persistent' '1') (process "test" (process.attr 'background' 'true') (process.attr 'loop' 'true') (task.call { cnt = cnt + 1 text e ('seconds passed: ' + cnt) if(cnt == 6) { process.done(ctx) } }) (task.wait 1.001) ; push a new process into the existing process... (appmain.createElement(playg card1)) ) (process (process.attr 'exit' 'true') (task.call { print "**************************************************" print "the main process exits now" }) ) (task.wait 30.0) ) def ctx (new JinxProcessCtx) p.start(ctx) } } } plugin.ui @noinfix(true) { page "First Test" "material2" { h1 "Simple page" } page "First Test" "material1" { navbar { ul.right.hide-on-med-and-down { li (a '#' 'Menu item 1') li (a '#' 'Menu item 2') li (a '#' 'Menu item 3') } } div.container { h1@(otsikko.yleinen) "Hello World" div.row.s12@(playground) { } div.row.s12 { div.col.s6 { input.col.s6 first_name "PI:NAME:<NAME>END_PI" input.col.s6 second_name "PI:NAME:<NAME>END_PI" } div.co.s6 { input.col.s8 first_name "PI:NAME:<NAME>END_PI" input.col.s4 second_name "PI:NAME:<NAME>END_PI" } } div.row.s12@(cards.obiwan) { div.col.s4@(samplecard) { card { div.card-image { img@(main.img) "https://i.imgflip.com/b62tb.jpg" } card-content { input card_title 'PI:NAME:<NAME>END_PI' } } } div.col.s4 { card { div.card-image { img@(main.img) "https://i.imgflip.com/b62tb.jpg" } card-content { p.card-title "Hello!" p "Here is some content to the card!!!" } } } div.col.s4 { card { div.card-image { img@(main.img) "https://i.imgflip.com/b62tb.jpg" } card-content { p.card-title "Hello!" p "Here is some content to the card!!!" } } } } button.floating (icon menu) button.floating (icon edit) card.blue-grey { div.card-content { p.card-title "Hello!" "Here is some content to the card!!!" div { button.floating (icon menu) button.floating (icon edit) } } } div.chip ( "Cool!" (icon.close 'close')) table { thead "Eka" "Toka" "Kolmas" tr 1 2 ( (b NOTE:) 'This works OK!!!') tr 4 5 6 tr 7 8 ( (div.chip 'hoo!!') ) } ul.collection { li.collection-item "Row 1" li.collection-item "Row 2" li.collection-item "Row 3" } div.row { button "OK" button "Fail" } } footer { div.container { div.row { p "here some text" } } div.footer-copyright { p "(C) ACME Ltd." } } } } plugin.file 'README.md' ' # Hello World from the file plugin ' plugin.md 'MDTEST.md' { ## Hello World table { tr 1 2 ( (b NOTE:) 'This works OK!!!') tr 4 5 6 tr 7 8 9 } code.javascript ` function foo() { } ` } plugin.md 'MDTEST2.md' @noinfix(true) { h1 @id('start') "Good to have some content" a 'http://www.yle.fi' 'Uuutiset' # Level 1 (i 'information') for you p 'Never leave home without it' ## Level 2 ### Level 3 pre 'Some code could be here' p { So each page must have introduction or perhaps even more... button "OK" } ul { li 'list item 1' li 'list item 2' } b '*) please notice these subleties...' p 'OK so here some more' ol { li 'second row with some more items' } pre ' for list item:string i { } ' p (button "OK") table { thead 'First items' ( (i 'Very') 'important ' things) 'the rest' tr 'here is one cell' 'here is second' 'AND here is the third' tr (Something here) (Something here) { 'I just wanted to create a longer subsection over here now' (p 'not because it is important though...') } tr "third row" '' '' } h1 @id("end") "Good to have some content" p { So each page must have introduction or perhaps even more... button "OK" } ul { li 'list item 1' li 'list item 2' } b '*) please notice these subleties...' p 'OK so here some more' ol { li 'second row with some more items' } pre ' for list item:string i { } ' p (button "OK") } plugin.slides @noinfix(true) { presentation "Testi presis" "reveal_test.html" { slide { h1 "Ranger" } slide { slide { h1 "Supports" table { tr 'JavaScript' 'Go' 'PHP' tr 'Scala' 'C#' 'Java' tr 'C++' 'TypeScript' 'Swift' } p.fragment '+ plugins' } } slide { quote `"We made a deliberate decision: no warnings. If it's worth complaining about, it's worth fixing."` i "-" PI:NAME:<NAME>END_PI } } }
[ { "context": " tag1-colls [coll1 coll2]\n tag-key \"tag1\"\n tag1 (tags/save-tag\n u", "end": 1612, "score": 0.9377464056015015, "start": 1608, "tag": "KEY", "value": "tag1" } ]
system-int-test/test/cmr/system_int_test/bootstrap/bulk_index/tag_test.clj
brianalexander/Common-Metadata-Repository
294
(ns cmr.system-int-test.bootstrap.bulk-index.tag-test "Integration test for CMR bulk index tag operations." (:require [clojure.test :refer :all] [cmr.mock-echo.client.echo-util :as e] [cmr.oracle.connection :as oracle] [cmr.system-int-test.bootstrap.bulk-index.core :as core] [cmr.system-int-test.data2.collection :as dc] [cmr.system-int-test.data2.core :as d] [cmr.system-int-test.system :as s] [cmr.system-int-test.utils.bootstrap-util :as bootstrap] [cmr.system-int-test.utils.index-util :as index] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.search-util :as search] [cmr.system-int-test.utils.tag-util :as tags])) (use-fixtures :each (join-fixtures [(ingest/reset-fixture {"provguid1" "PROV1"} {:grant-all-ingest? true :grant-all-search? true :grant-all-access-control? false}) tags/grant-all-tag-fixture])) ;; This test is to verify that bulk index works with tombstoned tag associations (deftest ^:oracle bulk-index-collections-with-tag-association-test (s/only-with-real-database (let [[coll1 coll2] (for [n (range 1 3)] (d/ingest "PROV1" (dc/collection {:entry-title (str "coll" n)}))) ;; Wait until collections are indexed so tags can be associated with them _ (index/wait-until-indexed) user1-token (e/login (s/context) "user1") tag1-colls [coll1 coll2] tag-key "tag1" tag1 (tags/save-tag user1-token (tags/make-tag {:tag-key tag-key}) tag1-colls)] (index/wait-until-indexed) ;; dissociate tag1 from coll2 and not send indexing events (core/disable-automatic-indexing) (tags/dissociate-by-query user1-token tag-key {:concept_id (:concept-id coll2)}) (core/reenable-automatic-indexing) (bootstrap/bulk-index-provider "PROV1") (index/wait-until-indexed) (testing "All tag parameters with XML references" (is (d/refs-match? [coll1] (search/find-refs :collection {:tag-key "tag1"})))))))
6560
(ns cmr.system-int-test.bootstrap.bulk-index.tag-test "Integration test for CMR bulk index tag operations." (:require [clojure.test :refer :all] [cmr.mock-echo.client.echo-util :as e] [cmr.oracle.connection :as oracle] [cmr.system-int-test.bootstrap.bulk-index.core :as core] [cmr.system-int-test.data2.collection :as dc] [cmr.system-int-test.data2.core :as d] [cmr.system-int-test.system :as s] [cmr.system-int-test.utils.bootstrap-util :as bootstrap] [cmr.system-int-test.utils.index-util :as index] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.search-util :as search] [cmr.system-int-test.utils.tag-util :as tags])) (use-fixtures :each (join-fixtures [(ingest/reset-fixture {"provguid1" "PROV1"} {:grant-all-ingest? true :grant-all-search? true :grant-all-access-control? false}) tags/grant-all-tag-fixture])) ;; This test is to verify that bulk index works with tombstoned tag associations (deftest ^:oracle bulk-index-collections-with-tag-association-test (s/only-with-real-database (let [[coll1 coll2] (for [n (range 1 3)] (d/ingest "PROV1" (dc/collection {:entry-title (str "coll" n)}))) ;; Wait until collections are indexed so tags can be associated with them _ (index/wait-until-indexed) user1-token (e/login (s/context) "user1") tag1-colls [coll1 coll2] tag-key "<KEY>" tag1 (tags/save-tag user1-token (tags/make-tag {:tag-key tag-key}) tag1-colls)] (index/wait-until-indexed) ;; dissociate tag1 from coll2 and not send indexing events (core/disable-automatic-indexing) (tags/dissociate-by-query user1-token tag-key {:concept_id (:concept-id coll2)}) (core/reenable-automatic-indexing) (bootstrap/bulk-index-provider "PROV1") (index/wait-until-indexed) (testing "All tag parameters with XML references" (is (d/refs-match? [coll1] (search/find-refs :collection {:tag-key "tag1"})))))))
true
(ns cmr.system-int-test.bootstrap.bulk-index.tag-test "Integration test for CMR bulk index tag operations." (:require [clojure.test :refer :all] [cmr.mock-echo.client.echo-util :as e] [cmr.oracle.connection :as oracle] [cmr.system-int-test.bootstrap.bulk-index.core :as core] [cmr.system-int-test.data2.collection :as dc] [cmr.system-int-test.data2.core :as d] [cmr.system-int-test.system :as s] [cmr.system-int-test.utils.bootstrap-util :as bootstrap] [cmr.system-int-test.utils.index-util :as index] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.search-util :as search] [cmr.system-int-test.utils.tag-util :as tags])) (use-fixtures :each (join-fixtures [(ingest/reset-fixture {"provguid1" "PROV1"} {:grant-all-ingest? true :grant-all-search? true :grant-all-access-control? false}) tags/grant-all-tag-fixture])) ;; This test is to verify that bulk index works with tombstoned tag associations (deftest ^:oracle bulk-index-collections-with-tag-association-test (s/only-with-real-database (let [[coll1 coll2] (for [n (range 1 3)] (d/ingest "PROV1" (dc/collection {:entry-title (str "coll" n)}))) ;; Wait until collections are indexed so tags can be associated with them _ (index/wait-until-indexed) user1-token (e/login (s/context) "user1") tag1-colls [coll1 coll2] tag-key "PI:KEY:<KEY>END_PI" tag1 (tags/save-tag user1-token (tags/make-tag {:tag-key tag-key}) tag1-colls)] (index/wait-until-indexed) ;; dissociate tag1 from coll2 and not send indexing events (core/disable-automatic-indexing) (tags/dissociate-by-query user1-token tag-key {:concept_id (:concept-id coll2)}) (core/reenable-automatic-indexing) (bootstrap/bulk-index-provider "PROV1") (index/wait-until-indexed) (testing "All tag parameters with XML references" (is (d/refs-match? [coll1] (search/find-refs :collection {:tag-key "tag1"})))))))
[ { "context": "{:id \"1\"\n; ; :first_name \"Sam\"\n; ; :last_name \"Smith\"\n; ; ", "end": 1806, "score": 0.9998681545257568, "start": 1803, "tag": "NAME", "value": "Sam" }, { "context": "first_name \"Sam\"\n; ; :last_name \"Smith\"\n; ; :email \"sam.smith@examp", "end": 1846, "score": 0.9996882081031799, "start": 1841, "tag": "NAME", "value": "Smith" }, { "context": "st_name \"Smith\"\n; ; :email \"sam.smith@example.com\"\n; ; :pass \"pass\"})))\n; ; ", "end": 1902, "score": 0.99991375207901, "start": 1881, "tag": "EMAIL", "value": "sam.smith@example.com" }, { "context": "ith@example.com\"\n; ; :pass \"pass\"})))\n; ; (is (= {:id \"1\"\n; ; ", "end": 1941, "score": 0.9987140893936157, "start": 1937, "tag": "PASSWORD", "value": "pass" }, { "context": " (= {:id \"1\"\n; ; :first_name \"Sam\"\n; ; :last_name \"Smith\"\n; ; ", "end": 2011, "score": 0.9998729825019836, "start": 2008, "tag": "NAME", "value": "Sam" }, { "context": " :first_name \"Sam\"\n; ; :last_name \"Smith\"\n; ; :email \"sam.smith@example.c", "end": 2047, "score": 0.9996992349624634, "start": 2042, "tag": "NAME", "value": "Smith" }, { "context": " :last_name \"Smith\"\n; ; :email \"sam.smith@example.com\"\n; ; :pass \"pass\"\n; ; ", "end": 2099, "score": 0.9999130964279175, "start": 2078, "tag": "EMAIL", "value": "sam.smith@example.com" }, { "context": "m.smith@example.com\"\n; ; :pass \"pass\"\n; ; :admin nil\n; ; ", "end": 2134, "score": 0.9988976716995239, "start": 2130, "tag": "PASSWORD", "value": "pass" } ]
test/clj/landschaften/test/db/core.clj
cljs-material-ui/landschaften
2
; (ns landschaften.test.db.core ; (:require ; [landschaften.test.db.fixtures :as fixtures] ; [clojure.test :refer [is deftest]] ; [landschaften.db.wga-concepts :refer :all] ; [landschaften.api :refer :all])) ; ; ; (def row fixtures/a-wga-concept-row-with-general-concepts) ; ; (def rows fixtures/wga-concept-rows-with-general-concepts) ; ; (deftest test-has-certainty-above ; (is (has-certainty-above {:name "cool" :value 0.8} 0.7))) ; ; (deftest test-has-certainty-above-1 ; (is (not (has-certainty-above {:name "cool" :value 0.8} 0.9)))) ; ; (deftest test-is-concept ; (is (is-concept {:name "cool" :value 0.8} "cool"))) ; ; (deftest test-is-concept-1 ; (is (not (is-concept {:name "cool" :value 0.8} "hotdog")))) ; ; (deftest test-has-concepts-satisfying ; (is (has-concept-satisfying ; row ; [#(is-concept % "no person") ; #(has-certainty-above % 0.95)]))) ; ; (deftest test-has-concepts-satisfying-1 ; (is (not (has-concept-satisfying ; row ; [#(is-concept % "no person") ; #(has-certainty-above % 0.99)])))) ; ; (deftest test-has-concepts-satisfying-2 ; (is (not (has-concept-satisfying ; row ; [#(is-concept % "beaux-arts") ; #(has-certainty-above % 0.95)])))) ; ; ; ; ; ; (clojure.test/is) ; ; (deftest test-rows-with-concepts-satisfying ; ; (let [preds [#(is-concept % "architecture") #(has-certainty-above % 0.80)]] ; ; (is ; ; (= ; ; (some) ; ; (rows-with-concepts-satisfying rows preds))))) ; ; ; ; ; ; ; ; (deftest test-users ; ; (jdbc/with-db-transaction [t-conn *db*] ; ; (jdbc/db-set-rollback-only! t-conn) ; ; (is (= 1 (db/create-user! ; ; t-conn ; ; {:id "1" ; ; :first_name "Sam" ; ; :last_name "Smith" ; ; :email "sam.smith@example.com" ; ; :pass "pass"}))) ; ; (is (= {:id "1" ; ; :first_name "Sam" ; ; :last_name "Smith" ; ; :email "sam.smith@example.com" ; ; :pass "pass" ; ; :admin nil ; ; :last_login nil ; ; :is_active nil} ; ; (db/get-user t-conn {:id "1"})))))
78085
; (ns landschaften.test.db.core ; (:require ; [landschaften.test.db.fixtures :as fixtures] ; [clojure.test :refer [is deftest]] ; [landschaften.db.wga-concepts :refer :all] ; [landschaften.api :refer :all])) ; ; ; (def row fixtures/a-wga-concept-row-with-general-concepts) ; ; (def rows fixtures/wga-concept-rows-with-general-concepts) ; ; (deftest test-has-certainty-above ; (is (has-certainty-above {:name "cool" :value 0.8} 0.7))) ; ; (deftest test-has-certainty-above-1 ; (is (not (has-certainty-above {:name "cool" :value 0.8} 0.9)))) ; ; (deftest test-is-concept ; (is (is-concept {:name "cool" :value 0.8} "cool"))) ; ; (deftest test-is-concept-1 ; (is (not (is-concept {:name "cool" :value 0.8} "hotdog")))) ; ; (deftest test-has-concepts-satisfying ; (is (has-concept-satisfying ; row ; [#(is-concept % "no person") ; #(has-certainty-above % 0.95)]))) ; ; (deftest test-has-concepts-satisfying-1 ; (is (not (has-concept-satisfying ; row ; [#(is-concept % "no person") ; #(has-certainty-above % 0.99)])))) ; ; (deftest test-has-concepts-satisfying-2 ; (is (not (has-concept-satisfying ; row ; [#(is-concept % "beaux-arts") ; #(has-certainty-above % 0.95)])))) ; ; ; ; ; ; (clojure.test/is) ; ; (deftest test-rows-with-concepts-satisfying ; ; (let [preds [#(is-concept % "architecture") #(has-certainty-above % 0.80)]] ; ; (is ; ; (= ; ; (some) ; ; (rows-with-concepts-satisfying rows preds))))) ; ; ; ; ; ; ; ; (deftest test-users ; ; (jdbc/with-db-transaction [t-conn *db*] ; ; (jdbc/db-set-rollback-only! t-conn) ; ; (is (= 1 (db/create-user! ; ; t-conn ; ; {:id "1" ; ; :first_name "<NAME>" ; ; :last_name "<NAME>" ; ; :email "<EMAIL>" ; ; :pass "<PASSWORD>"}))) ; ; (is (= {:id "1" ; ; :first_name "<NAME>" ; ; :last_name "<NAME>" ; ; :email "<EMAIL>" ; ; :pass "<PASSWORD>" ; ; :admin nil ; ; :last_login nil ; ; :is_active nil} ; ; (db/get-user t-conn {:id "1"})))))
true
; (ns landschaften.test.db.core ; (:require ; [landschaften.test.db.fixtures :as fixtures] ; [clojure.test :refer [is deftest]] ; [landschaften.db.wga-concepts :refer :all] ; [landschaften.api :refer :all])) ; ; ; (def row fixtures/a-wga-concept-row-with-general-concepts) ; ; (def rows fixtures/wga-concept-rows-with-general-concepts) ; ; (deftest test-has-certainty-above ; (is (has-certainty-above {:name "cool" :value 0.8} 0.7))) ; ; (deftest test-has-certainty-above-1 ; (is (not (has-certainty-above {:name "cool" :value 0.8} 0.9)))) ; ; (deftest test-is-concept ; (is (is-concept {:name "cool" :value 0.8} "cool"))) ; ; (deftest test-is-concept-1 ; (is (not (is-concept {:name "cool" :value 0.8} "hotdog")))) ; ; (deftest test-has-concepts-satisfying ; (is (has-concept-satisfying ; row ; [#(is-concept % "no person") ; #(has-certainty-above % 0.95)]))) ; ; (deftest test-has-concepts-satisfying-1 ; (is (not (has-concept-satisfying ; row ; [#(is-concept % "no person") ; #(has-certainty-above % 0.99)])))) ; ; (deftest test-has-concepts-satisfying-2 ; (is (not (has-concept-satisfying ; row ; [#(is-concept % "beaux-arts") ; #(has-certainty-above % 0.95)])))) ; ; ; ; ; ; (clojure.test/is) ; ; (deftest test-rows-with-concepts-satisfying ; ; (let [preds [#(is-concept % "architecture") #(has-certainty-above % 0.80)]] ; ; (is ; ; (= ; ; (some) ; ; (rows-with-concepts-satisfying rows preds))))) ; ; ; ; ; ; ; ; (deftest test-users ; ; (jdbc/with-db-transaction [t-conn *db*] ; ; (jdbc/db-set-rollback-only! t-conn) ; ; (is (= 1 (db/create-user! ; ; t-conn ; ; {:id "1" ; ; :first_name "PI:NAME:<NAME>END_PI" ; ; :last_name "PI:NAME:<NAME>END_PI" ; ; :email "PI:EMAIL:<EMAIL>END_PI" ; ; :pass "PI:PASSWORD:<PASSWORD>END_PI"}))) ; ; (is (= {:id "1" ; ; :first_name "PI:NAME:<NAME>END_PI" ; ; :last_name "PI:NAME:<NAME>END_PI" ; ; :email "PI:EMAIL:<EMAIL>END_PI" ; ; :pass "PI:PASSWORD:<PASSWORD>END_PI" ; ; :admin nil ; ; :last_login nil ; ; :is_active nil} ; ; (db/get-user t-conn {:id "1"})))))
[ { "context": "st\n\n;;; p.58\n;;; 6.aug.2015\n\n(def person {:fname \"Adam\" :lname \"Parker\"})\n\n(rest person)\n(cons [:mname \"", "end": 84, "score": 0.9997509121894836, "start": 80, "tag": "NAME", "value": "Adam" }, { "context": ";; 6.aug.2015\n\n(def person {:fname \"Adam\" :lname \"Parker\"})\n\n(rest person)\n(cons [:mname \"J\"] person)\n\n(cl", "end": 100, "score": 0.9992431402206421, "start": 94, "tag": "NAME", "value": "Parker" } ]
book-programming-clj-2nd-ed/seqs.clj
reddress/clojuring
0
;;;; seqs, cons, first, and rest ;;; p.58 ;;; 6.aug.2015 (def person {:fname "Adam" :lname "Parker"}) (rest person) (cons [:mname "J"] person) (class (cons [:mname "J"] person)) (first (cons [:mname "J"] person)) (seq? (cons 'a ()))
37964
;;;; seqs, cons, first, and rest ;;; p.58 ;;; 6.aug.2015 (def person {:fname "<NAME>" :lname "<NAME>"}) (rest person) (cons [:mname "J"] person) (class (cons [:mname "J"] person)) (first (cons [:mname "J"] person)) (seq? (cons 'a ()))
true
;;;; seqs, cons, first, and rest ;;; p.58 ;;; 6.aug.2015 (def person {:fname "PI:NAME:<NAME>END_PI" :lname "PI:NAME:<NAME>END_PI"}) (rest person) (cons [:mname "J"] person) (class (cons [:mname "J"] person)) (first (cons [:mname "J"] person)) (seq? (cons 'a ()))
[ { "context": "(ns repliclj.page\n ^{:author \"Thomas Bock <wactbprot@gmail.com>\"\n :doc \"Simple replicati", "end": 42, "score": 0.9998543858528137, "start": 31, "tag": "NAME", "value": "Thomas Bock" }, { "context": "(ns repliclj.page\n ^{:author \"Thomas Bock <wactbprot@gmail.com>\"\n :doc \"Simple replication state overview pag", "end": 63, "score": 0.9999287724494934, "start": 44, "tag": "EMAIL", "value": "wactbprot@gmail.com" } ]
src/repliclj/page.clj
wactbprot/repliclj
0
(ns repliclj.page ^{:author "Thomas Bock <wactbprot@gmail.com>" :doc "Simple replication state overview page delivered by server.clj."} (:require [hiccup.form :as hf] [hiccup.page :as hp] [repliclj.utils :as u] [clojure.string :as string])) (defn not-found [] (hp/html5 [:h1 "404 Error!"] [:b "Page not found!"] [:p [:a {:href ".."} "Return to main page"]])) ;;........................................................................ ;; nav ;;........................................................................ (defn nav [conf data] [:div.uk-navbar-container {:uk-navbar ""} [:div.uk-navbar-center [:ul.uk-navbar-nav [:li [:a {:target "_blank" :href "https://gitlab1.ptb.de/vaclab/repliclj"} "gitlab"]] [:li [:a {:target "_blank" :href "http://a75438:5601/app/discover#/view/6fde0090-06ff-11ec-a0ed-9fa5b8b37aed"} "elasticsearch"]] [:li [:a { :target "_blank" :href "https://docs.couchdb.org/en/main/replication/index.html"} "repli docu"]]]]]) ;;........................................................................ ;; table ;;........................................................................ (defn table-row [m] [:tr [:td (u/url->db (:source m))] [:td (u/url->db (:target m))] [:td (u/url->host-name (:target m))] [:td (:state m)] [:td (:changes_pending (:info m))] [:td (:error_count m)] [:td (u/nice-date (:start_time m))] [:td (u/nice-date (:last_updated m))] [:td [:a {:target "_blank" :uk-icon "link" :href (u/repli-doc-link m)}]]]) (defn table [v] [:table.uk-table.uk-table-hover.uk-table-striped [:thead [:tr [:th "source db"] [:th "target db"] [:th "target host"] [:th "status"] [:th {:uk-tooltip "pending changes"} "pc"] [:th {:uk-tooltip "error count"} "ec"] [:th "start time"] [:th "last updated"] [:th.uk-table-shrink "doc"]]] (into [:tbody] (map table-row v))]) (defn state-summary [v] (into [:span.uk-text-muted.uk-text-center] (mapv (fn [[state number]] (str state ":&nbsp;"number "&nbsp;&nbsp;&nbsp;")) (frequencies (mapv :state v))))) (defn db-info [v] (into [:ul.uk-breadcrumb] (mapv (fn [db] [:li [:span (:key db) "&nbsp;"] [:span.uk-badge (:doc_count (:info db))]]) v))) (defn li [m] (let [data (:docs m) sum (state-summary data)] [:li [:div.uk-accordion-title {:uk-grid ""} [:div.uk-text-muted.uk-text-left (if (seq data) sum "no data")] [:div.uk-width-expand.uk-grid-column-medium.uk-text-right (:alias m) [:span.uk-text-muted (u/host->host-name (:server m))]]] (when (seq data) [:div.uk-accordion-content (db-info (:db-info m)) (table data)])])) (defn accord [conf data] (into [:ul {:uk-accordion ""}] (mapv li data))) ;;........................................................................ ;; body ;;........................................................................ (defn body [conf data content libs] (into [:body#body (nav conf data) [:div.uk-container.uk-padding.uk-margin [:article.uk-article [:h4.uk-article-title.uk-text-uppercase.uk-heading-line.uk-text-center.uk-text-muted [:a.uk-link-reset {:href ""} "replication state"]] [:p.uk-article-meta (u/date)] [:p.uk-text-lead content]]]] libs)) ;;........................................................................ ;; head ;;........................................................................ (defn head [conf data] [:head [:title "repliclj"] [:meta {:charset "utf-8"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1"}] (hp/include-css "/css/uikit.css")]) ;;........................................................................ ;; index ;;........................................................................ (defn index [conf data] (hp/html5 (head conf data) (body conf data (accord conf data) [(hp/include-js "/js/uikit.js") (hp/include-js "/js/uikit-icons.js")])))
67505
(ns repliclj.page ^{:author "<NAME> <<EMAIL>>" :doc "Simple replication state overview page delivered by server.clj."} (:require [hiccup.form :as hf] [hiccup.page :as hp] [repliclj.utils :as u] [clojure.string :as string])) (defn not-found [] (hp/html5 [:h1 "404 Error!"] [:b "Page not found!"] [:p [:a {:href ".."} "Return to main page"]])) ;;........................................................................ ;; nav ;;........................................................................ (defn nav [conf data] [:div.uk-navbar-container {:uk-navbar ""} [:div.uk-navbar-center [:ul.uk-navbar-nav [:li [:a {:target "_blank" :href "https://gitlab1.ptb.de/vaclab/repliclj"} "gitlab"]] [:li [:a {:target "_blank" :href "http://a75438:5601/app/discover#/view/6fde0090-06ff-11ec-a0ed-9fa5b8b37aed"} "elasticsearch"]] [:li [:a { :target "_blank" :href "https://docs.couchdb.org/en/main/replication/index.html"} "repli docu"]]]]]) ;;........................................................................ ;; table ;;........................................................................ (defn table-row [m] [:tr [:td (u/url->db (:source m))] [:td (u/url->db (:target m))] [:td (u/url->host-name (:target m))] [:td (:state m)] [:td (:changes_pending (:info m))] [:td (:error_count m)] [:td (u/nice-date (:start_time m))] [:td (u/nice-date (:last_updated m))] [:td [:a {:target "_blank" :uk-icon "link" :href (u/repli-doc-link m)}]]]) (defn table [v] [:table.uk-table.uk-table-hover.uk-table-striped [:thead [:tr [:th "source db"] [:th "target db"] [:th "target host"] [:th "status"] [:th {:uk-tooltip "pending changes"} "pc"] [:th {:uk-tooltip "error count"} "ec"] [:th "start time"] [:th "last updated"] [:th.uk-table-shrink "doc"]]] (into [:tbody] (map table-row v))]) (defn state-summary [v] (into [:span.uk-text-muted.uk-text-center] (mapv (fn [[state number]] (str state ":&nbsp;"number "&nbsp;&nbsp;&nbsp;")) (frequencies (mapv :state v))))) (defn db-info [v] (into [:ul.uk-breadcrumb] (mapv (fn [db] [:li [:span (:key db) "&nbsp;"] [:span.uk-badge (:doc_count (:info db))]]) v))) (defn li [m] (let [data (:docs m) sum (state-summary data)] [:li [:div.uk-accordion-title {:uk-grid ""} [:div.uk-text-muted.uk-text-left (if (seq data) sum "no data")] [:div.uk-width-expand.uk-grid-column-medium.uk-text-right (:alias m) [:span.uk-text-muted (u/host->host-name (:server m))]]] (when (seq data) [:div.uk-accordion-content (db-info (:db-info m)) (table data)])])) (defn accord [conf data] (into [:ul {:uk-accordion ""}] (mapv li data))) ;;........................................................................ ;; body ;;........................................................................ (defn body [conf data content libs] (into [:body#body (nav conf data) [:div.uk-container.uk-padding.uk-margin [:article.uk-article [:h4.uk-article-title.uk-text-uppercase.uk-heading-line.uk-text-center.uk-text-muted [:a.uk-link-reset {:href ""} "replication state"]] [:p.uk-article-meta (u/date)] [:p.uk-text-lead content]]]] libs)) ;;........................................................................ ;; head ;;........................................................................ (defn head [conf data] [:head [:title "repliclj"] [:meta {:charset "utf-8"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1"}] (hp/include-css "/css/uikit.css")]) ;;........................................................................ ;; index ;;........................................................................ (defn index [conf data] (hp/html5 (head conf data) (body conf data (accord conf data) [(hp/include-js "/js/uikit.js") (hp/include-js "/js/uikit-icons.js")])))
true
(ns repliclj.page ^{:author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>" :doc "Simple replication state overview page delivered by server.clj."} (:require [hiccup.form :as hf] [hiccup.page :as hp] [repliclj.utils :as u] [clojure.string :as string])) (defn not-found [] (hp/html5 [:h1 "404 Error!"] [:b "Page not found!"] [:p [:a {:href ".."} "Return to main page"]])) ;;........................................................................ ;; nav ;;........................................................................ (defn nav [conf data] [:div.uk-navbar-container {:uk-navbar ""} [:div.uk-navbar-center [:ul.uk-navbar-nav [:li [:a {:target "_blank" :href "https://gitlab1.ptb.de/vaclab/repliclj"} "gitlab"]] [:li [:a {:target "_blank" :href "http://a75438:5601/app/discover#/view/6fde0090-06ff-11ec-a0ed-9fa5b8b37aed"} "elasticsearch"]] [:li [:a { :target "_blank" :href "https://docs.couchdb.org/en/main/replication/index.html"} "repli docu"]]]]]) ;;........................................................................ ;; table ;;........................................................................ (defn table-row [m] [:tr [:td (u/url->db (:source m))] [:td (u/url->db (:target m))] [:td (u/url->host-name (:target m))] [:td (:state m)] [:td (:changes_pending (:info m))] [:td (:error_count m)] [:td (u/nice-date (:start_time m))] [:td (u/nice-date (:last_updated m))] [:td [:a {:target "_blank" :uk-icon "link" :href (u/repli-doc-link m)}]]]) (defn table [v] [:table.uk-table.uk-table-hover.uk-table-striped [:thead [:tr [:th "source db"] [:th "target db"] [:th "target host"] [:th "status"] [:th {:uk-tooltip "pending changes"} "pc"] [:th {:uk-tooltip "error count"} "ec"] [:th "start time"] [:th "last updated"] [:th.uk-table-shrink "doc"]]] (into [:tbody] (map table-row v))]) (defn state-summary [v] (into [:span.uk-text-muted.uk-text-center] (mapv (fn [[state number]] (str state ":&nbsp;"number "&nbsp;&nbsp;&nbsp;")) (frequencies (mapv :state v))))) (defn db-info [v] (into [:ul.uk-breadcrumb] (mapv (fn [db] [:li [:span (:key db) "&nbsp;"] [:span.uk-badge (:doc_count (:info db))]]) v))) (defn li [m] (let [data (:docs m) sum (state-summary data)] [:li [:div.uk-accordion-title {:uk-grid ""} [:div.uk-text-muted.uk-text-left (if (seq data) sum "no data")] [:div.uk-width-expand.uk-grid-column-medium.uk-text-right (:alias m) [:span.uk-text-muted (u/host->host-name (:server m))]]] (when (seq data) [:div.uk-accordion-content (db-info (:db-info m)) (table data)])])) (defn accord [conf data] (into [:ul {:uk-accordion ""}] (mapv li data))) ;;........................................................................ ;; body ;;........................................................................ (defn body [conf data content libs] (into [:body#body (nav conf data) [:div.uk-container.uk-padding.uk-margin [:article.uk-article [:h4.uk-article-title.uk-text-uppercase.uk-heading-line.uk-text-center.uk-text-muted [:a.uk-link-reset {:href ""} "replication state"]] [:p.uk-article-meta (u/date)] [:p.uk-text-lead content]]]] libs)) ;;........................................................................ ;; head ;;........................................................................ (defn head [conf data] [:head [:title "repliclj"] [:meta {:charset "utf-8"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1"}] (hp/include-css "/css/uikit.css")]) ;;........................................................................ ;; index ;;........................................................................ (defn index [conf data] (hp/html5 (head conf data) (body conf data (accord conf data) [(hp/include-js "/js/uikit.js") (hp/include-js "/js/uikit-icons.js")])))
[ { "context": "st \"localhost\", :user \"Administrator\", :password \"password\", :definitions \"{\\\"tables\\\":[{\\\"name\\\": \\\"order\\\"", "end": 1970, "score": 0.9996488094329834, "start": 1962, "tag": "PASSWORD", "value": "password" } ]
test/metabase/driver/couchbase/query_processor_test.clj
xavierchow/metabase-couchbase-driver
7
(ns metabase.driver.couchbase.query-processor-test (:require [metabase.driver.couchbase.query-processor :as cqp] [metabase.query-processor.store :as qp.store] [clojure.test :refer [deftest testing is]])) (def basic-query {:database 5, :query {:source-table 11, :fields [[:field-id 47] [:field-id 48] [:field-id 49]], :limit 2000}, :type :query}) (def agg-query {:database 5, :query {:source-table 11, :aggregation [[:aggregation-options [:count] {:name "count"}]], :breakout [[:field-id 49]], :order-by [[:asc [:field-id 49]]]}}) ;; :aggregation [[:aggregation-options [:sum [:field 54 nil]] {:name "sum"}]] ;; :aggregation [[:aggregation-options [:sum [:field 54 nil]] {:name "sum"}] [:aggregation-options [:count] {:name "count"}]] (def agg-multiple-query {:database 5, :query {:source-table 11, :aggregation [[:aggregation-options [:count] {:name "count"}]], :breakout [[:field-id 49] [:field-id 48]], :order-by [[:asc [:field-id 49]] [:asc [:field-id 48]]]}}) (def agg-multiple-break-options {:database 5, :query {:source-table 11, :aggregation [[:aggregation-options [:sum [:field 49 nil]] {:name "sum"}] [:aggregation-options [:count] {:name "count"}]] :breakout [[:field-id 49] [:field-id 48]], :order-by [[:asc [:field-id 49]] [:asc [:field-id 48]]]}}) (def database {:details {:dbname "test-bucket", :host "localhost", :user "Administrator", :password "password", :definitions "{\"tables\":[{\"name\": \"order\", \"schema\": \"Order\", \"fields\": [ { \"name\": \"id\", \"type\": \"string\",\"database-position\": 0, \"pk?\": true}, { \"name\": \"type\", \"type\": \"string\",\"database-position\": 1 }, { \"name\": \"state\", \"type\": \"string\",\"database-position\": 2 }]}]}"}}) (deftest query-processor (testing "mbql->native" (with-redefs [qp.store/database (fn [] database) qp.store/table (fn [_] {:name "order"}) qp.store/field (fn [id] (case id 47 {:name "id" :special_type :type/PK} 48 {:name "type"} 49 {:name "state"}))] (is (= {:query "SELECT Meta().`id`,b.type AS type,b.state AS state FROM `test-bucket` b WHERE _type = \"Order\" LIMIT 2000;" :cols ["id" "type" "state"] :mbql? true} (cqp/mbql->native basic-query))))) (testing "mbql->native agg" (with-redefs [qp.store/database (fn [] database) qp.store/table (fn [_] {:name "order"}) qp.store/field (fn [id] (case id 48 {:name "type"} 49 {:name "state"}))] (is (= {:query "SELECT COUNT(*) count, b.state AS state FROM `test-bucket` b WHERE _type = \"Order\" GROUP BY b.state" :cols ["state" "count"] :mbql? true} (cqp/mbql->native agg-query))))) (testing "mbql->native multiple-agg" (with-redefs [qp.store/database (fn [] database) qp.store/table (fn [_] {:name "order"}) qp.store/field (fn [id] (case id 48 {:name "type"} 49 {:name "state"}))] (is (= {:query "SELECT COUNT(*) count, b.state AS state, b.type AS type FROM `test-bucket` b WHERE _type = \"Order\" GROUP BY b.state, b.type" :cols ["state" "type" "count"] :mbql? true} (cqp/mbql->native agg-multiple-query))) (is (= {:query "SELECT SUM(state) sum, COUNT(*) count, b.state AS state, b.type AS type FROM `test-bucket` b WHERE _type = \"Order\" GROUP BY b.state, b.type" :cols ["state" "type" "sum" "count"] :mbql? true} (cqp/mbql->native agg-multiple-break-options))))) (testing "aggregation-options-n1ql" (with-redefs [qp.store/field (fn [id] (case id 49 {:name "state"}))] (is (= {:name "count" :n1ql "COUNT(*) count"} (cqp/aggregation-options-n1ql [:aggregation-options [:count] {:name "count"}]) )) (is (= {:name "sum" :n1ql "SUM(state) sum"} (cqp/aggregation-options-n1ql [:aggregation-options [:sum [:field 49 nil]] {:name "sum"}]) )))) (testing "aggregation-ns-n1ql" (with-redefs [qp.store/field (fn [id] (case id 49 {:name "state"}))] (is (= {:name ["count"] :n1ql "COUNT(*) count, "} (cqp/aggregation-n1ql [[:aggregation-options [:count] {:name "count"}]]) )) (is (= {:name ["count" "sum"] :n1ql "COUNT(*) count, SUM(state) sum, "} (cqp/aggregation-n1ql [[:aggregation-options [:count] {:name "count"}] [:aggregation-options [:sum [:field 49 nil]] {:name "sum"}] ]) )) )) (testing "where-clause" (is (= "WHERE _type = \"foo\" " (cqp/where-clause {:schema "foo"} nil))) (is (= "WHERE type = \"foo\" " (cqp/where-clause {:schema "type:foo"} nil)))) (testing "normalize-col" (is (= "foo" (cqp/normalize-col {:name "foo"}))) (is (= "foo_bar" (cqp/normalize-col {:name "foo.bar"}))) (is (= "foo0_bar" (cqp/normalize-col {:name "foo[0].bar"}))) (is (= "foo_bar" (cqp/normalize-col {:name "`foo`.bar"})))))
73539
(ns metabase.driver.couchbase.query-processor-test (:require [metabase.driver.couchbase.query-processor :as cqp] [metabase.query-processor.store :as qp.store] [clojure.test :refer [deftest testing is]])) (def basic-query {:database 5, :query {:source-table 11, :fields [[:field-id 47] [:field-id 48] [:field-id 49]], :limit 2000}, :type :query}) (def agg-query {:database 5, :query {:source-table 11, :aggregation [[:aggregation-options [:count] {:name "count"}]], :breakout [[:field-id 49]], :order-by [[:asc [:field-id 49]]]}}) ;; :aggregation [[:aggregation-options [:sum [:field 54 nil]] {:name "sum"}]] ;; :aggregation [[:aggregation-options [:sum [:field 54 nil]] {:name "sum"}] [:aggregation-options [:count] {:name "count"}]] (def agg-multiple-query {:database 5, :query {:source-table 11, :aggregation [[:aggregation-options [:count] {:name "count"}]], :breakout [[:field-id 49] [:field-id 48]], :order-by [[:asc [:field-id 49]] [:asc [:field-id 48]]]}}) (def agg-multiple-break-options {:database 5, :query {:source-table 11, :aggregation [[:aggregation-options [:sum [:field 49 nil]] {:name "sum"}] [:aggregation-options [:count] {:name "count"}]] :breakout [[:field-id 49] [:field-id 48]], :order-by [[:asc [:field-id 49]] [:asc [:field-id 48]]]}}) (def database {:details {:dbname "test-bucket", :host "localhost", :user "Administrator", :password "<PASSWORD>", :definitions "{\"tables\":[{\"name\": \"order\", \"schema\": \"Order\", \"fields\": [ { \"name\": \"id\", \"type\": \"string\",\"database-position\": 0, \"pk?\": true}, { \"name\": \"type\", \"type\": \"string\",\"database-position\": 1 }, { \"name\": \"state\", \"type\": \"string\",\"database-position\": 2 }]}]}"}}) (deftest query-processor (testing "mbql->native" (with-redefs [qp.store/database (fn [] database) qp.store/table (fn [_] {:name "order"}) qp.store/field (fn [id] (case id 47 {:name "id" :special_type :type/PK} 48 {:name "type"} 49 {:name "state"}))] (is (= {:query "SELECT Meta().`id`,b.type AS type,b.state AS state FROM `test-bucket` b WHERE _type = \"Order\" LIMIT 2000;" :cols ["id" "type" "state"] :mbql? true} (cqp/mbql->native basic-query))))) (testing "mbql->native agg" (with-redefs [qp.store/database (fn [] database) qp.store/table (fn [_] {:name "order"}) qp.store/field (fn [id] (case id 48 {:name "type"} 49 {:name "state"}))] (is (= {:query "SELECT COUNT(*) count, b.state AS state FROM `test-bucket` b WHERE _type = \"Order\" GROUP BY b.state" :cols ["state" "count"] :mbql? true} (cqp/mbql->native agg-query))))) (testing "mbql->native multiple-agg" (with-redefs [qp.store/database (fn [] database) qp.store/table (fn [_] {:name "order"}) qp.store/field (fn [id] (case id 48 {:name "type"} 49 {:name "state"}))] (is (= {:query "SELECT COUNT(*) count, b.state AS state, b.type AS type FROM `test-bucket` b WHERE _type = \"Order\" GROUP BY b.state, b.type" :cols ["state" "type" "count"] :mbql? true} (cqp/mbql->native agg-multiple-query))) (is (= {:query "SELECT SUM(state) sum, COUNT(*) count, b.state AS state, b.type AS type FROM `test-bucket` b WHERE _type = \"Order\" GROUP BY b.state, b.type" :cols ["state" "type" "sum" "count"] :mbql? true} (cqp/mbql->native agg-multiple-break-options))))) (testing "aggregation-options-n1ql" (with-redefs [qp.store/field (fn [id] (case id 49 {:name "state"}))] (is (= {:name "count" :n1ql "COUNT(*) count"} (cqp/aggregation-options-n1ql [:aggregation-options [:count] {:name "count"}]) )) (is (= {:name "sum" :n1ql "SUM(state) sum"} (cqp/aggregation-options-n1ql [:aggregation-options [:sum [:field 49 nil]] {:name "sum"}]) )))) (testing "aggregation-ns-n1ql" (with-redefs [qp.store/field (fn [id] (case id 49 {:name "state"}))] (is (= {:name ["count"] :n1ql "COUNT(*) count, "} (cqp/aggregation-n1ql [[:aggregation-options [:count] {:name "count"}]]) )) (is (= {:name ["count" "sum"] :n1ql "COUNT(*) count, SUM(state) sum, "} (cqp/aggregation-n1ql [[:aggregation-options [:count] {:name "count"}] [:aggregation-options [:sum [:field 49 nil]] {:name "sum"}] ]) )) )) (testing "where-clause" (is (= "WHERE _type = \"foo\" " (cqp/where-clause {:schema "foo"} nil))) (is (= "WHERE type = \"foo\" " (cqp/where-clause {:schema "type:foo"} nil)))) (testing "normalize-col" (is (= "foo" (cqp/normalize-col {:name "foo"}))) (is (= "foo_bar" (cqp/normalize-col {:name "foo.bar"}))) (is (= "foo0_bar" (cqp/normalize-col {:name "foo[0].bar"}))) (is (= "foo_bar" (cqp/normalize-col {:name "`foo`.bar"})))))
true
(ns metabase.driver.couchbase.query-processor-test (:require [metabase.driver.couchbase.query-processor :as cqp] [metabase.query-processor.store :as qp.store] [clojure.test :refer [deftest testing is]])) (def basic-query {:database 5, :query {:source-table 11, :fields [[:field-id 47] [:field-id 48] [:field-id 49]], :limit 2000}, :type :query}) (def agg-query {:database 5, :query {:source-table 11, :aggregation [[:aggregation-options [:count] {:name "count"}]], :breakout [[:field-id 49]], :order-by [[:asc [:field-id 49]]]}}) ;; :aggregation [[:aggregation-options [:sum [:field 54 nil]] {:name "sum"}]] ;; :aggregation [[:aggregation-options [:sum [:field 54 nil]] {:name "sum"}] [:aggregation-options [:count] {:name "count"}]] (def agg-multiple-query {:database 5, :query {:source-table 11, :aggregation [[:aggregation-options [:count] {:name "count"}]], :breakout [[:field-id 49] [:field-id 48]], :order-by [[:asc [:field-id 49]] [:asc [:field-id 48]]]}}) (def agg-multiple-break-options {:database 5, :query {:source-table 11, :aggregation [[:aggregation-options [:sum [:field 49 nil]] {:name "sum"}] [:aggregation-options [:count] {:name "count"}]] :breakout [[:field-id 49] [:field-id 48]], :order-by [[:asc [:field-id 49]] [:asc [:field-id 48]]]}}) (def database {:details {:dbname "test-bucket", :host "localhost", :user "Administrator", :password "PI:PASSWORD:<PASSWORD>END_PI", :definitions "{\"tables\":[{\"name\": \"order\", \"schema\": \"Order\", \"fields\": [ { \"name\": \"id\", \"type\": \"string\",\"database-position\": 0, \"pk?\": true}, { \"name\": \"type\", \"type\": \"string\",\"database-position\": 1 }, { \"name\": \"state\", \"type\": \"string\",\"database-position\": 2 }]}]}"}}) (deftest query-processor (testing "mbql->native" (with-redefs [qp.store/database (fn [] database) qp.store/table (fn [_] {:name "order"}) qp.store/field (fn [id] (case id 47 {:name "id" :special_type :type/PK} 48 {:name "type"} 49 {:name "state"}))] (is (= {:query "SELECT Meta().`id`,b.type AS type,b.state AS state FROM `test-bucket` b WHERE _type = \"Order\" LIMIT 2000;" :cols ["id" "type" "state"] :mbql? true} (cqp/mbql->native basic-query))))) (testing "mbql->native agg" (with-redefs [qp.store/database (fn [] database) qp.store/table (fn [_] {:name "order"}) qp.store/field (fn [id] (case id 48 {:name "type"} 49 {:name "state"}))] (is (= {:query "SELECT COUNT(*) count, b.state AS state FROM `test-bucket` b WHERE _type = \"Order\" GROUP BY b.state" :cols ["state" "count"] :mbql? true} (cqp/mbql->native agg-query))))) (testing "mbql->native multiple-agg" (with-redefs [qp.store/database (fn [] database) qp.store/table (fn [_] {:name "order"}) qp.store/field (fn [id] (case id 48 {:name "type"} 49 {:name "state"}))] (is (= {:query "SELECT COUNT(*) count, b.state AS state, b.type AS type FROM `test-bucket` b WHERE _type = \"Order\" GROUP BY b.state, b.type" :cols ["state" "type" "count"] :mbql? true} (cqp/mbql->native agg-multiple-query))) (is (= {:query "SELECT SUM(state) sum, COUNT(*) count, b.state AS state, b.type AS type FROM `test-bucket` b WHERE _type = \"Order\" GROUP BY b.state, b.type" :cols ["state" "type" "sum" "count"] :mbql? true} (cqp/mbql->native agg-multiple-break-options))))) (testing "aggregation-options-n1ql" (with-redefs [qp.store/field (fn [id] (case id 49 {:name "state"}))] (is (= {:name "count" :n1ql "COUNT(*) count"} (cqp/aggregation-options-n1ql [:aggregation-options [:count] {:name "count"}]) )) (is (= {:name "sum" :n1ql "SUM(state) sum"} (cqp/aggregation-options-n1ql [:aggregation-options [:sum [:field 49 nil]] {:name "sum"}]) )))) (testing "aggregation-ns-n1ql" (with-redefs [qp.store/field (fn [id] (case id 49 {:name "state"}))] (is (= {:name ["count"] :n1ql "COUNT(*) count, "} (cqp/aggregation-n1ql [[:aggregation-options [:count] {:name "count"}]]) )) (is (= {:name ["count" "sum"] :n1ql "COUNT(*) count, SUM(state) sum, "} (cqp/aggregation-n1ql [[:aggregation-options [:count] {:name "count"}] [:aggregation-options [:sum [:field 49 nil]] {:name "sum"}] ]) )) )) (testing "where-clause" (is (= "WHERE _type = \"foo\" " (cqp/where-clause {:schema "foo"} nil))) (is (= "WHERE type = \"foo\" " (cqp/where-clause {:schema "type:foo"} nil)))) (testing "normalize-col" (is (= "foo" (cqp/normalize-col {:name "foo"}))) (is (= "foo_bar" (cqp/normalize-col {:name "foo.bar"}))) (is (= "foo0_bar" (cqp/normalize-col {:name "foo[0].bar"}))) (is (= "foo_bar" (cqp/normalize-col {:name "`foo`.bar"})))))
[ { "context": "\n (are [x y] (= x y)\n true (satisfy-rfc-822? \"foo@foo.com\")\n true (satisfy-rfc-822? \"foo@foocom\")\n tr", "end": 248, "score": 0.999734103679657, "start": 237, "tag": "EMAIL", "value": "foo@foo.com" }, { "context": "c-822? \"foo@foo.com\")\n true (satisfy-rfc-822? \"foo@foocom\")\n true (satisfy-rfc-822? \"fo.o@foo.com\")\n ", "end": 289, "score": 0.9763464331626892, "start": 279, "tag": "EMAIL", "value": "foo@foocom" }, { "context": "fc-822? \"foo@foocom\")\n true (satisfy-rfc-822? \"fo.o@foo.com\")\n false (satisfy-rfc-822? \".foo@foo.com\")\n ", "end": 332, "score": 0.9997186064720154, "start": 320, "tag": "EMAIL", "value": "fo.o@foo.com" }, { "context": "c-822? \"fo.o@foo.com\")\n false (satisfy-rfc-822? \".foo@foo.com\")\n false (satisfy-rfc-822? \"fo..o@foo.com\")\n ", "end": 376, "score": 0.9993757605552673, "start": 363, "tag": "EMAIL", "value": "\".foo@foo.com" }, { "context": "822? \".foo@foo.com\")\n false (satisfy-rfc-822? \"fo..o@foo.com\")\n false (satisfy-rfc-822? \"foo.@foo.com\")))\n\n", "end": 421, "score": 0.9996500015258789, "start": 408, "tag": "EMAIL", "value": "fo..o@foo.com" }, { "context": "22? \"fo..o@foo.com\")\n false (satisfy-rfc-822? \"foo.@foo.com\")))\n\n(deftest quote-email-test\n (are [x y] (= x ", "end": 465, "score": 0.9995954632759094, "start": 453, "tag": "EMAIL", "value": "foo.@foo.com" }, { "context": "eftest quote-email-test\n (are [x y] (= x y)\n \"foo@foo.com\" (quote-email \"foo@foo.com\")\n \"foo@foocom\" (qu", "end": 534, "score": 0.9996881484985352, "start": 523, "tag": "EMAIL", "value": "foo@foo.com" }, { "context": "are [x y] (= x y)\n \"foo@foo.com\" (quote-email \"foo@foo.com\")\n \"foo@foocom\" (quote-email \"foo@foocom\")\n ", "end": 561, "score": 0.9996765851974487, "start": 550, "tag": "EMAIL", "value": "foo@foo.com" }, { "context": "@foo.com\" (quote-email \"foo@foo.com\")\n \"foo@foocom\" (quote-email \"foo@foocom\")\n \"fo.o@foo.com\" (q", "end": 579, "score": 0.6066287755966187, "start": 576, "tag": "EMAIL", "value": "com" }, { "context": "o@foo.com\")\n \"foo@foocom\" (quote-email \"foo@foocom\")\n \"fo.o@foo.com\" (quote-email \"fo.o@foo.com\")", "end": 605, "score": 0.6917557120323181, "start": 602, "tag": "EMAIL", "value": "com" }, { "context": "\n \"foo@foocom\" (quote-email \"foo@foocom\")\n \"fo.o@foo.com\" (quote-email \"fo.o@foo.com\")\n \"\\\".foo\\\"@foo.c", "end": 625, "score": 0.9997440576553345, "start": 613, "tag": "EMAIL", "value": "fo.o@foo.com" }, { "context": "il \"foo@foocom\")\n \"fo.o@foo.com\" (quote-email \"fo.o@foo.com\")\n \"\\\".foo\\\"@foo.com\" (quote-email \".foo@foo.c", "end": 653, "score": 0.9993267059326172, "start": 641, "tag": "EMAIL", "value": "fo.o@foo.com" }, { "context": "o.o@foo.com\" (quote-email \"fo.o@foo.com\")\n \"\\\".foo\\\"@foo.com\" (quote-email \".foo@foo.com\")\n \"\\\"fo", "end": 667, "score": 0.5054470300674438, "start": 664, "tag": "EMAIL", "value": "foo" }, { "context": "o.com\" (quote-email \"fo.o@foo.com\")\n \"\\\".foo\\\"@foo.com\" (quote-email \".foo@foo.com\")\n \"\\\"fo..o\\\"@foo.", "end": 677, "score": 0.9987595677375793, "start": 670, "tag": "EMAIL", "value": "foo.com" }, { "context": "fo.o@foo.com\")\n \"\\\".foo\\\"@foo.com\" (quote-email \".foo@foo.com\")\n \"\\\"fo..o\\\"@foo.com\" (quote-email \"fo..o@foo", "end": 705, "score": 0.9907823204994202, "start": 692, "tag": "EMAIL", "value": "\".foo@foo.com" }, { "context": "oo\\\"@foo.com\" (quote-email \".foo@foo.com\")\n \"\\\"fo..o\\\"@foo.com\" (quote-email \"fo..o@foo.com\")\n \"", "end": 717, "score": 0.865746259689331, "start": 715, "tag": "EMAIL", "value": "fo" }, { "context": "@foo.com\" (quote-email \".foo@foo.com\")\n \"\\\"fo..o\\\"@foo.com\" (quote-email \"fo..o@foo.com\")\n \"\\\"f", "end": 720, "score": 0.6431576609611511, "start": 719, "tag": "EMAIL", "value": "o" }, { "context": ".com\" (quote-email \".foo@foo.com\")\n \"\\\"fo..o\\\"@foo.com\" (quote-email \"fo..o@foo.com\")\n \"\\\"foo.\\\"@foo.", "end": 730, "score": 0.999277651309967, "start": 723, "tag": "EMAIL", "value": "foo.com" }, { "context": "o@foo.com\")\n \"\\\"fo..o\\\"@foo.com\" (quote-email \"fo..o@foo.com\")\n \"\\\"foo.\\\"@foo.com\" (quote-email \"foo.@foo.c", "end": 759, "score": 0.9994524121284485, "start": 746, "tag": "EMAIL", "value": "fo..o@foo.com" }, { "context": ".com\" (quote-email \"fo..o@foo.com\")\n \"\\\"foo.\\\"@foo.com\" (quote-email \"foo.@foo.com\")))\n\n(deftest unquote", "end": 783, "score": 0.9512381553649902, "start": 776, "tag": "EMAIL", "value": "foo.com" }, { "context": ".o@foo.com\")\n \"\\\"foo.\\\"@foo.com\" (quote-email \"foo.@foo.com\")))\n\n(deftest unquote-email-test\n (are [x y] (= ", "end": 811, "score": 0.9995700716972351, "start": 799, "tag": "EMAIL", "value": "foo.@foo.com" }, { "context": "test unquote-email-test\n (are [x y] (= x y)\n \"foo@foo.com\" (unquote-email \"foo@foo.com\")\n \"foo@foocom\" (", "end": 882, "score": 0.999505341053009, "start": 871, "tag": "EMAIL", "value": "foo@foo.com" }, { "context": "e [x y] (= x y)\n \"foo@foo.com\" (unquote-email \"foo@foo.com\")\n \"foo@foocom\" (unquote-email \"foo@foocom\")\n ", "end": 911, "score": 0.9994696378707886, "start": 900, "tag": "EMAIL", "value": "foo@foo.com" }, { "context": " \"foo@foocom\" (unquote-email \"foo@foocom\")\n \"fo.o@foo.com\" (unquote-email \"fo.o@foo.com\")\n \".foo@foo.com", "end": 977, "score": 0.9995128512382507, "start": 965, "tag": "EMAIL", "value": "fo.o@foo.com" }, { "context": " \"foo@foocom\")\n \"fo.o@foo.com\" (unquote-email \"fo.o@foo.com\")\n \".foo@foo.com\" (unquote-email \"\\\".foo\\\"@foo", "end": 1007, "score": 0.9996206164360046, "start": 995, "tag": "EMAIL", "value": "fo.o@foo.com" }, { "context": " \"fo.o@foo.com\" (unquote-email \"fo.o@foo.com\")\n \".foo@foo.com\" (unquote-email \"\\\".foo\\\"@foo.com\")\n \"fo..o@fo", "end": 1027, "score": 0.9864991307258606, "start": 1014, "tag": "EMAIL", "value": "\".foo@foo.com" }, { "context": "com\")\n \".foo@foo.com\" (unquote-email \"\\\".foo\\\"@foo.com\")\n \"fo..o@foo.com\" (unquote-email \"\\\"fo..o\\\"@f", "end": 1061, "score": 0.8895909786224365, "start": 1054, "tag": "EMAIL", "value": "foo.com" }, { "context": "@foo.com\" (unquote-email \"\\\".foo\\\"@foo.com\")\n \"fo..o@foo.com\" (unquote-email \"\\\"fo..o\\\"@foo.com\")\n \"foo.@fo", "end": 1082, "score": 0.9990905523300171, "start": 1069, "tag": "EMAIL", "value": "fo..o@foo.com" }, { "context": "\"@foo.com\")\n \"fo..o@foo.com\" (unquote-email \"\\\"fo..o\\\"@foo.com\")\n \"foo.@foo.com\" (unquote-email \"\\\"", "end": 1107, "score": 0.8935796618461609, "start": 1102, "tag": "EMAIL", "value": "fo..o" }, { "context": "om\")\n \"fo..o@foo.com\" (unquote-email \"\\\"fo..o\\\"@foo.com\")\n \"foo.@foo.com\" (unquote-email \"\\\"foo.\\\"@foo", "end": 1117, "score": 0.8822948932647705, "start": 1109, "tag": "EMAIL", "value": "@foo.com" }, { "context": "foo.com\" (unquote-email \"\\\"fo..o\\\"@foo.com\")\n \"foo.@foo.com\" (unquote-email \"\\\"foo.\\\"@foo.com\")))\n", "end": 1137, "score": 0.9992362856864929, "start": 1125, "tag": "EMAIL", "value": "foo.@foo.com" }, { "context": "\\\"@foo.com\")\n \"foo.@foo.com\" (unquote-email \"\\\"foo.\\\"@foo.com\")))\n", "end": 1160, "score": 0.9292970299720764, "start": 1157, "tag": "EMAIL", "value": "foo" }, { "context": "com\")\n \"foo.@foo.com\" (unquote-email \"\\\"foo.\\\"@foo.com\")))\n", "end": 1171, "score": 0.9967928528785706, "start": 1164, "tag": "EMAIL", "value": "foo.com" } ]
test/toyokumo/commons/email_test.clj
toyokumo/toyokumo-commons
0
(ns toyokumo.commons.email-test (:require [clojure.test :refer :all] [toyokumo.commons.email :refer [satisfy-rfc-822? quote-email unquote-email]])) (deftest satisfy-rfc-822?-test (are [x y] (= x y) true (satisfy-rfc-822? "foo@foo.com") true (satisfy-rfc-822? "foo@foocom") true (satisfy-rfc-822? "fo.o@foo.com") false (satisfy-rfc-822? ".foo@foo.com") false (satisfy-rfc-822? "fo..o@foo.com") false (satisfy-rfc-822? "foo.@foo.com"))) (deftest quote-email-test (are [x y] (= x y) "foo@foo.com" (quote-email "foo@foo.com") "foo@foocom" (quote-email "foo@foocom") "fo.o@foo.com" (quote-email "fo.o@foo.com") "\".foo\"@foo.com" (quote-email ".foo@foo.com") "\"fo..o\"@foo.com" (quote-email "fo..o@foo.com") "\"foo.\"@foo.com" (quote-email "foo.@foo.com"))) (deftest unquote-email-test (are [x y] (= x y) "foo@foo.com" (unquote-email "foo@foo.com") "foo@foocom" (unquote-email "foo@foocom") "fo.o@foo.com" (unquote-email "fo.o@foo.com") ".foo@foo.com" (unquote-email "\".foo\"@foo.com") "fo..o@foo.com" (unquote-email "\"fo..o\"@foo.com") "foo.@foo.com" (unquote-email "\"foo.\"@foo.com")))
2730
(ns toyokumo.commons.email-test (:require [clojure.test :refer :all] [toyokumo.commons.email :refer [satisfy-rfc-822? quote-email unquote-email]])) (deftest satisfy-rfc-822?-test (are [x y] (= x y) true (satisfy-rfc-822? "<EMAIL>") true (satisfy-rfc-822? "<EMAIL>") true (satisfy-rfc-822? "<EMAIL>") false (satisfy-rfc-822? <EMAIL>") false (satisfy-rfc-822? "<EMAIL>") false (satisfy-rfc-822? "<EMAIL>"))) (deftest quote-email-test (are [x y] (= x y) "<EMAIL>" (quote-email "<EMAIL>") "foo@foo<EMAIL>" (quote-email "foo@foo<EMAIL>") "<EMAIL>" (quote-email "<EMAIL>") "\".<EMAIL>\"@<EMAIL>" (quote-email <EMAIL>") "\"<EMAIL>..<EMAIL>\"@<EMAIL>" (quote-email "<EMAIL>") "\"foo.\"@<EMAIL>" (quote-email "<EMAIL>"))) (deftest unquote-email-test (are [x y] (= x y) "<EMAIL>" (unquote-email "<EMAIL>") "foo@foocom" (unquote-email "foo@foocom") "<EMAIL>" (unquote-email "<EMAIL>") <EMAIL>" (unquote-email "\".foo\"@<EMAIL>") "<EMAIL>" (unquote-email "\"<EMAIL>\"<EMAIL>") "<EMAIL>" (unquote-email "\"<EMAIL>.\"@<EMAIL>")))
true
(ns toyokumo.commons.email-test (:require [clojure.test :refer :all] [toyokumo.commons.email :refer [satisfy-rfc-822? quote-email unquote-email]])) (deftest satisfy-rfc-822?-test (are [x y] (= x y) true (satisfy-rfc-822? "PI:EMAIL:<EMAIL>END_PI") true (satisfy-rfc-822? "PI:EMAIL:<EMAIL>END_PI") true (satisfy-rfc-822? "PI:EMAIL:<EMAIL>END_PI") false (satisfy-rfc-822? PI:EMAIL:<EMAIL>END_PI") false (satisfy-rfc-822? "PI:EMAIL:<EMAIL>END_PI") false (satisfy-rfc-822? "PI:EMAIL:<EMAIL>END_PI"))) (deftest quote-email-test (are [x y] (= x y) "PI:EMAIL:<EMAIL>END_PI" (quote-email "PI:EMAIL:<EMAIL>END_PI") "foo@fooPI:EMAIL:<EMAIL>END_PI" (quote-email "foo@fooPI:EMAIL:<EMAIL>END_PI") "PI:EMAIL:<EMAIL>END_PI" (quote-email "PI:EMAIL:<EMAIL>END_PI") "\".PI:EMAIL:<EMAIL>END_PI\"@PI:EMAIL:<EMAIL>END_PI" (quote-email PI:EMAIL:<EMAIL>END_PI") "\"PI:EMAIL:<EMAIL>END_PI..PI:EMAIL:<EMAIL>END_PI\"@PI:EMAIL:<EMAIL>END_PI" (quote-email "PI:EMAIL:<EMAIL>END_PI") "\"foo.\"@PI:EMAIL:<EMAIL>END_PI" (quote-email "PI:EMAIL:<EMAIL>END_PI"))) (deftest unquote-email-test (are [x y] (= x y) "PI:EMAIL:<EMAIL>END_PI" (unquote-email "PI:EMAIL:<EMAIL>END_PI") "foo@foocom" (unquote-email "foo@foocom") "PI:EMAIL:<EMAIL>END_PI" (unquote-email "PI:EMAIL:<EMAIL>END_PI") PI:EMAIL:<EMAIL>END_PI" (unquote-email "\".foo\"@PI:EMAIL:<EMAIL>END_PI") "PI:EMAIL:<EMAIL>END_PI" (unquote-email "\"PI:EMAIL:<EMAIL>END_PI\"PI:EMAIL:<EMAIL>END_PI") "PI:EMAIL:<EMAIL>END_PI" (unquote-email "\"PI:EMAIL:<EMAIL>END_PI.\"@PI:EMAIL:<EMAIL>END_PI")))
[ { "context": "y for Clojure ***\")\n (println \"Copyright (C) 2018 Frederic Peschanski (fredokun) under the MIT License.\")\n (println \"-", "end": 426, "score": 0.9997233748435974, "start": 407, "tag": "NAME", "value": "Frederic Peschanski" }, { "context": "(println \"Copyright (C) 2018 Frederic Peschanski (fredokun) under the MIT License.\")\n (println \"----\"))\n\n(d", "end": 436, "score": 0.7969474792480469, "start": 428, "tag": "USERNAME", "value": "fredokun" } ]
src/latte/main.clj
latte-central/LaTTe
239
(ns latte.main "The entry point for LaTTe as a standalone tool. This is mainly for certifying the core library (target `certify`) but other functionalities are provided, like listing axioms, etc." (:require [latte.utils :as u] [latte.certify :as cert])) (defn run-header [] (println "*** LaTTe : a proof assistant library for Clojure ***") (println "Copyright (C) 2018 Frederic Peschanski (fredokun) under the MIT License.") (println "----")) (defn run-doc [library-name] (println "Available LaTTe commands:") (println " :certify | certify the" library-name "library (written in resources/cert)") (println " :clear-cert | clear the last certification (if any)") (println " :axioms [namespaces] | list all axioms in `namespaces`, or in whole" library-name "library if not specified") (println " :help | this message")) (defn require-all! [namespaces] (doseq [namesp namespaces] (require namesp))) (defn run-certify! [library-name namespaces] (require-all! namespaces) (cert/certify-library! library-name namespaces)) (defn run-clear-cert! [] (cert/clear-certification!)) (defn run-axioms! [args namespaces] ;; TODO: take args into account (require-all! namespaces) (let [axiom-map (into {} (map (fn [namesp] [namesp (map first (:axioms (u/fetch-ns-elements (the-ns namesp))))]) namespaces))] (println axiom-map)) ) (defn latte-main [args library-name namespaces] (run-header) (if args (case (first args) ":certify" (run-certify! library-name namespaces) ":clear-cert" (run-clear-cert!) ":axioms" (run-axioms! (rest args) namespaces) ":help" ;; does not understand (do (println "==> Does not understand: " (first args)) (run-doc library-name))) (run-doc "core")))
4530
(ns latte.main "The entry point for LaTTe as a standalone tool. This is mainly for certifying the core library (target `certify`) but other functionalities are provided, like listing axioms, etc." (:require [latte.utils :as u] [latte.certify :as cert])) (defn run-header [] (println "*** LaTTe : a proof assistant library for Clojure ***") (println "Copyright (C) 2018 <NAME> (fredokun) under the MIT License.") (println "----")) (defn run-doc [library-name] (println "Available LaTTe commands:") (println " :certify | certify the" library-name "library (written in resources/cert)") (println " :clear-cert | clear the last certification (if any)") (println " :axioms [namespaces] | list all axioms in `namespaces`, or in whole" library-name "library if not specified") (println " :help | this message")) (defn require-all! [namespaces] (doseq [namesp namespaces] (require namesp))) (defn run-certify! [library-name namespaces] (require-all! namespaces) (cert/certify-library! library-name namespaces)) (defn run-clear-cert! [] (cert/clear-certification!)) (defn run-axioms! [args namespaces] ;; TODO: take args into account (require-all! namespaces) (let [axiom-map (into {} (map (fn [namesp] [namesp (map first (:axioms (u/fetch-ns-elements (the-ns namesp))))]) namespaces))] (println axiom-map)) ) (defn latte-main [args library-name namespaces] (run-header) (if args (case (first args) ":certify" (run-certify! library-name namespaces) ":clear-cert" (run-clear-cert!) ":axioms" (run-axioms! (rest args) namespaces) ":help" ;; does not understand (do (println "==> Does not understand: " (first args)) (run-doc library-name))) (run-doc "core")))
true
(ns latte.main "The entry point for LaTTe as a standalone tool. This is mainly for certifying the core library (target `certify`) but other functionalities are provided, like listing axioms, etc." (:require [latte.utils :as u] [latte.certify :as cert])) (defn run-header [] (println "*** LaTTe : a proof assistant library for Clojure ***") (println "Copyright (C) 2018 PI:NAME:<NAME>END_PI (fredokun) under the MIT License.") (println "----")) (defn run-doc [library-name] (println "Available LaTTe commands:") (println " :certify | certify the" library-name "library (written in resources/cert)") (println " :clear-cert | clear the last certification (if any)") (println " :axioms [namespaces] | list all axioms in `namespaces`, or in whole" library-name "library if not specified") (println " :help | this message")) (defn require-all! [namespaces] (doseq [namesp namespaces] (require namesp))) (defn run-certify! [library-name namespaces] (require-all! namespaces) (cert/certify-library! library-name namespaces)) (defn run-clear-cert! [] (cert/clear-certification!)) (defn run-axioms! [args namespaces] ;; TODO: take args into account (require-all! namespaces) (let [axiom-map (into {} (map (fn [namesp] [namesp (map first (:axioms (u/fetch-ns-elements (the-ns namesp))))]) namespaces))] (println axiom-map)) ) (defn latte-main [args library-name namespaces] (run-header) (if args (case (first args) ":certify" (run-certify! library-name namespaces) ":clear-cert" (run-clear-cert!) ":axioms" (run-axioms! (rest args) namespaces) ":help" ;; does not understand (do (println "==> Does not understand: " (first args)) (run-doc library-name))) (run-doc "core")))
[ { "context": ";; Copyright (c) 2021 Thomas J. Otterson\n;; \n;; This software is released under the MIT Li", "end": 40, "score": 0.9998018145561218, "start": 22, "tag": "NAME", "value": "Thomas J. Otterson" } ]
src/barandis/euler/p5.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 5: ;; ;; 2520 is the smallest number that can be divided by each of the numbers from 1 ;; to 10 without any remainder. ;; ;; What is the smallest positive number that is evenly divisible by all of the ;; numbers from 1 to 20? ;; This is an LCM problem without using the term. Solution is an algorithm that ;; uses GCD to calculate the LCM of two numbers, then a `reduce` call applies ;; that algorithm to all numbers in a range. ;; ;; This solution can be run using `clojure -X:p5`. It will default to the 20 ;; target described in the problem. To run with another target, use `clojure ;; -X:p5 :target 10` or similar. (ns barandis.euler.p5) (defn- lcm-all "Calculates the least common multiple of all of the args." [& args] (letfn [(gcd [x y] (if (zero? y) x (recur y (mod x y)))) (lcm [x y] (/ (* x y) (gcd x y)))] (reduce lcm args))) (defn solve "Prints out the LCM of all positive integers up to (:target data). This number defaults to 20, which makes the return value the solution to Project Euler problem 5." ([] (solve {})) ([data] (-> (apply lcm-all (range 1 (inc (get data :target 20)))) println time)))
46310
;; Copyright (c) 2021 <NAME> ;; ;; This software is released under the MIT License. ;; https://opensource.org/licenses/MIT ;; Solves Project Euler problem 5: ;; ;; 2520 is the smallest number that can be divided by each of the numbers from 1 ;; to 10 without any remainder. ;; ;; What is the smallest positive number that is evenly divisible by all of the ;; numbers from 1 to 20? ;; This is an LCM problem without using the term. Solution is an algorithm that ;; uses GCD to calculate the LCM of two numbers, then a `reduce` call applies ;; that algorithm to all numbers in a range. ;; ;; This solution can be run using `clojure -X:p5`. It will default to the 20 ;; target described in the problem. To run with another target, use `clojure ;; -X:p5 :target 10` or similar. (ns barandis.euler.p5) (defn- lcm-all "Calculates the least common multiple of all of the args." [& args] (letfn [(gcd [x y] (if (zero? y) x (recur y (mod x y)))) (lcm [x y] (/ (* x y) (gcd x y)))] (reduce lcm args))) (defn solve "Prints out the LCM of all positive integers up to (:target data). This number defaults to 20, which makes the return value the solution to Project Euler problem 5." ([] (solve {})) ([data] (-> (apply lcm-all (range 1 (inc (get data :target 20)))) 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 5: ;; ;; 2520 is the smallest number that can be divided by each of the numbers from 1 ;; to 10 without any remainder. ;; ;; What is the smallest positive number that is evenly divisible by all of the ;; numbers from 1 to 20? ;; This is an LCM problem without using the term. Solution is an algorithm that ;; uses GCD to calculate the LCM of two numbers, then a `reduce` call applies ;; that algorithm to all numbers in a range. ;; ;; This solution can be run using `clojure -X:p5`. It will default to the 20 ;; target described in the problem. To run with another target, use `clojure ;; -X:p5 :target 10` or similar. (ns barandis.euler.p5) (defn- lcm-all "Calculates the least common multiple of all of the args." [& args] (letfn [(gcd [x y] (if (zero? y) x (recur y (mod x y)))) (lcm [x y] (/ (* x y) (gcd x y)))] (reduce lcm args))) (defn solve "Prints out the LCM of all positive integers up to (:target data). This number defaults to 20, which makes the return value the solution to Project Euler problem 5." ([] (solve {})) ([data] (-> (apply lcm-all (range 1 (inc (get data :target 20)))) println time)))
[ { "context": ";; Copyright (c) 2007-2013 Basho Technologies, Inc. All Rights Reserved.\n;;\n;; This file is pr", "end": 45, "score": 0.8612100481987, "start": 27, "tag": "NAME", "value": "Basho Technologies" } ]
client_tests/clojure/clj-s3/test/java_s3_tests/test/client.clj
bashoold/riak_cs
0
;; Copyright (c) 2007-2013 Basho Technologies, Inc. All Rights Reserved. ;; ;; This file is provided to you under the Apache License, ;; Version 2.0 (the "License"); you may not use this file ;; except in compliance with the License. You may obtain ;; a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, ;; software distributed under the License is distributed on an ;; "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ;; KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations ;; under the License. (ns java-s3-tests.test.client (:import java.security.MessageDigest org.apache.commons.codec.binary.Hex com.amazonaws.services.s3.model.AmazonS3Exception com.amazonaws.services.s3.model.ObjectMetadata com.amazonaws.services.s3.transfer.TransferManager com.amazonaws.services.s3.transfer.TransferManagerConfiguration) (:require [aws.sdk.s3 :as s3]) (:require [java-s3-tests.user-creation :as user-creation]) (:use midje.sweet)) (def ^:internal riak-cs-host-with-protocol "http://localhost") (def ^:internal riak-cs-host "localhost") (defn get-riak-cs-port-str "Try to get a TCP port number from the OS environment" [] (let [port-str (get (System/getenv) "CS_HTTP_PORT")] (cond (nil? port-str) "8080" :else port-str))) (defn get-riak-cs-port [] (Integer/parseInt (get-riak-cs-port-str) 10)) (defn md5-byte-array [input-byte-array] (let [instance (MessageDigest/getInstance "MD5")] (.digest instance input-byte-array))) (defn md5-string [input-byte-array] (let [b (md5-byte-array input-byte-array)] (String. (Hex/encodeHex b)))) (defn random-client [] (let [new-creds (user-creation/create-random-user riak-cs-host-with-protocol (get-riak-cs-port))] (s3/client (:key_id new-creds) (:key_secret new-creds) {:proxy-host riak-cs-host :proxy-port (get-riak-cs-port) :protocol :http}))) (defmacro with-random-client "Execute `form` with a random-client bound to `var-name`" [var-name form] `(let [~var-name (random-client)] ~form)) (defn random-string [] (str (java.util.UUID/randomUUID))) (defn write-file [filename content] (with-open [w (clojure.java.io/writer filename :append false)] (.write w content))) (defn etag-suffix [etag] (subs etag (- (count etag) 2))) (defn create-manager [c] (TransferManager. c)) (defn configure-manager [tm] (let [tm-config (.getConfiguration tm)] (.setMultipartUploadThreshold tm-config 19) (.setMinimumUploadPartSize tm-config 10) (.setConfiguration tm tm-config))) (defn create-and-configure-manager [c] (let [tm (create-manager c)] (configure-manager tm) tm)) (defn upload-file [tm bucket-name object-name file-name] (let [f (clojure.java.io/file file-name) u (.upload tm bucket-name object-name f)] (.waitForCompletion u) (.delete f))) (fact "bogus creds raises an exception" (let [bogus-client (s3/client "foo" "bar" {:endpoint (str "http://localhost:" (get-riak-cs-port-str))})] (s3/list-buckets bogus-client)) => (throws AmazonS3Exception)) (fact "new users have no buckets" (with-random-client c (s3/list-buckets c)) => []) (let [bucket-name (random-string)] (fact "creating a bucket should list one bucket in list buckets" (with-random-client c (do (s3/create-bucket c bucket-name) ((comp :name first) (s3/list-buckets c)))) => bucket-name)) (let [bucket-name (random-string) object-name (random-string)] (fact "simple put works" (with-random-client c (do (s3/create-bucket c bucket-name) (s3/put-object c bucket-name object-name "contents"))) => truthy)) (let [bucket-name (random-string) object-name (random-string) value "this is the value!"] (fact "the value received during GET is the same as the object that was PUT" (with-random-client c (do (s3/create-bucket c bucket-name) (s3/put-object c bucket-name object-name value) ((comp slurp :content) (s3/get-object c bucket-name object-name)))) => value)) (let [bucket-name (random-string) object-name (random-string) value "this is the value!" as-bytes (.getBytes value "UTF-8") md5-sum (md5-string as-bytes)] (fact "check that the etag of the response is the same as the md5 of the original object" (with-random-client c (do (s3/create-bucket c bucket-name) (s3/put-object c bucket-name object-name value) ((comp :etag :metadata) (s3/get-object c bucket-name object-name)))) => md5-sum)) (let [bucket-name (random-string) object-name (random-string) value (str "aaaaaaaaaa" "bbbbbbbbbb") file-name "./clj-mp-test.txt"] (fact "mulitpart upload works" (with-random-client c (do (s3/create-bucket c bucket-name) (let [tm (create-and-configure-manager c)] (write-file file-name value) (upload-file tm bucket-name object-name file-name) (let [fetched-object (s3/get-object c bucket-name object-name)] [((comp slurp :content) fetched-object) ((comp etag-suffix :etag :metadata) fetched-object)])))) => [value, "-2"])) (let [bucket-name (random-string) object-name (random-string) value "this is the real value" wrong-md5 "2945d7de2f70de5b8c0cb3fbcba4fe92"] (fact "Bad content md5 throws an exception" (with-random-client c (do (s3/create-bucket c bucket-name) (s3/put-object c bucket-name object-name value {:content-md5 wrong-md5}))) => (throws AmazonS3Exception)))
49205
;; Copyright (c) 2007-2013 <NAME>, Inc. All Rights Reserved. ;; ;; This file is provided to you under the Apache License, ;; Version 2.0 (the "License"); you may not use this file ;; except in compliance with the License. You may obtain ;; a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, ;; software distributed under the License is distributed on an ;; "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ;; KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations ;; under the License. (ns java-s3-tests.test.client (:import java.security.MessageDigest org.apache.commons.codec.binary.Hex com.amazonaws.services.s3.model.AmazonS3Exception com.amazonaws.services.s3.model.ObjectMetadata com.amazonaws.services.s3.transfer.TransferManager com.amazonaws.services.s3.transfer.TransferManagerConfiguration) (:require [aws.sdk.s3 :as s3]) (:require [java-s3-tests.user-creation :as user-creation]) (:use midje.sweet)) (def ^:internal riak-cs-host-with-protocol "http://localhost") (def ^:internal riak-cs-host "localhost") (defn get-riak-cs-port-str "Try to get a TCP port number from the OS environment" [] (let [port-str (get (System/getenv) "CS_HTTP_PORT")] (cond (nil? port-str) "8080" :else port-str))) (defn get-riak-cs-port [] (Integer/parseInt (get-riak-cs-port-str) 10)) (defn md5-byte-array [input-byte-array] (let [instance (MessageDigest/getInstance "MD5")] (.digest instance input-byte-array))) (defn md5-string [input-byte-array] (let [b (md5-byte-array input-byte-array)] (String. (Hex/encodeHex b)))) (defn random-client [] (let [new-creds (user-creation/create-random-user riak-cs-host-with-protocol (get-riak-cs-port))] (s3/client (:key_id new-creds) (:key_secret new-creds) {:proxy-host riak-cs-host :proxy-port (get-riak-cs-port) :protocol :http}))) (defmacro with-random-client "Execute `form` with a random-client bound to `var-name`" [var-name form] `(let [~var-name (random-client)] ~form)) (defn random-string [] (str (java.util.UUID/randomUUID))) (defn write-file [filename content] (with-open [w (clojure.java.io/writer filename :append false)] (.write w content))) (defn etag-suffix [etag] (subs etag (- (count etag) 2))) (defn create-manager [c] (TransferManager. c)) (defn configure-manager [tm] (let [tm-config (.getConfiguration tm)] (.setMultipartUploadThreshold tm-config 19) (.setMinimumUploadPartSize tm-config 10) (.setConfiguration tm tm-config))) (defn create-and-configure-manager [c] (let [tm (create-manager c)] (configure-manager tm) tm)) (defn upload-file [tm bucket-name object-name file-name] (let [f (clojure.java.io/file file-name) u (.upload tm bucket-name object-name f)] (.waitForCompletion u) (.delete f))) (fact "bogus creds raises an exception" (let [bogus-client (s3/client "foo" "bar" {:endpoint (str "http://localhost:" (get-riak-cs-port-str))})] (s3/list-buckets bogus-client)) => (throws AmazonS3Exception)) (fact "new users have no buckets" (with-random-client c (s3/list-buckets c)) => []) (let [bucket-name (random-string)] (fact "creating a bucket should list one bucket in list buckets" (with-random-client c (do (s3/create-bucket c bucket-name) ((comp :name first) (s3/list-buckets c)))) => bucket-name)) (let [bucket-name (random-string) object-name (random-string)] (fact "simple put works" (with-random-client c (do (s3/create-bucket c bucket-name) (s3/put-object c bucket-name object-name "contents"))) => truthy)) (let [bucket-name (random-string) object-name (random-string) value "this is the value!"] (fact "the value received during GET is the same as the object that was PUT" (with-random-client c (do (s3/create-bucket c bucket-name) (s3/put-object c bucket-name object-name value) ((comp slurp :content) (s3/get-object c bucket-name object-name)))) => value)) (let [bucket-name (random-string) object-name (random-string) value "this is the value!" as-bytes (.getBytes value "UTF-8") md5-sum (md5-string as-bytes)] (fact "check that the etag of the response is the same as the md5 of the original object" (with-random-client c (do (s3/create-bucket c bucket-name) (s3/put-object c bucket-name object-name value) ((comp :etag :metadata) (s3/get-object c bucket-name object-name)))) => md5-sum)) (let [bucket-name (random-string) object-name (random-string) value (str "aaaaaaaaaa" "bbbbbbbbbb") file-name "./clj-mp-test.txt"] (fact "mulitpart upload works" (with-random-client c (do (s3/create-bucket c bucket-name) (let [tm (create-and-configure-manager c)] (write-file file-name value) (upload-file tm bucket-name object-name file-name) (let [fetched-object (s3/get-object c bucket-name object-name)] [((comp slurp :content) fetched-object) ((comp etag-suffix :etag :metadata) fetched-object)])))) => [value, "-2"])) (let [bucket-name (random-string) object-name (random-string) value "this is the real value" wrong-md5 "2945d7de2f70de5b8c0cb3fbcba4fe92"] (fact "Bad content md5 throws an exception" (with-random-client c (do (s3/create-bucket c bucket-name) (s3/put-object c bucket-name object-name value {:content-md5 wrong-md5}))) => (throws AmazonS3Exception)))
true
;; Copyright (c) 2007-2013 PI:NAME:<NAME>END_PI, Inc. All Rights Reserved. ;; ;; This file is provided to you under the Apache License, ;; Version 2.0 (the "License"); you may not use this file ;; except in compliance with the License. You may obtain ;; a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, ;; software distributed under the License is distributed on an ;; "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ;; KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations ;; under the License. (ns java-s3-tests.test.client (:import java.security.MessageDigest org.apache.commons.codec.binary.Hex com.amazonaws.services.s3.model.AmazonS3Exception com.amazonaws.services.s3.model.ObjectMetadata com.amazonaws.services.s3.transfer.TransferManager com.amazonaws.services.s3.transfer.TransferManagerConfiguration) (:require [aws.sdk.s3 :as s3]) (:require [java-s3-tests.user-creation :as user-creation]) (:use midje.sweet)) (def ^:internal riak-cs-host-with-protocol "http://localhost") (def ^:internal riak-cs-host "localhost") (defn get-riak-cs-port-str "Try to get a TCP port number from the OS environment" [] (let [port-str (get (System/getenv) "CS_HTTP_PORT")] (cond (nil? port-str) "8080" :else port-str))) (defn get-riak-cs-port [] (Integer/parseInt (get-riak-cs-port-str) 10)) (defn md5-byte-array [input-byte-array] (let [instance (MessageDigest/getInstance "MD5")] (.digest instance input-byte-array))) (defn md5-string [input-byte-array] (let [b (md5-byte-array input-byte-array)] (String. (Hex/encodeHex b)))) (defn random-client [] (let [new-creds (user-creation/create-random-user riak-cs-host-with-protocol (get-riak-cs-port))] (s3/client (:key_id new-creds) (:key_secret new-creds) {:proxy-host riak-cs-host :proxy-port (get-riak-cs-port) :protocol :http}))) (defmacro with-random-client "Execute `form` with a random-client bound to `var-name`" [var-name form] `(let [~var-name (random-client)] ~form)) (defn random-string [] (str (java.util.UUID/randomUUID))) (defn write-file [filename content] (with-open [w (clojure.java.io/writer filename :append false)] (.write w content))) (defn etag-suffix [etag] (subs etag (- (count etag) 2))) (defn create-manager [c] (TransferManager. c)) (defn configure-manager [tm] (let [tm-config (.getConfiguration tm)] (.setMultipartUploadThreshold tm-config 19) (.setMinimumUploadPartSize tm-config 10) (.setConfiguration tm tm-config))) (defn create-and-configure-manager [c] (let [tm (create-manager c)] (configure-manager tm) tm)) (defn upload-file [tm bucket-name object-name file-name] (let [f (clojure.java.io/file file-name) u (.upload tm bucket-name object-name f)] (.waitForCompletion u) (.delete f))) (fact "bogus creds raises an exception" (let [bogus-client (s3/client "foo" "bar" {:endpoint (str "http://localhost:" (get-riak-cs-port-str))})] (s3/list-buckets bogus-client)) => (throws AmazonS3Exception)) (fact "new users have no buckets" (with-random-client c (s3/list-buckets c)) => []) (let [bucket-name (random-string)] (fact "creating a bucket should list one bucket in list buckets" (with-random-client c (do (s3/create-bucket c bucket-name) ((comp :name first) (s3/list-buckets c)))) => bucket-name)) (let [bucket-name (random-string) object-name (random-string)] (fact "simple put works" (with-random-client c (do (s3/create-bucket c bucket-name) (s3/put-object c bucket-name object-name "contents"))) => truthy)) (let [bucket-name (random-string) object-name (random-string) value "this is the value!"] (fact "the value received during GET is the same as the object that was PUT" (with-random-client c (do (s3/create-bucket c bucket-name) (s3/put-object c bucket-name object-name value) ((comp slurp :content) (s3/get-object c bucket-name object-name)))) => value)) (let [bucket-name (random-string) object-name (random-string) value "this is the value!" as-bytes (.getBytes value "UTF-8") md5-sum (md5-string as-bytes)] (fact "check that the etag of the response is the same as the md5 of the original object" (with-random-client c (do (s3/create-bucket c bucket-name) (s3/put-object c bucket-name object-name value) ((comp :etag :metadata) (s3/get-object c bucket-name object-name)))) => md5-sum)) (let [bucket-name (random-string) object-name (random-string) value (str "aaaaaaaaaa" "bbbbbbbbbb") file-name "./clj-mp-test.txt"] (fact "mulitpart upload works" (with-random-client c (do (s3/create-bucket c bucket-name) (let [tm (create-and-configure-manager c)] (write-file file-name value) (upload-file tm bucket-name object-name file-name) (let [fetched-object (s3/get-object c bucket-name object-name)] [((comp slurp :content) fetched-object) ((comp etag-suffix :etag :metadata) fetched-object)])))) => [value, "-2"])) (let [bucket-name (random-string) object-name (random-string) value "this is the real value" wrong-md5 "2945d7de2f70de5b8c0cb3fbcba4fe92"] (fact "Bad content md5 throws an exception" (with-random-client c (do (s3/create-bucket c bucket-name) (s3/put-object c bucket-name object-name value {:content-md5 wrong-md5}))) => (throws AmazonS3Exception)))
[ { "context": "omment\n\n (def db\n [[1 :age 26]\n [1 :name \"jimmy\"]\n [2 :age 26]\n [2 :name \"steve\"]\n [3", "end": 723, "score": 0.9985108375549316, "start": 718, "tag": "NAME", "value": "jimmy" }, { "context": "[1 :name \"jimmy\"]\n [2 :age 26]\n [2 :name \"steve\"]\n [3 :age 24]\n [3 :name \"bob\"]\n [4 :", "end": 763, "score": 0.9964151978492737, "start": 758, "tag": "NAME", "value": "steve" }, { "context": "[2 :name \"steve\"]\n [3 :age 24]\n [3 :name \"bob\"]\n [4 :address 1]\n [4 :address-line-1 \"12", "end": 801, "score": 0.9996230602264404, "start": 798, "tag": "NAME", "value": "bob" } ]
libraries/clojure/query-engine/src/query_engine/core.clj
jimmyhmiller/one-hundred-lines-or-less
6
(ns query-engine.core (:require [unifier.core :as unifier])) (defn match-clause [clause facts env] (->> facts (map (partial unifier/unify env clause)) (filter (complement unifier/failed?)))) (defn match-all [clause facts envs] (mapcat (partial match-clause clause facts) envs)) (defn process-query [clauses facts envs] (if (empty? clauses) envs (recur (rest clauses) facts (match-all (first clauses) facts envs)))) (defn q* [{:keys [find where]} db] (let [envs (process-query where db [{}])] (map unifier/substitute (map vector envs (repeat find))))) (defmacro q [query db] `(q* (quote ~query) db)) (comment (def db [[1 :age 26] [1 :name "jimmy"] [2 :age 26] [2 :name "steve"] [3 :age 24] [3 :name "bob"] [4 :address 1] [4 :address-line-1 "123 street st"] [4 :city "Indianapolis"]]) (q {:find {:name ?name} :where [[?_ :name ?name]]} db) (q {:find {:name ?name :age ?age} :where [[?e :name ?name] [?e :age ?age]]} db) (q {:find {:name1 ?name1 :name2 ?name2} :where [[?e1 :name ?name1] [?e2 :name ?name2] [?e1 :age ?age] [?e2 :age ?age]]} db) (q {:find {:name ?name :address-line-1 ?address-line-1 :city ?city} :where [[?e :name ?name] [?a :address ?e] [?a :address-line-1 ?address-line-1] [?a :city ?city]]} db))
88842
(ns query-engine.core (:require [unifier.core :as unifier])) (defn match-clause [clause facts env] (->> facts (map (partial unifier/unify env clause)) (filter (complement unifier/failed?)))) (defn match-all [clause facts envs] (mapcat (partial match-clause clause facts) envs)) (defn process-query [clauses facts envs] (if (empty? clauses) envs (recur (rest clauses) facts (match-all (first clauses) facts envs)))) (defn q* [{:keys [find where]} db] (let [envs (process-query where db [{}])] (map unifier/substitute (map vector envs (repeat find))))) (defmacro q [query db] `(q* (quote ~query) db)) (comment (def db [[1 :age 26] [1 :name "<NAME>"] [2 :age 26] [2 :name "<NAME>"] [3 :age 24] [3 :name "<NAME>"] [4 :address 1] [4 :address-line-1 "123 street st"] [4 :city "Indianapolis"]]) (q {:find {:name ?name} :where [[?_ :name ?name]]} db) (q {:find {:name ?name :age ?age} :where [[?e :name ?name] [?e :age ?age]]} db) (q {:find {:name1 ?name1 :name2 ?name2} :where [[?e1 :name ?name1] [?e2 :name ?name2] [?e1 :age ?age] [?e2 :age ?age]]} db) (q {:find {:name ?name :address-line-1 ?address-line-1 :city ?city} :where [[?e :name ?name] [?a :address ?e] [?a :address-line-1 ?address-line-1] [?a :city ?city]]} db))
true
(ns query-engine.core (:require [unifier.core :as unifier])) (defn match-clause [clause facts env] (->> facts (map (partial unifier/unify env clause)) (filter (complement unifier/failed?)))) (defn match-all [clause facts envs] (mapcat (partial match-clause clause facts) envs)) (defn process-query [clauses facts envs] (if (empty? clauses) envs (recur (rest clauses) facts (match-all (first clauses) facts envs)))) (defn q* [{:keys [find where]} db] (let [envs (process-query where db [{}])] (map unifier/substitute (map vector envs (repeat find))))) (defmacro q [query db] `(q* (quote ~query) db)) (comment (def db [[1 :age 26] [1 :name "PI:NAME:<NAME>END_PI"] [2 :age 26] [2 :name "PI:NAME:<NAME>END_PI"] [3 :age 24] [3 :name "PI:NAME:<NAME>END_PI"] [4 :address 1] [4 :address-line-1 "123 street st"] [4 :city "Indianapolis"]]) (q {:find {:name ?name} :where [[?_ :name ?name]]} db) (q {:find {:name ?name :age ?age} :where [[?e :name ?name] [?e :age ?age]]} db) (q {:find {:name1 ?name1 :name2 ?name2} :where [[?e1 :name ?name1] [?e2 :name ?name2] [?e1 :age ?age] [?e2 :age ?age]]} db) (q {:find {:name ?name :address-line-1 ?address-line-1 :city ?city} :where [[?e :name ?name] [?a :address ?e] [?a :address-line-1 ?address-line-1] [?a :city ?city]]} db))
[ { "context": " :aria-label \"hello\"\n ", "end": 2535, "score": 0.8984599709510803, "start": 2530, "tag": "NAME", "value": "hello" }, { "context": "rue\n :aria-label \"hello\"\n :className \"pi", "end": 2966, "score": 0.9425049424171448, "start": 2961, "tag": "NAME", "value": "hello" } ]
re_view/test/re_view/hiccup_test.cljs
braintripping/re-view
32
(ns re-view.hiccup-test (:require [cljs.test :refer [deftest is are testing]] ["react" :as react] ["react-dom" :as react-dom] [re-view.hiccup.core :refer [element]] [re-view.hiccup.hiccup :as hiccup])) (enable-console-print!) (defn element-args [form] (let [[_ k id classes] (hiccup/parse-key-memoized (form 0)) [props children] (hiccup/parse-args form)] (-> (into [k (hiccup/props->js k id classes props)] children) (update 1 js->clj :keywordize-keys true)))) (deftest hiccup (testing "Parse props" (is (= (element-args [:h1#page-header]) ["h1" {:id "page-header"}]) "Parse ID from element tag") (is (= ["div" {:className "red"}] (element-args [:div.red]) (element-args [:div {:class "red"}]) (element-args [:div {:classes ["red"]}])) "Three ways to specify a class") (is (= ["div" {:className "red"}] (element-args [:div.red nil])) "Three ways to specify a class") (is (= (element-args [:.red {:class "white black" :classes ["purple"]}]) ["div" {:className "red white black purple"}]) "Combine classes from element tag, :class, and :classes") (is (= (element-args [:.red]) ["div" {:className "red"}]) "If tag name is not specified, use a `div`") (is (= (element-args [:div {:data-collapse true :aria-label "hello"}]) ["div" {:data-collapse true :aria-label "hello"}]) "Do not camelCase data- and aria- attributes") (is (= (element-args [:div {:some-attr true :someAttr "hello"}]) ["div" {:some-attr true :someAttr "hello"}]) "Do not camelCase custom attributes") (is (= (element-args [:div {:style {:font-family "serif" :custom-attr "x"}}]) ["div" {:style {:fontFamily "serif" :customAttr "x"}}]) "camelCase ALL style attributes") (is (= (element-args [:custom-element]) ["custom-element" {}]) "Custom element tag") (is (= (element-args [:custom-element/special]) ["custom-element:special" {}]) "Custom element tag with namespace") (is (= (element-args [:special/effect#el.pink {:data-collapse true :aria-label "hello" :class "bg-black" :classes ["white"] :style {:font-family "serif" :font-size 12}}]) ["special:effect" {:data-collapse true :aria-label "hello" :className "pink bg-black white" :style {:fontFamily "serif" :fontSize 12} :id "el"}]) "All together")))
120985
(ns re-view.hiccup-test (:require [cljs.test :refer [deftest is are testing]] ["react" :as react] ["react-dom" :as react-dom] [re-view.hiccup.core :refer [element]] [re-view.hiccup.hiccup :as hiccup])) (enable-console-print!) (defn element-args [form] (let [[_ k id classes] (hiccup/parse-key-memoized (form 0)) [props children] (hiccup/parse-args form)] (-> (into [k (hiccup/props->js k id classes props)] children) (update 1 js->clj :keywordize-keys true)))) (deftest hiccup (testing "Parse props" (is (= (element-args [:h1#page-header]) ["h1" {:id "page-header"}]) "Parse ID from element tag") (is (= ["div" {:className "red"}] (element-args [:div.red]) (element-args [:div {:class "red"}]) (element-args [:div {:classes ["red"]}])) "Three ways to specify a class") (is (= ["div" {:className "red"}] (element-args [:div.red nil])) "Three ways to specify a class") (is (= (element-args [:.red {:class "white black" :classes ["purple"]}]) ["div" {:className "red white black purple"}]) "Combine classes from element tag, :class, and :classes") (is (= (element-args [:.red]) ["div" {:className "red"}]) "If tag name is not specified, use a `div`") (is (= (element-args [:div {:data-collapse true :aria-label "hello"}]) ["div" {:data-collapse true :aria-label "hello"}]) "Do not camelCase data- and aria- attributes") (is (= (element-args [:div {:some-attr true :someAttr "hello"}]) ["div" {:some-attr true :someAttr "hello"}]) "Do not camelCase custom attributes") (is (= (element-args [:div {:style {:font-family "serif" :custom-attr "x"}}]) ["div" {:style {:fontFamily "serif" :customAttr "x"}}]) "camelCase ALL style attributes") (is (= (element-args [:custom-element]) ["custom-element" {}]) "Custom element tag") (is (= (element-args [:custom-element/special]) ["custom-element:special" {}]) "Custom element tag with namespace") (is (= (element-args [:special/effect#el.pink {:data-collapse true :aria-label "<NAME>" :class "bg-black" :classes ["white"] :style {:font-family "serif" :font-size 12}}]) ["special:effect" {:data-collapse true :aria-label "<NAME>" :className "pink bg-black white" :style {:fontFamily "serif" :fontSize 12} :id "el"}]) "All together")))
true
(ns re-view.hiccup-test (:require [cljs.test :refer [deftest is are testing]] ["react" :as react] ["react-dom" :as react-dom] [re-view.hiccup.core :refer [element]] [re-view.hiccup.hiccup :as hiccup])) (enable-console-print!) (defn element-args [form] (let [[_ k id classes] (hiccup/parse-key-memoized (form 0)) [props children] (hiccup/parse-args form)] (-> (into [k (hiccup/props->js k id classes props)] children) (update 1 js->clj :keywordize-keys true)))) (deftest hiccup (testing "Parse props" (is (= (element-args [:h1#page-header]) ["h1" {:id "page-header"}]) "Parse ID from element tag") (is (= ["div" {:className "red"}] (element-args [:div.red]) (element-args [:div {:class "red"}]) (element-args [:div {:classes ["red"]}])) "Three ways to specify a class") (is (= ["div" {:className "red"}] (element-args [:div.red nil])) "Three ways to specify a class") (is (= (element-args [:.red {:class "white black" :classes ["purple"]}]) ["div" {:className "red white black purple"}]) "Combine classes from element tag, :class, and :classes") (is (= (element-args [:.red]) ["div" {:className "red"}]) "If tag name is not specified, use a `div`") (is (= (element-args [:div {:data-collapse true :aria-label "hello"}]) ["div" {:data-collapse true :aria-label "hello"}]) "Do not camelCase data- and aria- attributes") (is (= (element-args [:div {:some-attr true :someAttr "hello"}]) ["div" {:some-attr true :someAttr "hello"}]) "Do not camelCase custom attributes") (is (= (element-args [:div {:style {:font-family "serif" :custom-attr "x"}}]) ["div" {:style {:fontFamily "serif" :customAttr "x"}}]) "camelCase ALL style attributes") (is (= (element-args [:custom-element]) ["custom-element" {}]) "Custom element tag") (is (= (element-args [:custom-element/special]) ["custom-element:special" {}]) "Custom element tag with namespace") (is (= (element-args [:special/effect#el.pink {:data-collapse true :aria-label "PI:NAME:<NAME>END_PI" :class "bg-black" :classes ["white"] :style {:font-family "serif" :font-size 12}}]) ["special:effect" {:data-collapse true :aria-label "PI:NAME:<NAME>END_PI" :className "pink bg-black white" :style {:fontFamily "serif" :fontSize 12} :id "el"}]) "All together")))
[ { "context": "rred to DARPA’s Public Release Center via email at prc@darpa.mil.\n\n\n(ns mbroker.rabbitmq\n (:require [langohr.core", "end": 336, "score": 0.9999212026596069, "start": 323, "tag": "EMAIL", "value": "prc@darpa.mil" } ]
src/mbroker/rabbitmq.clj
paulratdollabs/drl007
0
; ; The software contained herein is proprietary and ; a confidential trade secret of Dynamic Object Language Labs Inc. ; Copyright (c) 2012. All rights reserved. ;; DISTRIBUTION STATEMENT C: U.S. Government agencies and their contractors. ;; Other requests shall be referred to DARPA’s Public Release Center via email at prc@darpa.mil. (ns mbroker.rabbitmq (:require [langohr.core :as rmq] [langohr.channel :as lch] [langohr.queue :as lq] [langohr.exchange :as le] [langohr.consumers :as lc] [langohr.basic :as lb] [clojure.data.json :as json])) (def debug false) (def default-exchange (str "test-" (System/getProperty "user.name"))) (def default-host "localhost") (def default-port 5672) (defn message-handler [_ metadata ^bytes payload] (println "Received message metadata" metadata) (clojure.pprint/pprint (String. payload "UTF-8")) ;[ch {:keys [content-type delivery-tag type] :as meta} ^bytes payload] #_(println (format "[consumer] Received a message: %s, delivery tag: %d, content type: %s, type: %s" (String. payload "UTF-8") metadata))) (defn close-connection [conn] (when (and conn (rmq/open? conn)) (rmq/close conn))) (defn close-channel [ch & [which-ch]] (when (and ch (rmq/open? ch)) ;(:from-channel state) (println which-ch "channel is open. Closing") (lch/close ch))) ; Creates and returns a "topic" exchange with the given RMQ config. (defn make-channel [exch-name rmq-config] #_(println "make-producer-channel") (let [config (or rmq-config {}) conn (rmq/connect config) ch (lch/open conn) exch-name (or exch-name default-exchange)] (le/declare ch exch-name "topic") {:channel ch :config config :exchange exch-name :connection conn})) (defn close-all [m] (close-connection (:connection m)) (close-channel (:channel m))) ; TODO make publish fn thread safe as channels are not thread safe and could lead bogus data being written to the channel (defn publish [data routing-key to-ch exch-name] ;(println "publishing data" data) (let [r-key (or routing-key "tpn.dispatcher.default")] (if (and to-ch exch-name) (lb/publish to-ch exch-name r-key data) (when debug (println "incomplete info for publishing data. channel-object and name" to-ch exch-name))))) (defn make-subscription [sub-key msg-handler channel exch-name] (let [key (or sub-key "#") handler (or msg-handler message-handler) aq (if channel (lq/declare channel)) qname (if aq (.getQueue aq) (println "Subscription Q is nil. Channel must be nil.")) _ (if qname (lq/bind channel qname exch-name {:routing-key key}) (println "Q binding failed ch qname key" channel qname key)) c-tag (if qname (lc/subscribe channel qname handler {:auto-ack true})) ] {:routing-key key :consumer-tag c-tag :queue-name qname :message-handler handler})) (defn cancel-subscription [^String consumer-tag channel] (when channel (langohr.basic/cancel channel consumer-tag))) (defn publish-object [obj routing-key to-ch exch-name] "publish given object as json" ;(println "publishing" routing-key exch-name) ;(clojure.pprint/pprint obj) (publish (json/write-str obj) routing-key to-ch exch-name)) ; (mbroker.rabbitmq/publish (slurp "/Users/prakash/projects/pac2man/doll/tpn/test/data/create-parallel-ex.test.json"))
26919
; ; The software contained herein is proprietary and ; a confidential trade secret of Dynamic Object Language Labs Inc. ; Copyright (c) 2012. All rights reserved. ;; DISTRIBUTION STATEMENT C: U.S. Government agencies and their contractors. ;; Other requests shall be referred to DARPA’s Public Release Center via email at <EMAIL>. (ns mbroker.rabbitmq (:require [langohr.core :as rmq] [langohr.channel :as lch] [langohr.queue :as lq] [langohr.exchange :as le] [langohr.consumers :as lc] [langohr.basic :as lb] [clojure.data.json :as json])) (def debug false) (def default-exchange (str "test-" (System/getProperty "user.name"))) (def default-host "localhost") (def default-port 5672) (defn message-handler [_ metadata ^bytes payload] (println "Received message metadata" metadata) (clojure.pprint/pprint (String. payload "UTF-8")) ;[ch {:keys [content-type delivery-tag type] :as meta} ^bytes payload] #_(println (format "[consumer] Received a message: %s, delivery tag: %d, content type: %s, type: %s" (String. payload "UTF-8") metadata))) (defn close-connection [conn] (when (and conn (rmq/open? conn)) (rmq/close conn))) (defn close-channel [ch & [which-ch]] (when (and ch (rmq/open? ch)) ;(:from-channel state) (println which-ch "channel is open. Closing") (lch/close ch))) ; Creates and returns a "topic" exchange with the given RMQ config. (defn make-channel [exch-name rmq-config] #_(println "make-producer-channel") (let [config (or rmq-config {}) conn (rmq/connect config) ch (lch/open conn) exch-name (or exch-name default-exchange)] (le/declare ch exch-name "topic") {:channel ch :config config :exchange exch-name :connection conn})) (defn close-all [m] (close-connection (:connection m)) (close-channel (:channel m))) ; TODO make publish fn thread safe as channels are not thread safe and could lead bogus data being written to the channel (defn publish [data routing-key to-ch exch-name] ;(println "publishing data" data) (let [r-key (or routing-key "tpn.dispatcher.default")] (if (and to-ch exch-name) (lb/publish to-ch exch-name r-key data) (when debug (println "incomplete info for publishing data. channel-object and name" to-ch exch-name))))) (defn make-subscription [sub-key msg-handler channel exch-name] (let [key (or sub-key "#") handler (or msg-handler message-handler) aq (if channel (lq/declare channel)) qname (if aq (.getQueue aq) (println "Subscription Q is nil. Channel must be nil.")) _ (if qname (lq/bind channel qname exch-name {:routing-key key}) (println "Q binding failed ch qname key" channel qname key)) c-tag (if qname (lc/subscribe channel qname handler {:auto-ack true})) ] {:routing-key key :consumer-tag c-tag :queue-name qname :message-handler handler})) (defn cancel-subscription [^String consumer-tag channel] (when channel (langohr.basic/cancel channel consumer-tag))) (defn publish-object [obj routing-key to-ch exch-name] "publish given object as json" ;(println "publishing" routing-key exch-name) ;(clojure.pprint/pprint obj) (publish (json/write-str obj) routing-key to-ch exch-name)) ; (mbroker.rabbitmq/publish (slurp "/Users/prakash/projects/pac2man/doll/tpn/test/data/create-parallel-ex.test.json"))
true
; ; The software contained herein is proprietary and ; a confidential trade secret of Dynamic Object Language Labs Inc. ; Copyright (c) 2012. All rights reserved. ;; DISTRIBUTION STATEMENT C: U.S. Government agencies and their contractors. ;; Other requests shall be referred to DARPA’s Public Release Center via email at PI:EMAIL:<EMAIL>END_PI. (ns mbroker.rabbitmq (:require [langohr.core :as rmq] [langohr.channel :as lch] [langohr.queue :as lq] [langohr.exchange :as le] [langohr.consumers :as lc] [langohr.basic :as lb] [clojure.data.json :as json])) (def debug false) (def default-exchange (str "test-" (System/getProperty "user.name"))) (def default-host "localhost") (def default-port 5672) (defn message-handler [_ metadata ^bytes payload] (println "Received message metadata" metadata) (clojure.pprint/pprint (String. payload "UTF-8")) ;[ch {:keys [content-type delivery-tag type] :as meta} ^bytes payload] #_(println (format "[consumer] Received a message: %s, delivery tag: %d, content type: %s, type: %s" (String. payload "UTF-8") metadata))) (defn close-connection [conn] (when (and conn (rmq/open? conn)) (rmq/close conn))) (defn close-channel [ch & [which-ch]] (when (and ch (rmq/open? ch)) ;(:from-channel state) (println which-ch "channel is open. Closing") (lch/close ch))) ; Creates and returns a "topic" exchange with the given RMQ config. (defn make-channel [exch-name rmq-config] #_(println "make-producer-channel") (let [config (or rmq-config {}) conn (rmq/connect config) ch (lch/open conn) exch-name (or exch-name default-exchange)] (le/declare ch exch-name "topic") {:channel ch :config config :exchange exch-name :connection conn})) (defn close-all [m] (close-connection (:connection m)) (close-channel (:channel m))) ; TODO make publish fn thread safe as channels are not thread safe and could lead bogus data being written to the channel (defn publish [data routing-key to-ch exch-name] ;(println "publishing data" data) (let [r-key (or routing-key "tpn.dispatcher.default")] (if (and to-ch exch-name) (lb/publish to-ch exch-name r-key data) (when debug (println "incomplete info for publishing data. channel-object and name" to-ch exch-name))))) (defn make-subscription [sub-key msg-handler channel exch-name] (let [key (or sub-key "#") handler (or msg-handler message-handler) aq (if channel (lq/declare channel)) qname (if aq (.getQueue aq) (println "Subscription Q is nil. Channel must be nil.")) _ (if qname (lq/bind channel qname exch-name {:routing-key key}) (println "Q binding failed ch qname key" channel qname key)) c-tag (if qname (lc/subscribe channel qname handler {:auto-ack true})) ] {:routing-key key :consumer-tag c-tag :queue-name qname :message-handler handler})) (defn cancel-subscription [^String consumer-tag channel] (when channel (langohr.basic/cancel channel consumer-tag))) (defn publish-object [obj routing-key to-ch exch-name] "publish given object as json" ;(println "publishing" routing-key exch-name) ;(clojure.pprint/pprint obj) (publish (json/write-str obj) routing-key to-ch exch-name)) ; (mbroker.rabbitmq/publish (slurp "/Users/prakash/projects/pac2man/doll/tpn/test/data/create-parallel-ex.test.json"))
[ { "context": "-columns\n [\"id\"\n \"lastname\"\n \"firstname\"\n \"username\"\n \"DATE_FORMAT(dob,'%m/%d/%Y')\"\n \"cell\"\n \"p", "end": 555, "score": 0.9892498850822449, "start": 547, "tag": "USERNAME", "value": "username" }, { "context": "-columns\n [\"id\"\n \"lastname\"\n \"firstname\"\n \"username\"\n \"password\"\n \"DATE_FORMAT(dob,'%m/%d/%Y') as", "end": 900, "score": 0.998416006565094, "start": 892, "tag": "USERNAME", "value": "username" }, { "context": "d\"\n \"lastname\"\n \"firstname\"\n \"username\"\n \"password\"\n \"DATE_FORMAT(dob,'%m/%d/%Y') as dob\"\n \"cell", "end": 914, "score": 0.8733672499656677, "start": 906, "tag": "PASSWORD", "value": "password" } ]
src/cc/routes/admin/users.clj
hectorqlucero/cc
3
(ns cc.routes.admin.users (:require [cc.models.crud :refer :all] [cc.models.grid :refer :all] [cc.models.util :refer :all] [cheshire.core :refer :all] [clojure.string :refer [capitalize lower-case]] [compojure.core :refer :all] [noir.util.crypt :as crypt] [selmer.parser :refer [render-file]])) (defn users [request] (render-file "admin/users/index.html" {:title "Usuarios"})) ;;start users grid (def search-columns ["id" "lastname" "firstname" "username" "DATE_FORMAT(dob,'%m/%d/%Y')" "cell" "phone" "fax" "email" "CASE WHEN level ='A' THEN 'Administrador' WHEN level = 'U' THEN 'Usuario' WHEN level = 'S' THEN 'Sistema' END" "CASE WHEN active = 'T' THEN 'Activo' WHEN active = 'F' THEN 'Inactivo' END"]) (def aliases-columns ["id" "lastname" "firstname" "username" "password" "DATE_FORMAT(dob,'%m/%d/%Y') as dob" "cell" "phone" "fax" "email" "CASE WHEN level = 'A' THEN 'Administrador' WHEN level = 'U' THEN 'Usuario' WHEN level='S' THEN 'Sistema' END AS level" "CASE WHEN active = 'T' THEN 'Activo' WHEN active = 'F' THEN 'Inactivo' END AS active"]) (defn grid-json [request] (try (let [table "users" scolumns (convert-search-columns search-columns) aliases aliases-columns join "" search (grid-search (:search (:params request) nil) scolumns) order (grid-sort (:sort (:params request) nil) (:order (:params request) nil)) offset (grid-offset (parse-int (:rows (:params request))) (parse-int (:page (:params request)))) rows (grid-rows table aliases join search order offset)] (generate-string rows)) (catch Exception e (.getMessage e)))) ;;end users grid ;;start users form (def form-sql "SELECT id as id, lastname, firstname, username, password, DATE_FORMAT(dob,'%m/%d/%Y') as dob, cell, phone, fax, email, level, active FROM users WHERE id = ?") (defn form-json [id] (let [record (Query db [form-sql id])] (generate-string (first record)))) ;;end users form (defn users-save [{params :params}] (let [id (fix-id (:id params)) postvars {:id id :lastname (capitalize (:lastname params)) :firstname (capitalize (:firstname params)) :username (lower-case (:username params)) :password (if (> (count (:password params)) 60) (:password params) (crypt/encrypt (:password params))) :dob (format-date-internal (:dob params)) :cell (:cell params nil) :phone (:phone params) :fax (:fax params) :email (lower-case (:email params)) :level (:level params) :active (:active params "F")} result (Save db :users postvars ["id = ? " id])] (if (seq result) (generate-string {:success "Correctamente processado!"}) (generate-string {:error "No se pudo processar!"})))) (defn users-delete [request] (let [id (:id (:params request))] (Delete db :users ["id = ?" id]) (generate-string {:success "Removido appropiadamente!"}))) (defroutes users-routes (GET "/admin/users" request [] (if (= (user-level) "S") (users request))) (POST "/admin/users/json/grid" request [] (if (= (user-level) "S") (grid-json request))) (GET "/admin/users/json/form/:id" [id] (if (= (user-level) "S") (form-json id))) (POST "/admin/users/save" request [] (if (= (user-level) "S") (users-save request))) (POST "/admin/users/delete" request [] (if (= (user-level) "S") (users-delete request))))
84928
(ns cc.routes.admin.users (:require [cc.models.crud :refer :all] [cc.models.grid :refer :all] [cc.models.util :refer :all] [cheshire.core :refer :all] [clojure.string :refer [capitalize lower-case]] [compojure.core :refer :all] [noir.util.crypt :as crypt] [selmer.parser :refer [render-file]])) (defn users [request] (render-file "admin/users/index.html" {:title "Usuarios"})) ;;start users grid (def search-columns ["id" "lastname" "firstname" "username" "DATE_FORMAT(dob,'%m/%d/%Y')" "cell" "phone" "fax" "email" "CASE WHEN level ='A' THEN 'Administrador' WHEN level = 'U' THEN 'Usuario' WHEN level = 'S' THEN 'Sistema' END" "CASE WHEN active = 'T' THEN 'Activo' WHEN active = 'F' THEN 'Inactivo' END"]) (def aliases-columns ["id" "lastname" "firstname" "username" "<PASSWORD>" "DATE_FORMAT(dob,'%m/%d/%Y') as dob" "cell" "phone" "fax" "email" "CASE WHEN level = 'A' THEN 'Administrador' WHEN level = 'U' THEN 'Usuario' WHEN level='S' THEN 'Sistema' END AS level" "CASE WHEN active = 'T' THEN 'Activo' WHEN active = 'F' THEN 'Inactivo' END AS active"]) (defn grid-json [request] (try (let [table "users" scolumns (convert-search-columns search-columns) aliases aliases-columns join "" search (grid-search (:search (:params request) nil) scolumns) order (grid-sort (:sort (:params request) nil) (:order (:params request) nil)) offset (grid-offset (parse-int (:rows (:params request))) (parse-int (:page (:params request)))) rows (grid-rows table aliases join search order offset)] (generate-string rows)) (catch Exception e (.getMessage e)))) ;;end users grid ;;start users form (def form-sql "SELECT id as id, lastname, firstname, username, password, DATE_FORMAT(dob,'%m/%d/%Y') as dob, cell, phone, fax, email, level, active FROM users WHERE id = ?") (defn form-json [id] (let [record (Query db [form-sql id])] (generate-string (first record)))) ;;end users form (defn users-save [{params :params}] (let [id (fix-id (:id params)) postvars {:id id :lastname (capitalize (:lastname params)) :firstname (capitalize (:firstname params)) :username (lower-case (:username params)) :password (if (> (count (:password params)) 60) (:password params) (crypt/encrypt (:password params))) :dob (format-date-internal (:dob params)) :cell (:cell params nil) :phone (:phone params) :fax (:fax params) :email (lower-case (:email params)) :level (:level params) :active (:active params "F")} result (Save db :users postvars ["id = ? " id])] (if (seq result) (generate-string {:success "Correctamente processado!"}) (generate-string {:error "No se pudo processar!"})))) (defn users-delete [request] (let [id (:id (:params request))] (Delete db :users ["id = ?" id]) (generate-string {:success "Removido appropiadamente!"}))) (defroutes users-routes (GET "/admin/users" request [] (if (= (user-level) "S") (users request))) (POST "/admin/users/json/grid" request [] (if (= (user-level) "S") (grid-json request))) (GET "/admin/users/json/form/:id" [id] (if (= (user-level) "S") (form-json id))) (POST "/admin/users/save" request [] (if (= (user-level) "S") (users-save request))) (POST "/admin/users/delete" request [] (if (= (user-level) "S") (users-delete request))))
true
(ns cc.routes.admin.users (:require [cc.models.crud :refer :all] [cc.models.grid :refer :all] [cc.models.util :refer :all] [cheshire.core :refer :all] [clojure.string :refer [capitalize lower-case]] [compojure.core :refer :all] [noir.util.crypt :as crypt] [selmer.parser :refer [render-file]])) (defn users [request] (render-file "admin/users/index.html" {:title "Usuarios"})) ;;start users grid (def search-columns ["id" "lastname" "firstname" "username" "DATE_FORMAT(dob,'%m/%d/%Y')" "cell" "phone" "fax" "email" "CASE WHEN level ='A' THEN 'Administrador' WHEN level = 'U' THEN 'Usuario' WHEN level = 'S' THEN 'Sistema' END" "CASE WHEN active = 'T' THEN 'Activo' WHEN active = 'F' THEN 'Inactivo' END"]) (def aliases-columns ["id" "lastname" "firstname" "username" "PI:PASSWORD:<PASSWORD>END_PI" "DATE_FORMAT(dob,'%m/%d/%Y') as dob" "cell" "phone" "fax" "email" "CASE WHEN level = 'A' THEN 'Administrador' WHEN level = 'U' THEN 'Usuario' WHEN level='S' THEN 'Sistema' END AS level" "CASE WHEN active = 'T' THEN 'Activo' WHEN active = 'F' THEN 'Inactivo' END AS active"]) (defn grid-json [request] (try (let [table "users" scolumns (convert-search-columns search-columns) aliases aliases-columns join "" search (grid-search (:search (:params request) nil) scolumns) order (grid-sort (:sort (:params request) nil) (:order (:params request) nil)) offset (grid-offset (parse-int (:rows (:params request))) (parse-int (:page (:params request)))) rows (grid-rows table aliases join search order offset)] (generate-string rows)) (catch Exception e (.getMessage e)))) ;;end users grid ;;start users form (def form-sql "SELECT id as id, lastname, firstname, username, password, DATE_FORMAT(dob,'%m/%d/%Y') as dob, cell, phone, fax, email, level, active FROM users WHERE id = ?") (defn form-json [id] (let [record (Query db [form-sql id])] (generate-string (first record)))) ;;end users form (defn users-save [{params :params}] (let [id (fix-id (:id params)) postvars {:id id :lastname (capitalize (:lastname params)) :firstname (capitalize (:firstname params)) :username (lower-case (:username params)) :password (if (> (count (:password params)) 60) (:password params) (crypt/encrypt (:password params))) :dob (format-date-internal (:dob params)) :cell (:cell params nil) :phone (:phone params) :fax (:fax params) :email (lower-case (:email params)) :level (:level params) :active (:active params "F")} result (Save db :users postvars ["id = ? " id])] (if (seq result) (generate-string {:success "Correctamente processado!"}) (generate-string {:error "No se pudo processar!"})))) (defn users-delete [request] (let [id (:id (:params request))] (Delete db :users ["id = ?" id]) (generate-string {:success "Removido appropiadamente!"}))) (defroutes users-routes (GET "/admin/users" request [] (if (= (user-level) "S") (users request))) (POST "/admin/users/json/grid" request [] (if (= (user-level) "S") (grid-json request))) (GET "/admin/users/json/form/:id" [id] (if (= (user-level) "S") (form-json id))) (POST "/admin/users/save" request [] (if (= (user-level) "S") (users-save request))) (POST "/admin/users/delete" request [] (if (= (user-level) "S") (users-delete request))))
[ { "context": "all]))\n\n\n(defn setup\n []\n (h/create-test-user! \"success+1@simulator.amazonses.com\"))\n\n(defn fixture [test]\n (h/ensure-empty-table)", "end": 317, "score": 0.999928891658783, "start": 284, "tag": "EMAIL", "value": "success+1@simulator.amazonses.com" }, { "context": "[request (h/request\n {:session \"success+1@simulator.amazonses.com\"\n :query {:current-user {}}})\n", "end": 1575, "score": 0.999930739402771, "start": 1542, "tag": "EMAIL", "value": "success+1@simulator.amazonses.com" }, { "context": " {:current-user {}}})\n user-id (user/id \"success+1@simulator.amazonses.com\")\n user (user/fetch user-id)\n {", "end": 1686, "score": 0.9999313950538635, "start": 1653, "tag": "EMAIL", "value": "success+1@simulator.amazonses.com" } ]
api/test/feature/flow/query/current_user_test.clj
kgxsz/flow
0
(ns flow.query.current-user-test (:require [flow.core :refer :all] [flow.entity.authorisation :as authorisation] [flow.entity.user :as user] [flow.helpers :as h] [clojure.test :refer :all])) (defn setup [] (h/create-test-user! "success+1@simulator.amazonses.com")) (defn fixture [test] (h/ensure-empty-table) (setup) (test) (h/ensure-empty-table)) (use-fixtures :each fixture) (deftest test-current-user (testing "The handler negotiates the current-user query when no session is provided." (let [request (h/request {:query {:current-user {}}}) {:keys [status headers body] :as response} (handler request)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id nil}} (h/decode :transit body))))) (testing "The handler negotiates the current-user query when an unauthorised session is provided." (let [request (h/request {:session :unauthorised :query {:current-user {}}}) {:keys [status headers body] :as response} (handler request)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id nil}} (h/decode :transit body))))) (testing "The handler negotiates the current-user query when an authorised session is provided." (let [request (h/request {:session "success+1@simulator.amazonses.com" :query {:current-user {}}}) user-id (user/id "success+1@simulator.amazonses.com") user (user/fetch user-id) {:keys [status headers body] :as response} (handler request)] (is (= 200 status)) (is (= {:users {user-id user} :authorisations {} :metadata {} :session {:current-user-id user-id}} (h/decode :transit body))))))
55937
(ns flow.query.current-user-test (:require [flow.core :refer :all] [flow.entity.authorisation :as authorisation] [flow.entity.user :as user] [flow.helpers :as h] [clojure.test :refer :all])) (defn setup [] (h/create-test-user! "<EMAIL>")) (defn fixture [test] (h/ensure-empty-table) (setup) (test) (h/ensure-empty-table)) (use-fixtures :each fixture) (deftest test-current-user (testing "The handler negotiates the current-user query when no session is provided." (let [request (h/request {:query {:current-user {}}}) {:keys [status headers body] :as response} (handler request)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id nil}} (h/decode :transit body))))) (testing "The handler negotiates the current-user query when an unauthorised session is provided." (let [request (h/request {:session :unauthorised :query {:current-user {}}}) {:keys [status headers body] :as response} (handler request)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id nil}} (h/decode :transit body))))) (testing "The handler negotiates the current-user query when an authorised session is provided." (let [request (h/request {:session "<EMAIL>" :query {:current-user {}}}) user-id (user/id "<EMAIL>") user (user/fetch user-id) {:keys [status headers body] :as response} (handler request)] (is (= 200 status)) (is (= {:users {user-id user} :authorisations {} :metadata {} :session {:current-user-id user-id}} (h/decode :transit body))))))
true
(ns flow.query.current-user-test (:require [flow.core :refer :all] [flow.entity.authorisation :as authorisation] [flow.entity.user :as user] [flow.helpers :as h] [clojure.test :refer :all])) (defn setup [] (h/create-test-user! "PI:EMAIL:<EMAIL>END_PI")) (defn fixture [test] (h/ensure-empty-table) (setup) (test) (h/ensure-empty-table)) (use-fixtures :each fixture) (deftest test-current-user (testing "The handler negotiates the current-user query when no session is provided." (let [request (h/request {:query {:current-user {}}}) {:keys [status headers body] :as response} (handler request)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id nil}} (h/decode :transit body))))) (testing "The handler negotiates the current-user query when an unauthorised session is provided." (let [request (h/request {:session :unauthorised :query {:current-user {}}}) {:keys [status headers body] :as response} (handler request)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id nil}} (h/decode :transit body))))) (testing "The handler negotiates the current-user query when an authorised session is provided." (let [request (h/request {:session "PI:EMAIL:<EMAIL>END_PI" :query {:current-user {}}}) user-id (user/id "PI:EMAIL:<EMAIL>END_PI") user (user/fetch user-id) {:keys [status headers body] :as response} (handler request)] (is (= 200 status)) (is (= {:users {user-id user} :authorisations {} :metadata {} :session {:current-user-id user-id}} (h/decode :transit body))))))
[ { "context": ";; Copyright 2020 James Adam and the Open Data Management Platform contributor", "end": 28, "score": 0.9998094439506531, "start": 18, "tag": "NAME", "value": "James Adam" } ]
opendmp-ui/src/cljs/odmp_ui/views/processor/script_fields.cljs
rhinoman/odmp
21
;; Copyright 2020 James Adam and the Open Data Management Platform contributors. ;; 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 odmp-ui.views.processor.script-fields (:require [re-frame.core :as rf] [reagent.core :as r] [odmp-ui.views.processor.events :as proc-events] [odmp-ui.views.processor.subs :as proc-subs] [odmp-ui.views.processor.styles :refer [proc-styles]] [odmp-ui.util.styles :as style] ["react-ace" :default AceEditor] ["ace-builds/src-noconflict/mode-python"] ["ace-builds/src-noconflict/mode-clojure"] ["ace-builds/src-noconflict/mode-plain_text"] ["ace-builds/src-noconflict/theme-monokai"] ["@material-ui/core/Box" :default Box] ["@material-ui/core/Grid" :default Grid] ["@material-ui/core/FormGroup" :default FormGroup] ["@material-ui/core/FormControl" :default FormControl] ["@material-ui/core/InputLabel" :default InputLabel] ["@material-ui/core/Select" :default Select] ["@material-ui/core/Typography" :default Typography] ["@material-ui/core/MenuItem" :default MenuItem])) (defn code-field-changed [value atm] (rf/dispatch [::proc-events/set-processor-property :code value]) (reset! atm value)) (defn starter-code [ace-mode] (case ace-mode "clojure" "(defn process [xs])" "python" "def process(data):" "Select a scripting language")) (defn code-editor [ace-mode processor] (let [editor-contents (r/atom (or (get-in @processor [:properties :code]) (starter-code ace-mode)))] (fn [ace-mode processor] [:> AceEditor {:mode ace-mode :theme "monokai" :name "INPUT_SCRIPT_CODE" :width "100%" :style {:line-height 1.5} :showPrintMargin false :focus true :fontSize 14 :value @editor-contents :onChange #(code-field-changed % editor-contents)}]))) (defn script-fields [processor] (let [script-lang (rf/subscribe [::proc-subs/edit-script-language]) lang-field-value (or @script-lang (get-in @processor [:properties :language]) "") ace-mode (case lang-field-value "CLOJURE" "clojure" "PYTHON" "python" "plain_text")] (style/let [classes proc-styles] [:> Box {:style {:margin-top 10}} [:> Typography {:variant :subtitle2} "Enter Your script below"] [:> Typography {:variant :body2} "Note: Your script must contain a function named \"process\" that takes a byte array as input and returns a byte array as output"] [:> FormControl {:variant :filled :required true :margin :dense :fullWidth true} [:> InputLabel {:id "INPUT_LANGUAGE_LABEL"} "Language"] [:> Select {:labelid "INPUT_LANGUAGE_LABEL" :value lang-field-value :onChange #(rf/dispatch [::proc-events/set-processor-property :language (-> % .-target .-value)])} [:> MenuItem {:value ""} [:em "NONE"]] [:> MenuItem {:value "CLOJURE"} "Clojure"] [:> MenuItem {:value "PYTHON"} "Python"]]] [:> Box {:class (:ace-editor-wrapper classes)} [code-editor ace-mode processor]]])))
119131
;; Copyright 2020 <NAME> and the Open Data Management Platform contributors. ;; 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 odmp-ui.views.processor.script-fields (:require [re-frame.core :as rf] [reagent.core :as r] [odmp-ui.views.processor.events :as proc-events] [odmp-ui.views.processor.subs :as proc-subs] [odmp-ui.views.processor.styles :refer [proc-styles]] [odmp-ui.util.styles :as style] ["react-ace" :default AceEditor] ["ace-builds/src-noconflict/mode-python"] ["ace-builds/src-noconflict/mode-clojure"] ["ace-builds/src-noconflict/mode-plain_text"] ["ace-builds/src-noconflict/theme-monokai"] ["@material-ui/core/Box" :default Box] ["@material-ui/core/Grid" :default Grid] ["@material-ui/core/FormGroup" :default FormGroup] ["@material-ui/core/FormControl" :default FormControl] ["@material-ui/core/InputLabel" :default InputLabel] ["@material-ui/core/Select" :default Select] ["@material-ui/core/Typography" :default Typography] ["@material-ui/core/MenuItem" :default MenuItem])) (defn code-field-changed [value atm] (rf/dispatch [::proc-events/set-processor-property :code value]) (reset! atm value)) (defn starter-code [ace-mode] (case ace-mode "clojure" "(defn process [xs])" "python" "def process(data):" "Select a scripting language")) (defn code-editor [ace-mode processor] (let [editor-contents (r/atom (or (get-in @processor [:properties :code]) (starter-code ace-mode)))] (fn [ace-mode processor] [:> AceEditor {:mode ace-mode :theme "monokai" :name "INPUT_SCRIPT_CODE" :width "100%" :style {:line-height 1.5} :showPrintMargin false :focus true :fontSize 14 :value @editor-contents :onChange #(code-field-changed % editor-contents)}]))) (defn script-fields [processor] (let [script-lang (rf/subscribe [::proc-subs/edit-script-language]) lang-field-value (or @script-lang (get-in @processor [:properties :language]) "") ace-mode (case lang-field-value "CLOJURE" "clojure" "PYTHON" "python" "plain_text")] (style/let [classes proc-styles] [:> Box {:style {:margin-top 10}} [:> Typography {:variant :subtitle2} "Enter Your script below"] [:> Typography {:variant :body2} "Note: Your script must contain a function named \"process\" that takes a byte array as input and returns a byte array as output"] [:> FormControl {:variant :filled :required true :margin :dense :fullWidth true} [:> InputLabel {:id "INPUT_LANGUAGE_LABEL"} "Language"] [:> Select {:labelid "INPUT_LANGUAGE_LABEL" :value lang-field-value :onChange #(rf/dispatch [::proc-events/set-processor-property :language (-> % .-target .-value)])} [:> MenuItem {:value ""} [:em "NONE"]] [:> MenuItem {:value "CLOJURE"} "Clojure"] [:> MenuItem {:value "PYTHON"} "Python"]]] [:> Box {:class (:ace-editor-wrapper classes)} [code-editor ace-mode processor]]])))
true
;; Copyright 2020 PI:NAME:<NAME>END_PI and the Open Data Management Platform contributors. ;; 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 odmp-ui.views.processor.script-fields (:require [re-frame.core :as rf] [reagent.core :as r] [odmp-ui.views.processor.events :as proc-events] [odmp-ui.views.processor.subs :as proc-subs] [odmp-ui.views.processor.styles :refer [proc-styles]] [odmp-ui.util.styles :as style] ["react-ace" :default AceEditor] ["ace-builds/src-noconflict/mode-python"] ["ace-builds/src-noconflict/mode-clojure"] ["ace-builds/src-noconflict/mode-plain_text"] ["ace-builds/src-noconflict/theme-monokai"] ["@material-ui/core/Box" :default Box] ["@material-ui/core/Grid" :default Grid] ["@material-ui/core/FormGroup" :default FormGroup] ["@material-ui/core/FormControl" :default FormControl] ["@material-ui/core/InputLabel" :default InputLabel] ["@material-ui/core/Select" :default Select] ["@material-ui/core/Typography" :default Typography] ["@material-ui/core/MenuItem" :default MenuItem])) (defn code-field-changed [value atm] (rf/dispatch [::proc-events/set-processor-property :code value]) (reset! atm value)) (defn starter-code [ace-mode] (case ace-mode "clojure" "(defn process [xs])" "python" "def process(data):" "Select a scripting language")) (defn code-editor [ace-mode processor] (let [editor-contents (r/atom (or (get-in @processor [:properties :code]) (starter-code ace-mode)))] (fn [ace-mode processor] [:> AceEditor {:mode ace-mode :theme "monokai" :name "INPUT_SCRIPT_CODE" :width "100%" :style {:line-height 1.5} :showPrintMargin false :focus true :fontSize 14 :value @editor-contents :onChange #(code-field-changed % editor-contents)}]))) (defn script-fields [processor] (let [script-lang (rf/subscribe [::proc-subs/edit-script-language]) lang-field-value (or @script-lang (get-in @processor [:properties :language]) "") ace-mode (case lang-field-value "CLOJURE" "clojure" "PYTHON" "python" "plain_text")] (style/let [classes proc-styles] [:> Box {:style {:margin-top 10}} [:> Typography {:variant :subtitle2} "Enter Your script below"] [:> Typography {:variant :body2} "Note: Your script must contain a function named \"process\" that takes a byte array as input and returns a byte array as output"] [:> FormControl {:variant :filled :required true :margin :dense :fullWidth true} [:> InputLabel {:id "INPUT_LANGUAGE_LABEL"} "Language"] [:> Select {:labelid "INPUT_LANGUAGE_LABEL" :value lang-field-value :onChange #(rf/dispatch [::proc-events/set-processor-property :language (-> % .-target .-value)])} [:> MenuItem {:value ""} [:em "NONE"]] [:> MenuItem {:value "CLOJURE"} "Clojure"] [:> MenuItem {:value "PYTHON"} "Python"]]] [:> Box {:class (:ace-editor-wrapper classes)} [code-editor ace-mode processor]]])))
[ { "context": ";; Copyright (c) Rich Hickey and contributors. All rights reserved.\n;; The u", "end": 30, "score": 0.9998526573181152, "start": 19, "tag": "NAME", "value": "Rich Hickey" } ]
server/target/clojure/core/async/impl/concurrent.clj
OctavioBR/healthcheck
0
;; Copyright (c) Rich Hickey and contributors. 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 ^{:skip-wiki true} clojure.core.async.impl.concurrent (:import [java.util.concurrent ThreadFactory])) (set! *warn-on-reflection* true) (defn counted-thread-factory "Create a ThreadFactory that maintains a counter for naming Threads. name-format specifies thread names - use %d to include counter daemon is a flag for whether threads are daemons or not" [name-format daemon] (let [counter (atom 0)] (reify ThreadFactory (newThread [this runnable] (doto (Thread. runnable) (.setName (format name-format (swap! counter inc))) (.setDaemon daemon)))))) (defonce ^{:doc "Number of processors reported by the JVM"} processors (.availableProcessors (Runtime/getRuntime)))
123648
;; Copyright (c) <NAME> and contributors. 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 ^{:skip-wiki true} clojure.core.async.impl.concurrent (:import [java.util.concurrent ThreadFactory])) (set! *warn-on-reflection* true) (defn counted-thread-factory "Create a ThreadFactory that maintains a counter for naming Threads. name-format specifies thread names - use %d to include counter daemon is a flag for whether threads are daemons or not" [name-format daemon] (let [counter (atom 0)] (reify ThreadFactory (newThread [this runnable] (doto (Thread. runnable) (.setName (format name-format (swap! counter inc))) (.setDaemon daemon)))))) (defonce ^{:doc "Number of processors reported by the JVM"} processors (.availableProcessors (Runtime/getRuntime)))
true
;; Copyright (c) PI:NAME:<NAME>END_PI and contributors. 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 ^{:skip-wiki true} clojure.core.async.impl.concurrent (:import [java.util.concurrent ThreadFactory])) (set! *warn-on-reflection* true) (defn counted-thread-factory "Create a ThreadFactory that maintains a counter for naming Threads. name-format specifies thread names - use %d to include counter daemon is a flag for whether threads are daemons or not" [name-format daemon] (let [counter (atom 0)] (reify ThreadFactory (newThread [this runnable] (doto (Thread. runnable) (.setName (format name-format (swap! counter inc))) (.setDaemon daemon)))))) (defonce ^{:doc "Number of processors reported by the JVM"} processors (.availableProcessors (Runtime/getRuntime)))
[ { "context": ";; 1\n(def gemstone-db {\n :ruby {\n :name \"Ruby\"\n :stock 480\n :sales [1990 3644 6376 49", "end": 53, "score": 0.9983565807342529, "start": 49, "tag": "NAME", "value": "Ruby" }, { "context": "or \"Red\"\n }\n }\n :diamond {\n :name \"Diamond\"\n :stock 10\n :sales [8295 329 5960 6118", "end": 312, "score": 0.9983094334602356, "start": 305, "tag": "NAME", "value": "Diamond" }, { "context": "ess\"\n }\n }\n :moissanite {\n :name \"Moissanite\"\n :stock 45\n :sales [7761 3220]\n :", "end": 628, "score": 0.9993202090263367, "start": 618, "tag": "NAME", "value": "Moissanite" } ]
chapter02/exercise4/repl.clj
TrainingByPackt/Clojure
0
;; 1 (def gemstone-db { :ruby { :name "Ruby" :stock 480 :sales [1990 3644 6376 4918 7882 6747 7495 8573 5097 1712] :properties { :dispersion 0.018 :hardness 9.0 :refractive-index [1.77 1.78] :color "Red" } } :diamond { :name "Diamond" :stock 10 :sales [8295 329 5960 6118 4189 3436 9833 8870 9700 7182 7061 1579] :properties { :dispersion 0.044 :hardness 10 :refractive-index [2.417 2.419] :color "Typically yellow, brown or gray to colorless" } } :moissanite { :name "Moissanite" :stock 45 :sales [7761 3220] :properties { :dispersion 0.104 :hardness 9.5 :refractive-index [2.65 2.69] :color "Colorless, green, yellow" } } } ) ;; 2 (get (get (get gemstone-db :ruby) :properties) :hardness) ;; 3 (:hardness (:properties (:ruby gemstone-db))) ;; 4 (get-in gemstone-db [:ruby :properties :hardness]) ;; 5 (defn durability [db gemstone] (get-in db [gemstone :properties :hardness])) ;; 6 (durability gemstone-db :ruby) (durability gemstone-db :moissanite) ;; 7 (assoc (:ruby gemstone-db) :properties {:color "Near colorless through pink through all shades of red to a deep crimson"}) ;; 8 (update (:ruby gemstone-db) :properties into {:color "Near colorless through pink through all shades of red to a deep crimson"}) ;; 9 (assoc-in gemstone-db [:ruby :properties :color] "Near colorless through pink through all shades of red to a deep crimson") ;; 10 (pprint *1) ;; 11 (defn change-color [db gemstone new-color] (assoc-in gemstone-db [gemstone :properties :color] new-color)) ;; 12 (change-color gemstone-db :ruby "Some kind of red") ;; 13 (update-in gemstone-db [:diamond :stock] dec) ;; 14 (set! *print-level* 2) (update-in gemstone-db [:diamond :stock] dec) ;; 15 (update-in gemstone-db [:diamond :sales] conj 999) ;; 16 (set! *print-level* nil) (update-in gemstone-db [:diamond :sales] conj 999) ;; 17 (defn sell [db gemstone client-id] (let [clients-updated-db (update-in db [gemstone :sales] conj client-id)] (update-in clients-updated-db [gemstone :stock] dec))) ;; 18 (sell gemstone-db :moissanite 123)
100254
;; 1 (def gemstone-db { :ruby { :name "<NAME>" :stock 480 :sales [1990 3644 6376 4918 7882 6747 7495 8573 5097 1712] :properties { :dispersion 0.018 :hardness 9.0 :refractive-index [1.77 1.78] :color "Red" } } :diamond { :name "<NAME>" :stock 10 :sales [8295 329 5960 6118 4189 3436 9833 8870 9700 7182 7061 1579] :properties { :dispersion 0.044 :hardness 10 :refractive-index [2.417 2.419] :color "Typically yellow, brown or gray to colorless" } } :moissanite { :name "<NAME>" :stock 45 :sales [7761 3220] :properties { :dispersion 0.104 :hardness 9.5 :refractive-index [2.65 2.69] :color "Colorless, green, yellow" } } } ) ;; 2 (get (get (get gemstone-db :ruby) :properties) :hardness) ;; 3 (:hardness (:properties (:ruby gemstone-db))) ;; 4 (get-in gemstone-db [:ruby :properties :hardness]) ;; 5 (defn durability [db gemstone] (get-in db [gemstone :properties :hardness])) ;; 6 (durability gemstone-db :ruby) (durability gemstone-db :moissanite) ;; 7 (assoc (:ruby gemstone-db) :properties {:color "Near colorless through pink through all shades of red to a deep crimson"}) ;; 8 (update (:ruby gemstone-db) :properties into {:color "Near colorless through pink through all shades of red to a deep crimson"}) ;; 9 (assoc-in gemstone-db [:ruby :properties :color] "Near colorless through pink through all shades of red to a deep crimson") ;; 10 (pprint *1) ;; 11 (defn change-color [db gemstone new-color] (assoc-in gemstone-db [gemstone :properties :color] new-color)) ;; 12 (change-color gemstone-db :ruby "Some kind of red") ;; 13 (update-in gemstone-db [:diamond :stock] dec) ;; 14 (set! *print-level* 2) (update-in gemstone-db [:diamond :stock] dec) ;; 15 (update-in gemstone-db [:diamond :sales] conj 999) ;; 16 (set! *print-level* nil) (update-in gemstone-db [:diamond :sales] conj 999) ;; 17 (defn sell [db gemstone client-id] (let [clients-updated-db (update-in db [gemstone :sales] conj client-id)] (update-in clients-updated-db [gemstone :stock] dec))) ;; 18 (sell gemstone-db :moissanite 123)
true
;; 1 (def gemstone-db { :ruby { :name "PI:NAME:<NAME>END_PI" :stock 480 :sales [1990 3644 6376 4918 7882 6747 7495 8573 5097 1712] :properties { :dispersion 0.018 :hardness 9.0 :refractive-index [1.77 1.78] :color "Red" } } :diamond { :name "PI:NAME:<NAME>END_PI" :stock 10 :sales [8295 329 5960 6118 4189 3436 9833 8870 9700 7182 7061 1579] :properties { :dispersion 0.044 :hardness 10 :refractive-index [2.417 2.419] :color "Typically yellow, brown or gray to colorless" } } :moissanite { :name "PI:NAME:<NAME>END_PI" :stock 45 :sales [7761 3220] :properties { :dispersion 0.104 :hardness 9.5 :refractive-index [2.65 2.69] :color "Colorless, green, yellow" } } } ) ;; 2 (get (get (get gemstone-db :ruby) :properties) :hardness) ;; 3 (:hardness (:properties (:ruby gemstone-db))) ;; 4 (get-in gemstone-db [:ruby :properties :hardness]) ;; 5 (defn durability [db gemstone] (get-in db [gemstone :properties :hardness])) ;; 6 (durability gemstone-db :ruby) (durability gemstone-db :moissanite) ;; 7 (assoc (:ruby gemstone-db) :properties {:color "Near colorless through pink through all shades of red to a deep crimson"}) ;; 8 (update (:ruby gemstone-db) :properties into {:color "Near colorless through pink through all shades of red to a deep crimson"}) ;; 9 (assoc-in gemstone-db [:ruby :properties :color] "Near colorless through pink through all shades of red to a deep crimson") ;; 10 (pprint *1) ;; 11 (defn change-color [db gemstone new-color] (assoc-in gemstone-db [gemstone :properties :color] new-color)) ;; 12 (change-color gemstone-db :ruby "Some kind of red") ;; 13 (update-in gemstone-db [:diamond :stock] dec) ;; 14 (set! *print-level* 2) (update-in gemstone-db [:diamond :stock] dec) ;; 15 (update-in gemstone-db [:diamond :sales] conj 999) ;; 16 (set! *print-level* nil) (update-in gemstone-db [:diamond :sales] conj 999) ;; 17 (defn sell [db gemstone client-id] (let [clients-updated-db (update-in db [gemstone :sales] conj client-id)] (update-in clients-updated-db [gemstone :stock] dec))) ;; 18 (sell gemstone-db :moissanite 123)
[ { "context": "gory)\n (merge repo-data\n {:username username\n :password password})]))\n\n(defn updat", "end": 2079, "score": 0.9989224672317505, "start": 2071, "tag": "USERNAME", "value": "username" }, { "context": " {:username username\n :password password})]))\n\n(defn update-repositories\n [project]\n (if", "end": 2111, "score": 0.9947500228881836, "start": 2103, "tag": "PASSWORD", "value": "password" } ]
src/lein_essthree/repository.clj
reutsharabani/lein-essthree
0
(ns lein-essthree.repository "Middleware to update project repositories to include any configured S3 buckets." (:require [cuerdas.core :as c] [lein-essthree.schemas :refer [RepoConfig]] [schema.core :as s]) (:import com.amazonaws.auth.DefaultAWSCredentialsProviderChain)) (defn aws-credentials [] (let [creds (.getCredentials (DefaultAWSCredentialsProviderChain.))] {:access-key-id (.getAWSAccessKeyId creds) :secret-key (.getAWSSecretKey creds)})) (s/defn ^:private get-config :- (s/maybe RepoConfig) [project] (get-in project [:essthree :repository])) (s/defn ^:private build-repo-url :- s/Str [config :- RepoConfig build-category :- (s/enum "releases" "snapshots")] (let [bucket (:bucket config) path (:path config) url (->> [bucket path build-category] (filter identity) (map #(c/trim % "/")) (c/join "/"))] (str "s3://" url))) (s/defschema ^:private Repo (s/pair (s/enum "essthree-releases" "essthree-snapshots") "repo-name" {:url s/Str (s/optional-key :username) s/Str (s/optional-key :password) s/Str} "repo-data")) (s/defn ^:private build-repo :- Repo [config :- RepoConfig build-category :- (s/enum "releases" "snapshots")] (let [url (build-repo-url config build-category) lein-keys [:sign-releases :checksum :update] snapshots (= "snapshots" build-category) repo-data (merge {:url url :snapshots snapshots} (select-keys config lein-keys)) aws-creds (:aws-creds config) username (or (:access-key-id (aws-credentials)) (:access-key-id aws-creds) :env/aws_access_key_id) password (or (:secret-key (aws-credentials)) (:secret-access-key aws-creds) :env/aws_secret_access_key)] [(str "essthree-" build-category) (merge repo-data {:username username :password password})])) (defn update-repositories [project] (if-let [config (get-config project)] (-> project (update-in [:repositories] conj (build-repo config "snapshots")) (update-in [:repositories] conj (build-repo config "releases"))) project))
18329
(ns lein-essthree.repository "Middleware to update project repositories to include any configured S3 buckets." (:require [cuerdas.core :as c] [lein-essthree.schemas :refer [RepoConfig]] [schema.core :as s]) (:import com.amazonaws.auth.DefaultAWSCredentialsProviderChain)) (defn aws-credentials [] (let [creds (.getCredentials (DefaultAWSCredentialsProviderChain.))] {:access-key-id (.getAWSAccessKeyId creds) :secret-key (.getAWSSecretKey creds)})) (s/defn ^:private get-config :- (s/maybe RepoConfig) [project] (get-in project [:essthree :repository])) (s/defn ^:private build-repo-url :- s/Str [config :- RepoConfig build-category :- (s/enum "releases" "snapshots")] (let [bucket (:bucket config) path (:path config) url (->> [bucket path build-category] (filter identity) (map #(c/trim % "/")) (c/join "/"))] (str "s3://" url))) (s/defschema ^:private Repo (s/pair (s/enum "essthree-releases" "essthree-snapshots") "repo-name" {:url s/Str (s/optional-key :username) s/Str (s/optional-key :password) s/Str} "repo-data")) (s/defn ^:private build-repo :- Repo [config :- RepoConfig build-category :- (s/enum "releases" "snapshots")] (let [url (build-repo-url config build-category) lein-keys [:sign-releases :checksum :update] snapshots (= "snapshots" build-category) repo-data (merge {:url url :snapshots snapshots} (select-keys config lein-keys)) aws-creds (:aws-creds config) username (or (:access-key-id (aws-credentials)) (:access-key-id aws-creds) :env/aws_access_key_id) password (or (:secret-key (aws-credentials)) (:secret-access-key aws-creds) :env/aws_secret_access_key)] [(str "essthree-" build-category) (merge repo-data {:username username :password <PASSWORD>})])) (defn update-repositories [project] (if-let [config (get-config project)] (-> project (update-in [:repositories] conj (build-repo config "snapshots")) (update-in [:repositories] conj (build-repo config "releases"))) project))
true
(ns lein-essthree.repository "Middleware to update project repositories to include any configured S3 buckets." (:require [cuerdas.core :as c] [lein-essthree.schemas :refer [RepoConfig]] [schema.core :as s]) (:import com.amazonaws.auth.DefaultAWSCredentialsProviderChain)) (defn aws-credentials [] (let [creds (.getCredentials (DefaultAWSCredentialsProviderChain.))] {:access-key-id (.getAWSAccessKeyId creds) :secret-key (.getAWSSecretKey creds)})) (s/defn ^:private get-config :- (s/maybe RepoConfig) [project] (get-in project [:essthree :repository])) (s/defn ^:private build-repo-url :- s/Str [config :- RepoConfig build-category :- (s/enum "releases" "snapshots")] (let [bucket (:bucket config) path (:path config) url (->> [bucket path build-category] (filter identity) (map #(c/trim % "/")) (c/join "/"))] (str "s3://" url))) (s/defschema ^:private Repo (s/pair (s/enum "essthree-releases" "essthree-snapshots") "repo-name" {:url s/Str (s/optional-key :username) s/Str (s/optional-key :password) s/Str} "repo-data")) (s/defn ^:private build-repo :- Repo [config :- RepoConfig build-category :- (s/enum "releases" "snapshots")] (let [url (build-repo-url config build-category) lein-keys [:sign-releases :checksum :update] snapshots (= "snapshots" build-category) repo-data (merge {:url url :snapshots snapshots} (select-keys config lein-keys)) aws-creds (:aws-creds config) username (or (:access-key-id (aws-credentials)) (:access-key-id aws-creds) :env/aws_access_key_id) password (or (:secret-key (aws-credentials)) (:secret-access-key aws-creds) :env/aws_secret_access_key)] [(str "essthree-" build-category) (merge repo-data {:username username :password PI:PASSWORD:<PASSWORD>END_PI})])) (defn update-repositories [project] (if-let [config (get-config project)] (-> project (update-in [:repositories] conj (build-repo config "snapshots")) (update-in [:repositories] conj (build-repo config "releases"))) project))
[ { "context": ";;;;;;;;;;;;\n;; A kind of jazz music ;;\n;; By Mikkel Gravgaard, 2012 ;;\n;; ;;\n;;;;;;;;", "end": 86, "score": 0.9998696446418762, "start": 70, "tag": "NAME", "value": "Mikkel Gravgaard" } ]
overtone/src/algorithmuss/jazz.clj
lemilonkh/algorithmuss
13
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; A kind of jazz music ;; ;; By Mikkel Gravgaard, 2012 ;; ;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ns ^:hw overtone.examples.compositions.jazz (:use [overtone.live] [overtone.inst.drum] [overtone.inst.synth] [overtone.examples.compositions.rotater])) (remove-event-handler :breakbeat-handler) ;; just a simple example of a synth ;; we'll use this together with the bass (definst beep [note 60] (let [src (sin-osc (midicps note)) env (env-gen (perc 0.01 0.9) :action FREE)] (* src env))) ;; drums (def ride (sample (freesound-path 436))) (def cymbal (sample (freesound-path 13254))) (def snap (sample (freesound-path 87731))) ;; swing (defn offnote? [time] (= (mod time 1 ) 0.5)) (defn swing [time] (if (offnote? time) (+ time 0.2) time)) (def tempo 160) (def metro (metronome tempo)) (defn play-bar [bar-beat bar] (doseq [hit (bar)] (let [hit-time (swing (first hit)) instr (second hit)] (at (metro (+ bar-beat hit-time)) (instr))))) (defn loop-play [bar len] (let [beat (metro)] (play-bar beat bar) (apply-by (metro (+ len beat)) #'loop-play [bar len]))) (def length 4) (defn jazzdrums [] ;; filter out all nils (filter #(not (nil? %)) (concat ;; ride on every beat (map (fn [t] [t ride]) (range 0 length)) ;; off-beat ride (map #(when (< (rand) 0.3) [% ride]) (range 0.5 length)) ;; snaps on every other beat ;; the snaps are a bit late, subtract a bit to get them on time (map (fn [t] [(- t 0.02) snap]) (range 1 length 2)) ;; off-beat snare once in a while (map #(when (< (rand) 0.1) [% snare]) (range 0.5 length)) ;; 'hit' consisting of cymbal+kick at some random off-beat ;; doing it this way allows us to place two drums on same beat (when (< (rand) 0.1) (let [t (+ 0.5 (rand-int length))] (list [t kick] [t cymbal]))) ))) (defn limit [n minimum maximum] (max minimum (min maximum n))) (def jazz-intervals '(-7 -6 -5 5 6 7)) (def maxbass 40) (def minbass 65) (defn jazzbass ([] (let [start-note 45 beat (metro) next-even (if (zero? (mod beat 2)) beat (inc beat))] (apply-by (metro next-even) (jazzbass start-note)))) ([n] (let [beat (metro) tick (metro beat) note (if (not (zero? (mod beat 2))) ;; just go half a step down (dec n) ;; keep tone inside interval ;; TODO - avoid hanging around at the limits (limit (+ n (rand-nth jazz-intervals)) maxbass minbass))] (at tick (beep note) (bass (midi->hz note))) ;; extra off-beat note with same tone (when (> 0.1 (rand)) (at (metro (+ beat (swing 0.5)) ) (beep note) (bass (midi->hz note)))) (apply-by (metro (+ beat 1)) #'jazzbass [note])))) ;; Set up rotater (def device-filter [ :midi-device "Novation DMS Ltd" "Launchpad" "Launchpad"]) (on-event (conj device-filter :note-on) (fn [e] (rotater e 0)) :handle-rotate-on) (on-event (conj device-filter :note-off) (fn [e] (rotater e 0)) :handle-rotate-off) (defn rotater-hit [note vel len] (let [start (+ 1 (metro))] (do (at (metro start) (rotater-on note vel)) (apply-by (metro (+ len start)) #'rotater-off [note])))) (defn stab [] (let [note (rand-nth (range 56 67)) vel (rand-nth (range 10 80 5)) len (rand-nth (range 0.05 0.3 0.05)) interval (rand-nth [4])] (map #(rotater-hit % vel len) (list note (+ note interval))))) ;; Place cursor at the end of these expressions ;; and do C-x e to execute them ;; Play drums ;; (loop-play #'jazzdrums length) ;; Play bass ;; (jazzbass) ;; Play some pno! ;; currently, this sends out midi, so you'll have to ;; connect something at the other end ;-) ;; Check the synth-out def in rotater.clj ;; (stab) ;; (stop) ;; TODO - a way of ensuring that we start drums+bass at (zero? (mod beat 4)) ;; TODO - some way to go to double tempo - the one below turns music into noise! ;; (metro :bpm (* 2 tempo)) ;; And back to music! ;; (metro :bpm tempo)
105137
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; A kind of jazz music ;; ;; By <NAME>, 2012 ;; ;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ns ^:hw overtone.examples.compositions.jazz (:use [overtone.live] [overtone.inst.drum] [overtone.inst.synth] [overtone.examples.compositions.rotater])) (remove-event-handler :breakbeat-handler) ;; just a simple example of a synth ;; we'll use this together with the bass (definst beep [note 60] (let [src (sin-osc (midicps note)) env (env-gen (perc 0.01 0.9) :action FREE)] (* src env))) ;; drums (def ride (sample (freesound-path 436))) (def cymbal (sample (freesound-path 13254))) (def snap (sample (freesound-path 87731))) ;; swing (defn offnote? [time] (= (mod time 1 ) 0.5)) (defn swing [time] (if (offnote? time) (+ time 0.2) time)) (def tempo 160) (def metro (metronome tempo)) (defn play-bar [bar-beat bar] (doseq [hit (bar)] (let [hit-time (swing (first hit)) instr (second hit)] (at (metro (+ bar-beat hit-time)) (instr))))) (defn loop-play [bar len] (let [beat (metro)] (play-bar beat bar) (apply-by (metro (+ len beat)) #'loop-play [bar len]))) (def length 4) (defn jazzdrums [] ;; filter out all nils (filter #(not (nil? %)) (concat ;; ride on every beat (map (fn [t] [t ride]) (range 0 length)) ;; off-beat ride (map #(when (< (rand) 0.3) [% ride]) (range 0.5 length)) ;; snaps on every other beat ;; the snaps are a bit late, subtract a bit to get them on time (map (fn [t] [(- t 0.02) snap]) (range 1 length 2)) ;; off-beat snare once in a while (map #(when (< (rand) 0.1) [% snare]) (range 0.5 length)) ;; 'hit' consisting of cymbal+kick at some random off-beat ;; doing it this way allows us to place two drums on same beat (when (< (rand) 0.1) (let [t (+ 0.5 (rand-int length))] (list [t kick] [t cymbal]))) ))) (defn limit [n minimum maximum] (max minimum (min maximum n))) (def jazz-intervals '(-7 -6 -5 5 6 7)) (def maxbass 40) (def minbass 65) (defn jazzbass ([] (let [start-note 45 beat (metro) next-even (if (zero? (mod beat 2)) beat (inc beat))] (apply-by (metro next-even) (jazzbass start-note)))) ([n] (let [beat (metro) tick (metro beat) note (if (not (zero? (mod beat 2))) ;; just go half a step down (dec n) ;; keep tone inside interval ;; TODO - avoid hanging around at the limits (limit (+ n (rand-nth jazz-intervals)) maxbass minbass))] (at tick (beep note) (bass (midi->hz note))) ;; extra off-beat note with same tone (when (> 0.1 (rand)) (at (metro (+ beat (swing 0.5)) ) (beep note) (bass (midi->hz note)))) (apply-by (metro (+ beat 1)) #'jazzbass [note])))) ;; Set up rotater (def device-filter [ :midi-device "Novation DMS Ltd" "Launchpad" "Launchpad"]) (on-event (conj device-filter :note-on) (fn [e] (rotater e 0)) :handle-rotate-on) (on-event (conj device-filter :note-off) (fn [e] (rotater e 0)) :handle-rotate-off) (defn rotater-hit [note vel len] (let [start (+ 1 (metro))] (do (at (metro start) (rotater-on note vel)) (apply-by (metro (+ len start)) #'rotater-off [note])))) (defn stab [] (let [note (rand-nth (range 56 67)) vel (rand-nth (range 10 80 5)) len (rand-nth (range 0.05 0.3 0.05)) interval (rand-nth [4])] (map #(rotater-hit % vel len) (list note (+ note interval))))) ;; Place cursor at the end of these expressions ;; and do C-x e to execute them ;; Play drums ;; (loop-play #'jazzdrums length) ;; Play bass ;; (jazzbass) ;; Play some pno! ;; currently, this sends out midi, so you'll have to ;; connect something at the other end ;-) ;; Check the synth-out def in rotater.clj ;; (stab) ;; (stop) ;; TODO - a way of ensuring that we start drums+bass at (zero? (mod beat 4)) ;; TODO - some way to go to double tempo - the one below turns music into noise! ;; (metro :bpm (* 2 tempo)) ;; And back to music! ;; (metro :bpm tempo)
true
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; A kind of jazz music ;; ;; By PI:NAME:<NAME>END_PI, 2012 ;; ;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ns ^:hw overtone.examples.compositions.jazz (:use [overtone.live] [overtone.inst.drum] [overtone.inst.synth] [overtone.examples.compositions.rotater])) (remove-event-handler :breakbeat-handler) ;; just a simple example of a synth ;; we'll use this together with the bass (definst beep [note 60] (let [src (sin-osc (midicps note)) env (env-gen (perc 0.01 0.9) :action FREE)] (* src env))) ;; drums (def ride (sample (freesound-path 436))) (def cymbal (sample (freesound-path 13254))) (def snap (sample (freesound-path 87731))) ;; swing (defn offnote? [time] (= (mod time 1 ) 0.5)) (defn swing [time] (if (offnote? time) (+ time 0.2) time)) (def tempo 160) (def metro (metronome tempo)) (defn play-bar [bar-beat bar] (doseq [hit (bar)] (let [hit-time (swing (first hit)) instr (second hit)] (at (metro (+ bar-beat hit-time)) (instr))))) (defn loop-play [bar len] (let [beat (metro)] (play-bar beat bar) (apply-by (metro (+ len beat)) #'loop-play [bar len]))) (def length 4) (defn jazzdrums [] ;; filter out all nils (filter #(not (nil? %)) (concat ;; ride on every beat (map (fn [t] [t ride]) (range 0 length)) ;; off-beat ride (map #(when (< (rand) 0.3) [% ride]) (range 0.5 length)) ;; snaps on every other beat ;; the snaps are a bit late, subtract a bit to get them on time (map (fn [t] [(- t 0.02) snap]) (range 1 length 2)) ;; off-beat snare once in a while (map #(when (< (rand) 0.1) [% snare]) (range 0.5 length)) ;; 'hit' consisting of cymbal+kick at some random off-beat ;; doing it this way allows us to place two drums on same beat (when (< (rand) 0.1) (let [t (+ 0.5 (rand-int length))] (list [t kick] [t cymbal]))) ))) (defn limit [n minimum maximum] (max minimum (min maximum n))) (def jazz-intervals '(-7 -6 -5 5 6 7)) (def maxbass 40) (def minbass 65) (defn jazzbass ([] (let [start-note 45 beat (metro) next-even (if (zero? (mod beat 2)) beat (inc beat))] (apply-by (metro next-even) (jazzbass start-note)))) ([n] (let [beat (metro) tick (metro beat) note (if (not (zero? (mod beat 2))) ;; just go half a step down (dec n) ;; keep tone inside interval ;; TODO - avoid hanging around at the limits (limit (+ n (rand-nth jazz-intervals)) maxbass minbass))] (at tick (beep note) (bass (midi->hz note))) ;; extra off-beat note with same tone (when (> 0.1 (rand)) (at (metro (+ beat (swing 0.5)) ) (beep note) (bass (midi->hz note)))) (apply-by (metro (+ beat 1)) #'jazzbass [note])))) ;; Set up rotater (def device-filter [ :midi-device "Novation DMS Ltd" "Launchpad" "Launchpad"]) (on-event (conj device-filter :note-on) (fn [e] (rotater e 0)) :handle-rotate-on) (on-event (conj device-filter :note-off) (fn [e] (rotater e 0)) :handle-rotate-off) (defn rotater-hit [note vel len] (let [start (+ 1 (metro))] (do (at (metro start) (rotater-on note vel)) (apply-by (metro (+ len start)) #'rotater-off [note])))) (defn stab [] (let [note (rand-nth (range 56 67)) vel (rand-nth (range 10 80 5)) len (rand-nth (range 0.05 0.3 0.05)) interval (rand-nth [4])] (map #(rotater-hit % vel len) (list note (+ note interval))))) ;; Place cursor at the end of these expressions ;; and do C-x e to execute them ;; Play drums ;; (loop-play #'jazzdrums length) ;; Play bass ;; (jazzbass) ;; Play some pno! ;; currently, this sends out midi, so you'll have to ;; connect something at the other end ;-) ;; Check the synth-out def in rotater.clj ;; (stab) ;; (stop) ;; TODO - a way of ensuring that we start drums+bass at (zero? (mod beat 4)) ;; TODO - some way to go to double tempo - the one below turns music into noise! ;; (metro :bpm (* 2 tempo)) ;; And back to music! ;; (metro :bpm tempo)
[ { "context": " :subprotocol \"postgresql\"\n :user \"ruuvi\"\n :password \"ruuvi\"\n :subna", "end": 171, "score": 0.8248099684715271, "start": 166, "tag": "USERNAME", "value": "ruuvi" }, { "context": "\n :user \"ruuvi\"\n :password \"ruuvi\"\n :subname \"//localhost/ruuvi_server\"}", "end": 201, "score": 0.9991862177848816, "start": 196, "tag": "PASSWORD", "value": "ruuvi" } ]
resources/server-prod-config.clj
RuuviTracker/ruuvitracker_server
1
{ ;; Configuration for standalone server :environment :prod :database {:classname "org.postgresql.Driver" :subprotocol "postgresql" :user "ruuvi" :password "ruuvi" :subname "//localhost/ruuvi_server"} :server { :type :standalone :port 8080 :max-threads 80 :enable-gzip false :websocket true } :tracker-api { :require-authentication true :allow-tracker-creation false } :client-api { :default-max-search-results 100 :allowed-max-search-results 1000 } }
68187
{ ;; Configuration for standalone server :environment :prod :database {:classname "org.postgresql.Driver" :subprotocol "postgresql" :user "ruuvi" :password "<PASSWORD>" :subname "//localhost/ruuvi_server"} :server { :type :standalone :port 8080 :max-threads 80 :enable-gzip false :websocket true } :tracker-api { :require-authentication true :allow-tracker-creation false } :client-api { :default-max-search-results 100 :allowed-max-search-results 1000 } }
true
{ ;; Configuration for standalone server :environment :prod :database {:classname "org.postgresql.Driver" :subprotocol "postgresql" :user "ruuvi" :password "PI:PASSWORD:<PASSWORD>END_PI" :subname "//localhost/ruuvi_server"} :server { :type :standalone :port 8080 :max-threads 80 :enable-gzip false :websocket true } :tracker-api { :require-authentication true :allow-tracker-creation false } :client-api { :default-max-search-results 100 :allowed-max-search-results 1000 } }
[ { "context": ";leiningen.grid\n; <br />Author: Ralph Ritoch <rritoch@gmail.com>\n\n(ns ^{:author \"Ralph Ritoch ", "end": 44, "score": 0.9998930096626282, "start": 32, "tag": "NAME", "value": "Ralph Ritoch" }, { "context": ";leiningen.grid\n; <br />Author: Ralph Ritoch <rritoch@gmail.com>\n\n(ns ^{:author \"Ralph Ritoch <rritoch@gmail.com>", "end": 63, "score": 0.9999308586120605, "start": 46, "tag": "EMAIL", "value": "rritoch@gmail.com" }, { "context": " Ralph Ritoch <rritoch@gmail.com>\n\n(ns ^{:author \"Ralph Ritoch <rritoch@gmail.com>\"\n :doc \"Grid Plugin\"\n ", "end": 93, "score": 0.9998931884765625, "start": 81, "tag": "NAME", "value": "Ralph Ritoch" }, { "context": "<rritoch@gmail.com>\n\n(ns ^{:author \"Ralph Ritoch <rritoch@gmail.com>\"\n :doc \"Grid Plugin\"\n } leiningen.grid\n ", "end": 112, "score": 0.9999300837516785, "start": 95, "tag": "EMAIL", "value": "rritoch@gmail.com" } ]
data/test/clojure/b5110b7d8a5f298d404b35886a973372628383c9grid.clj
harshp8l/deep-learning-lang-detection
84
;leiningen.grid ; <br />Author: Ralph Ritoch <rritoch@gmail.com> (ns ^{:author "Ralph Ritoch <rritoch@gmail.com>" :doc "Grid Plugin" } leiningen.grid (:use [leiningen.help :only (help-for subtask-help-for)] [leiningen.grid.push :only (push)] [leiningen.grid.bundle :only (bundle)] [leiningen.grid.wipe-deps :only (wipe-deps)] [leiningen.grid.tomcat-deploy :only (tomcat-deploy)])) (defn grid "Manage a Grid Platform based application." {:help-arglists '([push bundle wipe-deps tomcat-deploy]) :subtasks [#'push #'bundle #'wipe-deps #'tomcat-deploy]} ([project] (println (help-for project "grid"))) ([project subtask & args] (case subtask "push" (apply push project args) "bundle" (apply bundle project args) "wipe-deps" (apply wipe-deps project args) "tomcat-deploy" (apply tomcat-deploy project args) (println "Subtask" (str \" subtask \") "not found." (subtask-help-for *ns* #'grid))))) ;; End of namespace leiningen.grid
67234
;leiningen.grid ; <br />Author: <NAME> <<EMAIL>> (ns ^{:author "<NAME> <<EMAIL>>" :doc "Grid Plugin" } leiningen.grid (:use [leiningen.help :only (help-for subtask-help-for)] [leiningen.grid.push :only (push)] [leiningen.grid.bundle :only (bundle)] [leiningen.grid.wipe-deps :only (wipe-deps)] [leiningen.grid.tomcat-deploy :only (tomcat-deploy)])) (defn grid "Manage a Grid Platform based application." {:help-arglists '([push bundle wipe-deps tomcat-deploy]) :subtasks [#'push #'bundle #'wipe-deps #'tomcat-deploy]} ([project] (println (help-for project "grid"))) ([project subtask & args] (case subtask "push" (apply push project args) "bundle" (apply bundle project args) "wipe-deps" (apply wipe-deps project args) "tomcat-deploy" (apply tomcat-deploy project args) (println "Subtask" (str \" subtask \") "not found." (subtask-help-for *ns* #'grid))))) ;; End of namespace leiningen.grid
true
;leiningen.grid ; <br />Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> (ns ^{:author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>" :doc "Grid Plugin" } leiningen.grid (:use [leiningen.help :only (help-for subtask-help-for)] [leiningen.grid.push :only (push)] [leiningen.grid.bundle :only (bundle)] [leiningen.grid.wipe-deps :only (wipe-deps)] [leiningen.grid.tomcat-deploy :only (tomcat-deploy)])) (defn grid "Manage a Grid Platform based application." {:help-arglists '([push bundle wipe-deps tomcat-deploy]) :subtasks [#'push #'bundle #'wipe-deps #'tomcat-deploy]} ([project] (println (help-for project "grid"))) ([project subtask & args] (case subtask "push" (apply push project args) "bundle" (apply bundle project args) "wipe-deps" (apply wipe-deps project args) "tomcat-deploy" (apply tomcat-deploy project args) (println "Subtask" (str \" subtask \") "not found." (subtask-help-for *ns* #'grid))))) ;; End of namespace leiningen.grid
[ { "context": " (let [dataobj (clj->js {\"data\" [[\"Tiger Nixon\" \"System Architect\" \"Edinburgh\" 61 \"2011/04/25\" \"", "end": 351, "score": 0.5600639581680298, "start": 341, "tag": "NAME", "value": "iger Nixon" }, { "context": " [\"Tim Garrett\"\t\"Accountant\"\t\"Tokyo\"\t63\t\"2011/07/25\"\t\"$170,750\"]", "end": 477, "score": 0.9998567700386047, "start": 466, "tag": "NAME", "value": "Tim Garrett" }, { "context": "00\"]\n [\"Tim Garrett\" \"Accountant\" \"Tokyo\" 63 \"2011/07/25\" \"$170,750\"]", "end": 1870, "score": 0.9998756051063538, "start": 1859, "tag": "NAME", "value": "Tim Garrett" }, { "context": "clj->js [\n; [\"Poppy Smith\"\n; \"Research", "end": 3078, "score": 0.9998738169670105, "start": 3067, "tag": "NAME", "value": "Poppy Smith" } ]
src/hello_datatables/core.cljs
staypufd/DataTables_from_ClojureScript_in_DevCards_PlayGround
0
(ns hello_datatables.core (:require #_[om.core :as om :include-macros true] [sablono.core :as sab :include-macros true]) (:require-macros [devcards.core :as dc :refer [defcard deftest dom-node]])) (enable-console-print!) ;(defonce dt ; (.ready (js/$ js/document()) ; (let [dataobj (clj->js {"data" [["Tiger Nixon" "System Architect" "Edinburgh" 61 "2011/04/25" "$320,800"] ; ["Tim Garrett" "Accountant" "Tokyo" 63 "2011/07/25" "$170,750"]] ; "columns" ; [{ "title" "Name" }, ; { "title" "Position" }, ; { "title" "Office" }, ; { "title" "Age" }, ; { "title" "Start date" }, ; { "title" "Salary" }]})] ; (.DataTable (js/jQuery "#example") dataobj)))) (defcard my-first-card (sab/html [:div [:h1 "Devcards is freaking awesome!"]])) (defcard my-second-card (sab/html [:div [:h1 "Table"] [:table {:id "example"} ]])) (defcard (fn [data-atom owner] (sab/html [:div [:h2 "Example: fn that returns React"] (prn-str data-atom)])) {:count 50}) (defcard trigger-datatables-data-file-and-style-example-table (fn [data-atom owner] (js/console.log "before .ready should be called") (.ready (js/$ js/document()) (let [dataobj (clj->js {"data" [["Tiger Nixon" "System Architect" "Edinburgh" 61 "2011/04/25" "$320,800"] ["Tim Garrett" "Accountant" "Tokyo" 63 "2011/07/25" "$170,750"]] "columns" [{"title" "Name"}, {"title" "Position"}, {"title" "Office"}, {"title" "Age"}, {"title" "Start date"}, {"title" "Salary"}]})] (.DataTable (js/jQuery "#example") dataobj))) (js/console.log "after end of .ready") "Function to set up DataTable called after documnet was ready") ;; This just is initial data to that function. Doesn't matter what we pass as we just want the side-effect ;; of cuasing it to update the #example table element in the html. ;; We could do the data and columns init via this data passed in if we wanted too! (:foo nil) ) ;(defcard add-row-to-table ; (fn [data-atom owner] ; (let [t (js/jQuery "#example") ; r (.row() t) ] ; (.add r (clj->js [ ; ["Poppy Smith" ; "Researcher" ; "Atlanta, GA" ; "25" ; "2012/02/14" ; "$58,500" ; ]]))) ; (.draw (js/Jquery "#example") true) ; ) ; {:foo nil} ; ) ;(defcard {} ; main obj ; {} ; initial data ; {:heading true}) ;(defn main [] ; ;; conditionally start the app based on wether the #main-app-area ; ;; node is on the page ; (if-let [node (.getElementById js/document "main-app-area")] ; (js/React.render (sab/html [:div "This is working"]) node))) ; ;(main) ;; remember to run lein figwheel and then browse to ;; http://localhost:3449/cards.html
67351
(ns hello_datatables.core (:require #_[om.core :as om :include-macros true] [sablono.core :as sab :include-macros true]) (:require-macros [devcards.core :as dc :refer [defcard deftest dom-node]])) (enable-console-print!) ;(defonce dt ; (.ready (js/$ js/document()) ; (let [dataobj (clj->js {"data" [["T<NAME>" "System Architect" "Edinburgh" 61 "2011/04/25" "$320,800"] ; ["<NAME>" "Accountant" "Tokyo" 63 "2011/07/25" "$170,750"]] ; "columns" ; [{ "title" "Name" }, ; { "title" "Position" }, ; { "title" "Office" }, ; { "title" "Age" }, ; { "title" "Start date" }, ; { "title" "Salary" }]})] ; (.DataTable (js/jQuery "#example") dataobj)))) (defcard my-first-card (sab/html [:div [:h1 "Devcards is freaking awesome!"]])) (defcard my-second-card (sab/html [:div [:h1 "Table"] [:table {:id "example"} ]])) (defcard (fn [data-atom owner] (sab/html [:div [:h2 "Example: fn that returns React"] (prn-str data-atom)])) {:count 50}) (defcard trigger-datatables-data-file-and-style-example-table (fn [data-atom owner] (js/console.log "before .ready should be called") (.ready (js/$ js/document()) (let [dataobj (clj->js {"data" [["Tiger Nixon" "System Architect" "Edinburgh" 61 "2011/04/25" "$320,800"] ["<NAME>" "Accountant" "Tokyo" 63 "2011/07/25" "$170,750"]] "columns" [{"title" "Name"}, {"title" "Position"}, {"title" "Office"}, {"title" "Age"}, {"title" "Start date"}, {"title" "Salary"}]})] (.DataTable (js/jQuery "#example") dataobj))) (js/console.log "after end of .ready") "Function to set up DataTable called after documnet was ready") ;; This just is initial data to that function. Doesn't matter what we pass as we just want the side-effect ;; of cuasing it to update the #example table element in the html. ;; We could do the data and columns init via this data passed in if we wanted too! (:foo nil) ) ;(defcard add-row-to-table ; (fn [data-atom owner] ; (let [t (js/jQuery "#example") ; r (.row() t) ] ; (.add r (clj->js [ ; ["<NAME>" ; "Researcher" ; "Atlanta, GA" ; "25" ; "2012/02/14" ; "$58,500" ; ]]))) ; (.draw (js/Jquery "#example") true) ; ) ; {:foo nil} ; ) ;(defcard {} ; main obj ; {} ; initial data ; {:heading true}) ;(defn main [] ; ;; conditionally start the app based on wether the #main-app-area ; ;; node is on the page ; (if-let [node (.getElementById js/document "main-app-area")] ; (js/React.render (sab/html [:div "This is working"]) node))) ; ;(main) ;; remember to run lein figwheel and then browse to ;; http://localhost:3449/cards.html
true
(ns hello_datatables.core (:require #_[om.core :as om :include-macros true] [sablono.core :as sab :include-macros true]) (:require-macros [devcards.core :as dc :refer [defcard deftest dom-node]])) (enable-console-print!) ;(defonce dt ; (.ready (js/$ js/document()) ; (let [dataobj (clj->js {"data" [["TPI:NAME:<NAME>END_PI" "System Architect" "Edinburgh" 61 "2011/04/25" "$320,800"] ; ["PI:NAME:<NAME>END_PI" "Accountant" "Tokyo" 63 "2011/07/25" "$170,750"]] ; "columns" ; [{ "title" "Name" }, ; { "title" "Position" }, ; { "title" "Office" }, ; { "title" "Age" }, ; { "title" "Start date" }, ; { "title" "Salary" }]})] ; (.DataTable (js/jQuery "#example") dataobj)))) (defcard my-first-card (sab/html [:div [:h1 "Devcards is freaking awesome!"]])) (defcard my-second-card (sab/html [:div [:h1 "Table"] [:table {:id "example"} ]])) (defcard (fn [data-atom owner] (sab/html [:div [:h2 "Example: fn that returns React"] (prn-str data-atom)])) {:count 50}) (defcard trigger-datatables-data-file-and-style-example-table (fn [data-atom owner] (js/console.log "before .ready should be called") (.ready (js/$ js/document()) (let [dataobj (clj->js {"data" [["Tiger Nixon" "System Architect" "Edinburgh" 61 "2011/04/25" "$320,800"] ["PI:NAME:<NAME>END_PI" "Accountant" "Tokyo" 63 "2011/07/25" "$170,750"]] "columns" [{"title" "Name"}, {"title" "Position"}, {"title" "Office"}, {"title" "Age"}, {"title" "Start date"}, {"title" "Salary"}]})] (.DataTable (js/jQuery "#example") dataobj))) (js/console.log "after end of .ready") "Function to set up DataTable called after documnet was ready") ;; This just is initial data to that function. Doesn't matter what we pass as we just want the side-effect ;; of cuasing it to update the #example table element in the html. ;; We could do the data and columns init via this data passed in if we wanted too! (:foo nil) ) ;(defcard add-row-to-table ; (fn [data-atom owner] ; (let [t (js/jQuery "#example") ; r (.row() t) ] ; (.add r (clj->js [ ; ["PI:NAME:<NAME>END_PI" ; "Researcher" ; "Atlanta, GA" ; "25" ; "2012/02/14" ; "$58,500" ; ]]))) ; (.draw (js/Jquery "#example") true) ; ) ; {:foo nil} ; ) ;(defcard {} ; main obj ; {} ; initial data ; {:heading true}) ;(defn main [] ; ;; conditionally start the app based on wether the #main-app-area ; ;; node is on the page ; (if-let [node (.getElementById js/document "main-app-area")] ; (js/React.render (sab/html [:div "This is working"]) node))) ; ;(main) ;; remember to run lein figwheel and then browse to ;; http://localhost:3449/cards.html
[ { "context": ";; Copyright (C) 2015, Jozef Wagner. All rights reserved.\n;;\n;; The use and distribut", "end": 35, "score": 0.9998257756233215, "start": 23, "tag": "NAME", "value": "Jozef Wagner" } ]
data/train/clojure/905d8a8a77792917f21256d61096995965e06950cfg.clj
harshp8l/deep-learning-lang-detection
84
;; Copyright (C) 2015, Jozef Wagner. 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 jogurt.util.cfg "Manage project's configuration." (:api dunaj) (:require [environ.core :as ec] [dunaj.string :as ds])) (defn cfg :- {} "Returns config map. Merges contents of config.edn on a classpath with environment variables, that are fetched with environ and put under :env key." [] (with-scope (let [conf (parse-whole edn (slurp "cp:config.edn")) env ec/env] (assoc conf :env env)))) (defn nget-in :- (Maybe Number) "Like get-in, but parses value with edn reader and asserts that it is a number. Does not parse default value. Allows nil values." ([cfg :- {}, ks :- Any] (nget-in cfg ks nil)) ([cfg :- {}, ks :- Any, default-value :- (Maybe Number)] (let [ks (if (vector? ks) ks (->vec ks))] (when-let [v (get-in cfg ks default-value)] (cond (identical? v default-value) v (number? v) v :else (let [pv (parse-whole edn v)] (when-not (number? pv) (throw (illegal-argument "cannot parse value to number"))) pv)))))) (defn sget-in :- (Maybe String) "Like get-in, but coerces to string. Does not parse default value. Allows nil values." ([cfg :- {}, ks :- Any] (sget-in cfg ks nil)) ([cfg :- {}, ks :- Any, default-value :- (Maybe String)] (let [ks (if (vector? ks) ks (->vec ks))] (when-let [v (get-in cfg ks default-value)] (cond (identical? v default-value) v (nil? v) v (string? v) v (canonical? v) (canonical v) :else (->str v)))))) (def bmap {"true" true "false" false "t" true "f" false "1" true "0" false "yes" true "no" false "on" true "off" false "enable" true "disable" false "enabled" true "disabled" false "default" :default}) (defn bget-in :- Boolean "Like get-in, but coerces to boolean. Does not parse default value. Defaults to false." ([cfg :- {}, ks :- Any] (bget-in cfg ks false)) ([cfg :- {}, ks :- Any, default-value :- Boolean] (if-let [s (sget-in cfg ks nil)] (let [r (get bmap (ds/lower-case s))] (cond (nil? r) (throw (illegal-argument "value not recognized")) (identical? :default r) default-value :else r))))) (defn bget :- Boolean "Like get, but coerces to boolean. Does not parse default value. Defaults to false" ([cfg :- {}, k :- Any] (bget-in cfg [k])) ([cfg :- {}, k :- Any, default :- Boolean] (bget-in cfg [k] default))) (defn sget :- (Maybe String) "Like get, but coerces to string. Does not parse default value. Allows nil values." ([cfg :- {}, k :- Any] (sget-in cfg [k])) ([cfg :- {}, k :- Any, default :- (Maybe String)] (sget-in cfg [k] default))) (defn nget :- (Maybe Number) "Like get, but coerces to number. Does not parse default value. Allows nil values." ([cfg :- {}, k :- Any] (nget-in cfg [k])) ([cfg :- {}, k :- Any, default :- (Maybe Number)] (nget-in cfg [k] default)))
110866
;; Copyright (C) 2015, <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 jogurt.util.cfg "Manage project's configuration." (:api dunaj) (:require [environ.core :as ec] [dunaj.string :as ds])) (defn cfg :- {} "Returns config map. Merges contents of config.edn on a classpath with environment variables, that are fetched with environ and put under :env key." [] (with-scope (let [conf (parse-whole edn (slurp "cp:config.edn")) env ec/env] (assoc conf :env env)))) (defn nget-in :- (Maybe Number) "Like get-in, but parses value with edn reader and asserts that it is a number. Does not parse default value. Allows nil values." ([cfg :- {}, ks :- Any] (nget-in cfg ks nil)) ([cfg :- {}, ks :- Any, default-value :- (Maybe Number)] (let [ks (if (vector? ks) ks (->vec ks))] (when-let [v (get-in cfg ks default-value)] (cond (identical? v default-value) v (number? v) v :else (let [pv (parse-whole edn v)] (when-not (number? pv) (throw (illegal-argument "cannot parse value to number"))) pv)))))) (defn sget-in :- (Maybe String) "Like get-in, but coerces to string. Does not parse default value. Allows nil values." ([cfg :- {}, ks :- Any] (sget-in cfg ks nil)) ([cfg :- {}, ks :- Any, default-value :- (Maybe String)] (let [ks (if (vector? ks) ks (->vec ks))] (when-let [v (get-in cfg ks default-value)] (cond (identical? v default-value) v (nil? v) v (string? v) v (canonical? v) (canonical v) :else (->str v)))))) (def bmap {"true" true "false" false "t" true "f" false "1" true "0" false "yes" true "no" false "on" true "off" false "enable" true "disable" false "enabled" true "disabled" false "default" :default}) (defn bget-in :- Boolean "Like get-in, but coerces to boolean. Does not parse default value. Defaults to false." ([cfg :- {}, ks :- Any] (bget-in cfg ks false)) ([cfg :- {}, ks :- Any, default-value :- Boolean] (if-let [s (sget-in cfg ks nil)] (let [r (get bmap (ds/lower-case s))] (cond (nil? r) (throw (illegal-argument "value not recognized")) (identical? :default r) default-value :else r))))) (defn bget :- Boolean "Like get, but coerces to boolean. Does not parse default value. Defaults to false" ([cfg :- {}, k :- Any] (bget-in cfg [k])) ([cfg :- {}, k :- Any, default :- Boolean] (bget-in cfg [k] default))) (defn sget :- (Maybe String) "Like get, but coerces to string. Does not parse default value. Allows nil values." ([cfg :- {}, k :- Any] (sget-in cfg [k])) ([cfg :- {}, k :- Any, default :- (Maybe String)] (sget-in cfg [k] default))) (defn nget :- (Maybe Number) "Like get, but coerces to number. Does not parse default value. Allows nil values." ([cfg :- {}, k :- Any] (nget-in cfg [k])) ([cfg :- {}, k :- Any, default :- (Maybe Number)] (nget-in cfg [k] default)))
true
;; Copyright (C) 2015, 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 jogurt.util.cfg "Manage project's configuration." (:api dunaj) (:require [environ.core :as ec] [dunaj.string :as ds])) (defn cfg :- {} "Returns config map. Merges contents of config.edn on a classpath with environment variables, that are fetched with environ and put under :env key." [] (with-scope (let [conf (parse-whole edn (slurp "cp:config.edn")) env ec/env] (assoc conf :env env)))) (defn nget-in :- (Maybe Number) "Like get-in, but parses value with edn reader and asserts that it is a number. Does not parse default value. Allows nil values." ([cfg :- {}, ks :- Any] (nget-in cfg ks nil)) ([cfg :- {}, ks :- Any, default-value :- (Maybe Number)] (let [ks (if (vector? ks) ks (->vec ks))] (when-let [v (get-in cfg ks default-value)] (cond (identical? v default-value) v (number? v) v :else (let [pv (parse-whole edn v)] (when-not (number? pv) (throw (illegal-argument "cannot parse value to number"))) pv)))))) (defn sget-in :- (Maybe String) "Like get-in, but coerces to string. Does not parse default value. Allows nil values." ([cfg :- {}, ks :- Any] (sget-in cfg ks nil)) ([cfg :- {}, ks :- Any, default-value :- (Maybe String)] (let [ks (if (vector? ks) ks (->vec ks))] (when-let [v (get-in cfg ks default-value)] (cond (identical? v default-value) v (nil? v) v (string? v) v (canonical? v) (canonical v) :else (->str v)))))) (def bmap {"true" true "false" false "t" true "f" false "1" true "0" false "yes" true "no" false "on" true "off" false "enable" true "disable" false "enabled" true "disabled" false "default" :default}) (defn bget-in :- Boolean "Like get-in, but coerces to boolean. Does not parse default value. Defaults to false." ([cfg :- {}, ks :- Any] (bget-in cfg ks false)) ([cfg :- {}, ks :- Any, default-value :- Boolean] (if-let [s (sget-in cfg ks nil)] (let [r (get bmap (ds/lower-case s))] (cond (nil? r) (throw (illegal-argument "value not recognized")) (identical? :default r) default-value :else r))))) (defn bget :- Boolean "Like get, but coerces to boolean. Does not parse default value. Defaults to false" ([cfg :- {}, k :- Any] (bget-in cfg [k])) ([cfg :- {}, k :- Any, default :- Boolean] (bget-in cfg [k] default))) (defn sget :- (Maybe String) "Like get, but coerces to string. Does not parse default value. Allows nil values." ([cfg :- {}, k :- Any] (sget-in cfg [k])) ([cfg :- {}, k :- Any, default :- (Maybe String)] (sget-in cfg [k] default))) (defn nget :- (Maybe Number) "Like get, but coerces to number. Does not parse default value. Allows nil values." ([cfg :- {}, k :- Any] (nget-in cfg [k])) ([cfg :- {}, k :- Any, default :- (Maybe Number)] (nget-in cfg [k] default)))
[ { "context": "tartrek.components.starship.interface\n {:author \"David Harrigan\"}\n (:require\n [startrek.components.starship.im", "end": 69, "score": 0.9998793601989746, "start": 55, "tag": "NAME", "value": "David Harrigan" } ]
src/startrek/components/starship/interface.clj
dharrigan/startrek
17
(ns startrek.components.starship.interface {:author "David Harrigan"} (:require [startrek.components.starship.impl :as starship])) (set! *warn-on-reflection* true) ;; ;; Alphabetical order please! ;; (defn create [starship app-config] (starship/create starship app-config)) (defn delete [query app-config] (starship/delete query app-config)) (defn find-by-id [query app-config] (starship/find-by-id query app-config)) (defn modify [query app-config] (starship/modify query app-config)) (defn search [query app-config] (starship/search query app-config))
85869
(ns startrek.components.starship.interface {:author "<NAME>"} (:require [startrek.components.starship.impl :as starship])) (set! *warn-on-reflection* true) ;; ;; Alphabetical order please! ;; (defn create [starship app-config] (starship/create starship app-config)) (defn delete [query app-config] (starship/delete query app-config)) (defn find-by-id [query app-config] (starship/find-by-id query app-config)) (defn modify [query app-config] (starship/modify query app-config)) (defn search [query app-config] (starship/search query app-config))
true
(ns startrek.components.starship.interface {:author "PI:NAME:<NAME>END_PI"} (:require [startrek.components.starship.impl :as starship])) (set! *warn-on-reflection* true) ;; ;; Alphabetical order please! ;; (defn create [starship app-config] (starship/create starship app-config)) (defn delete [query app-config] (starship/delete query app-config)) (defn find-by-id [query app-config] (starship/find-by-id query app-config)) (defn modify [query app-config] (starship/modify query app-config)) (defn search [query app-config] (starship/search query app-config))
[ { "context": "sers\"\n :not-loaded \"Not Loaded\"\n :password \"Password\"\n :rate \"Rate\"\n :rate-source \"Rate Source\"\n", "end": 1445, "score": 0.9995012283325195, "start": 1437, "tag": "PASSWORD", "value": "Password" }, { "context": "ggle\"\n :transactions \"Transactions\"\n :user \"User\"\n :username \"Username\"\n :users \"Users\"\n ", "end": 1797, "score": 0.9743849635124207, "start": 1793, "tag": "USERNAME", "value": "User" }, { "context": "ns \"Transactions\"\n :user \"User\"\n :username \"Username\"\n :users \"Users\"\n :user-label \"User: %1\"\n ", "end": 1822, "score": 0.999045729637146, "start": 1814, "tag": "USERNAME", "value": "Username" } ]
src/main/dinsro/translations.cljc
duck1123/dinsro
2
(ns dinsro.translations (:require [taoensso.tempura :as tempura] [taoensso.timbre :as log])) (def dictionary {;; :missing {:missing "Missing: %1"} :en {:missing (fn [arg1 arg2] (str "Missing text: " arg1 " - " arg2)) :about "About" :actions "Actions" :account "Account" :accounts "Accounts" :admin "Admin" :buttons "Buttons" :categories "Categories" :currencies "Currencies" :currency "Currency" :currency-label "Currency: %1" :date "Date" :delete "Delete" :description "Description" :fetch-accounts "Fetch Accounts: %1" :fetch-categories "Fetch Categories: %1" :fetch-currencies "Fetch Currencies: %1" :fetch-currency "Fetch Currency: %1 -> %2" :fetch-rate-sources "Fetch Rate Sources: %1" :fetch-rates "Fetch Rates: %1" :fetch-transactions "Fetch Transactions: %1" :fetch-users "Fetch Users: %1" :home-page "Home Page" :id "Id" :id-label "Id: %1" :index-accounts "Index Accounts" :initial-value "Initial Value" :initial-value-label "Initial Value: %1" :login "Login" :logout "Logout" :name "Name" :name-label "Name: %1" :no-accounts "No Accounts" :no-categories "No Categories" :no-currencies "No Currencies" :no-rate-sources "No Rate Sources" :no-rates "No Rates" :no-transactions "No Transactions" :no-users "No Users" :not-loaded "Not Loaded" :password "Password" :rate "Rate" :rate-source "Rate Source" :rate-sources "Rate Sources" :rate-sources-label "Rate Sources: %1" :rates "Rates" :register "Register" :sats "sats" :settings "Settings" :show-account "Show Account" :submit "Submit" :time "Time" :toggle "Toggle" :transactions "Transactions" :user "User" :username "Username" :users "Users" :user-label "User: %1" :url "Url" :value "Value"}}) (def opts {:dict dictionary}) (defn tr [a & b] (apply tempura/tr opts [:missing :en] a b))
8478
(ns dinsro.translations (:require [taoensso.tempura :as tempura] [taoensso.timbre :as log])) (def dictionary {;; :missing {:missing "Missing: %1"} :en {:missing (fn [arg1 arg2] (str "Missing text: " arg1 " - " arg2)) :about "About" :actions "Actions" :account "Account" :accounts "Accounts" :admin "Admin" :buttons "Buttons" :categories "Categories" :currencies "Currencies" :currency "Currency" :currency-label "Currency: %1" :date "Date" :delete "Delete" :description "Description" :fetch-accounts "Fetch Accounts: %1" :fetch-categories "Fetch Categories: %1" :fetch-currencies "Fetch Currencies: %1" :fetch-currency "Fetch Currency: %1 -> %2" :fetch-rate-sources "Fetch Rate Sources: %1" :fetch-rates "Fetch Rates: %1" :fetch-transactions "Fetch Transactions: %1" :fetch-users "Fetch Users: %1" :home-page "Home Page" :id "Id" :id-label "Id: %1" :index-accounts "Index Accounts" :initial-value "Initial Value" :initial-value-label "Initial Value: %1" :login "Login" :logout "Logout" :name "Name" :name-label "Name: %1" :no-accounts "No Accounts" :no-categories "No Categories" :no-currencies "No Currencies" :no-rate-sources "No Rate Sources" :no-rates "No Rates" :no-transactions "No Transactions" :no-users "No Users" :not-loaded "Not Loaded" :password "<PASSWORD>" :rate "Rate" :rate-source "Rate Source" :rate-sources "Rate Sources" :rate-sources-label "Rate Sources: %1" :rates "Rates" :register "Register" :sats "sats" :settings "Settings" :show-account "Show Account" :submit "Submit" :time "Time" :toggle "Toggle" :transactions "Transactions" :user "User" :username "Username" :users "Users" :user-label "User: %1" :url "Url" :value "Value"}}) (def opts {:dict dictionary}) (defn tr [a & b] (apply tempura/tr opts [:missing :en] a b))
true
(ns dinsro.translations (:require [taoensso.tempura :as tempura] [taoensso.timbre :as log])) (def dictionary {;; :missing {:missing "Missing: %1"} :en {:missing (fn [arg1 arg2] (str "Missing text: " arg1 " - " arg2)) :about "About" :actions "Actions" :account "Account" :accounts "Accounts" :admin "Admin" :buttons "Buttons" :categories "Categories" :currencies "Currencies" :currency "Currency" :currency-label "Currency: %1" :date "Date" :delete "Delete" :description "Description" :fetch-accounts "Fetch Accounts: %1" :fetch-categories "Fetch Categories: %1" :fetch-currencies "Fetch Currencies: %1" :fetch-currency "Fetch Currency: %1 -> %2" :fetch-rate-sources "Fetch Rate Sources: %1" :fetch-rates "Fetch Rates: %1" :fetch-transactions "Fetch Transactions: %1" :fetch-users "Fetch Users: %1" :home-page "Home Page" :id "Id" :id-label "Id: %1" :index-accounts "Index Accounts" :initial-value "Initial Value" :initial-value-label "Initial Value: %1" :login "Login" :logout "Logout" :name "Name" :name-label "Name: %1" :no-accounts "No Accounts" :no-categories "No Categories" :no-currencies "No Currencies" :no-rate-sources "No Rate Sources" :no-rates "No Rates" :no-transactions "No Transactions" :no-users "No Users" :not-loaded "Not Loaded" :password "PI:PASSWORD:<PASSWORD>END_PI" :rate "Rate" :rate-source "Rate Source" :rate-sources "Rate Sources" :rate-sources-label "Rate Sources: %1" :rates "Rates" :register "Register" :sats "sats" :settings "Settings" :show-account "Show Account" :submit "Submit" :time "Time" :toggle "Toggle" :transactions "Transactions" :user "User" :username "Username" :users "Users" :user-label "User: %1" :url "Url" :value "Value"}}) (def opts {:dict dictionary}) (defn tr [a & b] (apply tempura/tr opts [:missing :en] a b))
[ { "context": "/day1.input\"))\n\n; --- Day 1: Not Quite Lisp ---\n\n; Santa was hoping for a white Christmas, but his wea", "end": 125, "score": 0.8828002214431763, "start": 124, "tag": "NAME", "value": "S" }, { "context": " luck!\n\n; Here's an easy puzzle to warm you up.\n\n; Santa is trying to deliver presents in a large apar", "end": 592, "score": 0.7866755723953247, "start": 591, "tag": "NAME", "value": "S" } ]
src/aoc/day1.clj
magopian/adventofcode
0
; http://adventofcode.com/day/1 (ns aoc.day1) (def input (slurp "src/aoc/day1.input")) ; --- Day 1: Not Quite Lisp --- ; Santa was hoping for a white Christmas, but his weather machine's "snow" ; function is powered by stars, and he's fresh out! To save Christmas, he needs ; you to collect fifty stars by December 25th. ; Collect stars by helping Santa solve puzzles. Two puzzles will be made ; available on each day in the advent calendar; the second puzzle is unlocked ; when you complete the first. Each puzzle grants one star. Good luck! ; Here's an easy puzzle to warm you up. ; Santa is trying to deliver presents in a large apartment building, but he ; can't find the right floor - the directions he got are a little confusing. He ; starts on the ground floor (floor 0) and then follows the instructions one ; character at a time. ; An opening parenthesis, (, means he should go up one floor, and a closing ; parenthesis, ), means he should go down one floor. ; The apartment building is very tall, and the basement is very deep; he will ; never find the top or bottom floors. ; For example: ; (()) and ()() both result in floor 0. ; ((( and (()(()( both result in floor 3. ; ))((((( also results in floor 3. ; ()) and ))( both result in floor -1 (the first basement level). ; ))) and )())()) both result in floor -3. ; To what floor do the instructions take Santa? (defn get-floor [parens] (reduce (fn up-or-down [floor paren] (if (= paren \() (inc floor) (dec floor))) 0 parens)) (assert (= 0 (get-floor "(())") (get-floor "()()"))) (assert (= 3 (get-floor "(((") (get-floor "(()(()("))) (assert (= 3 (get-floor "))((((("))) (assert (= -1 (get-floor "())") (get-floor "))("))) (assert (= -3 (get-floor ")))") (get-floor ")())())"))) (defn part1 [] (println "The floor is" (get-floor input))) ; --- Part Two --- ; Now, given the same instructions, find the position of the first character ; that causes him to enter the basement (floor -1). The first character in the ; instructions has position 1, the second character has position 2, and so on. ; For example: ; ) causes him to enter the basement at character position 1. ; ()()) causes him to enter the basement at character position 5. ; What is the position of the character that causes Santa to first enter the ; basement? (defn basement? [floor] (< floor 0)) (defn get-position [parens] (reduce (fn floor-and-position [[floor position] paren] (let [new-position (inc position) new-floor (if (= paren \() (inc floor) (dec floor))] (if (basement? new-floor) (reduced new-position) [new-floor new-position]))) [0 0] parens) ) (assert (= 1 (get-position ")"))) (assert (= 5 (get-position "()())"))) (defn part2 [] (println "The position of the character that causes Santa to first" "enter the basement is" (get-position input)))
77366
; http://adventofcode.com/day/1 (ns aoc.day1) (def input (slurp "src/aoc/day1.input")) ; --- Day 1: Not Quite Lisp --- ; <NAME>anta was hoping for a white Christmas, but his weather machine's "snow" ; function is powered by stars, and he's fresh out! To save Christmas, he needs ; you to collect fifty stars by December 25th. ; Collect stars by helping Santa solve puzzles. Two puzzles will be made ; available on each day in the advent calendar; the second puzzle is unlocked ; when you complete the first. Each puzzle grants one star. Good luck! ; Here's an easy puzzle to warm you up. ; <NAME>anta is trying to deliver presents in a large apartment building, but he ; can't find the right floor - the directions he got are a little confusing. He ; starts on the ground floor (floor 0) and then follows the instructions one ; character at a time. ; An opening parenthesis, (, means he should go up one floor, and a closing ; parenthesis, ), means he should go down one floor. ; The apartment building is very tall, and the basement is very deep; he will ; never find the top or bottom floors. ; For example: ; (()) and ()() both result in floor 0. ; ((( and (()(()( both result in floor 3. ; ))((((( also results in floor 3. ; ()) and ))( both result in floor -1 (the first basement level). ; ))) and )())()) both result in floor -3. ; To what floor do the instructions take Santa? (defn get-floor [parens] (reduce (fn up-or-down [floor paren] (if (= paren \() (inc floor) (dec floor))) 0 parens)) (assert (= 0 (get-floor "(())") (get-floor "()()"))) (assert (= 3 (get-floor "(((") (get-floor "(()(()("))) (assert (= 3 (get-floor "))((((("))) (assert (= -1 (get-floor "())") (get-floor "))("))) (assert (= -3 (get-floor ")))") (get-floor ")())())"))) (defn part1 [] (println "The floor is" (get-floor input))) ; --- Part Two --- ; Now, given the same instructions, find the position of the first character ; that causes him to enter the basement (floor -1). The first character in the ; instructions has position 1, the second character has position 2, and so on. ; For example: ; ) causes him to enter the basement at character position 1. ; ()()) causes him to enter the basement at character position 5. ; What is the position of the character that causes Santa to first enter the ; basement? (defn basement? [floor] (< floor 0)) (defn get-position [parens] (reduce (fn floor-and-position [[floor position] paren] (let [new-position (inc position) new-floor (if (= paren \() (inc floor) (dec floor))] (if (basement? new-floor) (reduced new-position) [new-floor new-position]))) [0 0] parens) ) (assert (= 1 (get-position ")"))) (assert (= 5 (get-position "()())"))) (defn part2 [] (println "The position of the character that causes Santa to first" "enter the basement is" (get-position input)))
true
; http://adventofcode.com/day/1 (ns aoc.day1) (def input (slurp "src/aoc/day1.input")) ; --- Day 1: Not Quite Lisp --- ; PI:NAME:<NAME>END_PIanta was hoping for a white Christmas, but his weather machine's "snow" ; function is powered by stars, and he's fresh out! To save Christmas, he needs ; you to collect fifty stars by December 25th. ; Collect stars by helping Santa solve puzzles. Two puzzles will be made ; available on each day in the advent calendar; the second puzzle is unlocked ; when you complete the first. Each puzzle grants one star. Good luck! ; Here's an easy puzzle to warm you up. ; PI:NAME:<NAME>END_PIanta is trying to deliver presents in a large apartment building, but he ; can't find the right floor - the directions he got are a little confusing. He ; starts on the ground floor (floor 0) and then follows the instructions one ; character at a time. ; An opening parenthesis, (, means he should go up one floor, and a closing ; parenthesis, ), means he should go down one floor. ; The apartment building is very tall, and the basement is very deep; he will ; never find the top or bottom floors. ; For example: ; (()) and ()() both result in floor 0. ; ((( and (()(()( both result in floor 3. ; ))((((( also results in floor 3. ; ()) and ))( both result in floor -1 (the first basement level). ; ))) and )())()) both result in floor -3. ; To what floor do the instructions take Santa? (defn get-floor [parens] (reduce (fn up-or-down [floor paren] (if (= paren \() (inc floor) (dec floor))) 0 parens)) (assert (= 0 (get-floor "(())") (get-floor "()()"))) (assert (= 3 (get-floor "(((") (get-floor "(()(()("))) (assert (= 3 (get-floor "))((((("))) (assert (= -1 (get-floor "())") (get-floor "))("))) (assert (= -3 (get-floor ")))") (get-floor ")())())"))) (defn part1 [] (println "The floor is" (get-floor input))) ; --- Part Two --- ; Now, given the same instructions, find the position of the first character ; that causes him to enter the basement (floor -1). The first character in the ; instructions has position 1, the second character has position 2, and so on. ; For example: ; ) causes him to enter the basement at character position 1. ; ()()) causes him to enter the basement at character position 5. ; What is the position of the character that causes Santa to first enter the ; basement? (defn basement? [floor] (< floor 0)) (defn get-position [parens] (reduce (fn floor-and-position [[floor position] paren] (let [new-position (inc position) new-floor (if (= paren \() (inc floor) (dec floor))] (if (basement? new-floor) (reduced new-position) [new-floor new-position]))) [0 0] parens) ) (assert (= 1 (get-position ")"))) (assert (= 5 (get-position "()())"))) (defn part2 [] (println "The position of the character that causes Santa to first" "enter the basement is" (get-position input)))
[ { "context": " {:employees [{:id (uuid-generator) :name \"Alican\" :surname \"Celik\" :avatar-color (str \"#\" (avatar-", "end": 286, "score": 0.9997966885566711, "start": 280, "tag": "NAME", "value": "Alican" }, { "context": " [{:id (uuid-generator) :name \"Alican\" :surname \"Celik\" :avatar-color (str \"#\" (avatar-color-generator))", "end": 303, "score": 0.9992416501045227, "start": 298, "tag": "NAME", "value": "Celik" }, { "context": " {:id (uuid-generator) :name \"Ergenekon\" :surname \"Yigit\" :avatar-color (str \"#\" (avatar-", "end": 440, "score": 0.9997715950012207, "start": 431, "tag": "NAME", "value": "Ergenekon" }, { "context": "{:id (uuid-generator) :name \"Ergenekon\" :surname \"Yigit\" :avatar-color (str \"#\" (avatar-color-generator))", "end": 457, "score": 0.998923122882843, "start": 452, "tag": "NAME", "value": "Yigit" }, { "context": " {:id (uuid-generator) :name \"Sabire\" :surname \"Avci\" :avatar-color (str \"#\" (avatar-c", "end": 591, "score": 0.9997959733009338, "start": 585, "tag": "NAME", "value": "Sabire" }, { "context": " {:id (uuid-generator) :name \"Sabire\" :surname \"Avci\" :avatar-color (str \"#\" (avatar-color-generator))", "end": 607, "score": 0.9995639324188232, "start": 603, "tag": "NAME", "value": "Avci" } ]
src/crud_app/db.cljs
alicancelik/CRUD-App
3
(ns crud-app.db (:require [reagent.core :as r] [crud-app.helper :refer [uuid-generator avatar-color-generator]])) (defonce api-url "https://facebook.github.io/react-native/movies.json") (defonce app-state (r/atom {:employees [{:id (uuid-generator) :name "Alican" :surname "Celik" :avatar-color (str "#" (avatar-color-generator))} {:id (uuid-generator) :name "Ergenekon" :surname "Yigit" :avatar-color (str "#" (avatar-color-generator))} {:id (uuid-generator) :name "Sabire" :surname "Avci" :avatar-color (str "#" (avatar-color-generator))}] :editing false :movies {} :current-employee {:name "" :surname "" :id ""}}))
56072
(ns crud-app.db (:require [reagent.core :as r] [crud-app.helper :refer [uuid-generator avatar-color-generator]])) (defonce api-url "https://facebook.github.io/react-native/movies.json") (defonce app-state (r/atom {:employees [{:id (uuid-generator) :name "<NAME>" :surname "<NAME>" :avatar-color (str "#" (avatar-color-generator))} {:id (uuid-generator) :name "<NAME>" :surname "<NAME>" :avatar-color (str "#" (avatar-color-generator))} {:id (uuid-generator) :name "<NAME>" :surname "<NAME>" :avatar-color (str "#" (avatar-color-generator))}] :editing false :movies {} :current-employee {:name "" :surname "" :id ""}}))
true
(ns crud-app.db (:require [reagent.core :as r] [crud-app.helper :refer [uuid-generator avatar-color-generator]])) (defonce api-url "https://facebook.github.io/react-native/movies.json") (defonce app-state (r/atom {:employees [{:id (uuid-generator) :name "PI:NAME:<NAME>END_PI" :surname "PI:NAME:<NAME>END_PI" :avatar-color (str "#" (avatar-color-generator))} {:id (uuid-generator) :name "PI:NAME:<NAME>END_PI" :surname "PI:NAME:<NAME>END_PI" :avatar-color (str "#" (avatar-color-generator))} {:id (uuid-generator) :name "PI:NAME:<NAME>END_PI" :surname "PI:NAME:<NAME>END_PI" :avatar-color (str "#" (avatar-color-generator))}] :editing false :movies {} :current-employee {:name "" :surname "" :id ""}}))
[ { "context": "; Copyright 2016 David O'Meara\n;\n; Licensed under the Apache License, Version 2.", "end": 30, "score": 0.9998522996902466, "start": 17, "tag": "NAME", "value": "David O'Meara" } ]
src-cljs/ui/widgets.cljs
davidomeara/fnedit
0
; Copyright 2016 David O'Meara ; ; 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 ui.widgets (:require [cljs.core.async :refer [put!]] [reagent.core :as reagent] [ui.events :as events] [ui.debug :as debug])) (defn key-down [f] (fn [e] (when (= (.-which e) 13) (f)) nil)) (defn render-style-rule [[k v]] (str (name k) ":" v ";")) (defn render-curly-braces [s] (str "{" s "}")) (defn render-style [m] (->> m (map render-style-rule) (apply str) render-curly-braces)) (defn render-widget-style [{:keys [id default hover focus active]}] (str "#widget" id (render-style default) "#widget" id ":hover" (render-style hover) "#widget" id ":focus" (render-style focus) "#widget" id ":active" (render-style active))) (defonce widget-id (atom 0)) (defn button-style [id theme style-options enabled?] {:id id :default (merge {:display "inline-block" :cursor "pointer" :margin "2px" :padding "2px 5px 4px 5px" :color (:color theme) :border "1px solid transparent" :outline 0} (:default style-options) (if enabled? {} {:cursor "default" :color (:border-b theme) :border "1px solid transparent"})) :hover (if enabled? (merge {:color (:active theme) :border (str "1px solid " (:active theme))} (:hover style-options)) {}) :focus (if enabled? (merge {:color (:active theme) :border (str "1px solid " (:active theme))} (:focus style-options)) {}) :active (if enabled? (merge {:color (:active-color theme) :background-color (:active theme) :border (str "1px solid " (:active theme))} (:active style-options)) {})}) ; style channel key title (defn button "required channel, theme, key, title, button-options button-options [key=default] :tab-index=-1 :style=nil :enabled?=true :status=nil" [_ _ _ _ _] (let [id (swap! widget-id inc)] (fn [channel theme key title button-options] (let [options (merge {:tab-index -1 :enabled? true} button-options) status (fn [k] (fn [] (when (and (:enabled? options) (:status options)) (put! channel [k (:status options)]) nil))) action (fn [] (when (:enabled? options) (put! channel [key])) nil)] [:a {:id (str "widget" id) :tabIndex (:tab-index options) :on-focus (status :focus) :on-blur (status :blur) :on-mouse-enter (status :hover) :on-mouse-leave (status :unhover) :on-mouse-up action :on-key-up (key-down (fn [_] (action)))} title [:style {:style {:display "none"}} (render-widget-style (button-style id theme (:style options) (:enabled? options)))]])))) (def standard-button-style {:display "inline-block" :width "100px" :text-align "center"}) (def icon-style {:style {:margin-right "5px"}}) (defn standard-button [channel theme key title options] [button channel theme key title (update-in options [:style :default] merge standard-button-style)]) (defn positive-button [channel theme key caption options] [standard-button channel theme key [:span [:i.icon.ion-checkmark icon-style] caption] options]) (defn negative-button [channel theme key caption options] [standard-button channel theme key [:span [:i.icon.ion-close icon-style] caption] options])
37376
; Copyright 2016 <NAME> ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns ui.widgets (:require [cljs.core.async :refer [put!]] [reagent.core :as reagent] [ui.events :as events] [ui.debug :as debug])) (defn key-down [f] (fn [e] (when (= (.-which e) 13) (f)) nil)) (defn render-style-rule [[k v]] (str (name k) ":" v ";")) (defn render-curly-braces [s] (str "{" s "}")) (defn render-style [m] (->> m (map render-style-rule) (apply str) render-curly-braces)) (defn render-widget-style [{:keys [id default hover focus active]}] (str "#widget" id (render-style default) "#widget" id ":hover" (render-style hover) "#widget" id ":focus" (render-style focus) "#widget" id ":active" (render-style active))) (defonce widget-id (atom 0)) (defn button-style [id theme style-options enabled?] {:id id :default (merge {:display "inline-block" :cursor "pointer" :margin "2px" :padding "2px 5px 4px 5px" :color (:color theme) :border "1px solid transparent" :outline 0} (:default style-options) (if enabled? {} {:cursor "default" :color (:border-b theme) :border "1px solid transparent"})) :hover (if enabled? (merge {:color (:active theme) :border (str "1px solid " (:active theme))} (:hover style-options)) {}) :focus (if enabled? (merge {:color (:active theme) :border (str "1px solid " (:active theme))} (:focus style-options)) {}) :active (if enabled? (merge {:color (:active-color theme) :background-color (:active theme) :border (str "1px solid " (:active theme))} (:active style-options)) {})}) ; style channel key title (defn button "required channel, theme, key, title, button-options button-options [key=default] :tab-index=-1 :style=nil :enabled?=true :status=nil" [_ _ _ _ _] (let [id (swap! widget-id inc)] (fn [channel theme key title button-options] (let [options (merge {:tab-index -1 :enabled? true} button-options) status (fn [k] (fn [] (when (and (:enabled? options) (:status options)) (put! channel [k (:status options)]) nil))) action (fn [] (when (:enabled? options) (put! channel [key])) nil)] [:a {:id (str "widget" id) :tabIndex (:tab-index options) :on-focus (status :focus) :on-blur (status :blur) :on-mouse-enter (status :hover) :on-mouse-leave (status :unhover) :on-mouse-up action :on-key-up (key-down (fn [_] (action)))} title [:style {:style {:display "none"}} (render-widget-style (button-style id theme (:style options) (:enabled? options)))]])))) (def standard-button-style {:display "inline-block" :width "100px" :text-align "center"}) (def icon-style {:style {:margin-right "5px"}}) (defn standard-button [channel theme key title options] [button channel theme key title (update-in options [:style :default] merge standard-button-style)]) (defn positive-button [channel theme key caption options] [standard-button channel theme key [:span [:i.icon.ion-checkmark icon-style] caption] options]) (defn negative-button [channel theme key caption options] [standard-button channel theme key [:span [:i.icon.ion-close icon-style] caption] options])
true
; Copyright 2016 PI:NAME:<NAME>END_PI ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns ui.widgets (:require [cljs.core.async :refer [put!]] [reagent.core :as reagent] [ui.events :as events] [ui.debug :as debug])) (defn key-down [f] (fn [e] (when (= (.-which e) 13) (f)) nil)) (defn render-style-rule [[k v]] (str (name k) ":" v ";")) (defn render-curly-braces [s] (str "{" s "}")) (defn render-style [m] (->> m (map render-style-rule) (apply str) render-curly-braces)) (defn render-widget-style [{:keys [id default hover focus active]}] (str "#widget" id (render-style default) "#widget" id ":hover" (render-style hover) "#widget" id ":focus" (render-style focus) "#widget" id ":active" (render-style active))) (defonce widget-id (atom 0)) (defn button-style [id theme style-options enabled?] {:id id :default (merge {:display "inline-block" :cursor "pointer" :margin "2px" :padding "2px 5px 4px 5px" :color (:color theme) :border "1px solid transparent" :outline 0} (:default style-options) (if enabled? {} {:cursor "default" :color (:border-b theme) :border "1px solid transparent"})) :hover (if enabled? (merge {:color (:active theme) :border (str "1px solid " (:active theme))} (:hover style-options)) {}) :focus (if enabled? (merge {:color (:active theme) :border (str "1px solid " (:active theme))} (:focus style-options)) {}) :active (if enabled? (merge {:color (:active-color theme) :background-color (:active theme) :border (str "1px solid " (:active theme))} (:active style-options)) {})}) ; style channel key title (defn button "required channel, theme, key, title, button-options button-options [key=default] :tab-index=-1 :style=nil :enabled?=true :status=nil" [_ _ _ _ _] (let [id (swap! widget-id inc)] (fn [channel theme key title button-options] (let [options (merge {:tab-index -1 :enabled? true} button-options) status (fn [k] (fn [] (when (and (:enabled? options) (:status options)) (put! channel [k (:status options)]) nil))) action (fn [] (when (:enabled? options) (put! channel [key])) nil)] [:a {:id (str "widget" id) :tabIndex (:tab-index options) :on-focus (status :focus) :on-blur (status :blur) :on-mouse-enter (status :hover) :on-mouse-leave (status :unhover) :on-mouse-up action :on-key-up (key-down (fn [_] (action)))} title [:style {:style {:display "none"}} (render-widget-style (button-style id theme (:style options) (:enabled? options)))]])))) (def standard-button-style {:display "inline-block" :width "100px" :text-align "center"}) (def icon-style {:style {:margin-right "5px"}}) (defn standard-button [channel theme key title options] [button channel theme key title (update-in options [:style :default] merge standard-button-style)]) (defn positive-button [channel theme key caption options] [standard-button channel theme key [:span [:i.icon.ion-checkmark icon-style] caption] options]) (defn negative-button [channel theme key caption options] [standard-button channel theme key [:span [:i.icon.ion-close icon-style] caption] options])
[ { "context": "OS/lcmap-chipmunk project on GitHub, created by\n;; Jon Morton https://github.com/jmorton\n;; \n;; ## Init\n;;\n;; T", "end": 377, "score": 0.9998289346694946, "start": 367, "tag": "NAME", "value": "Jon Morton" }, { "context": "tHub, created by\n;; Jon Morton https://github.com/jmorton\n;; \n;; ## Init\n;;\n;; This makes it easier to use ", "end": 404, "score": 0.9997379779815674, "start": 397, "tag": "USERNAME", "value": "jmorton" } ]
src/lcmap/tiffany/gdal.clj
caustin-usgs/lcmap-tiffany
0
(ns lcmap.tiffany.gdal (:require [mount.core :as mount] [lcmap.tiffany.util :as util]) (:import [org.gdal.gdal gdal] [org.gdal.gdal Driver] [org.gdal.gdal Dataset] [org.gdal.gdalconst gdalconst])) ;; init and state constructs blatantly ripped off from the ;; USGS-EROS/lcmap-chipmunk project on GitHub, created by ;; Jon Morton https://github.com/jmorton ;; ;; ## Init ;; ;; This makes it easier to use Java GDAL libraries without ;; having to set environment variables. These are typical ;; install locations of GDAL libs on CentOS and Ubuntu. ;; ;; Before GDAL can open files, drivers must be registered. ;; Selective registration is more tedious and error prone, ;; so we just register all drivers. ;; ;; If anything goes wrong, a helpful string is printed to ;; stdout (not a log file). ;; (defn init "Initialize GDAL drivers." [] (try (util/amend-usr-path ["/usr/lib/java/gdal" "/usr/lib/jni"]) (gdal/AllRegister) (catch RuntimeException e (binding [*out* *err*] (println (str "Could not update paths to native libraries. " "You may need to set LD_LIBRARY_PATH to the " "directory containing libgdaljni.so")))) (finally (import org.gdal.gdal.gdal)))) ;; ## State ;; ;; A mount state is defined so that GDAL is initialized like ;; everything else (DB connections, HTTP listeners, etc...) ;; (mount/defstate gdal-init :start (init)) (defn create_geotiff [name values ulx uly projection x_size y_size x_offset y_offset] (let [driver (gdal/GetDriverByName "GTiff") dataset (.Create driver name x_size y_size) band (.GetRasterBand dataset 1) transform (double-array [ulx 30 0 uly 0 -30])] (.SetGeoTransform dataset transform) (.SetProjection dataset projection) (.WriteRaster band x_offset y_offset x_size y_size (float-array values)) (.delete band) (.delete dataset)) name) (defn update_geotiff ([tiff_name values x_offset y_offset x_size y_size] (let [dataset (gdal/Open tiff_name 1) band (.GetRasterBand dataset 1)] (.WriteRaster band x_offset y_offset x_size y_size (float-array values)) (.delete band) (.delete dataset))) ([tiff_name values x_offset y_offset] (update_geotiff tiff_name values x_offset y_offset 100 100)))
48619
(ns lcmap.tiffany.gdal (:require [mount.core :as mount] [lcmap.tiffany.util :as util]) (:import [org.gdal.gdal gdal] [org.gdal.gdal Driver] [org.gdal.gdal Dataset] [org.gdal.gdalconst gdalconst])) ;; init and state constructs blatantly ripped off from the ;; USGS-EROS/lcmap-chipmunk project on GitHub, created by ;; <NAME> https://github.com/jmorton ;; ;; ## Init ;; ;; This makes it easier to use Java GDAL libraries without ;; having to set environment variables. These are typical ;; install locations of GDAL libs on CentOS and Ubuntu. ;; ;; Before GDAL can open files, drivers must be registered. ;; Selective registration is more tedious and error prone, ;; so we just register all drivers. ;; ;; If anything goes wrong, a helpful string is printed to ;; stdout (not a log file). ;; (defn init "Initialize GDAL drivers." [] (try (util/amend-usr-path ["/usr/lib/java/gdal" "/usr/lib/jni"]) (gdal/AllRegister) (catch RuntimeException e (binding [*out* *err*] (println (str "Could not update paths to native libraries. " "You may need to set LD_LIBRARY_PATH to the " "directory containing libgdaljni.so")))) (finally (import org.gdal.gdal.gdal)))) ;; ## State ;; ;; A mount state is defined so that GDAL is initialized like ;; everything else (DB connections, HTTP listeners, etc...) ;; (mount/defstate gdal-init :start (init)) (defn create_geotiff [name values ulx uly projection x_size y_size x_offset y_offset] (let [driver (gdal/GetDriverByName "GTiff") dataset (.Create driver name x_size y_size) band (.GetRasterBand dataset 1) transform (double-array [ulx 30 0 uly 0 -30])] (.SetGeoTransform dataset transform) (.SetProjection dataset projection) (.WriteRaster band x_offset y_offset x_size y_size (float-array values)) (.delete band) (.delete dataset)) name) (defn update_geotiff ([tiff_name values x_offset y_offset x_size y_size] (let [dataset (gdal/Open tiff_name 1) band (.GetRasterBand dataset 1)] (.WriteRaster band x_offset y_offset x_size y_size (float-array values)) (.delete band) (.delete dataset))) ([tiff_name values x_offset y_offset] (update_geotiff tiff_name values x_offset y_offset 100 100)))
true
(ns lcmap.tiffany.gdal (:require [mount.core :as mount] [lcmap.tiffany.util :as util]) (:import [org.gdal.gdal gdal] [org.gdal.gdal Driver] [org.gdal.gdal Dataset] [org.gdal.gdalconst gdalconst])) ;; init and state constructs blatantly ripped off from the ;; USGS-EROS/lcmap-chipmunk project on GitHub, created by ;; PI:NAME:<NAME>END_PI https://github.com/jmorton ;; ;; ## Init ;; ;; This makes it easier to use Java GDAL libraries without ;; having to set environment variables. These are typical ;; install locations of GDAL libs on CentOS and Ubuntu. ;; ;; Before GDAL can open files, drivers must be registered. ;; Selective registration is more tedious and error prone, ;; so we just register all drivers. ;; ;; If anything goes wrong, a helpful string is printed to ;; stdout (not a log file). ;; (defn init "Initialize GDAL drivers." [] (try (util/amend-usr-path ["/usr/lib/java/gdal" "/usr/lib/jni"]) (gdal/AllRegister) (catch RuntimeException e (binding [*out* *err*] (println (str "Could not update paths to native libraries. " "You may need to set LD_LIBRARY_PATH to the " "directory containing libgdaljni.so")))) (finally (import org.gdal.gdal.gdal)))) ;; ## State ;; ;; A mount state is defined so that GDAL is initialized like ;; everything else (DB connections, HTTP listeners, etc...) ;; (mount/defstate gdal-init :start (init)) (defn create_geotiff [name values ulx uly projection x_size y_size x_offset y_offset] (let [driver (gdal/GetDriverByName "GTiff") dataset (.Create driver name x_size y_size) band (.GetRasterBand dataset 1) transform (double-array [ulx 30 0 uly 0 -30])] (.SetGeoTransform dataset transform) (.SetProjection dataset projection) (.WriteRaster band x_offset y_offset x_size y_size (float-array values)) (.delete band) (.delete dataset)) name) (defn update_geotiff ([tiff_name values x_offset y_offset x_size y_size] (let [dataset (gdal/Open tiff_name 1) band (.GetRasterBand dataset 1)] (.WriteRaster band x_offset y_offset x_size y_size (float-array values)) (.delete band) (.delete dataset))) ([tiff_name values x_offset y_offset] (update_geotiff tiff_name values x_offset y_offset 100 100)))
[ { "context": "on\"\n :user \"tsinghua\"\n :password \"tsinghua\"})\n", "end": 190, "score": 0.9991894960403442, "start": 182, "tag": "PASSWORD", "value": "tsinghua" } ]
src/demo/db_layer/db_define.clj
lincoln310/work
0
(ns demo.db-layer.db-define (:require [clojure.java.jdbc :as sql])) (def db {:subprotocol "postgresql" :subname "location" :user "tsinghua" :password "tsinghua"})
121255
(ns demo.db-layer.db-define (:require [clojure.java.jdbc :as sql])) (def db {:subprotocol "postgresql" :subname "location" :user "tsinghua" :password "<PASSWORD>"})
true
(ns demo.db-layer.db-define (:require [clojure.java.jdbc :as sql])) (def db {:subprotocol "postgresql" :subname "location" :user "tsinghua" :password "PI:PASSWORD:<PASSWORD>END_PI"})
[ { "context": "ce\n (fn [acc id]\n (let [doc-key (str (c/new-id id))\n doc-file (io/file dir doc-key)]\n ", "end": 639, "score": 0.8367850184440613, "start": 628, "tag": "KEY", "value": "c/new-id id" }, { "context": "doc] id-and-docs\n :let [doc-key (str (c/new-id id))]]\n (with-open [out (DataOutputStream. (", "end": 1148, "score": 0.7129980325698853, "start": 1142, "tag": "KEY", "value": "new-id" } ]
crux-core/src/crux/document_store.clj
deobald/crux
0
(ns ^:no-doc crux.document-store (:require [clojure.java.io :as io] [clojure.set :as set] [crux.codec :as c] [crux.db :as db] [crux.cache :as cache] [crux.memory :as mem] [taoensso.nippy :as nippy] [crux.system :as sys]) (:import clojure.lang.MapEntry (java.io Closeable DataInputStream DataOutputStream FileInputStream FileOutputStream) (java.nio.file Path))) (defrecord FileDocumentStore [dir] db/DocumentStore (fetch-docs [this ids] (persistent! (reduce (fn [acc id] (let [doc-key (str (c/new-id id)) doc-file (io/file dir doc-key)] (if-let [doc (when (.exists doc-file) (with-open [in (FileInputStream. doc-file)] (some->> in (DataInputStream.) (nippy/thaw-from-in!))))] (assoc! acc id doc) acc))) (transient {}) ids))) (submit-docs [this id-and-docs] (doseq [[id doc] id-and-docs :let [doc-key (str (c/new-id id))]] (with-open [out (DataOutputStream. (FileOutputStream. (io/file dir doc-key)))] (nippy/freeze-to-out! out doc)))) Closeable (close [_])) (defrecord CachedDocumentStore [cache document-store] db/DocumentStore (fetch-docs [this ids] (let [ids (set ids) cached-id->docs (persistent! (reduce (fn [acc id] (if-let [doc (get cache (c/->id-buffer id))] (assoc! acc id doc) acc)) (transient {}) ids)) missing-ids (set/difference ids (keys cached-id->docs)) missing-id->docs (db/fetch-docs document-store missing-ids)] (persistent! (reduce-kv (fn [acc id doc] (assoc! acc id (cache/compute-if-absent cache (c/->id-buffer id) mem/copy-to-unpooled-buffer (fn [_] doc)))) (transient cached-id->docs) missing-id->docs)))) (submit-docs [this id-and-docs] (db/submit-docs document-store (vec (for [[id doc] id-and-docs] (do (cache/evict cache (c/->id-buffer id)) (MapEntry/create id doc)))))) Closeable (close [_])) (defn ->cached-document-store {::sys/deps {:document-store :crux/document-store :document-cache 'crux.cache/->cache}} [{:keys [document-cache document-store]}] (->CachedDocumentStore document-cache document-store)) (defn ->file-document-store {::sys/deps {:document-cache 'crux.cache/->cache} ::sys/args {:dir {:doc "Directory to store documents" :required? true :spec ::sys/path}}} [{:keys [^Path dir document-cache] :as opts}] (let [dir (.toFile dir)] (.mkdirs dir) (->cached-document-store (assoc opts :document-cache document-cache :document-store (->FileDocumentStore dir)))))
28933
(ns ^:no-doc crux.document-store (:require [clojure.java.io :as io] [clojure.set :as set] [crux.codec :as c] [crux.db :as db] [crux.cache :as cache] [crux.memory :as mem] [taoensso.nippy :as nippy] [crux.system :as sys]) (:import clojure.lang.MapEntry (java.io Closeable DataInputStream DataOutputStream FileInputStream FileOutputStream) (java.nio.file Path))) (defrecord FileDocumentStore [dir] db/DocumentStore (fetch-docs [this ids] (persistent! (reduce (fn [acc id] (let [doc-key (str (<KEY>)) doc-file (io/file dir doc-key)] (if-let [doc (when (.exists doc-file) (with-open [in (FileInputStream. doc-file)] (some->> in (DataInputStream.) (nippy/thaw-from-in!))))] (assoc! acc id doc) acc))) (transient {}) ids))) (submit-docs [this id-and-docs] (doseq [[id doc] id-and-docs :let [doc-key (str (c/<KEY> id))]] (with-open [out (DataOutputStream. (FileOutputStream. (io/file dir doc-key)))] (nippy/freeze-to-out! out doc)))) Closeable (close [_])) (defrecord CachedDocumentStore [cache document-store] db/DocumentStore (fetch-docs [this ids] (let [ids (set ids) cached-id->docs (persistent! (reduce (fn [acc id] (if-let [doc (get cache (c/->id-buffer id))] (assoc! acc id doc) acc)) (transient {}) ids)) missing-ids (set/difference ids (keys cached-id->docs)) missing-id->docs (db/fetch-docs document-store missing-ids)] (persistent! (reduce-kv (fn [acc id doc] (assoc! acc id (cache/compute-if-absent cache (c/->id-buffer id) mem/copy-to-unpooled-buffer (fn [_] doc)))) (transient cached-id->docs) missing-id->docs)))) (submit-docs [this id-and-docs] (db/submit-docs document-store (vec (for [[id doc] id-and-docs] (do (cache/evict cache (c/->id-buffer id)) (MapEntry/create id doc)))))) Closeable (close [_])) (defn ->cached-document-store {::sys/deps {:document-store :crux/document-store :document-cache 'crux.cache/->cache}} [{:keys [document-cache document-store]}] (->CachedDocumentStore document-cache document-store)) (defn ->file-document-store {::sys/deps {:document-cache 'crux.cache/->cache} ::sys/args {:dir {:doc "Directory to store documents" :required? true :spec ::sys/path}}} [{:keys [^Path dir document-cache] :as opts}] (let [dir (.toFile dir)] (.mkdirs dir) (->cached-document-store (assoc opts :document-cache document-cache :document-store (->FileDocumentStore dir)))))
true
(ns ^:no-doc crux.document-store (:require [clojure.java.io :as io] [clojure.set :as set] [crux.codec :as c] [crux.db :as db] [crux.cache :as cache] [crux.memory :as mem] [taoensso.nippy :as nippy] [crux.system :as sys]) (:import clojure.lang.MapEntry (java.io Closeable DataInputStream DataOutputStream FileInputStream FileOutputStream) (java.nio.file Path))) (defrecord FileDocumentStore [dir] db/DocumentStore (fetch-docs [this ids] (persistent! (reduce (fn [acc id] (let [doc-key (str (PI:KEY:<KEY>END_PI)) doc-file (io/file dir doc-key)] (if-let [doc (when (.exists doc-file) (with-open [in (FileInputStream. doc-file)] (some->> in (DataInputStream.) (nippy/thaw-from-in!))))] (assoc! acc id doc) acc))) (transient {}) ids))) (submit-docs [this id-and-docs] (doseq [[id doc] id-and-docs :let [doc-key (str (c/PI:KEY:<KEY>END_PI id))]] (with-open [out (DataOutputStream. (FileOutputStream. (io/file dir doc-key)))] (nippy/freeze-to-out! out doc)))) Closeable (close [_])) (defrecord CachedDocumentStore [cache document-store] db/DocumentStore (fetch-docs [this ids] (let [ids (set ids) cached-id->docs (persistent! (reduce (fn [acc id] (if-let [doc (get cache (c/->id-buffer id))] (assoc! acc id doc) acc)) (transient {}) ids)) missing-ids (set/difference ids (keys cached-id->docs)) missing-id->docs (db/fetch-docs document-store missing-ids)] (persistent! (reduce-kv (fn [acc id doc] (assoc! acc id (cache/compute-if-absent cache (c/->id-buffer id) mem/copy-to-unpooled-buffer (fn [_] doc)))) (transient cached-id->docs) missing-id->docs)))) (submit-docs [this id-and-docs] (db/submit-docs document-store (vec (for [[id doc] id-and-docs] (do (cache/evict cache (c/->id-buffer id)) (MapEntry/create id doc)))))) Closeable (close [_])) (defn ->cached-document-store {::sys/deps {:document-store :crux/document-store :document-cache 'crux.cache/->cache}} [{:keys [document-cache document-store]}] (->CachedDocumentStore document-cache document-store)) (defn ->file-document-store {::sys/deps {:document-cache 'crux.cache/->cache} ::sys/args {:dir {:doc "Directory to store documents" :required? true :spec ::sys/path}}} [{:keys [^Path dir document-cache] :as opts}] (let [dir (.toFile dir)] (.mkdirs dir) (->cached-document-store (assoc opts :document-cache document-cache :document-store (->FileDocumentStore dir)))))
[ { "context": "ction \n\t\t(ds/create-entity {:kind \"Person\" :name \"liz\"}))]\n (is (= \"liz\" (:name entity))))\n (let [c", "end": 544, "score": 0.9888685941696167, "start": 541, "tag": "NAME", "value": "liz" }, { "context": "ntity {:kind \"Person\" :name \"liz\"}))]\n (is (= \"liz\" (:name entity))))\n (let [child (tr/with-transac", "end": 565, "score": 0.8614594340324402, "start": 562, "tag": "NAME", "value": "liz" }, { "context": " [parent (ds/create-entity {:kind \"Person\" :name \"jane\"})]\n\t\t (ds/create-entity {:kind \"Person\" :name \"", "end": 680, "score": 0.9977395534515381, "start": 676, "tag": "NAME", "value": "jane" }, { "context": "\"})]\n\t\t (ds/create-entity {:kind \"Person\" :name \"bob\" \n\t\t\t\t :parent-key (:key parent)})))]\n (is", "end": 733, "score": 0.9939792156219482, "start": 730, "tag": "NAME", "value": "bob" }, { "context": "\t\t :parent-key (:key parent)})))]\n (is (= \"bob\" (:name child)))\n (is (= [\"jane\"] \n\t (map :n", "end": 791, "score": 0.919940173625946, "start": 788, "tag": "NAME", "value": "bob" }, { "context": "))]\n (is (= \"bob\" (:name child)))\n (is (= [\"jane\"] \n\t (map :name (ds/find-all \n\t\t (doto (Q", "end": 826, "score": 0.9764625430107117, "start": 822, "tag": "NAME", "value": "jane" }, { "context": "lter \"name\" \n\t\t\t\t Query$FilterOperator/EQUAL \"jane\"))))))))\n\n(dstest do-rollback-in-transaction\n (", "end": 958, "score": 0.9421560168266296, "start": 954, "tag": "NAME", "value": "jane" }, { "context": "et1 (ds/create-entity \n\t\t\t\t{:kind \"Person\" :name \"ForgetMe1\"})\n\t\t forget2 (ds/create-entity \n\t\t\t\t{:kind", "end": 1114, "score": 0.7475159764289856, "start": 1105, "tag": "NAME", "value": "ForgetMe1" }, { "context": "et2 (ds/create-entity \n\t\t\t\t{:kind \"Person\" :name \"ForgetMe2\"\n\t\t\t\t :parent-key (:key forget1)})]\n\t\t (tr/roll", "end": 1190, "score": 0.7525161504745483, "start": 1181, "tag": "NAME", "value": "ForgetMe2" }, { "context": "ransaction\n (let [user (create-testuser {:name \"liz\" :job \"entrepreneur\"})]\n (create-testuser {:n", "end": 7097, "score": 0.7201679348945618, "start": 7094, "tag": "USERNAME", "value": "liz" }, { "context": "b \"entrepreneur\"})]\n (create-testuser {:name \"robert\" :job \"secretary\"\n\t\t :parent-key (:key user", "end": 7158, "score": 0.8519819378852844, "start": 7152, "tag": "USERNAME", "value": "robert" }, { "context": "r\"})]\n (create-testuser {:name \"robert\" :job \"secretary\"\n\t\t :parent-key (:key user)})))\n (let [an-", "end": 7175, "score": 0.7351704239845276, "start": 7166, "tag": "NAME", "value": "secretary" } ]
test/appengine/datastore/test/transactions.clj
jeandenis/appengine-clj
0
(ns appengine.datastore.test.transactions (:require [appengine.datastore.core :as ds] [appengine.datastore.transactions :as tr] [appengine.datastore.entities :as en]) (:use clojure.test appengine.test-utils) (:import (com.google.appengine.api.datastore EntityNotFoundException Query DatastoreFailureException Query$FilterOperator))) ;; appengine.datastore/core tests ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (dstest create-entity-in-transaction (let [entity (tr/with-transaction (ds/create-entity {:kind "Person" :name "liz"}))] (is (= "liz" (:name entity)))) (let [child (tr/with-transaction (let [parent (ds/create-entity {:kind "Person" :name "jane"})] (ds/create-entity {:kind "Person" :name "bob" :parent-key (:key parent)})))] (is (= "bob" (:name child))) (is (= ["jane"] (map :name (ds/find-all (doto (Query. "Person") (.addFilter "name" Query$FilterOperator/EQUAL "jane")))))))) (dstest do-rollback-in-transaction (let [[k1 k2] (tr/with-transaction (let [forget1 (ds/create-entity {:kind "Person" :name "ForgetMe1"}) forget2 (ds/create-entity {:kind "Person" :name "ForgetMe2" :parent-key (:key forget1)})] (tr/rollback-transaction) [(:key forget1) (:key forget2)]))] (is (thrown? EntityNotFoundException (ds/get-entity k1))) (is (thrown? EntityNotFoundException (ds/get-entity k2))))) (defn always-fails [] (throw (DatastoreFailureException. "Test Error"))) (dstest multiple-tries-in-transaction (is (thrown? DatastoreFailureException (tr/with-transaction (always-fails))))) (dstest non-transaction-datastore-operations-within-transactions (let [[k1 k2 k3 k4] (tr/with-transaction (let [entity (ds/create-entity {:kind "Person" :name "Entity"}) same-entity-group-as-entity (ds/create-entity {:kind "Person" :name "SameEntityGroupAsEntity" :parent-key (:key entity)})] (is (thrown? IllegalArgumentException ;; wrong entity group (ds/create-entity {:kind "Person" :name "WrongEntityGroup"}))) (map :key [entity same-entity-group-as-entity (tr/without-transaction ;; do atomic request via macro (ds/create-entity {:kind "Person" :name "DifferentEntityGroup"})) (ds/create-entity nil ;; do atomic request manually {:kind "Person" :name "CanDoItManuallyAsWell"})])))] (is (= "Entity" (:name (ds/get-entity k1)))) (is (= "SameEntityGroupAsEntity" (:name (ds/get-entity k2)))) (is (= "DifferentEntityGroup" (:name (ds/get-entity k3)))) (is (= "CanDoItManuallyAsWell" (:name (ds/get-entity k4)))))) (dstest nested-transactions (let [[k1 k2 k3 k4] (tr/with-transaction ;; transaction for first entity group (let [entity (ds/create-entity {:kind "Person" :name "Entity"}) same-entity-group-as-entity (ds/create-entity {:kind "Person" :name "SameEntityGroupAsEntity" :parent-key (:key entity)}) [entity2 same-entity-group-as-entity2] (tr/with-transaction ;; nested for a second entity group (let [entity2 (ds/create-entity {:kind "Person" :name "Entity2"}) same-entity-group-as-entity2 (ds/create-entity {:kind "Person" :name "SameEntityGroupAsEntity2" :parent-key (:key entity2)})] [entity2 same-entity-group-as-entity2]))] [entity same-entity-group-as-entity entity2 same-entity-group-as-entity2]))] (is (= "Entity" (:name (ds/get-entity k1)))) (is (= "SameEntityGroupAsEntity" (:name (ds/get-entity k2)))) (is (= "Entity2" (:name (ds/get-entity k3)))) (is (= "SameEntityGroupAsEntity2" (:name (ds/get-entity k4)))))) (dstest updates-with-transactions (let [entity (ds/create-entity {:kind "Person" :name "Entity"})] (tr/with-transaction (is (= "Entity" (:name entity))) (ds/update-entity entity {:day-job "hacker" :favorite-sport "beach volley"}) (ds/update-entity entity {:day-job "entrepreneur" :night-job "hacker++"}))) (let [[entity] (ds/find-all (doto (Query. "Person") (.addFilter "day-job" Query$FilterOperator/EQUAL "entrepreneur")))] (is (= "hacker++" (:night-job entity))) (is (= "Entity" (:name entity))) (is (nil? (:favorite-sport entity))))) ;; remember how ds's put works: only commit the latest Entity put ;; in case the same entity is put multiple times ;; transactions and find-all works, but is restricted as per ;; http://code.google.com/appengine/docs/java/datastore/queriesandindexes.html ;; text-search for Ancestor Queries (dstest deletes-with-transactions (let [entity (ds/create-entity {:kind "Person" :name "Entity"}) entity2 (ds/create-entity {:kind "Person" :name "Entity2"})] (tr/with-transaction (ds/delete-entity entity) (is (thrown? IllegalArgumentException (ds/delete-entity entity2)))) (is (thrown? EntityNotFoundException (ds/get-entity (:key entity)))) (is (= "Entity2" (:name (ds/get-entity (:key entity2))))) (tr/with-transaction (ds/delete-entity entity2) (tr/rollback-transaction)) (is (= "Entity2" (:name (ds/get-entity (:key entity2))))) (tr/with-transaction (ds/delete-entity entity2)) (is (thrown? EntityNotFoundException (ds/get-entity (:key entity2)))))) ;; We can also do transactions manually if we so wish (dstest manual-transactions (let [transaction (.beginTransaction (ds/datastore)) ;; manually create tr entity (ds/create-entity transaction {:kind "Person" :name "Entity"}) entity2 (ds/create-entity transaction {:kind "Person" :name "Entity2" :parent-key (:key entity)}) ;; transaction not committed so these should not be in ds yet [entity1?] (ds/find-all (doto (Query. "Person") (.addFilter "name" Query$FilterOperator/EQUAL "Entity"))) [entity2?] (ds/find-all (doto (Query. "Person") (.addFilter "name" Query$FilterOperator/EQUAL "Entity2")))] (is (nil? entity1?)) (is (nil? entity2?)) ;; now commit (.commit transaction) (let [[entity1?] (ds/find-all (doto (Query. "Person") (.addFilter "name" Query$FilterOperator/EQUAL "Entity"))) [entity2?] (ds/find-all (doto (Query. "Person") (.addFilter "name" Query$FilterOperator/EQUAL "Entity2")))] ;; post-commit we find the entities (is (= "Entity" (:name entity1?))) (is (= "Entity2" (:name entity2?)))))) ;just to show with-retries was tested manually ;(dstest doretry-transaction-manual-test ; (tr/with-retries 2 ; (try (tr/with-transaction ; (always-fails)) (catch Exception e (prn "error"))) ; (try (tr/with-transaction ; (always-fails)) (catch Exception e (prn "error"))))) ;; appengine.datastore/entities ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (en/defentity testuser () (name :key true) (job)) ;; it's the same deal as entities.clj relies on core.clj which ;; support transactions (dstest entities-macros-and-transactions (tr/with-transaction (let [user (create-testuser {:name "liz" :job "entrepreneur"})] (create-testuser {:name "robert" :job "secretary" :parent-key (:key user)}))) (let [an-entrepreneur (find-testuser-by-job "entrepreneur") bob (find-testuser-by-name "robert")] (is (= "secretary" (:job bob))) (is (= "liz" (:name an-entrepreneur)))))
123860
(ns appengine.datastore.test.transactions (:require [appengine.datastore.core :as ds] [appengine.datastore.transactions :as tr] [appengine.datastore.entities :as en]) (:use clojure.test appengine.test-utils) (:import (com.google.appengine.api.datastore EntityNotFoundException Query DatastoreFailureException Query$FilterOperator))) ;; appengine.datastore/core tests ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (dstest create-entity-in-transaction (let [entity (tr/with-transaction (ds/create-entity {:kind "Person" :name "<NAME>"}))] (is (= "<NAME>" (:name entity)))) (let [child (tr/with-transaction (let [parent (ds/create-entity {:kind "Person" :name "<NAME>"})] (ds/create-entity {:kind "Person" :name "<NAME>" :parent-key (:key parent)})))] (is (= "<NAME>" (:name child))) (is (= ["<NAME>"] (map :name (ds/find-all (doto (Query. "Person") (.addFilter "name" Query$FilterOperator/EQUAL "<NAME>")))))))) (dstest do-rollback-in-transaction (let [[k1 k2] (tr/with-transaction (let [forget1 (ds/create-entity {:kind "Person" :name "<NAME>"}) forget2 (ds/create-entity {:kind "Person" :name "<NAME>" :parent-key (:key forget1)})] (tr/rollback-transaction) [(:key forget1) (:key forget2)]))] (is (thrown? EntityNotFoundException (ds/get-entity k1))) (is (thrown? EntityNotFoundException (ds/get-entity k2))))) (defn always-fails [] (throw (DatastoreFailureException. "Test Error"))) (dstest multiple-tries-in-transaction (is (thrown? DatastoreFailureException (tr/with-transaction (always-fails))))) (dstest non-transaction-datastore-operations-within-transactions (let [[k1 k2 k3 k4] (tr/with-transaction (let [entity (ds/create-entity {:kind "Person" :name "Entity"}) same-entity-group-as-entity (ds/create-entity {:kind "Person" :name "SameEntityGroupAsEntity" :parent-key (:key entity)})] (is (thrown? IllegalArgumentException ;; wrong entity group (ds/create-entity {:kind "Person" :name "WrongEntityGroup"}))) (map :key [entity same-entity-group-as-entity (tr/without-transaction ;; do atomic request via macro (ds/create-entity {:kind "Person" :name "DifferentEntityGroup"})) (ds/create-entity nil ;; do atomic request manually {:kind "Person" :name "CanDoItManuallyAsWell"})])))] (is (= "Entity" (:name (ds/get-entity k1)))) (is (= "SameEntityGroupAsEntity" (:name (ds/get-entity k2)))) (is (= "DifferentEntityGroup" (:name (ds/get-entity k3)))) (is (= "CanDoItManuallyAsWell" (:name (ds/get-entity k4)))))) (dstest nested-transactions (let [[k1 k2 k3 k4] (tr/with-transaction ;; transaction for first entity group (let [entity (ds/create-entity {:kind "Person" :name "Entity"}) same-entity-group-as-entity (ds/create-entity {:kind "Person" :name "SameEntityGroupAsEntity" :parent-key (:key entity)}) [entity2 same-entity-group-as-entity2] (tr/with-transaction ;; nested for a second entity group (let [entity2 (ds/create-entity {:kind "Person" :name "Entity2"}) same-entity-group-as-entity2 (ds/create-entity {:kind "Person" :name "SameEntityGroupAsEntity2" :parent-key (:key entity2)})] [entity2 same-entity-group-as-entity2]))] [entity same-entity-group-as-entity entity2 same-entity-group-as-entity2]))] (is (= "Entity" (:name (ds/get-entity k1)))) (is (= "SameEntityGroupAsEntity" (:name (ds/get-entity k2)))) (is (= "Entity2" (:name (ds/get-entity k3)))) (is (= "SameEntityGroupAsEntity2" (:name (ds/get-entity k4)))))) (dstest updates-with-transactions (let [entity (ds/create-entity {:kind "Person" :name "Entity"})] (tr/with-transaction (is (= "Entity" (:name entity))) (ds/update-entity entity {:day-job "hacker" :favorite-sport "beach volley"}) (ds/update-entity entity {:day-job "entrepreneur" :night-job "hacker++"}))) (let [[entity] (ds/find-all (doto (Query. "Person") (.addFilter "day-job" Query$FilterOperator/EQUAL "entrepreneur")))] (is (= "hacker++" (:night-job entity))) (is (= "Entity" (:name entity))) (is (nil? (:favorite-sport entity))))) ;; remember how ds's put works: only commit the latest Entity put ;; in case the same entity is put multiple times ;; transactions and find-all works, but is restricted as per ;; http://code.google.com/appengine/docs/java/datastore/queriesandindexes.html ;; text-search for Ancestor Queries (dstest deletes-with-transactions (let [entity (ds/create-entity {:kind "Person" :name "Entity"}) entity2 (ds/create-entity {:kind "Person" :name "Entity2"})] (tr/with-transaction (ds/delete-entity entity) (is (thrown? IllegalArgumentException (ds/delete-entity entity2)))) (is (thrown? EntityNotFoundException (ds/get-entity (:key entity)))) (is (= "Entity2" (:name (ds/get-entity (:key entity2))))) (tr/with-transaction (ds/delete-entity entity2) (tr/rollback-transaction)) (is (= "Entity2" (:name (ds/get-entity (:key entity2))))) (tr/with-transaction (ds/delete-entity entity2)) (is (thrown? EntityNotFoundException (ds/get-entity (:key entity2)))))) ;; We can also do transactions manually if we so wish (dstest manual-transactions (let [transaction (.beginTransaction (ds/datastore)) ;; manually create tr entity (ds/create-entity transaction {:kind "Person" :name "Entity"}) entity2 (ds/create-entity transaction {:kind "Person" :name "Entity2" :parent-key (:key entity)}) ;; transaction not committed so these should not be in ds yet [entity1?] (ds/find-all (doto (Query. "Person") (.addFilter "name" Query$FilterOperator/EQUAL "Entity"))) [entity2?] (ds/find-all (doto (Query. "Person") (.addFilter "name" Query$FilterOperator/EQUAL "Entity2")))] (is (nil? entity1?)) (is (nil? entity2?)) ;; now commit (.commit transaction) (let [[entity1?] (ds/find-all (doto (Query. "Person") (.addFilter "name" Query$FilterOperator/EQUAL "Entity"))) [entity2?] (ds/find-all (doto (Query. "Person") (.addFilter "name" Query$FilterOperator/EQUAL "Entity2")))] ;; post-commit we find the entities (is (= "Entity" (:name entity1?))) (is (= "Entity2" (:name entity2?)))))) ;just to show with-retries was tested manually ;(dstest doretry-transaction-manual-test ; (tr/with-retries 2 ; (try (tr/with-transaction ; (always-fails)) (catch Exception e (prn "error"))) ; (try (tr/with-transaction ; (always-fails)) (catch Exception e (prn "error"))))) ;; appengine.datastore/entities ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (en/defentity testuser () (name :key true) (job)) ;; it's the same deal as entities.clj relies on core.clj which ;; support transactions (dstest entities-macros-and-transactions (tr/with-transaction (let [user (create-testuser {:name "liz" :job "entrepreneur"})] (create-testuser {:name "robert" :job "<NAME>" :parent-key (:key user)}))) (let [an-entrepreneur (find-testuser-by-job "entrepreneur") bob (find-testuser-by-name "robert")] (is (= "secretary" (:job bob))) (is (= "liz" (:name an-entrepreneur)))))
true
(ns appengine.datastore.test.transactions (:require [appengine.datastore.core :as ds] [appengine.datastore.transactions :as tr] [appengine.datastore.entities :as en]) (:use clojure.test appengine.test-utils) (:import (com.google.appengine.api.datastore EntityNotFoundException Query DatastoreFailureException Query$FilterOperator))) ;; appengine.datastore/core tests ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (dstest create-entity-in-transaction (let [entity (tr/with-transaction (ds/create-entity {:kind "Person" :name "PI:NAME:<NAME>END_PI"}))] (is (= "PI:NAME:<NAME>END_PI" (:name entity)))) (let [child (tr/with-transaction (let [parent (ds/create-entity {:kind "Person" :name "PI:NAME:<NAME>END_PI"})] (ds/create-entity {:kind "Person" :name "PI:NAME:<NAME>END_PI" :parent-key (:key parent)})))] (is (= "PI:NAME:<NAME>END_PI" (:name child))) (is (= ["PI:NAME:<NAME>END_PI"] (map :name (ds/find-all (doto (Query. "Person") (.addFilter "name" Query$FilterOperator/EQUAL "PI:NAME:<NAME>END_PI")))))))) (dstest do-rollback-in-transaction (let [[k1 k2] (tr/with-transaction (let [forget1 (ds/create-entity {:kind "Person" :name "PI:NAME:<NAME>END_PI"}) forget2 (ds/create-entity {:kind "Person" :name "PI:NAME:<NAME>END_PI" :parent-key (:key forget1)})] (tr/rollback-transaction) [(:key forget1) (:key forget2)]))] (is (thrown? EntityNotFoundException (ds/get-entity k1))) (is (thrown? EntityNotFoundException (ds/get-entity k2))))) (defn always-fails [] (throw (DatastoreFailureException. "Test Error"))) (dstest multiple-tries-in-transaction (is (thrown? DatastoreFailureException (tr/with-transaction (always-fails))))) (dstest non-transaction-datastore-operations-within-transactions (let [[k1 k2 k3 k4] (tr/with-transaction (let [entity (ds/create-entity {:kind "Person" :name "Entity"}) same-entity-group-as-entity (ds/create-entity {:kind "Person" :name "SameEntityGroupAsEntity" :parent-key (:key entity)})] (is (thrown? IllegalArgumentException ;; wrong entity group (ds/create-entity {:kind "Person" :name "WrongEntityGroup"}))) (map :key [entity same-entity-group-as-entity (tr/without-transaction ;; do atomic request via macro (ds/create-entity {:kind "Person" :name "DifferentEntityGroup"})) (ds/create-entity nil ;; do atomic request manually {:kind "Person" :name "CanDoItManuallyAsWell"})])))] (is (= "Entity" (:name (ds/get-entity k1)))) (is (= "SameEntityGroupAsEntity" (:name (ds/get-entity k2)))) (is (= "DifferentEntityGroup" (:name (ds/get-entity k3)))) (is (= "CanDoItManuallyAsWell" (:name (ds/get-entity k4)))))) (dstest nested-transactions (let [[k1 k2 k3 k4] (tr/with-transaction ;; transaction for first entity group (let [entity (ds/create-entity {:kind "Person" :name "Entity"}) same-entity-group-as-entity (ds/create-entity {:kind "Person" :name "SameEntityGroupAsEntity" :parent-key (:key entity)}) [entity2 same-entity-group-as-entity2] (tr/with-transaction ;; nested for a second entity group (let [entity2 (ds/create-entity {:kind "Person" :name "Entity2"}) same-entity-group-as-entity2 (ds/create-entity {:kind "Person" :name "SameEntityGroupAsEntity2" :parent-key (:key entity2)})] [entity2 same-entity-group-as-entity2]))] [entity same-entity-group-as-entity entity2 same-entity-group-as-entity2]))] (is (= "Entity" (:name (ds/get-entity k1)))) (is (= "SameEntityGroupAsEntity" (:name (ds/get-entity k2)))) (is (= "Entity2" (:name (ds/get-entity k3)))) (is (= "SameEntityGroupAsEntity2" (:name (ds/get-entity k4)))))) (dstest updates-with-transactions (let [entity (ds/create-entity {:kind "Person" :name "Entity"})] (tr/with-transaction (is (= "Entity" (:name entity))) (ds/update-entity entity {:day-job "hacker" :favorite-sport "beach volley"}) (ds/update-entity entity {:day-job "entrepreneur" :night-job "hacker++"}))) (let [[entity] (ds/find-all (doto (Query. "Person") (.addFilter "day-job" Query$FilterOperator/EQUAL "entrepreneur")))] (is (= "hacker++" (:night-job entity))) (is (= "Entity" (:name entity))) (is (nil? (:favorite-sport entity))))) ;; remember how ds's put works: only commit the latest Entity put ;; in case the same entity is put multiple times ;; transactions and find-all works, but is restricted as per ;; http://code.google.com/appengine/docs/java/datastore/queriesandindexes.html ;; text-search for Ancestor Queries (dstest deletes-with-transactions (let [entity (ds/create-entity {:kind "Person" :name "Entity"}) entity2 (ds/create-entity {:kind "Person" :name "Entity2"})] (tr/with-transaction (ds/delete-entity entity) (is (thrown? IllegalArgumentException (ds/delete-entity entity2)))) (is (thrown? EntityNotFoundException (ds/get-entity (:key entity)))) (is (= "Entity2" (:name (ds/get-entity (:key entity2))))) (tr/with-transaction (ds/delete-entity entity2) (tr/rollback-transaction)) (is (= "Entity2" (:name (ds/get-entity (:key entity2))))) (tr/with-transaction (ds/delete-entity entity2)) (is (thrown? EntityNotFoundException (ds/get-entity (:key entity2)))))) ;; We can also do transactions manually if we so wish (dstest manual-transactions (let [transaction (.beginTransaction (ds/datastore)) ;; manually create tr entity (ds/create-entity transaction {:kind "Person" :name "Entity"}) entity2 (ds/create-entity transaction {:kind "Person" :name "Entity2" :parent-key (:key entity)}) ;; transaction not committed so these should not be in ds yet [entity1?] (ds/find-all (doto (Query. "Person") (.addFilter "name" Query$FilterOperator/EQUAL "Entity"))) [entity2?] (ds/find-all (doto (Query. "Person") (.addFilter "name" Query$FilterOperator/EQUAL "Entity2")))] (is (nil? entity1?)) (is (nil? entity2?)) ;; now commit (.commit transaction) (let [[entity1?] (ds/find-all (doto (Query. "Person") (.addFilter "name" Query$FilterOperator/EQUAL "Entity"))) [entity2?] (ds/find-all (doto (Query. "Person") (.addFilter "name" Query$FilterOperator/EQUAL "Entity2")))] ;; post-commit we find the entities (is (= "Entity" (:name entity1?))) (is (= "Entity2" (:name entity2?)))))) ;just to show with-retries was tested manually ;(dstest doretry-transaction-manual-test ; (tr/with-retries 2 ; (try (tr/with-transaction ; (always-fails)) (catch Exception e (prn "error"))) ; (try (tr/with-transaction ; (always-fails)) (catch Exception e (prn "error"))))) ;; appengine.datastore/entities ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (en/defentity testuser () (name :key true) (job)) ;; it's the same deal as entities.clj relies on core.clj which ;; support transactions (dstest entities-macros-and-transactions (tr/with-transaction (let [user (create-testuser {:name "liz" :job "entrepreneur"})] (create-testuser {:name "robert" :job "PI:NAME:<NAME>END_PI" :parent-key (:key user)}))) (let [an-entrepreneur (find-testuser-by-job "entrepreneur") bob (find-testuser-by-name "robert")] (is (= "secretary" (:job bob))) (is (= "liz" (:name an-entrepreneur)))))
[ { "context": "e replacement for PHP\"\n :url \"https://github.com/alekcz/pcp\"\n :license {:name \"The MIT License\"\n ", "end": 136, "score": 0.9994082450866699, "start": 130, "tag": "USERNAME", "value": "alekcz" }, { "context": "2\"]\n [org.postgresql/postgresql \"42.2.11\"]\n [honeysql \"0.9.10\"]\n ", "end": 1245, "score": 0.8519598841667175, "start": 1238, "tag": "IP_ADDRESS", "value": "42.2.11" }, { "context": " org.clojure/clojurescript]]\n [alekcz/konserve-jdbc \"0.1.0-20210521.205028-12\" \n ", "end": 1696, "score": 0.6920410990715027, "start": 1690, "tag": "USERNAME", "value": "alekcz" }, { "context": ".jar\"}\n :test {:env {:my-passphrase \"s3cr3t-p455ph4r3\"\n :pcp-template-path \"r", "end": 2903, "score": 0.9890346527099609, "start": 2887, "tag": "PASSWORD", "value": "s3cr3t-p455ph4r3" }, { "context": "es\"}}\n :dev {:dependencies [[org.martinklepsch/clj-http-lite \"0.4.3\"]\n ", "end": 3032, "score": 0.5850129723548889, "start": 3023, "tag": "USERNAME", "value": "inklepsch" }, { "context": ".5.0\"]]\n :env {:my-passphrase \"s3cr3t-p455ph4r3\"}}}\n :aliases\n {\"pcp\" [\"run\" \"-m\" \"pcp.utility\"", "end": 3226, "score": 0.9757513403892517, "start": 3210, "tag": "PASSWORD", "value": "s3cr3t-p455ph4r3" } ]
project.clj
syk0saje/pcp
0
(defproject pcp "0.0.2-beta.3" :description "PCP: Clojure Processor - A Clojure replacement for PHP" :url "https://github.com/alekcz/pcp" :license {:name "The MIT License" :url "http://opensource.org/licenses/MIT"} :dependencies [ ;core [org.clojure/clojure "1.10.3"] [org.clojure/tools.cli "1.0.194"] [org.clojure/core.async "1.3.618"] [borkdude/sci "0.2.5"] [byte-streams "0.2.4"] [http-kit "2.5.0-RC1"] [ring "1.9.3"] [cheshire "5.9.0"] [danlentz/clj-uuid "0.1.9"] [commons-io/commons-io "2.6"] [commons-codec/commons-codec "1.14"] [com.google.guava/guava "28.2-jre"] [com.taoensso/nippy "3.1.1"] [environ "1.1.0"] [hiccup "2.0.0-alpha2"] [io.replikativ/hasch "0.3.7"] [org.clojure/core.cache "1.0.207"] ;includes for hosted environemnt [selmer "1.12.19"] [seancorfield/next.jdbc "1.1.582"] [org.postgresql/postgresql "42.2.11"] [honeysql "0.9.10"] [com.draines/postal "2.0.3"] [buddy "2.0.0"] [tick "0.4.23-alpha"] [alekcz/storyblok-clj "1.2.0"] [garden "1.3.10"] [io.replikativ/konserve "0.6.0-alpha3" :exclusions [org.clojure/clojure org.clojure/clojurescript]] [alekcz/konserve-jdbc "0.1.0-20210521.205028-12" :exclusions [org.clojure/clojure org.clojure/clojurescript com.h2database/h2 org.apache.derby/derby com.microsoft.sqlserver/mssql-jdbc]]] :main ^:skit-aot pcp.core :auto-clean false :dev-dependencies [[eftest/eftest "0.5.9"]] :plugins [[nrepl/lein-nrepl "0.3.2"] [lein-cloverage "1.2.2"] [lein-environ "1.1.0"] [lein-eftest "0.5.9"]] :cloverage {:runner :eftest :runner-opts {:test-warn-time 500 :fail-fast? false :multithread? :namespaces}} :profiles { :scgi { :aot :all :main pcp.core :jar-name "useless-pcp-server.jar" :uberjar-name "pcp-server.jar"} :utility { :main pcp.utility :aot [pcp.utility pcp.resp] :jar-name "useless-pcp.jar" :uberjar-name "pcp.jar"} :test {:env {:my-passphrase "s3cr3t-p455ph4r3" :pcp-template-path "resources/pcp-templates"}} :dev {:dependencies [[org.martinklepsch/clj-http-lite "0.4.3"] [eftest/eftest "0.5.9"]] :plugins [[lein-shell "0.5.0"]] :env {:my-passphrase "s3cr3t-p455ph4r3"}}} :aliases {"pcp" ["run" "-m" "pcp.utility"] "scgi" ["run" "-m" "pcp.core"] "build-pcp" ["with-profile" "utility" "uberjar"] "build-server" ["with-profile" "scgi" "uberjar"] "native" ["shell" "native-image" "--enable-url-protocols=http,https" "--report-unsupported-elements-at-runtime" "--no-fallback" "--initialize-at-build-time" "--allow-incomplete-classpath" "--initialize-at-run-time=org.postgresql.sspi.SSPIClient" "--enable-all-security-services" "--no-server" "-H:ReflectionConfigurationFiles=resources/reflect-config.json" "-jar" "./target/${:name}.jar" "-H:Name=./target/${:name}"] "run-native" ["shell" "./target/${:name} scgi"]})
75470
(defproject pcp "0.0.2-beta.3" :description "PCP: Clojure Processor - A Clojure replacement for PHP" :url "https://github.com/alekcz/pcp" :license {:name "The MIT License" :url "http://opensource.org/licenses/MIT"} :dependencies [ ;core [org.clojure/clojure "1.10.3"] [org.clojure/tools.cli "1.0.194"] [org.clojure/core.async "1.3.618"] [borkdude/sci "0.2.5"] [byte-streams "0.2.4"] [http-kit "2.5.0-RC1"] [ring "1.9.3"] [cheshire "5.9.0"] [danlentz/clj-uuid "0.1.9"] [commons-io/commons-io "2.6"] [commons-codec/commons-codec "1.14"] [com.google.guava/guava "28.2-jre"] [com.taoensso/nippy "3.1.1"] [environ "1.1.0"] [hiccup "2.0.0-alpha2"] [io.replikativ/hasch "0.3.7"] [org.clojure/core.cache "1.0.207"] ;includes for hosted environemnt [selmer "1.12.19"] [seancorfield/next.jdbc "1.1.582"] [org.postgresql/postgresql "42.2.11"] [honeysql "0.9.10"] [com.draines/postal "2.0.3"] [buddy "2.0.0"] [tick "0.4.23-alpha"] [alekcz/storyblok-clj "1.2.0"] [garden "1.3.10"] [io.replikativ/konserve "0.6.0-alpha3" :exclusions [org.clojure/clojure org.clojure/clojurescript]] [alekcz/konserve-jdbc "0.1.0-20210521.205028-12" :exclusions [org.clojure/clojure org.clojure/clojurescript com.h2database/h2 org.apache.derby/derby com.microsoft.sqlserver/mssql-jdbc]]] :main ^:skit-aot pcp.core :auto-clean false :dev-dependencies [[eftest/eftest "0.5.9"]] :plugins [[nrepl/lein-nrepl "0.3.2"] [lein-cloverage "1.2.2"] [lein-environ "1.1.0"] [lein-eftest "0.5.9"]] :cloverage {:runner :eftest :runner-opts {:test-warn-time 500 :fail-fast? false :multithread? :namespaces}} :profiles { :scgi { :aot :all :main pcp.core :jar-name "useless-pcp-server.jar" :uberjar-name "pcp-server.jar"} :utility { :main pcp.utility :aot [pcp.utility pcp.resp] :jar-name "useless-pcp.jar" :uberjar-name "pcp.jar"} :test {:env {:my-passphrase "<PASSWORD>" :pcp-template-path "resources/pcp-templates"}} :dev {:dependencies [[org.martinklepsch/clj-http-lite "0.4.3"] [eftest/eftest "0.5.9"]] :plugins [[lein-shell "0.5.0"]] :env {:my-passphrase "<PASSWORD>"}}} :aliases {"pcp" ["run" "-m" "pcp.utility"] "scgi" ["run" "-m" "pcp.core"] "build-pcp" ["with-profile" "utility" "uberjar"] "build-server" ["with-profile" "scgi" "uberjar"] "native" ["shell" "native-image" "--enable-url-protocols=http,https" "--report-unsupported-elements-at-runtime" "--no-fallback" "--initialize-at-build-time" "--allow-incomplete-classpath" "--initialize-at-run-time=org.postgresql.sspi.SSPIClient" "--enable-all-security-services" "--no-server" "-H:ReflectionConfigurationFiles=resources/reflect-config.json" "-jar" "./target/${:name}.jar" "-H:Name=./target/${:name}"] "run-native" ["shell" "./target/${:name} scgi"]})
true
(defproject pcp "0.0.2-beta.3" :description "PCP: Clojure Processor - A Clojure replacement for PHP" :url "https://github.com/alekcz/pcp" :license {:name "The MIT License" :url "http://opensource.org/licenses/MIT"} :dependencies [ ;core [org.clojure/clojure "1.10.3"] [org.clojure/tools.cli "1.0.194"] [org.clojure/core.async "1.3.618"] [borkdude/sci "0.2.5"] [byte-streams "0.2.4"] [http-kit "2.5.0-RC1"] [ring "1.9.3"] [cheshire "5.9.0"] [danlentz/clj-uuid "0.1.9"] [commons-io/commons-io "2.6"] [commons-codec/commons-codec "1.14"] [com.google.guava/guava "28.2-jre"] [com.taoensso/nippy "3.1.1"] [environ "1.1.0"] [hiccup "2.0.0-alpha2"] [io.replikativ/hasch "0.3.7"] [org.clojure/core.cache "1.0.207"] ;includes for hosted environemnt [selmer "1.12.19"] [seancorfield/next.jdbc "1.1.582"] [org.postgresql/postgresql "42.2.11"] [honeysql "0.9.10"] [com.draines/postal "2.0.3"] [buddy "2.0.0"] [tick "0.4.23-alpha"] [alekcz/storyblok-clj "1.2.0"] [garden "1.3.10"] [io.replikativ/konserve "0.6.0-alpha3" :exclusions [org.clojure/clojure org.clojure/clojurescript]] [alekcz/konserve-jdbc "0.1.0-20210521.205028-12" :exclusions [org.clojure/clojure org.clojure/clojurescript com.h2database/h2 org.apache.derby/derby com.microsoft.sqlserver/mssql-jdbc]]] :main ^:skit-aot pcp.core :auto-clean false :dev-dependencies [[eftest/eftest "0.5.9"]] :plugins [[nrepl/lein-nrepl "0.3.2"] [lein-cloverage "1.2.2"] [lein-environ "1.1.0"] [lein-eftest "0.5.9"]] :cloverage {:runner :eftest :runner-opts {:test-warn-time 500 :fail-fast? false :multithread? :namespaces}} :profiles { :scgi { :aot :all :main pcp.core :jar-name "useless-pcp-server.jar" :uberjar-name "pcp-server.jar"} :utility { :main pcp.utility :aot [pcp.utility pcp.resp] :jar-name "useless-pcp.jar" :uberjar-name "pcp.jar"} :test {:env {:my-passphrase "PI:PASSWORD:<PASSWORD>END_PI" :pcp-template-path "resources/pcp-templates"}} :dev {:dependencies [[org.martinklepsch/clj-http-lite "0.4.3"] [eftest/eftest "0.5.9"]] :plugins [[lein-shell "0.5.0"]] :env {:my-passphrase "PI:PASSWORD:<PASSWORD>END_PI"}}} :aliases {"pcp" ["run" "-m" "pcp.utility"] "scgi" ["run" "-m" "pcp.core"] "build-pcp" ["with-profile" "utility" "uberjar"] "build-server" ["with-profile" "scgi" "uberjar"] "native" ["shell" "native-image" "--enable-url-protocols=http,https" "--report-unsupported-elements-at-runtime" "--no-fallback" "--initialize-at-build-time" "--allow-incomplete-classpath" "--initialize-at-run-time=org.postgresql.sspi.SSPIClient" "--enable-all-security-services" "--no-server" "-H:ReflectionConfigurationFiles=resources/reflect-config.json" "-jar" "./target/${:name}.jar" "-H:Name=./target/${:name}"] "run-native" ["shell" "./target/${:name} scgi"]})
[ { "context": ";; Copyright (c) 2013-2017, Kenneth Leung. All rights reserved.\n;; The use and distribution", "end": 41, "score": 0.9998781085014343, "start": 28, "tag": "NAME", "value": "Kenneth Leung" }, { "context": "rs of\n vectors or maps.\"\n :author \"Kenneth Leung\"}\n\n czlab.antclj.antlib\n\n (:import [org.apache.", "end": 744, "score": 0.9998881220817566, "start": 731, "tag": "NAME", "value": "Kenneth Leung" }, { "context": " ^Target\n [^String target tasks]\n\n (let [pj @dftprj\n tg (Target.)]\n (. tg setName (or targe", "end": 20316, "score": 0.6379212141036987, "start": 20312, "tag": "USERNAME", "value": "tprj" } ]
attic/antlib.old.clj
llnek/cljant
0
;; Copyright (c) 2013-2017, Kenneth Leung. All rights reserved. ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns ^{:doc "Apache Ant project & task wrappers. The anatomy of an ant task is a xml construct, where the attributes are termed as options and nested elements are treated as vectors of vectors or maps." :author "Kenneth Leung"} czlab.antclj.antlib (:import [org.apache.tools.ant.taskdefs.optional.unix Symlink] [java.beans Introspector PropertyDescriptor] [java.lang.reflect Method] [java.util Stack] [java.io File] [org.apache.tools.ant.taskdefs Javadoc Java Copy Chmod Concat Move Mkdir Tar Replace ExecuteOn Delete Jar Zip ExecTask Javac Javadoc$AccessType Replace$Replacefilter Replace$NestedString Tar$TarFileSet Tar$TarCompressionMethod Javac$ImplementationSpecificArgument] [org.apache.tools.ant.listener AnsiColorLogger TimestampedLogger] [org.apache.tools.ant.types Commandline$Argument Commandline$Marker PatternSet$NameEntry Environment$Variable FileList$FileName FileList ZipFileSet Reference Mapper FileSet Path DirSet] [org.apache.tools.ant ProjectComponent NoBannerLogger Project Target Task] [org.apache.tools.ant.taskdefs.optional.junit FormatterElement$TypeAttribute JUnitTask$SummaryAttribute JUnitTask$ForkMode JUnitTask JUnitTest BatchTest FormatterElement] [org.apache.tools.ant.util FileNameMapper ChainedMapper GlobPatternMapper]) (:require [clojure.java.io :as io] [clojure.core :as cc] [clojure.string :as cs]) (:refer-clojure :exclude [apply get sync concat replace])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) (declare maybeCfgNested) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro ^:private nth?? "" [c p] `(first (drop (dec ~p) ~c))) (defmacro ^:private trap! "" [s] `(throw (Exception. ~s))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- capstr "Capitalize the 1st character" ^String [s] (if s (cs/capitalize (name s)) "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (def ^:private ansi-colors (cs/join "\n" ["AnsiColorLogger.ERROR_COLOR=0;31" "AnsiColorLogger.WARNING_COLOR=0;35" "AnsiColorLogger.INFO_COLOR=0;36" "AnsiColorLogger.VERBOSE_COLOR=0;32" "AnsiColorLogger.DEBUG_COLOR=0;34"])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- hackAnsiColors "" [] (let [f (-> (System/getProperty "java.io.tmpdir") (io/file "czlab-antlogansi.colors"))] (if-not (.exists f) (spit f ansi-colors)) (System/setProperty "ant.logger.defaults" (.getCanonicalPath f)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- project<> "New project" ^Project [] (let [_ (hackAnsiColors) lg (doto (AnsiColorLogger.) (.setOutputPrintStream System/out) (.setErrorPrintStream System/err) (.setMessageOutputLevel Project/MSG_INFO))] (doto (Project.) .init (.setName "projx") (.addBuildListener lg)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- execTarget "" [^Target t] (-> (.getProject t) (.executeTarget (.getName t)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro ^:private gpdn "" [pd] `(.getName ~(with-meta pd {:tag 'PropertyDescriptor}))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- getBeanInfo "" [cz] (persistent! (reduce #(assoc! %1 (keyword (gpdn %2)) %2) (transient {}) (-> (Introspector/getBeanInfo cz) .getPropertyDescriptors)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;create a default project. (defonce ^:private dftprj (atom (project<>))) (defonce ^:private beansCooked (atom false)) (def ^:private okay-tasks #{;;"ant" ;;"antcall" ;;"antstructure" ;;"antversion" "apply" "attrib" ;;"attributenamespacedef" ;;"augment" ;;"available" "basename" ;;"bindtargets" ;;"blgenclient" ;;"buildnumber" ;;"bunzip2" ;;"bzip2" "cab" ;;"cccheckin" ;;"cccheckout" ;;"cclock" ;;"ccmcheckin" ;;"ccmcheckintask" ;;"ccmcheckout" ;;"ccmcreatetask" ;;"ccmkattr" ;;"ccmkbl" ;;"ccmkdir" ;;"ccmkelem" ;;"ccmklabel" ;;"ccmklbtype" ;;"ccmreconfigure" ;;"ccrmtype" ;;"ccuncheckout" ;;"ccunlock" ;;"ccupdate" "checksum" "chgrp" "chmod" "chown" ;;"classloader" ;;"commandlauncher" ;;"componentdef" "concat" ;;"condition" "copy" ;;"copydir" ;;"copyfile" ;;"copypath" ;;"cvs" ;;"cvschangelog" ;;"cvspass" ;;"cvstagdiff" ;;"cvsversion" ;;"defaultexcludes" "delete" ;;"deltree" ;;"depend" ;;"dependset" ;;"diagnostics" ;;"dirname" "ear" "echo" "echoproperties" ;;"echoxml" ;;"ejbjar" "exec" ;;"execon" ;;"fail" ;;"filter" "fixcrlf" "genkey" "get" "gunzip" "gzip" "hostinfo" ;;"import" ;;"include" "input" ;;"iplanet-ejbc" "jar" ;;"jarlib-available" ;;"jarlib-display" ;;"jarlib-manifest" ;;"jarlib-resolve" "java" "javac" "javacc" "javadoc" ;;"javadoc2" "javah" "jjdoc" "jjtree" ;;"jlink" ;;"jspc" "junit" "junitreport" "length" ;;"loadfile" ;;"loadproperties" ;;"loadresource" ;;"local" ;;"macrodef" "mail" ;;"makeurl" "manifest" ;;"manifestclasspath" ;;"mimemail" "mkdir" "move" ;;"native2ascii" ;;"nice" ;;"parallel" "patch" ;;"pathconvert" ;;"presetdef" ;;"projecthelper" "property" ;;"propertyfile" ;;"propertyhelper" ;;"pvcs" ;;"record" ;;"rename" ;;"renameext" "replace" "replaceregexp" ;;"resourcecount" ;;"retry" ;;"rmic" "rpm" ;;"schemavalidate" ;;"script" ;;"scriptdef" ;;"sequential" ;;"serverdeploy" "setpermissions" "setproxy" "signjar" "sleep" ;;"soscheckin" ;;"soscheckout" ;;"sosget" ;;"soslabel" "sql" "style" ;;"subant" "symlink" "sync" "tar" ;;"taskdef" "tempfile" "touch" ;;"translate" "truncate" "tstamp" ;;"typedef" "unjar" "untar" "unwar" "unzip" ;;"uptodate" "verifyjar" ;;"vssadd" ;;"vsscheckin" ;;"vsscheckout" ;;"vsscp" ;;"vsscreate" ;;"vssget" ;;"vsshistory" ;;"vsslabel" ;;"waitfor" "war" "whichresource" ;;"wljspc" ;;"xmlproperty" ;;"xmlvalidate" "xslt" "zip"}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;cache ant task names as symbols, and cache bean-info of class (if-not @beansCooked (let [kees (atom (sorted-set)) beans (atom {}) syms (atom [])] (doseq [[k v] (. ^Project @dftprj getTaskDefinitions) :when (and (contains? okay-tasks k) (.isAssignableFrom Task v))] (swap! kees conj k) (swap! syms conj k k) (swap! beans assoc v (getBeanInfo v))) (println "syms = " @kees) (def ^:private _tasks (atom (partition 2 (map #(symbol %) @syms)))) (def ^:private _props (atom @beans)) (reset! beansCooked true))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- maybeProps "Add bean info for non-task classes" [cz] (let [b (getBeanInfo cz)] (swap! _props assoc cz b) b)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (def ^:private setterArgTypes ;;add more types when needed [String java.io.File Boolean/TYPE Boolean Integer/TYPE Integer Long/TYPE Long org.apache.tools.ant.types.Path]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- method? "Find this setter method via best match, if found, returns a tuple [method classofarg]" [^Class cz ^String m] (let [arr (make-array java.lang.Class 1)] (some (fn [^Class z] (try (aset #^"[Ljava.lang.Class;" arr 0 z) [(.getMethod cz m arr) z] (catch Throwable _))) setterArgTypes))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmulti ^:private koerce "Converter" (fn [_ a b] [a (class b)])) (defmethod koerce [Integer/TYPE String] [_ _ ^String v] (Integer/parseInt v (int 10))) (defmethod koerce [Integer String] [_ _ ^String v] (Integer/parseInt v (int 10))) (defmethod koerce [Integer/TYPE Long] [_ _ ^Long v] (.intValue v)) (defmethod koerce [Integer Long] [_ _ ^Long v] (.intValue v)) (defmethod koerce [Integer/TYPE Integer] [_ _ ^Integer v] v) (defmethod koerce [Integer Integer] [_ _ ^Integer v] v) (defmethod koerce [Long/TYPE String] [_ _ ^String v] (Long/parseLong v (int 10))) (defmethod koerce [Long String] [_ _ ^String v] (Long/parseLong v (int 10))) (defmethod koerce [Long/TYPE Long] [_ _ ^Long v] v) (defmethod koerce [Long Long] [_ _ ^Long v] v) (defmethod koerce [Path File] [^Project pj _ ^File v] (Path. pj (.getCanonicalPath v))) (defmethod koerce [Path String] [^Project pj _ ^String v] (Path. pj v)) (defmethod koerce [File String] [_ _ ^String v] (io/file v)) (defmethod koerce [File File] [_ _ v] v) (defmethod koerce :default [_ pz _] (Exception. (str "expected class " pz))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- coerce "Best attempt to convert a given value" [pj pz value] (cond (or (= Boolean/TYPE pz) (= Boolean pz)) (= "true" (str value)) (= String pz) (str value) :else (koerce pj pz value))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- setProp! "" [wm pojo k arr] (try (. ^Method wm invoke pojo arr) (catch Throwable _ (println (str "failed to set " k " for " (class pojo))) (throw _)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- setOptions "Use reflection to invoke setters -> to set options on the pojo" ([pj pojo options] (setOptions pj pojo options nil)) ([^Project pj pojo options skips] (let [arr (object-array 1) cz (class pojo) ps (or (cc/get @_props cz) (maybeProps cz))] (if (instance? ProjectComponent pojo) (. ^ProjectComponent pojo setProject pj)) (doseq [[k v] options :when (not (contains? skips k))] (if-some [^PropertyDescriptor pd (cc/get ps k)] (-> ;;some cases the beaninfo is erroneous ;;so fall back to use *best-try* (let [mn (str "set" (capstr k)) wm (.getWriteMethod pd) pt (.getPropertyType pd)] (if (some? wm) (do (->> (coerce pj pt v) (aset arr 0)) wm) (let [[wm pt] (method? cz mn)] (if (nil? wm) (trap! (str mn " not in " cz))) (->> (coerce pj pt v) (aset arr 0)) wm))) (setProp! pojo k arr)) (trap! (str "prop['" k "'] not in " cz))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- projcomp<> "Configure a project component" {:tag ProjectComponent} ([^Project pj ^ProjectComponent pc options nested] (if (fn? options) (options pj pc) (setOptions pj pc options)) (if (fn? nested) (nested pj pc) (maybeCfgNested pj pc nested)) pc) ([pj pc options] (projcomp<> pj pc options nil)) ([pj pc] (projcomp<> pj pc nil nil))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro ^:private antFileSet "" [options] `(merge {:errorOnMissingDir false} ~options)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- antChainedMapper "Handles glob only" ^ProjectComponent [nested pj cm] (doseq [n nested] (case (:type n) :glob (->> (doto (GlobPatternMapper.) (.setFrom (:from n)) (.setTo (:to n))) (. ^ChainedMapper cm add )) (trap! (str "unknown mapper: " n)))) cm) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- antFormatter "" ^ProjectComponent [options pj tk] (if-some [[k v] (find options :type)] (. ^FormatterElement tk setType (doto (FormatterElement$TypeAttribute.) (.setValue (str v))))) (setOptions pj tk options #{:type}) tk) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- setClassPath "Build a nested Path structure for classpath" [^Project pj ^Path root paths] (doseq [p paths] (case (first p) :location (doto (.createPath root) (.setLocation (io/file (str (last p))))) :refid (trap! "path:refid not supported") ;;(doto (.createPath root) (.setRefid (last p))) :fileset (->> (projcomp<> pj (FileSet.) (antFileSet (second p)) (nth?? p 3)) (.addFileset root)) (trap! (str "unknown path: " p)))) root) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- maybeCfgNested "" [pj tk nested] (doseq [p nested] (case (first p) :compilerarg (if-some [n (:line (last p))] (-> (.createCompilerArg tk) (.setLine ^String n))) :file (let [n (FileList$FileName.)] (. n setName (str (:name (second p)))) (. tk addConfiguredFile n)) :classpath (setClassPath pj (.createClasspath tk) (last p)) :sysprops (doseq [[k v] (last p)] (->> (doto (Environment$Variable.) (.setKey (name k)) (.setValue (str v))) (.addSysproperty tk))) :formatter (->> (projcomp<> pj (FormatterElement.) (partial antFormatter (last p))) (.addFormatter tk)) :include (let [v (cs/trim (str (last p)))] (if-not (empty? v) (-> (.createInclude tk) (.setName v)))) :exclude (let [v (cs/trim (str (last p)))] (if-not (empty? v) (-> (.createExclude tk) (.setName v)))) :filelist (->> (projcomp<> pj (FileList.) (second p) (nth?? p 3)) (.addFilelist tk)) :patternset (projcomp<> pj (.createPatternSet tk) (second p) (nth?? p 3)) :dirset (->> (projcomp<> pj (DirSet.) (antFileSet (second p)) (nth?? p 3)) (.addDirset tk )) :fileset (let [s (projcomp<> pj (FileSet.) (antFileSet (second p)) (nth?? p 3))] (if (instance? BatchTest tk) (.addFileSet tk s) (.addFileset tk s))) :argvalues (doseq [v (last p)] (-> (.createArg tk) (.setValue (str v)))) :argpaths (doseq [v (last p)] (-> (.createArg tk) (.setPath (Path. pj (str v))))) :arglines (doseq [v (last p)] (-> (.createArg tk) (.setLine (str v)))) :replacefilter (doto (.createReplacefilter tk) (.setToken (:token (nth p 1))) (.setValue (:value (nth p 1)))) :replacevalue (-> (.createReplaceValue tk) (.addText (:text (last p)))) :replacetoken (-> (.createReplaceToken tk) (.addText (:text (last p)))) :test (. tk addTest (projcomp<> pj (JUnitTest.) (second p) (nth?? p 3))) :chainedmapper (. tk add (projcomp<> pj (ChainedMapper.) (second p) (partial antChainedMapper (nth?? p 3)))) :targetfile (.createTargetfile tk) :srcfile (.createSrcfile tk) :batchtest (projcomp<> pj (.createBatchTest tk) (second p) (nth?? p 3)) :tarfileset (projcomp<> pj (.createTarFileSet tk) (second p) (nth?? p 3)) :zipfileset (projcomp<> pj (let [z (ZipFileSet.)] (. ^Zip tk addZipfileset z) z) (second p) (nth?? p 3)) (trap! (str "unknown nested: " p))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- xxx-preopts "" [tk options] [options #{}]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- delete-pre-opts "" [tk options] [(merge {:includeEmptyDirs true} options) #{}]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- junit-preopts "" [^JUnitTask tk options] (if-some [v (:printsummary options)] (. tk setPrintsummary (doto (JUnitTask$SummaryAttribute.) (.setValue (str v))))) (if-some [v (:forkMode options)] (. tk setForkMode (doto (JUnitTask$ForkMode.) (.setValue (str v))))) [options #{:printsummary :forkMode}]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- jdoc-preopts "" [tk options] (if-some [v (:access options)] (. ^Javadoc tk setAccess (doto (Javadoc$AccessType.) (.setValue (str v))))) [options #{:access}]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- tar-preopts "" [tk options] (if-some [v (:compression options)] (. ^Tar tk setCompression (doto (Tar$TarCompressionMethod.) (.setValue (str v))))) [options #{:compression}]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- init-task "Reify and configure actual ant tasks" ^Task [^Project pj ^Target target {:keys [pre-options tname task options nested]}] (let [preopts (or pre-options xxx-preopts)] (->> (doto ^Task task (.setProject pj) (.setOwningTarget target)) (.addTask target)) (->> (preopts task options) (cc/apply setOptions pj task)) (maybeCfgNested pj task nested) task)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- projAntTasks "Bind all the tasks to a target and a project" ^Target [^String target tasks] (let [pj @dftprj tg (Target.)] (. tg setName (or target "")) (. ^Project pj addOrReplaceTarget tg) ;;(println (str "number of tasks ==== " (count tasks))) (doseq [t tasks] (init-task pj tg t)) tg)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- projAntTasks* "Bind all the tasks to a target and a project" ^Target [target & tasks] (projAntTasks target tasks)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn runTarget "Run ant tasks" [target tasks] (-> (projAntTasks target tasks) execTarget)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn runTarget* "Run ant tasks" [target & tasks] (runTarget target tasks)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn runTasks "Run ant tasks" [tasks] (runTarget "" tasks)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn runTasks* "Run ant tasks" [& tasks] (runTarget "" tasks)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- ctask<> "" ^Task [^Project p ^String tt ^String tm] (doto (.createTask p tt) (.setTaskName tm))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro ^:private ant-task "Generate wrapper function for an ant task" ([pj sym docstr func preopt] (let [s (str func) tm (cs/lower-case (.substring s (inc (.lastIndexOf s "."))))] `(defn ~sym ~docstr ;;{:no-doc true} ([~'options] (~sym ~'options nil)) ([~'options ~'nestedElements] (let [tk# (ctask<> ~pj ~s ~tm) o# (or ~'options {}) n# (or ~'nestedElements []) r# {:pre-options ~preopt :tname ~tm :task tk# :options o# :nested n#}] (if (nil? (:pre-options r#)) (->> (case ~s ;;certain classes need special handling of properties ;;due to type mismatch or property name ;;inconsistencies "delete" delete-pre-opts "junit" junit-preopts "javadoc" jdoc-preopts "tar" tar-preopts nil) (assoc r# :pre-options)) r#)))))) ([pj sym docstr func] `(ant-task ~pj ~sym ~docstr ~func nil))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro ^:private declAntTasks "Introspect the default project and cache all registered ant-tasks" [pj] `(do ~@(map (fn [[a b]] `(ant-task ~pj ~a "" ~b)) (deref _tasks)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (declAntTasks @dftprj) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn cleanDir "Clean an existing dir or create it" ([d] (cleanDir d nil)) ([d {:keys [quiet] :or {quiet true}}] (let [dir (io/file d)] (if (.exists dir) (runTasks* (delete {:removeNotFollowedSymlinks true :quiet quiet} [[:fileset {:followSymlinks false :dir dir} [[:include "**/*"]]]])) (.mkdirs dir))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn deleteDir "Remove a directory" ([d] (deleteDir d nil)) ([d {:keys [quiet] :or {quiet true}}] (let [dir (io/file d)] (when (.exists dir) (runTasks* (delete {:removeNotFollowedSymlinks true :quiet quiet} [[:fileset {:followSymlinks false :dir dir}]])))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn copyFile "Copy a file to the target folder" [file toDir] (.mkdirs (io/file toDir)) (runTasks* (copy {:file file :todir toDir}))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn moveFile "Move a file to the target folder" [file toDir] (.mkdirs (io/file toDir)) (runTasks* (move {:file file :todir toDir}))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn deleteLink "Delete a file system symbolic link" [link] (runTasks* (symlink {:action "delete" :link link}))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn createLink "Create a file system symbolic link" ([link target] (createLink link target true)) ([link target overwrite?] (runTasks* (symlink {:overwrite overwrite? :action "single" :link link :resource target})))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
53418
;; Copyright (c) 2013-2017, <NAME>. All rights reserved. ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns ^{:doc "Apache Ant project & task wrappers. The anatomy of an ant task is a xml construct, where the attributes are termed as options and nested elements are treated as vectors of vectors or maps." :author "<NAME>"} czlab.antclj.antlib (:import [org.apache.tools.ant.taskdefs.optional.unix Symlink] [java.beans Introspector PropertyDescriptor] [java.lang.reflect Method] [java.util Stack] [java.io File] [org.apache.tools.ant.taskdefs Javadoc Java Copy Chmod Concat Move Mkdir Tar Replace ExecuteOn Delete Jar Zip ExecTask Javac Javadoc$AccessType Replace$Replacefilter Replace$NestedString Tar$TarFileSet Tar$TarCompressionMethod Javac$ImplementationSpecificArgument] [org.apache.tools.ant.listener AnsiColorLogger TimestampedLogger] [org.apache.tools.ant.types Commandline$Argument Commandline$Marker PatternSet$NameEntry Environment$Variable FileList$FileName FileList ZipFileSet Reference Mapper FileSet Path DirSet] [org.apache.tools.ant ProjectComponent NoBannerLogger Project Target Task] [org.apache.tools.ant.taskdefs.optional.junit FormatterElement$TypeAttribute JUnitTask$SummaryAttribute JUnitTask$ForkMode JUnitTask JUnitTest BatchTest FormatterElement] [org.apache.tools.ant.util FileNameMapper ChainedMapper GlobPatternMapper]) (:require [clojure.java.io :as io] [clojure.core :as cc] [clojure.string :as cs]) (:refer-clojure :exclude [apply get sync concat replace])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) (declare maybeCfgNested) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro ^:private nth?? "" [c p] `(first (drop (dec ~p) ~c))) (defmacro ^:private trap! "" [s] `(throw (Exception. ~s))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- capstr "Capitalize the 1st character" ^String [s] (if s (cs/capitalize (name s)) "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (def ^:private ansi-colors (cs/join "\n" ["AnsiColorLogger.ERROR_COLOR=0;31" "AnsiColorLogger.WARNING_COLOR=0;35" "AnsiColorLogger.INFO_COLOR=0;36" "AnsiColorLogger.VERBOSE_COLOR=0;32" "AnsiColorLogger.DEBUG_COLOR=0;34"])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- hackAnsiColors "" [] (let [f (-> (System/getProperty "java.io.tmpdir") (io/file "czlab-antlogansi.colors"))] (if-not (.exists f) (spit f ansi-colors)) (System/setProperty "ant.logger.defaults" (.getCanonicalPath f)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- project<> "New project" ^Project [] (let [_ (hackAnsiColors) lg (doto (AnsiColorLogger.) (.setOutputPrintStream System/out) (.setErrorPrintStream System/err) (.setMessageOutputLevel Project/MSG_INFO))] (doto (Project.) .init (.setName "projx") (.addBuildListener lg)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- execTarget "" [^Target t] (-> (.getProject t) (.executeTarget (.getName t)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro ^:private gpdn "" [pd] `(.getName ~(with-meta pd {:tag 'PropertyDescriptor}))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- getBeanInfo "" [cz] (persistent! (reduce #(assoc! %1 (keyword (gpdn %2)) %2) (transient {}) (-> (Introspector/getBeanInfo cz) .getPropertyDescriptors)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;create a default project. (defonce ^:private dftprj (atom (project<>))) (defonce ^:private beansCooked (atom false)) (def ^:private okay-tasks #{;;"ant" ;;"antcall" ;;"antstructure" ;;"antversion" "apply" "attrib" ;;"attributenamespacedef" ;;"augment" ;;"available" "basename" ;;"bindtargets" ;;"blgenclient" ;;"buildnumber" ;;"bunzip2" ;;"bzip2" "cab" ;;"cccheckin" ;;"cccheckout" ;;"cclock" ;;"ccmcheckin" ;;"ccmcheckintask" ;;"ccmcheckout" ;;"ccmcreatetask" ;;"ccmkattr" ;;"ccmkbl" ;;"ccmkdir" ;;"ccmkelem" ;;"ccmklabel" ;;"ccmklbtype" ;;"ccmreconfigure" ;;"ccrmtype" ;;"ccuncheckout" ;;"ccunlock" ;;"ccupdate" "checksum" "chgrp" "chmod" "chown" ;;"classloader" ;;"commandlauncher" ;;"componentdef" "concat" ;;"condition" "copy" ;;"copydir" ;;"copyfile" ;;"copypath" ;;"cvs" ;;"cvschangelog" ;;"cvspass" ;;"cvstagdiff" ;;"cvsversion" ;;"defaultexcludes" "delete" ;;"deltree" ;;"depend" ;;"dependset" ;;"diagnostics" ;;"dirname" "ear" "echo" "echoproperties" ;;"echoxml" ;;"ejbjar" "exec" ;;"execon" ;;"fail" ;;"filter" "fixcrlf" "genkey" "get" "gunzip" "gzip" "hostinfo" ;;"import" ;;"include" "input" ;;"iplanet-ejbc" "jar" ;;"jarlib-available" ;;"jarlib-display" ;;"jarlib-manifest" ;;"jarlib-resolve" "java" "javac" "javacc" "javadoc" ;;"javadoc2" "javah" "jjdoc" "jjtree" ;;"jlink" ;;"jspc" "junit" "junitreport" "length" ;;"loadfile" ;;"loadproperties" ;;"loadresource" ;;"local" ;;"macrodef" "mail" ;;"makeurl" "manifest" ;;"manifestclasspath" ;;"mimemail" "mkdir" "move" ;;"native2ascii" ;;"nice" ;;"parallel" "patch" ;;"pathconvert" ;;"presetdef" ;;"projecthelper" "property" ;;"propertyfile" ;;"propertyhelper" ;;"pvcs" ;;"record" ;;"rename" ;;"renameext" "replace" "replaceregexp" ;;"resourcecount" ;;"retry" ;;"rmic" "rpm" ;;"schemavalidate" ;;"script" ;;"scriptdef" ;;"sequential" ;;"serverdeploy" "setpermissions" "setproxy" "signjar" "sleep" ;;"soscheckin" ;;"soscheckout" ;;"sosget" ;;"soslabel" "sql" "style" ;;"subant" "symlink" "sync" "tar" ;;"taskdef" "tempfile" "touch" ;;"translate" "truncate" "tstamp" ;;"typedef" "unjar" "untar" "unwar" "unzip" ;;"uptodate" "verifyjar" ;;"vssadd" ;;"vsscheckin" ;;"vsscheckout" ;;"vsscp" ;;"vsscreate" ;;"vssget" ;;"vsshistory" ;;"vsslabel" ;;"waitfor" "war" "whichresource" ;;"wljspc" ;;"xmlproperty" ;;"xmlvalidate" "xslt" "zip"}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;cache ant task names as symbols, and cache bean-info of class (if-not @beansCooked (let [kees (atom (sorted-set)) beans (atom {}) syms (atom [])] (doseq [[k v] (. ^Project @dftprj getTaskDefinitions) :when (and (contains? okay-tasks k) (.isAssignableFrom Task v))] (swap! kees conj k) (swap! syms conj k k) (swap! beans assoc v (getBeanInfo v))) (println "syms = " @kees) (def ^:private _tasks (atom (partition 2 (map #(symbol %) @syms)))) (def ^:private _props (atom @beans)) (reset! beansCooked true))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- maybeProps "Add bean info for non-task classes" [cz] (let [b (getBeanInfo cz)] (swap! _props assoc cz b) b)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (def ^:private setterArgTypes ;;add more types when needed [String java.io.File Boolean/TYPE Boolean Integer/TYPE Integer Long/TYPE Long org.apache.tools.ant.types.Path]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- method? "Find this setter method via best match, if found, returns a tuple [method classofarg]" [^Class cz ^String m] (let [arr (make-array java.lang.Class 1)] (some (fn [^Class z] (try (aset #^"[Ljava.lang.Class;" arr 0 z) [(.getMethod cz m arr) z] (catch Throwable _))) setterArgTypes))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmulti ^:private koerce "Converter" (fn [_ a b] [a (class b)])) (defmethod koerce [Integer/TYPE String] [_ _ ^String v] (Integer/parseInt v (int 10))) (defmethod koerce [Integer String] [_ _ ^String v] (Integer/parseInt v (int 10))) (defmethod koerce [Integer/TYPE Long] [_ _ ^Long v] (.intValue v)) (defmethod koerce [Integer Long] [_ _ ^Long v] (.intValue v)) (defmethod koerce [Integer/TYPE Integer] [_ _ ^Integer v] v) (defmethod koerce [Integer Integer] [_ _ ^Integer v] v) (defmethod koerce [Long/TYPE String] [_ _ ^String v] (Long/parseLong v (int 10))) (defmethod koerce [Long String] [_ _ ^String v] (Long/parseLong v (int 10))) (defmethod koerce [Long/TYPE Long] [_ _ ^Long v] v) (defmethod koerce [Long Long] [_ _ ^Long v] v) (defmethod koerce [Path File] [^Project pj _ ^File v] (Path. pj (.getCanonicalPath v))) (defmethod koerce [Path String] [^Project pj _ ^String v] (Path. pj v)) (defmethod koerce [File String] [_ _ ^String v] (io/file v)) (defmethod koerce [File File] [_ _ v] v) (defmethod koerce :default [_ pz _] (Exception. (str "expected class " pz))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- coerce "Best attempt to convert a given value" [pj pz value] (cond (or (= Boolean/TYPE pz) (= Boolean pz)) (= "true" (str value)) (= String pz) (str value) :else (koerce pj pz value))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- setProp! "" [wm pojo k arr] (try (. ^Method wm invoke pojo arr) (catch Throwable _ (println (str "failed to set " k " for " (class pojo))) (throw _)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- setOptions "Use reflection to invoke setters -> to set options on the pojo" ([pj pojo options] (setOptions pj pojo options nil)) ([^Project pj pojo options skips] (let [arr (object-array 1) cz (class pojo) ps (or (cc/get @_props cz) (maybeProps cz))] (if (instance? ProjectComponent pojo) (. ^ProjectComponent pojo setProject pj)) (doseq [[k v] options :when (not (contains? skips k))] (if-some [^PropertyDescriptor pd (cc/get ps k)] (-> ;;some cases the beaninfo is erroneous ;;so fall back to use *best-try* (let [mn (str "set" (capstr k)) wm (.getWriteMethod pd) pt (.getPropertyType pd)] (if (some? wm) (do (->> (coerce pj pt v) (aset arr 0)) wm) (let [[wm pt] (method? cz mn)] (if (nil? wm) (trap! (str mn " not in " cz))) (->> (coerce pj pt v) (aset arr 0)) wm))) (setProp! pojo k arr)) (trap! (str "prop['" k "'] not in " cz))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- projcomp<> "Configure a project component" {:tag ProjectComponent} ([^Project pj ^ProjectComponent pc options nested] (if (fn? options) (options pj pc) (setOptions pj pc options)) (if (fn? nested) (nested pj pc) (maybeCfgNested pj pc nested)) pc) ([pj pc options] (projcomp<> pj pc options nil)) ([pj pc] (projcomp<> pj pc nil nil))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro ^:private antFileSet "" [options] `(merge {:errorOnMissingDir false} ~options)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- antChainedMapper "Handles glob only" ^ProjectComponent [nested pj cm] (doseq [n nested] (case (:type n) :glob (->> (doto (GlobPatternMapper.) (.setFrom (:from n)) (.setTo (:to n))) (. ^ChainedMapper cm add )) (trap! (str "unknown mapper: " n)))) cm) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- antFormatter "" ^ProjectComponent [options pj tk] (if-some [[k v] (find options :type)] (. ^FormatterElement tk setType (doto (FormatterElement$TypeAttribute.) (.setValue (str v))))) (setOptions pj tk options #{:type}) tk) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- setClassPath "Build a nested Path structure for classpath" [^Project pj ^Path root paths] (doseq [p paths] (case (first p) :location (doto (.createPath root) (.setLocation (io/file (str (last p))))) :refid (trap! "path:refid not supported") ;;(doto (.createPath root) (.setRefid (last p))) :fileset (->> (projcomp<> pj (FileSet.) (antFileSet (second p)) (nth?? p 3)) (.addFileset root)) (trap! (str "unknown path: " p)))) root) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- maybeCfgNested "" [pj tk nested] (doseq [p nested] (case (first p) :compilerarg (if-some [n (:line (last p))] (-> (.createCompilerArg tk) (.setLine ^String n))) :file (let [n (FileList$FileName.)] (. n setName (str (:name (second p)))) (. tk addConfiguredFile n)) :classpath (setClassPath pj (.createClasspath tk) (last p)) :sysprops (doseq [[k v] (last p)] (->> (doto (Environment$Variable.) (.setKey (name k)) (.setValue (str v))) (.addSysproperty tk))) :formatter (->> (projcomp<> pj (FormatterElement.) (partial antFormatter (last p))) (.addFormatter tk)) :include (let [v (cs/trim (str (last p)))] (if-not (empty? v) (-> (.createInclude tk) (.setName v)))) :exclude (let [v (cs/trim (str (last p)))] (if-not (empty? v) (-> (.createExclude tk) (.setName v)))) :filelist (->> (projcomp<> pj (FileList.) (second p) (nth?? p 3)) (.addFilelist tk)) :patternset (projcomp<> pj (.createPatternSet tk) (second p) (nth?? p 3)) :dirset (->> (projcomp<> pj (DirSet.) (antFileSet (second p)) (nth?? p 3)) (.addDirset tk )) :fileset (let [s (projcomp<> pj (FileSet.) (antFileSet (second p)) (nth?? p 3))] (if (instance? BatchTest tk) (.addFileSet tk s) (.addFileset tk s))) :argvalues (doseq [v (last p)] (-> (.createArg tk) (.setValue (str v)))) :argpaths (doseq [v (last p)] (-> (.createArg tk) (.setPath (Path. pj (str v))))) :arglines (doseq [v (last p)] (-> (.createArg tk) (.setLine (str v)))) :replacefilter (doto (.createReplacefilter tk) (.setToken (:token (nth p 1))) (.setValue (:value (nth p 1)))) :replacevalue (-> (.createReplaceValue tk) (.addText (:text (last p)))) :replacetoken (-> (.createReplaceToken tk) (.addText (:text (last p)))) :test (. tk addTest (projcomp<> pj (JUnitTest.) (second p) (nth?? p 3))) :chainedmapper (. tk add (projcomp<> pj (ChainedMapper.) (second p) (partial antChainedMapper (nth?? p 3)))) :targetfile (.createTargetfile tk) :srcfile (.createSrcfile tk) :batchtest (projcomp<> pj (.createBatchTest tk) (second p) (nth?? p 3)) :tarfileset (projcomp<> pj (.createTarFileSet tk) (second p) (nth?? p 3)) :zipfileset (projcomp<> pj (let [z (ZipFileSet.)] (. ^Zip tk addZipfileset z) z) (second p) (nth?? p 3)) (trap! (str "unknown nested: " p))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- xxx-preopts "" [tk options] [options #{}]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- delete-pre-opts "" [tk options] [(merge {:includeEmptyDirs true} options) #{}]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- junit-preopts "" [^JUnitTask tk options] (if-some [v (:printsummary options)] (. tk setPrintsummary (doto (JUnitTask$SummaryAttribute.) (.setValue (str v))))) (if-some [v (:forkMode options)] (. tk setForkMode (doto (JUnitTask$ForkMode.) (.setValue (str v))))) [options #{:printsummary :forkMode}]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- jdoc-preopts "" [tk options] (if-some [v (:access options)] (. ^Javadoc tk setAccess (doto (Javadoc$AccessType.) (.setValue (str v))))) [options #{:access}]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- tar-preopts "" [tk options] (if-some [v (:compression options)] (. ^Tar tk setCompression (doto (Tar$TarCompressionMethod.) (.setValue (str v))))) [options #{:compression}]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- init-task "Reify and configure actual ant tasks" ^Task [^Project pj ^Target target {:keys [pre-options tname task options nested]}] (let [preopts (or pre-options xxx-preopts)] (->> (doto ^Task task (.setProject pj) (.setOwningTarget target)) (.addTask target)) (->> (preopts task options) (cc/apply setOptions pj task)) (maybeCfgNested pj task nested) task)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- projAntTasks "Bind all the tasks to a target and a project" ^Target [^String target tasks] (let [pj @dftprj tg (Target.)] (. tg setName (or target "")) (. ^Project pj addOrReplaceTarget tg) ;;(println (str "number of tasks ==== " (count tasks))) (doseq [t tasks] (init-task pj tg t)) tg)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- projAntTasks* "Bind all the tasks to a target and a project" ^Target [target & tasks] (projAntTasks target tasks)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn runTarget "Run ant tasks" [target tasks] (-> (projAntTasks target tasks) execTarget)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn runTarget* "Run ant tasks" [target & tasks] (runTarget target tasks)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn runTasks "Run ant tasks" [tasks] (runTarget "" tasks)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn runTasks* "Run ant tasks" [& tasks] (runTarget "" tasks)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- ctask<> "" ^Task [^Project p ^String tt ^String tm] (doto (.createTask p tt) (.setTaskName tm))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro ^:private ant-task "Generate wrapper function for an ant task" ([pj sym docstr func preopt] (let [s (str func) tm (cs/lower-case (.substring s (inc (.lastIndexOf s "."))))] `(defn ~sym ~docstr ;;{:no-doc true} ([~'options] (~sym ~'options nil)) ([~'options ~'nestedElements] (let [tk# (ctask<> ~pj ~s ~tm) o# (or ~'options {}) n# (or ~'nestedElements []) r# {:pre-options ~preopt :tname ~tm :task tk# :options o# :nested n#}] (if (nil? (:pre-options r#)) (->> (case ~s ;;certain classes need special handling of properties ;;due to type mismatch or property name ;;inconsistencies "delete" delete-pre-opts "junit" junit-preopts "javadoc" jdoc-preopts "tar" tar-preopts nil) (assoc r# :pre-options)) r#)))))) ([pj sym docstr func] `(ant-task ~pj ~sym ~docstr ~func nil))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro ^:private declAntTasks "Introspect the default project and cache all registered ant-tasks" [pj] `(do ~@(map (fn [[a b]] `(ant-task ~pj ~a "" ~b)) (deref _tasks)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (declAntTasks @dftprj) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn cleanDir "Clean an existing dir or create it" ([d] (cleanDir d nil)) ([d {:keys [quiet] :or {quiet true}}] (let [dir (io/file d)] (if (.exists dir) (runTasks* (delete {:removeNotFollowedSymlinks true :quiet quiet} [[:fileset {:followSymlinks false :dir dir} [[:include "**/*"]]]])) (.mkdirs dir))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn deleteDir "Remove a directory" ([d] (deleteDir d nil)) ([d {:keys [quiet] :or {quiet true}}] (let [dir (io/file d)] (when (.exists dir) (runTasks* (delete {:removeNotFollowedSymlinks true :quiet quiet} [[:fileset {:followSymlinks false :dir dir}]])))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn copyFile "Copy a file to the target folder" [file toDir] (.mkdirs (io/file toDir)) (runTasks* (copy {:file file :todir toDir}))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn moveFile "Move a file to the target folder" [file toDir] (.mkdirs (io/file toDir)) (runTasks* (move {:file file :todir toDir}))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn deleteLink "Delete a file system symbolic link" [link] (runTasks* (symlink {:action "delete" :link link}))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn createLink "Create a file system symbolic link" ([link target] (createLink link target true)) ([link target overwrite?] (runTasks* (symlink {:overwrite overwrite? :action "single" :link link :resource target})))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
true
;; Copyright (c) 2013-2017, PI:NAME:<NAME>END_PI. All rights reserved. ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns ^{:doc "Apache Ant project & task wrappers. The anatomy of an ant task is a xml construct, where the attributes are termed as options and nested elements are treated as vectors of vectors or maps." :author "PI:NAME:<NAME>END_PI"} czlab.antclj.antlib (:import [org.apache.tools.ant.taskdefs.optional.unix Symlink] [java.beans Introspector PropertyDescriptor] [java.lang.reflect Method] [java.util Stack] [java.io File] [org.apache.tools.ant.taskdefs Javadoc Java Copy Chmod Concat Move Mkdir Tar Replace ExecuteOn Delete Jar Zip ExecTask Javac Javadoc$AccessType Replace$Replacefilter Replace$NestedString Tar$TarFileSet Tar$TarCompressionMethod Javac$ImplementationSpecificArgument] [org.apache.tools.ant.listener AnsiColorLogger TimestampedLogger] [org.apache.tools.ant.types Commandline$Argument Commandline$Marker PatternSet$NameEntry Environment$Variable FileList$FileName FileList ZipFileSet Reference Mapper FileSet Path DirSet] [org.apache.tools.ant ProjectComponent NoBannerLogger Project Target Task] [org.apache.tools.ant.taskdefs.optional.junit FormatterElement$TypeAttribute JUnitTask$SummaryAttribute JUnitTask$ForkMode JUnitTask JUnitTest BatchTest FormatterElement] [org.apache.tools.ant.util FileNameMapper ChainedMapper GlobPatternMapper]) (:require [clojure.java.io :as io] [clojure.core :as cc] [clojure.string :as cs]) (:refer-clojure :exclude [apply get sync concat replace])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) (declare maybeCfgNested) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro ^:private nth?? "" [c p] `(first (drop (dec ~p) ~c))) (defmacro ^:private trap! "" [s] `(throw (Exception. ~s))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- capstr "Capitalize the 1st character" ^String [s] (if s (cs/capitalize (name s)) "")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (def ^:private ansi-colors (cs/join "\n" ["AnsiColorLogger.ERROR_COLOR=0;31" "AnsiColorLogger.WARNING_COLOR=0;35" "AnsiColorLogger.INFO_COLOR=0;36" "AnsiColorLogger.VERBOSE_COLOR=0;32" "AnsiColorLogger.DEBUG_COLOR=0;34"])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- hackAnsiColors "" [] (let [f (-> (System/getProperty "java.io.tmpdir") (io/file "czlab-antlogansi.colors"))] (if-not (.exists f) (spit f ansi-colors)) (System/setProperty "ant.logger.defaults" (.getCanonicalPath f)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- project<> "New project" ^Project [] (let [_ (hackAnsiColors) lg (doto (AnsiColorLogger.) (.setOutputPrintStream System/out) (.setErrorPrintStream System/err) (.setMessageOutputLevel Project/MSG_INFO))] (doto (Project.) .init (.setName "projx") (.addBuildListener lg)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- execTarget "" [^Target t] (-> (.getProject t) (.executeTarget (.getName t)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro ^:private gpdn "" [pd] `(.getName ~(with-meta pd {:tag 'PropertyDescriptor}))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- getBeanInfo "" [cz] (persistent! (reduce #(assoc! %1 (keyword (gpdn %2)) %2) (transient {}) (-> (Introspector/getBeanInfo cz) .getPropertyDescriptors)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;create a default project. (defonce ^:private dftprj (atom (project<>))) (defonce ^:private beansCooked (atom false)) (def ^:private okay-tasks #{;;"ant" ;;"antcall" ;;"antstructure" ;;"antversion" "apply" "attrib" ;;"attributenamespacedef" ;;"augment" ;;"available" "basename" ;;"bindtargets" ;;"blgenclient" ;;"buildnumber" ;;"bunzip2" ;;"bzip2" "cab" ;;"cccheckin" ;;"cccheckout" ;;"cclock" ;;"ccmcheckin" ;;"ccmcheckintask" ;;"ccmcheckout" ;;"ccmcreatetask" ;;"ccmkattr" ;;"ccmkbl" ;;"ccmkdir" ;;"ccmkelem" ;;"ccmklabel" ;;"ccmklbtype" ;;"ccmreconfigure" ;;"ccrmtype" ;;"ccuncheckout" ;;"ccunlock" ;;"ccupdate" "checksum" "chgrp" "chmod" "chown" ;;"classloader" ;;"commandlauncher" ;;"componentdef" "concat" ;;"condition" "copy" ;;"copydir" ;;"copyfile" ;;"copypath" ;;"cvs" ;;"cvschangelog" ;;"cvspass" ;;"cvstagdiff" ;;"cvsversion" ;;"defaultexcludes" "delete" ;;"deltree" ;;"depend" ;;"dependset" ;;"diagnostics" ;;"dirname" "ear" "echo" "echoproperties" ;;"echoxml" ;;"ejbjar" "exec" ;;"execon" ;;"fail" ;;"filter" "fixcrlf" "genkey" "get" "gunzip" "gzip" "hostinfo" ;;"import" ;;"include" "input" ;;"iplanet-ejbc" "jar" ;;"jarlib-available" ;;"jarlib-display" ;;"jarlib-manifest" ;;"jarlib-resolve" "java" "javac" "javacc" "javadoc" ;;"javadoc2" "javah" "jjdoc" "jjtree" ;;"jlink" ;;"jspc" "junit" "junitreport" "length" ;;"loadfile" ;;"loadproperties" ;;"loadresource" ;;"local" ;;"macrodef" "mail" ;;"makeurl" "manifest" ;;"manifestclasspath" ;;"mimemail" "mkdir" "move" ;;"native2ascii" ;;"nice" ;;"parallel" "patch" ;;"pathconvert" ;;"presetdef" ;;"projecthelper" "property" ;;"propertyfile" ;;"propertyhelper" ;;"pvcs" ;;"record" ;;"rename" ;;"renameext" "replace" "replaceregexp" ;;"resourcecount" ;;"retry" ;;"rmic" "rpm" ;;"schemavalidate" ;;"script" ;;"scriptdef" ;;"sequential" ;;"serverdeploy" "setpermissions" "setproxy" "signjar" "sleep" ;;"soscheckin" ;;"soscheckout" ;;"sosget" ;;"soslabel" "sql" "style" ;;"subant" "symlink" "sync" "tar" ;;"taskdef" "tempfile" "touch" ;;"translate" "truncate" "tstamp" ;;"typedef" "unjar" "untar" "unwar" "unzip" ;;"uptodate" "verifyjar" ;;"vssadd" ;;"vsscheckin" ;;"vsscheckout" ;;"vsscp" ;;"vsscreate" ;;"vssget" ;;"vsshistory" ;;"vsslabel" ;;"waitfor" "war" "whichresource" ;;"wljspc" ;;"xmlproperty" ;;"xmlvalidate" "xslt" "zip"}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;cache ant task names as symbols, and cache bean-info of class (if-not @beansCooked (let [kees (atom (sorted-set)) beans (atom {}) syms (atom [])] (doseq [[k v] (. ^Project @dftprj getTaskDefinitions) :when (and (contains? okay-tasks k) (.isAssignableFrom Task v))] (swap! kees conj k) (swap! syms conj k k) (swap! beans assoc v (getBeanInfo v))) (println "syms = " @kees) (def ^:private _tasks (atom (partition 2 (map #(symbol %) @syms)))) (def ^:private _props (atom @beans)) (reset! beansCooked true))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- maybeProps "Add bean info for non-task classes" [cz] (let [b (getBeanInfo cz)] (swap! _props assoc cz b) b)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (def ^:private setterArgTypes ;;add more types when needed [String java.io.File Boolean/TYPE Boolean Integer/TYPE Integer Long/TYPE Long org.apache.tools.ant.types.Path]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- method? "Find this setter method via best match, if found, returns a tuple [method classofarg]" [^Class cz ^String m] (let [arr (make-array java.lang.Class 1)] (some (fn [^Class z] (try (aset #^"[Ljava.lang.Class;" arr 0 z) [(.getMethod cz m arr) z] (catch Throwable _))) setterArgTypes))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmulti ^:private koerce "Converter" (fn [_ a b] [a (class b)])) (defmethod koerce [Integer/TYPE String] [_ _ ^String v] (Integer/parseInt v (int 10))) (defmethod koerce [Integer String] [_ _ ^String v] (Integer/parseInt v (int 10))) (defmethod koerce [Integer/TYPE Long] [_ _ ^Long v] (.intValue v)) (defmethod koerce [Integer Long] [_ _ ^Long v] (.intValue v)) (defmethod koerce [Integer/TYPE Integer] [_ _ ^Integer v] v) (defmethod koerce [Integer Integer] [_ _ ^Integer v] v) (defmethod koerce [Long/TYPE String] [_ _ ^String v] (Long/parseLong v (int 10))) (defmethod koerce [Long String] [_ _ ^String v] (Long/parseLong v (int 10))) (defmethod koerce [Long/TYPE Long] [_ _ ^Long v] v) (defmethod koerce [Long Long] [_ _ ^Long v] v) (defmethod koerce [Path File] [^Project pj _ ^File v] (Path. pj (.getCanonicalPath v))) (defmethod koerce [Path String] [^Project pj _ ^String v] (Path. pj v)) (defmethod koerce [File String] [_ _ ^String v] (io/file v)) (defmethod koerce [File File] [_ _ v] v) (defmethod koerce :default [_ pz _] (Exception. (str "expected class " pz))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- coerce "Best attempt to convert a given value" [pj pz value] (cond (or (= Boolean/TYPE pz) (= Boolean pz)) (= "true" (str value)) (= String pz) (str value) :else (koerce pj pz value))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- setProp! "" [wm pojo k arr] (try (. ^Method wm invoke pojo arr) (catch Throwable _ (println (str "failed to set " k " for " (class pojo))) (throw _)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- setOptions "Use reflection to invoke setters -> to set options on the pojo" ([pj pojo options] (setOptions pj pojo options nil)) ([^Project pj pojo options skips] (let [arr (object-array 1) cz (class pojo) ps (or (cc/get @_props cz) (maybeProps cz))] (if (instance? ProjectComponent pojo) (. ^ProjectComponent pojo setProject pj)) (doseq [[k v] options :when (not (contains? skips k))] (if-some [^PropertyDescriptor pd (cc/get ps k)] (-> ;;some cases the beaninfo is erroneous ;;so fall back to use *best-try* (let [mn (str "set" (capstr k)) wm (.getWriteMethod pd) pt (.getPropertyType pd)] (if (some? wm) (do (->> (coerce pj pt v) (aset arr 0)) wm) (let [[wm pt] (method? cz mn)] (if (nil? wm) (trap! (str mn " not in " cz))) (->> (coerce pj pt v) (aset arr 0)) wm))) (setProp! pojo k arr)) (trap! (str "prop['" k "'] not in " cz))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- projcomp<> "Configure a project component" {:tag ProjectComponent} ([^Project pj ^ProjectComponent pc options nested] (if (fn? options) (options pj pc) (setOptions pj pc options)) (if (fn? nested) (nested pj pc) (maybeCfgNested pj pc nested)) pc) ([pj pc options] (projcomp<> pj pc options nil)) ([pj pc] (projcomp<> pj pc nil nil))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro ^:private antFileSet "" [options] `(merge {:errorOnMissingDir false} ~options)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- antChainedMapper "Handles glob only" ^ProjectComponent [nested pj cm] (doseq [n nested] (case (:type n) :glob (->> (doto (GlobPatternMapper.) (.setFrom (:from n)) (.setTo (:to n))) (. ^ChainedMapper cm add )) (trap! (str "unknown mapper: " n)))) cm) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- antFormatter "" ^ProjectComponent [options pj tk] (if-some [[k v] (find options :type)] (. ^FormatterElement tk setType (doto (FormatterElement$TypeAttribute.) (.setValue (str v))))) (setOptions pj tk options #{:type}) tk) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- setClassPath "Build a nested Path structure for classpath" [^Project pj ^Path root paths] (doseq [p paths] (case (first p) :location (doto (.createPath root) (.setLocation (io/file (str (last p))))) :refid (trap! "path:refid not supported") ;;(doto (.createPath root) (.setRefid (last p))) :fileset (->> (projcomp<> pj (FileSet.) (antFileSet (second p)) (nth?? p 3)) (.addFileset root)) (trap! (str "unknown path: " p)))) root) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- maybeCfgNested "" [pj tk nested] (doseq [p nested] (case (first p) :compilerarg (if-some [n (:line (last p))] (-> (.createCompilerArg tk) (.setLine ^String n))) :file (let [n (FileList$FileName.)] (. n setName (str (:name (second p)))) (. tk addConfiguredFile n)) :classpath (setClassPath pj (.createClasspath tk) (last p)) :sysprops (doseq [[k v] (last p)] (->> (doto (Environment$Variable.) (.setKey (name k)) (.setValue (str v))) (.addSysproperty tk))) :formatter (->> (projcomp<> pj (FormatterElement.) (partial antFormatter (last p))) (.addFormatter tk)) :include (let [v (cs/trim (str (last p)))] (if-not (empty? v) (-> (.createInclude tk) (.setName v)))) :exclude (let [v (cs/trim (str (last p)))] (if-not (empty? v) (-> (.createExclude tk) (.setName v)))) :filelist (->> (projcomp<> pj (FileList.) (second p) (nth?? p 3)) (.addFilelist tk)) :patternset (projcomp<> pj (.createPatternSet tk) (second p) (nth?? p 3)) :dirset (->> (projcomp<> pj (DirSet.) (antFileSet (second p)) (nth?? p 3)) (.addDirset tk )) :fileset (let [s (projcomp<> pj (FileSet.) (antFileSet (second p)) (nth?? p 3))] (if (instance? BatchTest tk) (.addFileSet tk s) (.addFileset tk s))) :argvalues (doseq [v (last p)] (-> (.createArg tk) (.setValue (str v)))) :argpaths (doseq [v (last p)] (-> (.createArg tk) (.setPath (Path. pj (str v))))) :arglines (doseq [v (last p)] (-> (.createArg tk) (.setLine (str v)))) :replacefilter (doto (.createReplacefilter tk) (.setToken (:token (nth p 1))) (.setValue (:value (nth p 1)))) :replacevalue (-> (.createReplaceValue tk) (.addText (:text (last p)))) :replacetoken (-> (.createReplaceToken tk) (.addText (:text (last p)))) :test (. tk addTest (projcomp<> pj (JUnitTest.) (second p) (nth?? p 3))) :chainedmapper (. tk add (projcomp<> pj (ChainedMapper.) (second p) (partial antChainedMapper (nth?? p 3)))) :targetfile (.createTargetfile tk) :srcfile (.createSrcfile tk) :batchtest (projcomp<> pj (.createBatchTest tk) (second p) (nth?? p 3)) :tarfileset (projcomp<> pj (.createTarFileSet tk) (second p) (nth?? p 3)) :zipfileset (projcomp<> pj (let [z (ZipFileSet.)] (. ^Zip tk addZipfileset z) z) (second p) (nth?? p 3)) (trap! (str "unknown nested: " p))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- xxx-preopts "" [tk options] [options #{}]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- delete-pre-opts "" [tk options] [(merge {:includeEmptyDirs true} options) #{}]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- junit-preopts "" [^JUnitTask tk options] (if-some [v (:printsummary options)] (. tk setPrintsummary (doto (JUnitTask$SummaryAttribute.) (.setValue (str v))))) (if-some [v (:forkMode options)] (. tk setForkMode (doto (JUnitTask$ForkMode.) (.setValue (str v))))) [options #{:printsummary :forkMode}]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- jdoc-preopts "" [tk options] (if-some [v (:access options)] (. ^Javadoc tk setAccess (doto (Javadoc$AccessType.) (.setValue (str v))))) [options #{:access}]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- tar-preopts "" [tk options] (if-some [v (:compression options)] (. ^Tar tk setCompression (doto (Tar$TarCompressionMethod.) (.setValue (str v))))) [options #{:compression}]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- init-task "Reify and configure actual ant tasks" ^Task [^Project pj ^Target target {:keys [pre-options tname task options nested]}] (let [preopts (or pre-options xxx-preopts)] (->> (doto ^Task task (.setProject pj) (.setOwningTarget target)) (.addTask target)) (->> (preopts task options) (cc/apply setOptions pj task)) (maybeCfgNested pj task nested) task)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- projAntTasks "Bind all the tasks to a target and a project" ^Target [^String target tasks] (let [pj @dftprj tg (Target.)] (. tg setName (or target "")) (. ^Project pj addOrReplaceTarget tg) ;;(println (str "number of tasks ==== " (count tasks))) (doseq [t tasks] (init-task pj tg t)) tg)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- projAntTasks* "Bind all the tasks to a target and a project" ^Target [target & tasks] (projAntTasks target tasks)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn runTarget "Run ant tasks" [target tasks] (-> (projAntTasks target tasks) execTarget)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn runTarget* "Run ant tasks" [target & tasks] (runTarget target tasks)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn runTasks "Run ant tasks" [tasks] (runTarget "" tasks)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn runTasks* "Run ant tasks" [& tasks] (runTarget "" tasks)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn- ctask<> "" ^Task [^Project p ^String tt ^String tm] (doto (.createTask p tt) (.setTaskName tm))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro ^:private ant-task "Generate wrapper function for an ant task" ([pj sym docstr func preopt] (let [s (str func) tm (cs/lower-case (.substring s (inc (.lastIndexOf s "."))))] `(defn ~sym ~docstr ;;{:no-doc true} ([~'options] (~sym ~'options nil)) ([~'options ~'nestedElements] (let [tk# (ctask<> ~pj ~s ~tm) o# (or ~'options {}) n# (or ~'nestedElements []) r# {:pre-options ~preopt :tname ~tm :task tk# :options o# :nested n#}] (if (nil? (:pre-options r#)) (->> (case ~s ;;certain classes need special handling of properties ;;due to type mismatch or property name ;;inconsistencies "delete" delete-pre-opts "junit" junit-preopts "javadoc" jdoc-preopts "tar" tar-preopts nil) (assoc r# :pre-options)) r#)))))) ([pj sym docstr func] `(ant-task ~pj ~sym ~docstr ~func nil))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro ^:private declAntTasks "Introspect the default project and cache all registered ant-tasks" [pj] `(do ~@(map (fn [[a b]] `(ant-task ~pj ~a "" ~b)) (deref _tasks)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (declAntTasks @dftprj) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn cleanDir "Clean an existing dir or create it" ([d] (cleanDir d nil)) ([d {:keys [quiet] :or {quiet true}}] (let [dir (io/file d)] (if (.exists dir) (runTasks* (delete {:removeNotFollowedSymlinks true :quiet quiet} [[:fileset {:followSymlinks false :dir dir} [[:include "**/*"]]]])) (.mkdirs dir))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn deleteDir "Remove a directory" ([d] (deleteDir d nil)) ([d {:keys [quiet] :or {quiet true}}] (let [dir (io/file d)] (when (.exists dir) (runTasks* (delete {:removeNotFollowedSymlinks true :quiet quiet} [[:fileset {:followSymlinks false :dir dir}]])))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn copyFile "Copy a file to the target folder" [file toDir] (.mkdirs (io/file toDir)) (runTasks* (copy {:file file :todir toDir}))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn moveFile "Move a file to the target folder" [file toDir] (.mkdirs (io/file toDir)) (runTasks* (move {:file file :todir toDir}))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn deleteLink "Delete a file system symbolic link" [link] (runTasks* (symlink {:action "delete" :link link}))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defn createLink "Create a file system symbolic link" ([link target] (createLink link target true)) ([link target overwrite?] (runTasks* (symlink {:overwrite overwrite? :action "single" :link link :resource target})))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
[ { "context": "-------------------------------\n;;\n;;\n;; Author: PLIQUE Guillaume (Yomguithereal)\n;; Version: 0.1\n;;\n(ns clj-fuzz", "end": 206, "score": 0.9998326897621155, "start": 190, "tag": "NAME", "value": "PLIQUE Guillaume" }, { "context": "------------\n;;\n;;\n;; Author: PLIQUE Guillaume (Yomguithereal)\n;; Version: 0.1\n;;\n(ns clj-fuzzy.metaphone-tes", "end": 221, "score": 0.9984983801841736, "start": 208, "tag": "USERNAME", "value": "Yomguithereal" } ]
test/clj_fuzzy/metaphone_test.clj
sooheon/clj-fuzzy
222
;; ------------------------------------------------------------------- ;; clj-fuzzy Metaphone Tests ;; ------------------------------------------------------------------- ;; ;; ;; Author: PLIQUE Guillaume (Yomguithereal) ;; Version: 0.1 ;; (ns clj-fuzzy.metaphone-test (:require [clojure.test :refer :all] [clj-fuzzy.metaphone :refer :all])) (deftest process-test (is (= "TSKRMNXN" (process "discrimination"))) (is (= "HL" (process "hello"))) (is (= "TRT" (process "droid"))) (is (= "HPKRT" (process "hypocrite"))) (is (= "WL" (process "well"))) (is (= "AM" (process "am"))) (is (= "S" (process "say"))) (is (= "FSNT" (process "pheasant"))) (is (= "KT" (process "god"))))
57824
;; ------------------------------------------------------------------- ;; clj-fuzzy Metaphone Tests ;; ------------------------------------------------------------------- ;; ;; ;; Author: <NAME> (Yomguithereal) ;; Version: 0.1 ;; (ns clj-fuzzy.metaphone-test (:require [clojure.test :refer :all] [clj-fuzzy.metaphone :refer :all])) (deftest process-test (is (= "TSKRMNXN" (process "discrimination"))) (is (= "HL" (process "hello"))) (is (= "TRT" (process "droid"))) (is (= "HPKRT" (process "hypocrite"))) (is (= "WL" (process "well"))) (is (= "AM" (process "am"))) (is (= "S" (process "say"))) (is (= "FSNT" (process "pheasant"))) (is (= "KT" (process "god"))))
true
;; ------------------------------------------------------------------- ;; clj-fuzzy Metaphone Tests ;; ------------------------------------------------------------------- ;; ;; ;; Author: PI:NAME:<NAME>END_PI (Yomguithereal) ;; Version: 0.1 ;; (ns clj-fuzzy.metaphone-test (:require [clojure.test :refer :all] [clj-fuzzy.metaphone :refer :all])) (deftest process-test (is (= "TSKRMNXN" (process "discrimination"))) (is (= "HL" (process "hello"))) (is (= "TRT" (process "droid"))) (is (= "HPKRT" (process "hypocrite"))) (is (= "WL" (process "well"))) (is (= "AM" (process "am"))) (is (= "S" (process "say"))) (is (= "FSNT" (process "pheasant"))) (is (= "KT" (process "god"))))
[ { "context": " :name \"Test tournament\"\n ", "end": 1361, "score": 0.6210941076278687, "start": 1357, "tag": "NAME", "value": "Test" }, { "context": "anctionid sanction-id\n :name \"Test tournament\"\n :organizer \"Test orga", "end": 1677, "score": 0.6210891008377075, "start": 1673, "tag": "NAME", "value": "Test" }, { "context": " 3})\n (add-apikey #uuid \"68126748-01fd-4d2b-a35d-d0f062403058\"))\n 400)))\n (testing \"PUT /ap", "end": 2499, "score": 0.9938696622848511, "start": 2463, "tag": "KEY", "value": "68126748-01fd-4d2b-a35d-d0f062403058" } ]
mtg-pairings-server/test/clj/mtg_pairings_server/api/api_test.clj
arttuka/mtg-pairings
2
(ns mtg-pairings-server.api.api-test (:require [clojure.test :refer :all] [clojure.edn :as edn] [config.core :refer [env]] [clj-time.core :as time] [korma.core :as sql] [ring.mock.request :as mock] [mtg-pairings-server.sql-db :as db] [mtg-pairings-server.test-util :refer [db-fixture erase-fixture users]] [mtg-pairings-server.handler :refer [app]]) (:import (java.io BufferedInputStream))) (use-fixtures :once db-fixture) (use-fixtures :each erase-fixture) (defn add-apikey ([request] (add-apikey request (get-in users [:user1 :uuid]))) ([request key] (mock/query-string request {:key key}))) (defn ->string [body] (condp instance? body String body BufferedInputStream (slurp body))) (defn make-request ([request] (make-request request 200)) ([request status] (let [response (app request)] (is (= status (:status response)) (str "Unexpected status code, response body: " (->string (:body response)))) response))) (def sanction-id "1-123456") (deftest api-test (testing "POST /api/tournament" (testing "inserts tournament" (make-request (-> (mock/request :post "/api/tournament") (mock/json-body {:sanctionid sanction-id :name "Test tournament" :organizer "Test organizer" :day "2019-03-10" :rounds 3}) (add-apikey))) (is (= [{:sanctionid sanction-id :name "Test tournament" :organizer "Test organizer" :day (time/local-date 2019 3 10) :rounds 3 :owner 1}] (sql/select db/tournament (sql/fields :sanctionid :name :organizer :day :rounds :owner))))) (testing "doesn't allow tournament with invalid apikey" (make-request (-> (mock/request :post "/api/tournament") (mock/json-body {:sanctionid "2-123456" :name "Test tournament" :organizer "Test organizer" :day "2019-03-10" :rounds 3}) (add-apikey #uuid "68126748-01fd-4d2b-a35d-d0f062403058")) 400))) (testing "PUT /api/tournament/:sanctionid" (testing "updates tournament name" (make-request (-> (mock/request :put (str "/api/tournament/" sanction-id)) (mock/json-body {:name "Updated test tournament"}) (add-apikey)) 204) (is (= [{:sanctionid sanction-id :name "Updated test tournament" :organizer "Test organizer" :day (time/local-date 2019 3 10) :rounds 3 :owner 1}] (sql/select db/tournament (sql/fields :sanctionid :name :organizer :day :rounds :owner)))))) (testing "PUT /api/tournament/:sanctionid/teams" (testing "adds teams and players" (make-request (-> (mock/request :put (str "/api/tournament/" sanction-id "/teams")) (mock/json-body {:teams [{:name "Team 1" :players [{:dci "100000" :name "Player 1"}]} {:name "Team 2" :players [{:dci "200000" :name "Player 2"}]} {:name "Team 3" :players [{:dci "300000" :name "Player 3"}]} {:name "Team 4" :players [{:dci "400000" :name "Player 4"}]}]}) (add-apikey)) 204) (is (= [{:dci "4050100000", :name "Player 1"} {:dci "1010200000", :name "Player 2"} {:dci "5060300000", :name "Player 3"} {:dci "7010400000", :name "Player 4"}] (sql/select db/player (sql/order :name)))) (let [teams (sql/select db/team (sql/with db/player) (sql/order :team.name))] (is (= ["Team 1" "Team 2" "Team 3" "Team 4"] (map :name teams))) (is (= [{:dci "4050100000", :name "Player 1"} {:dci "1010200000", :name "Player 2"} {:dci "5060300000", :name "Player 3"} {:dci "7010400000", :name "Player 4"}] (mapcat :player teams)))))) (testing "PUT /api/tournament/:sanctionid/pairings" (testing "adds pairings" (make-request (-> (mock/request :put (str "/api/tournament/" sanction-id "/round-1/pairings")) (mock/json-body {:pairings [{:team1 ["4050100000"] :team2 ["1010200000"] :table_number 1} {:team1 ["5060300000"] :team2 ["7010400000"] :table_number 2}] :playoff false}) (add-apikey)) 204) (is (= [{:team1 "Team 1" :team2 "Team 2" :table_number 1 :team1_points 0 :team2_points 0} {:team1 "Team 3" :team2 "Team 4" :table_number 2 :team1_points 0 :team2_points 0}] (sql/select db/pairing (sql/fields :table_number :team1_points :team2_points) (sql/with db/team1 (sql/fields [:name :team1])) (sql/with db/team2 (sql/fields [:name :team2])) (sql/order :table_number))))) (testing "can replace pairings" (make-request (-> (mock/request :put (str "/api/tournament/" sanction-id "/round-1/pairings")) (mock/json-body {:pairings [{:team1 ["4050100000"] :team2 ["5060300000"] :table_number 1} {:team1 ["1010200000"] :team2 ["7010400000"] :table_number 2}] :playoff false}) (add-apikey)) 204) (is (= [{:team1 "Team 1" :team2 "Team 3" :table_number 1 :team1_points 0 :team2_points 0} {:team1 "Team 2" :team2 "Team 4" :table_number 2 :team1_points 0 :team2_points 0}] (sql/select db/pairing (sql/fields :table_number :team1_points :team2_points) (sql/with db/team1 (sql/fields [:name :team1])) (sql/with db/team2 (sql/fields [:name :team2])) (sql/order :table_number)))))) (testing "PUT /api/tournament/:sanctionid/results" (testing "adds partial results" (make-request (-> (mock/request :put (str "/api/tournament/" sanction-id "/round-1/results")) (mock/json-body {:results [{:team1 ["4050100000"] :team2 ["5060300000"] :table_number 1 :team1_wins 2 :team2_wins 0 :draws 0}]}) (add-apikey)) 204) (is (= [{:table_number 1 :team1_wins 2 :team2_wins 0 :draws 0} {:table_number 2 :team1_wins nil :team2_wins nil :draws nil}] (sql/select db/pairing (sql/fields :table_number) (sql/with db/result (sql/fields :team1_wins :team2_wins :draws)))))) (testing "can replace results" (make-request (-> (mock/request :put (str "/api/tournament/" sanction-id "/round-1/results")) (mock/json-body {:results [{:team1 ["4050100000"] :team2 ["5060300000"] :table_number 1 :team1_wins 2 :team2_wins 1 :draws 0} {:team1 ["1010200000"] :team2 ["7010400000"] :table_number 2 :team1_wins 2 :team2_wins 0 :draws 0}]}) (add-apikey)) 204) (is (= [{:table_number 1 :team1_wins 2 :team2_wins 1 :draws 0} {:table_number 2 :team1_wins 2 :team2_wins 0 :draws 0}] (sql/select db/pairing (sql/fields :table_number) (sql/with db/result (sql/fields :team1_wins :team2_wins :draws)))))) (testing "calculates standings" (is (= [{:rank 1 :team_name "Team 2" :points 3 :omw 33/100 :pgw 1 :ogw 33/100} {:rank 2 :team_name "Team 1" :points 3 :omw 33/100 :pgw 2/3 :ogw 1/3} {:rank 3 :team_name "Team 3" :points 0 :omw 1 :pgw 1/3 :ogw 2/3} {:rank 4 :team_name "Team 4" :points 0 :omw 1 :pgw 33/100 :ogw 1}] (->> (sql/select db/standings) first :standings edn/read-string (map #(select-keys % [:rank :team_name :points :omw :pgw :ogw]))))))) (testing "another round" (testing "pairings" (make-request (-> (mock/request :put (str "/api/tournament/" sanction-id "/round-2/pairings")) (mock/json-body {:pairings [{:team1 ["4050100000"] :team2 ["1010200000"] :table_number 1} {:team1 ["5060300000"] :team2 ["7010400000"] :table_number 2}] :playoff false}) (add-apikey)) 204) (is (= [{:team1 "Team 1" :team2 "Team 2" :table_number 1 :team1_points 3 :team2_points 3} {:team1 "Team 3" :team2 "Team 4" :table_number 2 :team1_points 0 :team2_points 0}] (sql/select db/pairing (sql/fields :table_number :team1_points :team2_points) (sql/with db/round (sql/fields) (sql/where {:num 2})) (sql/with db/team1 (sql/fields [:name :team1])) (sql/with db/team2 (sql/fields [:name :team2])) (sql/order :table_number))))) (testing "results" (make-request (-> (mock/request :put (str "/api/tournament/" sanction-id "/round-2/results")) (mock/json-body {:results [{:team1 ["4050100000"] :team2 ["1010200000"] :table_number 1 :team1_wins 2 :team2_wins 1 :draws 0} {:team1 ["5060300000"] :team2 ["7010400000"] :table_number 2 :team1_wins 2 :team2_wins 1 :draws 0}]}) (add-apikey)) 204)) (testing "standings" (is (= [{:rank 1 :team_name "Team 1" :points 6 :omw 1/2 :pgw 2/3 :ogw 11/20} {:rank 2 :team_name "Team 2" :points 3 :omw 133/200 :pgw 3/5 :ogw 299/600} {:rank 3 :team_name "Team 3" :points 3 :omw 133/200 :pgw 1/2 :ogw 299/600} {:rank 4 :team_name "Team 4" :points 0 :omw 1/2 :pgw 33/100 :ogw 11/20}] (->> (sql/select db/standings (sql/where {:round 2})) first :standings edn/read-string (map #(select-keys % [:rank :team_name :points :omw :pgw :ogw]))))))))
49732
(ns mtg-pairings-server.api.api-test (:require [clojure.test :refer :all] [clojure.edn :as edn] [config.core :refer [env]] [clj-time.core :as time] [korma.core :as sql] [ring.mock.request :as mock] [mtg-pairings-server.sql-db :as db] [mtg-pairings-server.test-util :refer [db-fixture erase-fixture users]] [mtg-pairings-server.handler :refer [app]]) (:import (java.io BufferedInputStream))) (use-fixtures :once db-fixture) (use-fixtures :each erase-fixture) (defn add-apikey ([request] (add-apikey request (get-in users [:user1 :uuid]))) ([request key] (mock/query-string request {:key key}))) (defn ->string [body] (condp instance? body String body BufferedInputStream (slurp body))) (defn make-request ([request] (make-request request 200)) ([request status] (let [response (app request)] (is (= status (:status response)) (str "Unexpected status code, response body: " (->string (:body response)))) response))) (def sanction-id "1-123456") (deftest api-test (testing "POST /api/tournament" (testing "inserts tournament" (make-request (-> (mock/request :post "/api/tournament") (mock/json-body {:sanctionid sanction-id :name "<NAME> tournament" :organizer "Test organizer" :day "2019-03-10" :rounds 3}) (add-apikey))) (is (= [{:sanctionid sanction-id :name "<NAME> tournament" :organizer "Test organizer" :day (time/local-date 2019 3 10) :rounds 3 :owner 1}] (sql/select db/tournament (sql/fields :sanctionid :name :organizer :day :rounds :owner))))) (testing "doesn't allow tournament with invalid apikey" (make-request (-> (mock/request :post "/api/tournament") (mock/json-body {:sanctionid "2-123456" :name "Test tournament" :organizer "Test organizer" :day "2019-03-10" :rounds 3}) (add-apikey #uuid "<KEY>")) 400))) (testing "PUT /api/tournament/:sanctionid" (testing "updates tournament name" (make-request (-> (mock/request :put (str "/api/tournament/" sanction-id)) (mock/json-body {:name "Updated test tournament"}) (add-apikey)) 204) (is (= [{:sanctionid sanction-id :name "Updated test tournament" :organizer "Test organizer" :day (time/local-date 2019 3 10) :rounds 3 :owner 1}] (sql/select db/tournament (sql/fields :sanctionid :name :organizer :day :rounds :owner)))))) (testing "PUT /api/tournament/:sanctionid/teams" (testing "adds teams and players" (make-request (-> (mock/request :put (str "/api/tournament/" sanction-id "/teams")) (mock/json-body {:teams [{:name "Team 1" :players [{:dci "100000" :name "Player 1"}]} {:name "Team 2" :players [{:dci "200000" :name "Player 2"}]} {:name "Team 3" :players [{:dci "300000" :name "Player 3"}]} {:name "Team 4" :players [{:dci "400000" :name "Player 4"}]}]}) (add-apikey)) 204) (is (= [{:dci "4050100000", :name "Player 1"} {:dci "1010200000", :name "Player 2"} {:dci "5060300000", :name "Player 3"} {:dci "7010400000", :name "Player 4"}] (sql/select db/player (sql/order :name)))) (let [teams (sql/select db/team (sql/with db/player) (sql/order :team.name))] (is (= ["Team 1" "Team 2" "Team 3" "Team 4"] (map :name teams))) (is (= [{:dci "4050100000", :name "Player 1"} {:dci "1010200000", :name "Player 2"} {:dci "5060300000", :name "Player 3"} {:dci "7010400000", :name "Player 4"}] (mapcat :player teams)))))) (testing "PUT /api/tournament/:sanctionid/pairings" (testing "adds pairings" (make-request (-> (mock/request :put (str "/api/tournament/" sanction-id "/round-1/pairings")) (mock/json-body {:pairings [{:team1 ["4050100000"] :team2 ["1010200000"] :table_number 1} {:team1 ["5060300000"] :team2 ["7010400000"] :table_number 2}] :playoff false}) (add-apikey)) 204) (is (= [{:team1 "Team 1" :team2 "Team 2" :table_number 1 :team1_points 0 :team2_points 0} {:team1 "Team 3" :team2 "Team 4" :table_number 2 :team1_points 0 :team2_points 0}] (sql/select db/pairing (sql/fields :table_number :team1_points :team2_points) (sql/with db/team1 (sql/fields [:name :team1])) (sql/with db/team2 (sql/fields [:name :team2])) (sql/order :table_number))))) (testing "can replace pairings" (make-request (-> (mock/request :put (str "/api/tournament/" sanction-id "/round-1/pairings")) (mock/json-body {:pairings [{:team1 ["4050100000"] :team2 ["5060300000"] :table_number 1} {:team1 ["1010200000"] :team2 ["7010400000"] :table_number 2}] :playoff false}) (add-apikey)) 204) (is (= [{:team1 "Team 1" :team2 "Team 3" :table_number 1 :team1_points 0 :team2_points 0} {:team1 "Team 2" :team2 "Team 4" :table_number 2 :team1_points 0 :team2_points 0}] (sql/select db/pairing (sql/fields :table_number :team1_points :team2_points) (sql/with db/team1 (sql/fields [:name :team1])) (sql/with db/team2 (sql/fields [:name :team2])) (sql/order :table_number)))))) (testing "PUT /api/tournament/:sanctionid/results" (testing "adds partial results" (make-request (-> (mock/request :put (str "/api/tournament/" sanction-id "/round-1/results")) (mock/json-body {:results [{:team1 ["4050100000"] :team2 ["5060300000"] :table_number 1 :team1_wins 2 :team2_wins 0 :draws 0}]}) (add-apikey)) 204) (is (= [{:table_number 1 :team1_wins 2 :team2_wins 0 :draws 0} {:table_number 2 :team1_wins nil :team2_wins nil :draws nil}] (sql/select db/pairing (sql/fields :table_number) (sql/with db/result (sql/fields :team1_wins :team2_wins :draws)))))) (testing "can replace results" (make-request (-> (mock/request :put (str "/api/tournament/" sanction-id "/round-1/results")) (mock/json-body {:results [{:team1 ["4050100000"] :team2 ["5060300000"] :table_number 1 :team1_wins 2 :team2_wins 1 :draws 0} {:team1 ["1010200000"] :team2 ["7010400000"] :table_number 2 :team1_wins 2 :team2_wins 0 :draws 0}]}) (add-apikey)) 204) (is (= [{:table_number 1 :team1_wins 2 :team2_wins 1 :draws 0} {:table_number 2 :team1_wins 2 :team2_wins 0 :draws 0}] (sql/select db/pairing (sql/fields :table_number) (sql/with db/result (sql/fields :team1_wins :team2_wins :draws)))))) (testing "calculates standings" (is (= [{:rank 1 :team_name "Team 2" :points 3 :omw 33/100 :pgw 1 :ogw 33/100} {:rank 2 :team_name "Team 1" :points 3 :omw 33/100 :pgw 2/3 :ogw 1/3} {:rank 3 :team_name "Team 3" :points 0 :omw 1 :pgw 1/3 :ogw 2/3} {:rank 4 :team_name "Team 4" :points 0 :omw 1 :pgw 33/100 :ogw 1}] (->> (sql/select db/standings) first :standings edn/read-string (map #(select-keys % [:rank :team_name :points :omw :pgw :ogw]))))))) (testing "another round" (testing "pairings" (make-request (-> (mock/request :put (str "/api/tournament/" sanction-id "/round-2/pairings")) (mock/json-body {:pairings [{:team1 ["4050100000"] :team2 ["1010200000"] :table_number 1} {:team1 ["5060300000"] :team2 ["7010400000"] :table_number 2}] :playoff false}) (add-apikey)) 204) (is (= [{:team1 "Team 1" :team2 "Team 2" :table_number 1 :team1_points 3 :team2_points 3} {:team1 "Team 3" :team2 "Team 4" :table_number 2 :team1_points 0 :team2_points 0}] (sql/select db/pairing (sql/fields :table_number :team1_points :team2_points) (sql/with db/round (sql/fields) (sql/where {:num 2})) (sql/with db/team1 (sql/fields [:name :team1])) (sql/with db/team2 (sql/fields [:name :team2])) (sql/order :table_number))))) (testing "results" (make-request (-> (mock/request :put (str "/api/tournament/" sanction-id "/round-2/results")) (mock/json-body {:results [{:team1 ["4050100000"] :team2 ["1010200000"] :table_number 1 :team1_wins 2 :team2_wins 1 :draws 0} {:team1 ["5060300000"] :team2 ["7010400000"] :table_number 2 :team1_wins 2 :team2_wins 1 :draws 0}]}) (add-apikey)) 204)) (testing "standings" (is (= [{:rank 1 :team_name "Team 1" :points 6 :omw 1/2 :pgw 2/3 :ogw 11/20} {:rank 2 :team_name "Team 2" :points 3 :omw 133/200 :pgw 3/5 :ogw 299/600} {:rank 3 :team_name "Team 3" :points 3 :omw 133/200 :pgw 1/2 :ogw 299/600} {:rank 4 :team_name "Team 4" :points 0 :omw 1/2 :pgw 33/100 :ogw 11/20}] (->> (sql/select db/standings (sql/where {:round 2})) first :standings edn/read-string (map #(select-keys % [:rank :team_name :points :omw :pgw :ogw]))))))))
true
(ns mtg-pairings-server.api.api-test (:require [clojure.test :refer :all] [clojure.edn :as edn] [config.core :refer [env]] [clj-time.core :as time] [korma.core :as sql] [ring.mock.request :as mock] [mtg-pairings-server.sql-db :as db] [mtg-pairings-server.test-util :refer [db-fixture erase-fixture users]] [mtg-pairings-server.handler :refer [app]]) (:import (java.io BufferedInputStream))) (use-fixtures :once db-fixture) (use-fixtures :each erase-fixture) (defn add-apikey ([request] (add-apikey request (get-in users [:user1 :uuid]))) ([request key] (mock/query-string request {:key key}))) (defn ->string [body] (condp instance? body String body BufferedInputStream (slurp body))) (defn make-request ([request] (make-request request 200)) ([request status] (let [response (app request)] (is (= status (:status response)) (str "Unexpected status code, response body: " (->string (:body response)))) response))) (def sanction-id "1-123456") (deftest api-test (testing "POST /api/tournament" (testing "inserts tournament" (make-request (-> (mock/request :post "/api/tournament") (mock/json-body {:sanctionid sanction-id :name "PI:NAME:<NAME>END_PI tournament" :organizer "Test organizer" :day "2019-03-10" :rounds 3}) (add-apikey))) (is (= [{:sanctionid sanction-id :name "PI:NAME:<NAME>END_PI tournament" :organizer "Test organizer" :day (time/local-date 2019 3 10) :rounds 3 :owner 1}] (sql/select db/tournament (sql/fields :sanctionid :name :organizer :day :rounds :owner))))) (testing "doesn't allow tournament with invalid apikey" (make-request (-> (mock/request :post "/api/tournament") (mock/json-body {:sanctionid "2-123456" :name "Test tournament" :organizer "Test organizer" :day "2019-03-10" :rounds 3}) (add-apikey #uuid "PI:KEY:<KEY>END_PI")) 400))) (testing "PUT /api/tournament/:sanctionid" (testing "updates tournament name" (make-request (-> (mock/request :put (str "/api/tournament/" sanction-id)) (mock/json-body {:name "Updated test tournament"}) (add-apikey)) 204) (is (= [{:sanctionid sanction-id :name "Updated test tournament" :organizer "Test organizer" :day (time/local-date 2019 3 10) :rounds 3 :owner 1}] (sql/select db/tournament (sql/fields :sanctionid :name :organizer :day :rounds :owner)))))) (testing "PUT /api/tournament/:sanctionid/teams" (testing "adds teams and players" (make-request (-> (mock/request :put (str "/api/tournament/" sanction-id "/teams")) (mock/json-body {:teams [{:name "Team 1" :players [{:dci "100000" :name "Player 1"}]} {:name "Team 2" :players [{:dci "200000" :name "Player 2"}]} {:name "Team 3" :players [{:dci "300000" :name "Player 3"}]} {:name "Team 4" :players [{:dci "400000" :name "Player 4"}]}]}) (add-apikey)) 204) (is (= [{:dci "4050100000", :name "Player 1"} {:dci "1010200000", :name "Player 2"} {:dci "5060300000", :name "Player 3"} {:dci "7010400000", :name "Player 4"}] (sql/select db/player (sql/order :name)))) (let [teams (sql/select db/team (sql/with db/player) (sql/order :team.name))] (is (= ["Team 1" "Team 2" "Team 3" "Team 4"] (map :name teams))) (is (= [{:dci "4050100000", :name "Player 1"} {:dci "1010200000", :name "Player 2"} {:dci "5060300000", :name "Player 3"} {:dci "7010400000", :name "Player 4"}] (mapcat :player teams)))))) (testing "PUT /api/tournament/:sanctionid/pairings" (testing "adds pairings" (make-request (-> (mock/request :put (str "/api/tournament/" sanction-id "/round-1/pairings")) (mock/json-body {:pairings [{:team1 ["4050100000"] :team2 ["1010200000"] :table_number 1} {:team1 ["5060300000"] :team2 ["7010400000"] :table_number 2}] :playoff false}) (add-apikey)) 204) (is (= [{:team1 "Team 1" :team2 "Team 2" :table_number 1 :team1_points 0 :team2_points 0} {:team1 "Team 3" :team2 "Team 4" :table_number 2 :team1_points 0 :team2_points 0}] (sql/select db/pairing (sql/fields :table_number :team1_points :team2_points) (sql/with db/team1 (sql/fields [:name :team1])) (sql/with db/team2 (sql/fields [:name :team2])) (sql/order :table_number))))) (testing "can replace pairings" (make-request (-> (mock/request :put (str "/api/tournament/" sanction-id "/round-1/pairings")) (mock/json-body {:pairings [{:team1 ["4050100000"] :team2 ["5060300000"] :table_number 1} {:team1 ["1010200000"] :team2 ["7010400000"] :table_number 2}] :playoff false}) (add-apikey)) 204) (is (= [{:team1 "Team 1" :team2 "Team 3" :table_number 1 :team1_points 0 :team2_points 0} {:team1 "Team 2" :team2 "Team 4" :table_number 2 :team1_points 0 :team2_points 0}] (sql/select db/pairing (sql/fields :table_number :team1_points :team2_points) (sql/with db/team1 (sql/fields [:name :team1])) (sql/with db/team2 (sql/fields [:name :team2])) (sql/order :table_number)))))) (testing "PUT /api/tournament/:sanctionid/results" (testing "adds partial results" (make-request (-> (mock/request :put (str "/api/tournament/" sanction-id "/round-1/results")) (mock/json-body {:results [{:team1 ["4050100000"] :team2 ["5060300000"] :table_number 1 :team1_wins 2 :team2_wins 0 :draws 0}]}) (add-apikey)) 204) (is (= [{:table_number 1 :team1_wins 2 :team2_wins 0 :draws 0} {:table_number 2 :team1_wins nil :team2_wins nil :draws nil}] (sql/select db/pairing (sql/fields :table_number) (sql/with db/result (sql/fields :team1_wins :team2_wins :draws)))))) (testing "can replace results" (make-request (-> (mock/request :put (str "/api/tournament/" sanction-id "/round-1/results")) (mock/json-body {:results [{:team1 ["4050100000"] :team2 ["5060300000"] :table_number 1 :team1_wins 2 :team2_wins 1 :draws 0} {:team1 ["1010200000"] :team2 ["7010400000"] :table_number 2 :team1_wins 2 :team2_wins 0 :draws 0}]}) (add-apikey)) 204) (is (= [{:table_number 1 :team1_wins 2 :team2_wins 1 :draws 0} {:table_number 2 :team1_wins 2 :team2_wins 0 :draws 0}] (sql/select db/pairing (sql/fields :table_number) (sql/with db/result (sql/fields :team1_wins :team2_wins :draws)))))) (testing "calculates standings" (is (= [{:rank 1 :team_name "Team 2" :points 3 :omw 33/100 :pgw 1 :ogw 33/100} {:rank 2 :team_name "Team 1" :points 3 :omw 33/100 :pgw 2/3 :ogw 1/3} {:rank 3 :team_name "Team 3" :points 0 :omw 1 :pgw 1/3 :ogw 2/3} {:rank 4 :team_name "Team 4" :points 0 :omw 1 :pgw 33/100 :ogw 1}] (->> (sql/select db/standings) first :standings edn/read-string (map #(select-keys % [:rank :team_name :points :omw :pgw :ogw]))))))) (testing "another round" (testing "pairings" (make-request (-> (mock/request :put (str "/api/tournament/" sanction-id "/round-2/pairings")) (mock/json-body {:pairings [{:team1 ["4050100000"] :team2 ["1010200000"] :table_number 1} {:team1 ["5060300000"] :team2 ["7010400000"] :table_number 2}] :playoff false}) (add-apikey)) 204) (is (= [{:team1 "Team 1" :team2 "Team 2" :table_number 1 :team1_points 3 :team2_points 3} {:team1 "Team 3" :team2 "Team 4" :table_number 2 :team1_points 0 :team2_points 0}] (sql/select db/pairing (sql/fields :table_number :team1_points :team2_points) (sql/with db/round (sql/fields) (sql/where {:num 2})) (sql/with db/team1 (sql/fields [:name :team1])) (sql/with db/team2 (sql/fields [:name :team2])) (sql/order :table_number))))) (testing "results" (make-request (-> (mock/request :put (str "/api/tournament/" sanction-id "/round-2/results")) (mock/json-body {:results [{:team1 ["4050100000"] :team2 ["1010200000"] :table_number 1 :team1_wins 2 :team2_wins 1 :draws 0} {:team1 ["5060300000"] :team2 ["7010400000"] :table_number 2 :team1_wins 2 :team2_wins 1 :draws 0}]}) (add-apikey)) 204)) (testing "standings" (is (= [{:rank 1 :team_name "Team 1" :points 6 :omw 1/2 :pgw 2/3 :ogw 11/20} {:rank 2 :team_name "Team 2" :points 3 :omw 133/200 :pgw 3/5 :ogw 299/600} {:rank 3 :team_name "Team 3" :points 3 :omw 133/200 :pgw 1/2 :ogw 299/600} {:rank 4 :team_name "Team 4" :points 0 :omw 1/2 :pgw 33/100 :ogw 11/20}] (->> (sql/select db/standings (sql/where {:round 2})) first :standings edn/read-string (map #(select-keys % [:rank :team_name :points :omw :pgw :ogw]))))))))
[ { "context": "(ns vlagwt.utils\n ^{:author \"Thomas Bock <thomas.bock@ptb.de>\"\n :doc \"Utils.\"}\n (:requ", "end": 41, "score": 0.999883770942688, "start": 30, "tag": "NAME", "value": "Thomas Bock" }, { "context": "(ns vlagwt.utils\n ^{:author \"Thomas Bock <thomas.bock@ptb.de>\"\n :doc \"Utils.\"}\n (:require [clojure.string ", "end": 61, "score": 0.999925971031189, "start": 43, "tag": "EMAIL", "value": "thomas.bock@ptb.de" }, { "context": "count (filter kw v)))\n\n;; https://gist.github.com/hozumi/1472865\n(defn sha1-str [s]\n (->> (-> \"sha1\"\n ", "end": 499, "score": 0.9987548589706421, "start": 493, "tag": "USERNAME", "value": "hozumi" } ]
src/vlagwt/utils.clj
wactbprot/vl-agwt
0
(ns vlagwt.utils ^{:author "Thomas Bock <thomas.bock@ptb.de>" :doc "Utils."} (:require [clojure.string :as string]) (:import [java.time.format DateTimeFormatter] [java.time LocalDateTime])) (defn req->inq [req] (get-in req [:body])) (defn req->req-id [req] (get-in req [:route-params :req-id])) (defn db-req->value [db-req] (mapv :value db-req)) (defn db-req->key [db-req] (mapv :key db-req)) (defn number-of [v kw] (count (filter kw v))) ;; https://gist.github.com/hozumi/1472865 (defn sha1-str [s] (->> (-> "sha1" java.security.MessageDigest/getInstance (.digest (.getBytes s))) (map #(.substring (Integer/toString (+ (bit-and % 0xff) 0x100) 16) 1)) (apply str))) (defn unique-req-id [l] (group-by :key l)) (defn today [] (str (.format (java.time.LocalDateTime/now) (DateTimeFormatter/ofPattern "yyyy-MM-dd"))))
22863
(ns vlagwt.utils ^{:author "<NAME> <<EMAIL>>" :doc "Utils."} (:require [clojure.string :as string]) (:import [java.time.format DateTimeFormatter] [java.time LocalDateTime])) (defn req->inq [req] (get-in req [:body])) (defn req->req-id [req] (get-in req [:route-params :req-id])) (defn db-req->value [db-req] (mapv :value db-req)) (defn db-req->key [db-req] (mapv :key db-req)) (defn number-of [v kw] (count (filter kw v))) ;; https://gist.github.com/hozumi/1472865 (defn sha1-str [s] (->> (-> "sha1" java.security.MessageDigest/getInstance (.digest (.getBytes s))) (map #(.substring (Integer/toString (+ (bit-and % 0xff) 0x100) 16) 1)) (apply str))) (defn unique-req-id [l] (group-by :key l)) (defn today [] (str (.format (java.time.LocalDateTime/now) (DateTimeFormatter/ofPattern "yyyy-MM-dd"))))
true
(ns vlagwt.utils ^{:author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>" :doc "Utils."} (:require [clojure.string :as string]) (:import [java.time.format DateTimeFormatter] [java.time LocalDateTime])) (defn req->inq [req] (get-in req [:body])) (defn req->req-id [req] (get-in req [:route-params :req-id])) (defn db-req->value [db-req] (mapv :value db-req)) (defn db-req->key [db-req] (mapv :key db-req)) (defn number-of [v kw] (count (filter kw v))) ;; https://gist.github.com/hozumi/1472865 (defn sha1-str [s] (->> (-> "sha1" java.security.MessageDigest/getInstance (.digest (.getBytes s))) (map #(.substring (Integer/toString (+ (bit-and % 0xff) 0x100) 16) 1)) (apply str))) (defn unique-req-id [l] (group-by :key l)) (defn today [] (str (.format (java.time.LocalDateTime/now) (DateTimeFormatter/ofPattern "yyyy-MM-dd"))))
[ { "context": "ite-authenticator? waiter-url)\n (let [token (rand-name)\n response (post-token waiter-url (dis", "end": 495, "score": 0.6641449332237244, "start": 486, "tag": "KEY", "value": "rand-name" }, { "context": " \"'\")]\n (let [token (rand-name)\n {:keys [body] :as response} (post-", "end": 2269, "score": 0.7067130208015442, "start": 2260, "tag": "KEY", "value": "rand-name" }, { "context": "s? body error-message)))\n (let [token (rand-name)\n {:keys [body] :as response} (post-", "end": 2934, "score": 0.746118426322937, "start": 2930, "tag": "KEY", "value": "name" }, { "context": "ml-authentication? waiter-url)\n (let [token (rand-name)\n response (post-token waiter-url (-> ", "end": 4774, "score": 0.9542087912559509, "start": 4765, "tag": "KEY", "value": "rand-name" } ]
waiter/integration/waiter/authentication_test.clj
GetCloud/waiter
1
(ns waiter.authentication-test (:require [clj-time.core :as t] [clojure.data.json :as json] [clojure.string :as string] [clojure.test :refer :all] [reaver :as reaver] [waiter.util.client-tools :refer :all]) (:import (java.net URL URLEncoder))) (deftest ^:parallel ^:integration-fast test-default-composite-authenticator (testing-using-waiter-url (when (using-composite-authenticator? waiter-url) (let [token (rand-name) response (post-token waiter-url (dissoc (assoc (kitchen-params) :name token :permitted-user "*" :run-as-user (retrieve-username) :token token) :authentication))] (try (assert-response-status response 200) (let [{:keys [service-id body]} (make-request-with-debug-info {:x-waiter-token token} #(make-kitchen-request waiter-url % :path "/request-info")) body-json (json/read-str (str body))] (with-service-cleanup service-id (is (= (retrieve-username) (get-in body-json ["headers" "x-waiter-auth-principal"]))))) (finally (delete-token-and-assert waiter-url token))))))) (deftest ^:parallel ^:integration-fast test-token-authentication-parameter-error (testing-using-waiter-url (when (using-composite-authenticator? waiter-url) (let [authentication-providers (-> waiter-url waiter-settings (get-in [:authenticator-config :composite :authentication-providers]) keys (->> (map name))) error-message (str "authentication must be one of: '" (string/join "', '" (sort (into #{"disabled" "standard"} authentication-providers))) "'")] (let [token (rand-name) {:keys [body] :as response} (post-token waiter-url (assoc (kitchen-params) :authentication "invalid" :name token :permitted-user "*" :run-as-user (retrieve-username) :token token))] (assert-response-status response 400) (is (string/includes? body error-message))) (let [token (rand-name) {:keys [body] :as response} (post-token waiter-url (assoc (kitchen-params) :authentication "" :name token :permitted-user "*" :run-as-user (retrieve-username) :token token))] (assert-response-status response 400) (is (string/includes? body error-message))))))) (defn- perform-saml-authentication "Perform authentication wtih an identity provider service. Return map of waiter acs endpoint, saml-response and relay-state" [saml-redirect-location] (let [make-connection (fn [request-url] (let [http-connection (.openConnection (URL. request-url))] (.setDoOutput http-connection false) (.setDoInput http-connection true) (.setRequestMethod http-connection "GET") (.connect http-connection) http-connection)) conn (make-connection saml-redirect-location)] (is (= 200 (.getResponseCode conn))) (reaver/extract (reaver/parse (slurp (.getInputStream conn))) [:waiter-saml-acs-endpoint :saml-response :relay-state] "form" (reaver/attr :action) "form input[name=SAMLResponse]" (reaver/attr :value) "form input[name=RelayState]" (reaver/attr :value)))) (deftest ^:parallel ^:integration-fast test-saml-authentication (testing-using-waiter-url (when (supports-saml-authentication? waiter-url) (let [token (rand-name) response (post-token waiter-url (-> (kitchen-params) (assoc :authentication "saml" :name token :permitted-user "*" :run-as-user (retrieve-username) :token token)))] (assert-response-status response 200) (try (let [{:keys [headers] :as response} (make-request waiter-url "/request-info" :headers {:x-waiter-token token}) _ (assert-response-status response 302) saml-redirect-location (get headers "location") {:keys [relay-state saml-response waiter-saml-acs-endpoint]} (perform-saml-authentication saml-redirect-location) {:keys [body] :as response} (make-request waiter-saml-acs-endpoint "" :body (str "SAMLResponse=" (URLEncoder/encode saml-response) "&RelayState=" (URLEncoder/encode relay-state)) :headers {"content-type" "application/x-www-form-urlencoded"} :method :post) _ (assert-response-status response 200) {:keys [waiter-saml-auth-redirect-endpoint saml-auth-data]} (reaver/extract (reaver/parse body) [:waiter-saml-auth-redirect-endpoint :saml-auth-data] "form" (reaver/attr :action) "form input[name=saml-auth-data]" (reaver/attr :value)) _ (is (= (str "http://" waiter-url "/waiter-auth/saml/auth-redirect") waiter-saml-auth-redirect-endpoint)) {:keys [cookies headers] :as response} (make-request waiter-url "/waiter-auth/saml/auth-redirect" :body (str "saml-auth-data=" (URLEncoder/encode saml-auth-data)) :headers {"content-type" "application/x-www-form-urlencoded"} :method :post) _ (assert-response-status response 303) cookie-fn (fn [cookies name] (some #(when (= name (:name %)) %) cookies)) auth-cookie (cookie-fn cookies "x-waiter-auth") _ (is (not (nil? auth-cookie))) _ (is (> (:max-age auth-cookie) (-> 1 t/hours t/in-seconds))) _ (is (= (str "http://" waiter-url "/request-info") (get headers "location"))) {:keys [body service-id] :as response} (make-request-with-debug-info {:x-waiter-token token} #(make-request waiter-url "/request-info" :headers % :cookies cookies)) _ (assert-response-status response 200) body-json (json/read-str (str body))] (with-service-cleanup service-id (is (= (retrieve-username) (get-in body-json ["headers" "x-waiter-auth-principal"]))))) (finally (delete-token-and-assert waiter-url token)))))))
68968
(ns waiter.authentication-test (:require [clj-time.core :as t] [clojure.data.json :as json] [clojure.string :as string] [clojure.test :refer :all] [reaver :as reaver] [waiter.util.client-tools :refer :all]) (:import (java.net URL URLEncoder))) (deftest ^:parallel ^:integration-fast test-default-composite-authenticator (testing-using-waiter-url (when (using-composite-authenticator? waiter-url) (let [token (<KEY>) response (post-token waiter-url (dissoc (assoc (kitchen-params) :name token :permitted-user "*" :run-as-user (retrieve-username) :token token) :authentication))] (try (assert-response-status response 200) (let [{:keys [service-id body]} (make-request-with-debug-info {:x-waiter-token token} #(make-kitchen-request waiter-url % :path "/request-info")) body-json (json/read-str (str body))] (with-service-cleanup service-id (is (= (retrieve-username) (get-in body-json ["headers" "x-waiter-auth-principal"]))))) (finally (delete-token-and-assert waiter-url token))))))) (deftest ^:parallel ^:integration-fast test-token-authentication-parameter-error (testing-using-waiter-url (when (using-composite-authenticator? waiter-url) (let [authentication-providers (-> waiter-url waiter-settings (get-in [:authenticator-config :composite :authentication-providers]) keys (->> (map name))) error-message (str "authentication must be one of: '" (string/join "', '" (sort (into #{"disabled" "standard"} authentication-providers))) "'")] (let [token (<KEY>) {:keys [body] :as response} (post-token waiter-url (assoc (kitchen-params) :authentication "invalid" :name token :permitted-user "*" :run-as-user (retrieve-username) :token token))] (assert-response-status response 400) (is (string/includes? body error-message))) (let [token (rand-<KEY>) {:keys [body] :as response} (post-token waiter-url (assoc (kitchen-params) :authentication "" :name token :permitted-user "*" :run-as-user (retrieve-username) :token token))] (assert-response-status response 400) (is (string/includes? body error-message))))))) (defn- perform-saml-authentication "Perform authentication wtih an identity provider service. Return map of waiter acs endpoint, saml-response and relay-state" [saml-redirect-location] (let [make-connection (fn [request-url] (let [http-connection (.openConnection (URL. request-url))] (.setDoOutput http-connection false) (.setDoInput http-connection true) (.setRequestMethod http-connection "GET") (.connect http-connection) http-connection)) conn (make-connection saml-redirect-location)] (is (= 200 (.getResponseCode conn))) (reaver/extract (reaver/parse (slurp (.getInputStream conn))) [:waiter-saml-acs-endpoint :saml-response :relay-state] "form" (reaver/attr :action) "form input[name=SAMLResponse]" (reaver/attr :value) "form input[name=RelayState]" (reaver/attr :value)))) (deftest ^:parallel ^:integration-fast test-saml-authentication (testing-using-waiter-url (when (supports-saml-authentication? waiter-url) (let [token (<KEY>) response (post-token waiter-url (-> (kitchen-params) (assoc :authentication "saml" :name token :permitted-user "*" :run-as-user (retrieve-username) :token token)))] (assert-response-status response 200) (try (let [{:keys [headers] :as response} (make-request waiter-url "/request-info" :headers {:x-waiter-token token}) _ (assert-response-status response 302) saml-redirect-location (get headers "location") {:keys [relay-state saml-response waiter-saml-acs-endpoint]} (perform-saml-authentication saml-redirect-location) {:keys [body] :as response} (make-request waiter-saml-acs-endpoint "" :body (str "SAMLResponse=" (URLEncoder/encode saml-response) "&RelayState=" (URLEncoder/encode relay-state)) :headers {"content-type" "application/x-www-form-urlencoded"} :method :post) _ (assert-response-status response 200) {:keys [waiter-saml-auth-redirect-endpoint saml-auth-data]} (reaver/extract (reaver/parse body) [:waiter-saml-auth-redirect-endpoint :saml-auth-data] "form" (reaver/attr :action) "form input[name=saml-auth-data]" (reaver/attr :value)) _ (is (= (str "http://" waiter-url "/waiter-auth/saml/auth-redirect") waiter-saml-auth-redirect-endpoint)) {:keys [cookies headers] :as response} (make-request waiter-url "/waiter-auth/saml/auth-redirect" :body (str "saml-auth-data=" (URLEncoder/encode saml-auth-data)) :headers {"content-type" "application/x-www-form-urlencoded"} :method :post) _ (assert-response-status response 303) cookie-fn (fn [cookies name] (some #(when (= name (:name %)) %) cookies)) auth-cookie (cookie-fn cookies "x-waiter-auth") _ (is (not (nil? auth-cookie))) _ (is (> (:max-age auth-cookie) (-> 1 t/hours t/in-seconds))) _ (is (= (str "http://" waiter-url "/request-info") (get headers "location"))) {:keys [body service-id] :as response} (make-request-with-debug-info {:x-waiter-token token} #(make-request waiter-url "/request-info" :headers % :cookies cookies)) _ (assert-response-status response 200) body-json (json/read-str (str body))] (with-service-cleanup service-id (is (= (retrieve-username) (get-in body-json ["headers" "x-waiter-auth-principal"]))))) (finally (delete-token-and-assert waiter-url token)))))))
true
(ns waiter.authentication-test (:require [clj-time.core :as t] [clojure.data.json :as json] [clojure.string :as string] [clojure.test :refer :all] [reaver :as reaver] [waiter.util.client-tools :refer :all]) (:import (java.net URL URLEncoder))) (deftest ^:parallel ^:integration-fast test-default-composite-authenticator (testing-using-waiter-url (when (using-composite-authenticator? waiter-url) (let [token (PI:KEY:<KEY>END_PI) response (post-token waiter-url (dissoc (assoc (kitchen-params) :name token :permitted-user "*" :run-as-user (retrieve-username) :token token) :authentication))] (try (assert-response-status response 200) (let [{:keys [service-id body]} (make-request-with-debug-info {:x-waiter-token token} #(make-kitchen-request waiter-url % :path "/request-info")) body-json (json/read-str (str body))] (with-service-cleanup service-id (is (= (retrieve-username) (get-in body-json ["headers" "x-waiter-auth-principal"]))))) (finally (delete-token-and-assert waiter-url token))))))) (deftest ^:parallel ^:integration-fast test-token-authentication-parameter-error (testing-using-waiter-url (when (using-composite-authenticator? waiter-url) (let [authentication-providers (-> waiter-url waiter-settings (get-in [:authenticator-config :composite :authentication-providers]) keys (->> (map name))) error-message (str "authentication must be one of: '" (string/join "', '" (sort (into #{"disabled" "standard"} authentication-providers))) "'")] (let [token (PI:KEY:<KEY>END_PI) {:keys [body] :as response} (post-token waiter-url (assoc (kitchen-params) :authentication "invalid" :name token :permitted-user "*" :run-as-user (retrieve-username) :token token))] (assert-response-status response 400) (is (string/includes? body error-message))) (let [token (rand-PI:KEY:<KEY>END_PI) {:keys [body] :as response} (post-token waiter-url (assoc (kitchen-params) :authentication "" :name token :permitted-user "*" :run-as-user (retrieve-username) :token token))] (assert-response-status response 400) (is (string/includes? body error-message))))))) (defn- perform-saml-authentication "Perform authentication wtih an identity provider service. Return map of waiter acs endpoint, saml-response and relay-state" [saml-redirect-location] (let [make-connection (fn [request-url] (let [http-connection (.openConnection (URL. request-url))] (.setDoOutput http-connection false) (.setDoInput http-connection true) (.setRequestMethod http-connection "GET") (.connect http-connection) http-connection)) conn (make-connection saml-redirect-location)] (is (= 200 (.getResponseCode conn))) (reaver/extract (reaver/parse (slurp (.getInputStream conn))) [:waiter-saml-acs-endpoint :saml-response :relay-state] "form" (reaver/attr :action) "form input[name=SAMLResponse]" (reaver/attr :value) "form input[name=RelayState]" (reaver/attr :value)))) (deftest ^:parallel ^:integration-fast test-saml-authentication (testing-using-waiter-url (when (supports-saml-authentication? waiter-url) (let [token (PI:KEY:<KEY>END_PI) response (post-token waiter-url (-> (kitchen-params) (assoc :authentication "saml" :name token :permitted-user "*" :run-as-user (retrieve-username) :token token)))] (assert-response-status response 200) (try (let [{:keys [headers] :as response} (make-request waiter-url "/request-info" :headers {:x-waiter-token token}) _ (assert-response-status response 302) saml-redirect-location (get headers "location") {:keys [relay-state saml-response waiter-saml-acs-endpoint]} (perform-saml-authentication saml-redirect-location) {:keys [body] :as response} (make-request waiter-saml-acs-endpoint "" :body (str "SAMLResponse=" (URLEncoder/encode saml-response) "&RelayState=" (URLEncoder/encode relay-state)) :headers {"content-type" "application/x-www-form-urlencoded"} :method :post) _ (assert-response-status response 200) {:keys [waiter-saml-auth-redirect-endpoint saml-auth-data]} (reaver/extract (reaver/parse body) [:waiter-saml-auth-redirect-endpoint :saml-auth-data] "form" (reaver/attr :action) "form input[name=saml-auth-data]" (reaver/attr :value)) _ (is (= (str "http://" waiter-url "/waiter-auth/saml/auth-redirect") waiter-saml-auth-redirect-endpoint)) {:keys [cookies headers] :as response} (make-request waiter-url "/waiter-auth/saml/auth-redirect" :body (str "saml-auth-data=" (URLEncoder/encode saml-auth-data)) :headers {"content-type" "application/x-www-form-urlencoded"} :method :post) _ (assert-response-status response 303) cookie-fn (fn [cookies name] (some #(when (= name (:name %)) %) cookies)) auth-cookie (cookie-fn cookies "x-waiter-auth") _ (is (not (nil? auth-cookie))) _ (is (> (:max-age auth-cookie) (-> 1 t/hours t/in-seconds))) _ (is (= (str "http://" waiter-url "/request-info") (get headers "location"))) {:keys [body service-id] :as response} (make-request-with-debug-info {:x-waiter-token token} #(make-request waiter-url "/request-info" :headers % :cookies cookies)) _ (assert-response-status response 200) body-json (json/read-str (str body))] (with-service-cleanup service-id (is (= (retrieve-username) (get-in body-json ["headers" "x-waiter-auth-principal"]))))) (finally (delete-token-and-assert waiter-url token)))))))
[ { "context": ";; Copyright 2014 (c) Diego Souza <dsouza@c0d3.xxx>\n;; Copyright 2014 (c) Alexandre", "end": 33, "score": 0.9998793601989746, "start": 22, "tag": "NAME", "value": "Diego Souza" }, { "context": ";; Copyright 2014 (c) Diego Souza <dsouza@c0d3.xxx>\n;; Copyright 2014 (c) Alexandre Baaklini <abaakl", "end": 50, "score": 0.9998704195022583, "start": 35, "tag": "EMAIL", "value": "dsouza@c0d3.xxx" }, { "context": "iego Souza <dsouza@c0d3.xxx>\n;; Copyright 2014 (c) Alexandre Baaklini <abaaklini@gmail.com>\n;;\n;; Licensed under the Ap", "end": 92, "score": 0.9998772740364075, "start": 74, "tag": "NAME", "value": "Alexandre Baaklini" }, { "context": "d3.xxx>\n;; Copyright 2014 (c) Alexandre Baaklini <abaaklini@gmail.com>\n;;\n;; Licensed under the Apache License, Version", "end": 113, "score": 0.9999227523803711, "start": 94, "tag": "EMAIL", "value": "abaaklini@gmail.com" } ]
src/blackbox/src/leela/blackbox/data/time.clj
locaweb/leela
22
;; Copyright 2014 (c) Diego Souza <dsouza@c0d3.xxx> ;; Copyright 2014 (c) Alexandre Baaklini <abaaklini@gmail.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 leela.blackbox.data.time (:use [clj-time.format :only [formatter parse unparse]] [clj-time.coerce :only [to-long from-long]])) (def custom-formatter (formatter "yyyyMMddhhmmss")) (defn str-date-to-long "Given a string in the following format yyyyMMddhhmmss returns a long value to be stored on the database" [s] (to-long (parse custom-formatter s))) (defn long-to-date-str "Given a long number returns the respective string in the following format yyyyMMddhhmmss" [l] (unparse custom-formatter (from-long l)))
88195
;; Copyright 2014 (c) <NAME> <<EMAIL>> ;; Copyright 2014 (c) <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 leela.blackbox.data.time (:use [clj-time.format :only [formatter parse unparse]] [clj-time.coerce :only [to-long from-long]])) (def custom-formatter (formatter "yyyyMMddhhmmss")) (defn str-date-to-long "Given a string in the following format yyyyMMddhhmmss returns a long value to be stored on the database" [s] (to-long (parse custom-formatter s))) (defn long-to-date-str "Given a long number returns the respective string in the following format yyyyMMddhhmmss" [l] (unparse custom-formatter (from-long l)))
true
;; Copyright 2014 (c) PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ;; Copyright 2014 (c) 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 leela.blackbox.data.time (:use [clj-time.format :only [formatter parse unparse]] [clj-time.coerce :only [to-long from-long]])) (def custom-formatter (formatter "yyyyMMddhhmmss")) (defn str-date-to-long "Given a string in the following format yyyyMMddhhmmss returns a long value to be stored on the database" [s] (to-long (parse custom-formatter s))) (defn long-to-date-str "Given a long number returns the respective string in the following format yyyyMMddhhmmss" [l] (unparse custom-formatter (from-long l)))
[ { "context": ";; Copyright (c) 2015-2016 Andrey Antukh <niwi@niwi.nz>\n;; All rights reserved.\n;;\n;; Redi", "end": 40, "score": 0.9998809099197388, "start": 27, "tag": "NAME", "value": "Andrey Antukh" }, { "context": ";; Copyright (c) 2015-2016 Andrey Antukh <niwi@niwi.nz>\n;; All rights reserved.\n;;\n;; Redistribution and", "end": 54, "score": 0.9999333620071411, "start": 42, "tag": "EMAIL", "value": "niwi@niwi.nz" } ]
src/clojure/catacumba/core.clj
source-c/catacumba
212
;; Copyright (c) 2015-2016 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 catacumba.core (:require [catacumba.impl server routing context handlers websocket sse] [catacumba.impl.helpers :refer(defalias)])) (defalias run-server catacumba.impl.server/run-server) (defalias routes catacumba.impl.routing/routes) (defalias on-close catacumba.impl.context/on-close) (defalias before-send catacumba.impl.context/before-send) (defalias delegate catacumba.impl.context/delegate) (defalias delegated-context? catacumba.impl.context/delegated-context?) (defalias public-address catacumba.impl.context/public-address) (defalias get-body! catacumba.impl.context/get-body!) (defalias get-headers catacumba.impl.context/get-headers) (defalias set-headers! catacumba.impl.context/set-headers!) (defalias get-cookies catacumba.impl.context/get-cookies) (defalias set-cookies! catacumba.impl.context/set-cookies!) (defalias set-status! catacumba.impl.context/set-status!) (defalias get-formdata catacumba.impl.context/get-formdata) (defalias get-query-params catacumba.impl.context/get-query-params) (defalias send! catacumba.impl.handlers/send!) (defalias websocket catacumba.impl.websocket/websocket) (defalias sse catacumba.impl.sse/sse)
105803
;; Copyright (c) 2015-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: ;; ;; * 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 catacumba.core (:require [catacumba.impl server routing context handlers websocket sse] [catacumba.impl.helpers :refer(defalias)])) (defalias run-server catacumba.impl.server/run-server) (defalias routes catacumba.impl.routing/routes) (defalias on-close catacumba.impl.context/on-close) (defalias before-send catacumba.impl.context/before-send) (defalias delegate catacumba.impl.context/delegate) (defalias delegated-context? catacumba.impl.context/delegated-context?) (defalias public-address catacumba.impl.context/public-address) (defalias get-body! catacumba.impl.context/get-body!) (defalias get-headers catacumba.impl.context/get-headers) (defalias set-headers! catacumba.impl.context/set-headers!) (defalias get-cookies catacumba.impl.context/get-cookies) (defalias set-cookies! catacumba.impl.context/set-cookies!) (defalias set-status! catacumba.impl.context/set-status!) (defalias get-formdata catacumba.impl.context/get-formdata) (defalias get-query-params catacumba.impl.context/get-query-params) (defalias send! catacumba.impl.handlers/send!) (defalias websocket catacumba.impl.websocket/websocket) (defalias sse catacumba.impl.sse/sse)
true
;; Copyright (c) 2015-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: ;; ;; * 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 catacumba.core (:require [catacumba.impl server routing context handlers websocket sse] [catacumba.impl.helpers :refer(defalias)])) (defalias run-server catacumba.impl.server/run-server) (defalias routes catacumba.impl.routing/routes) (defalias on-close catacumba.impl.context/on-close) (defalias before-send catacumba.impl.context/before-send) (defalias delegate catacumba.impl.context/delegate) (defalias delegated-context? catacumba.impl.context/delegated-context?) (defalias public-address catacumba.impl.context/public-address) (defalias get-body! catacumba.impl.context/get-body!) (defalias get-headers catacumba.impl.context/get-headers) (defalias set-headers! catacumba.impl.context/set-headers!) (defalias get-cookies catacumba.impl.context/get-cookies) (defalias set-cookies! catacumba.impl.context/set-cookies!) (defalias set-status! catacumba.impl.context/set-status!) (defalias get-formdata catacumba.impl.context/get-formdata) (defalias get-query-params catacumba.impl.context/get-query-params) (defalias send! catacumba.impl.handlers/send!) (defalias websocket catacumba.impl.websocket/websocket) (defalias sse catacumba.impl.sse/sse)
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 29, "score": 0.9998685717582703, "start": 18, "tag": "NAME", "value": "Rich Hickey" }, { "context": "tor for Clojure data structures.\"\n :author \"Rich Hickey\"}\n clojure.inspector\n (:import\n (java.a", "end": 560, "score": 0.999881386756897, "start": 549, "tag": "NAME", "value": "Rich Hickey" } ]
server/target/clojure/inspector.clj
OctavioBR/healthcheck
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. (ns ^{:doc "Graphical object inspector for Clojure data structures." :author "Rich Hickey"} clojure.inspector (:import (java.awt BorderLayout) (java.awt.event ActionEvent ActionListener) (javax.swing.tree TreeModel) (javax.swing.table TableModel AbstractTableModel) (javax.swing JPanel JTree JTable JScrollPane JFrame JToolBar JButton SwingUtilities))) (defn atom? [x] (not (coll? x))) (defn collection-tag [x] (cond (map-entry? x) :entry (instance? java.util.Map x) :seqable (instance? java.util.Set x) :seqable (sequential? x) :seq (instance? clojure.lang.Seqable x) :seqable :else :atom)) (defmulti is-leaf collection-tag) (defmulti get-child (fn [parent index] (collection-tag parent))) (defmulti get-child-count collection-tag) (defmethod is-leaf :default [node] (atom? node)) (defmethod get-child :default [parent index] (nth parent index)) (defmethod get-child-count :default [parent] (count parent)) (defmethod is-leaf :entry [e] (is-leaf (val e))) (defmethod get-child :entry [e index] (get-child (val e) index)) (defmethod get-child-count :entry [e] (count (val e))) (defmethod is-leaf :seqable [parent] false) (defmethod get-child :seqable [parent index] (nth (seq parent) index)) (defmethod get-child-count :seqable [parent] (count (seq parent))) (defn tree-model [data] (proxy [TreeModel] [] (getRoot [] data) (addTreeModelListener [treeModelListener]) (getChild [parent index] (get-child parent index)) (getChildCount [parent] (get-child-count parent)) (isLeaf [node] (is-leaf node)) (valueForPathChanged [path newValue]) (getIndexOfChild [parent child] -1) (removeTreeModelListener [treeModelListener]))) (defn old-table-model [data] (let [row1 (first data) colcnt (count row1) cnt (count data) vals (if (map? row1) vals identity)] (proxy [TableModel] [] (addTableModelListener [tableModelListener]) (getColumnClass [columnIndex] Object) (getColumnCount [] colcnt) (getColumnName [columnIndex] (if (map? row1) (name (nth (keys row1) columnIndex)) (str columnIndex))) (getRowCount [] cnt) (getValueAt [rowIndex columnIndex] (nth (vals (nth data rowIndex)) columnIndex)) (isCellEditable [rowIndex columnIndex] false) (removeTableModelListener [tableModelListener])))) (defn inspect-tree "creates a graphical (Swing) inspector on the supplied hierarchical data" {:added "1.0"} [data] (doto (JFrame. "Clojure Inspector") (.add (JScrollPane. (JTree. (tree-model data)))) (.setSize 400 600) (.setVisible true))) (defn inspect-table "creates a graphical (Swing) inspector on the supplied regular data, which must be a sequential data structure of data structures of equal length" {:added "1.0"} [data] (doto (JFrame. "Clojure Inspector") (.add (JScrollPane. (JTable. (old-table-model data)))) (.setSize 400 600) (.setVisible true))) (defmulti list-provider class) (defmethod list-provider :default [x] {:nrows 1 :get-value (fn [i] x) :get-label (fn [i] (.getName (class x)))}) (defmethod list-provider java.util.List [c] (let [v (if (vector? c) c (vec c))] {:nrows (count v) :get-value (fn [i] (v i)) :get-label (fn [i] i)})) (defmethod list-provider java.util.Map [c] (let [v (vec (sort (map (fn [[k v]] (vector k v)) c)))] {:nrows (count v) :get-value (fn [i] ((v i) 1)) :get-label (fn [i] ((v i) 0))})) (defn list-model [provider] (let [{:keys [nrows get-value get-label]} provider] (proxy [AbstractTableModel] [] (getColumnCount [] 2) (getRowCount [] nrows) (getValueAt [rowIndex columnIndex] (cond (= 0 columnIndex) (get-label rowIndex) (= 1 columnIndex) (print-str (get-value rowIndex))))))) (defmulti table-model class) (defmethod table-model :default [x] (proxy [AbstractTableModel] [] (getColumnCount [] 2) (getRowCount [] 1) (getValueAt [rowIndex columnIndex] (if (zero? columnIndex) (class x) x)))) ;(defn make-inspector [x] ; (agent {:frame frame :data x :parent nil :index 0})) (defn inspect "creates a graphical (Swing) inspector on the supplied object" {:added "1.0"} [x] (doto (JFrame. "Clojure Inspector") (.add (doto (JPanel. (BorderLayout.)) (.add (doto (JToolBar.) (.add (JButton. "Back")) (.addSeparator) (.add (JButton. "List")) (.add (JButton. "Table")) (.add (JButton. "Bean")) (.add (JButton. "Line")) (.add (JButton. "Bar")) (.addSeparator) (.add (JButton. "Prev")) (.add (JButton. "Next"))) BorderLayout/NORTH) (.add (JScrollPane. (doto (JTable. (list-model (list-provider x))) (.setAutoResizeMode JTable/AUTO_RESIZE_LAST_COLUMN))) BorderLayout/CENTER))) (.setSize 400 400) (.setVisible true))) (comment (load-file "src/inspector.clj") (refer 'inspector) (inspect-tree {:a 1 :b 2 :c [1 2 3 {:d 4 :e 5 :f [6 7 8]}]}) (inspect-table [[1 2 3][4 5 6][7 8 9][10 11 12]]) )
70548
; Copyright (c) <NAME>. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns ^{:doc "Graphical object inspector for Clojure data structures." :author "<NAME>"} clojure.inspector (:import (java.awt BorderLayout) (java.awt.event ActionEvent ActionListener) (javax.swing.tree TreeModel) (javax.swing.table TableModel AbstractTableModel) (javax.swing JPanel JTree JTable JScrollPane JFrame JToolBar JButton SwingUtilities))) (defn atom? [x] (not (coll? x))) (defn collection-tag [x] (cond (map-entry? x) :entry (instance? java.util.Map x) :seqable (instance? java.util.Set x) :seqable (sequential? x) :seq (instance? clojure.lang.Seqable x) :seqable :else :atom)) (defmulti is-leaf collection-tag) (defmulti get-child (fn [parent index] (collection-tag parent))) (defmulti get-child-count collection-tag) (defmethod is-leaf :default [node] (atom? node)) (defmethod get-child :default [parent index] (nth parent index)) (defmethod get-child-count :default [parent] (count parent)) (defmethod is-leaf :entry [e] (is-leaf (val e))) (defmethod get-child :entry [e index] (get-child (val e) index)) (defmethod get-child-count :entry [e] (count (val e))) (defmethod is-leaf :seqable [parent] false) (defmethod get-child :seqable [parent index] (nth (seq parent) index)) (defmethod get-child-count :seqable [parent] (count (seq parent))) (defn tree-model [data] (proxy [TreeModel] [] (getRoot [] data) (addTreeModelListener [treeModelListener]) (getChild [parent index] (get-child parent index)) (getChildCount [parent] (get-child-count parent)) (isLeaf [node] (is-leaf node)) (valueForPathChanged [path newValue]) (getIndexOfChild [parent child] -1) (removeTreeModelListener [treeModelListener]))) (defn old-table-model [data] (let [row1 (first data) colcnt (count row1) cnt (count data) vals (if (map? row1) vals identity)] (proxy [TableModel] [] (addTableModelListener [tableModelListener]) (getColumnClass [columnIndex] Object) (getColumnCount [] colcnt) (getColumnName [columnIndex] (if (map? row1) (name (nth (keys row1) columnIndex)) (str columnIndex))) (getRowCount [] cnt) (getValueAt [rowIndex columnIndex] (nth (vals (nth data rowIndex)) columnIndex)) (isCellEditable [rowIndex columnIndex] false) (removeTableModelListener [tableModelListener])))) (defn inspect-tree "creates a graphical (Swing) inspector on the supplied hierarchical data" {:added "1.0"} [data] (doto (JFrame. "Clojure Inspector") (.add (JScrollPane. (JTree. (tree-model data)))) (.setSize 400 600) (.setVisible true))) (defn inspect-table "creates a graphical (Swing) inspector on the supplied regular data, which must be a sequential data structure of data structures of equal length" {:added "1.0"} [data] (doto (JFrame. "Clojure Inspector") (.add (JScrollPane. (JTable. (old-table-model data)))) (.setSize 400 600) (.setVisible true))) (defmulti list-provider class) (defmethod list-provider :default [x] {:nrows 1 :get-value (fn [i] x) :get-label (fn [i] (.getName (class x)))}) (defmethod list-provider java.util.List [c] (let [v (if (vector? c) c (vec c))] {:nrows (count v) :get-value (fn [i] (v i)) :get-label (fn [i] i)})) (defmethod list-provider java.util.Map [c] (let [v (vec (sort (map (fn [[k v]] (vector k v)) c)))] {:nrows (count v) :get-value (fn [i] ((v i) 1)) :get-label (fn [i] ((v i) 0))})) (defn list-model [provider] (let [{:keys [nrows get-value get-label]} provider] (proxy [AbstractTableModel] [] (getColumnCount [] 2) (getRowCount [] nrows) (getValueAt [rowIndex columnIndex] (cond (= 0 columnIndex) (get-label rowIndex) (= 1 columnIndex) (print-str (get-value rowIndex))))))) (defmulti table-model class) (defmethod table-model :default [x] (proxy [AbstractTableModel] [] (getColumnCount [] 2) (getRowCount [] 1) (getValueAt [rowIndex columnIndex] (if (zero? columnIndex) (class x) x)))) ;(defn make-inspector [x] ; (agent {:frame frame :data x :parent nil :index 0})) (defn inspect "creates a graphical (Swing) inspector on the supplied object" {:added "1.0"} [x] (doto (JFrame. "Clojure Inspector") (.add (doto (JPanel. (BorderLayout.)) (.add (doto (JToolBar.) (.add (JButton. "Back")) (.addSeparator) (.add (JButton. "List")) (.add (JButton. "Table")) (.add (JButton. "Bean")) (.add (JButton. "Line")) (.add (JButton. "Bar")) (.addSeparator) (.add (JButton. "Prev")) (.add (JButton. "Next"))) BorderLayout/NORTH) (.add (JScrollPane. (doto (JTable. (list-model (list-provider x))) (.setAutoResizeMode JTable/AUTO_RESIZE_LAST_COLUMN))) BorderLayout/CENTER))) (.setSize 400 400) (.setVisible true))) (comment (load-file "src/inspector.clj") (refer 'inspector) (inspect-tree {:a 1 :b 2 :c [1 2 3 {:d 4 :e 5 :f [6 7 8]}]}) (inspect-table [[1 2 3][4 5 6][7 8 9][10 11 12]]) )
true
; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns ^{:doc "Graphical object inspector for Clojure data structures." :author "PI:NAME:<NAME>END_PI"} clojure.inspector (:import (java.awt BorderLayout) (java.awt.event ActionEvent ActionListener) (javax.swing.tree TreeModel) (javax.swing.table TableModel AbstractTableModel) (javax.swing JPanel JTree JTable JScrollPane JFrame JToolBar JButton SwingUtilities))) (defn atom? [x] (not (coll? x))) (defn collection-tag [x] (cond (map-entry? x) :entry (instance? java.util.Map x) :seqable (instance? java.util.Set x) :seqable (sequential? x) :seq (instance? clojure.lang.Seqable x) :seqable :else :atom)) (defmulti is-leaf collection-tag) (defmulti get-child (fn [parent index] (collection-tag parent))) (defmulti get-child-count collection-tag) (defmethod is-leaf :default [node] (atom? node)) (defmethod get-child :default [parent index] (nth parent index)) (defmethod get-child-count :default [parent] (count parent)) (defmethod is-leaf :entry [e] (is-leaf (val e))) (defmethod get-child :entry [e index] (get-child (val e) index)) (defmethod get-child-count :entry [e] (count (val e))) (defmethod is-leaf :seqable [parent] false) (defmethod get-child :seqable [parent index] (nth (seq parent) index)) (defmethod get-child-count :seqable [parent] (count (seq parent))) (defn tree-model [data] (proxy [TreeModel] [] (getRoot [] data) (addTreeModelListener [treeModelListener]) (getChild [parent index] (get-child parent index)) (getChildCount [parent] (get-child-count parent)) (isLeaf [node] (is-leaf node)) (valueForPathChanged [path newValue]) (getIndexOfChild [parent child] -1) (removeTreeModelListener [treeModelListener]))) (defn old-table-model [data] (let [row1 (first data) colcnt (count row1) cnt (count data) vals (if (map? row1) vals identity)] (proxy [TableModel] [] (addTableModelListener [tableModelListener]) (getColumnClass [columnIndex] Object) (getColumnCount [] colcnt) (getColumnName [columnIndex] (if (map? row1) (name (nth (keys row1) columnIndex)) (str columnIndex))) (getRowCount [] cnt) (getValueAt [rowIndex columnIndex] (nth (vals (nth data rowIndex)) columnIndex)) (isCellEditable [rowIndex columnIndex] false) (removeTableModelListener [tableModelListener])))) (defn inspect-tree "creates a graphical (Swing) inspector on the supplied hierarchical data" {:added "1.0"} [data] (doto (JFrame. "Clojure Inspector") (.add (JScrollPane. (JTree. (tree-model data)))) (.setSize 400 600) (.setVisible true))) (defn inspect-table "creates a graphical (Swing) inspector on the supplied regular data, which must be a sequential data structure of data structures of equal length" {:added "1.0"} [data] (doto (JFrame. "Clojure Inspector") (.add (JScrollPane. (JTable. (old-table-model data)))) (.setSize 400 600) (.setVisible true))) (defmulti list-provider class) (defmethod list-provider :default [x] {:nrows 1 :get-value (fn [i] x) :get-label (fn [i] (.getName (class x)))}) (defmethod list-provider java.util.List [c] (let [v (if (vector? c) c (vec c))] {:nrows (count v) :get-value (fn [i] (v i)) :get-label (fn [i] i)})) (defmethod list-provider java.util.Map [c] (let [v (vec (sort (map (fn [[k v]] (vector k v)) c)))] {:nrows (count v) :get-value (fn [i] ((v i) 1)) :get-label (fn [i] ((v i) 0))})) (defn list-model [provider] (let [{:keys [nrows get-value get-label]} provider] (proxy [AbstractTableModel] [] (getColumnCount [] 2) (getRowCount [] nrows) (getValueAt [rowIndex columnIndex] (cond (= 0 columnIndex) (get-label rowIndex) (= 1 columnIndex) (print-str (get-value rowIndex))))))) (defmulti table-model class) (defmethod table-model :default [x] (proxy [AbstractTableModel] [] (getColumnCount [] 2) (getRowCount [] 1) (getValueAt [rowIndex columnIndex] (if (zero? columnIndex) (class x) x)))) ;(defn make-inspector [x] ; (agent {:frame frame :data x :parent nil :index 0})) (defn inspect "creates a graphical (Swing) inspector on the supplied object" {:added "1.0"} [x] (doto (JFrame. "Clojure Inspector") (.add (doto (JPanel. (BorderLayout.)) (.add (doto (JToolBar.) (.add (JButton. "Back")) (.addSeparator) (.add (JButton. "List")) (.add (JButton. "Table")) (.add (JButton. "Bean")) (.add (JButton. "Line")) (.add (JButton. "Bar")) (.addSeparator) (.add (JButton. "Prev")) (.add (JButton. "Next"))) BorderLayout/NORTH) (.add (JScrollPane. (doto (JTable. (list-model (list-provider x))) (.setAutoResizeMode JTable/AUTO_RESIZE_LAST_COLUMN))) BorderLayout/CENTER))) (.setSize 400 400) (.setVisible true))) (comment (load-file "src/inspector.clj") (refer 'inspector) (inspect-tree {:a 1 :b 2 :c [1 2 3 {:d 4 :e 5 :f [6 7 8]}]}) (inspect-table [[1 2 3][4 5 6][7 8 9][10 11 12]]) )
[ { "context": ";\n; Copyright © 2020 Peter Monks\n;\n; Licensed under the Apache License, Version 2.", "end": 32, "score": 0.9995041489601135, "start": 21, "tag": "NAME", "value": "Peter Monks" }, { "context": "ini\n \"SXM\" (alpha-2-to-flag \"SX\") ; Sint Maarten (Dutch part)\n \"SYC\" (alpha-2-to-flag \"SC\") ", "end": 13026, "score": 0.988798201084137, "start": 13019, "tag": "NAME", "value": "Maarten" } ]
src/futbot/flags.clj
pmonks/futbot
3
; ; Copyright © 2020 Peter Monks ; ; 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. ; ; SPDX-License-Identifier: Apache-2.0 ; (ns futbot.flags (:require [clojure.string :as s] [futbot.iso-3166 :as iso-3166])) (defn alpha-2-to-flag "Returns the emoji flag (e.g. '🇦🇺', '🇺🇸') for a valid ISO-3166-1 alpha-2 country code (e.g. 'AU', 'US', etc.), or another Unicode character for invalid country codes." [iso-3166-1-alpha-2] (let [code-point-offset 127397 country-code (if (= "UK" (s/upper-case iso-3166-1-alpha-2)) "GB" (s/upper-case iso-3166-1-alpha-2))] (str (doto (StringBuilder.) (.appendCodePoint (+ code-point-offset (int (first country-code)))) (.appendCodePoint (+ code-point-offset (int (second country-code)))))))) (def alpha-3-to-flag { "ABW" (alpha-2-to-flag "AW") ; Aruba "AFG" (alpha-2-to-flag "AF") ; Afghanistan "AGO" (alpha-2-to-flag "AO") ; Angola "AIA" (alpha-2-to-flag "AI") ; Anguilla "ALA" (alpha-2-to-flag "AX") ; Åland Islands "ALB" (alpha-2-to-flag "AL") ; Albania "AND" (alpha-2-to-flag "AD") ; Andorra "ARE" (alpha-2-to-flag "AE") ; United Arab Emirates (the) "ARG" (alpha-2-to-flag "AR") ; Argentina "ARM" (alpha-2-to-flag "AM") ; Armenia "ASM" (alpha-2-to-flag "AS") ; American Samoa "ATA" (alpha-2-to-flag "AQ") ; Antarctica "ATF" (alpha-2-to-flag "TF") ; French Southern Territories (the) "ATG" (alpha-2-to-flag "AG") ; Antigua and Barbuda "AUS" (alpha-2-to-flag "AU") ; Australia "AUT" (alpha-2-to-flag "AT") ; Austria "AZE" (alpha-2-to-flag "AZ") ; Azerbaijan "BDI" (alpha-2-to-flag "BI") ; Burundi "BEL" (alpha-2-to-flag "BE") ; Belgium "BEN" (alpha-2-to-flag "BJ") ; Benin "BES" (alpha-2-to-flag "BQ") ; Bonaire, Sint Eustatius and Saba "BFA" (alpha-2-to-flag "BF") ; Burkina Faso "BGD" (alpha-2-to-flag "BD") ; Bangladesh "BGR" (alpha-2-to-flag "BG") ; Bulgaria "BHR" (alpha-2-to-flag "BH") ; Bahrain "BHS" (alpha-2-to-flag "BS") ; Bahamas (the) "BIH" (alpha-2-to-flag "BA") ; Bosnia and Herzegovina "BLM" (alpha-2-to-flag "BL") ; Saint Barthélemy "BLR" (alpha-2-to-flag "BY") ; Belarus "BLZ" (alpha-2-to-flag "BZ") ; Belize "BMU" (alpha-2-to-flag "BM") ; Bermuda "BOL" (alpha-2-to-flag "BO") ; Bolivia (Plurinational State of) "BRA" (alpha-2-to-flag "BR") ; Brazil "BRB" (alpha-2-to-flag "BB") ; Barbados "BRN" (alpha-2-to-flag "BN") ; Brunei Darussalam "BTN" (alpha-2-to-flag "BT") ; Bhutan "BVT" (alpha-2-to-flag "BV") ; Bouvet Island "BWA" (alpha-2-to-flag "BW") ; Botswana "CAF" (alpha-2-to-flag "CF") ; Central African Republic (the) "CAN" (alpha-2-to-flag "CA") ; Canada "CCK" (alpha-2-to-flag "CC") ; Cocos (Keeling) Islands (the) "CHE" (alpha-2-to-flag "CH") ; Switzerland "CHL" (alpha-2-to-flag "CL") ; Chile "CHN" (alpha-2-to-flag "CN") ; China "CIV" (alpha-2-to-flag "CI") ; Côte d'Ivoire "CMR" (alpha-2-to-flag "CM") ; Cameroon "COD" (alpha-2-to-flag "CD") ; Congo (the Democratic Republic of the) "COG" (alpha-2-to-flag "CG") ; Congo (the) "COK" (alpha-2-to-flag "CK") ; Cook Islands (the) "COL" (alpha-2-to-flag "CO") ; Colombia "COM" (alpha-2-to-flag "KM") ; Comoros (the) "CPV" (alpha-2-to-flag "CV") ; Cabo Verde "CRI" (alpha-2-to-flag "CR") ; Costa Rica "CUB" (alpha-2-to-flag "CU") ; Cuba "CUW" (alpha-2-to-flag "CW") ; Curaçao "CXR" (alpha-2-to-flag "CX") ; Christmas Island "CYM" (alpha-2-to-flag "KY") ; Cayman Islands (the) "CYP" (alpha-2-to-flag "CY") ; Cyprus "CZE" (alpha-2-to-flag "CZ") ; Czechia "DEU" (alpha-2-to-flag "DE") ; Germany "DJI" (alpha-2-to-flag "DJ") ; Djibouti "DMA" (alpha-2-to-flag "DM") ; Dominica "DNK" (alpha-2-to-flag "DK") ; Denmark "DOM" (alpha-2-to-flag "DO") ; Dominican Republic (the) "DZA" (alpha-2-to-flag "DZ") ; Algeria "ECU" (alpha-2-to-flag "EC") ; Ecuador "EGY" (alpha-2-to-flag "EG") ; Egypt "ERI" (alpha-2-to-flag "ER") ; Eritrea "ESH" (alpha-2-to-flag "EH") ; Western Sahara "ESP" (alpha-2-to-flag "ES") ; Spain "EST" (alpha-2-to-flag "EE") ; Estonia "ETH" (alpha-2-to-flag "ET") ; Ethiopia "FIN" (alpha-2-to-flag "FI") ; Finland "FJI" (alpha-2-to-flag "FJ") ; Fiji "FLK" (alpha-2-to-flag "FK") ; Falkland Islands (the) [Malvinas] "FRA" (alpha-2-to-flag "FR") ; France "FRO" (alpha-2-to-flag "FO") ; Faroe Islands (the) "FSM" (alpha-2-to-flag "FM") ; Micronesia (Federated States of) "GAB" (alpha-2-to-flag "GA") ; Gabon "GBR" (alpha-2-to-flag "GB") ; United Kingdom of Great Britain and Northern Ireland (the) "GEO" (alpha-2-to-flag "GE") ; Georgia "GGY" (alpha-2-to-flag "GG") ; Guernsey "GHA" (alpha-2-to-flag "GH") ; Ghana "GIB" (alpha-2-to-flag "GI") ; Gibraltar "GIN" (alpha-2-to-flag "GN") ; Guinea "GLP" (alpha-2-to-flag "GP") ; Guadeloupe "GMB" (alpha-2-to-flag "GM") ; Gambia (the) "GNB" (alpha-2-to-flag "GW") ; Guinea-Bissau "GNQ" (alpha-2-to-flag "GQ") ; Equatorial Guinea "GRC" (alpha-2-to-flag "GR") ; Greece "GRD" (alpha-2-to-flag "GD") ; Grenada "GRL" (alpha-2-to-flag "GL") ; Greenland "GTM" (alpha-2-to-flag "GT") ; Guatemala "GUF" (alpha-2-to-flag "GF") ; French Guiana "GUM" (alpha-2-to-flag "GU") ; Guam "GUY" (alpha-2-to-flag "GY") ; Guyana "HKG" (alpha-2-to-flag "HK") ; Hong Kong "HMD" (alpha-2-to-flag "HM") ; Heard Island and McDonald Islands "HND" (alpha-2-to-flag "HN") ; Honduras "HRV" (alpha-2-to-flag "HR") ; Croatia "HTI" (alpha-2-to-flag "HT") ; Haiti "HUN" (alpha-2-to-flag "HU") ; Hungary "IDN" (alpha-2-to-flag "ID") ; Indonesia "IMN" (alpha-2-to-flag "IM") ; Isle of Man "IND" (alpha-2-to-flag "IN") ; India "IOT" (alpha-2-to-flag "IO") ; British Indian Ocean Territory (the) "IRL" (alpha-2-to-flag "IE") ; Ireland "IRN" (alpha-2-to-flag "IR") ; Iran (Islamic Republic of) "IRQ" (alpha-2-to-flag "IQ") ; Iraq "ISL" (alpha-2-to-flag "IS") ; Iceland "ISR" (alpha-2-to-flag "IL") ; Israel "ITA" (alpha-2-to-flag "IT") ; Italy "JAM" (alpha-2-to-flag "JM") ; Jamaica "JEY" (alpha-2-to-flag "JE") ; Jersey "JOR" (alpha-2-to-flag "JO") ; Jordan "JPN" (alpha-2-to-flag "JP") ; Japan "KAZ" (alpha-2-to-flag "KZ") ; Kazakhstan "KEN" (alpha-2-to-flag "KE") ; Kenya "KGZ" (alpha-2-to-flag "KG") ; Kyrgyzstan "KHM" (alpha-2-to-flag "KH") ; Cambodia "KIR" (alpha-2-to-flag "KI") ; Kiribati "KNA" (alpha-2-to-flag "KN") ; Saint Kitts and Nevis "KOR" (alpha-2-to-flag "KR") ; Korea (the Republic of) "KWT" (alpha-2-to-flag "KW") ; Kuwait "LAO" (alpha-2-to-flag "LA") ; Lao People's Democratic Republic (the) "LBN" (alpha-2-to-flag "LB") ; Lebanon "LBR" (alpha-2-to-flag "LR") ; Liberia "LBY" (alpha-2-to-flag "LY") ; Libya "LCA" (alpha-2-to-flag "LC") ; Saint Lucia "LIE" (alpha-2-to-flag "LI") ; Liechtenstein "LKA" (alpha-2-to-flag "LK") ; Sri Lanka "LSO" (alpha-2-to-flag "LS") ; Lesotho "LTU" (alpha-2-to-flag "LT") ; Lithuania "LUX" (alpha-2-to-flag "LU") ; Luxembourg "LVA" (alpha-2-to-flag "LV") ; Latvia "MAC" (alpha-2-to-flag "MO") ; Macao "MAF" (alpha-2-to-flag "MF") ; Saint Martin (French part) "MAR" (alpha-2-to-flag "MA") ; Morocco "MCO" (alpha-2-to-flag "MC") ; Monaco "MDA" (alpha-2-to-flag "MD") ; Moldova (the Republic of) "MDG" (alpha-2-to-flag "MG") ; Madagascar "MDV" (alpha-2-to-flag "MV") ; Maldives "MEX" (alpha-2-to-flag "MX") ; Mexico "MHL" (alpha-2-to-flag "MH") ; Marshall Islands (the) "MKD" (alpha-2-to-flag "MK") ; Republic of North Macedonia "MLI" (alpha-2-to-flag "ML") ; Mali "MLT" (alpha-2-to-flag "MT") ; Malta "MMR" (alpha-2-to-flag "MM") ; Myanmar "MNE" (alpha-2-to-flag "ME") ; Montenegro "MNG" (alpha-2-to-flag "MN") ; Mongolia "MNP" (alpha-2-to-flag "MP") ; Northern Mariana Islands (the) "MOZ" (alpha-2-to-flag "MZ") ; Mozambique "MRT" (alpha-2-to-flag "MR") ; Mauritania "MSR" (alpha-2-to-flag "MS") ; Montserrat "MTQ" (alpha-2-to-flag "MQ") ; Martinique "MUS" (alpha-2-to-flag "MU") ; Mauritius "MWI" (alpha-2-to-flag "MW") ; Malawi "MYS" (alpha-2-to-flag "MY") ; Malaysia "MYT" (alpha-2-to-flag "YT") ; Mayotte "NAM" (alpha-2-to-flag "NA") ; Namibia "NCL" (alpha-2-to-flag "NC") ; New Caledonia "NER" (alpha-2-to-flag "NE") ; Niger (the) "NFK" (alpha-2-to-flag "NF") ; Norfolk Island "NGA" (alpha-2-to-flag "NG") ; Nigeria "NIC" (alpha-2-to-flag "NI") ; Nicaragua "NIU" (alpha-2-to-flag "NU") ; Niue "NLD" (alpha-2-to-flag "NL") ; Netherlands (the) "NOR" (alpha-2-to-flag "NO") ; Norway "NPL" (alpha-2-to-flag "NP") ; Nepal "NRU" (alpha-2-to-flag "NR") ; Nauru "NZL" (alpha-2-to-flag "NZ") ; New Zealand "OMN" (alpha-2-to-flag "OM") ; Oman "PAK" (alpha-2-to-flag "PK") ; Pakistan "PAN" (alpha-2-to-flag "PA") ; Panama "PCN" (alpha-2-to-flag "PN") ; Pitcairn "PER" (alpha-2-to-flag "PE") ; Peru "PHL" (alpha-2-to-flag "PH") ; Philippines (the) "PLW" (alpha-2-to-flag "PW") ; Palau "PNG" (alpha-2-to-flag "PG") ; Papua New Guinea "POL" (alpha-2-to-flag "PL") ; Poland "PRI" (alpha-2-to-flag "PR") ; Puerto Rico "PRK" (alpha-2-to-flag "KP") ; Korea (the Democratic People's Republic of) "PRT" (alpha-2-to-flag "PT") ; Portugal "PRY" (alpha-2-to-flag "PY") ; Paraguay "PSE" (alpha-2-to-flag "PS") ; Palestine, State of "PYF" (alpha-2-to-flag "PF") ; French Polynesia "QAT" (alpha-2-to-flag "QA") ; Qatar "REU" (alpha-2-to-flag "RE") ; Réunion "ROU" (alpha-2-to-flag "RO") ; Romania "RUS" (alpha-2-to-flag "RU") ; Russian Federation (the) "RWA" (alpha-2-to-flag "RW") ; Rwanda "SAU" (alpha-2-to-flag "SA") ; Saudi Arabia "SDN" (alpha-2-to-flag "SD") ; Sudan (the) "SEN" (alpha-2-to-flag "SN") ; Senegal "SGP" (alpha-2-to-flag "SG") ; Singapore "SGS" (alpha-2-to-flag "GS") ; South Georgia and the South Sandwich Islands "SHN" (alpha-2-to-flag "SH") ; Saint Helena, Ascension and Tristan da Cunha "SJM" (alpha-2-to-flag "SJ") ; Svalbard and Jan Mayen "SLB" (alpha-2-to-flag "SB") ; Solomon Islands "SLE" (alpha-2-to-flag "SL") ; Sierra Leone "SLV" (alpha-2-to-flag "SV") ; El Salvador "SMR" (alpha-2-to-flag "SM") ; San Marino "SOM" (alpha-2-to-flag "SO") ; Somalia "SPM" (alpha-2-to-flag "PM") ; Saint Pierre and Miquelon "SRB" (alpha-2-to-flag "RS") ; Serbia "SSD" (alpha-2-to-flag "SS") ; South Sudan "STP" (alpha-2-to-flag "ST") ; Sao Tome and Principe "SUR" (alpha-2-to-flag "SR") ; Suriname "SVK" (alpha-2-to-flag "SK") ; Slovakia "SVN" (alpha-2-to-flag "SI") ; Slovenia "SWE" (alpha-2-to-flag "SE") ; Sweden "SWZ" (alpha-2-to-flag "SZ") ; Eswatini "SXM" (alpha-2-to-flag "SX") ; Sint Maarten (Dutch part) "SYC" (alpha-2-to-flag "SC") ; Seychelles "SYR" (alpha-2-to-flag "SY") ; Syrian Arab Republic "TCA" (alpha-2-to-flag "TC") ; Turks and Caicos Islands (the) "TCD" (alpha-2-to-flag "TD") ; Chad "TGO" (alpha-2-to-flag "TG") ; Togo "THA" (alpha-2-to-flag "TH") ; Thailand "TJK" (alpha-2-to-flag "TJ") ; Tajikistan "TKL" (alpha-2-to-flag "TK") ; Tokelau "TKM" (alpha-2-to-flag "TM") ; Turkmenistan "TLS" (alpha-2-to-flag "TL") ; Timor-Leste "TON" (alpha-2-to-flag "TO") ; Tonga "TTO" (alpha-2-to-flag "TT") ; Trinidad and Tobago "TUN" (alpha-2-to-flag "TN") ; Tunisia "TUR" (alpha-2-to-flag "TR") ; Turkey "TUV" (alpha-2-to-flag "TV") ; Tuvalu "TWN" (alpha-2-to-flag "TW") ; Taiwan (Province of China) "TZA" (alpha-2-to-flag "TZ") ; Tanzania, United Republic of "UGA" (alpha-2-to-flag "UG") ; Uganda "UKR" (alpha-2-to-flag "UA") ; Ukraine "UMI" (alpha-2-to-flag "UM") ; United States Minor Outlying Islands (the) "URY" (alpha-2-to-flag "UY") ; Uruguay "USA" (alpha-2-to-flag "US") ; United States of America (the) "UZB" (alpha-2-to-flag "UZ") ; Uzbekistan "VAT" (alpha-2-to-flag "VA") ; Holy See (the) "VCT" (alpha-2-to-flag "VC") ; Saint Vincent and the Grenadines "VEN" (alpha-2-to-flag "VE") ; Venezuela (Bolivarian Republic of) "VGB" (alpha-2-to-flag "VG") ; Virgin Islands (British) "VIR" (alpha-2-to-flag "VI") ; Virgin Islands (U.S.) "VNM" (alpha-2-to-flag "VN") ; Viet Nam "VUT" (alpha-2-to-flag "VU") ; Vanuatu "WLF" (alpha-2-to-flag "WF") ; Wallis and Futuna "WSM" (alpha-2-to-flag "WS") ; Samoa "YEM" (alpha-2-to-flag "YE") ; Yemen "ZAF" (alpha-2-to-flag "ZA") ; South Africa "ZMB" (alpha-2-to-flag "ZM") ; Zambia "ZWE" (alpha-2-to-flag "ZW") ; Zimbabwe ; 'bonus' 3 letter codes, including some custom ones returned by football-data.org "EUR" (alpha-2-to-flag "EU") ; Europe "INT" (alpha-2-to-flag "UN") ; World "AFR" "🌍" ; Africa "SAM" "🌎" ; South America ; "NAM" "🌎" ; North America ; NAM = Namibia "RSA" (alpha-2-to-flag "ZA") ; South Africa (alternative code) "ENG" "🏴󠁧󠁢󠁥󠁮󠁧󠁿" ; England "SCO" "🏴󠁧󠁢󠁳󠁣󠁴󠁿" ; Scotland "WAL" "🏴󠁧󠁢󠁷󠁬󠁳󠁿" ; Wales "BLK" "🏴" ; Plain black flag "WHT" "🏳" ; Plain white flag "GAY" "🏳️‍🌈" ; Pride flag "TRN" "🏳️‍⚧️" ; Transgender flag "CHK" "🏁" ; Checkered flag "TRI" "🚩" ; Triangular flag "CRX" "🎌" ; Crossed flags "PIR" "🏴‍☠️" ; Pirate flag }) (defn emoji "Returns the emoji flag (a string) for the given country-code (an ISO-3166-1 alpha-2 or alpha-3 code, or one of the 'bonus' 3 letter codes used by football-data.org). Returns nil for invalid 3-letter codes, or another, non-flag Unicode character for an invalid 2-letter code." [country-code] (when country-code (let [code (s/upper-case (s/trim country-code))] (case (count code) 2 (alpha-2-to-flag code) 3 (get alpha-3-to-flag code) nil)))) (defn emoji-from-name "Returns the emoji flag (a string) for the given name, or nil if the name is unknown." [name] (emoji (iso-3166/name-to-alpha-3 name))) (def ^:private custom-flag-urls { "EUR" "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b7/Flag_of_Europe.svg/320px-Flag_of_Europe.svg.png" "INT" "https://upload.wikimedia.org/wikipedia/commons/thumb/1/11/Flag_of_the_United_Nations.png/320px-Flag_of_the_United_Nations.png" "AFR" "https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Flag_of_the_African_Union.svg/320px-Flag_of_the_African_Union.svg.png" "SAM" "https://upload.wikimedia.org/wikipedia/commons/thumb/2/21/Flag_of_South_America_%28proposal%29.svg/320px-Flag_of_South_America_%28proposal%29.svg.png" ; "NAM" "https://upload.wikimedia.org/wikipedia/commons/thumb/4/49/Outline_North_America_%28PSF%29.png/255px-Outline_North_America_%28PSF%29.png" ; NAM = Namibia "ENG" "https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/English_flag.svg/320px-English_flag.svg.png" "SCO" "https://upload.wikimedia.org/wikipedia/commons/thumb/1/10/Flag_of_Scotland.svg/320px-Flag_of_Scotland.svg.png" "WAL" "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a9/Flag_of_Wales_%281959%E2%80%93present%29.svg/320px-Flag_of_Wales_%281959%E2%80%93present%29.svg.png" }) (defn flag-url "Returns a URL (as a string) for a flag image file for the given country-code (an ISO-3166-1 alpha-2 or alpha-3 code). Note: doesn't guarantee that the returned URL can be resolved." [country-code] (when country-code (let [code (s/upper-case (s/trim country-code))] (get custom-flag-urls code (case (count code) 2 (str "https://cdn.jsdelivr.net/gh/stefangabos/world_countries/flags/128x128/" (s/lower-case code) ".png") 3 (flag-url (iso-3166/alpha-3-to-alpha-2 code)) nil))))) (defn flag-url-from-name "Returns a URL (as a string) for a flag image file for the given name, or nil if the name is unknown." [name] (flag-url (iso-3166/name-to-alpha-3 name)))
22542
; ; 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. ; ; SPDX-License-Identifier: Apache-2.0 ; (ns futbot.flags (:require [clojure.string :as s] [futbot.iso-3166 :as iso-3166])) (defn alpha-2-to-flag "Returns the emoji flag (e.g. '🇦🇺', '🇺🇸') for a valid ISO-3166-1 alpha-2 country code (e.g. 'AU', 'US', etc.), or another Unicode character for invalid country codes." [iso-3166-1-alpha-2] (let [code-point-offset 127397 country-code (if (= "UK" (s/upper-case iso-3166-1-alpha-2)) "GB" (s/upper-case iso-3166-1-alpha-2))] (str (doto (StringBuilder.) (.appendCodePoint (+ code-point-offset (int (first country-code)))) (.appendCodePoint (+ code-point-offset (int (second country-code)))))))) (def alpha-3-to-flag { "ABW" (alpha-2-to-flag "AW") ; Aruba "AFG" (alpha-2-to-flag "AF") ; Afghanistan "AGO" (alpha-2-to-flag "AO") ; Angola "AIA" (alpha-2-to-flag "AI") ; Anguilla "ALA" (alpha-2-to-flag "AX") ; Åland Islands "ALB" (alpha-2-to-flag "AL") ; Albania "AND" (alpha-2-to-flag "AD") ; Andorra "ARE" (alpha-2-to-flag "AE") ; United Arab Emirates (the) "ARG" (alpha-2-to-flag "AR") ; Argentina "ARM" (alpha-2-to-flag "AM") ; Armenia "ASM" (alpha-2-to-flag "AS") ; American Samoa "ATA" (alpha-2-to-flag "AQ") ; Antarctica "ATF" (alpha-2-to-flag "TF") ; French Southern Territories (the) "ATG" (alpha-2-to-flag "AG") ; Antigua and Barbuda "AUS" (alpha-2-to-flag "AU") ; Australia "AUT" (alpha-2-to-flag "AT") ; Austria "AZE" (alpha-2-to-flag "AZ") ; Azerbaijan "BDI" (alpha-2-to-flag "BI") ; Burundi "BEL" (alpha-2-to-flag "BE") ; Belgium "BEN" (alpha-2-to-flag "BJ") ; Benin "BES" (alpha-2-to-flag "BQ") ; Bonaire, Sint Eustatius and Saba "BFA" (alpha-2-to-flag "BF") ; Burkina Faso "BGD" (alpha-2-to-flag "BD") ; Bangladesh "BGR" (alpha-2-to-flag "BG") ; Bulgaria "BHR" (alpha-2-to-flag "BH") ; Bahrain "BHS" (alpha-2-to-flag "BS") ; Bahamas (the) "BIH" (alpha-2-to-flag "BA") ; Bosnia and Herzegovina "BLM" (alpha-2-to-flag "BL") ; Saint Barthélemy "BLR" (alpha-2-to-flag "BY") ; Belarus "BLZ" (alpha-2-to-flag "BZ") ; Belize "BMU" (alpha-2-to-flag "BM") ; Bermuda "BOL" (alpha-2-to-flag "BO") ; Bolivia (Plurinational State of) "BRA" (alpha-2-to-flag "BR") ; Brazil "BRB" (alpha-2-to-flag "BB") ; Barbados "BRN" (alpha-2-to-flag "BN") ; Brunei Darussalam "BTN" (alpha-2-to-flag "BT") ; Bhutan "BVT" (alpha-2-to-flag "BV") ; Bouvet Island "BWA" (alpha-2-to-flag "BW") ; Botswana "CAF" (alpha-2-to-flag "CF") ; Central African Republic (the) "CAN" (alpha-2-to-flag "CA") ; Canada "CCK" (alpha-2-to-flag "CC") ; Cocos (Keeling) Islands (the) "CHE" (alpha-2-to-flag "CH") ; Switzerland "CHL" (alpha-2-to-flag "CL") ; Chile "CHN" (alpha-2-to-flag "CN") ; China "CIV" (alpha-2-to-flag "CI") ; Côte d'Ivoire "CMR" (alpha-2-to-flag "CM") ; Cameroon "COD" (alpha-2-to-flag "CD") ; Congo (the Democratic Republic of the) "COG" (alpha-2-to-flag "CG") ; Congo (the) "COK" (alpha-2-to-flag "CK") ; Cook Islands (the) "COL" (alpha-2-to-flag "CO") ; Colombia "COM" (alpha-2-to-flag "KM") ; Comoros (the) "CPV" (alpha-2-to-flag "CV") ; Cabo Verde "CRI" (alpha-2-to-flag "CR") ; Costa Rica "CUB" (alpha-2-to-flag "CU") ; Cuba "CUW" (alpha-2-to-flag "CW") ; Curaçao "CXR" (alpha-2-to-flag "CX") ; Christmas Island "CYM" (alpha-2-to-flag "KY") ; Cayman Islands (the) "CYP" (alpha-2-to-flag "CY") ; Cyprus "CZE" (alpha-2-to-flag "CZ") ; Czechia "DEU" (alpha-2-to-flag "DE") ; Germany "DJI" (alpha-2-to-flag "DJ") ; Djibouti "DMA" (alpha-2-to-flag "DM") ; Dominica "DNK" (alpha-2-to-flag "DK") ; Denmark "DOM" (alpha-2-to-flag "DO") ; Dominican Republic (the) "DZA" (alpha-2-to-flag "DZ") ; Algeria "ECU" (alpha-2-to-flag "EC") ; Ecuador "EGY" (alpha-2-to-flag "EG") ; Egypt "ERI" (alpha-2-to-flag "ER") ; Eritrea "ESH" (alpha-2-to-flag "EH") ; Western Sahara "ESP" (alpha-2-to-flag "ES") ; Spain "EST" (alpha-2-to-flag "EE") ; Estonia "ETH" (alpha-2-to-flag "ET") ; Ethiopia "FIN" (alpha-2-to-flag "FI") ; Finland "FJI" (alpha-2-to-flag "FJ") ; Fiji "FLK" (alpha-2-to-flag "FK") ; Falkland Islands (the) [Malvinas] "FRA" (alpha-2-to-flag "FR") ; France "FRO" (alpha-2-to-flag "FO") ; Faroe Islands (the) "FSM" (alpha-2-to-flag "FM") ; Micronesia (Federated States of) "GAB" (alpha-2-to-flag "GA") ; Gabon "GBR" (alpha-2-to-flag "GB") ; United Kingdom of Great Britain and Northern Ireland (the) "GEO" (alpha-2-to-flag "GE") ; Georgia "GGY" (alpha-2-to-flag "GG") ; Guernsey "GHA" (alpha-2-to-flag "GH") ; Ghana "GIB" (alpha-2-to-flag "GI") ; Gibraltar "GIN" (alpha-2-to-flag "GN") ; Guinea "GLP" (alpha-2-to-flag "GP") ; Guadeloupe "GMB" (alpha-2-to-flag "GM") ; Gambia (the) "GNB" (alpha-2-to-flag "GW") ; Guinea-Bissau "GNQ" (alpha-2-to-flag "GQ") ; Equatorial Guinea "GRC" (alpha-2-to-flag "GR") ; Greece "GRD" (alpha-2-to-flag "GD") ; Grenada "GRL" (alpha-2-to-flag "GL") ; Greenland "GTM" (alpha-2-to-flag "GT") ; Guatemala "GUF" (alpha-2-to-flag "GF") ; French Guiana "GUM" (alpha-2-to-flag "GU") ; Guam "GUY" (alpha-2-to-flag "GY") ; Guyana "HKG" (alpha-2-to-flag "HK") ; Hong Kong "HMD" (alpha-2-to-flag "HM") ; Heard Island and McDonald Islands "HND" (alpha-2-to-flag "HN") ; Honduras "HRV" (alpha-2-to-flag "HR") ; Croatia "HTI" (alpha-2-to-flag "HT") ; Haiti "HUN" (alpha-2-to-flag "HU") ; Hungary "IDN" (alpha-2-to-flag "ID") ; Indonesia "IMN" (alpha-2-to-flag "IM") ; Isle of Man "IND" (alpha-2-to-flag "IN") ; India "IOT" (alpha-2-to-flag "IO") ; British Indian Ocean Territory (the) "IRL" (alpha-2-to-flag "IE") ; Ireland "IRN" (alpha-2-to-flag "IR") ; Iran (Islamic Republic of) "IRQ" (alpha-2-to-flag "IQ") ; Iraq "ISL" (alpha-2-to-flag "IS") ; Iceland "ISR" (alpha-2-to-flag "IL") ; Israel "ITA" (alpha-2-to-flag "IT") ; Italy "JAM" (alpha-2-to-flag "JM") ; Jamaica "JEY" (alpha-2-to-flag "JE") ; Jersey "JOR" (alpha-2-to-flag "JO") ; Jordan "JPN" (alpha-2-to-flag "JP") ; Japan "KAZ" (alpha-2-to-flag "KZ") ; Kazakhstan "KEN" (alpha-2-to-flag "KE") ; Kenya "KGZ" (alpha-2-to-flag "KG") ; Kyrgyzstan "KHM" (alpha-2-to-flag "KH") ; Cambodia "KIR" (alpha-2-to-flag "KI") ; Kiribati "KNA" (alpha-2-to-flag "KN") ; Saint Kitts and Nevis "KOR" (alpha-2-to-flag "KR") ; Korea (the Republic of) "KWT" (alpha-2-to-flag "KW") ; Kuwait "LAO" (alpha-2-to-flag "LA") ; Lao People's Democratic Republic (the) "LBN" (alpha-2-to-flag "LB") ; Lebanon "LBR" (alpha-2-to-flag "LR") ; Liberia "LBY" (alpha-2-to-flag "LY") ; Libya "LCA" (alpha-2-to-flag "LC") ; Saint Lucia "LIE" (alpha-2-to-flag "LI") ; Liechtenstein "LKA" (alpha-2-to-flag "LK") ; Sri Lanka "LSO" (alpha-2-to-flag "LS") ; Lesotho "LTU" (alpha-2-to-flag "LT") ; Lithuania "LUX" (alpha-2-to-flag "LU") ; Luxembourg "LVA" (alpha-2-to-flag "LV") ; Latvia "MAC" (alpha-2-to-flag "MO") ; Macao "MAF" (alpha-2-to-flag "MF") ; Saint Martin (French part) "MAR" (alpha-2-to-flag "MA") ; Morocco "MCO" (alpha-2-to-flag "MC") ; Monaco "MDA" (alpha-2-to-flag "MD") ; Moldova (the Republic of) "MDG" (alpha-2-to-flag "MG") ; Madagascar "MDV" (alpha-2-to-flag "MV") ; Maldives "MEX" (alpha-2-to-flag "MX") ; Mexico "MHL" (alpha-2-to-flag "MH") ; Marshall Islands (the) "MKD" (alpha-2-to-flag "MK") ; Republic of North Macedonia "MLI" (alpha-2-to-flag "ML") ; Mali "MLT" (alpha-2-to-flag "MT") ; Malta "MMR" (alpha-2-to-flag "MM") ; Myanmar "MNE" (alpha-2-to-flag "ME") ; Montenegro "MNG" (alpha-2-to-flag "MN") ; Mongolia "MNP" (alpha-2-to-flag "MP") ; Northern Mariana Islands (the) "MOZ" (alpha-2-to-flag "MZ") ; Mozambique "MRT" (alpha-2-to-flag "MR") ; Mauritania "MSR" (alpha-2-to-flag "MS") ; Montserrat "MTQ" (alpha-2-to-flag "MQ") ; Martinique "MUS" (alpha-2-to-flag "MU") ; Mauritius "MWI" (alpha-2-to-flag "MW") ; Malawi "MYS" (alpha-2-to-flag "MY") ; Malaysia "MYT" (alpha-2-to-flag "YT") ; Mayotte "NAM" (alpha-2-to-flag "NA") ; Namibia "NCL" (alpha-2-to-flag "NC") ; New Caledonia "NER" (alpha-2-to-flag "NE") ; Niger (the) "NFK" (alpha-2-to-flag "NF") ; Norfolk Island "NGA" (alpha-2-to-flag "NG") ; Nigeria "NIC" (alpha-2-to-flag "NI") ; Nicaragua "NIU" (alpha-2-to-flag "NU") ; Niue "NLD" (alpha-2-to-flag "NL") ; Netherlands (the) "NOR" (alpha-2-to-flag "NO") ; Norway "NPL" (alpha-2-to-flag "NP") ; Nepal "NRU" (alpha-2-to-flag "NR") ; Nauru "NZL" (alpha-2-to-flag "NZ") ; New Zealand "OMN" (alpha-2-to-flag "OM") ; Oman "PAK" (alpha-2-to-flag "PK") ; Pakistan "PAN" (alpha-2-to-flag "PA") ; Panama "PCN" (alpha-2-to-flag "PN") ; Pitcairn "PER" (alpha-2-to-flag "PE") ; Peru "PHL" (alpha-2-to-flag "PH") ; Philippines (the) "PLW" (alpha-2-to-flag "PW") ; Palau "PNG" (alpha-2-to-flag "PG") ; Papua New Guinea "POL" (alpha-2-to-flag "PL") ; Poland "PRI" (alpha-2-to-flag "PR") ; Puerto Rico "PRK" (alpha-2-to-flag "KP") ; Korea (the Democratic People's Republic of) "PRT" (alpha-2-to-flag "PT") ; Portugal "PRY" (alpha-2-to-flag "PY") ; Paraguay "PSE" (alpha-2-to-flag "PS") ; Palestine, State of "PYF" (alpha-2-to-flag "PF") ; French Polynesia "QAT" (alpha-2-to-flag "QA") ; Qatar "REU" (alpha-2-to-flag "RE") ; Réunion "ROU" (alpha-2-to-flag "RO") ; Romania "RUS" (alpha-2-to-flag "RU") ; Russian Federation (the) "RWA" (alpha-2-to-flag "RW") ; Rwanda "SAU" (alpha-2-to-flag "SA") ; Saudi Arabia "SDN" (alpha-2-to-flag "SD") ; Sudan (the) "SEN" (alpha-2-to-flag "SN") ; Senegal "SGP" (alpha-2-to-flag "SG") ; Singapore "SGS" (alpha-2-to-flag "GS") ; South Georgia and the South Sandwich Islands "SHN" (alpha-2-to-flag "SH") ; Saint Helena, Ascension and Tristan da Cunha "SJM" (alpha-2-to-flag "SJ") ; Svalbard and Jan Mayen "SLB" (alpha-2-to-flag "SB") ; Solomon Islands "SLE" (alpha-2-to-flag "SL") ; Sierra Leone "SLV" (alpha-2-to-flag "SV") ; El Salvador "SMR" (alpha-2-to-flag "SM") ; San Marino "SOM" (alpha-2-to-flag "SO") ; Somalia "SPM" (alpha-2-to-flag "PM") ; Saint Pierre and Miquelon "SRB" (alpha-2-to-flag "RS") ; Serbia "SSD" (alpha-2-to-flag "SS") ; South Sudan "STP" (alpha-2-to-flag "ST") ; Sao Tome and Principe "SUR" (alpha-2-to-flag "SR") ; Suriname "SVK" (alpha-2-to-flag "SK") ; Slovakia "SVN" (alpha-2-to-flag "SI") ; Slovenia "SWE" (alpha-2-to-flag "SE") ; Sweden "SWZ" (alpha-2-to-flag "SZ") ; Eswatini "SXM" (alpha-2-to-flag "SX") ; Sint <NAME> (Dutch part) "SYC" (alpha-2-to-flag "SC") ; Seychelles "SYR" (alpha-2-to-flag "SY") ; Syrian Arab Republic "TCA" (alpha-2-to-flag "TC") ; Turks and Caicos Islands (the) "TCD" (alpha-2-to-flag "TD") ; Chad "TGO" (alpha-2-to-flag "TG") ; Togo "THA" (alpha-2-to-flag "TH") ; Thailand "TJK" (alpha-2-to-flag "TJ") ; Tajikistan "TKL" (alpha-2-to-flag "TK") ; Tokelau "TKM" (alpha-2-to-flag "TM") ; Turkmenistan "TLS" (alpha-2-to-flag "TL") ; Timor-Leste "TON" (alpha-2-to-flag "TO") ; Tonga "TTO" (alpha-2-to-flag "TT") ; Trinidad and Tobago "TUN" (alpha-2-to-flag "TN") ; Tunisia "TUR" (alpha-2-to-flag "TR") ; Turkey "TUV" (alpha-2-to-flag "TV") ; Tuvalu "TWN" (alpha-2-to-flag "TW") ; Taiwan (Province of China) "TZA" (alpha-2-to-flag "TZ") ; Tanzania, United Republic of "UGA" (alpha-2-to-flag "UG") ; Uganda "UKR" (alpha-2-to-flag "UA") ; Ukraine "UMI" (alpha-2-to-flag "UM") ; United States Minor Outlying Islands (the) "URY" (alpha-2-to-flag "UY") ; Uruguay "USA" (alpha-2-to-flag "US") ; United States of America (the) "UZB" (alpha-2-to-flag "UZ") ; Uzbekistan "VAT" (alpha-2-to-flag "VA") ; Holy See (the) "VCT" (alpha-2-to-flag "VC") ; Saint Vincent and the Grenadines "VEN" (alpha-2-to-flag "VE") ; Venezuela (Bolivarian Republic of) "VGB" (alpha-2-to-flag "VG") ; Virgin Islands (British) "VIR" (alpha-2-to-flag "VI") ; Virgin Islands (U.S.) "VNM" (alpha-2-to-flag "VN") ; Viet Nam "VUT" (alpha-2-to-flag "VU") ; Vanuatu "WLF" (alpha-2-to-flag "WF") ; Wallis and Futuna "WSM" (alpha-2-to-flag "WS") ; Samoa "YEM" (alpha-2-to-flag "YE") ; Yemen "ZAF" (alpha-2-to-flag "ZA") ; South Africa "ZMB" (alpha-2-to-flag "ZM") ; Zambia "ZWE" (alpha-2-to-flag "ZW") ; Zimbabwe ; 'bonus' 3 letter codes, including some custom ones returned by football-data.org "EUR" (alpha-2-to-flag "EU") ; Europe "INT" (alpha-2-to-flag "UN") ; World "AFR" "🌍" ; Africa "SAM" "🌎" ; South America ; "NAM" "🌎" ; North America ; NAM = Namibia "RSA" (alpha-2-to-flag "ZA") ; South Africa (alternative code) "ENG" "🏴󠁧󠁢󠁥󠁮󠁧󠁿" ; England "SCO" "🏴󠁧󠁢󠁳󠁣󠁴󠁿" ; Scotland "WAL" "🏴󠁧󠁢󠁷󠁬󠁳󠁿" ; Wales "BLK" "🏴" ; Plain black flag "WHT" "🏳" ; Plain white flag "GAY" "🏳️‍🌈" ; Pride flag "TRN" "🏳️‍⚧️" ; Transgender flag "CHK" "🏁" ; Checkered flag "TRI" "🚩" ; Triangular flag "CRX" "🎌" ; Crossed flags "PIR" "🏴‍☠️" ; Pirate flag }) (defn emoji "Returns the emoji flag (a string) for the given country-code (an ISO-3166-1 alpha-2 or alpha-3 code, or one of the 'bonus' 3 letter codes used by football-data.org). Returns nil for invalid 3-letter codes, or another, non-flag Unicode character for an invalid 2-letter code." [country-code] (when country-code (let [code (s/upper-case (s/trim country-code))] (case (count code) 2 (alpha-2-to-flag code) 3 (get alpha-3-to-flag code) nil)))) (defn emoji-from-name "Returns the emoji flag (a string) for the given name, or nil if the name is unknown." [name] (emoji (iso-3166/name-to-alpha-3 name))) (def ^:private custom-flag-urls { "EUR" "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b7/Flag_of_Europe.svg/320px-Flag_of_Europe.svg.png" "INT" "https://upload.wikimedia.org/wikipedia/commons/thumb/1/11/Flag_of_the_United_Nations.png/320px-Flag_of_the_United_Nations.png" "AFR" "https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Flag_of_the_African_Union.svg/320px-Flag_of_the_African_Union.svg.png" "SAM" "https://upload.wikimedia.org/wikipedia/commons/thumb/2/21/Flag_of_South_America_%28proposal%29.svg/320px-Flag_of_South_America_%28proposal%29.svg.png" ; "NAM" "https://upload.wikimedia.org/wikipedia/commons/thumb/4/49/Outline_North_America_%28PSF%29.png/255px-Outline_North_America_%28PSF%29.png" ; NAM = Namibia "ENG" "https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/English_flag.svg/320px-English_flag.svg.png" "SCO" "https://upload.wikimedia.org/wikipedia/commons/thumb/1/10/Flag_of_Scotland.svg/320px-Flag_of_Scotland.svg.png" "WAL" "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a9/Flag_of_Wales_%281959%E2%80%93present%29.svg/320px-Flag_of_Wales_%281959%E2%80%93present%29.svg.png" }) (defn flag-url "Returns a URL (as a string) for a flag image file for the given country-code (an ISO-3166-1 alpha-2 or alpha-3 code). Note: doesn't guarantee that the returned URL can be resolved." [country-code] (when country-code (let [code (s/upper-case (s/trim country-code))] (get custom-flag-urls code (case (count code) 2 (str "https://cdn.jsdelivr.net/gh/stefangabos/world_countries/flags/128x128/" (s/lower-case code) ".png") 3 (flag-url (iso-3166/alpha-3-to-alpha-2 code)) nil))))) (defn flag-url-from-name "Returns a URL (as a string) for a flag image file for the given name, or nil if the name is unknown." [name] (flag-url (iso-3166/name-to-alpha-3 name)))
true
; ; Copyright © 2020 PI:NAME:<NAME>END_PI ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; ; SPDX-License-Identifier: Apache-2.0 ; (ns futbot.flags (:require [clojure.string :as s] [futbot.iso-3166 :as iso-3166])) (defn alpha-2-to-flag "Returns the emoji flag (e.g. '🇦🇺', '🇺🇸') for a valid ISO-3166-1 alpha-2 country code (e.g. 'AU', 'US', etc.), or another Unicode character for invalid country codes." [iso-3166-1-alpha-2] (let [code-point-offset 127397 country-code (if (= "UK" (s/upper-case iso-3166-1-alpha-2)) "GB" (s/upper-case iso-3166-1-alpha-2))] (str (doto (StringBuilder.) (.appendCodePoint (+ code-point-offset (int (first country-code)))) (.appendCodePoint (+ code-point-offset (int (second country-code)))))))) (def alpha-3-to-flag { "ABW" (alpha-2-to-flag "AW") ; Aruba "AFG" (alpha-2-to-flag "AF") ; Afghanistan "AGO" (alpha-2-to-flag "AO") ; Angola "AIA" (alpha-2-to-flag "AI") ; Anguilla "ALA" (alpha-2-to-flag "AX") ; Åland Islands "ALB" (alpha-2-to-flag "AL") ; Albania "AND" (alpha-2-to-flag "AD") ; Andorra "ARE" (alpha-2-to-flag "AE") ; United Arab Emirates (the) "ARG" (alpha-2-to-flag "AR") ; Argentina "ARM" (alpha-2-to-flag "AM") ; Armenia "ASM" (alpha-2-to-flag "AS") ; American Samoa "ATA" (alpha-2-to-flag "AQ") ; Antarctica "ATF" (alpha-2-to-flag "TF") ; French Southern Territories (the) "ATG" (alpha-2-to-flag "AG") ; Antigua and Barbuda "AUS" (alpha-2-to-flag "AU") ; Australia "AUT" (alpha-2-to-flag "AT") ; Austria "AZE" (alpha-2-to-flag "AZ") ; Azerbaijan "BDI" (alpha-2-to-flag "BI") ; Burundi "BEL" (alpha-2-to-flag "BE") ; Belgium "BEN" (alpha-2-to-flag "BJ") ; Benin "BES" (alpha-2-to-flag "BQ") ; Bonaire, Sint Eustatius and Saba "BFA" (alpha-2-to-flag "BF") ; Burkina Faso "BGD" (alpha-2-to-flag "BD") ; Bangladesh "BGR" (alpha-2-to-flag "BG") ; Bulgaria "BHR" (alpha-2-to-flag "BH") ; Bahrain "BHS" (alpha-2-to-flag "BS") ; Bahamas (the) "BIH" (alpha-2-to-flag "BA") ; Bosnia and Herzegovina "BLM" (alpha-2-to-flag "BL") ; Saint Barthélemy "BLR" (alpha-2-to-flag "BY") ; Belarus "BLZ" (alpha-2-to-flag "BZ") ; Belize "BMU" (alpha-2-to-flag "BM") ; Bermuda "BOL" (alpha-2-to-flag "BO") ; Bolivia (Plurinational State of) "BRA" (alpha-2-to-flag "BR") ; Brazil "BRB" (alpha-2-to-flag "BB") ; Barbados "BRN" (alpha-2-to-flag "BN") ; Brunei Darussalam "BTN" (alpha-2-to-flag "BT") ; Bhutan "BVT" (alpha-2-to-flag "BV") ; Bouvet Island "BWA" (alpha-2-to-flag "BW") ; Botswana "CAF" (alpha-2-to-flag "CF") ; Central African Republic (the) "CAN" (alpha-2-to-flag "CA") ; Canada "CCK" (alpha-2-to-flag "CC") ; Cocos (Keeling) Islands (the) "CHE" (alpha-2-to-flag "CH") ; Switzerland "CHL" (alpha-2-to-flag "CL") ; Chile "CHN" (alpha-2-to-flag "CN") ; China "CIV" (alpha-2-to-flag "CI") ; Côte d'Ivoire "CMR" (alpha-2-to-flag "CM") ; Cameroon "COD" (alpha-2-to-flag "CD") ; Congo (the Democratic Republic of the) "COG" (alpha-2-to-flag "CG") ; Congo (the) "COK" (alpha-2-to-flag "CK") ; Cook Islands (the) "COL" (alpha-2-to-flag "CO") ; Colombia "COM" (alpha-2-to-flag "KM") ; Comoros (the) "CPV" (alpha-2-to-flag "CV") ; Cabo Verde "CRI" (alpha-2-to-flag "CR") ; Costa Rica "CUB" (alpha-2-to-flag "CU") ; Cuba "CUW" (alpha-2-to-flag "CW") ; Curaçao "CXR" (alpha-2-to-flag "CX") ; Christmas Island "CYM" (alpha-2-to-flag "KY") ; Cayman Islands (the) "CYP" (alpha-2-to-flag "CY") ; Cyprus "CZE" (alpha-2-to-flag "CZ") ; Czechia "DEU" (alpha-2-to-flag "DE") ; Germany "DJI" (alpha-2-to-flag "DJ") ; Djibouti "DMA" (alpha-2-to-flag "DM") ; Dominica "DNK" (alpha-2-to-flag "DK") ; Denmark "DOM" (alpha-2-to-flag "DO") ; Dominican Republic (the) "DZA" (alpha-2-to-flag "DZ") ; Algeria "ECU" (alpha-2-to-flag "EC") ; Ecuador "EGY" (alpha-2-to-flag "EG") ; Egypt "ERI" (alpha-2-to-flag "ER") ; Eritrea "ESH" (alpha-2-to-flag "EH") ; Western Sahara "ESP" (alpha-2-to-flag "ES") ; Spain "EST" (alpha-2-to-flag "EE") ; Estonia "ETH" (alpha-2-to-flag "ET") ; Ethiopia "FIN" (alpha-2-to-flag "FI") ; Finland "FJI" (alpha-2-to-flag "FJ") ; Fiji "FLK" (alpha-2-to-flag "FK") ; Falkland Islands (the) [Malvinas] "FRA" (alpha-2-to-flag "FR") ; France "FRO" (alpha-2-to-flag "FO") ; Faroe Islands (the) "FSM" (alpha-2-to-flag "FM") ; Micronesia (Federated States of) "GAB" (alpha-2-to-flag "GA") ; Gabon "GBR" (alpha-2-to-flag "GB") ; United Kingdom of Great Britain and Northern Ireland (the) "GEO" (alpha-2-to-flag "GE") ; Georgia "GGY" (alpha-2-to-flag "GG") ; Guernsey "GHA" (alpha-2-to-flag "GH") ; Ghana "GIB" (alpha-2-to-flag "GI") ; Gibraltar "GIN" (alpha-2-to-flag "GN") ; Guinea "GLP" (alpha-2-to-flag "GP") ; Guadeloupe "GMB" (alpha-2-to-flag "GM") ; Gambia (the) "GNB" (alpha-2-to-flag "GW") ; Guinea-Bissau "GNQ" (alpha-2-to-flag "GQ") ; Equatorial Guinea "GRC" (alpha-2-to-flag "GR") ; Greece "GRD" (alpha-2-to-flag "GD") ; Grenada "GRL" (alpha-2-to-flag "GL") ; Greenland "GTM" (alpha-2-to-flag "GT") ; Guatemala "GUF" (alpha-2-to-flag "GF") ; French Guiana "GUM" (alpha-2-to-flag "GU") ; Guam "GUY" (alpha-2-to-flag "GY") ; Guyana "HKG" (alpha-2-to-flag "HK") ; Hong Kong "HMD" (alpha-2-to-flag "HM") ; Heard Island and McDonald Islands "HND" (alpha-2-to-flag "HN") ; Honduras "HRV" (alpha-2-to-flag "HR") ; Croatia "HTI" (alpha-2-to-flag "HT") ; Haiti "HUN" (alpha-2-to-flag "HU") ; Hungary "IDN" (alpha-2-to-flag "ID") ; Indonesia "IMN" (alpha-2-to-flag "IM") ; Isle of Man "IND" (alpha-2-to-flag "IN") ; India "IOT" (alpha-2-to-flag "IO") ; British Indian Ocean Territory (the) "IRL" (alpha-2-to-flag "IE") ; Ireland "IRN" (alpha-2-to-flag "IR") ; Iran (Islamic Republic of) "IRQ" (alpha-2-to-flag "IQ") ; Iraq "ISL" (alpha-2-to-flag "IS") ; Iceland "ISR" (alpha-2-to-flag "IL") ; Israel "ITA" (alpha-2-to-flag "IT") ; Italy "JAM" (alpha-2-to-flag "JM") ; Jamaica "JEY" (alpha-2-to-flag "JE") ; Jersey "JOR" (alpha-2-to-flag "JO") ; Jordan "JPN" (alpha-2-to-flag "JP") ; Japan "KAZ" (alpha-2-to-flag "KZ") ; Kazakhstan "KEN" (alpha-2-to-flag "KE") ; Kenya "KGZ" (alpha-2-to-flag "KG") ; Kyrgyzstan "KHM" (alpha-2-to-flag "KH") ; Cambodia "KIR" (alpha-2-to-flag "KI") ; Kiribati "KNA" (alpha-2-to-flag "KN") ; Saint Kitts and Nevis "KOR" (alpha-2-to-flag "KR") ; Korea (the Republic of) "KWT" (alpha-2-to-flag "KW") ; Kuwait "LAO" (alpha-2-to-flag "LA") ; Lao People's Democratic Republic (the) "LBN" (alpha-2-to-flag "LB") ; Lebanon "LBR" (alpha-2-to-flag "LR") ; Liberia "LBY" (alpha-2-to-flag "LY") ; Libya "LCA" (alpha-2-to-flag "LC") ; Saint Lucia "LIE" (alpha-2-to-flag "LI") ; Liechtenstein "LKA" (alpha-2-to-flag "LK") ; Sri Lanka "LSO" (alpha-2-to-flag "LS") ; Lesotho "LTU" (alpha-2-to-flag "LT") ; Lithuania "LUX" (alpha-2-to-flag "LU") ; Luxembourg "LVA" (alpha-2-to-flag "LV") ; Latvia "MAC" (alpha-2-to-flag "MO") ; Macao "MAF" (alpha-2-to-flag "MF") ; Saint Martin (French part) "MAR" (alpha-2-to-flag "MA") ; Morocco "MCO" (alpha-2-to-flag "MC") ; Monaco "MDA" (alpha-2-to-flag "MD") ; Moldova (the Republic of) "MDG" (alpha-2-to-flag "MG") ; Madagascar "MDV" (alpha-2-to-flag "MV") ; Maldives "MEX" (alpha-2-to-flag "MX") ; Mexico "MHL" (alpha-2-to-flag "MH") ; Marshall Islands (the) "MKD" (alpha-2-to-flag "MK") ; Republic of North Macedonia "MLI" (alpha-2-to-flag "ML") ; Mali "MLT" (alpha-2-to-flag "MT") ; Malta "MMR" (alpha-2-to-flag "MM") ; Myanmar "MNE" (alpha-2-to-flag "ME") ; Montenegro "MNG" (alpha-2-to-flag "MN") ; Mongolia "MNP" (alpha-2-to-flag "MP") ; Northern Mariana Islands (the) "MOZ" (alpha-2-to-flag "MZ") ; Mozambique "MRT" (alpha-2-to-flag "MR") ; Mauritania "MSR" (alpha-2-to-flag "MS") ; Montserrat "MTQ" (alpha-2-to-flag "MQ") ; Martinique "MUS" (alpha-2-to-flag "MU") ; Mauritius "MWI" (alpha-2-to-flag "MW") ; Malawi "MYS" (alpha-2-to-flag "MY") ; Malaysia "MYT" (alpha-2-to-flag "YT") ; Mayotte "NAM" (alpha-2-to-flag "NA") ; Namibia "NCL" (alpha-2-to-flag "NC") ; New Caledonia "NER" (alpha-2-to-flag "NE") ; Niger (the) "NFK" (alpha-2-to-flag "NF") ; Norfolk Island "NGA" (alpha-2-to-flag "NG") ; Nigeria "NIC" (alpha-2-to-flag "NI") ; Nicaragua "NIU" (alpha-2-to-flag "NU") ; Niue "NLD" (alpha-2-to-flag "NL") ; Netherlands (the) "NOR" (alpha-2-to-flag "NO") ; Norway "NPL" (alpha-2-to-flag "NP") ; Nepal "NRU" (alpha-2-to-flag "NR") ; Nauru "NZL" (alpha-2-to-flag "NZ") ; New Zealand "OMN" (alpha-2-to-flag "OM") ; Oman "PAK" (alpha-2-to-flag "PK") ; Pakistan "PAN" (alpha-2-to-flag "PA") ; Panama "PCN" (alpha-2-to-flag "PN") ; Pitcairn "PER" (alpha-2-to-flag "PE") ; Peru "PHL" (alpha-2-to-flag "PH") ; Philippines (the) "PLW" (alpha-2-to-flag "PW") ; Palau "PNG" (alpha-2-to-flag "PG") ; Papua New Guinea "POL" (alpha-2-to-flag "PL") ; Poland "PRI" (alpha-2-to-flag "PR") ; Puerto Rico "PRK" (alpha-2-to-flag "KP") ; Korea (the Democratic People's Republic of) "PRT" (alpha-2-to-flag "PT") ; Portugal "PRY" (alpha-2-to-flag "PY") ; Paraguay "PSE" (alpha-2-to-flag "PS") ; Palestine, State of "PYF" (alpha-2-to-flag "PF") ; French Polynesia "QAT" (alpha-2-to-flag "QA") ; Qatar "REU" (alpha-2-to-flag "RE") ; Réunion "ROU" (alpha-2-to-flag "RO") ; Romania "RUS" (alpha-2-to-flag "RU") ; Russian Federation (the) "RWA" (alpha-2-to-flag "RW") ; Rwanda "SAU" (alpha-2-to-flag "SA") ; Saudi Arabia "SDN" (alpha-2-to-flag "SD") ; Sudan (the) "SEN" (alpha-2-to-flag "SN") ; Senegal "SGP" (alpha-2-to-flag "SG") ; Singapore "SGS" (alpha-2-to-flag "GS") ; South Georgia and the South Sandwich Islands "SHN" (alpha-2-to-flag "SH") ; Saint Helena, Ascension and Tristan da Cunha "SJM" (alpha-2-to-flag "SJ") ; Svalbard and Jan Mayen "SLB" (alpha-2-to-flag "SB") ; Solomon Islands "SLE" (alpha-2-to-flag "SL") ; Sierra Leone "SLV" (alpha-2-to-flag "SV") ; El Salvador "SMR" (alpha-2-to-flag "SM") ; San Marino "SOM" (alpha-2-to-flag "SO") ; Somalia "SPM" (alpha-2-to-flag "PM") ; Saint Pierre and Miquelon "SRB" (alpha-2-to-flag "RS") ; Serbia "SSD" (alpha-2-to-flag "SS") ; South Sudan "STP" (alpha-2-to-flag "ST") ; Sao Tome and Principe "SUR" (alpha-2-to-flag "SR") ; Suriname "SVK" (alpha-2-to-flag "SK") ; Slovakia "SVN" (alpha-2-to-flag "SI") ; Slovenia "SWE" (alpha-2-to-flag "SE") ; Sweden "SWZ" (alpha-2-to-flag "SZ") ; Eswatini "SXM" (alpha-2-to-flag "SX") ; Sint PI:NAME:<NAME>END_PI (Dutch part) "SYC" (alpha-2-to-flag "SC") ; Seychelles "SYR" (alpha-2-to-flag "SY") ; Syrian Arab Republic "TCA" (alpha-2-to-flag "TC") ; Turks and Caicos Islands (the) "TCD" (alpha-2-to-flag "TD") ; Chad "TGO" (alpha-2-to-flag "TG") ; Togo "THA" (alpha-2-to-flag "TH") ; Thailand "TJK" (alpha-2-to-flag "TJ") ; Tajikistan "TKL" (alpha-2-to-flag "TK") ; Tokelau "TKM" (alpha-2-to-flag "TM") ; Turkmenistan "TLS" (alpha-2-to-flag "TL") ; Timor-Leste "TON" (alpha-2-to-flag "TO") ; Tonga "TTO" (alpha-2-to-flag "TT") ; Trinidad and Tobago "TUN" (alpha-2-to-flag "TN") ; Tunisia "TUR" (alpha-2-to-flag "TR") ; Turkey "TUV" (alpha-2-to-flag "TV") ; Tuvalu "TWN" (alpha-2-to-flag "TW") ; Taiwan (Province of China) "TZA" (alpha-2-to-flag "TZ") ; Tanzania, United Republic of "UGA" (alpha-2-to-flag "UG") ; Uganda "UKR" (alpha-2-to-flag "UA") ; Ukraine "UMI" (alpha-2-to-flag "UM") ; United States Minor Outlying Islands (the) "URY" (alpha-2-to-flag "UY") ; Uruguay "USA" (alpha-2-to-flag "US") ; United States of America (the) "UZB" (alpha-2-to-flag "UZ") ; Uzbekistan "VAT" (alpha-2-to-flag "VA") ; Holy See (the) "VCT" (alpha-2-to-flag "VC") ; Saint Vincent and the Grenadines "VEN" (alpha-2-to-flag "VE") ; Venezuela (Bolivarian Republic of) "VGB" (alpha-2-to-flag "VG") ; Virgin Islands (British) "VIR" (alpha-2-to-flag "VI") ; Virgin Islands (U.S.) "VNM" (alpha-2-to-flag "VN") ; Viet Nam "VUT" (alpha-2-to-flag "VU") ; Vanuatu "WLF" (alpha-2-to-flag "WF") ; Wallis and Futuna "WSM" (alpha-2-to-flag "WS") ; Samoa "YEM" (alpha-2-to-flag "YE") ; Yemen "ZAF" (alpha-2-to-flag "ZA") ; South Africa "ZMB" (alpha-2-to-flag "ZM") ; Zambia "ZWE" (alpha-2-to-flag "ZW") ; Zimbabwe ; 'bonus' 3 letter codes, including some custom ones returned by football-data.org "EUR" (alpha-2-to-flag "EU") ; Europe "INT" (alpha-2-to-flag "UN") ; World "AFR" "🌍" ; Africa "SAM" "🌎" ; South America ; "NAM" "🌎" ; North America ; NAM = Namibia "RSA" (alpha-2-to-flag "ZA") ; South Africa (alternative code) "ENG" "🏴󠁧󠁢󠁥󠁮󠁧󠁿" ; England "SCO" "🏴󠁧󠁢󠁳󠁣󠁴󠁿" ; Scotland "WAL" "🏴󠁧󠁢󠁷󠁬󠁳󠁿" ; Wales "BLK" "🏴" ; Plain black flag "WHT" "🏳" ; Plain white flag "GAY" "🏳️‍🌈" ; Pride flag "TRN" "🏳️‍⚧️" ; Transgender flag "CHK" "🏁" ; Checkered flag "TRI" "🚩" ; Triangular flag "CRX" "🎌" ; Crossed flags "PIR" "🏴‍☠️" ; Pirate flag }) (defn emoji "Returns the emoji flag (a string) for the given country-code (an ISO-3166-1 alpha-2 or alpha-3 code, or one of the 'bonus' 3 letter codes used by football-data.org). Returns nil for invalid 3-letter codes, or another, non-flag Unicode character for an invalid 2-letter code." [country-code] (when country-code (let [code (s/upper-case (s/trim country-code))] (case (count code) 2 (alpha-2-to-flag code) 3 (get alpha-3-to-flag code) nil)))) (defn emoji-from-name "Returns the emoji flag (a string) for the given name, or nil if the name is unknown." [name] (emoji (iso-3166/name-to-alpha-3 name))) (def ^:private custom-flag-urls { "EUR" "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b7/Flag_of_Europe.svg/320px-Flag_of_Europe.svg.png" "INT" "https://upload.wikimedia.org/wikipedia/commons/thumb/1/11/Flag_of_the_United_Nations.png/320px-Flag_of_the_United_Nations.png" "AFR" "https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Flag_of_the_African_Union.svg/320px-Flag_of_the_African_Union.svg.png" "SAM" "https://upload.wikimedia.org/wikipedia/commons/thumb/2/21/Flag_of_South_America_%28proposal%29.svg/320px-Flag_of_South_America_%28proposal%29.svg.png" ; "NAM" "https://upload.wikimedia.org/wikipedia/commons/thumb/4/49/Outline_North_America_%28PSF%29.png/255px-Outline_North_America_%28PSF%29.png" ; NAM = Namibia "ENG" "https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/English_flag.svg/320px-English_flag.svg.png" "SCO" "https://upload.wikimedia.org/wikipedia/commons/thumb/1/10/Flag_of_Scotland.svg/320px-Flag_of_Scotland.svg.png" "WAL" "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a9/Flag_of_Wales_%281959%E2%80%93present%29.svg/320px-Flag_of_Wales_%281959%E2%80%93present%29.svg.png" }) (defn flag-url "Returns a URL (as a string) for a flag image file for the given country-code (an ISO-3166-1 alpha-2 or alpha-3 code). Note: doesn't guarantee that the returned URL can be resolved." [country-code] (when country-code (let [code (s/upper-case (s/trim country-code))] (get custom-flag-urls code (case (count code) 2 (str "https://cdn.jsdelivr.net/gh/stefangabos/world_countries/flags/128x128/" (s/lower-case code) ".png") 3 (flag-url (iso-3166/alpha-3-to-alpha-2 code)) nil))))) (defn flag-url-from-name "Returns a URL (as a string) for a flag image file for the given name, or nil if the name is unknown." [name] (flag-url (iso-3166/name-to-alpha-3 name)))
[ { "context": ";; Copyright (c) 2014-2016 Andrey Antukh <niwi@niwi.nz>\n;; Copyright (c) 2014-2016 Alejand", "end": 40, "score": 0.999893844127655, "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.9999279379844666, "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.9998893737792969, "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.9999338984489441, "start": 100, "tag": "EMAIL", "value": "alejandro@dialelo.com" } ]
src/cats/protocols.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.protocols "A collection of protocols upon which the cats abstractions are built. NOTE: Functions of this namespace are not intended to be used directly. It is considered internal api.") (defprotocol Context "A marker protocol for identifying the valid context types.") (defprotocol Contextual "Abstraction that establishes a concrete type as a member of a context. A great example is the Maybe monad type Just. It implements this abstraction to establish that Just is part of the Maybe monad." (-get-context [_] "Get the context associated with the type.")) (defprotocol Printable "An abstraction to make a type printable in a platform independent manner." (-repr ^String [_] "Get the repl ready representation of the object.")) (defprotocol Semigroup "A structure with an associative binary operation." (-mappend [s sv sv'] "An associative addition operation.")) (defprotocol Monoid "A Semigroup which has an identity element with respect to an associative binary operation." (-mempty [s] "The identity element for the given monoid.")) (defprotocol Extract "A type class to extract the value from a monad context." (-extract [mv] "Extract the value from monad context.")) (defprotocol Functor "A data type that can be mapped over without altering its context." (-fmap [ftor f fv] "Applies function f to the value(s) inside the context of the functor fv.")) (defprotocol Bifunctor "A 'Functor' of two arguments." (-bimap [btor f g bv] "Map over both arguments at the same time.")) (defprotocol Applicative "The Applicative abstraction." (-fapply [app af av] "Applies the function(s) inside af's context to the value(s) inside av's context while preserving the context.") (-pure [app v] "Takes any context or monadic value `app` and any value `v`, and puts the value `v` in the most minimal context (normally `mempty`) of same type of `app`")) (defprotocol Foldable "Abstraction of data structures that can be folded to a summary value." (-foldl [fctx f z xs] "Left-associative fold of a structure.") (-foldr [fctx f z xs] "Right-associative fold of a structure.")) (defprotocol Traversable "Abstraction of data structures that can be traversed from left to right performing an action on every element." (-traverse [tctx f tv] "Map each element to an Applicative, evaluate the applicatives from left to right and collect the results.")) (defprotocol Monad "The Monad abstraction." (-mreturn [m v]) (-mbind [m mv f])) (defprotocol MonadZero "A complement abstraction for monad that supports the notion of an identity element." (-mzero [m] "The identity element for the given monadzero.")) (defprotocol MonadPlus "A complement abstraction for Monad that supports the notion of addition." (-mplus [m mv mv'] "An associative addition operation."))
62607
;; 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.protocols "A collection of protocols upon which the cats abstractions are built. NOTE: Functions of this namespace are not intended to be used directly. It is considered internal api.") (defprotocol Context "A marker protocol for identifying the valid context types.") (defprotocol Contextual "Abstraction that establishes a concrete type as a member of a context. A great example is the Maybe monad type Just. It implements this abstraction to establish that Just is part of the Maybe monad." (-get-context [_] "Get the context associated with the type.")) (defprotocol Printable "An abstraction to make a type printable in a platform independent manner." (-repr ^String [_] "Get the repl ready representation of the object.")) (defprotocol Semigroup "A structure with an associative binary operation." (-mappend [s sv sv'] "An associative addition operation.")) (defprotocol Monoid "A Semigroup which has an identity element with respect to an associative binary operation." (-mempty [s] "The identity element for the given monoid.")) (defprotocol Extract "A type class to extract the value from a monad context." (-extract [mv] "Extract the value from monad context.")) (defprotocol Functor "A data type that can be mapped over without altering its context." (-fmap [ftor f fv] "Applies function f to the value(s) inside the context of the functor fv.")) (defprotocol Bifunctor "A 'Functor' of two arguments." (-bimap [btor f g bv] "Map over both arguments at the same time.")) (defprotocol Applicative "The Applicative abstraction." (-fapply [app af av] "Applies the function(s) inside af's context to the value(s) inside av's context while preserving the context.") (-pure [app v] "Takes any context or monadic value `app` and any value `v`, and puts the value `v` in the most minimal context (normally `mempty`) of same type of `app`")) (defprotocol Foldable "Abstraction of data structures that can be folded to a summary value." (-foldl [fctx f z xs] "Left-associative fold of a structure.") (-foldr [fctx f z xs] "Right-associative fold of a structure.")) (defprotocol Traversable "Abstraction of data structures that can be traversed from left to right performing an action on every element." (-traverse [tctx f tv] "Map each element to an Applicative, evaluate the applicatives from left to right and collect the results.")) (defprotocol Monad "The Monad abstraction." (-mreturn [m v]) (-mbind [m mv f])) (defprotocol MonadZero "A complement abstraction for monad that supports the notion of an identity element." (-mzero [m] "The identity element for the given monadzero.")) (defprotocol MonadPlus "A complement abstraction for Monad that supports the notion of addition." (-mplus [m mv mv'] "An associative addition operation."))
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.protocols "A collection of protocols upon which the cats abstractions are built. NOTE: Functions of this namespace are not intended to be used directly. It is considered internal api.") (defprotocol Context "A marker protocol for identifying the valid context types.") (defprotocol Contextual "Abstraction that establishes a concrete type as a member of a context. A great example is the Maybe monad type Just. It implements this abstraction to establish that Just is part of the Maybe monad." (-get-context [_] "Get the context associated with the type.")) (defprotocol Printable "An abstraction to make a type printable in a platform independent manner." (-repr ^String [_] "Get the repl ready representation of the object.")) (defprotocol Semigroup "A structure with an associative binary operation." (-mappend [s sv sv'] "An associative addition operation.")) (defprotocol Monoid "A Semigroup which has an identity element with respect to an associative binary operation." (-mempty [s] "The identity element for the given monoid.")) (defprotocol Extract "A type class to extract the value from a monad context." (-extract [mv] "Extract the value from monad context.")) (defprotocol Functor "A data type that can be mapped over without altering its context." (-fmap [ftor f fv] "Applies function f to the value(s) inside the context of the functor fv.")) (defprotocol Bifunctor "A 'Functor' of two arguments." (-bimap [btor f g bv] "Map over both arguments at the same time.")) (defprotocol Applicative "The Applicative abstraction." (-fapply [app af av] "Applies the function(s) inside af's context to the value(s) inside av's context while preserving the context.") (-pure [app v] "Takes any context or monadic value `app` and any value `v`, and puts the value `v` in the most minimal context (normally `mempty`) of same type of `app`")) (defprotocol Foldable "Abstraction of data structures that can be folded to a summary value." (-foldl [fctx f z xs] "Left-associative fold of a structure.") (-foldr [fctx f z xs] "Right-associative fold of a structure.")) (defprotocol Traversable "Abstraction of data structures that can be traversed from left to right performing an action on every element." (-traverse [tctx f tv] "Map each element to an Applicative, evaluate the applicatives from left to right and collect the results.")) (defprotocol Monad "The Monad abstraction." (-mreturn [m v]) (-mbind [m mv f])) (defprotocol MonadZero "A complement abstraction for monad that supports the notion of an identity element." (-mzero [m] "The identity element for the given monadzero.")) (defprotocol MonadPlus "A complement abstraction for Monad that supports the notion of addition." (-mplus [m mv mv'] "An associative addition operation."))
[ { "context": "ken) #\"\\|\")]\n {:username username :passwordHash passwordHash}))\n\n(defn valid-auth-token? [token]\n (if (not to", "end": 702, "score": 0.8032117486000061, "start": 690, "tag": "PASSWORD", "value": "passwordHash" } ]
src/ontrail/auth.clj
jrosti/ontrail
1
(ns ontrail.auth (:use ontrail.user ontrail.crypto)) (use '[clojure.string :only (split)]) (def #^{:private true} logger (org.slf4j.LoggerFactory/getLogger (str *ns*))) (defn authenticate [username password] (let [user (get-case-user username) is-match (and (not (= user nil)) (password-match? password (:passwordHash user)))] is-match)) (defn hash-part [password-hash] (if password-hash (last (.split password-hash "\\$")) "")) (defn auth-token [user] (encrypt (str (:username user) "|" (hash-part (:passwordHash user))))) (defn user-from-token [token] (let [[username, passwordHash] (split (decrypt token) #"\|")] {:username username :passwordHash passwordHash})) (defn valid-auth-token? [token] (if (not token) false (let [from-token (user-from-token token) user (if from-token (get-user (:username from-token)) {})] (and user (= (:passwordHash from-token) (hash-part (:passwordHash user))))))) (defn user-from-cookie [cookies] (try (:username (user-from-token (:value (cookies "authToken")))) (catch Exception exception (.trace logger (str "Could not get user from cookie " exception)) "nobody")))
76189
(ns ontrail.auth (:use ontrail.user ontrail.crypto)) (use '[clojure.string :only (split)]) (def #^{:private true} logger (org.slf4j.LoggerFactory/getLogger (str *ns*))) (defn authenticate [username password] (let [user (get-case-user username) is-match (and (not (= user nil)) (password-match? password (:passwordHash user)))] is-match)) (defn hash-part [password-hash] (if password-hash (last (.split password-hash "\\$")) "")) (defn auth-token [user] (encrypt (str (:username user) "|" (hash-part (:passwordHash user))))) (defn user-from-token [token] (let [[username, passwordHash] (split (decrypt token) #"\|")] {:username username :passwordHash <PASSWORD>})) (defn valid-auth-token? [token] (if (not token) false (let [from-token (user-from-token token) user (if from-token (get-user (:username from-token)) {})] (and user (= (:passwordHash from-token) (hash-part (:passwordHash user))))))) (defn user-from-cookie [cookies] (try (:username (user-from-token (:value (cookies "authToken")))) (catch Exception exception (.trace logger (str "Could not get user from cookie " exception)) "nobody")))
true
(ns ontrail.auth (:use ontrail.user ontrail.crypto)) (use '[clojure.string :only (split)]) (def #^{:private true} logger (org.slf4j.LoggerFactory/getLogger (str *ns*))) (defn authenticate [username password] (let [user (get-case-user username) is-match (and (not (= user nil)) (password-match? password (:passwordHash user)))] is-match)) (defn hash-part [password-hash] (if password-hash (last (.split password-hash "\\$")) "")) (defn auth-token [user] (encrypt (str (:username user) "|" (hash-part (:passwordHash user))))) (defn user-from-token [token] (let [[username, passwordHash] (split (decrypt token) #"\|")] {:username username :passwordHash PI:PASSWORD:<PASSWORD>END_PI})) (defn valid-auth-token? [token] (if (not token) false (let [from-token (user-from-token token) user (if from-token (get-user (:username from-token)) {})] (and user (= (:passwordHash from-token) (hash-part (:passwordHash user))))))) (defn user-from-cookie [cookies] (try (:username (user-from-token (:value (cookies "authToken")))) (catch Exception exception (.trace logger (str "Could not get user from cookie " exception)) "nobody")))
[ { "context": "rate\n; Date: March 17, 2016.\n; Authors:\n; A01371743 Luis Eduardo Ballinas Aguilar\n;------------------", "end": 150, "score": 0.9954205751419067, "start": 141, "tag": "USERNAME", "value": "A01371743" }, { "context": "e: March 17, 2016.\n; Authors:\n; A01371743 Luis Eduardo Ballinas Aguilar\n;------------------------------------------------", "end": 180, "score": 0.9998570680618286, "start": 151, "tag": "NAME", "value": "Luis Eduardo Ballinas Aguilar" } ]
4clojure/problem_62.clj
lu15v/TC2006
0
;---------------------------------------------------------- ; Problem 62: Re-implement Iterate ; Date: March 17, 2016. ; Authors: ; A01371743 Luis Eduardo Ballinas Aguilar ;---------------------------------------------------------- (use 'clojure.test) (def problem62 (fn [fx n] (lazy-seq (cons n (problem62 fx (fx n)))))) (deftest test-problem62 (is (= (take 5 (problem62 #(* 2 %) 1)) [1 2 4 8 16])) (is (= (take 100 (problem62 inc 0)) (take 100 (range)))) (is (= (take 9 (problem62 #(inc (mod % 3)) 1)) (take 9 (cycle [1 2 3]))))) (run-tests)
75072
;---------------------------------------------------------- ; Problem 62: Re-implement Iterate ; Date: March 17, 2016. ; Authors: ; A01371743 <NAME> ;---------------------------------------------------------- (use 'clojure.test) (def problem62 (fn [fx n] (lazy-seq (cons n (problem62 fx (fx n)))))) (deftest test-problem62 (is (= (take 5 (problem62 #(* 2 %) 1)) [1 2 4 8 16])) (is (= (take 100 (problem62 inc 0)) (take 100 (range)))) (is (= (take 9 (problem62 #(inc (mod % 3)) 1)) (take 9 (cycle [1 2 3]))))) (run-tests)
true
;---------------------------------------------------------- ; Problem 62: Re-implement Iterate ; Date: March 17, 2016. ; Authors: ; A01371743 PI:NAME:<NAME>END_PI ;---------------------------------------------------------- (use 'clojure.test) (def problem62 (fn [fx n] (lazy-seq (cons n (problem62 fx (fx n)))))) (deftest test-problem62 (is (= (take 5 (problem62 #(* 2 %) 1)) [1 2 4 8 16])) (is (= (take 100 (problem62 inc 0)) (take 100 (range)))) (is (= (take 9 (problem62 #(inc (mod % 3)) 1)) (take 9 (cycle [1 2 3]))))) (run-tests)
[ { "context": " \"stack-name\"\n :key \"stack-name\"\n :underlineShow false\n :required ", "end": 871, "score": 0.6213630437850952, "start": 867, "tag": "KEY", "value": "name" }, { "context": " \"stack-editor\"\n :key \"stack-editor\"\n :validations \"isValidCompose\"\n :multi", "end": 1133, "score": 0.7800037860870361, "start": 1127, "tag": "KEY", "value": "editor" } ]
ch16/swarmpit/src/cljs/swarmpit/component/stack/compose.cljs
vincestorm/Docker-on-Amazon-Web-Services
0
(ns swarmpit.component.stack.compose (:require [material.icon :as icon] [material.component :as comp] [material.component.form :as form] [material.component.panel :as panel] [swarmpit.component.editor :as editor] [swarmpit.component.state :as state] [swarmpit.component.mixin :as mixin] [swarmpit.component.message :as message] [swarmpit.component.progress :as progress] [swarmpit.ajax :as ajax] [swarmpit.routes :as routes] [swarmpit.url :refer [dispatch!]] [sablono.core :refer-macros [html]] [rum.core :as rum])) (enable-console-print!) (def editor-id "compose") (defn form-name [value] (form/comp "STACK NAME" (comp/vtext-field {:name "stack-name" :key "stack-name" :underlineShow false :required true :disabled true :value value}))) (defn- form-editor [value] (comp/vtext-field {:id editor-id :name "stack-editor" :key "stack-editor" :validations "isValidCompose" :multiLine true :rows 10 :rowsMax 10 :value value :underlineShow false :fullWidth true})) (defn- update-stack-handler [name] (ajax/post (routes/path-for-backend :stack-update {:name name}) {:params (state/get-value state/form-value-cursor) :state [:processing?] :on-success (fn [{:keys [origin?]}] (when origin? (dispatch! (routes/path-for-frontend :stack-info {:name name}))) (message/info (str "Stack " name " has been updated."))) :on-error (fn [{:keys [response]}] (message/error (str "Stack update failed. " (:error response))))})) (defn- compose-handler [name] (ajax/get (routes/path-for-backend :stack-compose {:name name}) {:state [:loading?] :on-success (fn [{:keys [response]}] (state/set-value response state/form-value-cursor))})) (def mixin-init-editor {:did-mount (fn [state] (let [editor (editor/yaml editor-id)] (.on editor "change" (fn [cm] (state/update-value [:spec :compose] (-> cm .getValue) state/form-value-cursor)))) state)}) (defn stackfile-handler [name] (ajax/get (routes/path-for-backend :stack-file {:name name}) {:on-success (fn [{:keys [response]}] (when (:spec response) (state/update-value [:last?] true state/form-state-cursor)) (when (:previousSpec response) (state/update-value [:previous?] true state/form-state-cursor))) :on-error (fn [_] (state/update-value [:last?] false state/form-state-cursor) (state/update-value [:previous?] false state/form-state-cursor))})) (defn- init-form-state [] (state/set-value {:valid? false :last? false :previous? false :loading? true :processing? false} state/form-state-cursor)) (defn- init-form-value [name] (state/set-value {:name name :spec {:compose ""}} state/form-value-cursor)) (def mixin-init-form (mixin/init-form (fn [{{:keys [name]} :params}] (init-form-state) (init-form-value name) (stackfile-handler name) (compose-handler name)))) (rum/defc editor < mixin-init-editor [spec] (form-editor spec)) (def action-menu-item-style {:padding "0px 10px 0px 20px"}) (defn file-select [name value last? previous?] (form/comp "COMPOSE FILE SOURCE" (comp/select-field {:name "cfs" :key "cfs" :required true :inputStyle {:width "270px"} :disabled false :value value} (comp/menu-item {:key "current" :innerDivStyle action-menu-item-style :href (routes/path-for-frontend :stack-compose {:name name}) :value :current :primaryText "Current engine state"}) (comp/menu-item {:key "last" :innerDivStyle action-menu-item-style :href (routes/path-for-frontend :stack-last {:name name}) :disabled (not last?) :value :last :primaryText "Last deployed"}) (comp/menu-item {:key "previous" :innerDivStyle action-menu-item-style :href (routes/path-for-frontend :stack-previous {:name name}) :disabled (not previous?) :value :previous :primaryText "Previously deployed (rollback)"})))) (rum/defc form-edit [{:keys [name spec]} {:keys [processing? valid? last? previous?]}] [:div [:div.form-panel [:div.form-panel-left (panel/info icon/stacks name)] [:div.form-panel-right (comp/progress-button {:label "Deploy" :disabled (not valid?) :primary true :onTouchTap #(update-stack-handler name)} processing?)]] (form/form {:onValid #(state/update-value [:valid?] true state/form-state-cursor) :onInvalid #(state/update-value [:valid?] false state/form-state-cursor)} (form-name name) (html (file-select name :current last? previous?)) (editor (:compose spec)))]) (rum/defc form < rum/reactive mixin-init-form [_] (let [state (state/react state/form-state-cursor) stackfile (state/react state/form-value-cursor)] (progress/form (:loading? state) (form-edit stackfile state))))
87466
(ns swarmpit.component.stack.compose (:require [material.icon :as icon] [material.component :as comp] [material.component.form :as form] [material.component.panel :as panel] [swarmpit.component.editor :as editor] [swarmpit.component.state :as state] [swarmpit.component.mixin :as mixin] [swarmpit.component.message :as message] [swarmpit.component.progress :as progress] [swarmpit.ajax :as ajax] [swarmpit.routes :as routes] [swarmpit.url :refer [dispatch!]] [sablono.core :refer-macros [html]] [rum.core :as rum])) (enable-console-print!) (def editor-id "compose") (defn form-name [value] (form/comp "STACK NAME" (comp/vtext-field {:name "stack-name" :key "stack-<KEY>" :underlineShow false :required true :disabled true :value value}))) (defn- form-editor [value] (comp/vtext-field {:id editor-id :name "stack-editor" :key "stack-<KEY>" :validations "isValidCompose" :multiLine true :rows 10 :rowsMax 10 :value value :underlineShow false :fullWidth true})) (defn- update-stack-handler [name] (ajax/post (routes/path-for-backend :stack-update {:name name}) {:params (state/get-value state/form-value-cursor) :state [:processing?] :on-success (fn [{:keys [origin?]}] (when origin? (dispatch! (routes/path-for-frontend :stack-info {:name name}))) (message/info (str "Stack " name " has been updated."))) :on-error (fn [{:keys [response]}] (message/error (str "Stack update failed. " (:error response))))})) (defn- compose-handler [name] (ajax/get (routes/path-for-backend :stack-compose {:name name}) {:state [:loading?] :on-success (fn [{:keys [response]}] (state/set-value response state/form-value-cursor))})) (def mixin-init-editor {:did-mount (fn [state] (let [editor (editor/yaml editor-id)] (.on editor "change" (fn [cm] (state/update-value [:spec :compose] (-> cm .getValue) state/form-value-cursor)))) state)}) (defn stackfile-handler [name] (ajax/get (routes/path-for-backend :stack-file {:name name}) {:on-success (fn [{:keys [response]}] (when (:spec response) (state/update-value [:last?] true state/form-state-cursor)) (when (:previousSpec response) (state/update-value [:previous?] true state/form-state-cursor))) :on-error (fn [_] (state/update-value [:last?] false state/form-state-cursor) (state/update-value [:previous?] false state/form-state-cursor))})) (defn- init-form-state [] (state/set-value {:valid? false :last? false :previous? false :loading? true :processing? false} state/form-state-cursor)) (defn- init-form-value [name] (state/set-value {:name name :spec {:compose ""}} state/form-value-cursor)) (def mixin-init-form (mixin/init-form (fn [{{:keys [name]} :params}] (init-form-state) (init-form-value name) (stackfile-handler name) (compose-handler name)))) (rum/defc editor < mixin-init-editor [spec] (form-editor spec)) (def action-menu-item-style {:padding "0px 10px 0px 20px"}) (defn file-select [name value last? previous?] (form/comp "COMPOSE FILE SOURCE" (comp/select-field {:name "cfs" :key "cfs" :required true :inputStyle {:width "270px"} :disabled false :value value} (comp/menu-item {:key "current" :innerDivStyle action-menu-item-style :href (routes/path-for-frontend :stack-compose {:name name}) :value :current :primaryText "Current engine state"}) (comp/menu-item {:key "last" :innerDivStyle action-menu-item-style :href (routes/path-for-frontend :stack-last {:name name}) :disabled (not last?) :value :last :primaryText "Last deployed"}) (comp/menu-item {:key "previous" :innerDivStyle action-menu-item-style :href (routes/path-for-frontend :stack-previous {:name name}) :disabled (not previous?) :value :previous :primaryText "Previously deployed (rollback)"})))) (rum/defc form-edit [{:keys [name spec]} {:keys [processing? valid? last? previous?]}] [:div [:div.form-panel [:div.form-panel-left (panel/info icon/stacks name)] [:div.form-panel-right (comp/progress-button {:label "Deploy" :disabled (not valid?) :primary true :onTouchTap #(update-stack-handler name)} processing?)]] (form/form {:onValid #(state/update-value [:valid?] true state/form-state-cursor) :onInvalid #(state/update-value [:valid?] false state/form-state-cursor)} (form-name name) (html (file-select name :current last? previous?)) (editor (:compose spec)))]) (rum/defc form < rum/reactive mixin-init-form [_] (let [state (state/react state/form-state-cursor) stackfile (state/react state/form-value-cursor)] (progress/form (:loading? state) (form-edit stackfile state))))
true
(ns swarmpit.component.stack.compose (:require [material.icon :as icon] [material.component :as comp] [material.component.form :as form] [material.component.panel :as panel] [swarmpit.component.editor :as editor] [swarmpit.component.state :as state] [swarmpit.component.mixin :as mixin] [swarmpit.component.message :as message] [swarmpit.component.progress :as progress] [swarmpit.ajax :as ajax] [swarmpit.routes :as routes] [swarmpit.url :refer [dispatch!]] [sablono.core :refer-macros [html]] [rum.core :as rum])) (enable-console-print!) (def editor-id "compose") (defn form-name [value] (form/comp "STACK NAME" (comp/vtext-field {:name "stack-name" :key "stack-PI:KEY:<KEY>END_PI" :underlineShow false :required true :disabled true :value value}))) (defn- form-editor [value] (comp/vtext-field {:id editor-id :name "stack-editor" :key "stack-PI:KEY:<KEY>END_PI" :validations "isValidCompose" :multiLine true :rows 10 :rowsMax 10 :value value :underlineShow false :fullWidth true})) (defn- update-stack-handler [name] (ajax/post (routes/path-for-backend :stack-update {:name name}) {:params (state/get-value state/form-value-cursor) :state [:processing?] :on-success (fn [{:keys [origin?]}] (when origin? (dispatch! (routes/path-for-frontend :stack-info {:name name}))) (message/info (str "Stack " name " has been updated."))) :on-error (fn [{:keys [response]}] (message/error (str "Stack update failed. " (:error response))))})) (defn- compose-handler [name] (ajax/get (routes/path-for-backend :stack-compose {:name name}) {:state [:loading?] :on-success (fn [{:keys [response]}] (state/set-value response state/form-value-cursor))})) (def mixin-init-editor {:did-mount (fn [state] (let [editor (editor/yaml editor-id)] (.on editor "change" (fn [cm] (state/update-value [:spec :compose] (-> cm .getValue) state/form-value-cursor)))) state)}) (defn stackfile-handler [name] (ajax/get (routes/path-for-backend :stack-file {:name name}) {:on-success (fn [{:keys [response]}] (when (:spec response) (state/update-value [:last?] true state/form-state-cursor)) (when (:previousSpec response) (state/update-value [:previous?] true state/form-state-cursor))) :on-error (fn [_] (state/update-value [:last?] false state/form-state-cursor) (state/update-value [:previous?] false state/form-state-cursor))})) (defn- init-form-state [] (state/set-value {:valid? false :last? false :previous? false :loading? true :processing? false} state/form-state-cursor)) (defn- init-form-value [name] (state/set-value {:name name :spec {:compose ""}} state/form-value-cursor)) (def mixin-init-form (mixin/init-form (fn [{{:keys [name]} :params}] (init-form-state) (init-form-value name) (stackfile-handler name) (compose-handler name)))) (rum/defc editor < mixin-init-editor [spec] (form-editor spec)) (def action-menu-item-style {:padding "0px 10px 0px 20px"}) (defn file-select [name value last? previous?] (form/comp "COMPOSE FILE SOURCE" (comp/select-field {:name "cfs" :key "cfs" :required true :inputStyle {:width "270px"} :disabled false :value value} (comp/menu-item {:key "current" :innerDivStyle action-menu-item-style :href (routes/path-for-frontend :stack-compose {:name name}) :value :current :primaryText "Current engine state"}) (comp/menu-item {:key "last" :innerDivStyle action-menu-item-style :href (routes/path-for-frontend :stack-last {:name name}) :disabled (not last?) :value :last :primaryText "Last deployed"}) (comp/menu-item {:key "previous" :innerDivStyle action-menu-item-style :href (routes/path-for-frontend :stack-previous {:name name}) :disabled (not previous?) :value :previous :primaryText "Previously deployed (rollback)"})))) (rum/defc form-edit [{:keys [name spec]} {:keys [processing? valid? last? previous?]}] [:div [:div.form-panel [:div.form-panel-left (panel/info icon/stacks name)] [:div.form-panel-right (comp/progress-button {:label "Deploy" :disabled (not valid?) :primary true :onTouchTap #(update-stack-handler name)} processing?)]] (form/form {:onValid #(state/update-value [:valid?] true state/form-state-cursor) :onInvalid #(state/update-value [:valid?] false state/form-state-cursor)} (form-name name) (html (file-select name :current last? previous?)) (editor (:compose spec)))]) (rum/defc form < rum/reactive mixin-init-form [_] (let [state (state/react state/form-state-cursor) stackfile (state/react state/form-value-cursor)] (progress/form (:loading? state) (form-edit stackfile state))))
[ { "context": "ect zip codes\"\n (generate-greetings [{:name \"Mike\" :address {:zip-code 19123}}\n ", "end": 262, "score": 0.9990849494934082, "start": 258, "tag": "NAME", "value": "Mike" }, { "context": "p-code 19123}}\n {:name \"John\" :address {:zip-code 19103}}\n ", "end": 331, "score": 0.9998182654380798, "start": 327, "tag": "NAME", "value": "John" }, { "context": "p-code 19103}}\n {:name \"Jill\" :address {:zip-code 19098}}]) =>\n ", "end": 400, "score": 0.9992004632949829, "start": 396, "tag": "NAME", "value": "Jill" }, { "context": "de 19098}}]) =>\n [\"Hello, Mike, and welcome to the Lambda Bar And Grille!\"\n ", "end": 474, "score": 0.9991058707237244, "start": 470, "tag": "NAME", "value": "Mike" }, { "context": "ar And Grille!\"\n \"Hello, John, and welcome to the Lambda Bar And Grille!\"])\n", "end": 558, "score": 0.9991301894187927, "start": 554, "tag": "NAME", "value": "John" } ]
ClojureExamples/test/mbfpp/test/oo/iterator/lambda_bar_and_grille.clj
cycle-chen/mbfpp-code
4
(ns mbfpp.test.oo.iterator.lambda-bar-and-grille (:use [mbfpp.oo.iterator.lambda-bar-and-grille]) (:use [midje.sweet])) (fact "generate-greetings generates a sequence of greetings for people in the correct zip codes" (generate-greetings [{:name "Mike" :address {:zip-code 19123}} {:name "John" :address {:zip-code 19103}} {:name "Jill" :address {:zip-code 19098}}]) => ["Hello, Mike, and welcome to the Lambda Bar And Grille!" "Hello, John, and welcome to the Lambda Bar And Grille!"])
75211
(ns mbfpp.test.oo.iterator.lambda-bar-and-grille (:use [mbfpp.oo.iterator.lambda-bar-and-grille]) (:use [midje.sweet])) (fact "generate-greetings generates a sequence of greetings for people in the correct zip codes" (generate-greetings [{:name "<NAME>" :address {:zip-code 19123}} {:name "<NAME>" :address {:zip-code 19103}} {:name "<NAME>" :address {:zip-code 19098}}]) => ["Hello, <NAME>, and welcome to the Lambda Bar And Grille!" "Hello, <NAME>, and welcome to the Lambda Bar And Grille!"])
true
(ns mbfpp.test.oo.iterator.lambda-bar-and-grille (:use [mbfpp.oo.iterator.lambda-bar-and-grille]) (:use [midje.sweet])) (fact "generate-greetings generates a sequence of greetings for people in the correct zip codes" (generate-greetings [{:name "PI:NAME:<NAME>END_PI" :address {:zip-code 19123}} {:name "PI:NAME:<NAME>END_PI" :address {:zip-code 19103}} {:name "PI:NAME:<NAME>END_PI" :address {:zip-code 19098}}]) => ["Hello, PI:NAME:<NAME>END_PI, and welcome to the Lambda Bar And Grille!" "Hello, PI:NAME:<NAME>END_PI, and welcome to the Lambda Bar And Grille!"])
[ { "context": " \n {:doc \"photo curation utilities\"\n :author \"palisades dot lakes at gmail dot com\"\n :version \"2021-11-16\"}\n \n (:refer-clojure :", "end": 259, "score": 0.8095436692237854, "start": 223, "tag": "EMAIL", "value": "palisades dot lakes at gmail dot com" }, { "context": "a/~phil/exiftool/#supported\n;; https://github.com/drewnoakes/metadata-extractor-images/wiki/ContentSummary\n#_(", "end": 2321, "score": 0.9996153712272644, "start": 2311, "tag": "USERNAME", "value": "drewnoakes" }, { "context": "\" ;; Hasselblad\n \"3g2\" \"3gp\"\n #_\"ari\" ;; Arri Alexa\n \"arw\" #_\"srf\" #_\"sr2\" ;; Sony\n #_\"bay\"", "end": 2465, "score": 0.9664532542228699, "start": 2455, "tag": "NAME", "value": "Arri Alexa" }, { "context": "selblad\n #_\"3g2\" \n #_\"3gp\"\n \"ari\" ;; Arri Alexa\n \"arw\" \"srf\" \"sr2\" ;; Sony\n \"bay\" ;; Casio\n", "end": 3473, "score": 0.9880805611610413, "start": 3468, "tag": "NAME", "value": "Alexa" } ]
src/main/clojure/palisades/lakes/curate/curate.clj
palisades-lakes/curate
0
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.curate.curate {:doc "photo curation utilities" :author "palisades dot lakes at gmail dot com" :version "2021-11-16"} (:refer-clojure :exclude [replace]) (:require [clojure.set :as set] [clojure.string :as s] [clojure.pprint :as pp] [clojure.java.io :as io] [clojure.stacktrace :as stacktrace]) (:import [java.io File FileInputStream] [java.nio.file Files LinkOption] [java.nio.file.attribute FileTime] [java.security DigestInputStream MessageDigest] [java.time LocalDateTime ZoneOffset] [java.time.format DateTimeFormatter] [java.util Arrays Collections LinkedHashMap Map] [com.drew.imaging ImageMetadataReader] [com.drew.metadata Directory Metadata Tag] #_[com.drew.metadata.exif ExifIFD0Directory ExifSubIFDDirectory])) ;; TODO: force exif keys to lower case, other standardization ;; TODO: detect and label DXO processed files, ;; other image software ;;---------------------------------------------------------------- ;; image files ;;---------------------------------------------------------------- (defn- unix-path "return a unix style pathname string." ^String [^File f] (s/replace (.getPath f) "\\" "/")) ;;---------------------------------------------------------------- (defn- file-prefix ^String [^File f] (let [filename (.getName f) i (s/last-index-of filename ".")] (if (nil? i) filename (s/lower-case (subs filename 0 i))))) ;;---------------------------------------------------------------- (defn- file-type ^String [^File f] (let [filename (.getName f) i (s/last-index-of filename ".") ^String ext (if (nil? i) "" (s/lower-case (subs filename (inc (long i)))))] (if (>= 5 (.length ext) 2) ext ""))) ;;---------------------------------------------------------------- ;; https://en.wikipedia.org/wiki/Raw_image_format#Raw_filename_extensions_and_respective_camera_manufacturers ;; https://sno.phy.queensu.ca/~phil/exiftool/#supported ;; https://github.com/drewnoakes/metadata-extractor-images/wiki/ContentSummary #_(def image-file-type? #{#_"3fr" ;; Hasselblad "3g2" "3gp" #_"ari" ;; Arri Alexa "arw" #_"srf" #_"sr2" ;; Sony #_"bay" ;; Casio "bmp" #_"cri" ;; Cintel #_"crw" "cr2" ;; Canon #_"cap" #_"iiq" #_"eip" ;; Phase One #_"dcs" #_"dcr" #_"drf" #_"k25" #_"kdc" ;; Kodak "dng" ;; Adobe, Leica #_"erf" ;; Epson #_"fff" ;; Imacon/Hasselblad raw "gif" "ico" "jpeg" "jpg" "m4v" #_"mef" ;; Mamiya #_"mdc" ;; Minolta, Agfa #_"mos" ;; Leaf "mov" "mp4" #_"mrw" ;; Minolta, Konica Minolta "nef" #_"nrw" ;; Nikon "orf" ;; Olympus "pcx" #_"pef" #_"ptx" ;; Pentax "png" "psd" #_"pxn" ;; Logitech #_"r3d" ;; RED Digital Cinema "raf" ;; Fuji "raw" ;; Panasonic, Leica "rw2" ;; Panasonic "rwl" ;; Leica #_"rwz" ;; Rawzor "srw" ;; Samsung "tif" "tiff" "webp" "x3f" ;; Sigma }) (def ^:private image-file-type? #{"3fr" ;; Hasselblad #_"3g2" #_"3gp" "ari" ;; Arri Alexa "arw" "srf" "sr2" ;; Sony "bay" ;; Casio "bmp" "cri" ;; Cintel "crw" "cr2" ;; Canon "cap" "iiq" "eip" ;; Phase One "dcs" "dcr" "drf" "k25" "kdc" ;; Kodak "dng" ;; Adobe, Leica "erf" ;; Epson "fff" ;; Imacon/Hasselblad raw #_"gif" "ico" "jpeg" "jpg" "m4v" "mef" ;; Mamiya "mdc" ;; Minolta, Agfa "mos" ;; Leaf #_"mov" #_"mp4" "mrw" ;; Minolta, Konica Minolta "nef" "nrw" ;; Nikon "orf" ;; Olympus "pcx" "pef" "ptx" ;; Pentax "png" "psd" "pxn" ;; Logitech "r3d" ;; RED Digital Cinema "raf" ;; Fuji "raw" ;; Panasonic, Leica "rw2" ;; Panasonic "rwl" ;; Leica "rwz" ;; Rawzor "srw" ;; Samsung "tif" "tiff" "webp" "x3f" ;; Sigma }) ;;---------------------------------------------------------------- (defn- image-file? [^File f] (image-file-type? (file-type f))) ;;---------------------------------------------------------------- (defn image-file-seq "Return a <code>seq</code> of all the files, in any folder under <code>d</code>, that are accepted by <code>image-file?</code>., which at present is just a set of known image file endings." [^File d] (assert (.exists d) (.getPath d)) (filter image-file? (file-seq d))) ;;---------------------------------------------------------------- ;; image metadata ;;---------------------------------------------------------------- (defn- log-error [^Map exif ^File f ^Throwable t] (println "ERROR:" (unix-path f)) (pp/pprint exif) (binding [*err* *out*] (stacktrace/print-cause-trace t)) (throw t)) ;;---------------------------------------------------------------- (defn- directory-map ^Map [^Directory d] (into {} (map (fn [^Tag t] [(.getTagName t) (.getDescription t)]) (.getTags d)))) ;;---------------------------------------------------------------- (defn- exif-maps "Return the image meta data as a map from <code>Directory</code> to a <code>Map</code> of tag-value pairs. I am ignoring the parent-child relation among exif directories, (for now), because metadata-extractor ignores it as well." ^Map [^File f] (let [^Metadata m (try (ImageMetadataReader/readMetadata f) (catch Throwable t (log-error nil f t))) ^Map lhm (LinkedHashMap.)] ;; preserve iteration order, so later looks can give ;; priority to first occurence of a tag. ;; ? might not be a goodf idea (doseq [^Directory d (.getDirectories m)] (.put lhm d (directory-map d))) (Collections/unmodifiableMap lhm))) ;;---------------------------------------------------------------- (defn print-exif [^File f] (pp/pprint (exif-maps f))) ;;---------------------------------------------------------------- (defn format-exif ^String [^File f] (with-out-str (print-exif f))) ;;---------------------------------------------------------------- ;; datetimes ;;---------------------------------------------------------------- (def ^:private datetime-regex #"((?i)date)|((?i)time)") (defn- dt-string? [^String s] (re-find datetime-regex s)) ;;---------------------------------------------------------------- #_(defn exif-map-datetimes ^Map [^Map metadata] (into (sorted-map) (filter #(dt-string? (key %))) exif)) ;;---------------------------------------------------------------- #_(defn print-exif-map-datetimes [^Map exif] (pp/pprint (exif-map-datetimes exif))) ;;---------------------------------------------------------------- #_(defn- directory-has-datetimes? [^Directory d] (loop [tags (seq (.getTags d))] (if (empty? tags) false (let [^Tag tag (first tags)] (if (dt-string? (.getTagName tag)) true (recur (rest tags))))))) ;;---------------------------------------------------------------- #_(defn print-exif-datetimes [^File f] (let [^Metadata m (try (ImageMetadataReader/readMetadata f) (catch Throwable t (binding [*err* *out*] (stacktrace/print-cause-trace t)) (throw t))) ^Iterable ds (.getDirectories m) exif (exif-map-datetimes (exif-maps f))] (doseq [^Directory d (seq ds)] (when (directory-has-datetimes? d) #_(println "----------------------------------------") (println (class d) (.getName d) (.getTagCount d)) (doseq [^Tag tag (.getTags d)] (when (dt-string? (.getTagName tag)) (println (.getTagTypeHex tag) (.getTagName tag) ":" (.getDescription tag)) (println (.toString tag))))) #_(let [^ExifSubIFDDirectory d (.getFirstDirectoryOfType m ExifSubIFDDirectory) date (.getDate d ExifSubIFDDirectory/TAG_DATETIME_ORIGINAL)] (println date))) (when-not (empty? exif) (pp/pprint exif)))) ;;---------------------------------------------------------------- (def ^:private arw-format (DateTimeFormatter/ofPattern "yyyy:MM:dd HH:mm:ss")) (defn- parse-datetime ^LocalDateTime [^String s] (when s (LocalDateTime/parse s arw-format))) (def ^:private file-prefix-format (DateTimeFormatter/ofPattern "yyyyMMdd-HHmmss")) (def ^:private year-format (DateTimeFormatter/ofPattern "yyyy")) (def ^:private month-format (DateTimeFormatter/ofPattern "MM")) ;;---------------------------------------------------------------- (defn- get-all ^Iterable [^Map exif ^String k] (keep #(get % k) (vals exif))) (defn- get-first ^String [^Map exif ^String k] (first (get-all exif k))) ;;---------------------------------------------------------------- #_(defn file-attributes ^Map [^File f] (Files/readAttributes (.toPath f) "*" ^"[Ljava.nio.file.LinkOption;" (make-array LinkOption 0))) ;;---------------------------------------------------------------- #_(defn- filetime-to-localdatetime ^LocalDateTime [^FileTime ft] (LocalDateTime/ofInstant (.toInstant ft) ZoneOffset/UTC)) ;;---------------------------------------------------------------- #_(defn- exif-datetime (^LocalDateTime [^Map exif] (when-not (empty? exif) (parse-datetime (get-first exif "Date/Time")))) (^LocalDateTime [^Map exif ^File f] (try (let [ldt (if (empty? exif) (println "no exif:" (unix-path f)) (exif-datetime exif))] (if (nil? ldt) (let [attributes (file-attributes f) filetime (or (.get attributes "creationTime") (.get attributes "lastModifiedTime") )] (filetime-to-localdatetime filetime)) ldt)) (catch Throwable t (log-error exif f t))))) (defn- exif-datetime (^LocalDateTime [^Map exif ^File f] (try (when-not (empty? exif) (parse-datetime (get-first exif "Date/Time"))) (catch Throwable t (log-error exif f t))))) ;;---------------------------------------------------------------- ;; camera make/model ;;---------------------------------------------------------------- (defn- replace ^String [^String s match ^String replacement] "null safe." (when (and s match) (s/replace s match replacement))) (defn- starts-with? [^String s ^String prefix] "null safe." (when (and s prefix) (.startsWith s prefix))) (defn ends-with? [^String s ^String suffix] "null safe." (when (and s suffix) (.endsWith s suffix))) (defn- lower-case ^String [^String s] "null safe." (when s (s/lower-case s))) ;;---------------------------------------------------------------- (defn- exif-width ^long [^Map exif ^File f] (try (let [exif (exif-maps f) s (or (get-first exif "Exif Image Width") (get-first exif "Image Width")) [n units] (s/split s #"\s")] (when units (assert (= units "pixels"))) (Long/parseLong n)) (catch Throwable t (log-error exif f t)))) ;;---------------------------------------------------------------- (defn- exif-height ^long [^Map exif ^File f] (try (let [s (or (get-first exif "Exif Image Height") (get-first exif "Image Height")) [n units] (s/split s #"\s")] (when units (assert (= units "pixels"))) (Long/parseLong n)) (catch Throwable t (log-error exif f t)))) ;;---------------------------------------------------------------- (defn exif-wxh (^String [^Map exif ^File f] (str (exif-width exif f) "x" (exif-height exif f))) (^String [^File f] (exif-wxh (exif-maps f) f))) ;;---------------------------------------------------------------- (defn- exif-make ^String [^Map exif ^File f] (try (let [exif (exif-maps f) make (replace (lower-case (get-first exif "Make")) " " "") make (if (starts-with? make "nikon") "nikon" make) make (if (starts-with? make "pentax") "pentax" make)] #_(when (nil? make) (println) (println "-----------------------------------------------------") (println "no exif make:" (unix-path f)) (pp/pprint exif)) make) (catch Throwable t (log-error exif f t)))) ;;---------------------------------------------------------------- (defn- exif-model ^String [^Map exif ^File f] (try (let [model (replace (lower-case (get-first exif "Model")) " " "") ^String model (replace model #"[ \-]+" "") ^String model (replace model "*" "")] #_(when (nil? model) (println) (println "-----------------------------------------------------") (println "no exif model:" (unix-path f)) (pp/pprint exif)) model) (catch Throwable t (log-error exif f t)))) ;;---------------------------------------------------------------- (defn exif-camera (^String [^Map exif ^File f] (try (let [^String make (exif-make exif f) ^String model (exif-model exif f) ^String make (if (starts-with? model "hp") "" make) ^String model (replace model make "") make-model (str make model) make-model (replace make-model "pentaxpentax" "pentax")] #_(when (empty? make-model) (println) (println "-----------------------------------------------------") (println "no exif make-model" (unix-path f)) (pp/pprint exif)) make-model) (catch Throwable t (log-error exif f t)))) (^String [^File f] (exif-camera (exif-maps f) f))) ;;---------------------------------------------------------------- (defn exif-software (^String [^Map exif ^File f] (try (get-all exif "Software") (catch Throwable t (log-error exif f t)))) (^String [^File f] (exif-software (exif-maps f) f))) ;;---------------------------------------------------------------- ;; separate camera originals from processed images ;; pairs : [keystring folder] ;; Search for match terminates with 1st success, so order matters (def ^:private processors [["Adobe" "adobe"] ["DxO" "dxo"] ["Image Data" "sony"] ["Microsoft" "microsoft"] ["Nikon Transfer" "nikon"] ["Picasa" "google"] ["Photos 1.5" "apple"] ["PMB" "sony"] ["Roxio" "roxio"] ["Skitch" "skitch"] ["ViewNX" "nikon"]]) (defn exif-processor (^String [^Map exif ^File f] (try (let [^String software (first (exif-software exif f)) processor (when-not (empty? software) (first (keep (fn [[^String k ^String v]] (when (.contains software k) v)) processors)))] (or processor "original")) (catch Throwable t (log-error exif f t)))) (^String [^File f] (exif-processor (exif-maps f) f))) ;;---------------------------------------------------------------- ;; file equality ;;---------------------------------------------------------------- #_(defn- file-checksum [^File file] (let [input (FileInputStream. file) digest (MessageDigest/getInstance "MD5") stream (DigestInputStream. input digest) nbytes (* 1024 1024) buf (byte-array nbytes)] (while (not= -1 (.read stream buf 0 nbytes))) (apply str (map (partial format "%02x") (.digest digest))))) ;;---------------------------------------------------------------- (defn- identical-contents? [^File f0 ^File f1] (let [i0 (FileInputStream. f0) i1 (FileInputStream. f1) n (* 1024 1024) ^bytes b0 (byte-array n) ^bytes b1 (byte-array n)] (loop [] (let [n0 (.read i0 b0 0 n) n1 (.read i1 b1 0 n)] (cond (== -1 n0 n1) true (and (== n0 n1) (Arrays/equals b0 b1)) (recur) :else false))))) ;;---------------------------------------------------------------- ;; renaming ;;---------------------------------------------------------------- (defn- new-path (^File [^File f ^File d ^String version] (try (let [^Map exif (exif-maps f) ^LocalDateTime ldt (exif-datetime exif f) ^String year (if ldt (format "%04d" (.getYear ldt)) "none") ^String month (if ldt (format "%02d" (.getMonthValue ldt)) "no") ^String prefix (if ldt (.format ldt file-prefix-format) (file-prefix f)) ^String ext (file-type f) ^String suffix (or (exif-camera exif f) (file-prefix f)) ^String wxh (exif-wxh exif f) ^String fname (if-not (empty? suffix) (str prefix "-" suffix) prefix) ^String fname (if (ends-with? fname (str "-" wxh)) fname (str fname "-" wxh)) ^String fname (if-not (empty? version) (str fname "-" version) fname) ^String processor (exif-processor exif f) ^String fname (if-not (.equals "original" processor) (str fname "-" processor) fname) ^File new-file (io/file d #_processor year month (str fname "." ext))] new-file) (catch Throwable t (log-error (exif-maps f) f t)))) (^File [^File f ^File d] (new-path f d nil))) ;;---------------------------------------------------------------- (defn- increment-version ^String [^String version] (if (empty? version) "1" (str (inc (Integer/parseInt version))))) ;;---------------------------------------------------------------- (defn rename-image ([^File f0 ^File d echo-new? ^String version] (try (let [^File f1 (new-path f0 d version)] ;; no new path if image file not parsable #_(println (unix-path f0)) (when f1 #_(println (unix-path f1)) (if-not (.exists f1) (do (when echo-new? (println "new:" (unix-path f0)) (println "--->" (unix-path f1))) (io/make-parents f1) (io/copy f0 f1)) (when-not (identical-contents? f0 f1) (rename-image f0 d echo-new? (increment-version version)))))) (catch Throwable t (log-error (exif-maps f0) f0 t)))) ([^File f0 ^File d echo-new?] #_(println) (rename-image f0 d echo-new? nil)) ([^File f0 ^File d] #_(println) (rename-image f0 d false nil))) ;;----------------------------------------------------------------
68535
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.curate.curate {:doc "photo curation utilities" :author "<EMAIL>" :version "2021-11-16"} (:refer-clojure :exclude [replace]) (:require [clojure.set :as set] [clojure.string :as s] [clojure.pprint :as pp] [clojure.java.io :as io] [clojure.stacktrace :as stacktrace]) (:import [java.io File FileInputStream] [java.nio.file Files LinkOption] [java.nio.file.attribute FileTime] [java.security DigestInputStream MessageDigest] [java.time LocalDateTime ZoneOffset] [java.time.format DateTimeFormatter] [java.util Arrays Collections LinkedHashMap Map] [com.drew.imaging ImageMetadataReader] [com.drew.metadata Directory Metadata Tag] #_[com.drew.metadata.exif ExifIFD0Directory ExifSubIFDDirectory])) ;; TODO: force exif keys to lower case, other standardization ;; TODO: detect and label DXO processed files, ;; other image software ;;---------------------------------------------------------------- ;; image files ;;---------------------------------------------------------------- (defn- unix-path "return a unix style pathname string." ^String [^File f] (s/replace (.getPath f) "\\" "/")) ;;---------------------------------------------------------------- (defn- file-prefix ^String [^File f] (let [filename (.getName f) i (s/last-index-of filename ".")] (if (nil? i) filename (s/lower-case (subs filename 0 i))))) ;;---------------------------------------------------------------- (defn- file-type ^String [^File f] (let [filename (.getName f) i (s/last-index-of filename ".") ^String ext (if (nil? i) "" (s/lower-case (subs filename (inc (long i)))))] (if (>= 5 (.length ext) 2) ext ""))) ;;---------------------------------------------------------------- ;; https://en.wikipedia.org/wiki/Raw_image_format#Raw_filename_extensions_and_respective_camera_manufacturers ;; https://sno.phy.queensu.ca/~phil/exiftool/#supported ;; https://github.com/drewnoakes/metadata-extractor-images/wiki/ContentSummary #_(def image-file-type? #{#_"3fr" ;; Hasselblad "3g2" "3gp" #_"ari" ;; <NAME> "arw" #_"srf" #_"sr2" ;; Sony #_"bay" ;; Casio "bmp" #_"cri" ;; Cintel #_"crw" "cr2" ;; Canon #_"cap" #_"iiq" #_"eip" ;; Phase One #_"dcs" #_"dcr" #_"drf" #_"k25" #_"kdc" ;; Kodak "dng" ;; Adobe, Leica #_"erf" ;; Epson #_"fff" ;; Imacon/Hasselblad raw "gif" "ico" "jpeg" "jpg" "m4v" #_"mef" ;; Mamiya #_"mdc" ;; Minolta, Agfa #_"mos" ;; Leaf "mov" "mp4" #_"mrw" ;; Minolta, Konica Minolta "nef" #_"nrw" ;; Nikon "orf" ;; Olympus "pcx" #_"pef" #_"ptx" ;; Pentax "png" "psd" #_"pxn" ;; Logitech #_"r3d" ;; RED Digital Cinema "raf" ;; Fuji "raw" ;; Panasonic, Leica "rw2" ;; Panasonic "rwl" ;; Leica #_"rwz" ;; Rawzor "srw" ;; Samsung "tif" "tiff" "webp" "x3f" ;; Sigma }) (def ^:private image-file-type? #{"3fr" ;; Hasselblad #_"3g2" #_"3gp" "ari" ;; Arri <NAME> "arw" "srf" "sr2" ;; Sony "bay" ;; Casio "bmp" "cri" ;; Cintel "crw" "cr2" ;; Canon "cap" "iiq" "eip" ;; Phase One "dcs" "dcr" "drf" "k25" "kdc" ;; Kodak "dng" ;; Adobe, Leica "erf" ;; Epson "fff" ;; Imacon/Hasselblad raw #_"gif" "ico" "jpeg" "jpg" "m4v" "mef" ;; Mamiya "mdc" ;; Minolta, Agfa "mos" ;; Leaf #_"mov" #_"mp4" "mrw" ;; Minolta, Konica Minolta "nef" "nrw" ;; Nikon "orf" ;; Olympus "pcx" "pef" "ptx" ;; Pentax "png" "psd" "pxn" ;; Logitech "r3d" ;; RED Digital Cinema "raf" ;; Fuji "raw" ;; Panasonic, Leica "rw2" ;; Panasonic "rwl" ;; Leica "rwz" ;; Rawzor "srw" ;; Samsung "tif" "tiff" "webp" "x3f" ;; Sigma }) ;;---------------------------------------------------------------- (defn- image-file? [^File f] (image-file-type? (file-type f))) ;;---------------------------------------------------------------- (defn image-file-seq "Return a <code>seq</code> of all the files, in any folder under <code>d</code>, that are accepted by <code>image-file?</code>., which at present is just a set of known image file endings." [^File d] (assert (.exists d) (.getPath d)) (filter image-file? (file-seq d))) ;;---------------------------------------------------------------- ;; image metadata ;;---------------------------------------------------------------- (defn- log-error [^Map exif ^File f ^Throwable t] (println "ERROR:" (unix-path f)) (pp/pprint exif) (binding [*err* *out*] (stacktrace/print-cause-trace t)) (throw t)) ;;---------------------------------------------------------------- (defn- directory-map ^Map [^Directory d] (into {} (map (fn [^Tag t] [(.getTagName t) (.getDescription t)]) (.getTags d)))) ;;---------------------------------------------------------------- (defn- exif-maps "Return the image meta data as a map from <code>Directory</code> to a <code>Map</code> of tag-value pairs. I am ignoring the parent-child relation among exif directories, (for now), because metadata-extractor ignores it as well." ^Map [^File f] (let [^Metadata m (try (ImageMetadataReader/readMetadata f) (catch Throwable t (log-error nil f t))) ^Map lhm (LinkedHashMap.)] ;; preserve iteration order, so later looks can give ;; priority to first occurence of a tag. ;; ? might not be a goodf idea (doseq [^Directory d (.getDirectories m)] (.put lhm d (directory-map d))) (Collections/unmodifiableMap lhm))) ;;---------------------------------------------------------------- (defn print-exif [^File f] (pp/pprint (exif-maps f))) ;;---------------------------------------------------------------- (defn format-exif ^String [^File f] (with-out-str (print-exif f))) ;;---------------------------------------------------------------- ;; datetimes ;;---------------------------------------------------------------- (def ^:private datetime-regex #"((?i)date)|((?i)time)") (defn- dt-string? [^String s] (re-find datetime-regex s)) ;;---------------------------------------------------------------- #_(defn exif-map-datetimes ^Map [^Map metadata] (into (sorted-map) (filter #(dt-string? (key %))) exif)) ;;---------------------------------------------------------------- #_(defn print-exif-map-datetimes [^Map exif] (pp/pprint (exif-map-datetimes exif))) ;;---------------------------------------------------------------- #_(defn- directory-has-datetimes? [^Directory d] (loop [tags (seq (.getTags d))] (if (empty? tags) false (let [^Tag tag (first tags)] (if (dt-string? (.getTagName tag)) true (recur (rest tags))))))) ;;---------------------------------------------------------------- #_(defn print-exif-datetimes [^File f] (let [^Metadata m (try (ImageMetadataReader/readMetadata f) (catch Throwable t (binding [*err* *out*] (stacktrace/print-cause-trace t)) (throw t))) ^Iterable ds (.getDirectories m) exif (exif-map-datetimes (exif-maps f))] (doseq [^Directory d (seq ds)] (when (directory-has-datetimes? d) #_(println "----------------------------------------") (println (class d) (.getName d) (.getTagCount d)) (doseq [^Tag tag (.getTags d)] (when (dt-string? (.getTagName tag)) (println (.getTagTypeHex tag) (.getTagName tag) ":" (.getDescription tag)) (println (.toString tag))))) #_(let [^ExifSubIFDDirectory d (.getFirstDirectoryOfType m ExifSubIFDDirectory) date (.getDate d ExifSubIFDDirectory/TAG_DATETIME_ORIGINAL)] (println date))) (when-not (empty? exif) (pp/pprint exif)))) ;;---------------------------------------------------------------- (def ^:private arw-format (DateTimeFormatter/ofPattern "yyyy:MM:dd HH:mm:ss")) (defn- parse-datetime ^LocalDateTime [^String s] (when s (LocalDateTime/parse s arw-format))) (def ^:private file-prefix-format (DateTimeFormatter/ofPattern "yyyyMMdd-HHmmss")) (def ^:private year-format (DateTimeFormatter/ofPattern "yyyy")) (def ^:private month-format (DateTimeFormatter/ofPattern "MM")) ;;---------------------------------------------------------------- (defn- get-all ^Iterable [^Map exif ^String k] (keep #(get % k) (vals exif))) (defn- get-first ^String [^Map exif ^String k] (first (get-all exif k))) ;;---------------------------------------------------------------- #_(defn file-attributes ^Map [^File f] (Files/readAttributes (.toPath f) "*" ^"[Ljava.nio.file.LinkOption;" (make-array LinkOption 0))) ;;---------------------------------------------------------------- #_(defn- filetime-to-localdatetime ^LocalDateTime [^FileTime ft] (LocalDateTime/ofInstant (.toInstant ft) ZoneOffset/UTC)) ;;---------------------------------------------------------------- #_(defn- exif-datetime (^LocalDateTime [^Map exif] (when-not (empty? exif) (parse-datetime (get-first exif "Date/Time")))) (^LocalDateTime [^Map exif ^File f] (try (let [ldt (if (empty? exif) (println "no exif:" (unix-path f)) (exif-datetime exif))] (if (nil? ldt) (let [attributes (file-attributes f) filetime (or (.get attributes "creationTime") (.get attributes "lastModifiedTime") )] (filetime-to-localdatetime filetime)) ldt)) (catch Throwable t (log-error exif f t))))) (defn- exif-datetime (^LocalDateTime [^Map exif ^File f] (try (when-not (empty? exif) (parse-datetime (get-first exif "Date/Time"))) (catch Throwable t (log-error exif f t))))) ;;---------------------------------------------------------------- ;; camera make/model ;;---------------------------------------------------------------- (defn- replace ^String [^String s match ^String replacement] "null safe." (when (and s match) (s/replace s match replacement))) (defn- starts-with? [^String s ^String prefix] "null safe." (when (and s prefix) (.startsWith s prefix))) (defn ends-with? [^String s ^String suffix] "null safe." (when (and s suffix) (.endsWith s suffix))) (defn- lower-case ^String [^String s] "null safe." (when s (s/lower-case s))) ;;---------------------------------------------------------------- (defn- exif-width ^long [^Map exif ^File f] (try (let [exif (exif-maps f) s (or (get-first exif "Exif Image Width") (get-first exif "Image Width")) [n units] (s/split s #"\s")] (when units (assert (= units "pixels"))) (Long/parseLong n)) (catch Throwable t (log-error exif f t)))) ;;---------------------------------------------------------------- (defn- exif-height ^long [^Map exif ^File f] (try (let [s (or (get-first exif "Exif Image Height") (get-first exif "Image Height")) [n units] (s/split s #"\s")] (when units (assert (= units "pixels"))) (Long/parseLong n)) (catch Throwable t (log-error exif f t)))) ;;---------------------------------------------------------------- (defn exif-wxh (^String [^Map exif ^File f] (str (exif-width exif f) "x" (exif-height exif f))) (^String [^File f] (exif-wxh (exif-maps f) f))) ;;---------------------------------------------------------------- (defn- exif-make ^String [^Map exif ^File f] (try (let [exif (exif-maps f) make (replace (lower-case (get-first exif "Make")) " " "") make (if (starts-with? make "nikon") "nikon" make) make (if (starts-with? make "pentax") "pentax" make)] #_(when (nil? make) (println) (println "-----------------------------------------------------") (println "no exif make:" (unix-path f)) (pp/pprint exif)) make) (catch Throwable t (log-error exif f t)))) ;;---------------------------------------------------------------- (defn- exif-model ^String [^Map exif ^File f] (try (let [model (replace (lower-case (get-first exif "Model")) " " "") ^String model (replace model #"[ \-]+" "") ^String model (replace model "*" "")] #_(when (nil? model) (println) (println "-----------------------------------------------------") (println "no exif model:" (unix-path f)) (pp/pprint exif)) model) (catch Throwable t (log-error exif f t)))) ;;---------------------------------------------------------------- (defn exif-camera (^String [^Map exif ^File f] (try (let [^String make (exif-make exif f) ^String model (exif-model exif f) ^String make (if (starts-with? model "hp") "" make) ^String model (replace model make "") make-model (str make model) make-model (replace make-model "pentaxpentax" "pentax")] #_(when (empty? make-model) (println) (println "-----------------------------------------------------") (println "no exif make-model" (unix-path f)) (pp/pprint exif)) make-model) (catch Throwable t (log-error exif f t)))) (^String [^File f] (exif-camera (exif-maps f) f))) ;;---------------------------------------------------------------- (defn exif-software (^String [^Map exif ^File f] (try (get-all exif "Software") (catch Throwable t (log-error exif f t)))) (^String [^File f] (exif-software (exif-maps f) f))) ;;---------------------------------------------------------------- ;; separate camera originals from processed images ;; pairs : [keystring folder] ;; Search for match terminates with 1st success, so order matters (def ^:private processors [["Adobe" "adobe"] ["DxO" "dxo"] ["Image Data" "sony"] ["Microsoft" "microsoft"] ["Nikon Transfer" "nikon"] ["Picasa" "google"] ["Photos 1.5" "apple"] ["PMB" "sony"] ["Roxio" "roxio"] ["Skitch" "skitch"] ["ViewNX" "nikon"]]) (defn exif-processor (^String [^Map exif ^File f] (try (let [^String software (first (exif-software exif f)) processor (when-not (empty? software) (first (keep (fn [[^String k ^String v]] (when (.contains software k) v)) processors)))] (or processor "original")) (catch Throwable t (log-error exif f t)))) (^String [^File f] (exif-processor (exif-maps f) f))) ;;---------------------------------------------------------------- ;; file equality ;;---------------------------------------------------------------- #_(defn- file-checksum [^File file] (let [input (FileInputStream. file) digest (MessageDigest/getInstance "MD5") stream (DigestInputStream. input digest) nbytes (* 1024 1024) buf (byte-array nbytes)] (while (not= -1 (.read stream buf 0 nbytes))) (apply str (map (partial format "%02x") (.digest digest))))) ;;---------------------------------------------------------------- (defn- identical-contents? [^File f0 ^File f1] (let [i0 (FileInputStream. f0) i1 (FileInputStream. f1) n (* 1024 1024) ^bytes b0 (byte-array n) ^bytes b1 (byte-array n)] (loop [] (let [n0 (.read i0 b0 0 n) n1 (.read i1 b1 0 n)] (cond (== -1 n0 n1) true (and (== n0 n1) (Arrays/equals b0 b1)) (recur) :else false))))) ;;---------------------------------------------------------------- ;; renaming ;;---------------------------------------------------------------- (defn- new-path (^File [^File f ^File d ^String version] (try (let [^Map exif (exif-maps f) ^LocalDateTime ldt (exif-datetime exif f) ^String year (if ldt (format "%04d" (.getYear ldt)) "none") ^String month (if ldt (format "%02d" (.getMonthValue ldt)) "no") ^String prefix (if ldt (.format ldt file-prefix-format) (file-prefix f)) ^String ext (file-type f) ^String suffix (or (exif-camera exif f) (file-prefix f)) ^String wxh (exif-wxh exif f) ^String fname (if-not (empty? suffix) (str prefix "-" suffix) prefix) ^String fname (if (ends-with? fname (str "-" wxh)) fname (str fname "-" wxh)) ^String fname (if-not (empty? version) (str fname "-" version) fname) ^String processor (exif-processor exif f) ^String fname (if-not (.equals "original" processor) (str fname "-" processor) fname) ^File new-file (io/file d #_processor year month (str fname "." ext))] new-file) (catch Throwable t (log-error (exif-maps f) f t)))) (^File [^File f ^File d] (new-path f d nil))) ;;---------------------------------------------------------------- (defn- increment-version ^String [^String version] (if (empty? version) "1" (str (inc (Integer/parseInt version))))) ;;---------------------------------------------------------------- (defn rename-image ([^File f0 ^File d echo-new? ^String version] (try (let [^File f1 (new-path f0 d version)] ;; no new path if image file not parsable #_(println (unix-path f0)) (when f1 #_(println (unix-path f1)) (if-not (.exists f1) (do (when echo-new? (println "new:" (unix-path f0)) (println "--->" (unix-path f1))) (io/make-parents f1) (io/copy f0 f1)) (when-not (identical-contents? f0 f1) (rename-image f0 d echo-new? (increment-version version)))))) (catch Throwable t (log-error (exif-maps f0) f0 t)))) ([^File f0 ^File d echo-new?] #_(println) (rename-image f0 d echo-new? nil)) ([^File f0 ^File d] #_(println) (rename-image f0 d false nil))) ;;----------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.curate.curate {:doc "photo curation utilities" :author "PI:EMAIL:<EMAIL>END_PI" :version "2021-11-16"} (:refer-clojure :exclude [replace]) (:require [clojure.set :as set] [clojure.string :as s] [clojure.pprint :as pp] [clojure.java.io :as io] [clojure.stacktrace :as stacktrace]) (:import [java.io File FileInputStream] [java.nio.file Files LinkOption] [java.nio.file.attribute FileTime] [java.security DigestInputStream MessageDigest] [java.time LocalDateTime ZoneOffset] [java.time.format DateTimeFormatter] [java.util Arrays Collections LinkedHashMap Map] [com.drew.imaging ImageMetadataReader] [com.drew.metadata Directory Metadata Tag] #_[com.drew.metadata.exif ExifIFD0Directory ExifSubIFDDirectory])) ;; TODO: force exif keys to lower case, other standardization ;; TODO: detect and label DXO processed files, ;; other image software ;;---------------------------------------------------------------- ;; image files ;;---------------------------------------------------------------- (defn- unix-path "return a unix style pathname string." ^String [^File f] (s/replace (.getPath f) "\\" "/")) ;;---------------------------------------------------------------- (defn- file-prefix ^String [^File f] (let [filename (.getName f) i (s/last-index-of filename ".")] (if (nil? i) filename (s/lower-case (subs filename 0 i))))) ;;---------------------------------------------------------------- (defn- file-type ^String [^File f] (let [filename (.getName f) i (s/last-index-of filename ".") ^String ext (if (nil? i) "" (s/lower-case (subs filename (inc (long i)))))] (if (>= 5 (.length ext) 2) ext ""))) ;;---------------------------------------------------------------- ;; https://en.wikipedia.org/wiki/Raw_image_format#Raw_filename_extensions_and_respective_camera_manufacturers ;; https://sno.phy.queensu.ca/~phil/exiftool/#supported ;; https://github.com/drewnoakes/metadata-extractor-images/wiki/ContentSummary #_(def image-file-type? #{#_"3fr" ;; Hasselblad "3g2" "3gp" #_"ari" ;; PI:NAME:<NAME>END_PI "arw" #_"srf" #_"sr2" ;; Sony #_"bay" ;; Casio "bmp" #_"cri" ;; Cintel #_"crw" "cr2" ;; Canon #_"cap" #_"iiq" #_"eip" ;; Phase One #_"dcs" #_"dcr" #_"drf" #_"k25" #_"kdc" ;; Kodak "dng" ;; Adobe, Leica #_"erf" ;; Epson #_"fff" ;; Imacon/Hasselblad raw "gif" "ico" "jpeg" "jpg" "m4v" #_"mef" ;; Mamiya #_"mdc" ;; Minolta, Agfa #_"mos" ;; Leaf "mov" "mp4" #_"mrw" ;; Minolta, Konica Minolta "nef" #_"nrw" ;; Nikon "orf" ;; Olympus "pcx" #_"pef" #_"ptx" ;; Pentax "png" "psd" #_"pxn" ;; Logitech #_"r3d" ;; RED Digital Cinema "raf" ;; Fuji "raw" ;; Panasonic, Leica "rw2" ;; Panasonic "rwl" ;; Leica #_"rwz" ;; Rawzor "srw" ;; Samsung "tif" "tiff" "webp" "x3f" ;; Sigma }) (def ^:private image-file-type? #{"3fr" ;; Hasselblad #_"3g2" #_"3gp" "ari" ;; Arri PI:NAME:<NAME>END_PI "arw" "srf" "sr2" ;; Sony "bay" ;; Casio "bmp" "cri" ;; Cintel "crw" "cr2" ;; Canon "cap" "iiq" "eip" ;; Phase One "dcs" "dcr" "drf" "k25" "kdc" ;; Kodak "dng" ;; Adobe, Leica "erf" ;; Epson "fff" ;; Imacon/Hasselblad raw #_"gif" "ico" "jpeg" "jpg" "m4v" "mef" ;; Mamiya "mdc" ;; Minolta, Agfa "mos" ;; Leaf #_"mov" #_"mp4" "mrw" ;; Minolta, Konica Minolta "nef" "nrw" ;; Nikon "orf" ;; Olympus "pcx" "pef" "ptx" ;; Pentax "png" "psd" "pxn" ;; Logitech "r3d" ;; RED Digital Cinema "raf" ;; Fuji "raw" ;; Panasonic, Leica "rw2" ;; Panasonic "rwl" ;; Leica "rwz" ;; Rawzor "srw" ;; Samsung "tif" "tiff" "webp" "x3f" ;; Sigma }) ;;---------------------------------------------------------------- (defn- image-file? [^File f] (image-file-type? (file-type f))) ;;---------------------------------------------------------------- (defn image-file-seq "Return a <code>seq</code> of all the files, in any folder under <code>d</code>, that are accepted by <code>image-file?</code>., which at present is just a set of known image file endings." [^File d] (assert (.exists d) (.getPath d)) (filter image-file? (file-seq d))) ;;---------------------------------------------------------------- ;; image metadata ;;---------------------------------------------------------------- (defn- log-error [^Map exif ^File f ^Throwable t] (println "ERROR:" (unix-path f)) (pp/pprint exif) (binding [*err* *out*] (stacktrace/print-cause-trace t)) (throw t)) ;;---------------------------------------------------------------- (defn- directory-map ^Map [^Directory d] (into {} (map (fn [^Tag t] [(.getTagName t) (.getDescription t)]) (.getTags d)))) ;;---------------------------------------------------------------- (defn- exif-maps "Return the image meta data as a map from <code>Directory</code> to a <code>Map</code> of tag-value pairs. I am ignoring the parent-child relation among exif directories, (for now), because metadata-extractor ignores it as well." ^Map [^File f] (let [^Metadata m (try (ImageMetadataReader/readMetadata f) (catch Throwable t (log-error nil f t))) ^Map lhm (LinkedHashMap.)] ;; preserve iteration order, so later looks can give ;; priority to first occurence of a tag. ;; ? might not be a goodf idea (doseq [^Directory d (.getDirectories m)] (.put lhm d (directory-map d))) (Collections/unmodifiableMap lhm))) ;;---------------------------------------------------------------- (defn print-exif [^File f] (pp/pprint (exif-maps f))) ;;---------------------------------------------------------------- (defn format-exif ^String [^File f] (with-out-str (print-exif f))) ;;---------------------------------------------------------------- ;; datetimes ;;---------------------------------------------------------------- (def ^:private datetime-regex #"((?i)date)|((?i)time)") (defn- dt-string? [^String s] (re-find datetime-regex s)) ;;---------------------------------------------------------------- #_(defn exif-map-datetimes ^Map [^Map metadata] (into (sorted-map) (filter #(dt-string? (key %))) exif)) ;;---------------------------------------------------------------- #_(defn print-exif-map-datetimes [^Map exif] (pp/pprint (exif-map-datetimes exif))) ;;---------------------------------------------------------------- #_(defn- directory-has-datetimes? [^Directory d] (loop [tags (seq (.getTags d))] (if (empty? tags) false (let [^Tag tag (first tags)] (if (dt-string? (.getTagName tag)) true (recur (rest tags))))))) ;;---------------------------------------------------------------- #_(defn print-exif-datetimes [^File f] (let [^Metadata m (try (ImageMetadataReader/readMetadata f) (catch Throwable t (binding [*err* *out*] (stacktrace/print-cause-trace t)) (throw t))) ^Iterable ds (.getDirectories m) exif (exif-map-datetimes (exif-maps f))] (doseq [^Directory d (seq ds)] (when (directory-has-datetimes? d) #_(println "----------------------------------------") (println (class d) (.getName d) (.getTagCount d)) (doseq [^Tag tag (.getTags d)] (when (dt-string? (.getTagName tag)) (println (.getTagTypeHex tag) (.getTagName tag) ":" (.getDescription tag)) (println (.toString tag))))) #_(let [^ExifSubIFDDirectory d (.getFirstDirectoryOfType m ExifSubIFDDirectory) date (.getDate d ExifSubIFDDirectory/TAG_DATETIME_ORIGINAL)] (println date))) (when-not (empty? exif) (pp/pprint exif)))) ;;---------------------------------------------------------------- (def ^:private arw-format (DateTimeFormatter/ofPattern "yyyy:MM:dd HH:mm:ss")) (defn- parse-datetime ^LocalDateTime [^String s] (when s (LocalDateTime/parse s arw-format))) (def ^:private file-prefix-format (DateTimeFormatter/ofPattern "yyyyMMdd-HHmmss")) (def ^:private year-format (DateTimeFormatter/ofPattern "yyyy")) (def ^:private month-format (DateTimeFormatter/ofPattern "MM")) ;;---------------------------------------------------------------- (defn- get-all ^Iterable [^Map exif ^String k] (keep #(get % k) (vals exif))) (defn- get-first ^String [^Map exif ^String k] (first (get-all exif k))) ;;---------------------------------------------------------------- #_(defn file-attributes ^Map [^File f] (Files/readAttributes (.toPath f) "*" ^"[Ljava.nio.file.LinkOption;" (make-array LinkOption 0))) ;;---------------------------------------------------------------- #_(defn- filetime-to-localdatetime ^LocalDateTime [^FileTime ft] (LocalDateTime/ofInstant (.toInstant ft) ZoneOffset/UTC)) ;;---------------------------------------------------------------- #_(defn- exif-datetime (^LocalDateTime [^Map exif] (when-not (empty? exif) (parse-datetime (get-first exif "Date/Time")))) (^LocalDateTime [^Map exif ^File f] (try (let [ldt (if (empty? exif) (println "no exif:" (unix-path f)) (exif-datetime exif))] (if (nil? ldt) (let [attributes (file-attributes f) filetime (or (.get attributes "creationTime") (.get attributes "lastModifiedTime") )] (filetime-to-localdatetime filetime)) ldt)) (catch Throwable t (log-error exif f t))))) (defn- exif-datetime (^LocalDateTime [^Map exif ^File f] (try (when-not (empty? exif) (parse-datetime (get-first exif "Date/Time"))) (catch Throwable t (log-error exif f t))))) ;;---------------------------------------------------------------- ;; camera make/model ;;---------------------------------------------------------------- (defn- replace ^String [^String s match ^String replacement] "null safe." (when (and s match) (s/replace s match replacement))) (defn- starts-with? [^String s ^String prefix] "null safe." (when (and s prefix) (.startsWith s prefix))) (defn ends-with? [^String s ^String suffix] "null safe." (when (and s suffix) (.endsWith s suffix))) (defn- lower-case ^String [^String s] "null safe." (when s (s/lower-case s))) ;;---------------------------------------------------------------- (defn- exif-width ^long [^Map exif ^File f] (try (let [exif (exif-maps f) s (or (get-first exif "Exif Image Width") (get-first exif "Image Width")) [n units] (s/split s #"\s")] (when units (assert (= units "pixels"))) (Long/parseLong n)) (catch Throwable t (log-error exif f t)))) ;;---------------------------------------------------------------- (defn- exif-height ^long [^Map exif ^File f] (try (let [s (or (get-first exif "Exif Image Height") (get-first exif "Image Height")) [n units] (s/split s #"\s")] (when units (assert (= units "pixels"))) (Long/parseLong n)) (catch Throwable t (log-error exif f t)))) ;;---------------------------------------------------------------- (defn exif-wxh (^String [^Map exif ^File f] (str (exif-width exif f) "x" (exif-height exif f))) (^String [^File f] (exif-wxh (exif-maps f) f))) ;;---------------------------------------------------------------- (defn- exif-make ^String [^Map exif ^File f] (try (let [exif (exif-maps f) make (replace (lower-case (get-first exif "Make")) " " "") make (if (starts-with? make "nikon") "nikon" make) make (if (starts-with? make "pentax") "pentax" make)] #_(when (nil? make) (println) (println "-----------------------------------------------------") (println "no exif make:" (unix-path f)) (pp/pprint exif)) make) (catch Throwable t (log-error exif f t)))) ;;---------------------------------------------------------------- (defn- exif-model ^String [^Map exif ^File f] (try (let [model (replace (lower-case (get-first exif "Model")) " " "") ^String model (replace model #"[ \-]+" "") ^String model (replace model "*" "")] #_(when (nil? model) (println) (println "-----------------------------------------------------") (println "no exif model:" (unix-path f)) (pp/pprint exif)) model) (catch Throwable t (log-error exif f t)))) ;;---------------------------------------------------------------- (defn exif-camera (^String [^Map exif ^File f] (try (let [^String make (exif-make exif f) ^String model (exif-model exif f) ^String make (if (starts-with? model "hp") "" make) ^String model (replace model make "") make-model (str make model) make-model (replace make-model "pentaxpentax" "pentax")] #_(when (empty? make-model) (println) (println "-----------------------------------------------------") (println "no exif make-model" (unix-path f)) (pp/pprint exif)) make-model) (catch Throwable t (log-error exif f t)))) (^String [^File f] (exif-camera (exif-maps f) f))) ;;---------------------------------------------------------------- (defn exif-software (^String [^Map exif ^File f] (try (get-all exif "Software") (catch Throwable t (log-error exif f t)))) (^String [^File f] (exif-software (exif-maps f) f))) ;;---------------------------------------------------------------- ;; separate camera originals from processed images ;; pairs : [keystring folder] ;; Search for match terminates with 1st success, so order matters (def ^:private processors [["Adobe" "adobe"] ["DxO" "dxo"] ["Image Data" "sony"] ["Microsoft" "microsoft"] ["Nikon Transfer" "nikon"] ["Picasa" "google"] ["Photos 1.5" "apple"] ["PMB" "sony"] ["Roxio" "roxio"] ["Skitch" "skitch"] ["ViewNX" "nikon"]]) (defn exif-processor (^String [^Map exif ^File f] (try (let [^String software (first (exif-software exif f)) processor (when-not (empty? software) (first (keep (fn [[^String k ^String v]] (when (.contains software k) v)) processors)))] (or processor "original")) (catch Throwable t (log-error exif f t)))) (^String [^File f] (exif-processor (exif-maps f) f))) ;;---------------------------------------------------------------- ;; file equality ;;---------------------------------------------------------------- #_(defn- file-checksum [^File file] (let [input (FileInputStream. file) digest (MessageDigest/getInstance "MD5") stream (DigestInputStream. input digest) nbytes (* 1024 1024) buf (byte-array nbytes)] (while (not= -1 (.read stream buf 0 nbytes))) (apply str (map (partial format "%02x") (.digest digest))))) ;;---------------------------------------------------------------- (defn- identical-contents? [^File f0 ^File f1] (let [i0 (FileInputStream. f0) i1 (FileInputStream. f1) n (* 1024 1024) ^bytes b0 (byte-array n) ^bytes b1 (byte-array n)] (loop [] (let [n0 (.read i0 b0 0 n) n1 (.read i1 b1 0 n)] (cond (== -1 n0 n1) true (and (== n0 n1) (Arrays/equals b0 b1)) (recur) :else false))))) ;;---------------------------------------------------------------- ;; renaming ;;---------------------------------------------------------------- (defn- new-path (^File [^File f ^File d ^String version] (try (let [^Map exif (exif-maps f) ^LocalDateTime ldt (exif-datetime exif f) ^String year (if ldt (format "%04d" (.getYear ldt)) "none") ^String month (if ldt (format "%02d" (.getMonthValue ldt)) "no") ^String prefix (if ldt (.format ldt file-prefix-format) (file-prefix f)) ^String ext (file-type f) ^String suffix (or (exif-camera exif f) (file-prefix f)) ^String wxh (exif-wxh exif f) ^String fname (if-not (empty? suffix) (str prefix "-" suffix) prefix) ^String fname (if (ends-with? fname (str "-" wxh)) fname (str fname "-" wxh)) ^String fname (if-not (empty? version) (str fname "-" version) fname) ^String processor (exif-processor exif f) ^String fname (if-not (.equals "original" processor) (str fname "-" processor) fname) ^File new-file (io/file d #_processor year month (str fname "." ext))] new-file) (catch Throwable t (log-error (exif-maps f) f t)))) (^File [^File f ^File d] (new-path f d nil))) ;;---------------------------------------------------------------- (defn- increment-version ^String [^String version] (if (empty? version) "1" (str (inc (Integer/parseInt version))))) ;;---------------------------------------------------------------- (defn rename-image ([^File f0 ^File d echo-new? ^String version] (try (let [^File f1 (new-path f0 d version)] ;; no new path if image file not parsable #_(println (unix-path f0)) (when f1 #_(println (unix-path f1)) (if-not (.exists f1) (do (when echo-new? (println "new:" (unix-path f0)) (println "--->" (unix-path f1))) (io/make-parents f1) (io/copy f0 f1)) (when-not (identical-contents? f0 f1) (rename-image f0 d echo-new? (increment-version version)))))) (catch Throwable t (log-error (exif-maps f0) f0 t)))) ([^File f0 ^File d echo-new?] #_(println) (rename-image f0 d echo-new? nil)) ([^File f0 ^File d] #_(println) (rename-image f0 d false nil))) ;;----------------------------------------------------------------
[ { "context": "t` might do.\n(add-message-with-backup (->Message \"John\" \"Message One\"))\n(add-message-with-backup (->Mess", "end": 2975, "score": 0.997133195400238, "start": 2971, "tag": "NAME", "value": "John" }, { "context": "ssage One\"))\n(add-message-with-backup (->Message \"Jane\" \"Message Two\"))\n\n\n;;; Managing Per-Thread State ", "end": 3034, "score": 0.9395777583122253, "start": 3030, "tag": "NAME", "value": "Jane" } ]
clojure/programming-clojure/walkthrough/src/walkthrough/concurrency.clj
waiyaki/learning-lisp
2
;; Prefer `alter` to `commute` when updates are not commutative, and most aren't. (def counter (ref 0)) (defn next-counter [] (dosync (alter counter inc))) ;;; Agents ;; Use agents for asynchronous updates - tasks that can proceed independently with minimal coordination. (def counter (agent 0)) (send counter inc) ;; The call to `send` doesn't return the new value of the agent, returns the agent itself. ;; `send` queues the update-fn to run later and immediately returns. ;; Agents can be dereferenced: @counter ;; => 1 ;; To be sure the agent has completed the actions sent to it, call `await` or `await-for` ;; `(await & agents)` ;; `(await-for timeout-millis & agents)` ;; These will cause the thread to block until all actions sent from current ;; thread or agent have completed. ;; `await-for` returns `nil` if the timeout expires, a non-nil value otherwise. ;; `await` has no timeout, it waits forever. ;;; Validating Agents and Handling Errors ;; Agents can take validation functions ;; `(agent initial-state options*)`, where `options` include: ;; `:validator` validate-fn ;; `:meta` metadata-map ;; `:error-handler` handler-fn ;; `:error-mode` mode-keyword (:continue or :fail) (def counter (agent 0 :validator number?)) (send counter (fn [_] "boo")) @counter ;; => 0 ;; When no `:error-handler` is provided, the error mode will be set to `:fail` (agent-error counter) ;; => #error { ;; :cause "Invalid reference state" ;; :via ;; [{:type java.lang.IllegalStateException ;; :message "Invalid reference state" ;; :at [clojure.lang.ARef validate "ARef.java" 33]}] ;; ... ;; When an agent has an error, all actions will be queued until `restart-agent` is called. ;; When with errors, all subsequent attempts to query the agent will return an error. (restart-agent counter 0) @counter ;; => 0 ;; When an `:error-handler` is provided, the error mode will be set to `:continue` (defn handler [agent err] (println "ERR!! " (.getMessage err))) (def counter2 (agent 0 :validator number? :error-handler handler)) (send counter (fn [_] "boo")) ;; => #agent[{:status :failed, :val 0} 0x457fa6f1] ;;; Including Agents in Transactions ;; Transactions can be retried, so shouldn't have side-effects. ;; If side-effects are desired, agents can be used. ;; If an action is sent to an agent within a transaction, that action is sent exactly once, ;; if and only if the transaction succeeds. ;; Consider an agent that writes to a file when a trx succeeds: (def messages (ref ())) (defrecord Message [sender text]) (def backup-agent (agent "output/messages-backup.clj")) (defn add-message-with-backup [msg] (dosync (let [snapshot (commute messages conj msg)] (send-off backup-agent (fn [filename] (spit filename snapshot) filename))))) ;; `send-off` is a variant of `send` for actions that expect to block, as a file ;; write with `spit` might do. (add-message-with-backup (->Message "John" "Message One")) (add-message-with-backup (->Message "Jane" "Message Two")) ;;; Managing Per-Thread State with Vars ;; When you call `def` or `defn`, you create a `var`. ;; The initial value passed to `def` becomes the **_root binding_** or the `var`. (def ^:dynamic foo 10) ;; The binding of `foo` is shared by all threads foo ;; => 10 (.start (Thread. (fn [] (println foo)))) ;; => nil ;; ==> 10 ;; The call to `.start` returns `nil`, and the value of `foo` is printed from ;; the new thread. ;; Bindings have *dynamic* scope ;; Visible everywhere during a thread's execution, until the thread exits the ;; scope where the binding began. ;; A binding is not visible to other threads. ;; E.g., create a thread local binding for `foo` and check its value. ;; Observe `let` has no effect outside its own form ;; The binding stays in effect down the chain. (binding [foo 42] foo) ;; => 42 (defn print-foo [] (println foo)) (let [foo "let foo"] (print-foo)) ;; => nil ;; ==> 10 (binding [foo "bound foo"] (print-foo)) ;; => nil ;; ==> bound foo ;;; State Models ;; Refs and STM - Coordinated, synchronous updates - Pure functions ;; Atoms - Uncoordinated, synchronous updates - Pure functions ;; Agents - Uncoordinated, asynchronous updates - Any functions ;; Vars - Thread-local dynamic scopes - Any functions ;; Java locks - Coordinated, synchronous updates - Any functions
17352
;; Prefer `alter` to `commute` when updates are not commutative, and most aren't. (def counter (ref 0)) (defn next-counter [] (dosync (alter counter inc))) ;;; Agents ;; Use agents for asynchronous updates - tasks that can proceed independently with minimal coordination. (def counter (agent 0)) (send counter inc) ;; The call to `send` doesn't return the new value of the agent, returns the agent itself. ;; `send` queues the update-fn to run later and immediately returns. ;; Agents can be dereferenced: @counter ;; => 1 ;; To be sure the agent has completed the actions sent to it, call `await` or `await-for` ;; `(await & agents)` ;; `(await-for timeout-millis & agents)` ;; These will cause the thread to block until all actions sent from current ;; thread or agent have completed. ;; `await-for` returns `nil` if the timeout expires, a non-nil value otherwise. ;; `await` has no timeout, it waits forever. ;;; Validating Agents and Handling Errors ;; Agents can take validation functions ;; `(agent initial-state options*)`, where `options` include: ;; `:validator` validate-fn ;; `:meta` metadata-map ;; `:error-handler` handler-fn ;; `:error-mode` mode-keyword (:continue or :fail) (def counter (agent 0 :validator number?)) (send counter (fn [_] "boo")) @counter ;; => 0 ;; When no `:error-handler` is provided, the error mode will be set to `:fail` (agent-error counter) ;; => #error { ;; :cause "Invalid reference state" ;; :via ;; [{:type java.lang.IllegalStateException ;; :message "Invalid reference state" ;; :at [clojure.lang.ARef validate "ARef.java" 33]}] ;; ... ;; When an agent has an error, all actions will be queued until `restart-agent` is called. ;; When with errors, all subsequent attempts to query the agent will return an error. (restart-agent counter 0) @counter ;; => 0 ;; When an `:error-handler` is provided, the error mode will be set to `:continue` (defn handler [agent err] (println "ERR!! " (.getMessage err))) (def counter2 (agent 0 :validator number? :error-handler handler)) (send counter (fn [_] "boo")) ;; => #agent[{:status :failed, :val 0} 0x457fa6f1] ;;; Including Agents in Transactions ;; Transactions can be retried, so shouldn't have side-effects. ;; If side-effects are desired, agents can be used. ;; If an action is sent to an agent within a transaction, that action is sent exactly once, ;; if and only if the transaction succeeds. ;; Consider an agent that writes to a file when a trx succeeds: (def messages (ref ())) (defrecord Message [sender text]) (def backup-agent (agent "output/messages-backup.clj")) (defn add-message-with-backup [msg] (dosync (let [snapshot (commute messages conj msg)] (send-off backup-agent (fn [filename] (spit filename snapshot) filename))))) ;; `send-off` is a variant of `send` for actions that expect to block, as a file ;; write with `spit` might do. (add-message-with-backup (->Message "<NAME>" "Message One")) (add-message-with-backup (->Message "<NAME>" "Message Two")) ;;; Managing Per-Thread State with Vars ;; When you call `def` or `defn`, you create a `var`. ;; The initial value passed to `def` becomes the **_root binding_** or the `var`. (def ^:dynamic foo 10) ;; The binding of `foo` is shared by all threads foo ;; => 10 (.start (Thread. (fn [] (println foo)))) ;; => nil ;; ==> 10 ;; The call to `.start` returns `nil`, and the value of `foo` is printed from ;; the new thread. ;; Bindings have *dynamic* scope ;; Visible everywhere during a thread's execution, until the thread exits the ;; scope where the binding began. ;; A binding is not visible to other threads. ;; E.g., create a thread local binding for `foo` and check its value. ;; Observe `let` has no effect outside its own form ;; The binding stays in effect down the chain. (binding [foo 42] foo) ;; => 42 (defn print-foo [] (println foo)) (let [foo "let foo"] (print-foo)) ;; => nil ;; ==> 10 (binding [foo "bound foo"] (print-foo)) ;; => nil ;; ==> bound foo ;;; State Models ;; Refs and STM - Coordinated, synchronous updates - Pure functions ;; Atoms - Uncoordinated, synchronous updates - Pure functions ;; Agents - Uncoordinated, asynchronous updates - Any functions ;; Vars - Thread-local dynamic scopes - Any functions ;; Java locks - Coordinated, synchronous updates - Any functions
true
;; Prefer `alter` to `commute` when updates are not commutative, and most aren't. (def counter (ref 0)) (defn next-counter [] (dosync (alter counter inc))) ;;; Agents ;; Use agents for asynchronous updates - tasks that can proceed independently with minimal coordination. (def counter (agent 0)) (send counter inc) ;; The call to `send` doesn't return the new value of the agent, returns the agent itself. ;; `send` queues the update-fn to run later and immediately returns. ;; Agents can be dereferenced: @counter ;; => 1 ;; To be sure the agent has completed the actions sent to it, call `await` or `await-for` ;; `(await & agents)` ;; `(await-for timeout-millis & agents)` ;; These will cause the thread to block until all actions sent from current ;; thread or agent have completed. ;; `await-for` returns `nil` if the timeout expires, a non-nil value otherwise. ;; `await` has no timeout, it waits forever. ;;; Validating Agents and Handling Errors ;; Agents can take validation functions ;; `(agent initial-state options*)`, where `options` include: ;; `:validator` validate-fn ;; `:meta` metadata-map ;; `:error-handler` handler-fn ;; `:error-mode` mode-keyword (:continue or :fail) (def counter (agent 0 :validator number?)) (send counter (fn [_] "boo")) @counter ;; => 0 ;; When no `:error-handler` is provided, the error mode will be set to `:fail` (agent-error counter) ;; => #error { ;; :cause "Invalid reference state" ;; :via ;; [{:type java.lang.IllegalStateException ;; :message "Invalid reference state" ;; :at [clojure.lang.ARef validate "ARef.java" 33]}] ;; ... ;; When an agent has an error, all actions will be queued until `restart-agent` is called. ;; When with errors, all subsequent attempts to query the agent will return an error. (restart-agent counter 0) @counter ;; => 0 ;; When an `:error-handler` is provided, the error mode will be set to `:continue` (defn handler [agent err] (println "ERR!! " (.getMessage err))) (def counter2 (agent 0 :validator number? :error-handler handler)) (send counter (fn [_] "boo")) ;; => #agent[{:status :failed, :val 0} 0x457fa6f1] ;;; Including Agents in Transactions ;; Transactions can be retried, so shouldn't have side-effects. ;; If side-effects are desired, agents can be used. ;; If an action is sent to an agent within a transaction, that action is sent exactly once, ;; if and only if the transaction succeeds. ;; Consider an agent that writes to a file when a trx succeeds: (def messages (ref ())) (defrecord Message [sender text]) (def backup-agent (agent "output/messages-backup.clj")) (defn add-message-with-backup [msg] (dosync (let [snapshot (commute messages conj msg)] (send-off backup-agent (fn [filename] (spit filename snapshot) filename))))) ;; `send-off` is a variant of `send` for actions that expect to block, as a file ;; write with `spit` might do. (add-message-with-backup (->Message "PI:NAME:<NAME>END_PI" "Message One")) (add-message-with-backup (->Message "PI:NAME:<NAME>END_PI" "Message Two")) ;;; Managing Per-Thread State with Vars ;; When you call `def` or `defn`, you create a `var`. ;; The initial value passed to `def` becomes the **_root binding_** or the `var`. (def ^:dynamic foo 10) ;; The binding of `foo` is shared by all threads foo ;; => 10 (.start (Thread. (fn [] (println foo)))) ;; => nil ;; ==> 10 ;; The call to `.start` returns `nil`, and the value of `foo` is printed from ;; the new thread. ;; Bindings have *dynamic* scope ;; Visible everywhere during a thread's execution, until the thread exits the ;; scope where the binding began. ;; A binding is not visible to other threads. ;; E.g., create a thread local binding for `foo` and check its value. ;; Observe `let` has no effect outside its own form ;; The binding stays in effect down the chain. (binding [foo 42] foo) ;; => 42 (defn print-foo [] (println foo)) (let [foo "let foo"] (print-foo)) ;; => nil ;; ==> 10 (binding [foo "bound foo"] (print-foo)) ;; => nil ;; ==> bound foo ;;; State Models ;; Refs and STM - Coordinated, synchronous updates - Pure functions ;; Atoms - Uncoordinated, synchronous updates - Pure functions ;; Agents - Uncoordinated, asynchronous updates - Any functions ;; Vars - Thread-local dynamic scopes - Any functions ;; Java locks - Coordinated, synchronous updates - Any functions
[ { "context": " :name \"John\"\n :character", "end": 1166, "score": 0.9997057318687439, "start": 1162, "tag": "NAME", "value": "John" }, { "context": " :name \"John\"\n :character", "end": 1972, "score": 0.9998021721839905, "start": 1968, "tag": "NAME", "value": "John" } ]
test/ziggurat/middleware/batch/batch_proto_deserializer_test.clj
shubhang93/ziggurat
1
(ns ziggurat.middleware.batch.batch-proto-deserializer-test (:require [clojure.test :refer :all]) (:require [ziggurat.middleware.batch.batch-proto-deserializer :refer :all] [protobuf.core :as proto]) (:import (flatland.protobuf.test Example$Photo Example$Photo$Tag) (com.gojek.test.proto PersonTestProto$Person))) (deftest batch-proto-deserializer-test (let [key {:person-id 100} value {:id 7 :path "/photos/h2k3j4h9h23"} key-with-struct {:id 100 :characters {:fields [{:key "hobbies", :value {:list-value {:values [{:string-value "eating"} {:string-value "sleeping"}]}}}]}} flattened-key-with-struct {:id 100 :characters {:hobbies ["eating" "sleeping"]}} value-with-struct {:id 100 :name "John" :characters {:fields [{:key "physique", :value {:struct-value {:fields [{:key "height", :value {:number-value 180.12}} {:key "weight", :value {:number-value 80.34}}]}}} {:key "age", :value {:number-value 50.5}} {:key "gender", :value {:string-value "male"}}]}} flattened-value-with-struct {:id 100 :name "John" :characters {:physique {:height 180.12 :weight 80.34} :age 50.5 :gender "male"}} key-proto-class Example$Photo$Tag value-proto-class Example$Photo struct-proto-class PersonTestProto$Person serialized-key (proto/->bytes (proto/create key-proto-class key)) serialized-value (proto/->bytes (proto/create value-proto-class value)) serialized-key-with-struct (proto/->bytes (proto/create struct-proto-class key-with-struct)) serialized-value-with-struct (proto/->bytes (proto/create struct-proto-class value-with-struct))] (testing "deserializes key and value for all the messages in a batch" (let [handler-fn-called? (atom false) batch-message (repeat 5 {:key serialized-key :value serialized-value}) handler-fn (fn [batch] (is (seq? batch)) (loop [msg batch] (when (not-empty msg) (let [key-value-pair (first msg)] (is (map? key-value-pair)) (is (= key (:key key-value-pair))) (is (= value (:value key-value-pair))) (recur (rest msg))))) (reset! handler-fn-called? true))] ((deserialize-batch-of-proto-messages handler-fn key-proto-class value-proto-class :some-topic-entity) batch-message) (is (true? @handler-fn-called?)))) (testing "Does not deserialize nil key or value" (let [handler-fn-called-2? (atom false) batch-message [{:key nil :value serialized-value} {:key serialized-key :value nil}] handler-fn (fn [batch] (is (seq? batch)) (loop [msg batch] (when (not-empty msg) (let [key-value-pair (first msg) deserialized-key (:key key-value-pair) deserialized-value (:value key-value-pair)] (is (map? key-value-pair)) (is (or (nil? deserialized-key) (= key deserialized-key))) (is (or (nil? deserialized-value) (= value deserialized-value))) (recur (rest msg))))) (reset! handler-fn-called-2? true))] ((deserialize-batch-of-proto-messages handler-fn key-proto-class value-proto-class :some-topic-entity) batch-message) (is (true? @handler-fn-called-2?)))) (testing "should not deserializes key and value for the messages in a batch and flatten protobuf structs if flatten-protobuf-struct? is false" (let [handler-fn-called? (atom false) batch-message (repeat 5 {:key serialized-key-with-struct :value serialized-value-with-struct}) handler-fn (fn [batch] (is (seq? batch)) (is (= 5 (count batch))) (loop [msg batch] (when (not-empty msg) (let [key-value-pair (first msg)] (is (map? key-value-pair)) (is (= key-with-struct (:key key-value-pair))) (is (= value-with-struct (:value key-value-pair))) (recur (rest msg))))) (reset! handler-fn-called? true))] ((deserialize-batch-of-proto-messages handler-fn struct-proto-class struct-proto-class :some-topic-entity false) batch-message) (is (true? @handler-fn-called?)))) (testing "should deserializes key and value for the messages in a batch and flatten protobuf structs if flatten-protobuf-struct? is true" (let [handler-fn-called? (atom false) batch-message (repeat 5 {:key serialized-key-with-struct :value serialized-value-with-struct}) handler-fn (fn [batch] (is (seq? batch)) (is (= 5 (count batch))) (loop [msg batch] (when (not-empty msg) (let [key-value-pair (first msg)] (is (map? key-value-pair)) (is (= flattened-key-with-struct (:key key-value-pair))) (is (= flattened-value-with-struct (:value key-value-pair))) (recur (rest msg))))) (reset! handler-fn-called? true))] ((deserialize-batch-of-proto-messages handler-fn struct-proto-class struct-proto-class :some-topic-entity true) batch-message) (is (true? @handler-fn-called?))))))
5229
(ns ziggurat.middleware.batch.batch-proto-deserializer-test (:require [clojure.test :refer :all]) (:require [ziggurat.middleware.batch.batch-proto-deserializer :refer :all] [protobuf.core :as proto]) (:import (flatland.protobuf.test Example$Photo Example$Photo$Tag) (com.gojek.test.proto PersonTestProto$Person))) (deftest batch-proto-deserializer-test (let [key {:person-id 100} value {:id 7 :path "/photos/h2k3j4h9h23"} key-with-struct {:id 100 :characters {:fields [{:key "hobbies", :value {:list-value {:values [{:string-value "eating"} {:string-value "sleeping"}]}}}]}} flattened-key-with-struct {:id 100 :characters {:hobbies ["eating" "sleeping"]}} value-with-struct {:id 100 :name "<NAME>" :characters {:fields [{:key "physique", :value {:struct-value {:fields [{:key "height", :value {:number-value 180.12}} {:key "weight", :value {:number-value 80.34}}]}}} {:key "age", :value {:number-value 50.5}} {:key "gender", :value {:string-value "male"}}]}} flattened-value-with-struct {:id 100 :name "<NAME>" :characters {:physique {:height 180.12 :weight 80.34} :age 50.5 :gender "male"}} key-proto-class Example$Photo$Tag value-proto-class Example$Photo struct-proto-class PersonTestProto$Person serialized-key (proto/->bytes (proto/create key-proto-class key)) serialized-value (proto/->bytes (proto/create value-proto-class value)) serialized-key-with-struct (proto/->bytes (proto/create struct-proto-class key-with-struct)) serialized-value-with-struct (proto/->bytes (proto/create struct-proto-class value-with-struct))] (testing "deserializes key and value for all the messages in a batch" (let [handler-fn-called? (atom false) batch-message (repeat 5 {:key serialized-key :value serialized-value}) handler-fn (fn [batch] (is (seq? batch)) (loop [msg batch] (when (not-empty msg) (let [key-value-pair (first msg)] (is (map? key-value-pair)) (is (= key (:key key-value-pair))) (is (= value (:value key-value-pair))) (recur (rest msg))))) (reset! handler-fn-called? true))] ((deserialize-batch-of-proto-messages handler-fn key-proto-class value-proto-class :some-topic-entity) batch-message) (is (true? @handler-fn-called?)))) (testing "Does not deserialize nil key or value" (let [handler-fn-called-2? (atom false) batch-message [{:key nil :value serialized-value} {:key serialized-key :value nil}] handler-fn (fn [batch] (is (seq? batch)) (loop [msg batch] (when (not-empty msg) (let [key-value-pair (first msg) deserialized-key (:key key-value-pair) deserialized-value (:value key-value-pair)] (is (map? key-value-pair)) (is (or (nil? deserialized-key) (= key deserialized-key))) (is (or (nil? deserialized-value) (= value deserialized-value))) (recur (rest msg))))) (reset! handler-fn-called-2? true))] ((deserialize-batch-of-proto-messages handler-fn key-proto-class value-proto-class :some-topic-entity) batch-message) (is (true? @handler-fn-called-2?)))) (testing "should not deserializes key and value for the messages in a batch and flatten protobuf structs if flatten-protobuf-struct? is false" (let [handler-fn-called? (atom false) batch-message (repeat 5 {:key serialized-key-with-struct :value serialized-value-with-struct}) handler-fn (fn [batch] (is (seq? batch)) (is (= 5 (count batch))) (loop [msg batch] (when (not-empty msg) (let [key-value-pair (first msg)] (is (map? key-value-pair)) (is (= key-with-struct (:key key-value-pair))) (is (= value-with-struct (:value key-value-pair))) (recur (rest msg))))) (reset! handler-fn-called? true))] ((deserialize-batch-of-proto-messages handler-fn struct-proto-class struct-proto-class :some-topic-entity false) batch-message) (is (true? @handler-fn-called?)))) (testing "should deserializes key and value for the messages in a batch and flatten protobuf structs if flatten-protobuf-struct? is true" (let [handler-fn-called? (atom false) batch-message (repeat 5 {:key serialized-key-with-struct :value serialized-value-with-struct}) handler-fn (fn [batch] (is (seq? batch)) (is (= 5 (count batch))) (loop [msg batch] (when (not-empty msg) (let [key-value-pair (first msg)] (is (map? key-value-pair)) (is (= flattened-key-with-struct (:key key-value-pair))) (is (= flattened-value-with-struct (:value key-value-pair))) (recur (rest msg))))) (reset! handler-fn-called? true))] ((deserialize-batch-of-proto-messages handler-fn struct-proto-class struct-proto-class :some-topic-entity true) batch-message) (is (true? @handler-fn-called?))))))
true
(ns ziggurat.middleware.batch.batch-proto-deserializer-test (:require [clojure.test :refer :all]) (:require [ziggurat.middleware.batch.batch-proto-deserializer :refer :all] [protobuf.core :as proto]) (:import (flatland.protobuf.test Example$Photo Example$Photo$Tag) (com.gojek.test.proto PersonTestProto$Person))) (deftest batch-proto-deserializer-test (let [key {:person-id 100} value {:id 7 :path "/photos/h2k3j4h9h23"} key-with-struct {:id 100 :characters {:fields [{:key "hobbies", :value {:list-value {:values [{:string-value "eating"} {:string-value "sleeping"}]}}}]}} flattened-key-with-struct {:id 100 :characters {:hobbies ["eating" "sleeping"]}} value-with-struct {:id 100 :name "PI:NAME:<NAME>END_PI" :characters {:fields [{:key "physique", :value {:struct-value {:fields [{:key "height", :value {:number-value 180.12}} {:key "weight", :value {:number-value 80.34}}]}}} {:key "age", :value {:number-value 50.5}} {:key "gender", :value {:string-value "male"}}]}} flattened-value-with-struct {:id 100 :name "PI:NAME:<NAME>END_PI" :characters {:physique {:height 180.12 :weight 80.34} :age 50.5 :gender "male"}} key-proto-class Example$Photo$Tag value-proto-class Example$Photo struct-proto-class PersonTestProto$Person serialized-key (proto/->bytes (proto/create key-proto-class key)) serialized-value (proto/->bytes (proto/create value-proto-class value)) serialized-key-with-struct (proto/->bytes (proto/create struct-proto-class key-with-struct)) serialized-value-with-struct (proto/->bytes (proto/create struct-proto-class value-with-struct))] (testing "deserializes key and value for all the messages in a batch" (let [handler-fn-called? (atom false) batch-message (repeat 5 {:key serialized-key :value serialized-value}) handler-fn (fn [batch] (is (seq? batch)) (loop [msg batch] (when (not-empty msg) (let [key-value-pair (first msg)] (is (map? key-value-pair)) (is (= key (:key key-value-pair))) (is (= value (:value key-value-pair))) (recur (rest msg))))) (reset! handler-fn-called? true))] ((deserialize-batch-of-proto-messages handler-fn key-proto-class value-proto-class :some-topic-entity) batch-message) (is (true? @handler-fn-called?)))) (testing "Does not deserialize nil key or value" (let [handler-fn-called-2? (atom false) batch-message [{:key nil :value serialized-value} {:key serialized-key :value nil}] handler-fn (fn [batch] (is (seq? batch)) (loop [msg batch] (when (not-empty msg) (let [key-value-pair (first msg) deserialized-key (:key key-value-pair) deserialized-value (:value key-value-pair)] (is (map? key-value-pair)) (is (or (nil? deserialized-key) (= key deserialized-key))) (is (or (nil? deserialized-value) (= value deserialized-value))) (recur (rest msg))))) (reset! handler-fn-called-2? true))] ((deserialize-batch-of-proto-messages handler-fn key-proto-class value-proto-class :some-topic-entity) batch-message) (is (true? @handler-fn-called-2?)))) (testing "should not deserializes key and value for the messages in a batch and flatten protobuf structs if flatten-protobuf-struct? is false" (let [handler-fn-called? (atom false) batch-message (repeat 5 {:key serialized-key-with-struct :value serialized-value-with-struct}) handler-fn (fn [batch] (is (seq? batch)) (is (= 5 (count batch))) (loop [msg batch] (when (not-empty msg) (let [key-value-pair (first msg)] (is (map? key-value-pair)) (is (= key-with-struct (:key key-value-pair))) (is (= value-with-struct (:value key-value-pair))) (recur (rest msg))))) (reset! handler-fn-called? true))] ((deserialize-batch-of-proto-messages handler-fn struct-proto-class struct-proto-class :some-topic-entity false) batch-message) (is (true? @handler-fn-called?)))) (testing "should deserializes key and value for the messages in a batch and flatten protobuf structs if flatten-protobuf-struct? is true" (let [handler-fn-called? (atom false) batch-message (repeat 5 {:key serialized-key-with-struct :value serialized-value-with-struct}) handler-fn (fn [batch] (is (seq? batch)) (is (= 5 (count batch))) (loop [msg batch] (when (not-empty msg) (let [key-value-pair (first msg)] (is (map? key-value-pair)) (is (= flattened-key-with-struct (:key key-value-pair))) (is (= flattened-value-with-struct (:value key-value-pair))) (recur (rest msg))))) (reset! handler-fn-called? true))] ((deserialize-batch-of-proto-messages handler-fn struct-proto-class struct-proto-class :some-topic-entity true) batch-message) (is (true? @handler-fn-called?))))))
[ { "context": "nuvla/service\n\n :smtp-username \"username\"\n :smtp-password \"password\"\n ", "end": 936, "score": 0.9994850754737854, "start": 928, "tag": "USERNAME", "value": "username" }, { "context": "ame \"username\"\n :smtp-password \"password\"\n :smtp-host \"host\"\n ", "end": 981, "score": 0.9994717240333557, "start": 973, "tag": "PASSWORD", "value": "password" }, { "context": "debug true\n\n :support-email \"admin@example.org\"\n\n :stripe-api-key \"sk_test_xxx", "end": 1193, "score": 0.9998941421508789, "start": 1176, "tag": "EMAIL", "value": "admin@example.org" }, { "context": "example.org\"\n\n :stripe-api-key \"sk_test_xxx\"\n :external-vulnerabilities-db ", "end": 1243, "score": 0.7904332280158997, "start": 1232, "tag": "KEY", "value": "sk_test_xxx" }, { "context": ":external-vulnerabilities-db \"https://github.com/nuvla/vuln-db/blob/main/databases/all.aggregated.json.g", "end": 1319, "score": 0.9976534843444824, "start": 1314, "tag": "USERNAME", "value": "nuvla" } ]
code/test/sixsq/nuvla/server/resources/spec/configuration_template_nuvla_test.cljc
0xbase12/api-server
6
(ns sixsq.nuvla.server.resources.spec.configuration-template-nuvla-test (:require [clojure.test :refer [deftest]] [sixsq.nuvla.server.resources.configuration-nuvla :as nuvla] [sixsq.nuvla.server.resources.configuration-template :as ct] [sixsq.nuvla.server.resources.spec.configuration-template-nuvla :as ct-nuvla] [sixsq.nuvla.server.resources.spec.spec-test-utils :as stu])) (def valid-acl {:owners ["group/nuvla-admin"] :view-acl ["group/nuvla-admin"]}) (deftest check-configuration-template-nuvla (let [timestamp "1964-08-25T10:00:00.00Z" cfg {:id (str ct/resource-type "/" nuvla/service) :resource-type nuvla/service :created timestamp :updated timestamp :acl valid-acl :service nuvla/service :smtp-username "username" :smtp-password "password" :smtp-host "host" :smtp-port 465 :smtp-ssl true :smtp-debug true :support-email "admin@example.org" :stripe-api-key "sk_test_xxx" :external-vulnerabilities-db "https://github.com/nuvla/vuln-db/blob/main/databases/all.aggregated.json.gz?raw=true" :conditions-url "https://nuvla.io/terms/tos"}] (stu/is-valid ::ct-nuvla/schema cfg) ;; mandatory keys (doseq [k #{:id :resource-type :created :updated :acl}] (stu/is-invalid ::ct-nuvla/schema (dissoc cfg k))) ;; optional keys (doseq [k #{:smtp-username :smtp-password :smtp-host :smtp-port :smtp-ssl :smtp-debug :support-email :stripe-api-key :external-vulnerabilities-db :conditions-url}] (stu/is-valid ::ct-nuvla/schema (dissoc cfg k)))))
68016
(ns sixsq.nuvla.server.resources.spec.configuration-template-nuvla-test (:require [clojure.test :refer [deftest]] [sixsq.nuvla.server.resources.configuration-nuvla :as nuvla] [sixsq.nuvla.server.resources.configuration-template :as ct] [sixsq.nuvla.server.resources.spec.configuration-template-nuvla :as ct-nuvla] [sixsq.nuvla.server.resources.spec.spec-test-utils :as stu])) (def valid-acl {:owners ["group/nuvla-admin"] :view-acl ["group/nuvla-admin"]}) (deftest check-configuration-template-nuvla (let [timestamp "1964-08-25T10:00:00.00Z" cfg {:id (str ct/resource-type "/" nuvla/service) :resource-type nuvla/service :created timestamp :updated timestamp :acl valid-acl :service nuvla/service :smtp-username "username" :smtp-password "<PASSWORD>" :smtp-host "host" :smtp-port 465 :smtp-ssl true :smtp-debug true :support-email "<EMAIL>" :stripe-api-key "<KEY>" :external-vulnerabilities-db "https://github.com/nuvla/vuln-db/blob/main/databases/all.aggregated.json.gz?raw=true" :conditions-url "https://nuvla.io/terms/tos"}] (stu/is-valid ::ct-nuvla/schema cfg) ;; mandatory keys (doseq [k #{:id :resource-type :created :updated :acl}] (stu/is-invalid ::ct-nuvla/schema (dissoc cfg k))) ;; optional keys (doseq [k #{:smtp-username :smtp-password :smtp-host :smtp-port :smtp-ssl :smtp-debug :support-email :stripe-api-key :external-vulnerabilities-db :conditions-url}] (stu/is-valid ::ct-nuvla/schema (dissoc cfg k)))))
true
(ns sixsq.nuvla.server.resources.spec.configuration-template-nuvla-test (:require [clojure.test :refer [deftest]] [sixsq.nuvla.server.resources.configuration-nuvla :as nuvla] [sixsq.nuvla.server.resources.configuration-template :as ct] [sixsq.nuvla.server.resources.spec.configuration-template-nuvla :as ct-nuvla] [sixsq.nuvla.server.resources.spec.spec-test-utils :as stu])) (def valid-acl {:owners ["group/nuvla-admin"] :view-acl ["group/nuvla-admin"]}) (deftest check-configuration-template-nuvla (let [timestamp "1964-08-25T10:00:00.00Z" cfg {:id (str ct/resource-type "/" nuvla/service) :resource-type nuvla/service :created timestamp :updated timestamp :acl valid-acl :service nuvla/service :smtp-username "username" :smtp-password "PI:PASSWORD:<PASSWORD>END_PI" :smtp-host "host" :smtp-port 465 :smtp-ssl true :smtp-debug true :support-email "PI:EMAIL:<EMAIL>END_PI" :stripe-api-key "PI:KEY:<KEY>END_PI" :external-vulnerabilities-db "https://github.com/nuvla/vuln-db/blob/main/databases/all.aggregated.json.gz?raw=true" :conditions-url "https://nuvla.io/terms/tos"}] (stu/is-valid ::ct-nuvla/schema cfg) ;; mandatory keys (doseq [k #{:id :resource-type :created :updated :acl}] (stu/is-invalid ::ct-nuvla/schema (dissoc cfg k))) ;; optional keys (doseq [k #{:smtp-username :smtp-password :smtp-host :smtp-port :smtp-ssl :smtp-debug :support-email :stripe-api-key :external-vulnerabilities-db :conditions-url}] (stu/is-valid ::ct-nuvla/schema (dissoc cfg k)))))
[ { "context": "ful arrays for clojure\"\n :url \"http://github.com/zcaudate/ova\"\n :license {:name \"The MIT License\"\n ", "end": 111, "score": 0.998393714427948, "start": 103, "tag": "USERNAME", "value": "zcaudate" }, { "context": " for clojure\"\n :author \"Chris Zheng\"\n :email \"z@caudate.me", "end": 665, "score": 0.9998804330825806, "start": 654, "tag": "NAME", "value": "Chris Zheng" }, { "context": "\"Chris Zheng\"\n :email \"z@caudate.me\"\n :tracking \"UA-3132051", "end": 715, "score": 0.9999274015426636, "start": 703, "tag": "EMAIL", "value": "z@caudate.me" } ]
project.clj
zcaudate-archive/ova
0
(defproject im.chit/ova "1.0.1" :description "Stateful arrays for clojure" :url "http://github.com/zcaudate/ova" :license {:name "The MIT License" :url "http://http://opensource.org/licenses/MIT"} :dependencies [[org.clojure/clojure "1.5.1"] [im.chit/hara "1.0.1"]] :profiles {:dev {:dependencies [[midje "1.6.0"]] :plugins [[lein-midje "3.1.3"]]}} :documentation {:files {"doc/index" {:input "test/midje_doc/ova_guide.clj" :title "ova" :sub-title "stateful arrays for clojure" :author "Chris Zheng" :email "z@caudate.me" :tracking "UA-31320512-2"}}})
106483
(defproject im.chit/ova "1.0.1" :description "Stateful arrays for clojure" :url "http://github.com/zcaudate/ova" :license {:name "The MIT License" :url "http://http://opensource.org/licenses/MIT"} :dependencies [[org.clojure/clojure "1.5.1"] [im.chit/hara "1.0.1"]] :profiles {:dev {:dependencies [[midje "1.6.0"]] :plugins [[lein-midje "3.1.3"]]}} :documentation {:files {"doc/index" {:input "test/midje_doc/ova_guide.clj" :title "ova" :sub-title "stateful arrays for clojure" :author "<NAME>" :email "<EMAIL>" :tracking "UA-31320512-2"}}})
true
(defproject im.chit/ova "1.0.1" :description "Stateful arrays for clojure" :url "http://github.com/zcaudate/ova" :license {:name "The MIT License" :url "http://http://opensource.org/licenses/MIT"} :dependencies [[org.clojure/clojure "1.5.1"] [im.chit/hara "1.0.1"]] :profiles {:dev {:dependencies [[midje "1.6.0"]] :plugins [[lein-midje "3.1.3"]]}} :documentation {:files {"doc/index" {:input "test/midje_doc/ova_guide.clj" :title "ova" :sub-title "stateful arrays for clojure" :author "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI" :tracking "UA-31320512-2"}}})
[ { "context": " :jen 1,\n :jordan 1,\n :john 0.5,\n :jimmy 0.8}\n {:jeff ", "end": 1788, "score": 0.6840924620628357, "start": 1784, "tag": "NAME", "value": "john" }, { "context": ":john 0.5,\n :jimmy 0.8}\n {:jeff 1,\n :kent 1,\n :cathy 1,\n ", "end": 1837, "score": 0.883714497089386, "start": 1833, "tag": "NAME", "value": "jeff" }, { "context": " {:jeff 1,\n :kent 1,\n :cathy 1,\n :eric 0.9,\n :jen 1,\n ", "end": 1882, "score": 0.9551271796226501, "start": 1877, "tag": "NAME", "value": "cathy" }, { "context": " :cathy 1,\n :eric 0.9,\n :jen 1,\n :jordan 1,\n :john 0.5", "end": 1927, "score": 0.9519826769828796, "start": 1924, "tag": "NAME", "value": "jen" }, { "context": " :eric 0.9,\n :jen 1,\n :jordan 1,\n :john 0.5,\n :jimmy 0.", "end": 1951, "score": 0.950645923614502, "start": 1945, "tag": "NAME", "value": "jordan" }, { "context": " :jen 1,\n :jordan 1,\n :john 0.5,\n :jimmy 0.8}\n {:jeff ", "end": 1973, "score": 0.954647421836853, "start": 1969, "tag": "NAME", "value": "john" }, { "context": ":john 0.5,\n :jimmy 0.8}\n {:jeff 1,\n :kent 1,\n :cathy 1,\n ", "end": 2022, "score": 0.8685086369514465, "start": 2018, "tag": "NAME", "value": "jeff" }, { "context": " {:jeff 1,\n :kent 1,\n :cathy 1,\n :eric 0.9,\n :jen 1,\n ", "end": 2067, "score": 0.9712421894073486, "start": 2062, "tag": "NAME", "value": "cathy" }, { "context": " :cathy 1,\n :eric 0.9,\n :jen 1,\n :jordan 1,\n :john 1,\n", "end": 2112, "score": 0.9516686797142029, "start": 2109, "tag": "NAME", "value": "jen" }, { "context": " :eric 0.9,\n :jen 1,\n :jordan 1,\n :john 1,\n :jimmy 0.8}", "end": 2136, "score": 0.9711627960205078, "start": 2130, "tag": "NAME", "value": "jordan" }, { "context": " :jen 1,\n :jordan 1,\n :john 1,\n :jimmy 0.8}],\n :project", "end": 2158, "score": 0.9805948138237, "start": 2154, "tag": "NAME", "value": "john" } ]
test/capacity/config_test.cljc
pierrel/capacity-planner
0
(ns capacity.config-test (:require [capacity.config :as sut] #?(:clj [clojure.test :as t] :cljs [cljs.test :as t :include-macros true]))) (def sample {:context "testing" :constants {:sprints 6 :unplanned 0.15 :velocity 5} :profs {:pierre #{:app :web} :selma #{:ios :android}} :contrib [{:pierre 1 :selma 0.5} {:pierre 0.5 :selma 2}] :projects [{:name "Proj1" :effort {:app 10 :ios 3}} {:name "Proj2" :effort {:app 2 :ios 4 :android 2}}]}) (t/deftest validate (t/is (map? (sut/validate sample))) (t/is (thrown-with-msg? RuntimeException #"Validation errors" (sut/validate (update-in sample [:projects 0 :effort] #(assoc % :meme 10)))))) (t/deftest read (t/is (= {:context "Test plan", :constants {:sprints 6, :unplanned 0.15, :velocity 5}, :profs {:eric #{:app :web}, :jen #{:web}, :jordan #{:app :web}, :cathy #{:app :data}, :jeff #{:ios :app}, :john #{:android :app}, :jimmy #{:ios :app}, :kent #{:app}, :mary #{:android :app}}, :contrib [{:eric 0.9, :jen 1, :jordan 1, :cathy 1, :jeff 0, :john 0.5, :jimmy 0.8, :kent 0, :mary 0.5} {:jeff 0, :kent 0, :cathy 1, :eric 0.9, :jen 1, :jordan 1, :john 0.5, :jimmy 0.8} {:jeff 1, :kent 1, :cathy 1, :eric 0.9, :jen 1, :jordan 1, :john 0.5, :jimmy 0.8} {:jeff 1, :kent 1, :cathy 1, :eric 0.9, :jen 1, :jordan 1, :john 1, :jimmy 0.8}], :projects '({:name "Dynamic FCap", :effort {:app 32}} {:name "A11y", :effort {:web 45}} {:name "Objectives", :effort {:web 4, :app 4}} {:name "Editability", :effort {:ios 3, :android 3, :app 32, :web 3}} {:name "Online Events Attribution", :effort {:app 20}} {:name "Test leads", :effort {:app 20}} {:name "TextViewModel migration", :effort {:app 5, :ios 2, :android 2, :web 3}} {:name "SSCS", :effort {:web 8, :app 30}} {:name "C2M", :effort {:ios 8, :android 8, :web 20, :app 40}} {:name "Deprecate Custom Senders", :effort {:app 20, :ios 8, :android 8, :web 8}} {:name "Sender Identity", :effort {:app 30, :web 20}} {:name "Human handoff", :effort {:app 40, :web 40, :android 10, :ios 10}})} (sut/read "test/resources/test-config.edn"))))
34235
(ns capacity.config-test (:require [capacity.config :as sut] #?(:clj [clojure.test :as t] :cljs [cljs.test :as t :include-macros true]))) (def sample {:context "testing" :constants {:sprints 6 :unplanned 0.15 :velocity 5} :profs {:pierre #{:app :web} :selma #{:ios :android}} :contrib [{:pierre 1 :selma 0.5} {:pierre 0.5 :selma 2}] :projects [{:name "Proj1" :effort {:app 10 :ios 3}} {:name "Proj2" :effort {:app 2 :ios 4 :android 2}}]}) (t/deftest validate (t/is (map? (sut/validate sample))) (t/is (thrown-with-msg? RuntimeException #"Validation errors" (sut/validate (update-in sample [:projects 0 :effort] #(assoc % :meme 10)))))) (t/deftest read (t/is (= {:context "Test plan", :constants {:sprints 6, :unplanned 0.15, :velocity 5}, :profs {:eric #{:app :web}, :jen #{:web}, :jordan #{:app :web}, :cathy #{:app :data}, :jeff #{:ios :app}, :john #{:android :app}, :jimmy #{:ios :app}, :kent #{:app}, :mary #{:android :app}}, :contrib [{:eric 0.9, :jen 1, :jordan 1, :cathy 1, :jeff 0, :john 0.5, :jimmy 0.8, :kent 0, :mary 0.5} {:jeff 0, :kent 0, :cathy 1, :eric 0.9, :jen 1, :jordan 1, :<NAME> 0.5, :jimmy 0.8} {:<NAME> 1, :kent 1, :<NAME> 1, :eric 0.9, :<NAME> 1, :<NAME> 1, :<NAME> 0.5, :jimmy 0.8} {:<NAME> 1, :kent 1, :<NAME> 1, :eric 0.9, :<NAME> 1, :<NAME> 1, :<NAME> 1, :jimmy 0.8}], :projects '({:name "Dynamic FCap", :effort {:app 32}} {:name "A11y", :effort {:web 45}} {:name "Objectives", :effort {:web 4, :app 4}} {:name "Editability", :effort {:ios 3, :android 3, :app 32, :web 3}} {:name "Online Events Attribution", :effort {:app 20}} {:name "Test leads", :effort {:app 20}} {:name "TextViewModel migration", :effort {:app 5, :ios 2, :android 2, :web 3}} {:name "SSCS", :effort {:web 8, :app 30}} {:name "C2M", :effort {:ios 8, :android 8, :web 20, :app 40}} {:name "Deprecate Custom Senders", :effort {:app 20, :ios 8, :android 8, :web 8}} {:name "Sender Identity", :effort {:app 30, :web 20}} {:name "Human handoff", :effort {:app 40, :web 40, :android 10, :ios 10}})} (sut/read "test/resources/test-config.edn"))))
true
(ns capacity.config-test (:require [capacity.config :as sut] #?(:clj [clojure.test :as t] :cljs [cljs.test :as t :include-macros true]))) (def sample {:context "testing" :constants {:sprints 6 :unplanned 0.15 :velocity 5} :profs {:pierre #{:app :web} :selma #{:ios :android}} :contrib [{:pierre 1 :selma 0.5} {:pierre 0.5 :selma 2}] :projects [{:name "Proj1" :effort {:app 10 :ios 3}} {:name "Proj2" :effort {:app 2 :ios 4 :android 2}}]}) (t/deftest validate (t/is (map? (sut/validate sample))) (t/is (thrown-with-msg? RuntimeException #"Validation errors" (sut/validate (update-in sample [:projects 0 :effort] #(assoc % :meme 10)))))) (t/deftest read (t/is (= {:context "Test plan", :constants {:sprints 6, :unplanned 0.15, :velocity 5}, :profs {:eric #{:app :web}, :jen #{:web}, :jordan #{:app :web}, :cathy #{:app :data}, :jeff #{:ios :app}, :john #{:android :app}, :jimmy #{:ios :app}, :kent #{:app}, :mary #{:android :app}}, :contrib [{:eric 0.9, :jen 1, :jordan 1, :cathy 1, :jeff 0, :john 0.5, :jimmy 0.8, :kent 0, :mary 0.5} {:jeff 0, :kent 0, :cathy 1, :eric 0.9, :jen 1, :jordan 1, :PI:NAME:<NAME>END_PI 0.5, :jimmy 0.8} {:PI:NAME:<NAME>END_PI 1, :kent 1, :PI:NAME:<NAME>END_PI 1, :eric 0.9, :PI:NAME:<NAME>END_PI 1, :PI:NAME:<NAME>END_PI 1, :PI:NAME:<NAME>END_PI 0.5, :jimmy 0.8} {:PI:NAME:<NAME>END_PI 1, :kent 1, :PI:NAME:<NAME>END_PI 1, :eric 0.9, :PI:NAME:<NAME>END_PI 1, :PI:NAME:<NAME>END_PI 1, :PI:NAME:<NAME>END_PI 1, :jimmy 0.8}], :projects '({:name "Dynamic FCap", :effort {:app 32}} {:name "A11y", :effort {:web 45}} {:name "Objectives", :effort {:web 4, :app 4}} {:name "Editability", :effort {:ios 3, :android 3, :app 32, :web 3}} {:name "Online Events Attribution", :effort {:app 20}} {:name "Test leads", :effort {:app 20}} {:name "TextViewModel migration", :effort {:app 5, :ios 2, :android 2, :web 3}} {:name "SSCS", :effort {:web 8, :app 30}} {:name "C2M", :effort {:ios 8, :android 8, :web 20, :app 40}} {:name "Deprecate Custom Senders", :effort {:app 20, :ios 8, :android 8, :web 8}} {:name "Sender Identity", :effort {:app 30, :web 20}} {:name "Human handoff", :effort {:app 40, :web 40, :android 10, :ios 10}})} (sut/read "test/resources/test-config.edn"))))
[ { "context": ";;\n;; Author:: Adam Jacob (<adam@opscode.com>)\n;; Author:: Christopher Brow", "end": 25, "score": 0.9998466968536377, "start": 15, "tag": "NAME", "value": "Adam Jacob" }, { "context": ";;\n;; Author:: Adam Jacob (<adam@opscode.com>)\n;; Author:: Christopher Brown (<cb@opscode.com>", "end": 44, "score": 0.9999340176582336, "start": 28, "tag": "EMAIL", "value": "adam@opscode.com" }, { "context": "thor:: Adam Jacob (<adam@opscode.com>)\n;; Author:: Christopher Brown (<cb@opscode.com>)\n;; Copyright:: Copyright (c) 2", "end": 76, "score": 0.9997701644897461, "start": 59, "tag": "NAME", "value": "Christopher Brown" }, { "context": "dam@opscode.com>)\n;; Author:: Christopher Brown (<cb@opscode.com>)\n;; Copyright:: Copyright (c) 2010 Opscode, Inc.", "end": 93, "score": 0.9999334216117859, "start": 79, "tag": "EMAIL", "value": "cb@opscode.com" } ]
config/software/rabbitmq.clj
racker/omnibus
2
;; ;; Author:: Adam Jacob (<adam@opscode.com>) ;; Author:: Christopher Brown (<cb@opscode.com>) ;; Copyright:: Copyright (c) 2010 Opscode, Inc. ;; License:: Apache License, Version 2.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. ;; (software "rabbitmq" :source "rabbitmq_server-2.2.0" :steps [ {:command "pwd"} {:command "cp" :args ["-a" "../rabbitmq_server-2.2.0" "/opt/opscode/embedded/lib/erlang/lib"]} {:command "ln" :args ["-sf" "/opt/opscode/embedded/lib/erlang/lib/rabbitmq_server-2.2.0/sbin/rabbitmqctl" "/opt/opscode/embedded/bin/rabbitmqctl"]} {:command "ln" :args ["-sf" "/opt/opscode/embedded/lib/erlang/lib/rabbitmq_server-2.2.0/sbin/rabbitmq-env" "/opt/opscode/embedded/bin/rabbitmq-env"]} {:command "ln" :args ["-sf" "/opt/opscode/embedded/lib/erlang/lib/rabbitmq_server-2.2.0/sbin/rabbitmq-multi" "/opt/opscode/embedded/bin/rabbitmq-multi"]} {:command "ln" :args ["-sf" "/opt/opscode/embedded/lib/erlang/lib/rabbitmq_server-2.2.0/sbin/rabbitmq-server" "/opt/opscode/embedded/bin/rabbitmq-server"]} ])
103625
;; ;; Author:: <NAME> (<<EMAIL>>) ;; Author:: <NAME> (<<EMAIL>>) ;; Copyright:: Copyright (c) 2010 Opscode, Inc. ;; License:: Apache License, Version 2.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. ;; (software "rabbitmq" :source "rabbitmq_server-2.2.0" :steps [ {:command "pwd"} {:command "cp" :args ["-a" "../rabbitmq_server-2.2.0" "/opt/opscode/embedded/lib/erlang/lib"]} {:command "ln" :args ["-sf" "/opt/opscode/embedded/lib/erlang/lib/rabbitmq_server-2.2.0/sbin/rabbitmqctl" "/opt/opscode/embedded/bin/rabbitmqctl"]} {:command "ln" :args ["-sf" "/opt/opscode/embedded/lib/erlang/lib/rabbitmq_server-2.2.0/sbin/rabbitmq-env" "/opt/opscode/embedded/bin/rabbitmq-env"]} {:command "ln" :args ["-sf" "/opt/opscode/embedded/lib/erlang/lib/rabbitmq_server-2.2.0/sbin/rabbitmq-multi" "/opt/opscode/embedded/bin/rabbitmq-multi"]} {:command "ln" :args ["-sf" "/opt/opscode/embedded/lib/erlang/lib/rabbitmq_server-2.2.0/sbin/rabbitmq-server" "/opt/opscode/embedded/bin/rabbitmq-server"]} ])
true
;; ;; Author:: PI:NAME:<NAME>END_PI (<PI:EMAIL:<EMAIL>END_PI>) ;; Author:: PI:NAME:<NAME>END_PI (<PI:EMAIL:<EMAIL>END_PI>) ;; Copyright:: Copyright (c) 2010 Opscode, Inc. ;; License:: Apache License, Version 2.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. ;; (software "rabbitmq" :source "rabbitmq_server-2.2.0" :steps [ {:command "pwd"} {:command "cp" :args ["-a" "../rabbitmq_server-2.2.0" "/opt/opscode/embedded/lib/erlang/lib"]} {:command "ln" :args ["-sf" "/opt/opscode/embedded/lib/erlang/lib/rabbitmq_server-2.2.0/sbin/rabbitmqctl" "/opt/opscode/embedded/bin/rabbitmqctl"]} {:command "ln" :args ["-sf" "/opt/opscode/embedded/lib/erlang/lib/rabbitmq_server-2.2.0/sbin/rabbitmq-env" "/opt/opscode/embedded/bin/rabbitmq-env"]} {:command "ln" :args ["-sf" "/opt/opscode/embedded/lib/erlang/lib/rabbitmq_server-2.2.0/sbin/rabbitmq-multi" "/opt/opscode/embedded/bin/rabbitmq-multi"]} {:command "ln" :args ["-sf" "/opt/opscode/embedded/lib/erlang/lib/rabbitmq_server-2.2.0/sbin/rabbitmq-server" "/opt/opscode/embedded/bin/rabbitmq-server"]} ])
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\r\n; The use and distributi", "end": 30, "score": 0.9998716115951538, "start": 19, "tag": "NAME", "value": "Rich Hickey" }, { "context": " other, from this software.\r\n\r\n(ns \r\n ^{:author \"David Miller\",\r\n :doc \"Shamelessly based on the clojure.ja", "end": 504, "score": 0.9997498989105225, "start": 492, "tag": "NAME", "value": "David Miller" }, { "context": "y based on the clojure.java.io package authored by Stuart Sierra, Chas Emerick, Stuart Halloway.\r\n This file d", "end": 593, "score": 0.999890923500061, "start": 580, "tag": "NAME", "value": "Stuart Sierra" }, { "context": "clojure.java.io package authored by Stuart Sierra, Chas Emerick, Stuart Halloway.\r\n This file defines polymor", "end": 607, "score": 0.9998893737792969, "start": 595, "tag": "NAME", "value": "Chas Emerick" }, { "context": "o package authored by Stuart Sierra, Chas Emerick, Stuart Halloway.\r\n This file defines polymorphic I/O utility ", "end": 624, "score": 0.9998796582221985, "start": 609, "tag": "NAME", "value": "Stuart Halloway" } ]
Source/clojure/clr/io.clj
max-lv/Arcadia
0
; Copyright (c) Rich Hickey. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns ^{:author "David Miller", :doc "Shamelessly based on the clojure.java.io package authored by Stuart Sierra, Chas Emerick, Stuart Halloway. This file defines polymorphic I/O utility functions for Clojure."} clojure.clr.io (:import (System.IO Stream BufferedStream FileInfo FileStream MemoryStream FileMode FileShare FileAccess FileOptions BinaryReader BinaryWriter StreamReader StreamWriter StringReader StringWriter TextReader TextWriter) (System.Net.Sockets Socket NetworkStream) (System.Text Encoding UTF8Encoding UnicodeEncoding UTF32Encoding UTF7Encoding ASCIIEncoding Decoder Encoder) (System Uri UriFormatException))) (defprotocol ^{:added "1.2"} Coercions "Coerce between various 'resource-namish' things." (^{:tag System.IO.FileInfo, :added "1.2"} as-file [x] "Coerce argument to a file.") (^{:tag System.Uri, :added "1.2"} as-uri [x] "Coerce argument to a URI.")) (extend-protocol Coercions nil (as-file [_] nil) (as-uri [_] nil) String (as-file [s] (FileInfo. s)) (as-uri [s] (Uri. s)) FileInfo (as-file [f] f) (as-uri [f] (Uri. (str "file://" (.FullName f)))) Uri (as-uri [u] u) (as-file [u] (if (.IsFile u) (as-file (.LocalPath u)) (throw (ArgumentException. (str "Not a file: " u)))))) (defprotocol ^{:added "1.2"} IOFactory "Factory functions that create ready-to-use, buffered versions of the various Java I/O stream types, on top of anything that can be unequivocally converted to the requested kind of stream. Common options include :buffer-size Ths size of buffer to use (default: 1024). :file-share A value from the System.IO.FileShare enumeration. :file-mode A value from the System.IO.FileMode enumeration. :file-access A value from the System.IO.FileAccess enumeration. :file-options A value from the System.IO.FileOptions enumeration. :encoding The encoding to use, either as a string, e.g. \"UTF-8\", a keyword, e.g. :utf-8, or a an System.Text.Encoding instance, e.g., (System.Text.UTF8Encoding.) Callers should generally prefer the higher level API provided by reader, writer, input-stream, and output-stream." (^{:added "1.2"} make-text-reader [x opts] "Creates a TextReader. See also IOFactory docs.") (^{:added "1.2"} make-text-writer [x opts] "Creates a TextWriter. See also IOFactory docs.") (^{:added "1.2"} make-input-stream [x opts] "Creates a Stream in input mode. See also IOFactory docs.") (^{:added "1.2"} make-output-stream [x opts] "Creates a Stream in output mode. See also IOFactory docs.") (^{:added "1.2"} make-binary-reader [x opts] "Creates a BinaryReader. See also IOFactory docs.") (^{:added "1.2"} make-binary-writer [x opts] "Creates a BinaryWriter. See also IOFactory docs.")) (defn ^TextReader text-reader "Attempts to coerce its argument into an open System.IO.TextReader. Default implementations are provided for Stream, Uri, FileInfo, Socket, byte arrays, and String. If argument is a String, it tries to resolve it first as a URI, then as a local file name. URIs with a 'file' protocol are converted to local file names. Should be used inside with-open to ensure the TextReader is properly closed." {:added "1.2"} [x & opts] (make-text-reader x (when opts (apply hash-map opts)))) (defn ^TextWriter text-writer "Attempts to coerce its argument into an open System.IO.TextWriter. Default implementations are provided for Stream, Uri, FileInfo, Socket, and String. If the argument is a String, it tries to resolve it first as a URI, then as a local file name. URIs with a 'file' protocol are converted to local file names. Should be used inside with-open to ensure the TestWriter is properly closed." {:added "1.2"} [x & opts] (make-text-writer x (when opts (apply hash-map opts)))) (defn ^Stream input-stream "Attempts to coerce its argument into an open System.IO.Stream in input mode. Default implementations are defined for Stream, FileInfo, Uri, Socket, byte array, char array, and String arguments. If the argument is a String, it tries to resolve it first as a URI, then as a local file name. URIs with a 'file' protocol are converted to local file names. Should be used inside with-open to ensure the Stream is properly closed." {:added "1.2"} [x & opts] (make-input-stream x (when opts (apply hash-map opts)))) (defn ^Stream output-stream "Attempts to coerce its argument into an open System.IO.Stream. Default implementations are defined for Stream, FileInfo, URI, Socket, and String arguments. If the argument is a String, it tries to resolve it first as a URI, then as a local file name. URIs with a 'file' protocol are converted to local file names. Should be used inside with-open to ensure the OutputStream is properly closed." {:added "1.2"} [x & opts] (make-output-stream x (when opts (apply hash-map opts)))) (defn ^BinaryReader binary-reader "Attempt to coerce its argument into an open System.IO.BinaryReader. Default implementations are defined for Stream, FileInfo, URI, Socket, byte array, and String arguments. If the argument is a String, it tries to resolve it first as a URI, then as a local file name. URIs with a 'file' protocol are converted to local file names. Should be used inside with-open to ensure the BinaryReader is properly closed." {:added "1.2"} [x & opts] (make-binary-reader x (when opts (apply hash-map opts)))) (defn ^BinaryWriter binary-writer "Attempt to coerce its argument into an open System.IO.BinaryWriter. Default implementations are defined for Stream, FileInfo, URI, Socket, and String arguments. If the argument is a String, it tries to resolve it first as a URI, then as a local file name. URIs with a 'file' protocol are converted to local file names. Should be used inside with-open to ensure the BinaryWriter is properly closed." {:added "1.2"} [x & opts] (make-binary-writer x (when opts (apply hash-map opts)))) (def string->encoding { "UTF-8" (UTF8Encoding.) "UTF-16" (UnicodeEncoding.) "UTF-32" (UTF32Encoding.) "UTF-7" (UTF7Encoding.) "ascii" (ASCIIEncoding.) "ASCII" (ASCIIEncoding.) "us-ascii" (ASCIIEncoding.) :utf8 (UTF8Encoding.) :utf16 (UnicodeEncoding.) :utf32 (UTF32Encoding.) :utf7 (UTF7Encoding.) :ascii (ASCIIEncoding.) :utf-8 (UTF8Encoding.) :utf-16 (UnicodeEncoding.) :utf-32 (UTF32Encoding.) :utf-7 (UTF7Encoding.) }) (defn- normalize-encoding [key] (if (string? key) (get string->encoding key) key)) (defn- ^Encoding encoding [opts] (or (normalize-encoding (:encoding opts)) (get string->encoding "UTF-8"))) (defn- buffer-size [opts] (or (:buffer-size opts) 1024)) (defn- ^FileMode file-mode [mode opts] (or (:file-mode opts) (if (= mode :read) FileMode/Open FileMode/OpenOrCreate))) (defn- ^FileShare file-share [opts] (or (:file-share opts) FileShare/None)) (defn- ^FileAccess file-access [mode opts] (or (:file-access opts) (if (= mode :read) FileAccess/Read FileAccess/Write))) (defn- ^FileOptions file-options [opts] (or (:file-options opts) FileOptions/None)) (def default-streams-impl {:make-text-reader (fn [x opts] (make-text-reader (make-input-stream x opts) opts)) :make-text-writer (fn [x opts] (make-text-writer (make-output-stream x opts) opts)) :make-binary-reader (fn [x opts] (make-binary-reader (make-input-stream x opts) opts)) :make-binary-writer (fn [x opts] (make-binary-writer (make-output-stream x opts) opts)) :make-input-stream (fn [x opts] (throw (ArgumentException. (str "Cannot open <" (pr-str x) "> as an input Stream.")))) :make-output-stream (fn [x opts] (throw (ArgumentException. (str "Cannot open <" (pr-str x) "> as an output Stream."))))}) (extend Stream IOFactory (assoc default-streams-impl :make-text-reader (fn [^Stream x opts] (StreamReader. x (encoding opts))) :make-text-writer (fn [^Stream x opts] (StreamWriter. x (encoding opts))) :make-binary-reader (fn [^Stream x opts] (BinaryReader. x (encoding opts))) :make-binary-writer (fn [^Stream x opts] (BinaryWriter. x (encoding opts))) :make-input-stream (fn [^Stream x opts] (if (.CanRead x) x (throw (ArgumentException. "Cannot convert non-reading stream to input stream")))) :make-output-stream (fn [^Stream x opts] (if (.CanWrite x) x (throw (ArgumentException. "Cannot convert non-reading stream to input stream")))))) (extend BinaryReader IOFactory (assoc default-streams-impl :make-binary-reader (fn [x opts] x) :make-input-stream (fn [^BinaryReader x opts] (.BaseStream x)) :make-output-stream (fn [^BinaryReader x opts] (make-output-stream (.BaseStream x) opts)))) (extend BinaryWriter IOFactory (assoc default-streams-impl :make-binary-writer (fn [x opts] x) :make-input-stream (fn [^BinaryWriter x opts] (make-input-stream (.BaseStream x) opts)) :make-output-stream (fn [^BinaryWriter x opts] (.BaseStream x)))) (extend StreamReader IOFactory (assoc default-streams-impl :make-text-reader (fn [x opts] x) :make-input-stream (fn [^StreamReader x opts] (.BaseStream x)) :make-output-stream (fn [^StreamReader x opts] (make-output-stream (.BaseStream x) opts)))) (extend StreamWriter IOFactory (assoc default-streams-impl :make-text-writer (fn [x opts] x) :make-input-stream (fn [^StreamWriter x opts] (make-input-stream (.BaseStream x) opts)) :make-output-stream (fn [^StreamWriter x opts] (.BaseStream x)))) (extend StringReader IOFactory (assoc default-streams-impl :make-text-reader (fn [x opts] x))) (extend StringWriter IOFactory (assoc default-streams-impl :make-text-writer (fn [x opts] x))) (extend FileInfo IOFactory (assoc default-streams-impl :make-input-stream (fn [^FileInfo x opts] (make-input-stream (FileStream. (.FullName x) (file-mode :read opts) (file-access :read opts) (file-share opts) (buffer-size opts) (file-options opts)) opts)) :make-output-stream (fn [^FileInfo x opts] (make-output-stream (FileStream. (.FullName x) (file-mode :write opts) (file-access :write opts) (file-share opts) (buffer-size opts) (file-options opts)) opts)))) (extend String IOFactory (assoc default-streams-impl :make-input-stream (fn [^String x opts] (try (make-input-stream (Uri. x) opts) (catch UriFormatException err (make-input-stream (FileInfo. x) opts)))) :make-output-stream (fn [^String x opts] (try (make-output-stream (Uri. x) opts) (catch UriFormatException err (make-output-stream (FileInfo. x) opts)))))) (extend Socket IOFactory (assoc default-streams-impl :make-input-stream (fn [^Socket x opts] (NetworkStream. x (file-access :read opts))) :make-output-stream (fn [^Socket x opts] (NetworkStream. x (file-access :write opts))))) (extend Uri IOFactory (assoc default-streams-impl :make-input-stream (fn [^Uri x opts] (if (.IsFile x) (make-input-stream (FileInfo. (.LocalPath x)) opts) (.OpenRead (System.Net.WebClient.) x))) :make-output-stream (fn [^Uri x opts] (if (.IsFile x) (make-output-stream (FileInfo. (.LocalPath x)) opts) (.OpenWrite (System.Net.WebClient.) x))))) (extend |System.Byte[]| IOFactory (assoc default-streams-impl :make-input-stream (fn [^|System.Byte[]| x opts] (MemoryStream. x)))) (extend Object IOFactory default-streams-impl) (extend nil IOFactory (assoc default-streams-impl :make-text-reader (fn [x opts] (throw (ArgumentException. (str "Cannot open <" (pr-str x) "> as a Reader.")))) :make-text-writer (fn [x opts] (throw (ArgumentException. (str "Cannot open <" (pr-str x) "> as a Writer.")))))) (defmulti ^{:doc "Internal helper for copy" :private true :arglists '([input output opts])} do-copy (fn [input output opts] [(type input) (type output)])) (defmethod do-copy [Stream Stream] [^Stream input ^Stream output opts] (let [ len (buffer-size opts) ^bytes buffer (make-array Byte len)] (loop [] (let [size (.Read input buffer 0 len)] (when (pos? size) (do (.Write output buffer 0 size) (recur))))))) (defmethod do-copy [Stream TextWriter] [^Stream input ^TextWriter output opts] (let [ len (buffer-size opts) ^bytes buffer (make-array Byte len) ^Decoder decoder (.GetDecoder (encoding opts)) ] (loop [] (let [size (.Read input buffer 0 len)] (when (pos? size) (let [ cnt (.GetCharCount decoder buffer 0 size) ^|System.Char[]| chbuf (make-array Char cnt)] (do (.GetChars decoder buffer 0 (int size) chbuf 0) (.Write output chbuf 0 cnt) (recur)))))))) (defmethod do-copy [Stream FileInfo] [^Stream input ^FileInfo output opts] (with-open [out (make-output-stream output opts)] (do-copy input out opts))) (defmethod do-copy [TextReader Stream] [^TextReader input ^Stream output opts] (let [ len (buffer-size opts) ^chars buffer (make-array Char len) ^Encoder encoder (.GetEncoder (encoding opts))] (loop [] (let [size (.Read input buffer 0 len)] (when (pos? size) (let [cnt (.GetByteCount encoder buffer 0 size false) bytes (make-array Byte cnt)] (do (.GetBytes encoder buffer 0 size bytes 0 false) (.Write output bytes 0 cnt) (recur)))))))) (defmethod do-copy [TextReader TextWriter] [^TextReader input ^TextWriter output opts] (let [ len (buffer-size opts) ^chars buffer (make-array Char len)] (loop [] (let [size (.Read input buffer 0 len)] (when (pos? size) (do (.Write output buffer 0 size) (recur))))))) (defmethod do-copy [TextReader FileInfo] [^TextReader input ^FileInfo output opts] (with-open [out (make-output-stream output opts)] (do-copy input out opts))) (defmethod do-copy [FileInfo Stream] [^FileInfo input ^Stream output opts] (with-open [in (make-input-stream input opts)] (do-copy in output opts))) (defmethod do-copy [FileInfo TextWriter] [^FileInfo input ^TextWriter output opts] (with-open [in (make-input-stream input opts)] (do-copy in output opts))) (defmethod do-copy [FileInfo FileInfo] [^FileInfo input ^FileInfo output opts] (with-open [in (make-input-stream input opts) out (make-output-stream output opts)] (do-copy in out opts))) (defmethod do-copy [String Stream] [^String input ^Stream output opts] (do-copy (StringReader. input) output opts)) (defmethod do-copy [String TextWriter] [^String input ^TextWriter output opts] (do-copy (StringReader. input) output opts)) (defmethod do-copy [String FileInfo] [^String input ^FileInfo output opts] (do-copy (StringReader. input) output opts)) (defmethod do-copy [|System.Byte[]| Stream] [^bytes input ^Stream output opts] (do-copy (MemoryStream. input) output opts)) (defmethod do-copy [|System.Byte[]| TextWriter] [^bytes input ^TextWriter output opts] (do-copy (MemoryStream. input) output opts)) (defmethod do-copy [|System.Byte[]| FileInfo] [^bytes input ^FileInfo output opts] (do-copy (MemoryStream. input) output opts)) (defn copy "Copies input to output. Returns nil or throws IOException. Input may be an InputStream, Reader, File, byte[], or String. Output may be an OutputStream, Writer, or File. Options are key/value pairs and may be one of :buffer-size buffer size to use, default is 1024. :encoding encoding to use if converting between byte and char streams. Does not close any streams except those it opens itself (on a File)." {:added "1.2"} [input output & opts] (do-copy input output (when opts (apply hash-map opts))))
64216
; Copyright (c) <NAME>. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns ^{:author "<NAME>", :doc "Shamelessly based on the clojure.java.io package authored by <NAME>, <NAME>, <NAME>. This file defines polymorphic I/O utility functions for Clojure."} clojure.clr.io (:import (System.IO Stream BufferedStream FileInfo FileStream MemoryStream FileMode FileShare FileAccess FileOptions BinaryReader BinaryWriter StreamReader StreamWriter StringReader StringWriter TextReader TextWriter) (System.Net.Sockets Socket NetworkStream) (System.Text Encoding UTF8Encoding UnicodeEncoding UTF32Encoding UTF7Encoding ASCIIEncoding Decoder Encoder) (System Uri UriFormatException))) (defprotocol ^{:added "1.2"} Coercions "Coerce between various 'resource-namish' things." (^{:tag System.IO.FileInfo, :added "1.2"} as-file [x] "Coerce argument to a file.") (^{:tag System.Uri, :added "1.2"} as-uri [x] "Coerce argument to a URI.")) (extend-protocol Coercions nil (as-file [_] nil) (as-uri [_] nil) String (as-file [s] (FileInfo. s)) (as-uri [s] (Uri. s)) FileInfo (as-file [f] f) (as-uri [f] (Uri. (str "file://" (.FullName f)))) Uri (as-uri [u] u) (as-file [u] (if (.IsFile u) (as-file (.LocalPath u)) (throw (ArgumentException. (str "Not a file: " u)))))) (defprotocol ^{:added "1.2"} IOFactory "Factory functions that create ready-to-use, buffered versions of the various Java I/O stream types, on top of anything that can be unequivocally converted to the requested kind of stream. Common options include :buffer-size Ths size of buffer to use (default: 1024). :file-share A value from the System.IO.FileShare enumeration. :file-mode A value from the System.IO.FileMode enumeration. :file-access A value from the System.IO.FileAccess enumeration. :file-options A value from the System.IO.FileOptions enumeration. :encoding The encoding to use, either as a string, e.g. \"UTF-8\", a keyword, e.g. :utf-8, or a an System.Text.Encoding instance, e.g., (System.Text.UTF8Encoding.) Callers should generally prefer the higher level API provided by reader, writer, input-stream, and output-stream." (^{:added "1.2"} make-text-reader [x opts] "Creates a TextReader. See also IOFactory docs.") (^{:added "1.2"} make-text-writer [x opts] "Creates a TextWriter. See also IOFactory docs.") (^{:added "1.2"} make-input-stream [x opts] "Creates a Stream in input mode. See also IOFactory docs.") (^{:added "1.2"} make-output-stream [x opts] "Creates a Stream in output mode. See also IOFactory docs.") (^{:added "1.2"} make-binary-reader [x opts] "Creates a BinaryReader. See also IOFactory docs.") (^{:added "1.2"} make-binary-writer [x opts] "Creates a BinaryWriter. See also IOFactory docs.")) (defn ^TextReader text-reader "Attempts to coerce its argument into an open System.IO.TextReader. Default implementations are provided for Stream, Uri, FileInfo, Socket, byte arrays, and String. If argument is a String, it tries to resolve it first as a URI, then as a local file name. URIs with a 'file' protocol are converted to local file names. Should be used inside with-open to ensure the TextReader is properly closed." {:added "1.2"} [x & opts] (make-text-reader x (when opts (apply hash-map opts)))) (defn ^TextWriter text-writer "Attempts to coerce its argument into an open System.IO.TextWriter. Default implementations are provided for Stream, Uri, FileInfo, Socket, and String. If the argument is a String, it tries to resolve it first as a URI, then as a local file name. URIs with a 'file' protocol are converted to local file names. Should be used inside with-open to ensure the TestWriter is properly closed." {:added "1.2"} [x & opts] (make-text-writer x (when opts (apply hash-map opts)))) (defn ^Stream input-stream "Attempts to coerce its argument into an open System.IO.Stream in input mode. Default implementations are defined for Stream, FileInfo, Uri, Socket, byte array, char array, and String arguments. If the argument is a String, it tries to resolve it first as a URI, then as a local file name. URIs with a 'file' protocol are converted to local file names. Should be used inside with-open to ensure the Stream is properly closed." {:added "1.2"} [x & opts] (make-input-stream x (when opts (apply hash-map opts)))) (defn ^Stream output-stream "Attempts to coerce its argument into an open System.IO.Stream. Default implementations are defined for Stream, FileInfo, URI, Socket, and String arguments. If the argument is a String, it tries to resolve it first as a URI, then as a local file name. URIs with a 'file' protocol are converted to local file names. Should be used inside with-open to ensure the OutputStream is properly closed." {:added "1.2"} [x & opts] (make-output-stream x (when opts (apply hash-map opts)))) (defn ^BinaryReader binary-reader "Attempt to coerce its argument into an open System.IO.BinaryReader. Default implementations are defined for Stream, FileInfo, URI, Socket, byte array, and String arguments. If the argument is a String, it tries to resolve it first as a URI, then as a local file name. URIs with a 'file' protocol are converted to local file names. Should be used inside with-open to ensure the BinaryReader is properly closed." {:added "1.2"} [x & opts] (make-binary-reader x (when opts (apply hash-map opts)))) (defn ^BinaryWriter binary-writer "Attempt to coerce its argument into an open System.IO.BinaryWriter. Default implementations are defined for Stream, FileInfo, URI, Socket, and String arguments. If the argument is a String, it tries to resolve it first as a URI, then as a local file name. URIs with a 'file' protocol are converted to local file names. Should be used inside with-open to ensure the BinaryWriter is properly closed." {:added "1.2"} [x & opts] (make-binary-writer x (when opts (apply hash-map opts)))) (def string->encoding { "UTF-8" (UTF8Encoding.) "UTF-16" (UnicodeEncoding.) "UTF-32" (UTF32Encoding.) "UTF-7" (UTF7Encoding.) "ascii" (ASCIIEncoding.) "ASCII" (ASCIIEncoding.) "us-ascii" (ASCIIEncoding.) :utf8 (UTF8Encoding.) :utf16 (UnicodeEncoding.) :utf32 (UTF32Encoding.) :utf7 (UTF7Encoding.) :ascii (ASCIIEncoding.) :utf-8 (UTF8Encoding.) :utf-16 (UnicodeEncoding.) :utf-32 (UTF32Encoding.) :utf-7 (UTF7Encoding.) }) (defn- normalize-encoding [key] (if (string? key) (get string->encoding key) key)) (defn- ^Encoding encoding [opts] (or (normalize-encoding (:encoding opts)) (get string->encoding "UTF-8"))) (defn- buffer-size [opts] (or (:buffer-size opts) 1024)) (defn- ^FileMode file-mode [mode opts] (or (:file-mode opts) (if (= mode :read) FileMode/Open FileMode/OpenOrCreate))) (defn- ^FileShare file-share [opts] (or (:file-share opts) FileShare/None)) (defn- ^FileAccess file-access [mode opts] (or (:file-access opts) (if (= mode :read) FileAccess/Read FileAccess/Write))) (defn- ^FileOptions file-options [opts] (or (:file-options opts) FileOptions/None)) (def default-streams-impl {:make-text-reader (fn [x opts] (make-text-reader (make-input-stream x opts) opts)) :make-text-writer (fn [x opts] (make-text-writer (make-output-stream x opts) opts)) :make-binary-reader (fn [x opts] (make-binary-reader (make-input-stream x opts) opts)) :make-binary-writer (fn [x opts] (make-binary-writer (make-output-stream x opts) opts)) :make-input-stream (fn [x opts] (throw (ArgumentException. (str "Cannot open <" (pr-str x) "> as an input Stream.")))) :make-output-stream (fn [x opts] (throw (ArgumentException. (str "Cannot open <" (pr-str x) "> as an output Stream."))))}) (extend Stream IOFactory (assoc default-streams-impl :make-text-reader (fn [^Stream x opts] (StreamReader. x (encoding opts))) :make-text-writer (fn [^Stream x opts] (StreamWriter. x (encoding opts))) :make-binary-reader (fn [^Stream x opts] (BinaryReader. x (encoding opts))) :make-binary-writer (fn [^Stream x opts] (BinaryWriter. x (encoding opts))) :make-input-stream (fn [^Stream x opts] (if (.CanRead x) x (throw (ArgumentException. "Cannot convert non-reading stream to input stream")))) :make-output-stream (fn [^Stream x opts] (if (.CanWrite x) x (throw (ArgumentException. "Cannot convert non-reading stream to input stream")))))) (extend BinaryReader IOFactory (assoc default-streams-impl :make-binary-reader (fn [x opts] x) :make-input-stream (fn [^BinaryReader x opts] (.BaseStream x)) :make-output-stream (fn [^BinaryReader x opts] (make-output-stream (.BaseStream x) opts)))) (extend BinaryWriter IOFactory (assoc default-streams-impl :make-binary-writer (fn [x opts] x) :make-input-stream (fn [^BinaryWriter x opts] (make-input-stream (.BaseStream x) opts)) :make-output-stream (fn [^BinaryWriter x opts] (.BaseStream x)))) (extend StreamReader IOFactory (assoc default-streams-impl :make-text-reader (fn [x opts] x) :make-input-stream (fn [^StreamReader x opts] (.BaseStream x)) :make-output-stream (fn [^StreamReader x opts] (make-output-stream (.BaseStream x) opts)))) (extend StreamWriter IOFactory (assoc default-streams-impl :make-text-writer (fn [x opts] x) :make-input-stream (fn [^StreamWriter x opts] (make-input-stream (.BaseStream x) opts)) :make-output-stream (fn [^StreamWriter x opts] (.BaseStream x)))) (extend StringReader IOFactory (assoc default-streams-impl :make-text-reader (fn [x opts] x))) (extend StringWriter IOFactory (assoc default-streams-impl :make-text-writer (fn [x opts] x))) (extend FileInfo IOFactory (assoc default-streams-impl :make-input-stream (fn [^FileInfo x opts] (make-input-stream (FileStream. (.FullName x) (file-mode :read opts) (file-access :read opts) (file-share opts) (buffer-size opts) (file-options opts)) opts)) :make-output-stream (fn [^FileInfo x opts] (make-output-stream (FileStream. (.FullName x) (file-mode :write opts) (file-access :write opts) (file-share opts) (buffer-size opts) (file-options opts)) opts)))) (extend String IOFactory (assoc default-streams-impl :make-input-stream (fn [^String x opts] (try (make-input-stream (Uri. x) opts) (catch UriFormatException err (make-input-stream (FileInfo. x) opts)))) :make-output-stream (fn [^String x opts] (try (make-output-stream (Uri. x) opts) (catch UriFormatException err (make-output-stream (FileInfo. x) opts)))))) (extend Socket IOFactory (assoc default-streams-impl :make-input-stream (fn [^Socket x opts] (NetworkStream. x (file-access :read opts))) :make-output-stream (fn [^Socket x opts] (NetworkStream. x (file-access :write opts))))) (extend Uri IOFactory (assoc default-streams-impl :make-input-stream (fn [^Uri x opts] (if (.IsFile x) (make-input-stream (FileInfo. (.LocalPath x)) opts) (.OpenRead (System.Net.WebClient.) x))) :make-output-stream (fn [^Uri x opts] (if (.IsFile x) (make-output-stream (FileInfo. (.LocalPath x)) opts) (.OpenWrite (System.Net.WebClient.) x))))) (extend |System.Byte[]| IOFactory (assoc default-streams-impl :make-input-stream (fn [^|System.Byte[]| x opts] (MemoryStream. x)))) (extend Object IOFactory default-streams-impl) (extend nil IOFactory (assoc default-streams-impl :make-text-reader (fn [x opts] (throw (ArgumentException. (str "Cannot open <" (pr-str x) "> as a Reader.")))) :make-text-writer (fn [x opts] (throw (ArgumentException. (str "Cannot open <" (pr-str x) "> as a Writer.")))))) (defmulti ^{:doc "Internal helper for copy" :private true :arglists '([input output opts])} do-copy (fn [input output opts] [(type input) (type output)])) (defmethod do-copy [Stream Stream] [^Stream input ^Stream output opts] (let [ len (buffer-size opts) ^bytes buffer (make-array Byte len)] (loop [] (let [size (.Read input buffer 0 len)] (when (pos? size) (do (.Write output buffer 0 size) (recur))))))) (defmethod do-copy [Stream TextWriter] [^Stream input ^TextWriter output opts] (let [ len (buffer-size opts) ^bytes buffer (make-array Byte len) ^Decoder decoder (.GetDecoder (encoding opts)) ] (loop [] (let [size (.Read input buffer 0 len)] (when (pos? size) (let [ cnt (.GetCharCount decoder buffer 0 size) ^|System.Char[]| chbuf (make-array Char cnt)] (do (.GetChars decoder buffer 0 (int size) chbuf 0) (.Write output chbuf 0 cnt) (recur)))))))) (defmethod do-copy [Stream FileInfo] [^Stream input ^FileInfo output opts] (with-open [out (make-output-stream output opts)] (do-copy input out opts))) (defmethod do-copy [TextReader Stream] [^TextReader input ^Stream output opts] (let [ len (buffer-size opts) ^chars buffer (make-array Char len) ^Encoder encoder (.GetEncoder (encoding opts))] (loop [] (let [size (.Read input buffer 0 len)] (when (pos? size) (let [cnt (.GetByteCount encoder buffer 0 size false) bytes (make-array Byte cnt)] (do (.GetBytes encoder buffer 0 size bytes 0 false) (.Write output bytes 0 cnt) (recur)))))))) (defmethod do-copy [TextReader TextWriter] [^TextReader input ^TextWriter output opts] (let [ len (buffer-size opts) ^chars buffer (make-array Char len)] (loop [] (let [size (.Read input buffer 0 len)] (when (pos? size) (do (.Write output buffer 0 size) (recur))))))) (defmethod do-copy [TextReader FileInfo] [^TextReader input ^FileInfo output opts] (with-open [out (make-output-stream output opts)] (do-copy input out opts))) (defmethod do-copy [FileInfo Stream] [^FileInfo input ^Stream output opts] (with-open [in (make-input-stream input opts)] (do-copy in output opts))) (defmethod do-copy [FileInfo TextWriter] [^FileInfo input ^TextWriter output opts] (with-open [in (make-input-stream input opts)] (do-copy in output opts))) (defmethod do-copy [FileInfo FileInfo] [^FileInfo input ^FileInfo output opts] (with-open [in (make-input-stream input opts) out (make-output-stream output opts)] (do-copy in out opts))) (defmethod do-copy [String Stream] [^String input ^Stream output opts] (do-copy (StringReader. input) output opts)) (defmethod do-copy [String TextWriter] [^String input ^TextWriter output opts] (do-copy (StringReader. input) output opts)) (defmethod do-copy [String FileInfo] [^String input ^FileInfo output opts] (do-copy (StringReader. input) output opts)) (defmethod do-copy [|System.Byte[]| Stream] [^bytes input ^Stream output opts] (do-copy (MemoryStream. input) output opts)) (defmethod do-copy [|System.Byte[]| TextWriter] [^bytes input ^TextWriter output opts] (do-copy (MemoryStream. input) output opts)) (defmethod do-copy [|System.Byte[]| FileInfo] [^bytes input ^FileInfo output opts] (do-copy (MemoryStream. input) output opts)) (defn copy "Copies input to output. Returns nil or throws IOException. Input may be an InputStream, Reader, File, byte[], or String. Output may be an OutputStream, Writer, or File. Options are key/value pairs and may be one of :buffer-size buffer size to use, default is 1024. :encoding encoding to use if converting between byte and char streams. Does not close any streams except those it opens itself (on a File)." {:added "1.2"} [input output & opts] (do-copy input output (when opts (apply hash-map opts))))
true
; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns ^{:author "PI:NAME:<NAME>END_PI", :doc "Shamelessly based on the clojure.java.io package authored by PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI. This file defines polymorphic I/O utility functions for Clojure."} clojure.clr.io (:import (System.IO Stream BufferedStream FileInfo FileStream MemoryStream FileMode FileShare FileAccess FileOptions BinaryReader BinaryWriter StreamReader StreamWriter StringReader StringWriter TextReader TextWriter) (System.Net.Sockets Socket NetworkStream) (System.Text Encoding UTF8Encoding UnicodeEncoding UTF32Encoding UTF7Encoding ASCIIEncoding Decoder Encoder) (System Uri UriFormatException))) (defprotocol ^{:added "1.2"} Coercions "Coerce between various 'resource-namish' things." (^{:tag System.IO.FileInfo, :added "1.2"} as-file [x] "Coerce argument to a file.") (^{:tag System.Uri, :added "1.2"} as-uri [x] "Coerce argument to a URI.")) (extend-protocol Coercions nil (as-file [_] nil) (as-uri [_] nil) String (as-file [s] (FileInfo. s)) (as-uri [s] (Uri. s)) FileInfo (as-file [f] f) (as-uri [f] (Uri. (str "file://" (.FullName f)))) Uri (as-uri [u] u) (as-file [u] (if (.IsFile u) (as-file (.LocalPath u)) (throw (ArgumentException. (str "Not a file: " u)))))) (defprotocol ^{:added "1.2"} IOFactory "Factory functions that create ready-to-use, buffered versions of the various Java I/O stream types, on top of anything that can be unequivocally converted to the requested kind of stream. Common options include :buffer-size Ths size of buffer to use (default: 1024). :file-share A value from the System.IO.FileShare enumeration. :file-mode A value from the System.IO.FileMode enumeration. :file-access A value from the System.IO.FileAccess enumeration. :file-options A value from the System.IO.FileOptions enumeration. :encoding The encoding to use, either as a string, e.g. \"UTF-8\", a keyword, e.g. :utf-8, or a an System.Text.Encoding instance, e.g., (System.Text.UTF8Encoding.) Callers should generally prefer the higher level API provided by reader, writer, input-stream, and output-stream." (^{:added "1.2"} make-text-reader [x opts] "Creates a TextReader. See also IOFactory docs.") (^{:added "1.2"} make-text-writer [x opts] "Creates a TextWriter. See also IOFactory docs.") (^{:added "1.2"} make-input-stream [x opts] "Creates a Stream in input mode. See also IOFactory docs.") (^{:added "1.2"} make-output-stream [x opts] "Creates a Stream in output mode. See also IOFactory docs.") (^{:added "1.2"} make-binary-reader [x opts] "Creates a BinaryReader. See also IOFactory docs.") (^{:added "1.2"} make-binary-writer [x opts] "Creates a BinaryWriter. See also IOFactory docs.")) (defn ^TextReader text-reader "Attempts to coerce its argument into an open System.IO.TextReader. Default implementations are provided for Stream, Uri, FileInfo, Socket, byte arrays, and String. If argument is a String, it tries to resolve it first as a URI, then as a local file name. URIs with a 'file' protocol are converted to local file names. Should be used inside with-open to ensure the TextReader is properly closed." {:added "1.2"} [x & opts] (make-text-reader x (when opts (apply hash-map opts)))) (defn ^TextWriter text-writer "Attempts to coerce its argument into an open System.IO.TextWriter. Default implementations are provided for Stream, Uri, FileInfo, Socket, and String. If the argument is a String, it tries to resolve it first as a URI, then as a local file name. URIs with a 'file' protocol are converted to local file names. Should be used inside with-open to ensure the TestWriter is properly closed." {:added "1.2"} [x & opts] (make-text-writer x (when opts (apply hash-map opts)))) (defn ^Stream input-stream "Attempts to coerce its argument into an open System.IO.Stream in input mode. Default implementations are defined for Stream, FileInfo, Uri, Socket, byte array, char array, and String arguments. If the argument is a String, it tries to resolve it first as a URI, then as a local file name. URIs with a 'file' protocol are converted to local file names. Should be used inside with-open to ensure the Stream is properly closed." {:added "1.2"} [x & opts] (make-input-stream x (when opts (apply hash-map opts)))) (defn ^Stream output-stream "Attempts to coerce its argument into an open System.IO.Stream. Default implementations are defined for Stream, FileInfo, URI, Socket, and String arguments. If the argument is a String, it tries to resolve it first as a URI, then as a local file name. URIs with a 'file' protocol are converted to local file names. Should be used inside with-open to ensure the OutputStream is properly closed." {:added "1.2"} [x & opts] (make-output-stream x (when opts (apply hash-map opts)))) (defn ^BinaryReader binary-reader "Attempt to coerce its argument into an open System.IO.BinaryReader. Default implementations are defined for Stream, FileInfo, URI, Socket, byte array, and String arguments. If the argument is a String, it tries to resolve it first as a URI, then as a local file name. URIs with a 'file' protocol are converted to local file names. Should be used inside with-open to ensure the BinaryReader is properly closed." {:added "1.2"} [x & opts] (make-binary-reader x (when opts (apply hash-map opts)))) (defn ^BinaryWriter binary-writer "Attempt to coerce its argument into an open System.IO.BinaryWriter. Default implementations are defined for Stream, FileInfo, URI, Socket, and String arguments. If the argument is a String, it tries to resolve it first as a URI, then as a local file name. URIs with a 'file' protocol are converted to local file names. Should be used inside with-open to ensure the BinaryWriter is properly closed." {:added "1.2"} [x & opts] (make-binary-writer x (when opts (apply hash-map opts)))) (def string->encoding { "UTF-8" (UTF8Encoding.) "UTF-16" (UnicodeEncoding.) "UTF-32" (UTF32Encoding.) "UTF-7" (UTF7Encoding.) "ascii" (ASCIIEncoding.) "ASCII" (ASCIIEncoding.) "us-ascii" (ASCIIEncoding.) :utf8 (UTF8Encoding.) :utf16 (UnicodeEncoding.) :utf32 (UTF32Encoding.) :utf7 (UTF7Encoding.) :ascii (ASCIIEncoding.) :utf-8 (UTF8Encoding.) :utf-16 (UnicodeEncoding.) :utf-32 (UTF32Encoding.) :utf-7 (UTF7Encoding.) }) (defn- normalize-encoding [key] (if (string? key) (get string->encoding key) key)) (defn- ^Encoding encoding [opts] (or (normalize-encoding (:encoding opts)) (get string->encoding "UTF-8"))) (defn- buffer-size [opts] (or (:buffer-size opts) 1024)) (defn- ^FileMode file-mode [mode opts] (or (:file-mode opts) (if (= mode :read) FileMode/Open FileMode/OpenOrCreate))) (defn- ^FileShare file-share [opts] (or (:file-share opts) FileShare/None)) (defn- ^FileAccess file-access [mode opts] (or (:file-access opts) (if (= mode :read) FileAccess/Read FileAccess/Write))) (defn- ^FileOptions file-options [opts] (or (:file-options opts) FileOptions/None)) (def default-streams-impl {:make-text-reader (fn [x opts] (make-text-reader (make-input-stream x opts) opts)) :make-text-writer (fn [x opts] (make-text-writer (make-output-stream x opts) opts)) :make-binary-reader (fn [x opts] (make-binary-reader (make-input-stream x opts) opts)) :make-binary-writer (fn [x opts] (make-binary-writer (make-output-stream x opts) opts)) :make-input-stream (fn [x opts] (throw (ArgumentException. (str "Cannot open <" (pr-str x) "> as an input Stream.")))) :make-output-stream (fn [x opts] (throw (ArgumentException. (str "Cannot open <" (pr-str x) "> as an output Stream."))))}) (extend Stream IOFactory (assoc default-streams-impl :make-text-reader (fn [^Stream x opts] (StreamReader. x (encoding opts))) :make-text-writer (fn [^Stream x opts] (StreamWriter. x (encoding opts))) :make-binary-reader (fn [^Stream x opts] (BinaryReader. x (encoding opts))) :make-binary-writer (fn [^Stream x opts] (BinaryWriter. x (encoding opts))) :make-input-stream (fn [^Stream x opts] (if (.CanRead x) x (throw (ArgumentException. "Cannot convert non-reading stream to input stream")))) :make-output-stream (fn [^Stream x opts] (if (.CanWrite x) x (throw (ArgumentException. "Cannot convert non-reading stream to input stream")))))) (extend BinaryReader IOFactory (assoc default-streams-impl :make-binary-reader (fn [x opts] x) :make-input-stream (fn [^BinaryReader x opts] (.BaseStream x)) :make-output-stream (fn [^BinaryReader x opts] (make-output-stream (.BaseStream x) opts)))) (extend BinaryWriter IOFactory (assoc default-streams-impl :make-binary-writer (fn [x opts] x) :make-input-stream (fn [^BinaryWriter x opts] (make-input-stream (.BaseStream x) opts)) :make-output-stream (fn [^BinaryWriter x opts] (.BaseStream x)))) (extend StreamReader IOFactory (assoc default-streams-impl :make-text-reader (fn [x opts] x) :make-input-stream (fn [^StreamReader x opts] (.BaseStream x)) :make-output-stream (fn [^StreamReader x opts] (make-output-stream (.BaseStream x) opts)))) (extend StreamWriter IOFactory (assoc default-streams-impl :make-text-writer (fn [x opts] x) :make-input-stream (fn [^StreamWriter x opts] (make-input-stream (.BaseStream x) opts)) :make-output-stream (fn [^StreamWriter x opts] (.BaseStream x)))) (extend StringReader IOFactory (assoc default-streams-impl :make-text-reader (fn [x opts] x))) (extend StringWriter IOFactory (assoc default-streams-impl :make-text-writer (fn [x opts] x))) (extend FileInfo IOFactory (assoc default-streams-impl :make-input-stream (fn [^FileInfo x opts] (make-input-stream (FileStream. (.FullName x) (file-mode :read opts) (file-access :read opts) (file-share opts) (buffer-size opts) (file-options opts)) opts)) :make-output-stream (fn [^FileInfo x opts] (make-output-stream (FileStream. (.FullName x) (file-mode :write opts) (file-access :write opts) (file-share opts) (buffer-size opts) (file-options opts)) opts)))) (extend String IOFactory (assoc default-streams-impl :make-input-stream (fn [^String x opts] (try (make-input-stream (Uri. x) opts) (catch UriFormatException err (make-input-stream (FileInfo. x) opts)))) :make-output-stream (fn [^String x opts] (try (make-output-stream (Uri. x) opts) (catch UriFormatException err (make-output-stream (FileInfo. x) opts)))))) (extend Socket IOFactory (assoc default-streams-impl :make-input-stream (fn [^Socket x opts] (NetworkStream. x (file-access :read opts))) :make-output-stream (fn [^Socket x opts] (NetworkStream. x (file-access :write opts))))) (extend Uri IOFactory (assoc default-streams-impl :make-input-stream (fn [^Uri x opts] (if (.IsFile x) (make-input-stream (FileInfo. (.LocalPath x)) opts) (.OpenRead (System.Net.WebClient.) x))) :make-output-stream (fn [^Uri x opts] (if (.IsFile x) (make-output-stream (FileInfo. (.LocalPath x)) opts) (.OpenWrite (System.Net.WebClient.) x))))) (extend |System.Byte[]| IOFactory (assoc default-streams-impl :make-input-stream (fn [^|System.Byte[]| x opts] (MemoryStream. x)))) (extend Object IOFactory default-streams-impl) (extend nil IOFactory (assoc default-streams-impl :make-text-reader (fn [x opts] (throw (ArgumentException. (str "Cannot open <" (pr-str x) "> as a Reader.")))) :make-text-writer (fn [x opts] (throw (ArgumentException. (str "Cannot open <" (pr-str x) "> as a Writer.")))))) (defmulti ^{:doc "Internal helper for copy" :private true :arglists '([input output opts])} do-copy (fn [input output opts] [(type input) (type output)])) (defmethod do-copy [Stream Stream] [^Stream input ^Stream output opts] (let [ len (buffer-size opts) ^bytes buffer (make-array Byte len)] (loop [] (let [size (.Read input buffer 0 len)] (when (pos? size) (do (.Write output buffer 0 size) (recur))))))) (defmethod do-copy [Stream TextWriter] [^Stream input ^TextWriter output opts] (let [ len (buffer-size opts) ^bytes buffer (make-array Byte len) ^Decoder decoder (.GetDecoder (encoding opts)) ] (loop [] (let [size (.Read input buffer 0 len)] (when (pos? size) (let [ cnt (.GetCharCount decoder buffer 0 size) ^|System.Char[]| chbuf (make-array Char cnt)] (do (.GetChars decoder buffer 0 (int size) chbuf 0) (.Write output chbuf 0 cnt) (recur)))))))) (defmethod do-copy [Stream FileInfo] [^Stream input ^FileInfo output opts] (with-open [out (make-output-stream output opts)] (do-copy input out opts))) (defmethod do-copy [TextReader Stream] [^TextReader input ^Stream output opts] (let [ len (buffer-size opts) ^chars buffer (make-array Char len) ^Encoder encoder (.GetEncoder (encoding opts))] (loop [] (let [size (.Read input buffer 0 len)] (when (pos? size) (let [cnt (.GetByteCount encoder buffer 0 size false) bytes (make-array Byte cnt)] (do (.GetBytes encoder buffer 0 size bytes 0 false) (.Write output bytes 0 cnt) (recur)))))))) (defmethod do-copy [TextReader TextWriter] [^TextReader input ^TextWriter output opts] (let [ len (buffer-size opts) ^chars buffer (make-array Char len)] (loop [] (let [size (.Read input buffer 0 len)] (when (pos? size) (do (.Write output buffer 0 size) (recur))))))) (defmethod do-copy [TextReader FileInfo] [^TextReader input ^FileInfo output opts] (with-open [out (make-output-stream output opts)] (do-copy input out opts))) (defmethod do-copy [FileInfo Stream] [^FileInfo input ^Stream output opts] (with-open [in (make-input-stream input opts)] (do-copy in output opts))) (defmethod do-copy [FileInfo TextWriter] [^FileInfo input ^TextWriter output opts] (with-open [in (make-input-stream input opts)] (do-copy in output opts))) (defmethod do-copy [FileInfo FileInfo] [^FileInfo input ^FileInfo output opts] (with-open [in (make-input-stream input opts) out (make-output-stream output opts)] (do-copy in out opts))) (defmethod do-copy [String Stream] [^String input ^Stream output opts] (do-copy (StringReader. input) output opts)) (defmethod do-copy [String TextWriter] [^String input ^TextWriter output opts] (do-copy (StringReader. input) output opts)) (defmethod do-copy [String FileInfo] [^String input ^FileInfo output opts] (do-copy (StringReader. input) output opts)) (defmethod do-copy [|System.Byte[]| Stream] [^bytes input ^Stream output opts] (do-copy (MemoryStream. input) output opts)) (defmethod do-copy [|System.Byte[]| TextWriter] [^bytes input ^TextWriter output opts] (do-copy (MemoryStream. input) output opts)) (defmethod do-copy [|System.Byte[]| FileInfo] [^bytes input ^FileInfo output opts] (do-copy (MemoryStream. input) output opts)) (defn copy "Copies input to output. Returns nil or throws IOException. Input may be an InputStream, Reader, File, byte[], or String. Output may be an OutputStream, Writer, or File. Options are key/value pairs and may be one of :buffer-size buffer size to use, default is 1024. :encoding encoding to use if converting between byte and char streams. Does not close any streams except those it opens itself (on a File)." {:added "1.2"} [input output & opts] (do-copy input output (when opts (apply hash-map opts))))
[ { "context": "{ :location (string/join \",\" lat-lon)\n :key \"elQO3jwiKxEGzcGkqD0hY5yMDzaRrCxd\"}))\n\n(defn cidade-lat-lon\n [lat-lon-response]\n ", "end": 2018, "score": 0.9995966553688049, "start": 1986, "tag": "KEY", "value": "elQO3jwiKxEGzcGkqD0hY5yMDzaRrCxd" } ]
src/clojure_analytics/core.clj
MrDallOca/clojure-analytics
2
(ns clojure-analytics.core (:require [clj-http.client :as client] [clojure.data.json :as json] [clojure.string :as string] [clojure.spec :as s])) (defn url-args [m] (let [argfy (fn [acc [k v]] (if (keyword? k) (str acc (subs (str k) 1) "=" (string/replace v #" " "%20") "&") (str acc (str k) "=" (string/replace v #" " "%20") "&"))) asdf (reduce argfy "" m)] (subs asdf 0 (- (count asdf) 1)))) (defn temNet? [] true) (defn consulta ( [onde] (binding [clj-http.core/*cookie-store* (clj-http.cookies/cookie-store)] (-> (str onde) (client/get {:as :auto}) (:body)))) ( [onde args] (-> (binding [clj-http.core/*cookie-store* (clj-http.cookies/cookie-store)] (-> (str onde "?" (url-args args)) (client/get {:as :auto}) (:body)))))) (defn consulta-json ( [onde] (-> (consulta onde) (json/read-str :key-fn keyword))) ( [onde args] (-> (consulta onde args) (json/read-str :key-fn keyword)))) (defn consulta-no-futuro [& args] (future (apply consulta args))) (defn consultar-local [] (consulta-json "http://ipinfo.io/json")) (defn consultar-tempo [& {:keys [lat-lon cidade]}] (if (nil? lat-lon) (if (nil? cidade) nil (consulta-json "http://api.openweathermap.org/data/2.5/weather" { :q (str cidade) :lang "pt" :units "metric" :appid "effecbe8e48b82f1d0aed912553d1a75"})) (consulta-json "http://api.openweathermap.org/data/2.5/weather" { :lat (get lat-lon 0) :lon (get lat-lon 1) :lang "pt" :units "metric" :appid "effecbe8e48b82f1d0aed912553d1a75"}))) (defn consultar-lat-lon [lat-lon] (consulta-json "http://www.mapquestapi.com/geocoding/v1/reverse" { :location (string/join "," lat-lon) :key "elQO3jwiKxEGzcGkqD0hY5yMDzaRrCxd"})) (defn cidade-lat-lon [lat-lon-response] (if (empty? (:results lat-lon-response)) nil (-> (:results lat-lon-response) (first) (:locations) (first) (:adminArea5)))) (defn consultar-tempo-aqui [] (let [ local (consultar-local) lat-lon (string/split (:loc local) #",") tempo (consultar-tempo lat-lon)] tempo)) (defn consultar-wiki [topico] (let [ args (-> { :format "json" :action "query" :prop "extracts" :exintro "" :utf8 "" :explaintext "" :titles (str topico)} (url-args)) feio (-> (str "https://en.wikipedia.org/w/api.php?" args) (slurp) (string/split #"\"extract\":\"") (second))] (if (empty? feio) nil (if (re-find #"(\\n)" feio) (first (string/split feio #"(\\n)")) (string/replace feio "\"}}}}" ""))))) (defn notificar-quando-acabar [task msgInicio msgFim] (println (str msgInicio)) (future (#(do (println (str msgFim)) (println %)) (time @task))))
76453
(ns clojure-analytics.core (:require [clj-http.client :as client] [clojure.data.json :as json] [clojure.string :as string] [clojure.spec :as s])) (defn url-args [m] (let [argfy (fn [acc [k v]] (if (keyword? k) (str acc (subs (str k) 1) "=" (string/replace v #" " "%20") "&") (str acc (str k) "=" (string/replace v #" " "%20") "&"))) asdf (reduce argfy "" m)] (subs asdf 0 (- (count asdf) 1)))) (defn temNet? [] true) (defn consulta ( [onde] (binding [clj-http.core/*cookie-store* (clj-http.cookies/cookie-store)] (-> (str onde) (client/get {:as :auto}) (:body)))) ( [onde args] (-> (binding [clj-http.core/*cookie-store* (clj-http.cookies/cookie-store)] (-> (str onde "?" (url-args args)) (client/get {:as :auto}) (:body)))))) (defn consulta-json ( [onde] (-> (consulta onde) (json/read-str :key-fn keyword))) ( [onde args] (-> (consulta onde args) (json/read-str :key-fn keyword)))) (defn consulta-no-futuro [& args] (future (apply consulta args))) (defn consultar-local [] (consulta-json "http://ipinfo.io/json")) (defn consultar-tempo [& {:keys [lat-lon cidade]}] (if (nil? lat-lon) (if (nil? cidade) nil (consulta-json "http://api.openweathermap.org/data/2.5/weather" { :q (str cidade) :lang "pt" :units "metric" :appid "effecbe8e48b82f1d0aed912553d1a75"})) (consulta-json "http://api.openweathermap.org/data/2.5/weather" { :lat (get lat-lon 0) :lon (get lat-lon 1) :lang "pt" :units "metric" :appid "effecbe8e48b82f1d0aed912553d1a75"}))) (defn consultar-lat-lon [lat-lon] (consulta-json "http://www.mapquestapi.com/geocoding/v1/reverse" { :location (string/join "," lat-lon) :key "<KEY>"})) (defn cidade-lat-lon [lat-lon-response] (if (empty? (:results lat-lon-response)) nil (-> (:results lat-lon-response) (first) (:locations) (first) (:adminArea5)))) (defn consultar-tempo-aqui [] (let [ local (consultar-local) lat-lon (string/split (:loc local) #",") tempo (consultar-tempo lat-lon)] tempo)) (defn consultar-wiki [topico] (let [ args (-> { :format "json" :action "query" :prop "extracts" :exintro "" :utf8 "" :explaintext "" :titles (str topico)} (url-args)) feio (-> (str "https://en.wikipedia.org/w/api.php?" args) (slurp) (string/split #"\"extract\":\"") (second))] (if (empty? feio) nil (if (re-find #"(\\n)" feio) (first (string/split feio #"(\\n)")) (string/replace feio "\"}}}}" ""))))) (defn notificar-quando-acabar [task msgInicio msgFim] (println (str msgInicio)) (future (#(do (println (str msgFim)) (println %)) (time @task))))
true
(ns clojure-analytics.core (:require [clj-http.client :as client] [clojure.data.json :as json] [clojure.string :as string] [clojure.spec :as s])) (defn url-args [m] (let [argfy (fn [acc [k v]] (if (keyword? k) (str acc (subs (str k) 1) "=" (string/replace v #" " "%20") "&") (str acc (str k) "=" (string/replace v #" " "%20") "&"))) asdf (reduce argfy "" m)] (subs asdf 0 (- (count asdf) 1)))) (defn temNet? [] true) (defn consulta ( [onde] (binding [clj-http.core/*cookie-store* (clj-http.cookies/cookie-store)] (-> (str onde) (client/get {:as :auto}) (:body)))) ( [onde args] (-> (binding [clj-http.core/*cookie-store* (clj-http.cookies/cookie-store)] (-> (str onde "?" (url-args args)) (client/get {:as :auto}) (:body)))))) (defn consulta-json ( [onde] (-> (consulta onde) (json/read-str :key-fn keyword))) ( [onde args] (-> (consulta onde args) (json/read-str :key-fn keyword)))) (defn consulta-no-futuro [& args] (future (apply consulta args))) (defn consultar-local [] (consulta-json "http://ipinfo.io/json")) (defn consultar-tempo [& {:keys [lat-lon cidade]}] (if (nil? lat-lon) (if (nil? cidade) nil (consulta-json "http://api.openweathermap.org/data/2.5/weather" { :q (str cidade) :lang "pt" :units "metric" :appid "effecbe8e48b82f1d0aed912553d1a75"})) (consulta-json "http://api.openweathermap.org/data/2.5/weather" { :lat (get lat-lon 0) :lon (get lat-lon 1) :lang "pt" :units "metric" :appid "effecbe8e48b82f1d0aed912553d1a75"}))) (defn consultar-lat-lon [lat-lon] (consulta-json "http://www.mapquestapi.com/geocoding/v1/reverse" { :location (string/join "," lat-lon) :key "PI:KEY:<KEY>END_PI"})) (defn cidade-lat-lon [lat-lon-response] (if (empty? (:results lat-lon-response)) nil (-> (:results lat-lon-response) (first) (:locations) (first) (:adminArea5)))) (defn consultar-tempo-aqui [] (let [ local (consultar-local) lat-lon (string/split (:loc local) #",") tempo (consultar-tempo lat-lon)] tempo)) (defn consultar-wiki [topico] (let [ args (-> { :format "json" :action "query" :prop "extracts" :exintro "" :utf8 "" :explaintext "" :titles (str topico)} (url-args)) feio (-> (str "https://en.wikipedia.org/w/api.php?" args) (slurp) (string/split #"\"extract\":\"") (second))] (if (empty? feio) nil (if (re-find #"(\\n)" feio) (first (string/split feio #"(\\n)")) (string/replace feio "\"}}}}" ""))))) (defn notificar-quando-acabar [task msgInicio msgFim] (println (str msgInicio)) (future (#(do (println (str msgFim)) (println %)) (time @task))))
[ { "context": " \"\n \"AND a.screen_name = s.ust_full_name \"\n \"AN", "end": 2863, "score": 0.5419369339942932, "start": 2862, "tag": "NAME", "value": "s" }, { "context": " \"\n \"AND a.screen_name = s.ust_full_name \"\n \"AND a.name = ?) ", "end": 2877, "score": 0.8619318008422852, "start": 2864, "tag": "USERNAME", "value": "ust_full_name" }, { "context": "ember-model)\n member-name-col (get-column \"usr_twitter_username\" member-model)]\n (->\n (db/select* model)\n", "end": 6829, "score": 0.9962488412857056, "start": 6809, "tag": "USERNAME", "value": "usr_twitter_username" } ]
src/repository/timely_status.clj
thierrymarianne/devobs-worker
0
(ns repository.timely-status (:require [korma.core :as db]) (:use [korma.db] [repository.database-schema] [repository.query-executor] [utils.string])) (declare timely-status) (defn get-timely-status-model [connection] (db/defentity timely-status (db/pk :id) (db/table :timely_status) (db/database connection) (db/entity-fields :publication_date_time :member_name :aggregate_id :aggregate_name :status_id :time_range)) timely-status) (defn get-timely-statuses-for-aggregate "Get total statuses and ids of statuses related to the aggregate, which name is passed as first argument for a given week of the year" ; Relies on raw statuses ([{aggregate-id :aggregate-id aggregate-name :aggregate-name publication-week :publication-week publication-year :publication-year are-archived :are-archived exclude-member-aggregate :exclude-member-aggregate}] (let [table-name (if are-archived "weaving_archived_status" "weaving_status") join-table-name (if are-archived "weaving_archived_status_aggregate" "weaving_status_aggregate") join-condition (cond (some? exclude-member-aggregate) "AND a.screen_name IS NULL " (some? are-archived) "" :else "AND a.screen_name IS NOT NULL ") restriction-by-aggregate-id (if aggregate-id "AND a.id = ? " "") restriction-by-week (if publication-week "AND EXTRACT(WEEK FROM s.ust_created_at) = ?" "") query (str "SELECT " "COUNT(*) \"total-timely-statuses\", " "COALESCE( " " array_to_string(array_agg(s.ust_id), ','), " " '' " ") \"statuses-ids\" " "FROM " table-name " s " "INNER JOIN " join-table-name " sa " "ON sa.status_id = s.ust_id " "INNER JOIN publishers_list a " "ON (a.id = sa.aggregate_id " "AND a.screen_name = s.ust_full_name " "AND a.name = ?) " join-condition "AND (s.ust_id, a.id) NOT IN ( " " SELECT status_id, aggregate_id " " FROM timely_status " ") " "AND EXTRACT(YEAR FROM s.ust_created_at) = ? " restriction-by-aggregate-id restriction-by-week) params [aggregate-name publication-year] may-include-aggregate-id (if aggregate-id (conj params aggregate-id) params) may-include-week (if publication-week (conj params publication-week) may-include-aggregate-id) results (db/exec-raw [query may-include-week] :results) record (first results) ids (explode #"," (:statuses-ids record)) total-timely-statuses (:total-timely-statuses record) statuses-ids (if (= (first ids) "") '(0) (map #(Long/parseLong %) ids))] {:statuses-ids statuses-ids :total-timely-statuses total-timely-statuses})) ([aggregate-name publication-week publication-year & [are-archived]] (get-timely-statuses-for-aggregate {:aggregate-name aggregate-name :publication-week publication-week :publication-year publication-year :are-archived are-archived}))) (defn find-timely-statuses-by-aggregate-and-publication-date "Find the timely status statuses of a member published on a given day" ; Relies on available timely statuses ([aggregate-name] (let [results (find-timely-statuses-by-aggregate-and-publication-date aggregate-name nil)] results)) ([aggregate-name publication-date] (let [base-query (str " SELECT ts.status_id as \"status-id\" FROM timely_status ts WHERE ts.aggregate_name = ? ") query (if (nil? publication-date) (str base-query "AND NOW()::date <= ts.publication_date_time::date ") (str base-query "AND CAST(? AS date) = ts.publication_date_time::date ")) params (if (nil? publication-date) [aggregate-name] [aggregate-name publication-date]) query (str query "GROUP BY ts.status_id") results (db/exec-raw [query params] :results)] results))) (defn find-aggregate-having-publication-from-date "Find the distinct aggregates for which publications have been collected for a given date" [date aggregate & [include-aggregate]] (let [aggregate-clause (str (if (some? include-aggregate) " AND aggregate_name = (?) " " AND aggregate_name != (?) ")) query (str "SELECT DISTINCT aggregate_name as \"aggregate-name\" " "FROM ( " " SELECT aggregate_name FROM timely_status " " WHERE publication_date_time::date = CAST(? as date) " aggregate-clause " GROUP BY aggregate_id, aggregate_name " ") select_") query (str query) results (db/exec-raw [query [date aggregate]] :results)] results)) (defn select-fields [model status-model member-model] (let [status-api-document-col (get-column "ust_api_document" status-model) status-id-col (get-column "ust_id" status-model) member-id-col (get-column "usr_id" member-model) member-name-col (get-column "usr_twitter_username" member-model)] (-> (db/select* model) (db/fields :id [status-api-document-col :status-api-document] [member-id-col :member-id] [:aggregate_id :aggregate-id] [:aggregate_name :aggregate-name] [:member_name :member-name] [:status_id :status-id] [:publication_date_time :publication-date-time]) (db/join status-model (= status-id-col :status_id)) (db/join member-model (= member-name-col :member_name))))) (defn find-by-ids "Find timely statuses by their ids" [timely-statuses-ids {model :timely-status status-model :status member-model :members}] (let [ids (if timely-statuses-ids timely-statuses-ids '(0)) matching-statuses (-> (select-fields model status-model member-model) (db/where {:id [in ids]}) (db/select))] (if matching-statuses matching-statuses '()))) (defn find-last-week-timely-status [] (let [query (str "SELECT ts.id, s.ust_api_document as \"status-api-document\", e.member_id as \"member-id\", ts.member_name as \"member-name\", ts.aggregate_name as \"aggregate-name\", ts.status_id as \"status-id\", ts.publication_date_time as \"publication-date-time\" FROM publication_batch_collected_event e INNER JOIN weaving_user m ON m.usr_id = e.member_id AND DATEDIFF(NOW(), e.occurred_at) <= 7 INNER JOIN timely_status ts ON member_name = m.usr_twitter_username LEFT JOIN keyword k ON k.status_id = ts.status_id INNER JOIN weaving_status s ON s.ust_id = ts.status_id WHERE k.id IS NULL LIMIT 10000;") query (str query) results (db/exec-raw [query []] :results)] results)) (defn find-timely-statuses-by-constraints "Find timely statuses by ids of statuses or constraints" ([constraints {model :timely-status member-model :members status-model :status}] (let [{columns :columns values :values default-values :default-values} constraints constraining-values (if (pos? (count values)) values default-values) matching-statuses (-> (select-fields model status-model member-model) (db/where (in columns constraining-values)) (db/select))] (if matching-statuses matching-statuses '()))) ([statuses-ids aggregate-name {model :timely-status member-model :members status-model :status}] (let [ids (if statuses-ids statuses-ids '(0)) matching-statuses (-> (select-fields model status-model member-model) (db/where (and (= :aggregate_name aggregate-name) (in :status_id ids))) (db/select))] (if matching-statuses matching-statuses '())))) (defn find-timely-statuses-by-aggregate-name [aggregate-name models] (find-timely-statuses-by-constraints {:columns [:aggregate_name] :default-values '("") :values [aggregate-name]} models)) (defn find-timely-statuses-by-aggregate-id [aggregate-id models] (find-timely-statuses-by-constraints {:columns [:aggregate_id] :default-values '(0) :values [aggregate-id]} models)) (defn bulk-insert-timely-statuses-from-aggregate [aggregate-id] (let [query (str " INSERT INTO timely_status ( id, status_id, member_name, aggregate_id, aggregate_name, publication_date_time, time_range ) SELECT UUID() AS id, s.ust_id AS status_id, s.ust_full_name AS member_name, a.id AS aggregate_id, a.name AS aggregate_name, s.ust_created_at AS publication_date_time, CASE WHEN s.ust_created_at > NOW()::timestamp - '5 MINUTES'::INTERVAL THEN 0 WHEN s.ust_created_at > NOW()::timestamp - '10 MINUTES'::INTERVAL THEN 1 WHEN s.ust_created_at > NOW()::timestamp - '30 MINUTES'::INTERVAL THEN 2 WHEN s.ust_created_at > NOW()::timestamp - '1 DAY'::INTERVAL THEN 3 WHEN s.ust_created_at > NOW()::timestamp - '1 WEEK'::INTERVAL THEN 4 ELSE 5 END AS time_range FROM publishers_list AS a INNER JOIN weaving_status_aggregate sa ON sa.aggregate_id = a.id INNER JOIN weaving_status AS s ON s.ust_id = sa.status_id WHERE a.id = ? AND (s.ust_id, a.id) NOT IN ( SELECT status_id, aggregate_id FROM timely_status )") count (exec-query [query [aggregate-id]])] (first count)))
35736
(ns repository.timely-status (:require [korma.core :as db]) (:use [korma.db] [repository.database-schema] [repository.query-executor] [utils.string])) (declare timely-status) (defn get-timely-status-model [connection] (db/defentity timely-status (db/pk :id) (db/table :timely_status) (db/database connection) (db/entity-fields :publication_date_time :member_name :aggregate_id :aggregate_name :status_id :time_range)) timely-status) (defn get-timely-statuses-for-aggregate "Get total statuses and ids of statuses related to the aggregate, which name is passed as first argument for a given week of the year" ; Relies on raw statuses ([{aggregate-id :aggregate-id aggregate-name :aggregate-name publication-week :publication-week publication-year :publication-year are-archived :are-archived exclude-member-aggregate :exclude-member-aggregate}] (let [table-name (if are-archived "weaving_archived_status" "weaving_status") join-table-name (if are-archived "weaving_archived_status_aggregate" "weaving_status_aggregate") join-condition (cond (some? exclude-member-aggregate) "AND a.screen_name IS NULL " (some? are-archived) "" :else "AND a.screen_name IS NOT NULL ") restriction-by-aggregate-id (if aggregate-id "AND a.id = ? " "") restriction-by-week (if publication-week "AND EXTRACT(WEEK FROM s.ust_created_at) = ?" "") query (str "SELECT " "COUNT(*) \"total-timely-statuses\", " "COALESCE( " " array_to_string(array_agg(s.ust_id), ','), " " '' " ") \"statuses-ids\" " "FROM " table-name " s " "INNER JOIN " join-table-name " sa " "ON sa.status_id = s.ust_id " "INNER JOIN publishers_list a " "ON (a.id = sa.aggregate_id " "AND a.screen_name = <NAME>.ust_full_name " "AND a.name = ?) " join-condition "AND (s.ust_id, a.id) NOT IN ( " " SELECT status_id, aggregate_id " " FROM timely_status " ") " "AND EXTRACT(YEAR FROM s.ust_created_at) = ? " restriction-by-aggregate-id restriction-by-week) params [aggregate-name publication-year] may-include-aggregate-id (if aggregate-id (conj params aggregate-id) params) may-include-week (if publication-week (conj params publication-week) may-include-aggregate-id) results (db/exec-raw [query may-include-week] :results) record (first results) ids (explode #"," (:statuses-ids record)) total-timely-statuses (:total-timely-statuses record) statuses-ids (if (= (first ids) "") '(0) (map #(Long/parseLong %) ids))] {:statuses-ids statuses-ids :total-timely-statuses total-timely-statuses})) ([aggregate-name publication-week publication-year & [are-archived]] (get-timely-statuses-for-aggregate {:aggregate-name aggregate-name :publication-week publication-week :publication-year publication-year :are-archived are-archived}))) (defn find-timely-statuses-by-aggregate-and-publication-date "Find the timely status statuses of a member published on a given day" ; Relies on available timely statuses ([aggregate-name] (let [results (find-timely-statuses-by-aggregate-and-publication-date aggregate-name nil)] results)) ([aggregate-name publication-date] (let [base-query (str " SELECT ts.status_id as \"status-id\" FROM timely_status ts WHERE ts.aggregate_name = ? ") query (if (nil? publication-date) (str base-query "AND NOW()::date <= ts.publication_date_time::date ") (str base-query "AND CAST(? AS date) = ts.publication_date_time::date ")) params (if (nil? publication-date) [aggregate-name] [aggregate-name publication-date]) query (str query "GROUP BY ts.status_id") results (db/exec-raw [query params] :results)] results))) (defn find-aggregate-having-publication-from-date "Find the distinct aggregates for which publications have been collected for a given date" [date aggregate & [include-aggregate]] (let [aggregate-clause (str (if (some? include-aggregate) " AND aggregate_name = (?) " " AND aggregate_name != (?) ")) query (str "SELECT DISTINCT aggregate_name as \"aggregate-name\" " "FROM ( " " SELECT aggregate_name FROM timely_status " " WHERE publication_date_time::date = CAST(? as date) " aggregate-clause " GROUP BY aggregate_id, aggregate_name " ") select_") query (str query) results (db/exec-raw [query [date aggregate]] :results)] results)) (defn select-fields [model status-model member-model] (let [status-api-document-col (get-column "ust_api_document" status-model) status-id-col (get-column "ust_id" status-model) member-id-col (get-column "usr_id" member-model) member-name-col (get-column "usr_twitter_username" member-model)] (-> (db/select* model) (db/fields :id [status-api-document-col :status-api-document] [member-id-col :member-id] [:aggregate_id :aggregate-id] [:aggregate_name :aggregate-name] [:member_name :member-name] [:status_id :status-id] [:publication_date_time :publication-date-time]) (db/join status-model (= status-id-col :status_id)) (db/join member-model (= member-name-col :member_name))))) (defn find-by-ids "Find timely statuses by their ids" [timely-statuses-ids {model :timely-status status-model :status member-model :members}] (let [ids (if timely-statuses-ids timely-statuses-ids '(0)) matching-statuses (-> (select-fields model status-model member-model) (db/where {:id [in ids]}) (db/select))] (if matching-statuses matching-statuses '()))) (defn find-last-week-timely-status [] (let [query (str "SELECT ts.id, s.ust_api_document as \"status-api-document\", e.member_id as \"member-id\", ts.member_name as \"member-name\", ts.aggregate_name as \"aggregate-name\", ts.status_id as \"status-id\", ts.publication_date_time as \"publication-date-time\" FROM publication_batch_collected_event e INNER JOIN weaving_user m ON m.usr_id = e.member_id AND DATEDIFF(NOW(), e.occurred_at) <= 7 INNER JOIN timely_status ts ON member_name = m.usr_twitter_username LEFT JOIN keyword k ON k.status_id = ts.status_id INNER JOIN weaving_status s ON s.ust_id = ts.status_id WHERE k.id IS NULL LIMIT 10000;") query (str query) results (db/exec-raw [query []] :results)] results)) (defn find-timely-statuses-by-constraints "Find timely statuses by ids of statuses or constraints" ([constraints {model :timely-status member-model :members status-model :status}] (let [{columns :columns values :values default-values :default-values} constraints constraining-values (if (pos? (count values)) values default-values) matching-statuses (-> (select-fields model status-model member-model) (db/where (in columns constraining-values)) (db/select))] (if matching-statuses matching-statuses '()))) ([statuses-ids aggregate-name {model :timely-status member-model :members status-model :status}] (let [ids (if statuses-ids statuses-ids '(0)) matching-statuses (-> (select-fields model status-model member-model) (db/where (and (= :aggregate_name aggregate-name) (in :status_id ids))) (db/select))] (if matching-statuses matching-statuses '())))) (defn find-timely-statuses-by-aggregate-name [aggregate-name models] (find-timely-statuses-by-constraints {:columns [:aggregate_name] :default-values '("") :values [aggregate-name]} models)) (defn find-timely-statuses-by-aggregate-id [aggregate-id models] (find-timely-statuses-by-constraints {:columns [:aggregate_id] :default-values '(0) :values [aggregate-id]} models)) (defn bulk-insert-timely-statuses-from-aggregate [aggregate-id] (let [query (str " INSERT INTO timely_status ( id, status_id, member_name, aggregate_id, aggregate_name, publication_date_time, time_range ) SELECT UUID() AS id, s.ust_id AS status_id, s.ust_full_name AS member_name, a.id AS aggregate_id, a.name AS aggregate_name, s.ust_created_at AS publication_date_time, CASE WHEN s.ust_created_at > NOW()::timestamp - '5 MINUTES'::INTERVAL THEN 0 WHEN s.ust_created_at > NOW()::timestamp - '10 MINUTES'::INTERVAL THEN 1 WHEN s.ust_created_at > NOW()::timestamp - '30 MINUTES'::INTERVAL THEN 2 WHEN s.ust_created_at > NOW()::timestamp - '1 DAY'::INTERVAL THEN 3 WHEN s.ust_created_at > NOW()::timestamp - '1 WEEK'::INTERVAL THEN 4 ELSE 5 END AS time_range FROM publishers_list AS a INNER JOIN weaving_status_aggregate sa ON sa.aggregate_id = a.id INNER JOIN weaving_status AS s ON s.ust_id = sa.status_id WHERE a.id = ? AND (s.ust_id, a.id) NOT IN ( SELECT status_id, aggregate_id FROM timely_status )") count (exec-query [query [aggregate-id]])] (first count)))
true
(ns repository.timely-status (:require [korma.core :as db]) (:use [korma.db] [repository.database-schema] [repository.query-executor] [utils.string])) (declare timely-status) (defn get-timely-status-model [connection] (db/defentity timely-status (db/pk :id) (db/table :timely_status) (db/database connection) (db/entity-fields :publication_date_time :member_name :aggregate_id :aggregate_name :status_id :time_range)) timely-status) (defn get-timely-statuses-for-aggregate "Get total statuses and ids of statuses related to the aggregate, which name is passed as first argument for a given week of the year" ; Relies on raw statuses ([{aggregate-id :aggregate-id aggregate-name :aggregate-name publication-week :publication-week publication-year :publication-year are-archived :are-archived exclude-member-aggregate :exclude-member-aggregate}] (let [table-name (if are-archived "weaving_archived_status" "weaving_status") join-table-name (if are-archived "weaving_archived_status_aggregate" "weaving_status_aggregate") join-condition (cond (some? exclude-member-aggregate) "AND a.screen_name IS NULL " (some? are-archived) "" :else "AND a.screen_name IS NOT NULL ") restriction-by-aggregate-id (if aggregate-id "AND a.id = ? " "") restriction-by-week (if publication-week "AND EXTRACT(WEEK FROM s.ust_created_at) = ?" "") query (str "SELECT " "COUNT(*) \"total-timely-statuses\", " "COALESCE( " " array_to_string(array_agg(s.ust_id), ','), " " '' " ") \"statuses-ids\" " "FROM " table-name " s " "INNER JOIN " join-table-name " sa " "ON sa.status_id = s.ust_id " "INNER JOIN publishers_list a " "ON (a.id = sa.aggregate_id " "AND a.screen_name = PI:NAME:<NAME>END_PI.ust_full_name " "AND a.name = ?) " join-condition "AND (s.ust_id, a.id) NOT IN ( " " SELECT status_id, aggregate_id " " FROM timely_status " ") " "AND EXTRACT(YEAR FROM s.ust_created_at) = ? " restriction-by-aggregate-id restriction-by-week) params [aggregate-name publication-year] may-include-aggregate-id (if aggregate-id (conj params aggregate-id) params) may-include-week (if publication-week (conj params publication-week) may-include-aggregate-id) results (db/exec-raw [query may-include-week] :results) record (first results) ids (explode #"," (:statuses-ids record)) total-timely-statuses (:total-timely-statuses record) statuses-ids (if (= (first ids) "") '(0) (map #(Long/parseLong %) ids))] {:statuses-ids statuses-ids :total-timely-statuses total-timely-statuses})) ([aggregate-name publication-week publication-year & [are-archived]] (get-timely-statuses-for-aggregate {:aggregate-name aggregate-name :publication-week publication-week :publication-year publication-year :are-archived are-archived}))) (defn find-timely-statuses-by-aggregate-and-publication-date "Find the timely status statuses of a member published on a given day" ; Relies on available timely statuses ([aggregate-name] (let [results (find-timely-statuses-by-aggregate-and-publication-date aggregate-name nil)] results)) ([aggregate-name publication-date] (let [base-query (str " SELECT ts.status_id as \"status-id\" FROM timely_status ts WHERE ts.aggregate_name = ? ") query (if (nil? publication-date) (str base-query "AND NOW()::date <= ts.publication_date_time::date ") (str base-query "AND CAST(? AS date) = ts.publication_date_time::date ")) params (if (nil? publication-date) [aggregate-name] [aggregate-name publication-date]) query (str query "GROUP BY ts.status_id") results (db/exec-raw [query params] :results)] results))) (defn find-aggregate-having-publication-from-date "Find the distinct aggregates for which publications have been collected for a given date" [date aggregate & [include-aggregate]] (let [aggregate-clause (str (if (some? include-aggregate) " AND aggregate_name = (?) " " AND aggregate_name != (?) ")) query (str "SELECT DISTINCT aggregate_name as \"aggregate-name\" " "FROM ( " " SELECT aggregate_name FROM timely_status " " WHERE publication_date_time::date = CAST(? as date) " aggregate-clause " GROUP BY aggregate_id, aggregate_name " ") select_") query (str query) results (db/exec-raw [query [date aggregate]] :results)] results)) (defn select-fields [model status-model member-model] (let [status-api-document-col (get-column "ust_api_document" status-model) status-id-col (get-column "ust_id" status-model) member-id-col (get-column "usr_id" member-model) member-name-col (get-column "usr_twitter_username" member-model)] (-> (db/select* model) (db/fields :id [status-api-document-col :status-api-document] [member-id-col :member-id] [:aggregate_id :aggregate-id] [:aggregate_name :aggregate-name] [:member_name :member-name] [:status_id :status-id] [:publication_date_time :publication-date-time]) (db/join status-model (= status-id-col :status_id)) (db/join member-model (= member-name-col :member_name))))) (defn find-by-ids "Find timely statuses by their ids" [timely-statuses-ids {model :timely-status status-model :status member-model :members}] (let [ids (if timely-statuses-ids timely-statuses-ids '(0)) matching-statuses (-> (select-fields model status-model member-model) (db/where {:id [in ids]}) (db/select))] (if matching-statuses matching-statuses '()))) (defn find-last-week-timely-status [] (let [query (str "SELECT ts.id, s.ust_api_document as \"status-api-document\", e.member_id as \"member-id\", ts.member_name as \"member-name\", ts.aggregate_name as \"aggregate-name\", ts.status_id as \"status-id\", ts.publication_date_time as \"publication-date-time\" FROM publication_batch_collected_event e INNER JOIN weaving_user m ON m.usr_id = e.member_id AND DATEDIFF(NOW(), e.occurred_at) <= 7 INNER JOIN timely_status ts ON member_name = m.usr_twitter_username LEFT JOIN keyword k ON k.status_id = ts.status_id INNER JOIN weaving_status s ON s.ust_id = ts.status_id WHERE k.id IS NULL LIMIT 10000;") query (str query) results (db/exec-raw [query []] :results)] results)) (defn find-timely-statuses-by-constraints "Find timely statuses by ids of statuses or constraints" ([constraints {model :timely-status member-model :members status-model :status}] (let [{columns :columns values :values default-values :default-values} constraints constraining-values (if (pos? (count values)) values default-values) matching-statuses (-> (select-fields model status-model member-model) (db/where (in columns constraining-values)) (db/select))] (if matching-statuses matching-statuses '()))) ([statuses-ids aggregate-name {model :timely-status member-model :members status-model :status}] (let [ids (if statuses-ids statuses-ids '(0)) matching-statuses (-> (select-fields model status-model member-model) (db/where (and (= :aggregate_name aggregate-name) (in :status_id ids))) (db/select))] (if matching-statuses matching-statuses '())))) (defn find-timely-statuses-by-aggregate-name [aggregate-name models] (find-timely-statuses-by-constraints {:columns [:aggregate_name] :default-values '("") :values [aggregate-name]} models)) (defn find-timely-statuses-by-aggregate-id [aggregate-id models] (find-timely-statuses-by-constraints {:columns [:aggregate_id] :default-values '(0) :values [aggregate-id]} models)) (defn bulk-insert-timely-statuses-from-aggregate [aggregate-id] (let [query (str " INSERT INTO timely_status ( id, status_id, member_name, aggregate_id, aggregate_name, publication_date_time, time_range ) SELECT UUID() AS id, s.ust_id AS status_id, s.ust_full_name AS member_name, a.id AS aggregate_id, a.name AS aggregate_name, s.ust_created_at AS publication_date_time, CASE WHEN s.ust_created_at > NOW()::timestamp - '5 MINUTES'::INTERVAL THEN 0 WHEN s.ust_created_at > NOW()::timestamp - '10 MINUTES'::INTERVAL THEN 1 WHEN s.ust_created_at > NOW()::timestamp - '30 MINUTES'::INTERVAL THEN 2 WHEN s.ust_created_at > NOW()::timestamp - '1 DAY'::INTERVAL THEN 3 WHEN s.ust_created_at > NOW()::timestamp - '1 WEEK'::INTERVAL THEN 4 ELSE 5 END AS time_range FROM publishers_list AS a INNER JOIN weaving_status_aggregate sa ON sa.aggregate_id = a.id INNER JOIN weaving_status AS s ON s.ust_id = sa.status_id WHERE a.id = ? AND (s.ust_id, a.id) NOT IN ( SELECT status_id, aggregate_id FROM timely_status )") count (exec-query [query [aggregate-id]])] (first count)))
[ { "context": "/input [:customer/id]\n ...}\n {:customer/name \\\"Bob\\\"})\n\"\n :arglists '([sym docstring? arg", "end": 2163, "score": 0.9995408058166504, "start": 2160, "tag": "NAME", "value": "Bob" } ]
src/main/amplifytest/server_components/pathom_wrappers.clj
timeyyy/fuclro-aws-amplify
1
(ns amplifytest.server-components.pathom-wrappers (:require [clojure.spec.alpha :as s] [fulcro.server] [fulcro.util :as util] [taoensso.timbre :as log] [com.wsscode.pathom.connect :as pc])) (defonce pathom-registry (atom {})) (defn register! [resolver] (log/debug "Registering resolver " (::pc/sym resolver)) (swap! pathom-registry assoc (::pc/sym resolver) resolver)) (s/def ::mutation-args (s/cat :sym simple-symbol? :doc (s/? string?) :arglist vector? :config map? :body (s/* any?))) ;; This is the macro syntax generator for resolvers and mutations, so you can add a security layer (e.g. based on the ;; config passed in) to your resolvers and mutations easily here, and it can have access to anything in the ;; parsing environment and query/tx at runtime. (defn defpathom-endpoint* [endpoint args] (let [{:keys [sym arglist doc config body]} (util/conform! ::mutation-args args) config (dissoc config :security) env-arg (first arglist) params-arg (second arglist)] `(do (~endpoint ~(cond-> sym doc (with-meta {:doc doc})) [env# params#] ~config ;; Example of how to integrate a security check into all mutations and resolvers (let [~env-arg env# ~params-arg params#] ~@body)) (amplifytest.server-components.pathom-wrappers/register! ~sym)))) (defmacro ^{:doc "Defines a server-side PATHOM mutation. This macro can be \"resolved as\" defn for IDE recognition. Example: (defmutation do-thing \"Optional docstring\" [params] {::pc/input [:param/name] ; PATHOM config ::pc/output [:result/prop]} body) " :arglists '([sym docstring? arglist config & body])} defmutation [& args] (defpathom-endpoint* `pc/defmutation args)) (defmacro ^{:doc "Defines a pathom resolver but with authorization. Looks like `defn`. Example: (defresolver resolver-name [env input] {::pc/input [:customer/id] ...} {:customer/name \"Bob\"}) " :arglists '([sym docstring? arglist config & body])} defresolver [& args] (defpathom-endpoint* `pc/defresolver args))
101548
(ns amplifytest.server-components.pathom-wrappers (:require [clojure.spec.alpha :as s] [fulcro.server] [fulcro.util :as util] [taoensso.timbre :as log] [com.wsscode.pathom.connect :as pc])) (defonce pathom-registry (atom {})) (defn register! [resolver] (log/debug "Registering resolver " (::pc/sym resolver)) (swap! pathom-registry assoc (::pc/sym resolver) resolver)) (s/def ::mutation-args (s/cat :sym simple-symbol? :doc (s/? string?) :arglist vector? :config map? :body (s/* any?))) ;; This is the macro syntax generator for resolvers and mutations, so you can add a security layer (e.g. based on the ;; config passed in) to your resolvers and mutations easily here, and it can have access to anything in the ;; parsing environment and query/tx at runtime. (defn defpathom-endpoint* [endpoint args] (let [{:keys [sym arglist doc config body]} (util/conform! ::mutation-args args) config (dissoc config :security) env-arg (first arglist) params-arg (second arglist)] `(do (~endpoint ~(cond-> sym doc (with-meta {:doc doc})) [env# params#] ~config ;; Example of how to integrate a security check into all mutations and resolvers (let [~env-arg env# ~params-arg params#] ~@body)) (amplifytest.server-components.pathom-wrappers/register! ~sym)))) (defmacro ^{:doc "Defines a server-side PATHOM mutation. This macro can be \"resolved as\" defn for IDE recognition. Example: (defmutation do-thing \"Optional docstring\" [params] {::pc/input [:param/name] ; PATHOM config ::pc/output [:result/prop]} body) " :arglists '([sym docstring? arglist config & body])} defmutation [& args] (defpathom-endpoint* `pc/defmutation args)) (defmacro ^{:doc "Defines a pathom resolver but with authorization. Looks like `defn`. Example: (defresolver resolver-name [env input] {::pc/input [:customer/id] ...} {:customer/name \"<NAME>\"}) " :arglists '([sym docstring? arglist config & body])} defresolver [& args] (defpathom-endpoint* `pc/defresolver args))
true
(ns amplifytest.server-components.pathom-wrappers (:require [clojure.spec.alpha :as s] [fulcro.server] [fulcro.util :as util] [taoensso.timbre :as log] [com.wsscode.pathom.connect :as pc])) (defonce pathom-registry (atom {})) (defn register! [resolver] (log/debug "Registering resolver " (::pc/sym resolver)) (swap! pathom-registry assoc (::pc/sym resolver) resolver)) (s/def ::mutation-args (s/cat :sym simple-symbol? :doc (s/? string?) :arglist vector? :config map? :body (s/* any?))) ;; This is the macro syntax generator for resolvers and mutations, so you can add a security layer (e.g. based on the ;; config passed in) to your resolvers and mutations easily here, and it can have access to anything in the ;; parsing environment and query/tx at runtime. (defn defpathom-endpoint* [endpoint args] (let [{:keys [sym arglist doc config body]} (util/conform! ::mutation-args args) config (dissoc config :security) env-arg (first arglist) params-arg (second arglist)] `(do (~endpoint ~(cond-> sym doc (with-meta {:doc doc})) [env# params#] ~config ;; Example of how to integrate a security check into all mutations and resolvers (let [~env-arg env# ~params-arg params#] ~@body)) (amplifytest.server-components.pathom-wrappers/register! ~sym)))) (defmacro ^{:doc "Defines a server-side PATHOM mutation. This macro can be \"resolved as\" defn for IDE recognition. Example: (defmutation do-thing \"Optional docstring\" [params] {::pc/input [:param/name] ; PATHOM config ::pc/output [:result/prop]} body) " :arglists '([sym docstring? arglist config & body])} defmutation [& args] (defpathom-endpoint* `pc/defmutation args)) (defmacro ^{:doc "Defines a pathom resolver but with authorization. Looks like `defn`. Example: (defresolver resolver-name [env input] {::pc/input [:customer/id] ...} {:customer/name \"PI:NAME:<NAME>END_PI\"}) " :arglists '([sym docstring? arglist config & body])} defresolver [& args] (defpathom-endpoint* `pc/defresolver args))
[ { "context": " (= (:text token) (:val token))))\n \n \"alex@wit.ai\"\n \"alex.lebrun@mail.wit.com\"\n (fn [token _] (and ", "end": 501, "score": 0.9999290704727173, "start": 490, "tag": "EMAIL", "value": "alex@wit.ai" }, { "context": " (:text token) (:val token))))\n \n \"alex@wit.ai\"\n \"alex.lebrun@mail.wit.com\"\n (fn [token _] (and (= :email (:dim token))\n ", "end": 529, "score": 0.9999323487281799, "start": 505, "tag": "EMAIL", "value": "alex.lebrun@mail.wit.com" } ]
resources/languages/pt/corpus/communication.clj
irvingflores/duckling
0
( {} "19 99999999" "999999999" "+33 19 76095663" "06 2070 2220" "(650)-283-4757 ext 897" (fn [token _] (and (= :phone-number (:dim token)) (= (:text token) (:val token)))) "http://www.bla.com" "www.bla.com:8080/path" "https://myserver?foo=bar" "cnn.com/info" "bla.com/path/path?ext=%23&foo=bla" "localhost" "localhost:8000" "http://kimchi" ; local url (fn [token _] (and (= :url (:dim token)) (= (:text token) (:val token)))) "alex@wit.ai" "alex.lebrun@mail.wit.com" (fn [token _] (and (= :email (:dim token)) (= (:text token) (:val token)))) )
69127
( {} "19 99999999" "999999999" "+33 19 76095663" "06 2070 2220" "(650)-283-4757 ext 897" (fn [token _] (and (= :phone-number (:dim token)) (= (:text token) (:val token)))) "http://www.bla.com" "www.bla.com:8080/path" "https://myserver?foo=bar" "cnn.com/info" "bla.com/path/path?ext=%23&foo=bla" "localhost" "localhost:8000" "http://kimchi" ; local url (fn [token _] (and (= :url (:dim token)) (= (:text token) (:val token)))) "<EMAIL>" "<EMAIL>" (fn [token _] (and (= :email (:dim token)) (= (:text token) (:val token)))) )
true
( {} "19 99999999" "999999999" "+33 19 76095663" "06 2070 2220" "(650)-283-4757 ext 897" (fn [token _] (and (= :phone-number (:dim token)) (= (:text token) (:val token)))) "http://www.bla.com" "www.bla.com:8080/path" "https://myserver?foo=bar" "cnn.com/info" "bla.com/path/path?ext=%23&foo=bla" "localhost" "localhost:8000" "http://kimchi" ; local url (fn [token _] (and (= :url (:dim token)) (= (:text token) (:val token)))) "PI:EMAIL:<EMAIL>END_PI" "PI:EMAIL:<EMAIL>END_PI" (fn [token _] (and (= :email (:dim token)) (= (:text token) (:val token)))) )
[ { "context": "ch with Clojure. YMMV.&#8221;\"]\n [:p \"&#8212;Rich Hickey, author, Clojure programming language\"]]))\n\n(defn", "end": 384, "score": 0.9998782873153687, "start": 373, "tag": "NAME", "value": "Rich Hickey" } ]
src/sicpclojure/templates/cover.clj
domgetter/sicpclojure
57
(ns sicpclojure.templates.cover (:require [hiccup.core :refer [html]]) (:require [hiccup.page :refer [html5]]) (:use [sicpclojure.templates.base :exclude [render]])) (def content (html [:div.title [:h1 "SICP In Clojure"]] [:div.quote [:h1 "&#8220;I personally don't think SICP will help you much with Clojure. YMMV.&#8221;"] [:p "&#8212;Rich Hickey, author, Clojure programming language"]])) (defn render [] (html5 {:lang "en"} (let [title (head :title) js (head :js) css (head :css) fonts (head :fonts)] [:head [:meta {:charset "utf-8"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1.0"}] title js css fonts]) [:body [:div.container [:div.row [:div {:class "sidebar span3"} [:nav [:p [:a {:href "pages/contents.html"} "Contents"]] [:p#colorscheme ]] [:footer footer]] [:div {:class "content span9 offset3"} content]]]]))
121212
(ns sicpclojure.templates.cover (:require [hiccup.core :refer [html]]) (:require [hiccup.page :refer [html5]]) (:use [sicpclojure.templates.base :exclude [render]])) (def content (html [:div.title [:h1 "SICP In Clojure"]] [:div.quote [:h1 "&#8220;I personally don't think SICP will help you much with Clojure. YMMV.&#8221;"] [:p "&#8212;<NAME>, author, Clojure programming language"]])) (defn render [] (html5 {:lang "en"} (let [title (head :title) js (head :js) css (head :css) fonts (head :fonts)] [:head [:meta {:charset "utf-8"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1.0"}] title js css fonts]) [:body [:div.container [:div.row [:div {:class "sidebar span3"} [:nav [:p [:a {:href "pages/contents.html"} "Contents"]] [:p#colorscheme ]] [:footer footer]] [:div {:class "content span9 offset3"} content]]]]))
true
(ns sicpclojure.templates.cover (:require [hiccup.core :refer [html]]) (:require [hiccup.page :refer [html5]]) (:use [sicpclojure.templates.base :exclude [render]])) (def content (html [:div.title [:h1 "SICP In Clojure"]] [:div.quote [:h1 "&#8220;I personally don't think SICP will help you much with Clojure. YMMV.&#8221;"] [:p "&#8212;PI:NAME:<NAME>END_PI, author, Clojure programming language"]])) (defn render [] (html5 {:lang "en"} (let [title (head :title) js (head :js) css (head :css) fonts (head :fonts)] [:head [:meta {:charset "utf-8"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1.0"}] title js css fonts]) [:body [:div.container [:div.row [:div {:class "sidebar span3"} [:nav [:p [:a {:href "pages/contents.html"} "Contents"]] [:p#colorscheme ]] [:footer footer]] [:div {:class "content span9 offset3"} content]]]]))
[ { "context": "he preparation\"\n :user \"newuser\"})\n\n(def sample-measurement {:ingredient \"garlic\"", "end": 597, "score": 0.9993440508842468, "start": 590, "tag": "USERNAME", "value": "newuser" }, { "context": "est;MVCC=true\"})\n (db/create-user! {:username \"newuser\"\n :password \"pass\"\n ", "end": 954, "score": 0.9995726346969604, "start": 947, "tag": "USERNAME", "value": "newuser" }, { "context": "ername \"newuser\"\n :password \"pass\"\n :admin false})\n (db/", "end": 993, "score": 0.9995464086532593, "start": 989, "tag": "PASSWORD", "value": "pass" } ]
test/copa/test/db/recipe_measurements.clj
hjrnunes/copa
2
(ns copa.test.db.recipe-measurements (:require [copa.db.core :refer [*db*] :as db] [luminus-migrations.core :as migrations] [clojure.test :refer :all] [clojure.java.jdbc :as jdbc] [copa.config :refer [env]] [mount.core :as mount]) (:import (java.sql SQLException))) (def sample-recipe {:name "a recipe" :description "a description" :portions "3" :source "a source" :preparation "the preparation" :user "newuser"}) (def sample-measurement {:ingredient "garlic" :quantity 1 :unit "g"}) (use-fixtures :once (fn [f] (mount/start #'copa.config/env #'copa.db.core/*db*) (migrations/migrate ["reset"] {:database-url "jdbc:h2:./copa_test;MVCC=true"}) (db/create-user! {:username "newuser" :password "pass" :admin false}) (db/create-ingredient! {:name "garlic"}) (f))) (deftest get-all-ingredients (testing "get all users" (is (= 1 (count (db/get-ingredients)))))) (defn create-measurement [t-conn] (get (db/create-measurement! t-conn sample-measurement) (keyword "scope_identity()"))) (deftest insert-recipe-measurement (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (let [recres (db/create-recipe! t-conn sample-recipe) rid (get recres (keyword "scope_identity()")) mid (create-measurement t-conn)] (testing "insert a new recipe measurement" (db/create-recipe-measurement! t-conn {:recipe_id rid :measurement_id mid}) (let [rms (db/get-recipe-measurements-for-recipe t-conn {:recipe_id rid})] (is (= 1 (count rms))) (is (= {:recipe_id rid :measurement_id mid} (dissoc (first rms) :rec_measurement_id))))) (testing "insert another recipe measurement" (let [mid2 (create-measurement t-conn)] (db/create-recipe-measurement! t-conn {:recipe_id rid :measurement_id mid2}) (let [rms (db/get-recipe-measurements-for-recipe t-conn {:recipe_id rid})] (is (= 2 (count rms))) (is (= {:recipe_id rid :measurement_id mid2} (dissoc (second rms) :rec_measurement_id)))))) (testing "insert a recipe measurement without recipe_id fails" (is (thrown? SQLException (db/create-recipe-measurement! t-conn {:measurement_id mid :recipe_id nil})))) (testing "insert a recipe measurement without measurement_id fails" (is (thrown? SQLException (db/create-recipe-measurement! t-conn {:recipe_id rid :measurement_id nil})))))))
80693
(ns copa.test.db.recipe-measurements (:require [copa.db.core :refer [*db*] :as db] [luminus-migrations.core :as migrations] [clojure.test :refer :all] [clojure.java.jdbc :as jdbc] [copa.config :refer [env]] [mount.core :as mount]) (:import (java.sql SQLException))) (def sample-recipe {:name "a recipe" :description "a description" :portions "3" :source "a source" :preparation "the preparation" :user "newuser"}) (def sample-measurement {:ingredient "garlic" :quantity 1 :unit "g"}) (use-fixtures :once (fn [f] (mount/start #'copa.config/env #'copa.db.core/*db*) (migrations/migrate ["reset"] {:database-url "jdbc:h2:./copa_test;MVCC=true"}) (db/create-user! {:username "newuser" :password "<PASSWORD>" :admin false}) (db/create-ingredient! {:name "garlic"}) (f))) (deftest get-all-ingredients (testing "get all users" (is (= 1 (count (db/get-ingredients)))))) (defn create-measurement [t-conn] (get (db/create-measurement! t-conn sample-measurement) (keyword "scope_identity()"))) (deftest insert-recipe-measurement (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (let [recres (db/create-recipe! t-conn sample-recipe) rid (get recres (keyword "scope_identity()")) mid (create-measurement t-conn)] (testing "insert a new recipe measurement" (db/create-recipe-measurement! t-conn {:recipe_id rid :measurement_id mid}) (let [rms (db/get-recipe-measurements-for-recipe t-conn {:recipe_id rid})] (is (= 1 (count rms))) (is (= {:recipe_id rid :measurement_id mid} (dissoc (first rms) :rec_measurement_id))))) (testing "insert another recipe measurement" (let [mid2 (create-measurement t-conn)] (db/create-recipe-measurement! t-conn {:recipe_id rid :measurement_id mid2}) (let [rms (db/get-recipe-measurements-for-recipe t-conn {:recipe_id rid})] (is (= 2 (count rms))) (is (= {:recipe_id rid :measurement_id mid2} (dissoc (second rms) :rec_measurement_id)))))) (testing "insert a recipe measurement without recipe_id fails" (is (thrown? SQLException (db/create-recipe-measurement! t-conn {:measurement_id mid :recipe_id nil})))) (testing "insert a recipe measurement without measurement_id fails" (is (thrown? SQLException (db/create-recipe-measurement! t-conn {:recipe_id rid :measurement_id nil})))))))
true
(ns copa.test.db.recipe-measurements (:require [copa.db.core :refer [*db*] :as db] [luminus-migrations.core :as migrations] [clojure.test :refer :all] [clojure.java.jdbc :as jdbc] [copa.config :refer [env]] [mount.core :as mount]) (:import (java.sql SQLException))) (def sample-recipe {:name "a recipe" :description "a description" :portions "3" :source "a source" :preparation "the preparation" :user "newuser"}) (def sample-measurement {:ingredient "garlic" :quantity 1 :unit "g"}) (use-fixtures :once (fn [f] (mount/start #'copa.config/env #'copa.db.core/*db*) (migrations/migrate ["reset"] {:database-url "jdbc:h2:./copa_test;MVCC=true"}) (db/create-user! {:username "newuser" :password "PI:PASSWORD:<PASSWORD>END_PI" :admin false}) (db/create-ingredient! {:name "garlic"}) (f))) (deftest get-all-ingredients (testing "get all users" (is (= 1 (count (db/get-ingredients)))))) (defn create-measurement [t-conn] (get (db/create-measurement! t-conn sample-measurement) (keyword "scope_identity()"))) (deftest insert-recipe-measurement (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (let [recres (db/create-recipe! t-conn sample-recipe) rid (get recres (keyword "scope_identity()")) mid (create-measurement t-conn)] (testing "insert a new recipe measurement" (db/create-recipe-measurement! t-conn {:recipe_id rid :measurement_id mid}) (let [rms (db/get-recipe-measurements-for-recipe t-conn {:recipe_id rid})] (is (= 1 (count rms))) (is (= {:recipe_id rid :measurement_id mid} (dissoc (first rms) :rec_measurement_id))))) (testing "insert another recipe measurement" (let [mid2 (create-measurement t-conn)] (db/create-recipe-measurement! t-conn {:recipe_id rid :measurement_id mid2}) (let [rms (db/get-recipe-measurements-for-recipe t-conn {:recipe_id rid})] (is (= 2 (count rms))) (is (= {:recipe_id rid :measurement_id mid2} (dissoc (second rms) :rec_measurement_id)))))) (testing "insert a recipe measurement without recipe_id fails" (is (thrown? SQLException (db/create-recipe-measurement! t-conn {:measurement_id mid :recipe_id nil})))) (testing "insert a recipe measurement without measurement_id fails" (is (thrown? SQLException (db/create-recipe-measurement! t-conn {:recipe_id rid :measurement_id nil})))))))
[ { "context": "z-user-agent\" \"aws-amplify/3.0.2\"\n \"x-api-key\" \"da2-kgm3anvg4zfhlgpc5hfpkpvtt4\"})\n\n(def endpoint \"https://pvgc4hmgxngb7n5ant4ucs", "end": 367, "score": 0.999750554561615, "start": 337, "tag": "KEY", "value": "da2-kgm3anvg4zfhlgpc5hfpkpvtt4" }, { "context": "he\")\n\n(def athlete-name->athlete-id-overrides\n {\"titi ncincihli\" 14417761,\n \"johansen matias ho", "end": 1795, "score": 0.9998713731765747, "start": 1781, "tag": "NAME", "value": "titi ncincihli" }, { "context": " {\"titi ncincihli\" 14417761,\n \"johansen matias hove\" 14652141,\n \"desalu eseosa\" ", "end": 1847, "score": 0.9998686909675598, "start": 1827, "tag": "NAME", "value": "johansen matias hove" }, { "context": " \"johansen matias hove\" 14652141,\n \"desalu eseosa\" 14403082,\n \"hove johansen and", "end": 1886, "score": 0.9997614026069641, "start": 1873, "tag": "NAME", "value": "desalu eseosa" }, { "context": " \"desalu eseosa\" 14403082,\n \"hove johansen andreas\" 14652141,\n \"camilo de oliveira paulo ", "end": 1940, "score": 0.9970486164093018, "start": 1919, "tag": "NAME", "value": "hove johansen andreas" }, { "context": " \"hove johansen andreas\" 14652141,\n \"camilo de oliveira paulo andré\" 14699143,\n \"koffi wilfried\" 14", "end": 1995, "score": 0.9998633861541748, "start": 1965, "tag": "NAME", "value": "camilo de oliveira paulo andré" }, { "context": " \"camilo de oliveira paulo andré\" 14699143,\n \"koffi wilfried\" 14185652,\n \"zeze mickael-meba\"", "end": 2025, "score": 0.9998873472213745, "start": 2011, "tag": "NAME", "value": "koffi wilfried" }, { "context": " \"koffi wilfried\" 14185652,\n \"zeze mickael-meba\" 14389351,\n \"kyeremeh stefan skogh", "end": 2074, "score": 0.9998569488525391, "start": 2057, "tag": "NAME", "value": "zeze mickael-meba" }, { "context": " \"zeze mickael-meba\" 14389351,\n \"kyeremeh stefan skogheim\" 14774584,\n \"zeze méba-mickaël\" ", "end": 2127, "score": 0.9995288848876953, "start": 2103, "tag": "NAME", "value": "kyeremeh stefan skogheim" }, { "context": " \"kyeremeh stefan skogheim\" 14774584,\n \"zeze méba-mickaël\" 14389351})\n\n(defn athlete-name->ath", "end": 2166, "score": 0.9998839497566223, "start": 2149, "tag": "NAME", "value": "zeze méba-mickaël" }, { "context": " (fastest-time-by-year (athlete-name->athlete-id \"noah lyles\") 2021))\n", "end": 6495, "score": 0.9979581832885742, "start": 6485, "tag": "NAME", "value": "noah lyles" } ]
src/lane_analysis/worldathletics.clj
jchen1/200m-curve-analysis
0
(ns lane-analysis.worldathletics (:require [clj-http.client :as http] [clojure.data.json :as json] [clojure.string :as str] [lane-analysis.util :as util] [clojure.java.io :as io] [clojure.edn :as edn])) (def headers {"x-amz-user-agent" "aws-amplify/3.0.2" "x-api-key" "da2-kgm3anvg4zfhlgpc5hfpkpvtt4"}) (def endpoint "https://pvgc4hmgxngb7n5ant4ucszemq.appsync-api.eu-west-1.amazonaws.com/graphql") (def search-query "query SearchCompetitors($query: String, $gender: GenderType, $disciplineCode: String, $environment: String, $countryCode: String) {\n searchCompetitors(query: $query, gender: $gender, disciplineCode: $disciplineCode, environment: $environment, countryCode: $countryCode) {\n aaAthleteId\n familyName\n givenName\n birthDate\n disciplines\n iaafId\n gender\n country\n urlSlug\n }\n}\n") (def fastest-time-query "query GetSingleCompetitorResultsDiscipline($id: Int, $resultsByYearOrderBy: String, $resultsByYear: Int) {\n getSingleCompetitorResultsDiscipline(id: $id, resultsByYear: $resultsByYear, resultsByYearOrderBy: $resultsByYearOrderBy) {\n parameters {\n resultsByYear\n resultsByYearOrderBy\n __typename\n }\n activeYears\n resultsByEvent {\n indoor\n disciplineCode\n disciplineNameUrlSlug\n typeNameUrlSlug\n discipline\n withWind\n results {\n date\n competition\n venue\n country\n category\n race\n place\n mark\n wind\n notLegal\n resultScore\n remark\n __typename\n }\n __typename\n }\n __typename\n }\n}\n") (def cache-dir "cache") (def athlete-name->athlete-id-overrides {"titi ncincihli" 14417761, "johansen matias hove" 14652141, "desalu eseosa" 14403082, "hove johansen andreas" 14652141, "camilo de oliveira paulo andré" 14699143, "koffi wilfried" 14185652, "zeze mickael-meba" 14389351, "kyeremeh stefan skogheim" 14774584, "zeze méba-mickaël" 14389351}) (defn athlete-name->athlete-id [athlete-name] (or (athlete-name->athlete-id-overrides athlete-name) (let [cache-file (io/file cache-dir "search" (format "%s.edn" (util/md5 athlete-name))) normalized-name (-> athlete-name util/deaccent str/lower-case) search-name-set (-> normalized-name (str/split #"\s+") set) {:keys [status body] :as response} (when-not (.exists cache-file) (http/post endpoint {:body (json/write-str {:operationName "SearchCompetitors" :variables {:query normalized-name :gender "male" :disciplineCode "200" :environment "outdoor"} :query search-query}) :content-type :json :accept :json :headers headers})) _ (assert (or (.exists cache-file) (= 200 status)) (format "got status %s when searching for %s" status athlete-name)) results (if (.exists cache-file) (-> cache-file slurp edn/read-string) (-> (json/read-str body :key-fn keyword) :data :searchCompetitors))] (spit cache-file results) (some->> results (filter #(= search-name-set (-> (format "%s %s" (:familyName %) (:givenName %)) util/deaccent str/lower-case (str/split #"\s+") set))) (first) :aaAthleteId (Integer/parseInt))))) (comment (athlete-name->athlete-id "reid leon")) (defn fastest-time-by-year [athlete-id year] (let [cache-file (io/file cache-dir "results" (format "%s.edn" (util/md5 (str athlete-id year)))) {:keys [status body] :as response} (when-not (.exists cache-file) (http/post endpoint {:body (json/write-str {:operationName "GetSingleCompetitorResultsDiscipline" :variables {:id athlete-id :resultsByYear year :resultsByYearOrderBy "discipline"} :query fastest-time-query}) :content-type :json :accept :json :headers headers})) _ (assert (or (.exists cache-file) (= 200 status)) (format "got status %s when looking for fastest times for %s %s" status athlete-id year)) results (if (.exists cache-file) (-> cache-file slurp edn/read-string) (-> (json/read-str body :key-fn keyword) :data :getSingleCompetitorResultsDiscipline :resultsByEvent))] (spit cache-file results) (some->> results (filter #(and (not (:notLegal %)) (= (:disciplineCode %) "200") (not (:indoor %)))) (first) :results (keep (fn [{:keys [mark wind]}] (let [mark (util/parse-double mark) wind (util/parse-double wind)] (when (and (double? mark) (double? wind)) (util/correct-200m-for-wind mark wind))))) (sort) (first)))) (comment (fastest-time-by-year (athlete-name->athlete-id "noah lyles") 2021))
6229
(ns lane-analysis.worldathletics (:require [clj-http.client :as http] [clojure.data.json :as json] [clojure.string :as str] [lane-analysis.util :as util] [clojure.java.io :as io] [clojure.edn :as edn])) (def headers {"x-amz-user-agent" "aws-amplify/3.0.2" "x-api-key" "<KEY>"}) (def endpoint "https://pvgc4hmgxngb7n5ant4ucszemq.appsync-api.eu-west-1.amazonaws.com/graphql") (def search-query "query SearchCompetitors($query: String, $gender: GenderType, $disciplineCode: String, $environment: String, $countryCode: String) {\n searchCompetitors(query: $query, gender: $gender, disciplineCode: $disciplineCode, environment: $environment, countryCode: $countryCode) {\n aaAthleteId\n familyName\n givenName\n birthDate\n disciplines\n iaafId\n gender\n country\n urlSlug\n }\n}\n") (def fastest-time-query "query GetSingleCompetitorResultsDiscipline($id: Int, $resultsByYearOrderBy: String, $resultsByYear: Int) {\n getSingleCompetitorResultsDiscipline(id: $id, resultsByYear: $resultsByYear, resultsByYearOrderBy: $resultsByYearOrderBy) {\n parameters {\n resultsByYear\n resultsByYearOrderBy\n __typename\n }\n activeYears\n resultsByEvent {\n indoor\n disciplineCode\n disciplineNameUrlSlug\n typeNameUrlSlug\n discipline\n withWind\n results {\n date\n competition\n venue\n country\n category\n race\n place\n mark\n wind\n notLegal\n resultScore\n remark\n __typename\n }\n __typename\n }\n __typename\n }\n}\n") (def cache-dir "cache") (def athlete-name->athlete-id-overrides {"<NAME>" 14417761, "<NAME>" 14652141, "<NAME>" 14403082, "<NAME>" 14652141, "<NAME>" 14699143, "<NAME>" 14185652, "<NAME>" 14389351, "<NAME>" 14774584, "<NAME>" 14389351}) (defn athlete-name->athlete-id [athlete-name] (or (athlete-name->athlete-id-overrides athlete-name) (let [cache-file (io/file cache-dir "search" (format "%s.edn" (util/md5 athlete-name))) normalized-name (-> athlete-name util/deaccent str/lower-case) search-name-set (-> normalized-name (str/split #"\s+") set) {:keys [status body] :as response} (when-not (.exists cache-file) (http/post endpoint {:body (json/write-str {:operationName "SearchCompetitors" :variables {:query normalized-name :gender "male" :disciplineCode "200" :environment "outdoor"} :query search-query}) :content-type :json :accept :json :headers headers})) _ (assert (or (.exists cache-file) (= 200 status)) (format "got status %s when searching for %s" status athlete-name)) results (if (.exists cache-file) (-> cache-file slurp edn/read-string) (-> (json/read-str body :key-fn keyword) :data :searchCompetitors))] (spit cache-file results) (some->> results (filter #(= search-name-set (-> (format "%s %s" (:familyName %) (:givenName %)) util/deaccent str/lower-case (str/split #"\s+") set))) (first) :aaAthleteId (Integer/parseInt))))) (comment (athlete-name->athlete-id "reid leon")) (defn fastest-time-by-year [athlete-id year] (let [cache-file (io/file cache-dir "results" (format "%s.edn" (util/md5 (str athlete-id year)))) {:keys [status body] :as response} (when-not (.exists cache-file) (http/post endpoint {:body (json/write-str {:operationName "GetSingleCompetitorResultsDiscipline" :variables {:id athlete-id :resultsByYear year :resultsByYearOrderBy "discipline"} :query fastest-time-query}) :content-type :json :accept :json :headers headers})) _ (assert (or (.exists cache-file) (= 200 status)) (format "got status %s when looking for fastest times for %s %s" status athlete-id year)) results (if (.exists cache-file) (-> cache-file slurp edn/read-string) (-> (json/read-str body :key-fn keyword) :data :getSingleCompetitorResultsDiscipline :resultsByEvent))] (spit cache-file results) (some->> results (filter #(and (not (:notLegal %)) (= (:disciplineCode %) "200") (not (:indoor %)))) (first) :results (keep (fn [{:keys [mark wind]}] (let [mark (util/parse-double mark) wind (util/parse-double wind)] (when (and (double? mark) (double? wind)) (util/correct-200m-for-wind mark wind))))) (sort) (first)))) (comment (fastest-time-by-year (athlete-name->athlete-id "<NAME>") 2021))
true
(ns lane-analysis.worldathletics (:require [clj-http.client :as http] [clojure.data.json :as json] [clojure.string :as str] [lane-analysis.util :as util] [clojure.java.io :as io] [clojure.edn :as edn])) (def headers {"x-amz-user-agent" "aws-amplify/3.0.2" "x-api-key" "PI:KEY:<KEY>END_PI"}) (def endpoint "https://pvgc4hmgxngb7n5ant4ucszemq.appsync-api.eu-west-1.amazonaws.com/graphql") (def search-query "query SearchCompetitors($query: String, $gender: GenderType, $disciplineCode: String, $environment: String, $countryCode: String) {\n searchCompetitors(query: $query, gender: $gender, disciplineCode: $disciplineCode, environment: $environment, countryCode: $countryCode) {\n aaAthleteId\n familyName\n givenName\n birthDate\n disciplines\n iaafId\n gender\n country\n urlSlug\n }\n}\n") (def fastest-time-query "query GetSingleCompetitorResultsDiscipline($id: Int, $resultsByYearOrderBy: String, $resultsByYear: Int) {\n getSingleCompetitorResultsDiscipline(id: $id, resultsByYear: $resultsByYear, resultsByYearOrderBy: $resultsByYearOrderBy) {\n parameters {\n resultsByYear\n resultsByYearOrderBy\n __typename\n }\n activeYears\n resultsByEvent {\n indoor\n disciplineCode\n disciplineNameUrlSlug\n typeNameUrlSlug\n discipline\n withWind\n results {\n date\n competition\n venue\n country\n category\n race\n place\n mark\n wind\n notLegal\n resultScore\n remark\n __typename\n }\n __typename\n }\n __typename\n }\n}\n") (def cache-dir "cache") (def athlete-name->athlete-id-overrides {"PI:NAME:<NAME>END_PI" 14417761, "PI:NAME:<NAME>END_PI" 14652141, "PI:NAME:<NAME>END_PI" 14403082, "PI:NAME:<NAME>END_PI" 14652141, "PI:NAME:<NAME>END_PI" 14699143, "PI:NAME:<NAME>END_PI" 14185652, "PI:NAME:<NAME>END_PI" 14389351, "PI:NAME:<NAME>END_PI" 14774584, "PI:NAME:<NAME>END_PI" 14389351}) (defn athlete-name->athlete-id [athlete-name] (or (athlete-name->athlete-id-overrides athlete-name) (let [cache-file (io/file cache-dir "search" (format "%s.edn" (util/md5 athlete-name))) normalized-name (-> athlete-name util/deaccent str/lower-case) search-name-set (-> normalized-name (str/split #"\s+") set) {:keys [status body] :as response} (when-not (.exists cache-file) (http/post endpoint {:body (json/write-str {:operationName "SearchCompetitors" :variables {:query normalized-name :gender "male" :disciplineCode "200" :environment "outdoor"} :query search-query}) :content-type :json :accept :json :headers headers})) _ (assert (or (.exists cache-file) (= 200 status)) (format "got status %s when searching for %s" status athlete-name)) results (if (.exists cache-file) (-> cache-file slurp edn/read-string) (-> (json/read-str body :key-fn keyword) :data :searchCompetitors))] (spit cache-file results) (some->> results (filter #(= search-name-set (-> (format "%s %s" (:familyName %) (:givenName %)) util/deaccent str/lower-case (str/split #"\s+") set))) (first) :aaAthleteId (Integer/parseInt))))) (comment (athlete-name->athlete-id "reid leon")) (defn fastest-time-by-year [athlete-id year] (let [cache-file (io/file cache-dir "results" (format "%s.edn" (util/md5 (str athlete-id year)))) {:keys [status body] :as response} (when-not (.exists cache-file) (http/post endpoint {:body (json/write-str {:operationName "GetSingleCompetitorResultsDiscipline" :variables {:id athlete-id :resultsByYear year :resultsByYearOrderBy "discipline"} :query fastest-time-query}) :content-type :json :accept :json :headers headers})) _ (assert (or (.exists cache-file) (= 200 status)) (format "got status %s when looking for fastest times for %s %s" status athlete-id year)) results (if (.exists cache-file) (-> cache-file slurp edn/read-string) (-> (json/read-str body :key-fn keyword) :data :getSingleCompetitorResultsDiscipline :resultsByEvent))] (spit cache-file results) (some->> results (filter #(and (not (:notLegal %)) (= (:disciplineCode %) "200") (not (:indoor %)))) (first) :results (keep (fn [{:keys [mark wind]}] (let [mark (util/parse-double mark) wind (util/parse-double wind)] (when (and (double? mark) (double? wind)) (util/correct-200m-for-wind mark wind))))) (sort) (first)))) (comment (fastest-time-by-year (athlete-name->athlete-id "PI:NAME:<NAME>END_PI") 2021))
[ { "context": "er :xml-jaxb :fr) manager)))))\n\n\n;; Copyright 2018 Frederic Merizen\n;;\n;; Licensed under the Apache License, Version ", "end": 3091, "score": 0.9998608827590942, "start": 3075, "tag": "NAME", "value": "Frederic Merizen" } ]
test/ferje/place_test.clj
chourave/clojyday
0
;; Copyright and license information at end of file (ns ferje.place-test (:require [clojure.test :refer [deftest is join-fixtures testing use-fixtures]] [ferje.jaxb-utils :refer [jaxb-fixture]] [ferje.place :as place] [ferje.spec-test-utils :refer [instrument-fixture]] [ferje.util :as util] [clojure.java.io :as io]) (:import (de.jollyday HolidayCalendar) (de.jollyday.parameter UrlManagerParameter) (java.util Locale))) ;; Fixtures (use-fixtures :once (join-fixtures [jaxb-fixture instrument-fixture])) ;; Basic type predicates (deftest locale?-test (testing "only instances of Locale are locales" (is (place/locale? (Locale/FRANCE))) (is (not (place/locale? :france))))) (deftest format?-test (is (place/format? :any-format)) (is (place/format? :xml)) (is (place/format? :xml-jaxb)) (is (not (place/format? :random)))) ;; (deftest format-properties-test (let [old-hierarchy @#'place/format-hierarchy] (with-redefs [place/format-hierarchy (-> (make-hierarchy) (derive :foo :foo/bar) (derive :foo/bar :any-format))] (testing "with namespaced keyword" (is (= :foo/bar (-> (doto (UrlManagerParameter. nil nil) (place/set-format! :foo/bar)) place/get-format)))) (testing "with plain keyword" (is (= :foo (-> (doto (UrlManagerParameter. nil nil) (place/set-format! :foo)) place/get-format))))))) ;; Parsing a place (defn get-calendar-id "Prove that we can load HolidayManager that’s at least superficially valid by returning its id." [cal] (-> (place/holiday-manager :xml-jaxb cal) (.getCalendarHierarchy) (.getId))) (deftest holiday-manager-test ;; Smoke test: we check that we can load a ;; HolidayManager through the various ;; means of identifying it. (testing "With a locale keyword identifier" (is (= "fr" (get-calendar-id :fr)))) (testing "With a locale string identifier" (is (= "fr" (get-calendar-id "fr")))) (testing "With a Java locale" (is (= "fr" (get-calendar-id Locale/FRANCE)))) (testing "With a an existing holiday calendar" (is (= "fr" (get-calendar-id (HolidayCalendar/FRANCE))))) (testing "With a configuration file URL" (is (= "fr" (get-calendar-id (io/resource "holidays/Holidays_fr.xml")))))) (deftest parse-place-test (testing "With a single arument, give holidays for the whole country" (let [{::place/keys [manager zones]} (place/parse-place :xml-jaxb :fr)] (is (util/string-array? zones)) (is (nil? (seq zones))) (is (= (place/holiday-manager :xml-jaxb :fr) manager)))) (testing "More arguments are translated into zones" (let [{::place/keys [manager zones]} (place/parse-place :xml-jaxb [:fr :br])] (is (util/string-array? zones)) (is (= ["br"] (seq zones))) (is (= (place/holiday-manager :xml-jaxb :fr) manager))))) ;; 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.
5525
;; Copyright and license information at end of file (ns ferje.place-test (:require [clojure.test :refer [deftest is join-fixtures testing use-fixtures]] [ferje.jaxb-utils :refer [jaxb-fixture]] [ferje.place :as place] [ferje.spec-test-utils :refer [instrument-fixture]] [ferje.util :as util] [clojure.java.io :as io]) (:import (de.jollyday HolidayCalendar) (de.jollyday.parameter UrlManagerParameter) (java.util Locale))) ;; Fixtures (use-fixtures :once (join-fixtures [jaxb-fixture instrument-fixture])) ;; Basic type predicates (deftest locale?-test (testing "only instances of Locale are locales" (is (place/locale? (Locale/FRANCE))) (is (not (place/locale? :france))))) (deftest format?-test (is (place/format? :any-format)) (is (place/format? :xml)) (is (place/format? :xml-jaxb)) (is (not (place/format? :random)))) ;; (deftest format-properties-test (let [old-hierarchy @#'place/format-hierarchy] (with-redefs [place/format-hierarchy (-> (make-hierarchy) (derive :foo :foo/bar) (derive :foo/bar :any-format))] (testing "with namespaced keyword" (is (= :foo/bar (-> (doto (UrlManagerParameter. nil nil) (place/set-format! :foo/bar)) place/get-format)))) (testing "with plain keyword" (is (= :foo (-> (doto (UrlManagerParameter. nil nil) (place/set-format! :foo)) place/get-format))))))) ;; Parsing a place (defn get-calendar-id "Prove that we can load HolidayManager that’s at least superficially valid by returning its id." [cal] (-> (place/holiday-manager :xml-jaxb cal) (.getCalendarHierarchy) (.getId))) (deftest holiday-manager-test ;; Smoke test: we check that we can load a ;; HolidayManager through the various ;; means of identifying it. (testing "With a locale keyword identifier" (is (= "fr" (get-calendar-id :fr)))) (testing "With a locale string identifier" (is (= "fr" (get-calendar-id "fr")))) (testing "With a Java locale" (is (= "fr" (get-calendar-id Locale/FRANCE)))) (testing "With a an existing holiday calendar" (is (= "fr" (get-calendar-id (HolidayCalendar/FRANCE))))) (testing "With a configuration file URL" (is (= "fr" (get-calendar-id (io/resource "holidays/Holidays_fr.xml")))))) (deftest parse-place-test (testing "With a single arument, give holidays for the whole country" (let [{::place/keys [manager zones]} (place/parse-place :xml-jaxb :fr)] (is (util/string-array? zones)) (is (nil? (seq zones))) (is (= (place/holiday-manager :xml-jaxb :fr) manager)))) (testing "More arguments are translated into zones" (let [{::place/keys [manager zones]} (place/parse-place :xml-jaxb [:fr :br])] (is (util/string-array? zones)) (is (= ["br"] (seq zones))) (is (= (place/holiday-manager :xml-jaxb :fr) manager))))) ;; 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.place-test (:require [clojure.test :refer [deftest is join-fixtures testing use-fixtures]] [ferje.jaxb-utils :refer [jaxb-fixture]] [ferje.place :as place] [ferje.spec-test-utils :refer [instrument-fixture]] [ferje.util :as util] [clojure.java.io :as io]) (:import (de.jollyday HolidayCalendar) (de.jollyday.parameter UrlManagerParameter) (java.util Locale))) ;; Fixtures (use-fixtures :once (join-fixtures [jaxb-fixture instrument-fixture])) ;; Basic type predicates (deftest locale?-test (testing "only instances of Locale are locales" (is (place/locale? (Locale/FRANCE))) (is (not (place/locale? :france))))) (deftest format?-test (is (place/format? :any-format)) (is (place/format? :xml)) (is (place/format? :xml-jaxb)) (is (not (place/format? :random)))) ;; (deftest format-properties-test (let [old-hierarchy @#'place/format-hierarchy] (with-redefs [place/format-hierarchy (-> (make-hierarchy) (derive :foo :foo/bar) (derive :foo/bar :any-format))] (testing "with namespaced keyword" (is (= :foo/bar (-> (doto (UrlManagerParameter. nil nil) (place/set-format! :foo/bar)) place/get-format)))) (testing "with plain keyword" (is (= :foo (-> (doto (UrlManagerParameter. nil nil) (place/set-format! :foo)) place/get-format))))))) ;; Parsing a place (defn get-calendar-id "Prove that we can load HolidayManager that’s at least superficially valid by returning its id." [cal] (-> (place/holiday-manager :xml-jaxb cal) (.getCalendarHierarchy) (.getId))) (deftest holiday-manager-test ;; Smoke test: we check that we can load a ;; HolidayManager through the various ;; means of identifying it. (testing "With a locale keyword identifier" (is (= "fr" (get-calendar-id :fr)))) (testing "With a locale string identifier" (is (= "fr" (get-calendar-id "fr")))) (testing "With a Java locale" (is (= "fr" (get-calendar-id Locale/FRANCE)))) (testing "With a an existing holiday calendar" (is (= "fr" (get-calendar-id (HolidayCalendar/FRANCE))))) (testing "With a configuration file URL" (is (= "fr" (get-calendar-id (io/resource "holidays/Holidays_fr.xml")))))) (deftest parse-place-test (testing "With a single arument, give holidays for the whole country" (let [{::place/keys [manager zones]} (place/parse-place :xml-jaxb :fr)] (is (util/string-array? zones)) (is (nil? (seq zones))) (is (= (place/holiday-manager :xml-jaxb :fr) manager)))) (testing "More arguments are translated into zones" (let [{::place/keys [manager zones]} (place/parse-place :xml-jaxb [:fr :br])] (is (util/string-array? zones)) (is (= ["br"] (seq zones))) (is (= (place/holiday-manager :xml-jaxb :fr) manager))))) ;; 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": "; Copyright 2016-2019 Peter Schwarz\n;\n; Licensed under the Apache License, Version 2.", "end": 35, "score": 0.9998142719268799, "start": 22, "tag": "NAME", "value": "Peter Schwarz" } ]
test/virtua/event_test.cljs
peterschwarz/virtua
4
; Copyright 2016-2019 Peter Schwarz ; ; 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 virtua.event-test (:require [cljs.test :refer-macros [deftest testing async is are use-fixtures]] [virtua.core :as v] [virtua.test-utils :refer-macros [with-container]] [goog.dom :as gdom] [goog.events :as evt])) (defn- trigger! [el evt-type] (let [event (js/document.createEvent "HTMLEvents")] (.initEvent event evt-type, true, false) (.dispatchEvent el event))) (defn- click! [el] (trigger! el "click")) (defn- change! [el value] (set! (.-value el) value) (trigger! el "change")) (deftest test-click (let [clicked? (atom false)] (with-container el (v/attach! [:div {:id "test" :on-click #(reset! clicked? true)}] {} el) (click! (gdom/getRequiredElement "test"))) (is (= true @clicked?)))) (deftest test-change (let [new-value (atom nil)] (with-container el (v/attach! [:div {:id "test" :on-change #(reset! new-value (.. % -target -value))}] {} el) (change! (gdom/getRequiredElement "test") "changed!")) (is (= "changed!" @new-value)))) (deftest test-update-change-handler (let [clicked-value (atom 0) app-state (atom {:click-fn #(swap! clicked-value inc)})] (with-container el (v/attach! (fn [state] [:button {:id "btn" :on-click (:click-fn state)}]) app-state el) (click! (gdom/getRequiredElement "btn")) (is (= 1 @clicked-value)) (swap! app-state assoc :click-fn #(swap! clicked-value dec)) (click! (gdom/getRequiredElement "btn")) (is (= 0 @clicked-value)))))
110189
; Copyright 2016-2019 <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 virtua.event-test (:require [cljs.test :refer-macros [deftest testing async is are use-fixtures]] [virtua.core :as v] [virtua.test-utils :refer-macros [with-container]] [goog.dom :as gdom] [goog.events :as evt])) (defn- trigger! [el evt-type] (let [event (js/document.createEvent "HTMLEvents")] (.initEvent event evt-type, true, false) (.dispatchEvent el event))) (defn- click! [el] (trigger! el "click")) (defn- change! [el value] (set! (.-value el) value) (trigger! el "change")) (deftest test-click (let [clicked? (atom false)] (with-container el (v/attach! [:div {:id "test" :on-click #(reset! clicked? true)}] {} el) (click! (gdom/getRequiredElement "test"))) (is (= true @clicked?)))) (deftest test-change (let [new-value (atom nil)] (with-container el (v/attach! [:div {:id "test" :on-change #(reset! new-value (.. % -target -value))}] {} el) (change! (gdom/getRequiredElement "test") "changed!")) (is (= "changed!" @new-value)))) (deftest test-update-change-handler (let [clicked-value (atom 0) app-state (atom {:click-fn #(swap! clicked-value inc)})] (with-container el (v/attach! (fn [state] [:button {:id "btn" :on-click (:click-fn state)}]) app-state el) (click! (gdom/getRequiredElement "btn")) (is (= 1 @clicked-value)) (swap! app-state assoc :click-fn #(swap! clicked-value dec)) (click! (gdom/getRequiredElement "btn")) (is (= 0 @clicked-value)))))
true
; Copyright 2016-2019 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 virtua.event-test (:require [cljs.test :refer-macros [deftest testing async is are use-fixtures]] [virtua.core :as v] [virtua.test-utils :refer-macros [with-container]] [goog.dom :as gdom] [goog.events :as evt])) (defn- trigger! [el evt-type] (let [event (js/document.createEvent "HTMLEvents")] (.initEvent event evt-type, true, false) (.dispatchEvent el event))) (defn- click! [el] (trigger! el "click")) (defn- change! [el value] (set! (.-value el) value) (trigger! el "change")) (deftest test-click (let [clicked? (atom false)] (with-container el (v/attach! [:div {:id "test" :on-click #(reset! clicked? true)}] {} el) (click! (gdom/getRequiredElement "test"))) (is (= true @clicked?)))) (deftest test-change (let [new-value (atom nil)] (with-container el (v/attach! [:div {:id "test" :on-change #(reset! new-value (.. % -target -value))}] {} el) (change! (gdom/getRequiredElement "test") "changed!")) (is (= "changed!" @new-value)))) (deftest test-update-change-handler (let [clicked-value (atom 0) app-state (atom {:click-fn #(swap! clicked-value inc)})] (with-container el (v/attach! (fn [state] [:button {:id "btn" :on-click (:click-fn state)}]) app-state el) (click! (gdom/getRequiredElement "btn")) (is (= 1 @clicked-value)) (swap! app-state assoc :click-fn #(swap! clicked-value dec)) (click! (gdom/getRequiredElement "btn")) (is (= 0 @clicked-value)))))
[ { "context": ";;; Copyright 2013 Mitchell Kember. Subject to the MIT License.\n\n(ns mini-pinions.me", "end": 34, "score": 0.9999054074287415, "start": 19, "tag": "NAME", "value": "Mitchell Kember" }, { "context": "utton-margin 20)\n\n(def copyright \"Copyright © 2013 Mitchell Kember.\\nSubject to the MIT License.\")\n(def copyright-si", "end": 441, "score": 0.9998699426651001, "start": 426, "tag": "NAME", "value": "Mitchell Kember" } ]
src/mini_pinions/menu.clj
mk12/mini-pinions
1
;;; Copyright 2013 Mitchell Kember. Subject to the MIT License. (ns mini-pinions.menu "Implements the main menu world, the starting point of the application." (:require [quil.core :as q] [mini-pinions.button :as b] [mini-pinions.common :as c] [mini-pinions.vector :as v])) ;;;;; Constants (def background-color [160 240 255]) (def button-margin 20) (def copyright "Copyright © 2013 Mitchell Kember.\nSubject to the MIT License.") (def copyright-size 18) (def copyright-pos (v/make c/half-width (- c/height 80))) (def instructions-size 20) (def instructions-lines ["Fledge is a special bird. His pinions (wings) are so mini he can't fly." "Instead, he has to take advantage of gravity to slide and gain speed." "" "Control Fledge by CLICKING THE MOUSE to make him nosedive," "and time it just right to SLIDE along a valley each time." "Get to the end of the level with as high a score as possible!" "" "For serious points, reach escape velocity and visit OUTER SPACE!" "You'll get 10 times more points, but watch out! Planets exert their own" "gravitational pull, and if you're not careful you'll crash into one," "fall down, and take a 500 point penalty."]) (def scores-size 30) ;;;;; Menu button (defn menu-action "Returns to the main menu, passing along cached data." [world] (c/init {:name :menu :game (:game world) :high-scores (:high-scores world)})) (def menu-button (b/make-control "<" menu-action b/top-left-1 [255 255 255])) ;;;;; Buttons (defmacro returning-action "Makes an action that will go to the given world, passing along cached data." [world-name] `(fn [world#] {:name ~world-name :game (:game world#) :high-scores (:high-scores world#)})) (defn play-action [world] "Creates (or retrieves) the game world when the play button is pressed." (or (:game world) (c/init {:name :game :level 1 :high-scores (:high-scores world)}))) (def main-buttons (b/make-button-stack (v/make c/half-width c/half-height) (v/make 400 300) button-margin [{:text "Play" :action play-action :color [255 150 0]} {:text "Levels" :action (returning-action :level-select) :color [100 100 100]} {:text "Instructions" :action (returning-action :instructions) :color [0 221 255]} {:text "Scores" :action (returning-action :scores) :color [200 200 200]}])) (defmacro level-action [level] `(fn [world#] (let [game# (:game world#)] (if (= (:level game#) ~level) game# (c/init {:name :game :level ~level :high-scores (:high-scores world#)}))))) (def level-buttons (conj (b/make-button-grid :rect (v/make c/half-width c/half-height) (v/make 300 200) button-margin 3 (map #(hash-map :text (str %) :action (level-action %) :color [80 80 80]) (range 1 7))) menu-button)) ;;;;; Draw (defn draw-title "Draws a title in large text in the top-center region." [title] (q/text-size 50) (c/fill-grey 0) (c/draw-text title (v/make c/half-width 75))) ;;;;; Menu world (defmethod c/input :menu [world] (or (b/button-action main-buttons world) world)) (defmethod c/draw :menu [world] (c/clear-background background-color) (draw-title "Mini Pinions") (q/text-size copyright-size) (c/draw-text copyright copyright-pos) (b/draw-buttons main-buttons)) ;;;;; Level select world (defmethod c/input :level-select [world] (or (b/button-action level-buttons world) world)) (defmethod c/draw :level-select [world] (c/clear-background background-color) (draw-title "Level Select") (b/draw-buttons level-buttons)) ;;;;; Instructions world (defmethod c/input :instructions [world] (or (b/button-action [menu-button] world) world)) (defmethod c/draw :instructions [world] (c/clear-background background-color) (draw-title "Instructions") (b/draw-button menu-button) (q/text-size instructions-size) (doall (map-indexed (fn [index line] (c/draw-text line (v/make c/half-width (+ 150 (* index 40))))) instructions-lines))) ;;;;; Scores world (defn score-list "Returns its argument unless it is nil, in which case it returns a list containing a zero for each level." [high-scores] (vec (or high-scores (repeat 6 0)))) (defn add-score "Adds a score to the list of high scores. Only changes if it is a new best." [level score high-scores] (let [v (score-list high-scores) index (- level 1)] (assoc v index (max (v index) score)))) (defmethod c/input :scores [world] (or (b/button-action [menu-button] world) world)) (defmethod c/draw :scores [world] (c/clear-background background-color) (draw-title "Scores") (b/draw-button menu-button) (q/text-size scores-size) (doall (map-indexed (fn [index score] (c/draw-text (str "Level " (+ index 1) ": " (int score)) (v/make c/half-width (+ 200 (* index 40))))) (score-list (:high-scores world)))))
97145
;;; Copyright 2013 <NAME>. Subject to the MIT License. (ns mini-pinions.menu "Implements the main menu world, the starting point of the application." (:require [quil.core :as q] [mini-pinions.button :as b] [mini-pinions.common :as c] [mini-pinions.vector :as v])) ;;;;; Constants (def background-color [160 240 255]) (def button-margin 20) (def copyright "Copyright © 2013 <NAME>.\nSubject to the MIT License.") (def copyright-size 18) (def copyright-pos (v/make c/half-width (- c/height 80))) (def instructions-size 20) (def instructions-lines ["Fledge is a special bird. His pinions (wings) are so mini he can't fly." "Instead, he has to take advantage of gravity to slide and gain speed." "" "Control Fledge by CLICKING THE MOUSE to make him nosedive," "and time it just right to SLIDE along a valley each time." "Get to the end of the level with as high a score as possible!" "" "For serious points, reach escape velocity and visit OUTER SPACE!" "You'll get 10 times more points, but watch out! Planets exert their own" "gravitational pull, and if you're not careful you'll crash into one," "fall down, and take a 500 point penalty."]) (def scores-size 30) ;;;;; Menu button (defn menu-action "Returns to the main menu, passing along cached data." [world] (c/init {:name :menu :game (:game world) :high-scores (:high-scores world)})) (def menu-button (b/make-control "<" menu-action b/top-left-1 [255 255 255])) ;;;;; Buttons (defmacro returning-action "Makes an action that will go to the given world, passing along cached data." [world-name] `(fn [world#] {:name ~world-name :game (:game world#) :high-scores (:high-scores world#)})) (defn play-action [world] "Creates (or retrieves) the game world when the play button is pressed." (or (:game world) (c/init {:name :game :level 1 :high-scores (:high-scores world)}))) (def main-buttons (b/make-button-stack (v/make c/half-width c/half-height) (v/make 400 300) button-margin [{:text "Play" :action play-action :color [255 150 0]} {:text "Levels" :action (returning-action :level-select) :color [100 100 100]} {:text "Instructions" :action (returning-action :instructions) :color [0 221 255]} {:text "Scores" :action (returning-action :scores) :color [200 200 200]}])) (defmacro level-action [level] `(fn [world#] (let [game# (:game world#)] (if (= (:level game#) ~level) game# (c/init {:name :game :level ~level :high-scores (:high-scores world#)}))))) (def level-buttons (conj (b/make-button-grid :rect (v/make c/half-width c/half-height) (v/make 300 200) button-margin 3 (map #(hash-map :text (str %) :action (level-action %) :color [80 80 80]) (range 1 7))) menu-button)) ;;;;; Draw (defn draw-title "Draws a title in large text in the top-center region." [title] (q/text-size 50) (c/fill-grey 0) (c/draw-text title (v/make c/half-width 75))) ;;;;; Menu world (defmethod c/input :menu [world] (or (b/button-action main-buttons world) world)) (defmethod c/draw :menu [world] (c/clear-background background-color) (draw-title "Mini Pinions") (q/text-size copyright-size) (c/draw-text copyright copyright-pos) (b/draw-buttons main-buttons)) ;;;;; Level select world (defmethod c/input :level-select [world] (or (b/button-action level-buttons world) world)) (defmethod c/draw :level-select [world] (c/clear-background background-color) (draw-title "Level Select") (b/draw-buttons level-buttons)) ;;;;; Instructions world (defmethod c/input :instructions [world] (or (b/button-action [menu-button] world) world)) (defmethod c/draw :instructions [world] (c/clear-background background-color) (draw-title "Instructions") (b/draw-button menu-button) (q/text-size instructions-size) (doall (map-indexed (fn [index line] (c/draw-text line (v/make c/half-width (+ 150 (* index 40))))) instructions-lines))) ;;;;; Scores world (defn score-list "Returns its argument unless it is nil, in which case it returns a list containing a zero for each level." [high-scores] (vec (or high-scores (repeat 6 0)))) (defn add-score "Adds a score to the list of high scores. Only changes if it is a new best." [level score high-scores] (let [v (score-list high-scores) index (- level 1)] (assoc v index (max (v index) score)))) (defmethod c/input :scores [world] (or (b/button-action [menu-button] world) world)) (defmethod c/draw :scores [world] (c/clear-background background-color) (draw-title "Scores") (b/draw-button menu-button) (q/text-size scores-size) (doall (map-indexed (fn [index score] (c/draw-text (str "Level " (+ index 1) ": " (int score)) (v/make c/half-width (+ 200 (* index 40))))) (score-list (:high-scores world)))))
true
;;; Copyright 2013 PI:NAME:<NAME>END_PI. Subject to the MIT License. (ns mini-pinions.menu "Implements the main menu world, the starting point of the application." (:require [quil.core :as q] [mini-pinions.button :as b] [mini-pinions.common :as c] [mini-pinions.vector :as v])) ;;;;; Constants (def background-color [160 240 255]) (def button-margin 20) (def copyright "Copyright © 2013 PI:NAME:<NAME>END_PI.\nSubject to the MIT License.") (def copyright-size 18) (def copyright-pos (v/make c/half-width (- c/height 80))) (def instructions-size 20) (def instructions-lines ["Fledge is a special bird. His pinions (wings) are so mini he can't fly." "Instead, he has to take advantage of gravity to slide and gain speed." "" "Control Fledge by CLICKING THE MOUSE to make him nosedive," "and time it just right to SLIDE along a valley each time." "Get to the end of the level with as high a score as possible!" "" "For serious points, reach escape velocity and visit OUTER SPACE!" "You'll get 10 times more points, but watch out! Planets exert their own" "gravitational pull, and if you're not careful you'll crash into one," "fall down, and take a 500 point penalty."]) (def scores-size 30) ;;;;; Menu button (defn menu-action "Returns to the main menu, passing along cached data." [world] (c/init {:name :menu :game (:game world) :high-scores (:high-scores world)})) (def menu-button (b/make-control "<" menu-action b/top-left-1 [255 255 255])) ;;;;; Buttons (defmacro returning-action "Makes an action that will go to the given world, passing along cached data." [world-name] `(fn [world#] {:name ~world-name :game (:game world#) :high-scores (:high-scores world#)})) (defn play-action [world] "Creates (or retrieves) the game world when the play button is pressed." (or (:game world) (c/init {:name :game :level 1 :high-scores (:high-scores world)}))) (def main-buttons (b/make-button-stack (v/make c/half-width c/half-height) (v/make 400 300) button-margin [{:text "Play" :action play-action :color [255 150 0]} {:text "Levels" :action (returning-action :level-select) :color [100 100 100]} {:text "Instructions" :action (returning-action :instructions) :color [0 221 255]} {:text "Scores" :action (returning-action :scores) :color [200 200 200]}])) (defmacro level-action [level] `(fn [world#] (let [game# (:game world#)] (if (= (:level game#) ~level) game# (c/init {:name :game :level ~level :high-scores (:high-scores world#)}))))) (def level-buttons (conj (b/make-button-grid :rect (v/make c/half-width c/half-height) (v/make 300 200) button-margin 3 (map #(hash-map :text (str %) :action (level-action %) :color [80 80 80]) (range 1 7))) menu-button)) ;;;;; Draw (defn draw-title "Draws a title in large text in the top-center region." [title] (q/text-size 50) (c/fill-grey 0) (c/draw-text title (v/make c/half-width 75))) ;;;;; Menu world (defmethod c/input :menu [world] (or (b/button-action main-buttons world) world)) (defmethod c/draw :menu [world] (c/clear-background background-color) (draw-title "Mini Pinions") (q/text-size copyright-size) (c/draw-text copyright copyright-pos) (b/draw-buttons main-buttons)) ;;;;; Level select world (defmethod c/input :level-select [world] (or (b/button-action level-buttons world) world)) (defmethod c/draw :level-select [world] (c/clear-background background-color) (draw-title "Level Select") (b/draw-buttons level-buttons)) ;;;;; Instructions world (defmethod c/input :instructions [world] (or (b/button-action [menu-button] world) world)) (defmethod c/draw :instructions [world] (c/clear-background background-color) (draw-title "Instructions") (b/draw-button menu-button) (q/text-size instructions-size) (doall (map-indexed (fn [index line] (c/draw-text line (v/make c/half-width (+ 150 (* index 40))))) instructions-lines))) ;;;;; Scores world (defn score-list "Returns its argument unless it is nil, in which case it returns a list containing a zero for each level." [high-scores] (vec (or high-scores (repeat 6 0)))) (defn add-score "Adds a score to the list of high scores. Only changes if it is a new best." [level score high-scores] (let [v (score-list high-scores) index (- level 1)] (assoc v index (max (v index) score)))) (defmethod c/input :scores [world] (or (b/button-action [menu-button] world) world)) (defmethod c/draw :scores [world] (c/clear-background background-color) (draw-title "Scores") (b/draw-button menu-button) (q/text-size scores-size) (doall (map-indexed (fn [index score] (c/draw-text (str "Level " (+ index 1) ": " (int score)) (v/make c/half-width (+ 200 (* index 40))))) (score-list (:high-scores world)))))
[ { "context": "e(s). Memoized.\n\n (translations \\\"es\\\") ;-> {\\\"Username\\\" \\\"Nombre Usuario\\\", ...}\"\n (comp (memoize tran", "end": 3466, "score": 0.9766929745674133, "start": 3458, "tag": "USERNAME", "value": "Username" }, { "context": "d.\n\n (translations \\\"es\\\") ;-> {\\\"Username\\\" \\\"Nombre Usuario\\\", ...}\"\n (comp (memoize translations*) ", "end": 3477, "score": 0.39564165472984314, "start": 3471, "tag": "NAME", "value": "Nombre" }, { "context": " (translations \\\"es\\\") ;-> {\\\"Username\\\" \\\"Nombre Usuario\\\", ...}\"\n (comp (memoize translations*) locale))", "end": 3485, "score": 0.5034931302070618, "start": 3478, "tag": "USERNAME", "value": "Usuario" } ]
c#-metabase/src/metabase/util/i18n/impl.clj
hanakhry/Crime_Admin
0
(ns metabase.util.i18n.impl "Lower-level implementation functions for `metabase.util.i18n`. Most of this is not meant to be used directly; use the functions and macros in `metabase.util.i18n` instead." (:require [clojure.java.io :as io] [clojure.string :as str] [clojure.tools.logging :as log] [clojure.tools.reader.edn :as edn] [metabase.plugins.classloader :as classloader] [potemkin.types :as p.types]) (:import java.text.MessageFormat java.util.Locale org.apache.commons.lang3.LocaleUtils)) (p.types/defprotocol+ CoerceToLocale "Protocol for anything that can be coerced to a `java.util.Locale`." (locale ^java.util.Locale [this] "Coerce `this` to a `java.util.Locale`.")) (defn normalized-locale-string "Normalize a locale string to the canonical format. (normalized-locale-string \"EN-US\") ;-> \"en_US\" Returns `nil` for invalid strings -- you can use this to check whether a String is valid." ^String [s] {:pre [((some-fn nil? string?) s)]} (when (string? s) (when-let [[_ language country] (re-matches #"^(\w{2})(?:[-_](\w{2}))?$" s)] (let [language (str/lower-case language)] (if country (str language \_ (some-> country str/upper-case)) language))))) (extend-protocol CoerceToLocale nil (locale [_] nil) Locale (locale [this] this) String (locale [^String s] (some-> (normalized-locale-string s) LocaleUtils/toLocale)) ;; Support namespaced keywords like `:en/US` and `:en/UK` because we can clojure.lang.Keyword (locale [this] (locale (if-let [namespce (namespace this)] (str namespce \_ (name this)) (name this))))) (defn available-locale? "True if `locale` (a string, keyword, or `Locale`) is a valid locale available on this system. Normalizes args automatically." [locale-or-name] (boolean (when-let [locale (locale locale-or-name)] (LocaleUtils/isAvailableLocale locale)))) (defn parent-locale "For langugage + country Locales, returns the language-only Locale. Otherwise returns `nil`. (parent-locale \"en/US\") ; -> #object[java.util.Locale 0x79301688 \"en\"]" ^Locale [locale-or-name] (when-let [a-locale (locale locale-or-name)] (when (seq (.getCountry a-locale)) (locale (.getLanguage a-locale))))) (defn- locale-edn-resource "The resource URL for the edn file containing translations for `locale-or-name`. These files are built by the scripts in `bin/i18n` from `.po` files from POEditor. (locale-edn-resources \"es\") ;-> #object[java.net.URL \"file:/home/cam/metabase/resources/metabase/es.edn\"]" ^java.net.URL [locale-or-name] (when-let [a-locale (locale locale-or-name)] (let [locale-name (-> (normalized-locale-string (str a-locale)) (str/replace #"_" "-")) filename (format "i18n/%s.edn" locale-name)] (io/resource filename (classloader/the-classloader))))) (defn- translations* [a-locale] (when-let [resource (locale-edn-resource a-locale)] (edn/read-string (slurp resource)))) (def ^:private ^{:arglists '([locale-or-name])} translations "Fetch a map of original untranslated message format string -> translated message format string for `locale-or-name` by reading the corresponding EDN resource file. Does not include translations for parent locale(s). Memoized. (translations \"es\") ;-> {\"Username\" \"Nombre Usuario\", ...}" (comp (memoize translations*) locale)) (defn- translated-format-string* "Find the translated version of `format-string` for `locale-or-name`, or `nil` if none can be found. Does not search 'parent' (language-only) translations." ^String [locale-or-name format-string] (when (seq format-string) (when-let [locale (locale locale-or-name)] (when-let [translations (translations locale)] (get translations format-string))))) (defn- translated-format-string "Find the translated version of `format-string` for `locale-or-name`, or `nil` if none can be found. Searches parent (language-only) translations if none exist for a language + country locale." ^String [locale-or-name format-string] (when-let [a-locale (locale locale-or-name)] (or (when (= (.getLanguage a-locale) "en") format-string) (translated-format-string* a-locale format-string) (when-let [parent-locale (parent-locale a-locale)] (log/tracef "No translated string found, trying parent locale %s" (pr-str parent-locale)) (translated-format-string* parent-locale format-string)) format-string))) (defn- message-format ^MessageFormat [locale-or-name ^String format-string] (or (when-let [a-locale (locale locale-or-name)] (when-let [^String translated (translated-format-string a-locale format-string)] (MessageFormat. translated a-locale))) (MessageFormat. format-string))) (defn translate "Find the translated version of `format-string` for a `locale-or-name`, then format it. Translates using the resource bundles generated by the `./bin/i18n/build-translation-resources` script; these live in `./resources/metabase/Metabase/Messages_<locale>.class`. Attempts to translate with `language-country` Locale if specified, falling back to `language` (without country), finally falling back to English (i.e., not formatting the original untranslated `format-string`) if no matching bundles/translations exist, or if translation fails for some other reason. Will attempt to translate `format-string`, but if for some reason we're not able to (such as a typo in the translated version of the string), log the failure but return the original (untranslated) string. This is a workaround for translations that, due to a typo, will fail to parse using Java's message formatter. (translate \"es-MX\" \"must be {0} characters or less\" 140) ; -> \"deben tener 140 caracteres o menos\"" [locale-or-name ^String format-string & args] (when (seq format-string) (try (.format (message-format locale-or-name format-string) (to-array args)) (catch Throwable e ;; Not translating this string to prevent an unfortunate stack overflow. If this string happened to be the one ;; that had the typo, we'd just recur endlessly without logging an error. (log/errorf e "Unable to translate string %s to %s" (pr-str format-string) (str locale-or-name)) (try (.format (MessageFormat. format-string) (to-array args)) (catch Throwable _ (log/errorf e "Invalid format string %s" (pr-str format-string)) format-string)))))) (defn- available-locale-names* [] (log/info "Reading available locales from locales.clj...") (some-> (io/resource "locales.clj") slurp edn/read-string :locales set)) (def ^{:arglists '([])} available-locale-names "Return set of available locales, as Strings. (available-locale-names) ; -> #{\"nl\" \"pt\" \"en\" \"zh\"}" (let [locales (delay (available-locale-names*))] (fn [] @locales))) ;; We can't fetch the system locale until the application DB has been initiailized. Once that's done, we don't need to ;; do the check anymore -- swapping out the getter fn with the simpler one speeds things up substantially (def ^:private site-locale-from-setting-fn (atom (fn [] (when-let [db-is-set-up? (resolve 'metabase.db/db-is-set-up?)] (when (and (bound? db-is-set-up?) (db-is-set-up?)) (when-let [get-string (resolve 'metabase.models.setting/get-string)] (when (bound? get-string) (let [f (fn [] (get-string :site-locale))] (reset! site-locale-from-setting-fn f) (f))))))))) (defn site-locale-from-setting "Fetch the value of the `site-locale` Setting." [] (@site-locale-from-setting-fn)) (defmethod print-method Locale [locale ^java.io.Writer writer] ((get-method print-dup Locale) locale writer)) (defmethod print-dup Locale [locale ^java.io.Writer writer] (.write writer (format "#locale %s" (pr-str (str locale)))))
3743
(ns metabase.util.i18n.impl "Lower-level implementation functions for `metabase.util.i18n`. Most of this is not meant to be used directly; use the functions and macros in `metabase.util.i18n` instead." (:require [clojure.java.io :as io] [clojure.string :as str] [clojure.tools.logging :as log] [clojure.tools.reader.edn :as edn] [metabase.plugins.classloader :as classloader] [potemkin.types :as p.types]) (:import java.text.MessageFormat java.util.Locale org.apache.commons.lang3.LocaleUtils)) (p.types/defprotocol+ CoerceToLocale "Protocol for anything that can be coerced to a `java.util.Locale`." (locale ^java.util.Locale [this] "Coerce `this` to a `java.util.Locale`.")) (defn normalized-locale-string "Normalize a locale string to the canonical format. (normalized-locale-string \"EN-US\") ;-> \"en_US\" Returns `nil` for invalid strings -- you can use this to check whether a String is valid." ^String [s] {:pre [((some-fn nil? string?) s)]} (when (string? s) (when-let [[_ language country] (re-matches #"^(\w{2})(?:[-_](\w{2}))?$" s)] (let [language (str/lower-case language)] (if country (str language \_ (some-> country str/upper-case)) language))))) (extend-protocol CoerceToLocale nil (locale [_] nil) Locale (locale [this] this) String (locale [^String s] (some-> (normalized-locale-string s) LocaleUtils/toLocale)) ;; Support namespaced keywords like `:en/US` and `:en/UK` because we can clojure.lang.Keyword (locale [this] (locale (if-let [namespce (namespace this)] (str namespce \_ (name this)) (name this))))) (defn available-locale? "True if `locale` (a string, keyword, or `Locale`) is a valid locale available on this system. Normalizes args automatically." [locale-or-name] (boolean (when-let [locale (locale locale-or-name)] (LocaleUtils/isAvailableLocale locale)))) (defn parent-locale "For langugage + country Locales, returns the language-only Locale. Otherwise returns `nil`. (parent-locale \"en/US\") ; -> #object[java.util.Locale 0x79301688 \"en\"]" ^Locale [locale-or-name] (when-let [a-locale (locale locale-or-name)] (when (seq (.getCountry a-locale)) (locale (.getLanguage a-locale))))) (defn- locale-edn-resource "The resource URL for the edn file containing translations for `locale-or-name`. These files are built by the scripts in `bin/i18n` from `.po` files from POEditor. (locale-edn-resources \"es\") ;-> #object[java.net.URL \"file:/home/cam/metabase/resources/metabase/es.edn\"]" ^java.net.URL [locale-or-name] (when-let [a-locale (locale locale-or-name)] (let [locale-name (-> (normalized-locale-string (str a-locale)) (str/replace #"_" "-")) filename (format "i18n/%s.edn" locale-name)] (io/resource filename (classloader/the-classloader))))) (defn- translations* [a-locale] (when-let [resource (locale-edn-resource a-locale)] (edn/read-string (slurp resource)))) (def ^:private ^{:arglists '([locale-or-name])} translations "Fetch a map of original untranslated message format string -> translated message format string for `locale-or-name` by reading the corresponding EDN resource file. Does not include translations for parent locale(s). Memoized. (translations \"es\") ;-> {\"Username\" \"<NAME> Usuario\", ...}" (comp (memoize translations*) locale)) (defn- translated-format-string* "Find the translated version of `format-string` for `locale-or-name`, or `nil` if none can be found. Does not search 'parent' (language-only) translations." ^String [locale-or-name format-string] (when (seq format-string) (when-let [locale (locale locale-or-name)] (when-let [translations (translations locale)] (get translations format-string))))) (defn- translated-format-string "Find the translated version of `format-string` for `locale-or-name`, or `nil` if none can be found. Searches parent (language-only) translations if none exist for a language + country locale." ^String [locale-or-name format-string] (when-let [a-locale (locale locale-or-name)] (or (when (= (.getLanguage a-locale) "en") format-string) (translated-format-string* a-locale format-string) (when-let [parent-locale (parent-locale a-locale)] (log/tracef "No translated string found, trying parent locale %s" (pr-str parent-locale)) (translated-format-string* parent-locale format-string)) format-string))) (defn- message-format ^MessageFormat [locale-or-name ^String format-string] (or (when-let [a-locale (locale locale-or-name)] (when-let [^String translated (translated-format-string a-locale format-string)] (MessageFormat. translated a-locale))) (MessageFormat. format-string))) (defn translate "Find the translated version of `format-string` for a `locale-or-name`, then format it. Translates using the resource bundles generated by the `./bin/i18n/build-translation-resources` script; these live in `./resources/metabase/Metabase/Messages_<locale>.class`. Attempts to translate with `language-country` Locale if specified, falling back to `language` (without country), finally falling back to English (i.e., not formatting the original untranslated `format-string`) if no matching bundles/translations exist, or if translation fails for some other reason. Will attempt to translate `format-string`, but if for some reason we're not able to (such as a typo in the translated version of the string), log the failure but return the original (untranslated) string. This is a workaround for translations that, due to a typo, will fail to parse using Java's message formatter. (translate \"es-MX\" \"must be {0} characters or less\" 140) ; -> \"deben tener 140 caracteres o menos\"" [locale-or-name ^String format-string & args] (when (seq format-string) (try (.format (message-format locale-or-name format-string) (to-array args)) (catch Throwable e ;; Not translating this string to prevent an unfortunate stack overflow. If this string happened to be the one ;; that had the typo, we'd just recur endlessly without logging an error. (log/errorf e "Unable to translate string %s to %s" (pr-str format-string) (str locale-or-name)) (try (.format (MessageFormat. format-string) (to-array args)) (catch Throwable _ (log/errorf e "Invalid format string %s" (pr-str format-string)) format-string)))))) (defn- available-locale-names* [] (log/info "Reading available locales from locales.clj...") (some-> (io/resource "locales.clj") slurp edn/read-string :locales set)) (def ^{:arglists '([])} available-locale-names "Return set of available locales, as Strings. (available-locale-names) ; -> #{\"nl\" \"pt\" \"en\" \"zh\"}" (let [locales (delay (available-locale-names*))] (fn [] @locales))) ;; We can't fetch the system locale until the application DB has been initiailized. Once that's done, we don't need to ;; do the check anymore -- swapping out the getter fn with the simpler one speeds things up substantially (def ^:private site-locale-from-setting-fn (atom (fn [] (when-let [db-is-set-up? (resolve 'metabase.db/db-is-set-up?)] (when (and (bound? db-is-set-up?) (db-is-set-up?)) (when-let [get-string (resolve 'metabase.models.setting/get-string)] (when (bound? get-string) (let [f (fn [] (get-string :site-locale))] (reset! site-locale-from-setting-fn f) (f))))))))) (defn site-locale-from-setting "Fetch the value of the `site-locale` Setting." [] (@site-locale-from-setting-fn)) (defmethod print-method Locale [locale ^java.io.Writer writer] ((get-method print-dup Locale) locale writer)) (defmethod print-dup Locale [locale ^java.io.Writer writer] (.write writer (format "#locale %s" (pr-str (str locale)))))
true
(ns metabase.util.i18n.impl "Lower-level implementation functions for `metabase.util.i18n`. Most of this is not meant to be used directly; use the functions and macros in `metabase.util.i18n` instead." (:require [clojure.java.io :as io] [clojure.string :as str] [clojure.tools.logging :as log] [clojure.tools.reader.edn :as edn] [metabase.plugins.classloader :as classloader] [potemkin.types :as p.types]) (:import java.text.MessageFormat java.util.Locale org.apache.commons.lang3.LocaleUtils)) (p.types/defprotocol+ CoerceToLocale "Protocol for anything that can be coerced to a `java.util.Locale`." (locale ^java.util.Locale [this] "Coerce `this` to a `java.util.Locale`.")) (defn normalized-locale-string "Normalize a locale string to the canonical format. (normalized-locale-string \"EN-US\") ;-> \"en_US\" Returns `nil` for invalid strings -- you can use this to check whether a String is valid." ^String [s] {:pre [((some-fn nil? string?) s)]} (when (string? s) (when-let [[_ language country] (re-matches #"^(\w{2})(?:[-_](\w{2}))?$" s)] (let [language (str/lower-case language)] (if country (str language \_ (some-> country str/upper-case)) language))))) (extend-protocol CoerceToLocale nil (locale [_] nil) Locale (locale [this] this) String (locale [^String s] (some-> (normalized-locale-string s) LocaleUtils/toLocale)) ;; Support namespaced keywords like `:en/US` and `:en/UK` because we can clojure.lang.Keyword (locale [this] (locale (if-let [namespce (namespace this)] (str namespce \_ (name this)) (name this))))) (defn available-locale? "True if `locale` (a string, keyword, or `Locale`) is a valid locale available on this system. Normalizes args automatically." [locale-or-name] (boolean (when-let [locale (locale locale-or-name)] (LocaleUtils/isAvailableLocale locale)))) (defn parent-locale "For langugage + country Locales, returns the language-only Locale. Otherwise returns `nil`. (parent-locale \"en/US\") ; -> #object[java.util.Locale 0x79301688 \"en\"]" ^Locale [locale-or-name] (when-let [a-locale (locale locale-or-name)] (when (seq (.getCountry a-locale)) (locale (.getLanguage a-locale))))) (defn- locale-edn-resource "The resource URL for the edn file containing translations for `locale-or-name`. These files are built by the scripts in `bin/i18n` from `.po` files from POEditor. (locale-edn-resources \"es\") ;-> #object[java.net.URL \"file:/home/cam/metabase/resources/metabase/es.edn\"]" ^java.net.URL [locale-or-name] (when-let [a-locale (locale locale-or-name)] (let [locale-name (-> (normalized-locale-string (str a-locale)) (str/replace #"_" "-")) filename (format "i18n/%s.edn" locale-name)] (io/resource filename (classloader/the-classloader))))) (defn- translations* [a-locale] (when-let [resource (locale-edn-resource a-locale)] (edn/read-string (slurp resource)))) (def ^:private ^{:arglists '([locale-or-name])} translations "Fetch a map of original untranslated message format string -> translated message format string for `locale-or-name` by reading the corresponding EDN resource file. Does not include translations for parent locale(s). Memoized. (translations \"es\") ;-> {\"Username\" \"PI:NAME:<NAME>END_PI Usuario\", ...}" (comp (memoize translations*) locale)) (defn- translated-format-string* "Find the translated version of `format-string` for `locale-or-name`, or `nil` if none can be found. Does not search 'parent' (language-only) translations." ^String [locale-or-name format-string] (when (seq format-string) (when-let [locale (locale locale-or-name)] (when-let [translations (translations locale)] (get translations format-string))))) (defn- translated-format-string "Find the translated version of `format-string` for `locale-or-name`, or `nil` if none can be found. Searches parent (language-only) translations if none exist for a language + country locale." ^String [locale-or-name format-string] (when-let [a-locale (locale locale-or-name)] (or (when (= (.getLanguage a-locale) "en") format-string) (translated-format-string* a-locale format-string) (when-let [parent-locale (parent-locale a-locale)] (log/tracef "No translated string found, trying parent locale %s" (pr-str parent-locale)) (translated-format-string* parent-locale format-string)) format-string))) (defn- message-format ^MessageFormat [locale-or-name ^String format-string] (or (when-let [a-locale (locale locale-or-name)] (when-let [^String translated (translated-format-string a-locale format-string)] (MessageFormat. translated a-locale))) (MessageFormat. format-string))) (defn translate "Find the translated version of `format-string` for a `locale-or-name`, then format it. Translates using the resource bundles generated by the `./bin/i18n/build-translation-resources` script; these live in `./resources/metabase/Metabase/Messages_<locale>.class`. Attempts to translate with `language-country` Locale if specified, falling back to `language` (without country), finally falling back to English (i.e., not formatting the original untranslated `format-string`) if no matching bundles/translations exist, or if translation fails for some other reason. Will attempt to translate `format-string`, but if for some reason we're not able to (such as a typo in the translated version of the string), log the failure but return the original (untranslated) string. This is a workaround for translations that, due to a typo, will fail to parse using Java's message formatter. (translate \"es-MX\" \"must be {0} characters or less\" 140) ; -> \"deben tener 140 caracteres o menos\"" [locale-or-name ^String format-string & args] (when (seq format-string) (try (.format (message-format locale-or-name format-string) (to-array args)) (catch Throwable e ;; Not translating this string to prevent an unfortunate stack overflow. If this string happened to be the one ;; that had the typo, we'd just recur endlessly without logging an error. (log/errorf e "Unable to translate string %s to %s" (pr-str format-string) (str locale-or-name)) (try (.format (MessageFormat. format-string) (to-array args)) (catch Throwable _ (log/errorf e "Invalid format string %s" (pr-str format-string)) format-string)))))) (defn- available-locale-names* [] (log/info "Reading available locales from locales.clj...") (some-> (io/resource "locales.clj") slurp edn/read-string :locales set)) (def ^{:arglists '([])} available-locale-names "Return set of available locales, as Strings. (available-locale-names) ; -> #{\"nl\" \"pt\" \"en\" \"zh\"}" (let [locales (delay (available-locale-names*))] (fn [] @locales))) ;; We can't fetch the system locale until the application DB has been initiailized. Once that's done, we don't need to ;; do the check anymore -- swapping out the getter fn with the simpler one speeds things up substantially (def ^:private site-locale-from-setting-fn (atom (fn [] (when-let [db-is-set-up? (resolve 'metabase.db/db-is-set-up?)] (when (and (bound? db-is-set-up?) (db-is-set-up?)) (when-let [get-string (resolve 'metabase.models.setting/get-string)] (when (bound? get-string) (let [f (fn [] (get-string :site-locale))] (reset! site-locale-from-setting-fn f) (f))))))))) (defn site-locale-from-setting "Fetch the value of the `site-locale` Setting." [] (@site-locale-from-setting-fn)) (defmethod print-method Locale [locale ^java.io.Writer writer] ((get-method print-dup Locale) locale writer)) (defmethod print-dup Locale [locale ^java.io.Writer writer] (.write writer (format "#locale %s" (pr-str (str locale)))))
[ { "context": " (let [response (register-req {:username \"tes\" :password \"passwor\"})\n body ", "end": 985, "score": 0.7923092842102051, "start": 982, "tag": "USERNAME", "value": "tes" }, { "context": "esponse (register-req {:username \"tes\" :password \"passwor\"})\n body (parse-body (:body r", "end": 1005, "score": 0.999217689037323, "start": 998, "tag": "PASSWORD", "value": "passwor" }, { "context": "\"]\n :password [\"Password length must be greater than 7\"]}))\n\n (fact \"correctly filled field do n", "end": 1282, "score": 0.9981644749641418, "start": 1244, "tag": "PASSWORD", "value": "Password length must be greater than 7" }, { "context": " (let [response (register-req {:username \"user\" :password \"wrong\"})\n body (p", "end": 1421, "score": 0.6144073009490967, "start": 1417, "tag": "USERNAME", "value": "user" }, { "context": "sponse (register-req {:username \"user\" :password \"wrong\"})\n body (parse-body (:body r", "end": 1439, "score": 0.9712094664573669, "start": 1434, "tag": "PASSWORD", "value": "wrong" }, { "context": " returns username\"\n (let [sameuser \"user\"\n response (register-req {:us", "end": 1775, "score": 0.9839105010032654, "start": 1771, "tag": "USERNAME", "value": "user" }, { "context": "onse (register-req {:username sameuser :password \"password\"})\n body (parse-body (:body r", "end": 1860, "score": 0.9995810985565186, "start": 1852, "tag": "PASSWORD", "value": "password" }, { "context": "er code and error\"\n (let [sameuser \"user\"\n _ (register-req {:username ", "end": 2130, "score": 0.9790558815002441, "start": 2126, "tag": "USERNAME", "value": "user" }, { "context": "r\"\n _ (register-req {:username sameuser :password \"password\"})\n respo", "end": 2188, "score": 0.9982629418373108, "start": 2180, "tag": "USERNAME", "value": "sameuser" }, { "context": " _ (register-req {:username sameuser :password \"password\"})\n response (register-req {:", "end": 2208, "score": 0.9996252059936523, "start": 2200, "tag": "PASSWORD", "value": "password" }, { "context": " response (register-req {:username sameuser :password \"anything\"})\n body ", "end": 2275, "score": 0.99736088514328, "start": 2267, "tag": "USERNAME", "value": "sameuser" }, { "context": "onse (register-req {:username sameuser :password \"anything\"})\n body (parse-body (:body r", "end": 2295, "score": 0.9995313882827759, "start": 2287, "tag": "PASSWORD", "value": "anything" }, { "context": "User already exists\"))))\n\n(let [creds {:username \"user\" :password \"password\"}\n inv-pass {:username ", "end": 2488, "score": 0.9554795622825623, "start": 2484, "tag": "USERNAME", "value": "user" }, { "context": "ts\"))))\n\n(let [creds {:username \"user\" :password \"password\"}\n inv-pass {:username \"user\" :password \"wro", "end": 2509, "score": 0.9996414184570312, "start": 2501, "tag": "PASSWORD", "value": "password" }, { "context": " :password \"password\"}\n inv-pass {:username \"user\" :password \"wrong\"}]\n (with-state-changes [(befo", "end": 2543, "score": 0.9635715484619141, "start": 2539, "tag": "USERNAME", "value": "user" }, { "context": "ord\"}\n inv-pass {:username \"user\" :password \"wrong\"}]\n (with-state-changes [(before :contents (do (", "end": 2561, "score": 0.9995593428611755, "start": 2556, "tag": "PASSWORD", "value": "wrong" }, { "context": "(:username creds)})))))\n\n\n(let [creds {:username \"user\" :password \"password\"}\n other-creds {:userna", "end": 3403, "score": 0.9962038397789001, "start": 3399, "tag": "USERNAME", "value": "user" }, { "context": "})))))\n\n\n(let [creds {:username \"user\" :password \"password\"}\n other-creds {:username \"otheruser\" :passw", "end": 3424, "score": 0.9996029734611511, "start": 3416, "tag": "PASSWORD", "value": "password" }, { "context": "assword \"password\"}\n other-creds {:username \"otheruser\" :password \"anypassword\"}\n non-user {:userna", "end": 3466, "score": 0.9993722438812256, "start": 3457, "tag": "USERNAME", "value": "otheruser" }, { "context": " other-creds {:username \"otheruser\" :password \"anypassword\"}\n non-user {:username \"nobody\" :password \"p", "end": 3490, "score": 0.9993710517883301, "start": 3479, "tag": "PASSWORD", "value": "anypassword" }, { "context": "assword \"anypassword\"}\n non-user {:username \"nobody\" :password \"password\"}\n version \"4.20\"\n ", "end": 3526, "score": 0.999595046043396, "start": 3520, "tag": "USERNAME", "value": "nobody" }, { "context": "d\"}\n non-user {:username \"nobody\" :password \"password\"}\n version \"4.20\"\n mac \"F9:EC:6C:C0:29:", "end": 3547, "score": 0.999561607837677, "start": 3539, "tag": "PASSWORD", "value": "password" } ]
test/otaservice/api_test.clj
fominok/otaservice
1
(ns otaservice.api-test (:use midje.sweet) (:require [ring.mock.request :as mock] [cheshire.core :as cheshire] [deploy :refer :all] [buddy.sign.jwt :as jwt] [environ.core :refer [env]] [otaservice.core :refer [app]])) (defn parse-body [body] (cheshire/parse-string (slurp body) true)) (defn register-req [query] (app (-> (mock/request :post "/api/v1/register") (mock/content-type "application/json") (mock/body (cheshire/generate-string query))))) (defn login-req [query] (app (-> (mock/request :post "/api/v1/login") (mock/content-type "application/json") (mock/body (cheshire/generate-string query))))) (with-state-changes [(before :facts (migrate)) (after :facts (rollback-all))] (facts "about registration" (fact "if register with short login/pass proper error returned" (let [response (register-req {:username "tes" :password "passwor"}) body (parse-body (:body response))] (:status response) => 400 (:error body) => {:username ["Username length must be greater than 3"] :password ["Password length must be greater than 7"]})) (fact "correctly filled field do not show up in error message" (let [response (register-req {:username "user" :password "wrong"}) body (parse-body (:body response))] (:status response) => 400 (:error body) =not=> (contains {:username anything}) (:error body) => (contains {:password anything}))) (fact "successful registration returns username" (let [sameuser "user" response (register-req {:username sameuser :password "password"}) body (parse-body (:body response))] (:status response) => 200 (:identity body) => sameuser)) (fact "registering with existing username returns proper code and error" (let [sameuser "user" _ (register-req {:username sameuser :password "password"}) response (register-req {:username sameuser :password "anything"}) body (parse-body (:body response))] (:status response) => 409 (:error body) => "User already exists")))) (let [creds {:username "user" :password "password"} inv-pass {:username "user" :password "wrong"}] (with-state-changes [(before :contents (do (migrate) (register-req creds))) (after :contents (rollback-all))] (facts "about authentication" (fact "cannot login with wrong password" (let [response (login-req inv-pass) body (parse-body (:body response))] (:status response) => 401 (:error body) => "Wrong credentials")) (fact "successful login returns JWS token with encrypted identity" (let [response (login-req creds) body (parse-body (:body response))] (:status response) => 200 (jwt/unsign (:token body) (env :secret)) => {:user (:username creds)}))))) (let [creds {:username "user" :password "password"} other-creds {:username "otheruser" :password "anypassword"} non-user {:username "nobody" :password "password"} version "4.20" mac "F9:EC:6C:C0:29:25"] (with-state-changes [(before :contents (do (migrate) (register-req creds) (register-req other-creds))) (after :contents (rollback-all))] (let [ping-req #(app (-> (mock/request :get (str "/api/v1/" (:username %) "/ping")) (mock/header "user-agent" "ESP8266-http-Update") (mock/header "x-esp8266-sta-mac" mac) (mock/query-string {:version version}))) nouser-ping-resp (ping-req non-user) exst-ping-resp (ping-req creds) token (-> (login-req creds) :body parse-body :token) other-token (-> (login-req other-creds) :body parse-body :token) auth-header #(mock/header % "Authorization" (str "Token " token)) other-auth-header #(mock/header % "Authorization" (str "Token " other-token))] (facts "about device management" (fact "no user equals no firmware for existing user and returning 304" (:status nouser-ping-resp) => 304 (:status exst-ping-resp) => 304) (fact "device management requires authentication" (let [resp (app (-> (mock/request :get (str "/api/v1/" (:username creds) "/devices")))) body (parse-body (:body resp))] (:status resp) => 403 (:error body) => "No access rights to this resource")) (fact "user can access his devices only" (let [resp-correct (app (-> (mock/request :get (str "/api/v1/" (:username creds) "/devices")) auth-header)) resp-wrong (app (-> (mock/request :get (str "/api/v1/" (:username creds) "/devices")) other-auth-header))] ;; note token for other user (:status resp-correct) => 200 (:status resp-wrong) => 403))))))
115020
(ns otaservice.api-test (:use midje.sweet) (:require [ring.mock.request :as mock] [cheshire.core :as cheshire] [deploy :refer :all] [buddy.sign.jwt :as jwt] [environ.core :refer [env]] [otaservice.core :refer [app]])) (defn parse-body [body] (cheshire/parse-string (slurp body) true)) (defn register-req [query] (app (-> (mock/request :post "/api/v1/register") (mock/content-type "application/json") (mock/body (cheshire/generate-string query))))) (defn login-req [query] (app (-> (mock/request :post "/api/v1/login") (mock/content-type "application/json") (mock/body (cheshire/generate-string query))))) (with-state-changes [(before :facts (migrate)) (after :facts (rollback-all))] (facts "about registration" (fact "if register with short login/pass proper error returned" (let [response (register-req {:username "tes" :password "<PASSWORD>"}) body (parse-body (:body response))] (:status response) => 400 (:error body) => {:username ["Username length must be greater than 3"] :password ["<PASSWORD>"]})) (fact "correctly filled field do not show up in error message" (let [response (register-req {:username "user" :password "<PASSWORD>"}) body (parse-body (:body response))] (:status response) => 400 (:error body) =not=> (contains {:username anything}) (:error body) => (contains {:password anything}))) (fact "successful registration returns username" (let [sameuser "user" response (register-req {:username sameuser :password "<PASSWORD>"}) body (parse-body (:body response))] (:status response) => 200 (:identity body) => sameuser)) (fact "registering with existing username returns proper code and error" (let [sameuser "user" _ (register-req {:username sameuser :password "<PASSWORD>"}) response (register-req {:username sameuser :password "<PASSWORD>"}) body (parse-body (:body response))] (:status response) => 409 (:error body) => "User already exists")))) (let [creds {:username "user" :password "<PASSWORD>"} inv-pass {:username "user" :password "<PASSWORD>"}] (with-state-changes [(before :contents (do (migrate) (register-req creds))) (after :contents (rollback-all))] (facts "about authentication" (fact "cannot login with wrong password" (let [response (login-req inv-pass) body (parse-body (:body response))] (:status response) => 401 (:error body) => "Wrong credentials")) (fact "successful login returns JWS token with encrypted identity" (let [response (login-req creds) body (parse-body (:body response))] (:status response) => 200 (jwt/unsign (:token body) (env :secret)) => {:user (:username creds)}))))) (let [creds {:username "user" :password "<PASSWORD>"} other-creds {:username "otheruser" :password "<PASSWORD>"} non-user {:username "nobody" :password "<PASSWORD>"} version "4.20" mac "F9:EC:6C:C0:29:25"] (with-state-changes [(before :contents (do (migrate) (register-req creds) (register-req other-creds))) (after :contents (rollback-all))] (let [ping-req #(app (-> (mock/request :get (str "/api/v1/" (:username %) "/ping")) (mock/header "user-agent" "ESP8266-http-Update") (mock/header "x-esp8266-sta-mac" mac) (mock/query-string {:version version}))) nouser-ping-resp (ping-req non-user) exst-ping-resp (ping-req creds) token (-> (login-req creds) :body parse-body :token) other-token (-> (login-req other-creds) :body parse-body :token) auth-header #(mock/header % "Authorization" (str "Token " token)) other-auth-header #(mock/header % "Authorization" (str "Token " other-token))] (facts "about device management" (fact "no user equals no firmware for existing user and returning 304" (:status nouser-ping-resp) => 304 (:status exst-ping-resp) => 304) (fact "device management requires authentication" (let [resp (app (-> (mock/request :get (str "/api/v1/" (:username creds) "/devices")))) body (parse-body (:body resp))] (:status resp) => 403 (:error body) => "No access rights to this resource")) (fact "user can access his devices only" (let [resp-correct (app (-> (mock/request :get (str "/api/v1/" (:username creds) "/devices")) auth-header)) resp-wrong (app (-> (mock/request :get (str "/api/v1/" (:username creds) "/devices")) other-auth-header))] ;; note token for other user (:status resp-correct) => 200 (:status resp-wrong) => 403))))))
true
(ns otaservice.api-test (:use midje.sweet) (:require [ring.mock.request :as mock] [cheshire.core :as cheshire] [deploy :refer :all] [buddy.sign.jwt :as jwt] [environ.core :refer [env]] [otaservice.core :refer [app]])) (defn parse-body [body] (cheshire/parse-string (slurp body) true)) (defn register-req [query] (app (-> (mock/request :post "/api/v1/register") (mock/content-type "application/json") (mock/body (cheshire/generate-string query))))) (defn login-req [query] (app (-> (mock/request :post "/api/v1/login") (mock/content-type "application/json") (mock/body (cheshire/generate-string query))))) (with-state-changes [(before :facts (migrate)) (after :facts (rollback-all))] (facts "about registration" (fact "if register with short login/pass proper error returned" (let [response (register-req {:username "tes" :password "PI:PASSWORD:<PASSWORD>END_PI"}) body (parse-body (:body response))] (:status response) => 400 (:error body) => {:username ["Username length must be greater than 3"] :password ["PI:PASSWORD:<PASSWORD>END_PI"]})) (fact "correctly filled field do not show up in error message" (let [response (register-req {:username "user" :password "PI:PASSWORD:<PASSWORD>END_PI"}) body (parse-body (:body response))] (:status response) => 400 (:error body) =not=> (contains {:username anything}) (:error body) => (contains {:password anything}))) (fact "successful registration returns username" (let [sameuser "user" response (register-req {:username sameuser :password "PI:PASSWORD:<PASSWORD>END_PI"}) body (parse-body (:body response))] (:status response) => 200 (:identity body) => sameuser)) (fact "registering with existing username returns proper code and error" (let [sameuser "user" _ (register-req {:username sameuser :password "PI:PASSWORD:<PASSWORD>END_PI"}) response (register-req {:username sameuser :password "PI:PASSWORD:<PASSWORD>END_PI"}) body (parse-body (:body response))] (:status response) => 409 (:error body) => "User already exists")))) (let [creds {:username "user" :password "PI:PASSWORD:<PASSWORD>END_PI"} inv-pass {:username "user" :password "PI:PASSWORD:<PASSWORD>END_PI"}] (with-state-changes [(before :contents (do (migrate) (register-req creds))) (after :contents (rollback-all))] (facts "about authentication" (fact "cannot login with wrong password" (let [response (login-req inv-pass) body (parse-body (:body response))] (:status response) => 401 (:error body) => "Wrong credentials")) (fact "successful login returns JWS token with encrypted identity" (let [response (login-req creds) body (parse-body (:body response))] (:status response) => 200 (jwt/unsign (:token body) (env :secret)) => {:user (:username creds)}))))) (let [creds {:username "user" :password "PI:PASSWORD:<PASSWORD>END_PI"} other-creds {:username "otheruser" :password "PI:PASSWORD:<PASSWORD>END_PI"} non-user {:username "nobody" :password "PI:PASSWORD:<PASSWORD>END_PI"} version "4.20" mac "F9:EC:6C:C0:29:25"] (with-state-changes [(before :contents (do (migrate) (register-req creds) (register-req other-creds))) (after :contents (rollback-all))] (let [ping-req #(app (-> (mock/request :get (str "/api/v1/" (:username %) "/ping")) (mock/header "user-agent" "ESP8266-http-Update") (mock/header "x-esp8266-sta-mac" mac) (mock/query-string {:version version}))) nouser-ping-resp (ping-req non-user) exst-ping-resp (ping-req creds) token (-> (login-req creds) :body parse-body :token) other-token (-> (login-req other-creds) :body parse-body :token) auth-header #(mock/header % "Authorization" (str "Token " token)) other-auth-header #(mock/header % "Authorization" (str "Token " other-token))] (facts "about device management" (fact "no user equals no firmware for existing user and returning 304" (:status nouser-ping-resp) => 304 (:status exst-ping-resp) => 304) (fact "device management requires authentication" (let [resp (app (-> (mock/request :get (str "/api/v1/" (:username creds) "/devices")))) body (parse-body (:body resp))] (:status resp) => 403 (:error body) => "No access rights to this resource")) (fact "user can access his devices only" (let [resp-correct (app (-> (mock/request :get (str "/api/v1/" (:username creds) "/devices")) auth-header)) resp-wrong (app (-> (mock/request :get (str "/api/v1/" (:username creds) "/devices")) other-auth-header))] ;; note token for other user (:status resp-correct) => 200 (:status resp-wrong) => 403))))))
[ { "context": "; Copyright (C) 2013-2014 Joseph Fosco. All Rights Reserved\n;\n; This program is free ", "end": 42, "score": 0.9998252987861633, "start": 30, "tag": "NAME", "value": "Joseph Fosco" } ]
data/train/clojure/72490c3cbb594cab6bd65b81da1e2096526103f6tst-players.clj
harshp8l/deep-learning-lang-detection
84
; Copyright (C) 2013-2014 Joseph Fosco. All Rights Reserved ; ; This program is free software: you can redistribute it and/or modify ; it under the terms of the GNU General Public License as published by ; the Free Software Foundation, either version 3 of the License, or ; (at your option) any later version. ; ; This program is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of ; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ; GNU General Public License for more details. ; ; You should have received a copy of the GNU General Public License ; along with this program. If not, see <http://www.gnu.org/licenses/>. ;; This fle defines an vector tst-players with 2 players (0 and 1). ;; To be used for testing. ;; Change the ns to the appropriate namespace (ns transport.melody (:require [overtone.live :refer [metronome]] [transport.behavior :refer :all] [transport.instrument :refer [select-random-instrument]] [transport.melodychar :refer :all] ) (:import transport.melodychar.MelodyChar transport.behavior.Behavior ) ) (def tst-players { 0 { :behavior (Behavior. 0.2966165302092916, 3, 0, 1) :change-follow-info-note 0 :cur-note-beat 0 :function transport.ensemble/play-melody :instrument-info (select-random-instrument) :key 0 :melody {} :melody-char (MelodyChar. 9, 4, 2, 0) :metronome (metronome 64) :mm 64 :player-id 0 :prev-note-beat 0 :scale :ionian :seg-len 19726 :seg-start 0 } 1 { :behavior (Behavior. 0.4798252752058973, 0, 0, nil) :change-follow-info-note nil :cur-note-beat 0 :function transport.ensemble/play-melody :instrument-info(select-random-instrument) :key 8 :melody {} :melody-char (MelodyChar. 1, 7, 2, 6) :metronome (metronome 94) :mm 94 :player-id 1 :prev-note-beat 0 :scale :hindu :seg-len 10565 :seg-start 0 } } )
50987
; Copyright (C) 2013-2014 <NAME>. All Rights Reserved ; ; This program is free software: you can redistribute it and/or modify ; it under the terms of the GNU General Public License as published by ; the Free Software Foundation, either version 3 of the License, or ; (at your option) any later version. ; ; This program is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of ; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ; GNU General Public License for more details. ; ; You should have received a copy of the GNU General Public License ; along with this program. If not, see <http://www.gnu.org/licenses/>. ;; This fle defines an vector tst-players with 2 players (0 and 1). ;; To be used for testing. ;; Change the ns to the appropriate namespace (ns transport.melody (:require [overtone.live :refer [metronome]] [transport.behavior :refer :all] [transport.instrument :refer [select-random-instrument]] [transport.melodychar :refer :all] ) (:import transport.melodychar.MelodyChar transport.behavior.Behavior ) ) (def tst-players { 0 { :behavior (Behavior. 0.2966165302092916, 3, 0, 1) :change-follow-info-note 0 :cur-note-beat 0 :function transport.ensemble/play-melody :instrument-info (select-random-instrument) :key 0 :melody {} :melody-char (MelodyChar. 9, 4, 2, 0) :metronome (metronome 64) :mm 64 :player-id 0 :prev-note-beat 0 :scale :ionian :seg-len 19726 :seg-start 0 } 1 { :behavior (Behavior. 0.4798252752058973, 0, 0, nil) :change-follow-info-note nil :cur-note-beat 0 :function transport.ensemble/play-melody :instrument-info(select-random-instrument) :key 8 :melody {} :melody-char (MelodyChar. 1, 7, 2, 6) :metronome (metronome 94) :mm 94 :player-id 1 :prev-note-beat 0 :scale :hindu :seg-len 10565 :seg-start 0 } } )
true
; Copyright (C) 2013-2014 PI:NAME:<NAME>END_PI. All Rights Reserved ; ; This program is free software: you can redistribute it and/or modify ; it under the terms of the GNU General Public License as published by ; the Free Software Foundation, either version 3 of the License, or ; (at your option) any later version. ; ; This program is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of ; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ; GNU General Public License for more details. ; ; You should have received a copy of the GNU General Public License ; along with this program. If not, see <http://www.gnu.org/licenses/>. ;; This fle defines an vector tst-players with 2 players (0 and 1). ;; To be used for testing. ;; Change the ns to the appropriate namespace (ns transport.melody (:require [overtone.live :refer [metronome]] [transport.behavior :refer :all] [transport.instrument :refer [select-random-instrument]] [transport.melodychar :refer :all] ) (:import transport.melodychar.MelodyChar transport.behavior.Behavior ) ) (def tst-players { 0 { :behavior (Behavior. 0.2966165302092916, 3, 0, 1) :change-follow-info-note 0 :cur-note-beat 0 :function transport.ensemble/play-melody :instrument-info (select-random-instrument) :key 0 :melody {} :melody-char (MelodyChar. 9, 4, 2, 0) :metronome (metronome 64) :mm 64 :player-id 0 :prev-note-beat 0 :scale :ionian :seg-len 19726 :seg-start 0 } 1 { :behavior (Behavior. 0.4798252752058973, 0, 0, nil) :change-follow-info-note nil :cur-note-beat 0 :function transport.ensemble/play-melody :instrument-info(select-random-instrument) :key 8 :melody {} :melody-char (MelodyChar. 1, 7, 2, 6) :metronome (metronome 94) :mm 94 :player-id 1 :prev-note-beat 0 :scale :hindu :seg-len 10565 :seg-start 0 } } )
[ { "context": "nnection\n [{:db/id :datomic.id/joe :user/name \"Joe\" :user/age 45 :user/mate :datomic.id/mary :user/f", "end": 406, "score": 0.9997115135192871, "start": 403, "tag": "NAME", "value": "Joe" }, { "context": "/mary}}\n {:db/id :datomic.id/mary :user/name \"Mary\" :user/age 33 :user/mate :datomic.id/joe :user/fr", "end": 546, "score": 0.9996727705001831, "start": 542, "tag": "NAME", "value": "Mary" }, { "context": "/sally}}\n {:db/id :datomic.id/sam :user/name \"Sam\" :user/age 15 :user/friends #{:datomic.id/sally}}", "end": 668, "score": 0.9998292922973633, "start": 665, "tag": "NAME", "value": "Sam" }, { "context": "ally}}\n {:db/id :datomic.id/sally :user/name \"Sally\" :user/age 22 :user/friends #{:datomic.id/sam :da", "end": 767, "score": 0.9997193813323975, "start": 762, "tag": "NAME", "value": "Sally" }, { "context": " joe (get-user :datomic.id/joe)\n mary (get-user :datomic.id/mary)\n sam (get-us", "end": 1585, "score": 0.9963526725769043, "start": 1581, "tag": "NAME", "value": "mary" }, { "context": "omic.id/joe)\n mary (get-user :datomic.id/mary)\n sam (get-user :datomic.id/sam)\n ", "end": 1612, "score": 0.9276576042175293, "start": 1608, "tag": "NAME", "value": "mary" }, { "context": "er :datomic.id/sally)]\n (assertions\n \"Joe is married to Mary (solution)\"\n (-> joe :u", "end": 1731, "score": 0.9958018064498901, "start": 1728, "tag": "NAME", "value": "Joe" }, { "context": "lly)]\n (assertions\n \"Joe is married to Mary (solution)\"\n (-> joe :user/mate :user/name", "end": 1750, "score": 0.9991449117660522, "start": 1746, "tag": "NAME", "value": "Mary" }, { "context": "tion)\"\n (-> joe :user/mate :user/name) => \"Mary\"\n \"Mary is friends with Sally (solution)\"\n", "end": 1810, "score": 0.9994171857833862, "start": 1806, "tag": "NAME", "value": "Mary" }, { "context": "(-> joe :user/mate :user/name) => \"Mary\"\n \"Mary is friends with Sally (solution)\"\n (->> ma", "end": 1825, "score": 0.9993159770965576, "start": 1821, "tag": "NAME", "value": "Mary" }, { "context": "user/name) => \"Mary\"\n \"Mary is friends with Sally (solution)\"\n (->> mary :user/friends (mapv", "end": 1847, "score": 0.9992796182632446, "start": 1842, "tag": "NAME", "value": "Sally" }, { "context": " (mapv :db/id) set) => #{(:db/id sally)}\n \"Joe is friends with Mary and Sam (solution)\"\n ", "end": 1944, "score": 0.9564040899276733, "start": 1941, "tag": "NAME", "value": "Joe" }, { "context": " => #{(:db/id sally)}\n \"Joe is friends with Mary and Sam (solution)\"\n (->> joe :user/friend", "end": 1965, "score": 0.9989582300186157, "start": 1961, "tag": "NAME", "value": "Mary" }, { "context": "b/id sally)}\n \"Joe is friends with Mary and Sam (solution)\"\n (->> joe :user/friends (mapv ", "end": 1973, "score": 0.9995132684707642, "start": 1970, "tag": "NAME", "value": "Sam" }, { "context": " joe :user/friends (mapv :db/id) set) => #{(:db/id mary) (:db/id sam)}\n \"Sam is 15 years old (solu", "end": 2053, "score": 0.9840004444122314, "start": 2049, "tag": "NAME", "value": "mary" }, { "context": "d) set) => #{(:db/id mary) (:db/id sam)}\n \"Sam is 15 years old (solution)\"\n (-> sam :user", "end": 2081, "score": 0.980868935585022, "start": 2078, "tag": "NAME", "value": "Sam" } ]
test/server/app/db_testing_solutions_spec.clj
pholas/untangled-devguide
43
(ns app.db-testing-solutions-spec (:require [untangled-spec.core :refer [specification provided behavior assertions]] [datomic.api :as d] [untangled.datomic.protocols :as udb] [untangled.datomic.test-helpers :as helpers :refer [with-db-fixture]])) (defn user-seed [connection] (helpers/link-and-load-seed-data connection [{:db/id :datomic.id/joe :user/name "Joe" :user/age 45 :user/mate :datomic.id/mary :user/friends #{:datomic.id/sam :datomic.id/mary}} {:db/id :datomic.id/mary :user/name "Mary" :user/age 33 :user/mate :datomic.id/joe :user/friends #{:datomic.id/sally}} {:db/id :datomic.id/sam :user/name "Sam" :user/age 15 :user/friends #{:datomic.id/sally}} {:db/id :datomic.id/sally :user/name "Sally" :user/age 22 :user/friends #{:datomic.id/sam :datomic.id/mary}}])) (defn db-fixture-defs "Given a db-fixture returns a map containing: `connection`: a connection to the fixture's db `get-id`: give it a temp-id from seeded data, and it will return the real id from seeded data" [fixture] (let [connection (udb/get-connection fixture) tempid-map (:seed-result (udb/get-info fixture)) get-id (partial get tempid-map)] {:connection connection :get-id get-id})) (specification "My Seeded Users (SOLUTION)" (with-db-fixture my-db (let [{:keys [connection get-id]} (db-fixture-defs my-db) info (udb/get-info my-db) db (d/db connection) get-user (fn [id] (some->> (get-id id) (d/entity db))) joe (get-user :datomic.id/joe) mary (get-user :datomic.id/mary) sam (get-user :datomic.id/sam) sally (get-user :datomic.id/sally)] (assertions "Joe is married to Mary (solution)" (-> joe :user/mate :user/name) => "Mary" "Mary is friends with Sally (solution)" (->> mary :user/friends (mapv :db/id) set) => #{(:db/id sally)} "Joe is friends with Mary and Sam (solution)" (->> joe :user/friends (mapv :db/id) set) => #{(:db/id mary) (:db/id sam)} "Sam is 15 years old (solution)" (-> sam :user/age) => 15)) :migrations "app.sample-migrations" :seed-fn user-seed))
42099
(ns app.db-testing-solutions-spec (:require [untangled-spec.core :refer [specification provided behavior assertions]] [datomic.api :as d] [untangled.datomic.protocols :as udb] [untangled.datomic.test-helpers :as helpers :refer [with-db-fixture]])) (defn user-seed [connection] (helpers/link-and-load-seed-data connection [{:db/id :datomic.id/joe :user/name "<NAME>" :user/age 45 :user/mate :datomic.id/mary :user/friends #{:datomic.id/sam :datomic.id/mary}} {:db/id :datomic.id/mary :user/name "<NAME>" :user/age 33 :user/mate :datomic.id/joe :user/friends #{:datomic.id/sally}} {:db/id :datomic.id/sam :user/name "<NAME>" :user/age 15 :user/friends #{:datomic.id/sally}} {:db/id :datomic.id/sally :user/name "<NAME>" :user/age 22 :user/friends #{:datomic.id/sam :datomic.id/mary}}])) (defn db-fixture-defs "Given a db-fixture returns a map containing: `connection`: a connection to the fixture's db `get-id`: give it a temp-id from seeded data, and it will return the real id from seeded data" [fixture] (let [connection (udb/get-connection fixture) tempid-map (:seed-result (udb/get-info fixture)) get-id (partial get tempid-map)] {:connection connection :get-id get-id})) (specification "My Seeded Users (SOLUTION)" (with-db-fixture my-db (let [{:keys [connection get-id]} (db-fixture-defs my-db) info (udb/get-info my-db) db (d/db connection) get-user (fn [id] (some->> (get-id id) (d/entity db))) joe (get-user :datomic.id/joe) <NAME> (get-user :datomic.id/<NAME>) sam (get-user :datomic.id/sam) sally (get-user :datomic.id/sally)] (assertions "<NAME> is married to <NAME> (solution)" (-> joe :user/mate :user/name) => "<NAME>" "<NAME> is friends with <NAME> (solution)" (->> mary :user/friends (mapv :db/id) set) => #{(:db/id sally)} "<NAME> is friends with <NAME> and <NAME> (solution)" (->> joe :user/friends (mapv :db/id) set) => #{(:db/id <NAME>) (:db/id sam)} "<NAME> is 15 years old (solution)" (-> sam :user/age) => 15)) :migrations "app.sample-migrations" :seed-fn user-seed))
true
(ns app.db-testing-solutions-spec (:require [untangled-spec.core :refer [specification provided behavior assertions]] [datomic.api :as d] [untangled.datomic.protocols :as udb] [untangled.datomic.test-helpers :as helpers :refer [with-db-fixture]])) (defn user-seed [connection] (helpers/link-and-load-seed-data connection [{:db/id :datomic.id/joe :user/name "PI:NAME:<NAME>END_PI" :user/age 45 :user/mate :datomic.id/mary :user/friends #{:datomic.id/sam :datomic.id/mary}} {:db/id :datomic.id/mary :user/name "PI:NAME:<NAME>END_PI" :user/age 33 :user/mate :datomic.id/joe :user/friends #{:datomic.id/sally}} {:db/id :datomic.id/sam :user/name "PI:NAME:<NAME>END_PI" :user/age 15 :user/friends #{:datomic.id/sally}} {:db/id :datomic.id/sally :user/name "PI:NAME:<NAME>END_PI" :user/age 22 :user/friends #{:datomic.id/sam :datomic.id/mary}}])) (defn db-fixture-defs "Given a db-fixture returns a map containing: `connection`: a connection to the fixture's db `get-id`: give it a temp-id from seeded data, and it will return the real id from seeded data" [fixture] (let [connection (udb/get-connection fixture) tempid-map (:seed-result (udb/get-info fixture)) get-id (partial get tempid-map)] {:connection connection :get-id get-id})) (specification "My Seeded Users (SOLUTION)" (with-db-fixture my-db (let [{:keys [connection get-id]} (db-fixture-defs my-db) info (udb/get-info my-db) db (d/db connection) get-user (fn [id] (some->> (get-id id) (d/entity db))) joe (get-user :datomic.id/joe) PI:NAME:<NAME>END_PI (get-user :datomic.id/PI:NAME:<NAME>END_PI) sam (get-user :datomic.id/sam) sally (get-user :datomic.id/sally)] (assertions "PI:NAME:<NAME>END_PI is married to PI:NAME:<NAME>END_PI (solution)" (-> joe :user/mate :user/name) => "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI is friends with PI:NAME:<NAME>END_PI (solution)" (->> mary :user/friends (mapv :db/id) set) => #{(:db/id sally)} "PI:NAME:<NAME>END_PI is friends with PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI (solution)" (->> joe :user/friends (mapv :db/id) set) => #{(:db/id PI:NAME:<NAME>END_PI) (:db/id sam)} "PI:NAME:<NAME>END_PI is 15 years old (solution)" (-> sam :user/age) => 15)) :migrations "app.sample-migrations" :seed-fn user-seed))
[ { "context": " LoginBodyParams\n {:user_email Str\n :password Str})\n\n(s/defschema InvoiceID\n (ring-s/field Uuid\n ", "end": 616, "score": 0.9780475497245789, "start": 613, "tag": "PASSWORD", "value": "Str" } ]
src/kulu_backend/transcriber/api.clj
vkrmis/kulu-backend
3
(ns kulu-backend.transcriber.api (:require [clj-time.coerce :as time-c] [clojure.tools.logging :as log] [kulu-backend.currencies :refer [Currency valid?] :as curr] [kulu-backend.transcriber.model :as ext] [kulu-backend.config :as cfg] [kulu-backend.models.helpers.pagination :as pagn] [ring.swagger.schema :as ring-s :only [describe]] [schema.core :as s :refer [defschema optional-key maybe pred enum Str Inst Num Uuid]])) (defschema LoggedInUser {:token Uuid}) (defschema LoginBodyParams {:user_email Str :password Str}) (s/defschema InvoiceID (ring-s/field Uuid {:description "UUID formatted string"})) (defschema Invoice "schema for Invoices at the 'web side' of things" {(optional-key :organization_id) (maybe Uuid) (optional-key :id) (maybe Uuid) (optional-key :name) (maybe Str) (optional-key :date) (maybe Inst) (optional-key :amount) (maybe Num) (optional-key :currency) (maybe Str) (optional-key :status) (maybe Str) (optional-key :remarks) (maybe Str) (optional-key :expense_type) (maybe Str) (optional-key :attachment_url) (maybe Str) (optional-key :attachment_content_type) (maybe Str) (optional-key :email) (maybe Str) (optional-key :role) (maybe Str) (optional-key :user_name) (maybe Str) (optional-key :conflict) (maybe Boolean)}) (s/defschema PaginatedInvoiceList "paginated results as well as meta data for the results" {:meta pagn/PaginationResults :items [Invoice]}) (s/defschema GetInvoicesQueryParams (merge {:user_email s/Str} pagn/PaginationParams)) (s/defschema ChangeInvoiceBodyParams { (optional-key :name) Str (optional-key :date) Inst (optional-key :amount) Num (optional-key :currency) (pred curr/valid? 'valid?) (optional-key :remarks) Str (optional-key :expense_type) Str (optional-key :email) Str (optional-key :user_name) Str (optional-key :status) Str (optional-key :conflict) Str}) ;; index page (defn- rm-private-fields "removes fields such as timestamps from the given invoice (map)" [m] (dissoc m :created-at :updated-at :storage-key :deleted :email-2 :id-2 :created-at-2 :updated-at-2 :password)) (defn index [m] {:meta (pagn/info (merge (select-keys m [:page :per-page :order :direction]) {:total-count (ext/size m)})) :items (map rm-private-fields (ext/all m))}) ;; show page (defn lookup [id] (-> (ext/lookup id) rm-private-fields)) (defn conflict? [conflict] (= conflict "true")) ;; update page (defn update [[id attrs]] (when-let [original-i (ext/lookup id)] (-> attrs (update-in [:conflict] conflict?) (update-in [:date] time-c/to-sql-date) (->> (ext/update id))) (let [new-i (lookup id)] (log/info "Updated Invoice %s from %s to %s" id original-i new-i) new-i))) ;; next/prev page (defn next-and-prev-invoices [[id params]] (ext/next-and-prev-invoices id params))
42456
(ns kulu-backend.transcriber.api (:require [clj-time.coerce :as time-c] [clojure.tools.logging :as log] [kulu-backend.currencies :refer [Currency valid?] :as curr] [kulu-backend.transcriber.model :as ext] [kulu-backend.config :as cfg] [kulu-backend.models.helpers.pagination :as pagn] [ring.swagger.schema :as ring-s :only [describe]] [schema.core :as s :refer [defschema optional-key maybe pred enum Str Inst Num Uuid]])) (defschema LoggedInUser {:token Uuid}) (defschema LoginBodyParams {:user_email Str :password <PASSWORD>}) (s/defschema InvoiceID (ring-s/field Uuid {:description "UUID formatted string"})) (defschema Invoice "schema for Invoices at the 'web side' of things" {(optional-key :organization_id) (maybe Uuid) (optional-key :id) (maybe Uuid) (optional-key :name) (maybe Str) (optional-key :date) (maybe Inst) (optional-key :amount) (maybe Num) (optional-key :currency) (maybe Str) (optional-key :status) (maybe Str) (optional-key :remarks) (maybe Str) (optional-key :expense_type) (maybe Str) (optional-key :attachment_url) (maybe Str) (optional-key :attachment_content_type) (maybe Str) (optional-key :email) (maybe Str) (optional-key :role) (maybe Str) (optional-key :user_name) (maybe Str) (optional-key :conflict) (maybe Boolean)}) (s/defschema PaginatedInvoiceList "paginated results as well as meta data for the results" {:meta pagn/PaginationResults :items [Invoice]}) (s/defschema GetInvoicesQueryParams (merge {:user_email s/Str} pagn/PaginationParams)) (s/defschema ChangeInvoiceBodyParams { (optional-key :name) Str (optional-key :date) Inst (optional-key :amount) Num (optional-key :currency) (pred curr/valid? 'valid?) (optional-key :remarks) Str (optional-key :expense_type) Str (optional-key :email) Str (optional-key :user_name) Str (optional-key :status) Str (optional-key :conflict) Str}) ;; index page (defn- rm-private-fields "removes fields such as timestamps from the given invoice (map)" [m] (dissoc m :created-at :updated-at :storage-key :deleted :email-2 :id-2 :created-at-2 :updated-at-2 :password)) (defn index [m] {:meta (pagn/info (merge (select-keys m [:page :per-page :order :direction]) {:total-count (ext/size m)})) :items (map rm-private-fields (ext/all m))}) ;; show page (defn lookup [id] (-> (ext/lookup id) rm-private-fields)) (defn conflict? [conflict] (= conflict "true")) ;; update page (defn update [[id attrs]] (when-let [original-i (ext/lookup id)] (-> attrs (update-in [:conflict] conflict?) (update-in [:date] time-c/to-sql-date) (->> (ext/update id))) (let [new-i (lookup id)] (log/info "Updated Invoice %s from %s to %s" id original-i new-i) new-i))) ;; next/prev page (defn next-and-prev-invoices [[id params]] (ext/next-and-prev-invoices id params))
true
(ns kulu-backend.transcriber.api (:require [clj-time.coerce :as time-c] [clojure.tools.logging :as log] [kulu-backend.currencies :refer [Currency valid?] :as curr] [kulu-backend.transcriber.model :as ext] [kulu-backend.config :as cfg] [kulu-backend.models.helpers.pagination :as pagn] [ring.swagger.schema :as ring-s :only [describe]] [schema.core :as s :refer [defschema optional-key maybe pred enum Str Inst Num Uuid]])) (defschema LoggedInUser {:token Uuid}) (defschema LoginBodyParams {:user_email Str :password PI:PASSWORD:<PASSWORD>END_PI}) (s/defschema InvoiceID (ring-s/field Uuid {:description "UUID formatted string"})) (defschema Invoice "schema for Invoices at the 'web side' of things" {(optional-key :organization_id) (maybe Uuid) (optional-key :id) (maybe Uuid) (optional-key :name) (maybe Str) (optional-key :date) (maybe Inst) (optional-key :amount) (maybe Num) (optional-key :currency) (maybe Str) (optional-key :status) (maybe Str) (optional-key :remarks) (maybe Str) (optional-key :expense_type) (maybe Str) (optional-key :attachment_url) (maybe Str) (optional-key :attachment_content_type) (maybe Str) (optional-key :email) (maybe Str) (optional-key :role) (maybe Str) (optional-key :user_name) (maybe Str) (optional-key :conflict) (maybe Boolean)}) (s/defschema PaginatedInvoiceList "paginated results as well as meta data for the results" {:meta pagn/PaginationResults :items [Invoice]}) (s/defschema GetInvoicesQueryParams (merge {:user_email s/Str} pagn/PaginationParams)) (s/defschema ChangeInvoiceBodyParams { (optional-key :name) Str (optional-key :date) Inst (optional-key :amount) Num (optional-key :currency) (pred curr/valid? 'valid?) (optional-key :remarks) Str (optional-key :expense_type) Str (optional-key :email) Str (optional-key :user_name) Str (optional-key :status) Str (optional-key :conflict) Str}) ;; index page (defn- rm-private-fields "removes fields such as timestamps from the given invoice (map)" [m] (dissoc m :created-at :updated-at :storage-key :deleted :email-2 :id-2 :created-at-2 :updated-at-2 :password)) (defn index [m] {:meta (pagn/info (merge (select-keys m [:page :per-page :order :direction]) {:total-count (ext/size m)})) :items (map rm-private-fields (ext/all m))}) ;; show page (defn lookup [id] (-> (ext/lookup id) rm-private-fields)) (defn conflict? [conflict] (= conflict "true")) ;; update page (defn update [[id attrs]] (when-let [original-i (ext/lookup id)] (-> attrs (update-in [:conflict] conflict?) (update-in [:date] time-c/to-sql-date) (->> (ext/update id))) (let [new-i (lookup id)] (log/info "Updated Invoice %s from %s to %s" id original-i new-i) new-i))) ;; next/prev page (defn next-and-prev-invoices [[id params]] (ext/next-and-prev-invoices id params))
[ { "context": ";;;; Copyright 2016 Peter Stephens. All Rights Reserved.\r\n;;;;\r\n;;;; Licensed unde", "end": 36, "score": 0.9997690916061401, "start": 22, "tag": "NAME", "value": "Peter Stephens" } ]
src/bible/macros.clj
pstephens/kingjames.bible
23
;;;; Copyright 2016 Peter Stephens. All Rights Reserved. ;;;; ;;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;;; you may not use this file except in compliance with the License. ;;;; You may obtain a copy of the License at ;;;; ;;;; http://www.apache.org/licenses/LICENSE-2.0 ;;;; ;;;; Unless required by applicable law or agreed to in writing, software ;;;; distributed under the License is distributed on an "AS IS" BASIS, ;;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;;; See the License for the specific language governing permissions and ;;;; limitations under the License. (ns bible.macros) ; Implemented async error handling pattern as described in http://swannodette.github.io/2013/08/31/asynchronous-error-handling/ (defmacro <? [expr] `(bible.helpers/throw-err (cljs.core.async/<! ~expr)))
91356
;;;; Copyright 2016 <NAME>. All Rights Reserved. ;;;; ;;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;;; you may not use this file except in compliance with the License. ;;;; You may obtain a copy of the License at ;;;; ;;;; http://www.apache.org/licenses/LICENSE-2.0 ;;;; ;;;; Unless required by applicable law or agreed to in writing, software ;;;; distributed under the License is distributed on an "AS IS" BASIS, ;;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;;; See the License for the specific language governing permissions and ;;;; limitations under the License. (ns bible.macros) ; Implemented async error handling pattern as described in http://swannodette.github.io/2013/08/31/asynchronous-error-handling/ (defmacro <? [expr] `(bible.helpers/throw-err (cljs.core.async/<! ~expr)))
true
;;;; Copyright 2016 PI:NAME:<NAME>END_PI. All Rights Reserved. ;;;; ;;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;;; you may not use this file except in compliance with the License. ;;;; You may obtain a copy of the License at ;;;; ;;;; http://www.apache.org/licenses/LICENSE-2.0 ;;;; ;;;; Unless required by applicable law or agreed to in writing, software ;;;; distributed under the License is distributed on an "AS IS" BASIS, ;;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;;; See the License for the specific language governing permissions and ;;;; limitations under the License. (ns bible.macros) ; Implemented async error handling pattern as described in http://swannodette.github.io/2013/08/31/asynchronous-error-handling/ (defmacro <? [expr] `(bible.helpers/throw-err (cljs.core.async/<! ~expr)))
[ { "context": "]\n [:input.input-form {:type \"text\" :name \"username\"}] \n [:br]\n \"Password:\"\n [:b", "end": 1014, "score": 0.9941949248313904, "start": 1006, "tag": "USERNAME", "value": "username" }, { "context": "\n [:br]\n [:input.input-form {:type \"password\" :name \"password\"}]\n [:br]\n [:input", "end": 1110, "score": 0.597337543964386, "start": 1102, "tag": "PASSWORD", "value": "password" }, { "context": "]\n [:input.input-form {:type \"text\" :name \"username\"}] \n [:br]\n \"Password:\"\n [:b", "end": 1453, "score": 0.9931060671806335, "start": 1445, "tag": "USERNAME", "value": "username" } ]
src/cljs/dogerain/signin.cljs
dogefordoges/dogerain
0
(ns dogerain.signin (:require [reagent.core :as r] [secretary.core :as secretary] [taoensso.sente :as sente])) ;;change this to about page, with login as left sidebar (defn info [] [:div [:h2 "Learn More:"] [:p "To learn more about dogecoin and dogecoin related projects check out these links:"] [:p [:a {:href "http://dogecoin.com/"} "Official Dogecoin Website"]] [:p [:a {:href "https://www.reddit.com/r/dogecoin/wiki/index"} "Dogecoin wiki"]] [:p [:a {:href "https://www.reddit.com/r/dogecoin/"} "r/dogecoin"]]]) (defn signin-page [state sign-in sign-up] [:div.login-page [:div.forms-section.container {:style {:height "100vh"}} [:div.top-portion.container {:style {:text-align "center" :font-size "5em"}} [:p [:big "Welcome to dogerain!"]]] [:div.login-form.container [:row [:div.col-md-2] [:div.col-md-8 [:div.spacing] [:div "Username:" [:br] [:input.input-form {:type "text" :name "username"}] [:br] "Password:" [:br] [:input.input-form {:type "password" :name "password"}] [:br] [:input {:type "submit" :value "Sign In!" :on-click (sign-in state)}] [:hr]]]]] [:div.sign-up-form.container [:row [:div.col-md-2] [:div.col-md-8 [:div.spacing] [:div "Username:" [:br] [:input.input-form {:type "text" :name "username"}] [:br] "Password:" [:br] [:input.input-form {:type "password" :name "password"}] "Password Again:" [:br] [:input.input-form {:type "password" :name "password-again"}] [:br] [:input {:type "submit" :value "Sign Up!" :on-click sign-up}] [:br]]]]]]])
93356
(ns dogerain.signin (:require [reagent.core :as r] [secretary.core :as secretary] [taoensso.sente :as sente])) ;;change this to about page, with login as left sidebar (defn info [] [:div [:h2 "Learn More:"] [:p "To learn more about dogecoin and dogecoin related projects check out these links:"] [:p [:a {:href "http://dogecoin.com/"} "Official Dogecoin Website"]] [:p [:a {:href "https://www.reddit.com/r/dogecoin/wiki/index"} "Dogecoin wiki"]] [:p [:a {:href "https://www.reddit.com/r/dogecoin/"} "r/dogecoin"]]]) (defn signin-page [state sign-in sign-up] [:div.login-page [:div.forms-section.container {:style {:height "100vh"}} [:div.top-portion.container {:style {:text-align "center" :font-size "5em"}} [:p [:big "Welcome to dogerain!"]]] [:div.login-form.container [:row [:div.col-md-2] [:div.col-md-8 [:div.spacing] [:div "Username:" [:br] [:input.input-form {:type "text" :name "username"}] [:br] "Password:" [:br] [:input.input-form {:type "<PASSWORD>" :name "password"}] [:br] [:input {:type "submit" :value "Sign In!" :on-click (sign-in state)}] [:hr]]]]] [:div.sign-up-form.container [:row [:div.col-md-2] [:div.col-md-8 [:div.spacing] [:div "Username:" [:br] [:input.input-form {:type "text" :name "username"}] [:br] "Password:" [:br] [:input.input-form {:type "password" :name "password"}] "Password Again:" [:br] [:input.input-form {:type "password" :name "password-again"}] [:br] [:input {:type "submit" :value "Sign Up!" :on-click sign-up}] [:br]]]]]]])
true
(ns dogerain.signin (:require [reagent.core :as r] [secretary.core :as secretary] [taoensso.sente :as sente])) ;;change this to about page, with login as left sidebar (defn info [] [:div [:h2 "Learn More:"] [:p "To learn more about dogecoin and dogecoin related projects check out these links:"] [:p [:a {:href "http://dogecoin.com/"} "Official Dogecoin Website"]] [:p [:a {:href "https://www.reddit.com/r/dogecoin/wiki/index"} "Dogecoin wiki"]] [:p [:a {:href "https://www.reddit.com/r/dogecoin/"} "r/dogecoin"]]]) (defn signin-page [state sign-in sign-up] [:div.login-page [:div.forms-section.container {:style {:height "100vh"}} [:div.top-portion.container {:style {:text-align "center" :font-size "5em"}} [:p [:big "Welcome to dogerain!"]]] [:div.login-form.container [:row [:div.col-md-2] [:div.col-md-8 [:div.spacing] [:div "Username:" [:br] [:input.input-form {:type "text" :name "username"}] [:br] "Password:" [:br] [:input.input-form {:type "PI:PASSWORD:<PASSWORD>END_PI" :name "password"}] [:br] [:input {:type "submit" :value "Sign In!" :on-click (sign-in state)}] [:hr]]]]] [:div.sign-up-form.container [:row [:div.col-md-2] [:div.col-md-8 [:div.spacing] [:div "Username:" [:br] [:input.input-form {:type "text" :name "username"}] [:br] "Password:" [:br] [:input.input-form {:type "password" :name "password"}] "Password Again:" [:br] [:input.input-form {:type "password" :name "password-again"}] [:br] [:input {:type "submit" :value "Sign Up!" :on-click sign-up}] [:br]]]]]]])
[ { "context": ";; Copyright © 2015-2020 Esko Luontola\n;; This software is released under the Apache Lic", "end": 38, "score": 0.9998871684074402, "start": 25, "tag": "NAME", "value": "Esko Luontola" } ]
test/territory_bro/events_test.clj
3breadt/territory-bro
2
;; Copyright © 2015-2020 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.events-test (:require [clojure.string :as str] [clojure.test :refer :all] [clojure.test.check.generators :as gen] [schema-generators.generators :as sg] [schema.core :as s] [territory-bro.events :as events] [territory-bro.test.testutil :refer [re-equals re-contains]]) (:import (clojure.lang ExceptionInfo) (java.time Instant) (java.util UUID))) (deftest enrich-events-test (let [time (Instant/now) injections {:now (constantly time)} user (UUID/randomUUID) system "some-subsystem" events [{:extra-keys :foo}]] (testing "no context (not really allowed)" (is (= [{:event/time time :extra-keys :foo}] (events/enrich-events {} injections events)))) (testing "user context" (is (= [{:event/time time :event/user user :extra-keys :foo}] (events/enrich-events {:command/user user} injections events)))) (testing "system context" (is (= [{:event/time time :event/system system :extra-keys :foo}] (events/enrich-events {:command/system system} injections events)))) (testing "user and system context (not really allowed)" (is (= [{:event/time time :event/user user :event/system system :extra-keys :foo}] (events/enrich-events {:command/system system, :command/user user} injections events)))))) (def valid-event {:event/type :congregation.event/congregation-created :event/time (Instant/now) :event/user (UUID/randomUUID) :congregation/id (UUID/randomUUID) :congregation/name "" :congregation/schema-name ""}) (def lax-event (dissoc valid-event :event/time)) (def invalid-event (dissoc valid-event :congregation/name)) (def unknown-event (assoc valid-event :event/type :foo)) (deftest sorted-keys-test (is (nil? (events/sorted-keys nil))) (is (= [:event/type :event/user :event/time :congregation/id :congregation/name :congregation/schema-name] (keys (events/sorted-keys valid-event))))) ;; TODO: deduplicate event & command validation infra (deftest event-schema-test (testing "check specific event schema" (is (nil? (s/check events/CongregationCreated valid-event)))) (testing "check generic event schema" (is (nil? (s/check events/Event valid-event)))) (testing "invalid event" (is (= {:congregation/name 'missing-required-key} (s/check events/Event invalid-event)))) (testing "unknown event type" ;; TODO: produce a helpful error message (is (s/check events/Event unknown-event)))) (deftest validate-event-test (testing "valid event" (is (= valid-event (events/validate-event valid-event)))) (testing "invalid event" (is (thrown-with-msg? ExceptionInfo (re-contains "{:congregation/name missing-required-key}") (events/validate-event invalid-event)))) (testing "basic validation accepts lax events" (is (= lax-event (events/validate-event lax-event)))) (testing "strict validation rejects lax events" (is (thrown-with-msg? ExceptionInfo (re-contains "{:event/time missing-required-key}") (events/strict-validate-event lax-event)))) (testing "unknown event type" (is (thrown-with-msg? ExceptionInfo (re-equals "Unknown event type :foo") (events/validate-event unknown-event))))) (deftest validate-events-test (testing "no events" (is (= [] (events/validate-events []) (events/strict-validate-events [])))) (testing "valid event" (is (= [valid-event] (events/validate-events [valid-event]) (events/strict-validate-events [valid-event])))) (testing "lax event" (is (= [lax-event] (events/validate-events [lax-event]))) (is (thrown? ExceptionInfo (events/strict-validate-events [lax-event])))) (testing "invalid event" (is (thrown? ExceptionInfo (events/validate-events [invalid-event]))) (is (thrown? ExceptionInfo (events/strict-validate-events [invalid-event]))))) ;;;; Generators for serialization tests (def uuid-gen (gen/fmap (fn [[a b]] (UUID. a b)) (gen/tuple gen/large-integer gen/large-integer))) (def instant-gen (gen/fmap (fn [millis] (Instant/ofEpochMilli millis)) (gen/large-integer* {:min 0}))) (def leaf-generators {UUID uuid-gen Instant instant-gen}) (def event-user-gen (gen/tuple (gen/elements [:event/user]) uuid-gen)) (def event-system-gen (gen/tuple (gen/elements [:event/system]) gen/string-alphanumeric)) (def lax-event-gen (gen/one-of (->> (vals events/event-schemas) (map #(sg/generator % leaf-generators))))) (def strict-event-gen (gen/fmap (fn [[event time [k v]]] ;; add required keys for strict validation (-> event (assoc :event/time time) (dissoc :event/user :event/system) (assoc k v))) (gen/tuple lax-event-gen instant-gen (gen/one-of [event-user-gen event-system-gen])))) (deftest ^:slow event-serialization-gen-test (testing "round trip serialization" (doseq [event (gen/sample strict-event-gen 100)] (is (= event (-> event events/event->json events/json->event)))))) (deftest event-serialization-test (testing "round trip serialization" (is (= valid-event (-> valid-event events/event->json events/json->event)))) (testing "event->json validates events" (is (thrown-with-msg? ExceptionInfo (re-equals "Unknown event type nil") (events/event->json {}))) (is (thrown-with-msg? ExceptionInfo (re-contains "Value does not match schema") (events/event->json invalid-event)))) (testing "json->event validates events" (is (thrown-with-msg? ExceptionInfo (re-contains "Value cannot be coerced to match schema") (events/json->event "{}")))) (testing "json data format" (let [event (assoc valid-event :event/time (Instant/ofEpochMilli 1)) json (events/event->json event)] (is (str/includes? json "\"event/time\":\"1970-01-01T00:00:00.001Z\"")))))
83260
;; Copyright © 2015-2020 <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.events-test (:require [clojure.string :as str] [clojure.test :refer :all] [clojure.test.check.generators :as gen] [schema-generators.generators :as sg] [schema.core :as s] [territory-bro.events :as events] [territory-bro.test.testutil :refer [re-equals re-contains]]) (:import (clojure.lang ExceptionInfo) (java.time Instant) (java.util UUID))) (deftest enrich-events-test (let [time (Instant/now) injections {:now (constantly time)} user (UUID/randomUUID) system "some-subsystem" events [{:extra-keys :foo}]] (testing "no context (not really allowed)" (is (= [{:event/time time :extra-keys :foo}] (events/enrich-events {} injections events)))) (testing "user context" (is (= [{:event/time time :event/user user :extra-keys :foo}] (events/enrich-events {:command/user user} injections events)))) (testing "system context" (is (= [{:event/time time :event/system system :extra-keys :foo}] (events/enrich-events {:command/system system} injections events)))) (testing "user and system context (not really allowed)" (is (= [{:event/time time :event/user user :event/system system :extra-keys :foo}] (events/enrich-events {:command/system system, :command/user user} injections events)))))) (def valid-event {:event/type :congregation.event/congregation-created :event/time (Instant/now) :event/user (UUID/randomUUID) :congregation/id (UUID/randomUUID) :congregation/name "" :congregation/schema-name ""}) (def lax-event (dissoc valid-event :event/time)) (def invalid-event (dissoc valid-event :congregation/name)) (def unknown-event (assoc valid-event :event/type :foo)) (deftest sorted-keys-test (is (nil? (events/sorted-keys nil))) (is (= [:event/type :event/user :event/time :congregation/id :congregation/name :congregation/schema-name] (keys (events/sorted-keys valid-event))))) ;; TODO: deduplicate event & command validation infra (deftest event-schema-test (testing "check specific event schema" (is (nil? (s/check events/CongregationCreated valid-event)))) (testing "check generic event schema" (is (nil? (s/check events/Event valid-event)))) (testing "invalid event" (is (= {:congregation/name 'missing-required-key} (s/check events/Event invalid-event)))) (testing "unknown event type" ;; TODO: produce a helpful error message (is (s/check events/Event unknown-event)))) (deftest validate-event-test (testing "valid event" (is (= valid-event (events/validate-event valid-event)))) (testing "invalid event" (is (thrown-with-msg? ExceptionInfo (re-contains "{:congregation/name missing-required-key}") (events/validate-event invalid-event)))) (testing "basic validation accepts lax events" (is (= lax-event (events/validate-event lax-event)))) (testing "strict validation rejects lax events" (is (thrown-with-msg? ExceptionInfo (re-contains "{:event/time missing-required-key}") (events/strict-validate-event lax-event)))) (testing "unknown event type" (is (thrown-with-msg? ExceptionInfo (re-equals "Unknown event type :foo") (events/validate-event unknown-event))))) (deftest validate-events-test (testing "no events" (is (= [] (events/validate-events []) (events/strict-validate-events [])))) (testing "valid event" (is (= [valid-event] (events/validate-events [valid-event]) (events/strict-validate-events [valid-event])))) (testing "lax event" (is (= [lax-event] (events/validate-events [lax-event]))) (is (thrown? ExceptionInfo (events/strict-validate-events [lax-event])))) (testing "invalid event" (is (thrown? ExceptionInfo (events/validate-events [invalid-event]))) (is (thrown? ExceptionInfo (events/strict-validate-events [invalid-event]))))) ;;;; Generators for serialization tests (def uuid-gen (gen/fmap (fn [[a b]] (UUID. a b)) (gen/tuple gen/large-integer gen/large-integer))) (def instant-gen (gen/fmap (fn [millis] (Instant/ofEpochMilli millis)) (gen/large-integer* {:min 0}))) (def leaf-generators {UUID uuid-gen Instant instant-gen}) (def event-user-gen (gen/tuple (gen/elements [:event/user]) uuid-gen)) (def event-system-gen (gen/tuple (gen/elements [:event/system]) gen/string-alphanumeric)) (def lax-event-gen (gen/one-of (->> (vals events/event-schemas) (map #(sg/generator % leaf-generators))))) (def strict-event-gen (gen/fmap (fn [[event time [k v]]] ;; add required keys for strict validation (-> event (assoc :event/time time) (dissoc :event/user :event/system) (assoc k v))) (gen/tuple lax-event-gen instant-gen (gen/one-of [event-user-gen event-system-gen])))) (deftest ^:slow event-serialization-gen-test (testing "round trip serialization" (doseq [event (gen/sample strict-event-gen 100)] (is (= event (-> event events/event->json events/json->event)))))) (deftest event-serialization-test (testing "round trip serialization" (is (= valid-event (-> valid-event events/event->json events/json->event)))) (testing "event->json validates events" (is (thrown-with-msg? ExceptionInfo (re-equals "Unknown event type nil") (events/event->json {}))) (is (thrown-with-msg? ExceptionInfo (re-contains "Value does not match schema") (events/event->json invalid-event)))) (testing "json->event validates events" (is (thrown-with-msg? ExceptionInfo (re-contains "Value cannot be coerced to match schema") (events/json->event "{}")))) (testing "json data format" (let [event (assoc valid-event :event/time (Instant/ofEpochMilli 1)) json (events/event->json event)] (is (str/includes? json "\"event/time\":\"1970-01-01T00:00:00.001Z\"")))))
true
;; Copyright © 2015-2020 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.events-test (:require [clojure.string :as str] [clojure.test :refer :all] [clojure.test.check.generators :as gen] [schema-generators.generators :as sg] [schema.core :as s] [territory-bro.events :as events] [territory-bro.test.testutil :refer [re-equals re-contains]]) (:import (clojure.lang ExceptionInfo) (java.time Instant) (java.util UUID))) (deftest enrich-events-test (let [time (Instant/now) injections {:now (constantly time)} user (UUID/randomUUID) system "some-subsystem" events [{:extra-keys :foo}]] (testing "no context (not really allowed)" (is (= [{:event/time time :extra-keys :foo}] (events/enrich-events {} injections events)))) (testing "user context" (is (= [{:event/time time :event/user user :extra-keys :foo}] (events/enrich-events {:command/user user} injections events)))) (testing "system context" (is (= [{:event/time time :event/system system :extra-keys :foo}] (events/enrich-events {:command/system system} injections events)))) (testing "user and system context (not really allowed)" (is (= [{:event/time time :event/user user :event/system system :extra-keys :foo}] (events/enrich-events {:command/system system, :command/user user} injections events)))))) (def valid-event {:event/type :congregation.event/congregation-created :event/time (Instant/now) :event/user (UUID/randomUUID) :congregation/id (UUID/randomUUID) :congregation/name "" :congregation/schema-name ""}) (def lax-event (dissoc valid-event :event/time)) (def invalid-event (dissoc valid-event :congregation/name)) (def unknown-event (assoc valid-event :event/type :foo)) (deftest sorted-keys-test (is (nil? (events/sorted-keys nil))) (is (= [:event/type :event/user :event/time :congregation/id :congregation/name :congregation/schema-name] (keys (events/sorted-keys valid-event))))) ;; TODO: deduplicate event & command validation infra (deftest event-schema-test (testing "check specific event schema" (is (nil? (s/check events/CongregationCreated valid-event)))) (testing "check generic event schema" (is (nil? (s/check events/Event valid-event)))) (testing "invalid event" (is (= {:congregation/name 'missing-required-key} (s/check events/Event invalid-event)))) (testing "unknown event type" ;; TODO: produce a helpful error message (is (s/check events/Event unknown-event)))) (deftest validate-event-test (testing "valid event" (is (= valid-event (events/validate-event valid-event)))) (testing "invalid event" (is (thrown-with-msg? ExceptionInfo (re-contains "{:congregation/name missing-required-key}") (events/validate-event invalid-event)))) (testing "basic validation accepts lax events" (is (= lax-event (events/validate-event lax-event)))) (testing "strict validation rejects lax events" (is (thrown-with-msg? ExceptionInfo (re-contains "{:event/time missing-required-key}") (events/strict-validate-event lax-event)))) (testing "unknown event type" (is (thrown-with-msg? ExceptionInfo (re-equals "Unknown event type :foo") (events/validate-event unknown-event))))) (deftest validate-events-test (testing "no events" (is (= [] (events/validate-events []) (events/strict-validate-events [])))) (testing "valid event" (is (= [valid-event] (events/validate-events [valid-event]) (events/strict-validate-events [valid-event])))) (testing "lax event" (is (= [lax-event] (events/validate-events [lax-event]))) (is (thrown? ExceptionInfo (events/strict-validate-events [lax-event])))) (testing "invalid event" (is (thrown? ExceptionInfo (events/validate-events [invalid-event]))) (is (thrown? ExceptionInfo (events/strict-validate-events [invalid-event]))))) ;;;; Generators for serialization tests (def uuid-gen (gen/fmap (fn [[a b]] (UUID. a b)) (gen/tuple gen/large-integer gen/large-integer))) (def instant-gen (gen/fmap (fn [millis] (Instant/ofEpochMilli millis)) (gen/large-integer* {:min 0}))) (def leaf-generators {UUID uuid-gen Instant instant-gen}) (def event-user-gen (gen/tuple (gen/elements [:event/user]) uuid-gen)) (def event-system-gen (gen/tuple (gen/elements [:event/system]) gen/string-alphanumeric)) (def lax-event-gen (gen/one-of (->> (vals events/event-schemas) (map #(sg/generator % leaf-generators))))) (def strict-event-gen (gen/fmap (fn [[event time [k v]]] ;; add required keys for strict validation (-> event (assoc :event/time time) (dissoc :event/user :event/system) (assoc k v))) (gen/tuple lax-event-gen instant-gen (gen/one-of [event-user-gen event-system-gen])))) (deftest ^:slow event-serialization-gen-test (testing "round trip serialization" (doseq [event (gen/sample strict-event-gen 100)] (is (= event (-> event events/event->json events/json->event)))))) (deftest event-serialization-test (testing "round trip serialization" (is (= valid-event (-> valid-event events/event->json events/json->event)))) (testing "event->json validates events" (is (thrown-with-msg? ExceptionInfo (re-equals "Unknown event type nil") (events/event->json {}))) (is (thrown-with-msg? ExceptionInfo (re-contains "Value does not match schema") (events/event->json invalid-event)))) (testing "json->event validates events" (is (thrown-with-msg? ExceptionInfo (re-contains "Value cannot be coerced to match schema") (events/json->event "{}")))) (testing "json data format" (let [event (assoc valid-event :event/time (Instant/ofEpochMilli 1)) json (events/event->json event)] (is (str/includes? json "\"event/time\":\"1970-01-01T00:00:00.001Z\"")))))
[ { "context": " :username config/db-user\n :password config/db-password})\n\n(def ds (connection/->pool HikariDataSource db", "end": 427, "score": 0.8536792993545532, "start": 409, "tag": "PASSWORD", "value": "config/db-password" } ]
src/auth_template/db.clj
cjbarre/auth-template
51
(ns auth-template.db (:require [next.jdbc :as jdbc] [next.jdbc.connection :as connection] [auth-template.config :as config] [clojure.string :as str]) (:import (com.zaxxer.hikari HikariDataSource))) (def db-spec {:dbtype "postgresql" :dbname config/db-name :host config/db-host :username config/db-user :password config/db-password}) (def ds (connection/->pool HikariDataSource db-spec)) (defn insert-user! [email password-hash] (jdbc/execute-one! ds ["INSERT INTO users (email, password_hash) VALUES (?, ?)" email password-hash])) (defn get-user-by-email [email] (jdbc/execute-one! ds ["SELECT id, email, password_hash FROM users WHERE lower(email) = ?" (str/lower-case email)])) (defn insert-email-verification! [user-id email verification-token expires-at] (jdbc/execute-one! ds ["INSERT INTO email_verifications (user_id, email, verification_token, expires_at) VALUES (?, ?, ?, ?)" user-id email verification-token expires-at])) (defn get-email-verification-by-token [token] (jdbc/execute-one! ds ["SELECT id, expires_at FROM email_verifications WHERE verification_token = ?" token])) (defn set-email-verification-to-verified! [id] (jdbc/execute-one! ds ["UPDATE email_verifications SET verified = true WHERE id = ?" id])) (defn get-email-verification-for-user [user-id email] (jdbc/execute-one! ds [" select expires_at, verified from email_verifications where user_id = ? and lower(email) = ? order by expires_at desc" user-id (clojure.string/lower-case email)])) (defn insert-session! [{:keys [user-id session-key user-agent ip-address expires-at anti-forgery-token]}] (jdbc/execute-one! ds [" INSERT INTO sessions (user_id, session_key, user_agent, ip_address, expires_at, anti_forgery_token) VALUES (?, ?, ?, ?::inet, ?, ?)" user-id session-key user-agent ip-address expires-at anti-forgery-token])) (defn get-session-data [key] (jdbc/execute-one! ds [" select s.user_id, s.user_agent, s.ip_address::text, s.anti_forgery_token, u.email from sessions s left outer join users u on (s.user_id = u.id) where session_key = ? and expires_at > now ()" key])) (defn expire-session! [session-key] (jdbc/execute-one! ds [" update sessions set expires_at = now () where session_key = ?" session-key])) (defn insert-password-reset-token! [{:keys [user-id reset-token expires-at]}] (jdbc/execute-one! ds [" INSERT INTO password_reset_tokens (user_id, reset_token, expires_at) VALUES (?, ?, ?)" user-id reset-token expires-at])) (defn get-valid-password-reset-token [token] (jdbc/execute-one! ds [" select id, user_id from password_reset_tokens where reset_token = ? and expires_at > now() and used_at is null" token])) (defn set-password-reset-token-to-used! [id] (jdbc/execute-one! ds [" update password_reset_tokens set used_at = now() where id = ?" id])) (defn invalidate-user-sessions! [user-id] (jdbc/execute-one! ds [" update sessions set expires_at = now () where user_id = ?" user-id])) (defn set-password-hash-for-user! [password-hash user-id] (jdbc/execute-one! ds [" update users set password_hash = ? where id = ?" password-hash user-id]))
67227
(ns auth-template.db (:require [next.jdbc :as jdbc] [next.jdbc.connection :as connection] [auth-template.config :as config] [clojure.string :as str]) (:import (com.zaxxer.hikari HikariDataSource))) (def db-spec {:dbtype "postgresql" :dbname config/db-name :host config/db-host :username config/db-user :password <PASSWORD>}) (def ds (connection/->pool HikariDataSource db-spec)) (defn insert-user! [email password-hash] (jdbc/execute-one! ds ["INSERT INTO users (email, password_hash) VALUES (?, ?)" email password-hash])) (defn get-user-by-email [email] (jdbc/execute-one! ds ["SELECT id, email, password_hash FROM users WHERE lower(email) = ?" (str/lower-case email)])) (defn insert-email-verification! [user-id email verification-token expires-at] (jdbc/execute-one! ds ["INSERT INTO email_verifications (user_id, email, verification_token, expires_at) VALUES (?, ?, ?, ?)" user-id email verification-token expires-at])) (defn get-email-verification-by-token [token] (jdbc/execute-one! ds ["SELECT id, expires_at FROM email_verifications WHERE verification_token = ?" token])) (defn set-email-verification-to-verified! [id] (jdbc/execute-one! ds ["UPDATE email_verifications SET verified = true WHERE id = ?" id])) (defn get-email-verification-for-user [user-id email] (jdbc/execute-one! ds [" select expires_at, verified from email_verifications where user_id = ? and lower(email) = ? order by expires_at desc" user-id (clojure.string/lower-case email)])) (defn insert-session! [{:keys [user-id session-key user-agent ip-address expires-at anti-forgery-token]}] (jdbc/execute-one! ds [" INSERT INTO sessions (user_id, session_key, user_agent, ip_address, expires_at, anti_forgery_token) VALUES (?, ?, ?, ?::inet, ?, ?)" user-id session-key user-agent ip-address expires-at anti-forgery-token])) (defn get-session-data [key] (jdbc/execute-one! ds [" select s.user_id, s.user_agent, s.ip_address::text, s.anti_forgery_token, u.email from sessions s left outer join users u on (s.user_id = u.id) where session_key = ? and expires_at > now ()" key])) (defn expire-session! [session-key] (jdbc/execute-one! ds [" update sessions set expires_at = now () where session_key = ?" session-key])) (defn insert-password-reset-token! [{:keys [user-id reset-token expires-at]}] (jdbc/execute-one! ds [" INSERT INTO password_reset_tokens (user_id, reset_token, expires_at) VALUES (?, ?, ?)" user-id reset-token expires-at])) (defn get-valid-password-reset-token [token] (jdbc/execute-one! ds [" select id, user_id from password_reset_tokens where reset_token = ? and expires_at > now() and used_at is null" token])) (defn set-password-reset-token-to-used! [id] (jdbc/execute-one! ds [" update password_reset_tokens set used_at = now() where id = ?" id])) (defn invalidate-user-sessions! [user-id] (jdbc/execute-one! ds [" update sessions set expires_at = now () where user_id = ?" user-id])) (defn set-password-hash-for-user! [password-hash user-id] (jdbc/execute-one! ds [" update users set password_hash = ? where id = ?" password-hash user-id]))
true
(ns auth-template.db (:require [next.jdbc :as jdbc] [next.jdbc.connection :as connection] [auth-template.config :as config] [clojure.string :as str]) (:import (com.zaxxer.hikari HikariDataSource))) (def db-spec {:dbtype "postgresql" :dbname config/db-name :host config/db-host :username config/db-user :password PI:PASSWORD:<PASSWORD>END_PI}) (def ds (connection/->pool HikariDataSource db-spec)) (defn insert-user! [email password-hash] (jdbc/execute-one! ds ["INSERT INTO users (email, password_hash) VALUES (?, ?)" email password-hash])) (defn get-user-by-email [email] (jdbc/execute-one! ds ["SELECT id, email, password_hash FROM users WHERE lower(email) = ?" (str/lower-case email)])) (defn insert-email-verification! [user-id email verification-token expires-at] (jdbc/execute-one! ds ["INSERT INTO email_verifications (user_id, email, verification_token, expires_at) VALUES (?, ?, ?, ?)" user-id email verification-token expires-at])) (defn get-email-verification-by-token [token] (jdbc/execute-one! ds ["SELECT id, expires_at FROM email_verifications WHERE verification_token = ?" token])) (defn set-email-verification-to-verified! [id] (jdbc/execute-one! ds ["UPDATE email_verifications SET verified = true WHERE id = ?" id])) (defn get-email-verification-for-user [user-id email] (jdbc/execute-one! ds [" select expires_at, verified from email_verifications where user_id = ? and lower(email) = ? order by expires_at desc" user-id (clojure.string/lower-case email)])) (defn insert-session! [{:keys [user-id session-key user-agent ip-address expires-at anti-forgery-token]}] (jdbc/execute-one! ds [" INSERT INTO sessions (user_id, session_key, user_agent, ip_address, expires_at, anti_forgery_token) VALUES (?, ?, ?, ?::inet, ?, ?)" user-id session-key user-agent ip-address expires-at anti-forgery-token])) (defn get-session-data [key] (jdbc/execute-one! ds [" select s.user_id, s.user_agent, s.ip_address::text, s.anti_forgery_token, u.email from sessions s left outer join users u on (s.user_id = u.id) where session_key = ? and expires_at > now ()" key])) (defn expire-session! [session-key] (jdbc/execute-one! ds [" update sessions set expires_at = now () where session_key = ?" session-key])) (defn insert-password-reset-token! [{:keys [user-id reset-token expires-at]}] (jdbc/execute-one! ds [" INSERT INTO password_reset_tokens (user_id, reset_token, expires_at) VALUES (?, ?, ?)" user-id reset-token expires-at])) (defn get-valid-password-reset-token [token] (jdbc/execute-one! ds [" select id, user_id from password_reset_tokens where reset_token = ? and expires_at > now() and used_at is null" token])) (defn set-password-reset-token-to-used! [id] (jdbc/execute-one! ds [" update password_reset_tokens set used_at = now() where id = ?" id])) (defn invalidate-user-sessions! [user-id] (jdbc/execute-one! ds [" update sessions set expires_at = now () where user_id = ?" user-id])) (defn set-password-hash-for-user! [password-hash user-id] (jdbc/execute-one! ds [" update users set password_hash = ? where id = ?" password-hash user-id]))
[ { "context": "; Copyright 2016 David O'Meara\n;\n; Licensed under the Apache License, Version 2.", "end": 30, "score": 0.9998507499694824, "start": 17, "tag": "NAME", "value": "David O'Meara" } ]
src-clr/core/main.clj
davidomeara/fnedit
0
; Copyright 2016 David O'Meara ; ; 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. (assembly-load-with-partial-name "System.Windows.Forms") (assembly-load-with-partial-name "CefSharp") (assembly-load-with-partial-name "CefSharp.Core") (assembly-load-with-partial-name "CefSharp.WinForms") (ns core.main (:gen-class :name "FnEdit") (:require [core.clojure-clr-wrapper :refer (->Wrapper)]) (:import (System.IO Path) (System.Drawing Size Icon) (System.Reflection Assembly) (System.Threading Thread ThreadStart ApartmentState) (System.Windows.Forms Application Form FormStartPosition DialogResult DockStyle) (CefSharp Cef CefSettings LogSeverity) (CefSharp.WinForms ChromiumWebBrowser))) (defn as [x t] (when (= (type x) t) x)) (defn on-init [browser debug?] (gen-delegate Action [] (.RegisterJsObject browser "clr" (->Wrapper browser debug?) true) (when debug? (.ShowDevTools browser)))) (defn init-delegate [debug?] (gen-delegate |System.EventHandler`1[CefSharp.IsBrowserInitializedChangedEventArgs]| [sender e] (let [browser (as sender ChromiumWebBrowser)] (when (and (.IsBrowserInitialized e) (not (= browser nil))) (.BeginInvoke browser (on-init browser debug?)))))) (defn exe-dir [] (-> (Assembly/GetEntryAssembly) .get_Location Path/GetDirectoryName (str "/"))) (defn index-path [folder?] (str "file:///" (Path/GetFullPath (str (exe-dir) (if folder? "../cljs/" "") "index.html")))) (defn browser [debug? folder?] (doto (ChromiumWebBrowser. (index-path folder?)) (.set_Dock DockStyle/Fill) (.add_IsBrowserInitializedChanged (init-delegate debug?)))) (defn focus-handler [browser] (gen-delegate |System.EventHandler| [sender e] (.SetFocus browser true))) (defn form [folder? browser] (doto (Form.) (.set_Icon (Icon. (Path/GetFullPath (str (exe-dir) (if folder? "../cljs/" "") "fn.ico")))) (.set_StartPosition FormStartPosition/CenterScreen) (.set_MinimumSize (Size. 600 400)) (.set_Size (Size. 800 600)) (#(.Add (.get_Controls %) browser)) (.add_Activated (focus-handler browser)))) (defn sta-thread [f] (let [^ThreadStart thread-start (gen-delegate ThreadStart [] (f))] (doto (Thread. thread-start) (.SetApartmentState ApartmentState/STA) .Start .Join))) ;https://code.google.com/p/chromium/issues/detail?id=372596 (defn cef-settings [] (let [settings (CefSettings.)] (-> settings .get_CefCommandLineArgs (.Add "disable-gpu" "1")) settings)) (defn -main [& args] (sta-thread (fn [] (Cef/Initialize (cef-settings)) (let [debug? (boolean (some #{"-d"} args)) folder? (boolean (some #{"-f"} args)) browser (browser debug? folder?)] (.ShowDialog (form folder? browser)) (.Dispose browser) (Cef/Shutdown) (shutdown-agents)))))
120616
; Copyright 2016 <NAME> ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (assembly-load-with-partial-name "System.Windows.Forms") (assembly-load-with-partial-name "CefSharp") (assembly-load-with-partial-name "CefSharp.Core") (assembly-load-with-partial-name "CefSharp.WinForms") (ns core.main (:gen-class :name "FnEdit") (:require [core.clojure-clr-wrapper :refer (->Wrapper)]) (:import (System.IO Path) (System.Drawing Size Icon) (System.Reflection Assembly) (System.Threading Thread ThreadStart ApartmentState) (System.Windows.Forms Application Form FormStartPosition DialogResult DockStyle) (CefSharp Cef CefSettings LogSeverity) (CefSharp.WinForms ChromiumWebBrowser))) (defn as [x t] (when (= (type x) t) x)) (defn on-init [browser debug?] (gen-delegate Action [] (.RegisterJsObject browser "clr" (->Wrapper browser debug?) true) (when debug? (.ShowDevTools browser)))) (defn init-delegate [debug?] (gen-delegate |System.EventHandler`1[CefSharp.IsBrowserInitializedChangedEventArgs]| [sender e] (let [browser (as sender ChromiumWebBrowser)] (when (and (.IsBrowserInitialized e) (not (= browser nil))) (.BeginInvoke browser (on-init browser debug?)))))) (defn exe-dir [] (-> (Assembly/GetEntryAssembly) .get_Location Path/GetDirectoryName (str "/"))) (defn index-path [folder?] (str "file:///" (Path/GetFullPath (str (exe-dir) (if folder? "../cljs/" "") "index.html")))) (defn browser [debug? folder?] (doto (ChromiumWebBrowser. (index-path folder?)) (.set_Dock DockStyle/Fill) (.add_IsBrowserInitializedChanged (init-delegate debug?)))) (defn focus-handler [browser] (gen-delegate |System.EventHandler| [sender e] (.SetFocus browser true))) (defn form [folder? browser] (doto (Form.) (.set_Icon (Icon. (Path/GetFullPath (str (exe-dir) (if folder? "../cljs/" "") "fn.ico")))) (.set_StartPosition FormStartPosition/CenterScreen) (.set_MinimumSize (Size. 600 400)) (.set_Size (Size. 800 600)) (#(.Add (.get_Controls %) browser)) (.add_Activated (focus-handler browser)))) (defn sta-thread [f] (let [^ThreadStart thread-start (gen-delegate ThreadStart [] (f))] (doto (Thread. thread-start) (.SetApartmentState ApartmentState/STA) .Start .Join))) ;https://code.google.com/p/chromium/issues/detail?id=372596 (defn cef-settings [] (let [settings (CefSettings.)] (-> settings .get_CefCommandLineArgs (.Add "disable-gpu" "1")) settings)) (defn -main [& args] (sta-thread (fn [] (Cef/Initialize (cef-settings)) (let [debug? (boolean (some #{"-d"} args)) folder? (boolean (some #{"-f"} args)) browser (browser debug? folder?)] (.ShowDialog (form folder? browser)) (.Dispose browser) (Cef/Shutdown) (shutdown-agents)))))
true
; Copyright 2016 PI:NAME:<NAME>END_PI ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (assembly-load-with-partial-name "System.Windows.Forms") (assembly-load-with-partial-name "CefSharp") (assembly-load-with-partial-name "CefSharp.Core") (assembly-load-with-partial-name "CefSharp.WinForms") (ns core.main (:gen-class :name "FnEdit") (:require [core.clojure-clr-wrapper :refer (->Wrapper)]) (:import (System.IO Path) (System.Drawing Size Icon) (System.Reflection Assembly) (System.Threading Thread ThreadStart ApartmentState) (System.Windows.Forms Application Form FormStartPosition DialogResult DockStyle) (CefSharp Cef CefSettings LogSeverity) (CefSharp.WinForms ChromiumWebBrowser))) (defn as [x t] (when (= (type x) t) x)) (defn on-init [browser debug?] (gen-delegate Action [] (.RegisterJsObject browser "clr" (->Wrapper browser debug?) true) (when debug? (.ShowDevTools browser)))) (defn init-delegate [debug?] (gen-delegate |System.EventHandler`1[CefSharp.IsBrowserInitializedChangedEventArgs]| [sender e] (let [browser (as sender ChromiumWebBrowser)] (when (and (.IsBrowserInitialized e) (not (= browser nil))) (.BeginInvoke browser (on-init browser debug?)))))) (defn exe-dir [] (-> (Assembly/GetEntryAssembly) .get_Location Path/GetDirectoryName (str "/"))) (defn index-path [folder?] (str "file:///" (Path/GetFullPath (str (exe-dir) (if folder? "../cljs/" "") "index.html")))) (defn browser [debug? folder?] (doto (ChromiumWebBrowser. (index-path folder?)) (.set_Dock DockStyle/Fill) (.add_IsBrowserInitializedChanged (init-delegate debug?)))) (defn focus-handler [browser] (gen-delegate |System.EventHandler| [sender e] (.SetFocus browser true))) (defn form [folder? browser] (doto (Form.) (.set_Icon (Icon. (Path/GetFullPath (str (exe-dir) (if folder? "../cljs/" "") "fn.ico")))) (.set_StartPosition FormStartPosition/CenterScreen) (.set_MinimumSize (Size. 600 400)) (.set_Size (Size. 800 600)) (#(.Add (.get_Controls %) browser)) (.add_Activated (focus-handler browser)))) (defn sta-thread [f] (let [^ThreadStart thread-start (gen-delegate ThreadStart [] (f))] (doto (Thread. thread-start) (.SetApartmentState ApartmentState/STA) .Start .Join))) ;https://code.google.com/p/chromium/issues/detail?id=372596 (defn cef-settings [] (let [settings (CefSettings.)] (-> settings .get_CefCommandLineArgs (.Add "disable-gpu" "1")) settings)) (defn -main [& args] (sta-thread (fn [] (Cef/Initialize (cef-settings)) (let [debug? (boolean (some #{"-d"} args)) folder? (boolean (some #{"-f"} args)) browser (browser debug? folder?)] (.ShowDialog (form folder? browser)) (.Dispose browser) (Cef/Shutdown) (shutdown-agents)))))
[ { "context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"John Alan McDonald\" \n :date \"2017-10-21\"\n :doc \"Eager vers", "end": 105, "score": 0.9998669028282166, "start": 87, "tag": "NAME", "value": "John Alan McDonald" } ]
src/main/clojure/zana/collections/guava.clj
wahpenayo/zana
2
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "John Alan McDonald" :date "2017-10-21" :doc "Eager versions of filter, map, reduce, etc." } zana.collections.guava (:refer-clojure :exclude [any? compare concat count doall drop empty? every? filter first list map map-indexed mapcat next nth pmap remove repeatedly second shuffle some sort sort-by split-at take]) (:require [clojure.pprint :as pp] [zana.commons.core :as cc] [zana.collections.generic :as g]) (:import [com.google.common.base Function Predicate] [com.google.common.collect ImmutableList Iterables Iterators Multimap Ordering Sets Table] [com.google.common.primitives Doubles] [clojure.lang IFn] [java.util ArrayList Collection Collections HashMap IdentityHashMap Iterator List Map Set] [java.util.concurrent Executors Future])) ;;------------------------------------------------------------------------------ ;; TODO: rename to zana.collections.eager ;; TODO: break up into list, map, set, table, ..., namespaces ;; TODO: ImmutableList vs Collections/unmodifiableList performance issues. ;;------------------------------------------------------------------------------ (defn function ^com.google.common.base.Function [f] (cond (instance? Function f) f (ifn? f) (reify Function (apply [this x] (f x))) :else (throw (IllegalArgumentException. (print-str "Not a function:" f))))) ;;------------------------------------------------------------------------------ (defn predicate ^com.google.common.base.Predicate [f] (cond (instance? Predicate f) f (ifn? f)(reify Predicate (apply [this x] (boolean (f x)))) :else (throw (IllegalArgumentException. (print-str "Not a function:" f))))) ;;------------------------------------------------------------------------------ ;; ImmutableList ;;------------------------------------------------------------------------------ (defn nth [things ^long i] (assert things (str "No things to fetch " i "th element from.")) (cond (instance? List things) (.get ^List things (int i)) (instance? Iterator things) (let [^Iterator things things i (int i)] (loop [ii (int 0)] (when (g/has-next? things) (let [x (g/next-item things)] (if (== ii i) x (recur (inc ii))))))) :else (nth (g/iterator things) i))) ;;------------------------------------------------------------------------------ ;; A misleading name here! (defn ^:no-doc doall "Add all the </code>things</code> to a new immutable list." [things] (let [b (ArrayList.)] (.addAll b things) (Collections/unmodifiableList b))) ;;------------------------------------------------------------------------------ (defn #^:no-doc list "Coerce <code>x</code> to an immutable list, if possible. Throw an exception if not." ^java.util.List [x] (cond (nil? x) (ImmutableList/of) (instance? List x) x ;; should we copy to immutable list here? (instance? Collection x) (ImmutableList/copyOf ^Collection x) (instance? Iterable x) (ImmutableList/copyOf ^Iterable x) (instance? Iterator x) (ImmutableList/copyOf ^Iterator x) (cc/object-array? x) (ImmutableList/copyOf ^objects x) :else (throw (UnsupportedOperationException. (str "can't List-ify: " x))))) ;;------------------------------------------------------------------------------ (defn any? "Does <code>f</code> return a <a href=\"http://blog.jayfields.com/2011/02/clojure-truthy-and-falsey.html\">truthy</a> value for any element of <code>things</code>?<br> Returns <code>true</code> or <code>false</code>." [f things] (assert (ifn? f) (print-str "Not a function:" f)) (let [it (g/iterator things)] (loop [] (cond (not (g/has-next? it)) false (f (g/next-item it)) true :else (recur))))) ;;------------------------------------------------------------------------------ (defn some "Does <code>f</code> return a <a href=\"http://blog.jayfields.com/2011/02/clojure-truthy-and-falsey.html\">truthy</a> value for any element of <code>things</code><br> Returns the truthy value or </code>nil</code>." [f things] (assert (ifn? f) (print-str "Not a function:" f)) (let [it (g/iterator things)] (loop [] (if-not (g/has-next? it) nil (let [fi (f (g/next-item it))] (if fi fi (recur))))))) ;;------------------------------------------------------------------------------ (defn repeatedly "Call <code>f</code>, with no arguments, <code>n</code> times, accumulating the results in an <a href=\"https://docs.oracle.com/javase/8/docs/api/index.html?java/lang/Iterable.html\"> Iterable</a>." ^Iterable [^long n f] (assert (ifn? f) (print-str "Not a function:" f)) (let [b (ArrayList. n)] (dotimes [i n] (.add b (f))) (Collections/unmodifiableList b))) ;;------------------------------------------------------------------------------ (defn take "Return an <a href=\"https://docs.oracle.com/javase/8/docs/api/index.html?java/lang/Iterable.html\"> Iterable</a> over the first <code>n</code> elements of <code>things</code>." ^Iterable [^long n things] (let [b (ArrayList. n) it (g/iterator things)] (loop [i 0] (when (and (< i n) (g/has-next? it)) (g/add! b (g/next-item it)) (recur (inc i)))) (Collections/unmodifiableList b))) ;;------------------------------------------------------------------------------ (defn drop "Return an <a href=\"https://docs.oracle.com/javase/8/docs/api/index.html?java/lang/Iterable.html\"> Iterable</a> that skips the first <code>n</code> elements of <code>things</code>." ^Iterable [^long n things] (let [b (ArrayList. n) it (g/iterator things)] (loop [i 0] (when (and (< i n) (g/has-next? it)) (g/next-item it) (recur (inc i)))) (while (g/has-next? it) (g/add! b (g/next-item it))) (Collections/unmodifiableList b))) ;;------------------------------------------------------------------------------ (defn split-at "Returns equivalent of <code>[(take n things) (drop n things)]</code>, see [[take]] and [[drop]]." ^Iterable [^long n things] (let [b0 (ArrayList. n) b1 (ArrayList. n) it (g/iterator things)] (loop [i 0] (when (and (< i n) (g/has-next? it)) (g/add! b0 (g/next-item it)) (recur (inc i)))) (while (g/has-next? it) (g/add! b1 (g/next-item it))) [(Collections/unmodifiableList b0) (Collections/unmodifiableList b1)])) ;;------------------------------------------------------------------------------ #_(defn lazy-filter ^Iterable [f ^Iterable things] (assert (ifn? f) (print-str "Not a function:" f)) (Iterables/filter things (predicate f))) ;;------------------------------------------------------------------------------ (defn remove "Like <code>(filter #(not (f %)) things)</code>." ^Iterable [f things] (assert (ifn? f) (print-str "Not a function:" f)) (g/filter #(not (f %)) things)) ;;------------------------------------------------------------------------------ (defn not-nil "Like <code>(filter #(not (nil? %)) things)</code>." ^Iterable [things] (let [b (ArrayList. (g/count things)) it (g/iterator things)] (while (g/has-next? it) (when-let [thing (g/next-item it)] (g/add! b thing))) (Collections/unmodifiableList b))) ;;------------------------------------------------------------------------------ #_(defn split-by "Like [[group-by[[, but truthy vs non-truthy, and returns a pair of Iterables." [f things] (assert (ifn? f) (print-str "Not a function:" f)) (let [n (g/count things) bt (ArrayList. n) bf (ArrayList. n) it (g/iterator things)] (while (g/has-next? it) (let [thing (g/next-item it)] (if (f thing) (g/add! bt thing) (g/add! bf thing)))) [(Collections/unmodifiableList bt) (Collections/unmodifiableList bf)])) ;;------------------------------------------------------------------------------ (defn- map-indexed-collection (^Iterable [f ^java.util.Collection things] (assert (ifn? f) (print-str "Not a function:" f)) (let [b (ArrayList. (g/count things)) it (g/iterator things)] (loop [i (int 0)] (when (g/has-next? it) (let [nxt (g/next-item it)] (try (g/add! b (f nxt i)) (catch Throwable t (println "map failed:" f nxt (f i nxt)) (.printStackTrace t) (throw t)))) (recur (inc i)))) (Collections/unmodifiableList b))) (^Iterable [f ^java.util.Collection things0 ^java.util.Collection things1] (assert (ifn? f) (print-str "Not a function:" f)) (let [b (ArrayList. (max (g/count things0) (g/count things1))) it0 (g/iterator things0) it1 (g/iterator things1)] (loop [i (int 0)] (when (and (g/has-next? it0) (g/has-next? it1)) (g/add! b (f i (g/next-item it0) (g/next-item it1))) (recur (inc i)))) (Collections/unmodifiableList b)))) ;;------------------------------------------------------------------------------ (defn- map-indexed-iterable (^Iterable [f things] (assert (ifn? f) (print-str "Not a function:" f)) (let [b (ArrayList.) it (g/iterator things)] (loop [i (int 0)] (when (g/has-next? it) (let [nxt (g/next-item it)] (try (.add b (f nxt i)) (catch Throwable t (println "map failed:" f nxt (f i nxt)) (.printStackTrace t) (throw t)))) (recur (inc i)))) (Collections/unmodifiableList b))) (^Iterable [f things0 things1] (assert (ifn? f) (print-str "Not a function:" f)) (let [b (ArrayList.) it0 (g/iterator things0) it1 (g/iterator things1)] (loop [i (int 0)] (when (and (g/has-next? it0) (g/has-next? it1)) (.add b (f i (g/next-item it0) (g/next-item it1))) (recur (inc i)))) (Collections/unmodifiableList b)))) ;;------------------------------------------------------------------------------ (defn map-indexed "Faster, eager, more general version of <code>clojure.core/map-indexed</code>." (^Iterable [f things] (assert (ifn? f) (print-str "Not a function:" f)) (cond (instance? java.util.Collection things) (map-indexed-collection f things) :else (map-indexed-iterable f things))) (^Iterable [f things0 things1] (assert (ifn? f) (print-str "Not a function:" f)) (cond (and (instance? java.util.Collection things0) (instance? java.util.Collection things1)) (map-indexed-collection f things0 things1) :else (map-indexed-iterable f things0 things1)))) ;;------------------------------------------------------------------------------ (defn filter-map "Like <code>(filter p (map f things))</code>." ^java.util.List [p f things] (assert (ifn? p) (print-str "Not a function:" p)) (assert (ifn? f) (print-str "Not a function:" f)) (let [b (ArrayList. (g/count things)) it (g/iterator things)] (while (g/has-next? it) (let [thing (f (g/next-item it))] (when (p thing) (g/add! b thing)))) (Collections/unmodifiableList b))) ;;------------------------------------------------------------------------------ (defn keep-map "Like <code>(keep identity (map f things))</code>." ^java.util.List [f things] (assert (ifn? f) (print-str "Not a function:" f)) (let [b (ArrayList. (g/count things)) it (g/iterator things)] (while (g/has-next? it) (when-let [fi (f (g/next-item it))] (g/add! b fi))) (Collections/unmodifiableList b))) ;;------------------------------------------------------------------------------ ;; Looks like clojure functions are both Callable and Runnable, ;; and ExecutorService treats them as Runnable (no return value). #_(defn- callable (^java.util.concurrent.Callable [f x] (assert (ifn? f) (print-str "Not a function:" f)) (reify java.util.concurrent.Callable (call [this] (f x)))) (^java.util.concurrent.Callable [f x0 x1] (assert (ifn? f) (print-str "Not a function:" f)) (reify java.util.concurrent.Callable (call [this] (f x0 x1)))) (^java.util.concurrent.Callable [f x0 x1 x2] (assert (ifn? f) (print-str "Not a function:" f)) (reify java.util.concurrent.Callable (call [this] (f x0 x1 x2)))) (^java.util.concurrent.Callable [f x0 x1 x2 & args] (assert (ifn? f) (print-str "Not a function:" f)) (reify java.util.concurrent.Callable (call [this] (apply f x0 x1 x2 args))))) ;;------------------------------------------------------------------------------ #_(defn nmap "Eager version of <code>clojure.core/pmap</code> that uses <code>n</code> threads." (^Iterable [n f things] (assert (ifn? f) (print-str "Not a function:" f)) (let [pool (Executors/newFixedThreadPool (int n)) tasks (mapv #(callable f %) things) b (ArrayList. (g/count things))] (try (doseq [^Future future (.invokeAll pool tasks)] (let [v (.get future)] (g/add! b v))) (finally (.shutdown pool))) ;;(.build b))) (Collections/unmodifiableList b))) (^Iterable [n f things0 things1] (assert (ifn? f) (print-str "Not a function:" f)) (let [pool (Executors/newFixedThreadPool (int n)) tasks (mapv (fn [x0 x1] (callable f x0 x1)) things0 things1) b (ArrayList.)] (try (doseq [^Future future (.invokeAll pool tasks)] (.add b (.get future))) (finally (.shutdown pool))) (Collections/unmodifiableList b))) (^Iterable [n f things0 things1 things2] (assert (ifn? f) (print-str "Not a function:" f)) (let [pool (Executors/newFixedThreadPool (int n)) tasks (mapv (fn [x0 x1 x2] (callable f x0 x1 x2)) things0 things1 things2) b (ArrayList.)] (try (doseq [^Future future (.invokeAll pool tasks)] (.add b (.get future))) (finally (.shutdown pool))) (Collections/unmodifiableList b)))) ;;------------------------------------------------------------------------------ #_(defn pmap "Eager version of <code>clojure.core/pmap</code> that uses as many threads as there are <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/Runtime.html#availableProcessors--\"> available processors." (^Iterable [f things] (assert (ifn? f) (print-str "Not a function:" f)) (nmap (.availableProcessors (Runtime/getRuntime)) f things)) (^Iterable [f things0 things1] (assert (ifn? f) (print-str "Not a function:" f)) (nmap (.availableProcessors (Runtime/getRuntime)) f things0 things1)) (^Iterable [f things0 things1 things2] (assert (ifn? f) (print-str "Not a function:" f)) (nmap (.availableProcessors (Runtime/getRuntime)) f things0 things1 things2))) ;;------------------------------------------------------------------------------ #_(defn nmap-indexed "A combination of [[nmap]] and [[map-indexed]]." (^Iterable [^long n f things] (assert (ifn? f) (print-str "Not a function:" f)) (let [pool (Executors/newFixedThreadPool (int n)) nthings (g/count things) tasks (map-indexed (fn [i x] (callable f i x)) things) b (ArrayList. nthings)] (try (doseq [^Future future (.invokeAll pool tasks)] (let [v (.get future)] (.add b v))) (finally (.shutdown pool))) (Collections/unmodifiableList b))) (^Iterable [^long n f things0 things1] (assert (ifn? f) (print-str "Not a function:" f)) (let [pool (Executors/newFixedThreadPool (int n)) tasks (map-indexed (fn [i x0 x1] (callable f i x0 x1)) things0 things1) b (ArrayList.)] (try (doseq [^Future future (.invokeAll pool tasks)] (.add b (.get future))) (finally (.shutdown pool))) (Collections/unmodifiableList b))) (^Iterable [n f things0 things1 things2] (assert (ifn? f) (print-str "Not a function:" f)) (let [pool (Executors/newFixedThreadPool (int n)) tasks (map-indexed (fn [i x0 x1 x2] (callable f i x0 x1 x2)) things0 things1 things2) b (ArrayList.)] (try (doseq [^Future future (.invokeAll pool tasks)] (.add b (.get future))) (finally (.shutdown pool))) (Collections/unmodifiableList b)))) ;;------------------------------------------------------------------------------ #_(defn pmap-indexed "A combination of [[pmap]] and [[map-indexed]]." (^Iterable [f things] (assert (ifn? f) (print-str "Not a function:" f)) (nmap-indexed (.availableProcessors (Runtime/getRuntime)) f things)) (^Iterable [f things0 things1] (assert (ifn? f) (print-str "Not a function:" f)) (nmap-indexed (.availableProcessors (Runtime/getRuntime)) f things0 things1)) (^Iterable [f things0 things1 things2] (assert (ifn? f) (print-str "Not a function:" f)) (nmap-indexed (.availableProcessors (Runtime/getRuntime)) f things0 things1 things2))) ;;------------------------------------------------------------------------------ ;; TODO: move somewhere more appropriate ;; This works for any Iterable, not just immutable lists. ;; Faster and less garbage than seq operation on iterator-seq on Iterable. #_(defn mapc "Like [[map]] but purely for side effects; always returns <code>nil</code>." ([f things] (assert (ifn? f) (print-str "Not a function:" f)) (let [i (g/iterator things)] (while (g/has-next? i) (f (g/next-item i)))) nil) ([f things0 things1] (assert (ifn? f) (print-str "Not a function:" f)) (let [i0 (g/iterator things0) i1 (g/iterator things1)] (while (and (g/has-next? i0) (g/has-next? i1)) (f (g/next-item i0) (g/next-item i1)))) nil)) ;;------------------------------------------------------------------------------ #_(defn mapc-indexed "Like [[map-indexed]] but purely for side effects; always returns <code>nil</code>." ([f things] (assert (ifn? f) (print-str "Not a function:" f)) (let [it (g/iterator things)] (loop [i (int 0)] (when (g/has-next? it) (f i (g/next-item it)) (recur (inc i))))) nil) ([f things0 things1] (assert (ifn? f) (print-str "Not a function:" f)) (let [i0 (g/iterator things0) i1 (g/iterator things1)] (loop [i (int 0)] (when (and (g/has-next? i0) (g/has-next? i1)) (f i (g/next-item i0) (g/next-item i1)) (recur (inc i))))) nil)) ;;------------------------------------------------------------------------------ ;; sorting ;;------------------------------------------------------------------------------ ;; TODO: functions rather than singletons? (def ^com.google.common.collect.Ordering natural-ordering (Ordering/natural)) (def ^com.google.common.collect.Ordering lexicographic-ordering (.lexicographical (Ordering/natural))) (def ^com.google.common.collect.Ordering string-ordering (Ordering/usingToString)) #_(defn- compare (^long [^Ordering ordering this that] (.compare ordering this that)) (^long [this that] (compare natural-ordering this that))) (defn ^:no-doc lexicographical-compare ^long [this that] (.compare lexicographic-ordering this that)) (defn sort "Sort <code>things</code> according to an instance of <code>com.google.common.collect.Ordering</code>, defaulting to natural ordering for <code>Comparable</code>s and lexicographc ordering of <code>toString</code> output otherwise." (^Iterable [^Ordering ordering ^Iterable things] (if (<= (g/count things) 1) things (.immutableSortedCopy ordering things))) (^Iterable [^Iterable things] (if (<= (g/count things) 1) things (if (g/every? #(instance? Comparable %) things) (sort natural-ordering things) (sort string-ordering things))))) (defn sort-by "Sort <code>things</code> by the value of <code>f</code>, according to an instance of <code>com.google.common.collect.Ordering</code>, defaulting to natural ordering for <code>Comparable</code>s and lexicographc ordering of <code>toString</code> output otherwise." (^Iterable [^Ordering ordering f ^Iterable things] (assert (ifn? f) (print-str "Not a function:" f)) (sort (.onResultOf ordering (function f)) things)) (^Iterable [f ^Iterable things] (assert (ifn? f) (print-str "Not a function:" f)) (sort-by natural-ordering f things))) ;;------------------------------------------------------------------------------
75824
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "<NAME>" :date "2017-10-21" :doc "Eager versions of filter, map, reduce, etc." } zana.collections.guava (:refer-clojure :exclude [any? compare concat count doall drop empty? every? filter first list map map-indexed mapcat next nth pmap remove repeatedly second shuffle some sort sort-by split-at take]) (:require [clojure.pprint :as pp] [zana.commons.core :as cc] [zana.collections.generic :as g]) (:import [com.google.common.base Function Predicate] [com.google.common.collect ImmutableList Iterables Iterators Multimap Ordering Sets Table] [com.google.common.primitives Doubles] [clojure.lang IFn] [java.util ArrayList Collection Collections HashMap IdentityHashMap Iterator List Map Set] [java.util.concurrent Executors Future])) ;;------------------------------------------------------------------------------ ;; TODO: rename to zana.collections.eager ;; TODO: break up into list, map, set, table, ..., namespaces ;; TODO: ImmutableList vs Collections/unmodifiableList performance issues. ;;------------------------------------------------------------------------------ (defn function ^com.google.common.base.Function [f] (cond (instance? Function f) f (ifn? f) (reify Function (apply [this x] (f x))) :else (throw (IllegalArgumentException. (print-str "Not a function:" f))))) ;;------------------------------------------------------------------------------ (defn predicate ^com.google.common.base.Predicate [f] (cond (instance? Predicate f) f (ifn? f)(reify Predicate (apply [this x] (boolean (f x)))) :else (throw (IllegalArgumentException. (print-str "Not a function:" f))))) ;;------------------------------------------------------------------------------ ;; ImmutableList ;;------------------------------------------------------------------------------ (defn nth [things ^long i] (assert things (str "No things to fetch " i "th element from.")) (cond (instance? List things) (.get ^List things (int i)) (instance? Iterator things) (let [^Iterator things things i (int i)] (loop [ii (int 0)] (when (g/has-next? things) (let [x (g/next-item things)] (if (== ii i) x (recur (inc ii))))))) :else (nth (g/iterator things) i))) ;;------------------------------------------------------------------------------ ;; A misleading name here! (defn ^:no-doc doall "Add all the </code>things</code> to a new immutable list." [things] (let [b (ArrayList.)] (.addAll b things) (Collections/unmodifiableList b))) ;;------------------------------------------------------------------------------ (defn #^:no-doc list "Coerce <code>x</code> to an immutable list, if possible. Throw an exception if not." ^java.util.List [x] (cond (nil? x) (ImmutableList/of) (instance? List x) x ;; should we copy to immutable list here? (instance? Collection x) (ImmutableList/copyOf ^Collection x) (instance? Iterable x) (ImmutableList/copyOf ^Iterable x) (instance? Iterator x) (ImmutableList/copyOf ^Iterator x) (cc/object-array? x) (ImmutableList/copyOf ^objects x) :else (throw (UnsupportedOperationException. (str "can't List-ify: " x))))) ;;------------------------------------------------------------------------------ (defn any? "Does <code>f</code> return a <a href=\"http://blog.jayfields.com/2011/02/clojure-truthy-and-falsey.html\">truthy</a> value for any element of <code>things</code>?<br> Returns <code>true</code> or <code>false</code>." [f things] (assert (ifn? f) (print-str "Not a function:" f)) (let [it (g/iterator things)] (loop [] (cond (not (g/has-next? it)) false (f (g/next-item it)) true :else (recur))))) ;;------------------------------------------------------------------------------ (defn some "Does <code>f</code> return a <a href=\"http://blog.jayfields.com/2011/02/clojure-truthy-and-falsey.html\">truthy</a> value for any element of <code>things</code><br> Returns the truthy value or </code>nil</code>." [f things] (assert (ifn? f) (print-str "Not a function:" f)) (let [it (g/iterator things)] (loop [] (if-not (g/has-next? it) nil (let [fi (f (g/next-item it))] (if fi fi (recur))))))) ;;------------------------------------------------------------------------------ (defn repeatedly "Call <code>f</code>, with no arguments, <code>n</code> times, accumulating the results in an <a href=\"https://docs.oracle.com/javase/8/docs/api/index.html?java/lang/Iterable.html\"> Iterable</a>." ^Iterable [^long n f] (assert (ifn? f) (print-str "Not a function:" f)) (let [b (ArrayList. n)] (dotimes [i n] (.add b (f))) (Collections/unmodifiableList b))) ;;------------------------------------------------------------------------------ (defn take "Return an <a href=\"https://docs.oracle.com/javase/8/docs/api/index.html?java/lang/Iterable.html\"> Iterable</a> over the first <code>n</code> elements of <code>things</code>." ^Iterable [^long n things] (let [b (ArrayList. n) it (g/iterator things)] (loop [i 0] (when (and (< i n) (g/has-next? it)) (g/add! b (g/next-item it)) (recur (inc i)))) (Collections/unmodifiableList b))) ;;------------------------------------------------------------------------------ (defn drop "Return an <a href=\"https://docs.oracle.com/javase/8/docs/api/index.html?java/lang/Iterable.html\"> Iterable</a> that skips the first <code>n</code> elements of <code>things</code>." ^Iterable [^long n things] (let [b (ArrayList. n) it (g/iterator things)] (loop [i 0] (when (and (< i n) (g/has-next? it)) (g/next-item it) (recur (inc i)))) (while (g/has-next? it) (g/add! b (g/next-item it))) (Collections/unmodifiableList b))) ;;------------------------------------------------------------------------------ (defn split-at "Returns equivalent of <code>[(take n things) (drop n things)]</code>, see [[take]] and [[drop]]." ^Iterable [^long n things] (let [b0 (ArrayList. n) b1 (ArrayList. n) it (g/iterator things)] (loop [i 0] (when (and (< i n) (g/has-next? it)) (g/add! b0 (g/next-item it)) (recur (inc i)))) (while (g/has-next? it) (g/add! b1 (g/next-item it))) [(Collections/unmodifiableList b0) (Collections/unmodifiableList b1)])) ;;------------------------------------------------------------------------------ #_(defn lazy-filter ^Iterable [f ^Iterable things] (assert (ifn? f) (print-str "Not a function:" f)) (Iterables/filter things (predicate f))) ;;------------------------------------------------------------------------------ (defn remove "Like <code>(filter #(not (f %)) things)</code>." ^Iterable [f things] (assert (ifn? f) (print-str "Not a function:" f)) (g/filter #(not (f %)) things)) ;;------------------------------------------------------------------------------ (defn not-nil "Like <code>(filter #(not (nil? %)) things)</code>." ^Iterable [things] (let [b (ArrayList. (g/count things)) it (g/iterator things)] (while (g/has-next? it) (when-let [thing (g/next-item it)] (g/add! b thing))) (Collections/unmodifiableList b))) ;;------------------------------------------------------------------------------ #_(defn split-by "Like [[group-by[[, but truthy vs non-truthy, and returns a pair of Iterables." [f things] (assert (ifn? f) (print-str "Not a function:" f)) (let [n (g/count things) bt (ArrayList. n) bf (ArrayList. n) it (g/iterator things)] (while (g/has-next? it) (let [thing (g/next-item it)] (if (f thing) (g/add! bt thing) (g/add! bf thing)))) [(Collections/unmodifiableList bt) (Collections/unmodifiableList bf)])) ;;------------------------------------------------------------------------------ (defn- map-indexed-collection (^Iterable [f ^java.util.Collection things] (assert (ifn? f) (print-str "Not a function:" f)) (let [b (ArrayList. (g/count things)) it (g/iterator things)] (loop [i (int 0)] (when (g/has-next? it) (let [nxt (g/next-item it)] (try (g/add! b (f nxt i)) (catch Throwable t (println "map failed:" f nxt (f i nxt)) (.printStackTrace t) (throw t)))) (recur (inc i)))) (Collections/unmodifiableList b))) (^Iterable [f ^java.util.Collection things0 ^java.util.Collection things1] (assert (ifn? f) (print-str "Not a function:" f)) (let [b (ArrayList. (max (g/count things0) (g/count things1))) it0 (g/iterator things0) it1 (g/iterator things1)] (loop [i (int 0)] (when (and (g/has-next? it0) (g/has-next? it1)) (g/add! b (f i (g/next-item it0) (g/next-item it1))) (recur (inc i)))) (Collections/unmodifiableList b)))) ;;------------------------------------------------------------------------------ (defn- map-indexed-iterable (^Iterable [f things] (assert (ifn? f) (print-str "Not a function:" f)) (let [b (ArrayList.) it (g/iterator things)] (loop [i (int 0)] (when (g/has-next? it) (let [nxt (g/next-item it)] (try (.add b (f nxt i)) (catch Throwable t (println "map failed:" f nxt (f i nxt)) (.printStackTrace t) (throw t)))) (recur (inc i)))) (Collections/unmodifiableList b))) (^Iterable [f things0 things1] (assert (ifn? f) (print-str "Not a function:" f)) (let [b (ArrayList.) it0 (g/iterator things0) it1 (g/iterator things1)] (loop [i (int 0)] (when (and (g/has-next? it0) (g/has-next? it1)) (.add b (f i (g/next-item it0) (g/next-item it1))) (recur (inc i)))) (Collections/unmodifiableList b)))) ;;------------------------------------------------------------------------------ (defn map-indexed "Faster, eager, more general version of <code>clojure.core/map-indexed</code>." (^Iterable [f things] (assert (ifn? f) (print-str "Not a function:" f)) (cond (instance? java.util.Collection things) (map-indexed-collection f things) :else (map-indexed-iterable f things))) (^Iterable [f things0 things1] (assert (ifn? f) (print-str "Not a function:" f)) (cond (and (instance? java.util.Collection things0) (instance? java.util.Collection things1)) (map-indexed-collection f things0 things1) :else (map-indexed-iterable f things0 things1)))) ;;------------------------------------------------------------------------------ (defn filter-map "Like <code>(filter p (map f things))</code>." ^java.util.List [p f things] (assert (ifn? p) (print-str "Not a function:" p)) (assert (ifn? f) (print-str "Not a function:" f)) (let [b (ArrayList. (g/count things)) it (g/iterator things)] (while (g/has-next? it) (let [thing (f (g/next-item it))] (when (p thing) (g/add! b thing)))) (Collections/unmodifiableList b))) ;;------------------------------------------------------------------------------ (defn keep-map "Like <code>(keep identity (map f things))</code>." ^java.util.List [f things] (assert (ifn? f) (print-str "Not a function:" f)) (let [b (ArrayList. (g/count things)) it (g/iterator things)] (while (g/has-next? it) (when-let [fi (f (g/next-item it))] (g/add! b fi))) (Collections/unmodifiableList b))) ;;------------------------------------------------------------------------------ ;; Looks like clojure functions are both Callable and Runnable, ;; and ExecutorService treats them as Runnable (no return value). #_(defn- callable (^java.util.concurrent.Callable [f x] (assert (ifn? f) (print-str "Not a function:" f)) (reify java.util.concurrent.Callable (call [this] (f x)))) (^java.util.concurrent.Callable [f x0 x1] (assert (ifn? f) (print-str "Not a function:" f)) (reify java.util.concurrent.Callable (call [this] (f x0 x1)))) (^java.util.concurrent.Callable [f x0 x1 x2] (assert (ifn? f) (print-str "Not a function:" f)) (reify java.util.concurrent.Callable (call [this] (f x0 x1 x2)))) (^java.util.concurrent.Callable [f x0 x1 x2 & args] (assert (ifn? f) (print-str "Not a function:" f)) (reify java.util.concurrent.Callable (call [this] (apply f x0 x1 x2 args))))) ;;------------------------------------------------------------------------------ #_(defn nmap "Eager version of <code>clojure.core/pmap</code> that uses <code>n</code> threads." (^Iterable [n f things] (assert (ifn? f) (print-str "Not a function:" f)) (let [pool (Executors/newFixedThreadPool (int n)) tasks (mapv #(callable f %) things) b (ArrayList. (g/count things))] (try (doseq [^Future future (.invokeAll pool tasks)] (let [v (.get future)] (g/add! b v))) (finally (.shutdown pool))) ;;(.build b))) (Collections/unmodifiableList b))) (^Iterable [n f things0 things1] (assert (ifn? f) (print-str "Not a function:" f)) (let [pool (Executors/newFixedThreadPool (int n)) tasks (mapv (fn [x0 x1] (callable f x0 x1)) things0 things1) b (ArrayList.)] (try (doseq [^Future future (.invokeAll pool tasks)] (.add b (.get future))) (finally (.shutdown pool))) (Collections/unmodifiableList b))) (^Iterable [n f things0 things1 things2] (assert (ifn? f) (print-str "Not a function:" f)) (let [pool (Executors/newFixedThreadPool (int n)) tasks (mapv (fn [x0 x1 x2] (callable f x0 x1 x2)) things0 things1 things2) b (ArrayList.)] (try (doseq [^Future future (.invokeAll pool tasks)] (.add b (.get future))) (finally (.shutdown pool))) (Collections/unmodifiableList b)))) ;;------------------------------------------------------------------------------ #_(defn pmap "Eager version of <code>clojure.core/pmap</code> that uses as many threads as there are <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/Runtime.html#availableProcessors--\"> available processors." (^Iterable [f things] (assert (ifn? f) (print-str "Not a function:" f)) (nmap (.availableProcessors (Runtime/getRuntime)) f things)) (^Iterable [f things0 things1] (assert (ifn? f) (print-str "Not a function:" f)) (nmap (.availableProcessors (Runtime/getRuntime)) f things0 things1)) (^Iterable [f things0 things1 things2] (assert (ifn? f) (print-str "Not a function:" f)) (nmap (.availableProcessors (Runtime/getRuntime)) f things0 things1 things2))) ;;------------------------------------------------------------------------------ #_(defn nmap-indexed "A combination of [[nmap]] and [[map-indexed]]." (^Iterable [^long n f things] (assert (ifn? f) (print-str "Not a function:" f)) (let [pool (Executors/newFixedThreadPool (int n)) nthings (g/count things) tasks (map-indexed (fn [i x] (callable f i x)) things) b (ArrayList. nthings)] (try (doseq [^Future future (.invokeAll pool tasks)] (let [v (.get future)] (.add b v))) (finally (.shutdown pool))) (Collections/unmodifiableList b))) (^Iterable [^long n f things0 things1] (assert (ifn? f) (print-str "Not a function:" f)) (let [pool (Executors/newFixedThreadPool (int n)) tasks (map-indexed (fn [i x0 x1] (callable f i x0 x1)) things0 things1) b (ArrayList.)] (try (doseq [^Future future (.invokeAll pool tasks)] (.add b (.get future))) (finally (.shutdown pool))) (Collections/unmodifiableList b))) (^Iterable [n f things0 things1 things2] (assert (ifn? f) (print-str "Not a function:" f)) (let [pool (Executors/newFixedThreadPool (int n)) tasks (map-indexed (fn [i x0 x1 x2] (callable f i x0 x1 x2)) things0 things1 things2) b (ArrayList.)] (try (doseq [^Future future (.invokeAll pool tasks)] (.add b (.get future))) (finally (.shutdown pool))) (Collections/unmodifiableList b)))) ;;------------------------------------------------------------------------------ #_(defn pmap-indexed "A combination of [[pmap]] and [[map-indexed]]." (^Iterable [f things] (assert (ifn? f) (print-str "Not a function:" f)) (nmap-indexed (.availableProcessors (Runtime/getRuntime)) f things)) (^Iterable [f things0 things1] (assert (ifn? f) (print-str "Not a function:" f)) (nmap-indexed (.availableProcessors (Runtime/getRuntime)) f things0 things1)) (^Iterable [f things0 things1 things2] (assert (ifn? f) (print-str "Not a function:" f)) (nmap-indexed (.availableProcessors (Runtime/getRuntime)) f things0 things1 things2))) ;;------------------------------------------------------------------------------ ;; TODO: move somewhere more appropriate ;; This works for any Iterable, not just immutable lists. ;; Faster and less garbage than seq operation on iterator-seq on Iterable. #_(defn mapc "Like [[map]] but purely for side effects; always returns <code>nil</code>." ([f things] (assert (ifn? f) (print-str "Not a function:" f)) (let [i (g/iterator things)] (while (g/has-next? i) (f (g/next-item i)))) nil) ([f things0 things1] (assert (ifn? f) (print-str "Not a function:" f)) (let [i0 (g/iterator things0) i1 (g/iterator things1)] (while (and (g/has-next? i0) (g/has-next? i1)) (f (g/next-item i0) (g/next-item i1)))) nil)) ;;------------------------------------------------------------------------------ #_(defn mapc-indexed "Like [[map-indexed]] but purely for side effects; always returns <code>nil</code>." ([f things] (assert (ifn? f) (print-str "Not a function:" f)) (let [it (g/iterator things)] (loop [i (int 0)] (when (g/has-next? it) (f i (g/next-item it)) (recur (inc i))))) nil) ([f things0 things1] (assert (ifn? f) (print-str "Not a function:" f)) (let [i0 (g/iterator things0) i1 (g/iterator things1)] (loop [i (int 0)] (when (and (g/has-next? i0) (g/has-next? i1)) (f i (g/next-item i0) (g/next-item i1)) (recur (inc i))))) nil)) ;;------------------------------------------------------------------------------ ;; sorting ;;------------------------------------------------------------------------------ ;; TODO: functions rather than singletons? (def ^com.google.common.collect.Ordering natural-ordering (Ordering/natural)) (def ^com.google.common.collect.Ordering lexicographic-ordering (.lexicographical (Ordering/natural))) (def ^com.google.common.collect.Ordering string-ordering (Ordering/usingToString)) #_(defn- compare (^long [^Ordering ordering this that] (.compare ordering this that)) (^long [this that] (compare natural-ordering this that))) (defn ^:no-doc lexicographical-compare ^long [this that] (.compare lexicographic-ordering this that)) (defn sort "Sort <code>things</code> according to an instance of <code>com.google.common.collect.Ordering</code>, defaulting to natural ordering for <code>Comparable</code>s and lexicographc ordering of <code>toString</code> output otherwise." (^Iterable [^Ordering ordering ^Iterable things] (if (<= (g/count things) 1) things (.immutableSortedCopy ordering things))) (^Iterable [^Iterable things] (if (<= (g/count things) 1) things (if (g/every? #(instance? Comparable %) things) (sort natural-ordering things) (sort string-ordering things))))) (defn sort-by "Sort <code>things</code> by the value of <code>f</code>, according to an instance of <code>com.google.common.collect.Ordering</code>, defaulting to natural ordering for <code>Comparable</code>s and lexicographc ordering of <code>toString</code> output otherwise." (^Iterable [^Ordering ordering f ^Iterable things] (assert (ifn? f) (print-str "Not a function:" f)) (sort (.onResultOf ordering (function f)) things)) (^Iterable [f ^Iterable things] (assert (ifn? f) (print-str "Not a function:" f)) (sort-by natural-ordering f things))) ;;------------------------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "PI:NAME:<NAME>END_PI" :date "2017-10-21" :doc "Eager versions of filter, map, reduce, etc." } zana.collections.guava (:refer-clojure :exclude [any? compare concat count doall drop empty? every? filter first list map map-indexed mapcat next nth pmap remove repeatedly second shuffle some sort sort-by split-at take]) (:require [clojure.pprint :as pp] [zana.commons.core :as cc] [zana.collections.generic :as g]) (:import [com.google.common.base Function Predicate] [com.google.common.collect ImmutableList Iterables Iterators Multimap Ordering Sets Table] [com.google.common.primitives Doubles] [clojure.lang IFn] [java.util ArrayList Collection Collections HashMap IdentityHashMap Iterator List Map Set] [java.util.concurrent Executors Future])) ;;------------------------------------------------------------------------------ ;; TODO: rename to zana.collections.eager ;; TODO: break up into list, map, set, table, ..., namespaces ;; TODO: ImmutableList vs Collections/unmodifiableList performance issues. ;;------------------------------------------------------------------------------ (defn function ^com.google.common.base.Function [f] (cond (instance? Function f) f (ifn? f) (reify Function (apply [this x] (f x))) :else (throw (IllegalArgumentException. (print-str "Not a function:" f))))) ;;------------------------------------------------------------------------------ (defn predicate ^com.google.common.base.Predicate [f] (cond (instance? Predicate f) f (ifn? f)(reify Predicate (apply [this x] (boolean (f x)))) :else (throw (IllegalArgumentException. (print-str "Not a function:" f))))) ;;------------------------------------------------------------------------------ ;; ImmutableList ;;------------------------------------------------------------------------------ (defn nth [things ^long i] (assert things (str "No things to fetch " i "th element from.")) (cond (instance? List things) (.get ^List things (int i)) (instance? Iterator things) (let [^Iterator things things i (int i)] (loop [ii (int 0)] (when (g/has-next? things) (let [x (g/next-item things)] (if (== ii i) x (recur (inc ii))))))) :else (nth (g/iterator things) i))) ;;------------------------------------------------------------------------------ ;; A misleading name here! (defn ^:no-doc doall "Add all the </code>things</code> to a new immutable list." [things] (let [b (ArrayList.)] (.addAll b things) (Collections/unmodifiableList b))) ;;------------------------------------------------------------------------------ (defn #^:no-doc list "Coerce <code>x</code> to an immutable list, if possible. Throw an exception if not." ^java.util.List [x] (cond (nil? x) (ImmutableList/of) (instance? List x) x ;; should we copy to immutable list here? (instance? Collection x) (ImmutableList/copyOf ^Collection x) (instance? Iterable x) (ImmutableList/copyOf ^Iterable x) (instance? Iterator x) (ImmutableList/copyOf ^Iterator x) (cc/object-array? x) (ImmutableList/copyOf ^objects x) :else (throw (UnsupportedOperationException. (str "can't List-ify: " x))))) ;;------------------------------------------------------------------------------ (defn any? "Does <code>f</code> return a <a href=\"http://blog.jayfields.com/2011/02/clojure-truthy-and-falsey.html\">truthy</a> value for any element of <code>things</code>?<br> Returns <code>true</code> or <code>false</code>." [f things] (assert (ifn? f) (print-str "Not a function:" f)) (let [it (g/iterator things)] (loop [] (cond (not (g/has-next? it)) false (f (g/next-item it)) true :else (recur))))) ;;------------------------------------------------------------------------------ (defn some "Does <code>f</code> return a <a href=\"http://blog.jayfields.com/2011/02/clojure-truthy-and-falsey.html\">truthy</a> value for any element of <code>things</code><br> Returns the truthy value or </code>nil</code>." [f things] (assert (ifn? f) (print-str "Not a function:" f)) (let [it (g/iterator things)] (loop [] (if-not (g/has-next? it) nil (let [fi (f (g/next-item it))] (if fi fi (recur))))))) ;;------------------------------------------------------------------------------ (defn repeatedly "Call <code>f</code>, with no arguments, <code>n</code> times, accumulating the results in an <a href=\"https://docs.oracle.com/javase/8/docs/api/index.html?java/lang/Iterable.html\"> Iterable</a>." ^Iterable [^long n f] (assert (ifn? f) (print-str "Not a function:" f)) (let [b (ArrayList. n)] (dotimes [i n] (.add b (f))) (Collections/unmodifiableList b))) ;;------------------------------------------------------------------------------ (defn take "Return an <a href=\"https://docs.oracle.com/javase/8/docs/api/index.html?java/lang/Iterable.html\"> Iterable</a> over the first <code>n</code> elements of <code>things</code>." ^Iterable [^long n things] (let [b (ArrayList. n) it (g/iterator things)] (loop [i 0] (when (and (< i n) (g/has-next? it)) (g/add! b (g/next-item it)) (recur (inc i)))) (Collections/unmodifiableList b))) ;;------------------------------------------------------------------------------ (defn drop "Return an <a href=\"https://docs.oracle.com/javase/8/docs/api/index.html?java/lang/Iterable.html\"> Iterable</a> that skips the first <code>n</code> elements of <code>things</code>." ^Iterable [^long n things] (let [b (ArrayList. n) it (g/iterator things)] (loop [i 0] (when (and (< i n) (g/has-next? it)) (g/next-item it) (recur (inc i)))) (while (g/has-next? it) (g/add! b (g/next-item it))) (Collections/unmodifiableList b))) ;;------------------------------------------------------------------------------ (defn split-at "Returns equivalent of <code>[(take n things) (drop n things)]</code>, see [[take]] and [[drop]]." ^Iterable [^long n things] (let [b0 (ArrayList. n) b1 (ArrayList. n) it (g/iterator things)] (loop [i 0] (when (and (< i n) (g/has-next? it)) (g/add! b0 (g/next-item it)) (recur (inc i)))) (while (g/has-next? it) (g/add! b1 (g/next-item it))) [(Collections/unmodifiableList b0) (Collections/unmodifiableList b1)])) ;;------------------------------------------------------------------------------ #_(defn lazy-filter ^Iterable [f ^Iterable things] (assert (ifn? f) (print-str "Not a function:" f)) (Iterables/filter things (predicate f))) ;;------------------------------------------------------------------------------ (defn remove "Like <code>(filter #(not (f %)) things)</code>." ^Iterable [f things] (assert (ifn? f) (print-str "Not a function:" f)) (g/filter #(not (f %)) things)) ;;------------------------------------------------------------------------------ (defn not-nil "Like <code>(filter #(not (nil? %)) things)</code>." ^Iterable [things] (let [b (ArrayList. (g/count things)) it (g/iterator things)] (while (g/has-next? it) (when-let [thing (g/next-item it)] (g/add! b thing))) (Collections/unmodifiableList b))) ;;------------------------------------------------------------------------------ #_(defn split-by "Like [[group-by[[, but truthy vs non-truthy, and returns a pair of Iterables." [f things] (assert (ifn? f) (print-str "Not a function:" f)) (let [n (g/count things) bt (ArrayList. n) bf (ArrayList. n) it (g/iterator things)] (while (g/has-next? it) (let [thing (g/next-item it)] (if (f thing) (g/add! bt thing) (g/add! bf thing)))) [(Collections/unmodifiableList bt) (Collections/unmodifiableList bf)])) ;;------------------------------------------------------------------------------ (defn- map-indexed-collection (^Iterable [f ^java.util.Collection things] (assert (ifn? f) (print-str "Not a function:" f)) (let [b (ArrayList. (g/count things)) it (g/iterator things)] (loop [i (int 0)] (when (g/has-next? it) (let [nxt (g/next-item it)] (try (g/add! b (f nxt i)) (catch Throwable t (println "map failed:" f nxt (f i nxt)) (.printStackTrace t) (throw t)))) (recur (inc i)))) (Collections/unmodifiableList b))) (^Iterable [f ^java.util.Collection things0 ^java.util.Collection things1] (assert (ifn? f) (print-str "Not a function:" f)) (let [b (ArrayList. (max (g/count things0) (g/count things1))) it0 (g/iterator things0) it1 (g/iterator things1)] (loop [i (int 0)] (when (and (g/has-next? it0) (g/has-next? it1)) (g/add! b (f i (g/next-item it0) (g/next-item it1))) (recur (inc i)))) (Collections/unmodifiableList b)))) ;;------------------------------------------------------------------------------ (defn- map-indexed-iterable (^Iterable [f things] (assert (ifn? f) (print-str "Not a function:" f)) (let [b (ArrayList.) it (g/iterator things)] (loop [i (int 0)] (when (g/has-next? it) (let [nxt (g/next-item it)] (try (.add b (f nxt i)) (catch Throwable t (println "map failed:" f nxt (f i nxt)) (.printStackTrace t) (throw t)))) (recur (inc i)))) (Collections/unmodifiableList b))) (^Iterable [f things0 things1] (assert (ifn? f) (print-str "Not a function:" f)) (let [b (ArrayList.) it0 (g/iterator things0) it1 (g/iterator things1)] (loop [i (int 0)] (when (and (g/has-next? it0) (g/has-next? it1)) (.add b (f i (g/next-item it0) (g/next-item it1))) (recur (inc i)))) (Collections/unmodifiableList b)))) ;;------------------------------------------------------------------------------ (defn map-indexed "Faster, eager, more general version of <code>clojure.core/map-indexed</code>." (^Iterable [f things] (assert (ifn? f) (print-str "Not a function:" f)) (cond (instance? java.util.Collection things) (map-indexed-collection f things) :else (map-indexed-iterable f things))) (^Iterable [f things0 things1] (assert (ifn? f) (print-str "Not a function:" f)) (cond (and (instance? java.util.Collection things0) (instance? java.util.Collection things1)) (map-indexed-collection f things0 things1) :else (map-indexed-iterable f things0 things1)))) ;;------------------------------------------------------------------------------ (defn filter-map "Like <code>(filter p (map f things))</code>." ^java.util.List [p f things] (assert (ifn? p) (print-str "Not a function:" p)) (assert (ifn? f) (print-str "Not a function:" f)) (let [b (ArrayList. (g/count things)) it (g/iterator things)] (while (g/has-next? it) (let [thing (f (g/next-item it))] (when (p thing) (g/add! b thing)))) (Collections/unmodifiableList b))) ;;------------------------------------------------------------------------------ (defn keep-map "Like <code>(keep identity (map f things))</code>." ^java.util.List [f things] (assert (ifn? f) (print-str "Not a function:" f)) (let [b (ArrayList. (g/count things)) it (g/iterator things)] (while (g/has-next? it) (when-let [fi (f (g/next-item it))] (g/add! b fi))) (Collections/unmodifiableList b))) ;;------------------------------------------------------------------------------ ;; Looks like clojure functions are both Callable and Runnable, ;; and ExecutorService treats them as Runnable (no return value). #_(defn- callable (^java.util.concurrent.Callable [f x] (assert (ifn? f) (print-str "Not a function:" f)) (reify java.util.concurrent.Callable (call [this] (f x)))) (^java.util.concurrent.Callable [f x0 x1] (assert (ifn? f) (print-str "Not a function:" f)) (reify java.util.concurrent.Callable (call [this] (f x0 x1)))) (^java.util.concurrent.Callable [f x0 x1 x2] (assert (ifn? f) (print-str "Not a function:" f)) (reify java.util.concurrent.Callable (call [this] (f x0 x1 x2)))) (^java.util.concurrent.Callable [f x0 x1 x2 & args] (assert (ifn? f) (print-str "Not a function:" f)) (reify java.util.concurrent.Callable (call [this] (apply f x0 x1 x2 args))))) ;;------------------------------------------------------------------------------ #_(defn nmap "Eager version of <code>clojure.core/pmap</code> that uses <code>n</code> threads." (^Iterable [n f things] (assert (ifn? f) (print-str "Not a function:" f)) (let [pool (Executors/newFixedThreadPool (int n)) tasks (mapv #(callable f %) things) b (ArrayList. (g/count things))] (try (doseq [^Future future (.invokeAll pool tasks)] (let [v (.get future)] (g/add! b v))) (finally (.shutdown pool))) ;;(.build b))) (Collections/unmodifiableList b))) (^Iterable [n f things0 things1] (assert (ifn? f) (print-str "Not a function:" f)) (let [pool (Executors/newFixedThreadPool (int n)) tasks (mapv (fn [x0 x1] (callable f x0 x1)) things0 things1) b (ArrayList.)] (try (doseq [^Future future (.invokeAll pool tasks)] (.add b (.get future))) (finally (.shutdown pool))) (Collections/unmodifiableList b))) (^Iterable [n f things0 things1 things2] (assert (ifn? f) (print-str "Not a function:" f)) (let [pool (Executors/newFixedThreadPool (int n)) tasks (mapv (fn [x0 x1 x2] (callable f x0 x1 x2)) things0 things1 things2) b (ArrayList.)] (try (doseq [^Future future (.invokeAll pool tasks)] (.add b (.get future))) (finally (.shutdown pool))) (Collections/unmodifiableList b)))) ;;------------------------------------------------------------------------------ #_(defn pmap "Eager version of <code>clojure.core/pmap</code> that uses as many threads as there are <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/Runtime.html#availableProcessors--\"> available processors." (^Iterable [f things] (assert (ifn? f) (print-str "Not a function:" f)) (nmap (.availableProcessors (Runtime/getRuntime)) f things)) (^Iterable [f things0 things1] (assert (ifn? f) (print-str "Not a function:" f)) (nmap (.availableProcessors (Runtime/getRuntime)) f things0 things1)) (^Iterable [f things0 things1 things2] (assert (ifn? f) (print-str "Not a function:" f)) (nmap (.availableProcessors (Runtime/getRuntime)) f things0 things1 things2))) ;;------------------------------------------------------------------------------ #_(defn nmap-indexed "A combination of [[nmap]] and [[map-indexed]]." (^Iterable [^long n f things] (assert (ifn? f) (print-str "Not a function:" f)) (let [pool (Executors/newFixedThreadPool (int n)) nthings (g/count things) tasks (map-indexed (fn [i x] (callable f i x)) things) b (ArrayList. nthings)] (try (doseq [^Future future (.invokeAll pool tasks)] (let [v (.get future)] (.add b v))) (finally (.shutdown pool))) (Collections/unmodifiableList b))) (^Iterable [^long n f things0 things1] (assert (ifn? f) (print-str "Not a function:" f)) (let [pool (Executors/newFixedThreadPool (int n)) tasks (map-indexed (fn [i x0 x1] (callable f i x0 x1)) things0 things1) b (ArrayList.)] (try (doseq [^Future future (.invokeAll pool tasks)] (.add b (.get future))) (finally (.shutdown pool))) (Collections/unmodifiableList b))) (^Iterable [n f things0 things1 things2] (assert (ifn? f) (print-str "Not a function:" f)) (let [pool (Executors/newFixedThreadPool (int n)) tasks (map-indexed (fn [i x0 x1 x2] (callable f i x0 x1 x2)) things0 things1 things2) b (ArrayList.)] (try (doseq [^Future future (.invokeAll pool tasks)] (.add b (.get future))) (finally (.shutdown pool))) (Collections/unmodifiableList b)))) ;;------------------------------------------------------------------------------ #_(defn pmap-indexed "A combination of [[pmap]] and [[map-indexed]]." (^Iterable [f things] (assert (ifn? f) (print-str "Not a function:" f)) (nmap-indexed (.availableProcessors (Runtime/getRuntime)) f things)) (^Iterable [f things0 things1] (assert (ifn? f) (print-str "Not a function:" f)) (nmap-indexed (.availableProcessors (Runtime/getRuntime)) f things0 things1)) (^Iterable [f things0 things1 things2] (assert (ifn? f) (print-str "Not a function:" f)) (nmap-indexed (.availableProcessors (Runtime/getRuntime)) f things0 things1 things2))) ;;------------------------------------------------------------------------------ ;; TODO: move somewhere more appropriate ;; This works for any Iterable, not just immutable lists. ;; Faster and less garbage than seq operation on iterator-seq on Iterable. #_(defn mapc "Like [[map]] but purely for side effects; always returns <code>nil</code>." ([f things] (assert (ifn? f) (print-str "Not a function:" f)) (let [i (g/iterator things)] (while (g/has-next? i) (f (g/next-item i)))) nil) ([f things0 things1] (assert (ifn? f) (print-str "Not a function:" f)) (let [i0 (g/iterator things0) i1 (g/iterator things1)] (while (and (g/has-next? i0) (g/has-next? i1)) (f (g/next-item i0) (g/next-item i1)))) nil)) ;;------------------------------------------------------------------------------ #_(defn mapc-indexed "Like [[map-indexed]] but purely for side effects; always returns <code>nil</code>." ([f things] (assert (ifn? f) (print-str "Not a function:" f)) (let [it (g/iterator things)] (loop [i (int 0)] (when (g/has-next? it) (f i (g/next-item it)) (recur (inc i))))) nil) ([f things0 things1] (assert (ifn? f) (print-str "Not a function:" f)) (let [i0 (g/iterator things0) i1 (g/iterator things1)] (loop [i (int 0)] (when (and (g/has-next? i0) (g/has-next? i1)) (f i (g/next-item i0) (g/next-item i1)) (recur (inc i))))) nil)) ;;------------------------------------------------------------------------------ ;; sorting ;;------------------------------------------------------------------------------ ;; TODO: functions rather than singletons? (def ^com.google.common.collect.Ordering natural-ordering (Ordering/natural)) (def ^com.google.common.collect.Ordering lexicographic-ordering (.lexicographical (Ordering/natural))) (def ^com.google.common.collect.Ordering string-ordering (Ordering/usingToString)) #_(defn- compare (^long [^Ordering ordering this that] (.compare ordering this that)) (^long [this that] (compare natural-ordering this that))) (defn ^:no-doc lexicographical-compare ^long [this that] (.compare lexicographic-ordering this that)) (defn sort "Sort <code>things</code> according to an instance of <code>com.google.common.collect.Ordering</code>, defaulting to natural ordering for <code>Comparable</code>s and lexicographc ordering of <code>toString</code> output otherwise." (^Iterable [^Ordering ordering ^Iterable things] (if (<= (g/count things) 1) things (.immutableSortedCopy ordering things))) (^Iterable [^Iterable things] (if (<= (g/count things) 1) things (if (g/every? #(instance? Comparable %) things) (sort natural-ordering things) (sort string-ordering things))))) (defn sort-by "Sort <code>things</code> by the value of <code>f</code>, according to an instance of <code>com.google.common.collect.Ordering</code>, defaulting to natural ordering for <code>Comparable</code>s and lexicographc ordering of <code>toString</code> output otherwise." (^Iterable [^Ordering ordering f ^Iterable things] (assert (ifn? f) (print-str "Not a function:" f)) (sort (.onResultOf ordering (function f)) things)) (^Iterable [f ^Iterable things] (assert (ifn? f) (print-str "Not a function:" f)) (sort-by natural-ordering f things))) ;;------------------------------------------------------------------------------
[ { "context": " :password \"password\"\n nil)\n ", "end": 9256, "score": 0.9993738532066345, "start": 9248, "tag": "PASSWORD", "value": "password" } ]
src/re_com/misc.cljs
Deraen/re-com
0
(ns re-com.misc (:require-macros [re-com.core :refer [handler-fn]]) (:require [re-com.util :refer [deref-or-value px]] [re-com.popover :refer [popover-tooltip]] [re-com.box :refer [h-box v-box box gap line flex-child-style align-style]] [re-com.validate :refer [input-status-type? input-status-types-list regex? string-or-hiccup? css-style? html-attr? number-or-string? string-or-atom? nillable-string-or-atom? throbber-size? throbber-sizes-list] :refer-macros [validate-args-macro]] [reagent.core :as reagent])) ;; ------------------------------------------------------------------------------------ ;; Component: throbber ;; ------------------------------------------------------------------------------------ (def throbber-args-desc [{:name :size :required false :default :regular :type "keyword" :validate-fn throbber-size? :description [:span "one of " throbber-sizes-list]} {:name :color :required false :default "#999" :type "string" :validate-fn string? :description "CSS color"} {:name :class :required false :type "string" :validate-fn string? :description "CSS class names, space separated (applies to the throbber, not the wrapping div)"} {:name :style :required false :type "CSS style map" :validate-fn css-style? :description "CSS styles to add or override (applies to the throbber, not the wrapping div)"} {:name :attr :required false :type "HTML attr map" :validate-fn html-attr? :description [:span "HTML attributes, like " [:code ":on-mouse-move"] [:br] "No " [:code ":class"] " or " [:code ":style"] "allowed (applies to the throbber, not the wrapping div)"]}]) (defn throbber "Render an animated throbber using CSS" [& {:keys [size color class style attr] :as args}] {:pre [(validate-args-macro throbber-args-desc args "throbber")]} (let [seg (fn [] [:li (when color {:style {:background-color color}})])] [box :class "rc-throbber-wrapper" :align :start :child [:ul (merge {:class (str "rc-throbber loader " (case size :regular "" :smaller "smaller " :small "small " :large "large " "") class) :style style} attr) [seg] [seg] [seg] [seg] [seg] [seg] [seg] [seg]]])) ;; Each :li element in [seg] represents one of the eight circles in the throbber ;; ------------------------------------------------------------------------------------ ;; Component: input-text ;; ------------------------------------------------------------------------------------ (def input-text-args-desc [{:name :model :required true :type "string/nil | atom" :validate-fn nillable-string-or-atom? :description "text of the input (can be atom or value/nil)"} {:name :on-change :required true :type "string -> nil" :validate-fn fn? :description [:span [:code ":change-on-blur?"] " controls when it is called. Passed the current input string"]} {:name :status :required false :type "keyword" :validate-fn input-status-type? :description [:span "validation status. " [:code "nil/omitted"] " for normal status or one of: " input-status-types-list]} {:name :status-icon? :required false :default false :type "boolean" :description [:span "when true, display an icon to match " [:code ":status"] " (no icon for nil)"]} {:name :status-tooltip :required false :type "string" :validate-fn string? :description "displayed in status icon's tooltip"} {:name :placeholder :required false :type "string" :validate-fn string? :description "background text shown when empty"} {:name :width :required false :default "250px" :type "string" :validate-fn string? :description "standard CSS width setting for this input"} {:name :height :required false :type "string" :validate-fn string? :description "standard CSS height setting for this input"} {:name :rows :required false :default 3 :type "integer | string" :validate-fn number-or-string? :description "ONLY applies to 'input-textarea': the number of rows of text to show"} {:name :change-on-blur? :required false :default true :type "boolean | atom" :description [:span "when true, invoke " [:code ":on-change"] " function on blur, otherwise on every change (character by character)"]} {:name :on-alter :required false :type "string -> string" :validate-fn fn? :description "called with the new value to alter it immediately"} {:name :validation-regex :required false :type "regex" :validate-fn regex? :description "user input is only accepted if it would result in a string that matches this regular expression"} {:name :disabled? :required false :default false :type "boolean | atom" :description "if true, the user can't interact (input anything)"} {:name :class :required false :type "string" :validate-fn string? :description "CSS class names, space separated (applies to the textbox, not the wrapping div)"} {:name :style :required false :type "CSS style map" :validate-fn css-style? :description "CSS styles to add or override (applies to the textbox, not the wrapping div)"} {:name :attr :required false :type "HTML attr map" :validate-fn html-attr? :description [:span "HTML attributes, like " [:code ":on-mouse-move"] [:br] "No " [:code ":class"] " or " [:code ":style"] "allowed (applies to the textbox, not the wrapping div)"]} {:name :input-type :required false :type "keyword" :validate-fn keyword? :description [:span "ONLY applies to super function 'base-input-text': either " [:code ":input"] ", " [:code ":password"] " or " [:code ":textarea"]]}]) ;; Sample regex's: ;; - #"^(-{0,1})(\d*)$" ;; Signed integer ;; - #"^(\d{0,2})$|^(\d{0,2}\.\d{0,1})$" ;; Specific numeric value ##.# ;; - #"^.{0,8}$" ;; 8 chars max ;; - #"^[0-9a-fA-F]*$" ;; Hex number ;; - #"^(\d{0,2})()()$|^(\d{0,1})(:{0,1})(\d{0,2})$|^(\d{0,2})(:{0,1})(\d{0,2})$" ;; Time input (defn- input-text-base "Returns markup for a basic text input label" [& {:keys [model input-type] :as args}] {:pre [(validate-args-macro input-text-args-desc args "input-text")]} (let [external-model (reagent/atom (deref-or-value model)) ;; Holds the last known external value of model, to detect external model changes internal-model (reagent/atom (if (nil? @external-model) "" @external-model))] ;; Create a new atom from the model to be used internally (avoid nil) (fn [& {:keys [model on-change status status-icon? status-tooltip placeholder width height rows change-on-blur? on-alter validation-regex disabled? class style attr] :or {change-on-blur? true, on-alter identity} :as args}] {:pre [(validate-args-macro input-text-args-desc args "input-text")]} (let [latest-ext-model (deref-or-value model) disabled? (deref-or-value disabled?) change-on-blur? (deref-or-value change-on-blur?) showing? (reagent/atom false)] (when (not= @external-model latest-ext-model) ;; Has model changed externally? (reset! external-model latest-ext-model) (reset! internal-model latest-ext-model)) [h-box :class "rc-input-text " :align :start :width (if width width "250px") :children [[:div {:class (str "rc-input-text-inner " ;; form-group (case status :success "has-success " :warning "has-warning " :error "has-error " "") (when (and status status-icon?) "has-feedback")) :style (flex-child-style "auto")} [(if (= input-type :password) :input input-type) (merge {:class (str "form-control " class) :type (case input-type :input "text" :password "password" nil) :rows (when (= input-type :textarea) (or rows 3)) :style (merge (flex-child-style "none") {:height height :padding-right "12px"} ;; override for when icon exists style) :placeholder placeholder :value @internal-model :disabled disabled? :on-change (handler-fn (let [new-val-orig (-> event .-target .-value) new-val (on-alter new-val-orig)] (when (not= new-val new-val-orig) (set! (-> event .-target .-value) new-val)) (when (and on-change (not disabled?) (if validation-regex (re-find validation-regex new-val) true)) (reset! internal-model new-val) (when-not change-on-blur? (reset! external-model @internal-model) (on-change @internal-model))))) :on-blur (handler-fn (when (and on-change change-on-blur? (not= @internal-model @external-model)) (reset! external-model @internal-model) (on-change @internal-model))) :on-key-up (handler-fn (if disabled? (.preventDefault event) (case (.-which event) 13 (when on-change (reset! external-model @internal-model) (on-change @internal-model)) 27 (reset! internal-model @external-model) true)))} attr)]] (when (and status-icon? status) (let [icon-class (case status :success "zmdi-check-circle" :warning "zmdi-alert-triangle" :error "zmdi-alert-circle zmdi-spinner" :validating "zmdi-hc-spin zmdi-rotate-right zmdi-spinner")] (if status-tooltip [popover-tooltip :label status-tooltip :position :right-center :status status ;:width "200px" :showing? showing? :anchor (if (= :validating status) [throbber :size :regular :class "smaller" :attr {:on-mouse-over (handler-fn (when (and status-icon? status) (reset! showing? true))) :on-mouse-out (handler-fn (reset! showing? false))}] [:i {:class (str "zmdi zmdi-hc-fw " icon-class " form-control-feedback") :style {:position "static" :height "auto" :opacity (if (and status-icon? status) "1" "0")} :on-mouse-over (handler-fn (when (and status-icon? status) (reset! showing? true))) :on-mouse-out (handler-fn (reset! showing? false))}]) :style (merge (flex-child-style "none") (align-style :align-self :center) {:font-size "130%" :margin-left "4px"})] (if (= :validating status) [throbber :size :regular :class "smaller"] [:i {:class (str "zmdi zmdi-hc-fw " icon-class " form-control-feedback") :style (merge (flex-child-style "none") (align-style :align-self :center) {:position "static" :font-size "130%" :margin-left "4px" :opacity (if (and status-icon? status) "1" "0") :height "auto"}) :title status-tooltip}]))))]])))) (defn input-text [& args] (apply input-text-base :input-type :input args)) (defn input-password [& args] (apply input-text-base :input-type :password args)) (defn input-textarea [& args] (apply input-text-base :input-type :textarea args)) ;; ------------------------------------------------------------------------------------ ;; Component: checkbox ;; ------------------------------------------------------------------------------------ (def checkbox-args-desc [{:name :model :required true :type "boolean | atom" :description "holds state of the checkbox when it is called"} {:name :on-change :required true :type "boolean -> nil" :validate-fn fn? :description "called when the checkbox is clicked. Passed the new value of the checkbox"} {:name :label :required false :type "string | hiccup" :validate-fn string-or-hiccup? :description "the label shown to the right"} {:name :disabled? :required false :default false :type "boolean | atom" :description "if true, user interaction is disabled"} {:name :label-class :required false :type "string" :validate-fn string? :description "CSS class names (applies to the label)"} {:name :label-style :required false :type "CSS style map" :validate-fn css-style? :description "CSS style map (applies to the label)"} {:name :class :required false :type "string" :validate-fn string? :description "CSS class names, space separated (applies to the checkbox, not the wrapping div)"} {:name :style :required false :type "CSS style map" :validate-fn css-style? :description "CSS style map (applies to the checkbox, not the wrapping div)"} {:name :attr :required false :type "HTML attr map" :validate-fn html-attr? :description [:span "HTML attributes, like " [:code ":on-mouse-move"] [:br] "No " [:code ":class"] " or " [:code ":style"] "allowed (applies to the checkbox, not the wrapping div)"]}]) ;; TODO: when disabled?, should the text appear "disabled". (defn checkbox "I return the markup for a checkbox, with an optional RHS label" [& {:keys [model on-change label disabled? label-class label-style class style attr] :as args}] {:pre [(validate-args-macro checkbox-args-desc args "checkbox")]} (let [cursor "default" model (deref-or-value model) disabled? (deref-or-value disabled?) callback-fn #(when (and on-change (not disabled?)) (on-change (not model)))] ;; call on-change with either true or false [h-box :class "rc-checkbox-wrapper noselect" :align :start :children [[:input (merge {:class (str "rc-checkbox " class) :type "checkbox" :style (merge (flex-child-style "none") {:cursor cursor} style) :disabled disabled? :checked (boolean model) :on-change (handler-fn (callback-fn))} attr)] (when label [:span {:class label-class :style (merge (flex-child-style "none") {:padding-left "8px" :cursor cursor} label-style) :on-click (handler-fn (callback-fn))} label])]])) ;; ------------------------------------------------------------------------------------ ;; Component: radio-button ;; ------------------------------------------------------------------------------------ (def radio-button-args-desc [{:name :model :required true :type "anything | atom" :description [:span "selected value of the radio button group. See also " [:code ":value"]]} {:name :value :required false :type "anything" :description [:span "if " [:code ":model"] " equals " [:code ":value"] " then this radio button is selected"]} {:name :on-change :required true :type "anything -> nil" :validate-fn fn? :description [:span "called when the radio button is clicked. Passed " [:code ":value"]]} {:name :label :required false :type "string | hiccup" :validate-fn string-or-hiccup? :description "the label shown to the right"} {:name :disabled? :required false :default false :type "boolean | atom" :description "if true, the user can't click the radio button"} {:name :label-class :required false :type "string" :validate-fn string? :description "CSS class names (applies to the label)"} {:name :label-style :required false :type "CSS style map" :validate-fn css-style? :description "CSS style map (applies to the label)"} {:name :class :required false :type "string" :validate-fn string? :description "CSS class names, space separated (applies to the radio-button, not the wrapping div)"} {:name :style :required false :type "CSS style map" :validate-fn css-style? :description "CSS style map (applies to the radio-button, not the wrapping div)"} {:name :attr :required false :type "HTML attr map" :validate-fn html-attr? :description [:span "HTML attributes, like " [:code ":on-mouse-move"] [:br] "No " [:code ":class"] " or " [:code ":style"] "allowed (applies to the radio-button, not the wrapping div)"]}]) (defn radio-button "I return the markup for a radio button, with an optional RHS label" [& {:keys [model value on-change label disabled? label-class label-style class style attr] :as args}] {:pre [(validate-args-macro radio-button-args-desc args "radio-button")]} (let [cursor "default" model (deref-or-value model) disabled? (deref-or-value disabled?) callback-fn #(when (and on-change (not disabled?)) (on-change value))] ;; call on-change with the :value arg [h-box :class "rc-radio-button-wrapper noselect" :align :start :children [[:input (merge {:class (str "rc-radio-button " class) :style (merge (flex-child-style "none") {:cursor cursor} style) :type "radio" :disabled disabled? :checked (= model value) :on-change (handler-fn (callback-fn))} attr)] (when label [:span {:class label-class :style (merge (flex-child-style "none") {:padding-left "8px" :cursor cursor} label-style) :on-click (handler-fn (callback-fn))} label])]])) ;; ------------------------------------------------------------------------------------ ;; Component: slider ;; ------------------------------------------------------------------------------------ (def slider-args-desc [{:name :model :required true :type "double | string | atom" :validate-fn number-or-string? :description "current value of the slider"} {:name :on-change :required true :type "double -> nil" :validate-fn fn? :description "called when the slider is moved. Passed the new value of the slider"} {:name :min :required false :default 0 :type "double | string | atom" :validate-fn number-or-string? :description "the minimum value of the slider"} {:name :max :required false :default 100 :type "double | string | atom" :validate-fn number-or-string? :description "the maximum value of the slider"} {:name :step :required false :default 1 :type "double | string | atom" :validate-fn number-or-string? :description "step value between min and max"} {:name :width :required false :default "400px" :type "string" :validate-fn string? :description "standard CSS width setting for the slider"} {:name :disabled? :required false :default false :type "boolean | atom" :description "if true, the user can't change the slider"} {:name :class :required false :type "string" :validate-fn string? :description "CSS class names, space separated (applies to the slider, not the wrapping div)"} {:name :style :required false :type "CSS style map" :validate-fn css-style? :description "CSS styles to add or override (applies to the slider, not the wrapping div)"} {:name :attr :required false :type "HTML attr map" :validate-fn html-attr? :description [:span "HTML attributes, like " [:code ":on-mouse-move"] [:br] "No " [:code ":class"] " or " [:code ":style"] "allowed (applies to the slider, not the wrapping div)"]}]) (defn slider "Returns markup for an HTML5 slider input" [& {:keys [model min max step width on-change disabled? class style attr] :or {min 0 max 100} :as args}] {:pre [(validate-args-macro slider-args-desc args "slider")]} (let [model (deref-or-value model) min (deref-or-value min) max (deref-or-value max) step (deref-or-value step) disabled? (deref-or-value disabled?)] [box :class "rc-slider-wrapper" :align :start :child [:input (merge {:class (str "rc-slider " class) :type "range" ;:orient "vertical" ;; Make Firefox slider vertical (doesn't work because React ignores it, I think) :style (merge (flex-child-style "none") {;:-webkit-appearance "slider-vertical" ;; TODO: Make a :orientation (:horizontal/:vertical) option ;:writing-mode "bt-lr" ;; Make IE slider vertical :width (or width "400px") :cursor (if disabled? "default" "pointer")} style) :min min :max max :step step :value model :disabled disabled? :on-change (handler-fn (on-change (js/Number (-> event .-target .-value))))} attr)]])) ;; ------------------------------------------------------------------------------------ ;; Component: progress-bar ;; ------------------------------------------------------------------------------------ (def progress-bar-args-desc [{:name :model :required true :type "double | string | atom" :validate-fn number-or-string? :description "current value of the slider. A number between 0 and 100"} {:name :width :required false :default "100%" :type "string" :validate-fn string? :description "a CSS width"} {:name :striped? :required false :default false :type "boolean" :description "when true, the progress section is a set of animated stripes"} {:name :bar-class :required false :type "string" :validate-fn string? :description "CSS class name(s) for the actual progress bar itself, space separated"} {:name :class :required false :type "string" :validate-fn string? :description "CSS class names, space separated (applies to the progress-bar, not the wrapping div)"} {:name :style :required false :type "CSS style map" :validate-fn css-style? :description "CSS styles to add or override (applies to the progress-bar, not the wrapping div)"} {:name :attr :required false :type "HTML attr map" :validate-fn html-attr? :description [:span "HTML attributes, like " [:code ":on-mouse-move"] [:br] "No " [:code ":class"] " or " [:code ":style"] "allowed (applies to the progress-bar, not the wrapping div)"]}]) (defn progress-bar "Render a bootstrap styled progress bar" [& {:keys [model width striped? class bar-class style attr] :or {width "100%"} :as args}] {:pre [(validate-args-macro progress-bar-args-desc args "progress-bar")]} (let [model (deref-or-value model)] [box :class "rc-progress-bar-wrapper" :align :start :child [:div (merge {:class (str "rc-progress-bar progress " class) :style (merge (flex-child-style "none") {:width width} style)} attr) [:div {:class (str "progress-bar " (when striped? "progress-bar-striped active ") bar-class) :role "progressbar" :style {:width (str model "%") :transition "none"}} ;; Default BS transitions cause the progress bar to lag behind (str model "%")]]]))
74209
(ns re-com.misc (:require-macros [re-com.core :refer [handler-fn]]) (:require [re-com.util :refer [deref-or-value px]] [re-com.popover :refer [popover-tooltip]] [re-com.box :refer [h-box v-box box gap line flex-child-style align-style]] [re-com.validate :refer [input-status-type? input-status-types-list regex? string-or-hiccup? css-style? html-attr? number-or-string? string-or-atom? nillable-string-or-atom? throbber-size? throbber-sizes-list] :refer-macros [validate-args-macro]] [reagent.core :as reagent])) ;; ------------------------------------------------------------------------------------ ;; Component: throbber ;; ------------------------------------------------------------------------------------ (def throbber-args-desc [{:name :size :required false :default :regular :type "keyword" :validate-fn throbber-size? :description [:span "one of " throbber-sizes-list]} {:name :color :required false :default "#999" :type "string" :validate-fn string? :description "CSS color"} {:name :class :required false :type "string" :validate-fn string? :description "CSS class names, space separated (applies to the throbber, not the wrapping div)"} {:name :style :required false :type "CSS style map" :validate-fn css-style? :description "CSS styles to add or override (applies to the throbber, not the wrapping div)"} {:name :attr :required false :type "HTML attr map" :validate-fn html-attr? :description [:span "HTML attributes, like " [:code ":on-mouse-move"] [:br] "No " [:code ":class"] " or " [:code ":style"] "allowed (applies to the throbber, not the wrapping div)"]}]) (defn throbber "Render an animated throbber using CSS" [& {:keys [size color class style attr] :as args}] {:pre [(validate-args-macro throbber-args-desc args "throbber")]} (let [seg (fn [] [:li (when color {:style {:background-color color}})])] [box :class "rc-throbber-wrapper" :align :start :child [:ul (merge {:class (str "rc-throbber loader " (case size :regular "" :smaller "smaller " :small "small " :large "large " "") class) :style style} attr) [seg] [seg] [seg] [seg] [seg] [seg] [seg] [seg]]])) ;; Each :li element in [seg] represents one of the eight circles in the throbber ;; ------------------------------------------------------------------------------------ ;; Component: input-text ;; ------------------------------------------------------------------------------------ (def input-text-args-desc [{:name :model :required true :type "string/nil | atom" :validate-fn nillable-string-or-atom? :description "text of the input (can be atom or value/nil)"} {:name :on-change :required true :type "string -> nil" :validate-fn fn? :description [:span [:code ":change-on-blur?"] " controls when it is called. Passed the current input string"]} {:name :status :required false :type "keyword" :validate-fn input-status-type? :description [:span "validation status. " [:code "nil/omitted"] " for normal status or one of: " input-status-types-list]} {:name :status-icon? :required false :default false :type "boolean" :description [:span "when true, display an icon to match " [:code ":status"] " (no icon for nil)"]} {:name :status-tooltip :required false :type "string" :validate-fn string? :description "displayed in status icon's tooltip"} {:name :placeholder :required false :type "string" :validate-fn string? :description "background text shown when empty"} {:name :width :required false :default "250px" :type "string" :validate-fn string? :description "standard CSS width setting for this input"} {:name :height :required false :type "string" :validate-fn string? :description "standard CSS height setting for this input"} {:name :rows :required false :default 3 :type "integer | string" :validate-fn number-or-string? :description "ONLY applies to 'input-textarea': the number of rows of text to show"} {:name :change-on-blur? :required false :default true :type "boolean | atom" :description [:span "when true, invoke " [:code ":on-change"] " function on blur, otherwise on every change (character by character)"]} {:name :on-alter :required false :type "string -> string" :validate-fn fn? :description "called with the new value to alter it immediately"} {:name :validation-regex :required false :type "regex" :validate-fn regex? :description "user input is only accepted if it would result in a string that matches this regular expression"} {:name :disabled? :required false :default false :type "boolean | atom" :description "if true, the user can't interact (input anything)"} {:name :class :required false :type "string" :validate-fn string? :description "CSS class names, space separated (applies to the textbox, not the wrapping div)"} {:name :style :required false :type "CSS style map" :validate-fn css-style? :description "CSS styles to add or override (applies to the textbox, not the wrapping div)"} {:name :attr :required false :type "HTML attr map" :validate-fn html-attr? :description [:span "HTML attributes, like " [:code ":on-mouse-move"] [:br] "No " [:code ":class"] " or " [:code ":style"] "allowed (applies to the textbox, not the wrapping div)"]} {:name :input-type :required false :type "keyword" :validate-fn keyword? :description [:span "ONLY applies to super function 'base-input-text': either " [:code ":input"] ", " [:code ":password"] " or " [:code ":textarea"]]}]) ;; Sample regex's: ;; - #"^(-{0,1})(\d*)$" ;; Signed integer ;; - #"^(\d{0,2})$|^(\d{0,2}\.\d{0,1})$" ;; Specific numeric value ##.# ;; - #"^.{0,8}$" ;; 8 chars max ;; - #"^[0-9a-fA-F]*$" ;; Hex number ;; - #"^(\d{0,2})()()$|^(\d{0,1})(:{0,1})(\d{0,2})$|^(\d{0,2})(:{0,1})(\d{0,2})$" ;; Time input (defn- input-text-base "Returns markup for a basic text input label" [& {:keys [model input-type] :as args}] {:pre [(validate-args-macro input-text-args-desc args "input-text")]} (let [external-model (reagent/atom (deref-or-value model)) ;; Holds the last known external value of model, to detect external model changes internal-model (reagent/atom (if (nil? @external-model) "" @external-model))] ;; Create a new atom from the model to be used internally (avoid nil) (fn [& {:keys [model on-change status status-icon? status-tooltip placeholder width height rows change-on-blur? on-alter validation-regex disabled? class style attr] :or {change-on-blur? true, on-alter identity} :as args}] {:pre [(validate-args-macro input-text-args-desc args "input-text")]} (let [latest-ext-model (deref-or-value model) disabled? (deref-or-value disabled?) change-on-blur? (deref-or-value change-on-blur?) showing? (reagent/atom false)] (when (not= @external-model latest-ext-model) ;; Has model changed externally? (reset! external-model latest-ext-model) (reset! internal-model latest-ext-model)) [h-box :class "rc-input-text " :align :start :width (if width width "250px") :children [[:div {:class (str "rc-input-text-inner " ;; form-group (case status :success "has-success " :warning "has-warning " :error "has-error " "") (when (and status status-icon?) "has-feedback")) :style (flex-child-style "auto")} [(if (= input-type :password) :input input-type) (merge {:class (str "form-control " class) :type (case input-type :input "text" :password "<PASSWORD>" nil) :rows (when (= input-type :textarea) (or rows 3)) :style (merge (flex-child-style "none") {:height height :padding-right "12px"} ;; override for when icon exists style) :placeholder placeholder :value @internal-model :disabled disabled? :on-change (handler-fn (let [new-val-orig (-> event .-target .-value) new-val (on-alter new-val-orig)] (when (not= new-val new-val-orig) (set! (-> event .-target .-value) new-val)) (when (and on-change (not disabled?) (if validation-regex (re-find validation-regex new-val) true)) (reset! internal-model new-val) (when-not change-on-blur? (reset! external-model @internal-model) (on-change @internal-model))))) :on-blur (handler-fn (when (and on-change change-on-blur? (not= @internal-model @external-model)) (reset! external-model @internal-model) (on-change @internal-model))) :on-key-up (handler-fn (if disabled? (.preventDefault event) (case (.-which event) 13 (when on-change (reset! external-model @internal-model) (on-change @internal-model)) 27 (reset! internal-model @external-model) true)))} attr)]] (when (and status-icon? status) (let [icon-class (case status :success "zmdi-check-circle" :warning "zmdi-alert-triangle" :error "zmdi-alert-circle zmdi-spinner" :validating "zmdi-hc-spin zmdi-rotate-right zmdi-spinner")] (if status-tooltip [popover-tooltip :label status-tooltip :position :right-center :status status ;:width "200px" :showing? showing? :anchor (if (= :validating status) [throbber :size :regular :class "smaller" :attr {:on-mouse-over (handler-fn (when (and status-icon? status) (reset! showing? true))) :on-mouse-out (handler-fn (reset! showing? false))}] [:i {:class (str "zmdi zmdi-hc-fw " icon-class " form-control-feedback") :style {:position "static" :height "auto" :opacity (if (and status-icon? status) "1" "0")} :on-mouse-over (handler-fn (when (and status-icon? status) (reset! showing? true))) :on-mouse-out (handler-fn (reset! showing? false))}]) :style (merge (flex-child-style "none") (align-style :align-self :center) {:font-size "130%" :margin-left "4px"})] (if (= :validating status) [throbber :size :regular :class "smaller"] [:i {:class (str "zmdi zmdi-hc-fw " icon-class " form-control-feedback") :style (merge (flex-child-style "none") (align-style :align-self :center) {:position "static" :font-size "130%" :margin-left "4px" :opacity (if (and status-icon? status) "1" "0") :height "auto"}) :title status-tooltip}]))))]])))) (defn input-text [& args] (apply input-text-base :input-type :input args)) (defn input-password [& args] (apply input-text-base :input-type :password args)) (defn input-textarea [& args] (apply input-text-base :input-type :textarea args)) ;; ------------------------------------------------------------------------------------ ;; Component: checkbox ;; ------------------------------------------------------------------------------------ (def checkbox-args-desc [{:name :model :required true :type "boolean | atom" :description "holds state of the checkbox when it is called"} {:name :on-change :required true :type "boolean -> nil" :validate-fn fn? :description "called when the checkbox is clicked. Passed the new value of the checkbox"} {:name :label :required false :type "string | hiccup" :validate-fn string-or-hiccup? :description "the label shown to the right"} {:name :disabled? :required false :default false :type "boolean | atom" :description "if true, user interaction is disabled"} {:name :label-class :required false :type "string" :validate-fn string? :description "CSS class names (applies to the label)"} {:name :label-style :required false :type "CSS style map" :validate-fn css-style? :description "CSS style map (applies to the label)"} {:name :class :required false :type "string" :validate-fn string? :description "CSS class names, space separated (applies to the checkbox, not the wrapping div)"} {:name :style :required false :type "CSS style map" :validate-fn css-style? :description "CSS style map (applies to the checkbox, not the wrapping div)"} {:name :attr :required false :type "HTML attr map" :validate-fn html-attr? :description [:span "HTML attributes, like " [:code ":on-mouse-move"] [:br] "No " [:code ":class"] " or " [:code ":style"] "allowed (applies to the checkbox, not the wrapping div)"]}]) ;; TODO: when disabled?, should the text appear "disabled". (defn checkbox "I return the markup for a checkbox, with an optional RHS label" [& {:keys [model on-change label disabled? label-class label-style class style attr] :as args}] {:pre [(validate-args-macro checkbox-args-desc args "checkbox")]} (let [cursor "default" model (deref-or-value model) disabled? (deref-or-value disabled?) callback-fn #(when (and on-change (not disabled?)) (on-change (not model)))] ;; call on-change with either true or false [h-box :class "rc-checkbox-wrapper noselect" :align :start :children [[:input (merge {:class (str "rc-checkbox " class) :type "checkbox" :style (merge (flex-child-style "none") {:cursor cursor} style) :disabled disabled? :checked (boolean model) :on-change (handler-fn (callback-fn))} attr)] (when label [:span {:class label-class :style (merge (flex-child-style "none") {:padding-left "8px" :cursor cursor} label-style) :on-click (handler-fn (callback-fn))} label])]])) ;; ------------------------------------------------------------------------------------ ;; Component: radio-button ;; ------------------------------------------------------------------------------------ (def radio-button-args-desc [{:name :model :required true :type "anything | atom" :description [:span "selected value of the radio button group. See also " [:code ":value"]]} {:name :value :required false :type "anything" :description [:span "if " [:code ":model"] " equals " [:code ":value"] " then this radio button is selected"]} {:name :on-change :required true :type "anything -> nil" :validate-fn fn? :description [:span "called when the radio button is clicked. Passed " [:code ":value"]]} {:name :label :required false :type "string | hiccup" :validate-fn string-or-hiccup? :description "the label shown to the right"} {:name :disabled? :required false :default false :type "boolean | atom" :description "if true, the user can't click the radio button"} {:name :label-class :required false :type "string" :validate-fn string? :description "CSS class names (applies to the label)"} {:name :label-style :required false :type "CSS style map" :validate-fn css-style? :description "CSS style map (applies to the label)"} {:name :class :required false :type "string" :validate-fn string? :description "CSS class names, space separated (applies to the radio-button, not the wrapping div)"} {:name :style :required false :type "CSS style map" :validate-fn css-style? :description "CSS style map (applies to the radio-button, not the wrapping div)"} {:name :attr :required false :type "HTML attr map" :validate-fn html-attr? :description [:span "HTML attributes, like " [:code ":on-mouse-move"] [:br] "No " [:code ":class"] " or " [:code ":style"] "allowed (applies to the radio-button, not the wrapping div)"]}]) (defn radio-button "I return the markup for a radio button, with an optional RHS label" [& {:keys [model value on-change label disabled? label-class label-style class style attr] :as args}] {:pre [(validate-args-macro radio-button-args-desc args "radio-button")]} (let [cursor "default" model (deref-or-value model) disabled? (deref-or-value disabled?) callback-fn #(when (and on-change (not disabled?)) (on-change value))] ;; call on-change with the :value arg [h-box :class "rc-radio-button-wrapper noselect" :align :start :children [[:input (merge {:class (str "rc-radio-button " class) :style (merge (flex-child-style "none") {:cursor cursor} style) :type "radio" :disabled disabled? :checked (= model value) :on-change (handler-fn (callback-fn))} attr)] (when label [:span {:class label-class :style (merge (flex-child-style "none") {:padding-left "8px" :cursor cursor} label-style) :on-click (handler-fn (callback-fn))} label])]])) ;; ------------------------------------------------------------------------------------ ;; Component: slider ;; ------------------------------------------------------------------------------------ (def slider-args-desc [{:name :model :required true :type "double | string | atom" :validate-fn number-or-string? :description "current value of the slider"} {:name :on-change :required true :type "double -> nil" :validate-fn fn? :description "called when the slider is moved. Passed the new value of the slider"} {:name :min :required false :default 0 :type "double | string | atom" :validate-fn number-or-string? :description "the minimum value of the slider"} {:name :max :required false :default 100 :type "double | string | atom" :validate-fn number-or-string? :description "the maximum value of the slider"} {:name :step :required false :default 1 :type "double | string | atom" :validate-fn number-or-string? :description "step value between min and max"} {:name :width :required false :default "400px" :type "string" :validate-fn string? :description "standard CSS width setting for the slider"} {:name :disabled? :required false :default false :type "boolean | atom" :description "if true, the user can't change the slider"} {:name :class :required false :type "string" :validate-fn string? :description "CSS class names, space separated (applies to the slider, not the wrapping div)"} {:name :style :required false :type "CSS style map" :validate-fn css-style? :description "CSS styles to add or override (applies to the slider, not the wrapping div)"} {:name :attr :required false :type "HTML attr map" :validate-fn html-attr? :description [:span "HTML attributes, like " [:code ":on-mouse-move"] [:br] "No " [:code ":class"] " or " [:code ":style"] "allowed (applies to the slider, not the wrapping div)"]}]) (defn slider "Returns markup for an HTML5 slider input" [& {:keys [model min max step width on-change disabled? class style attr] :or {min 0 max 100} :as args}] {:pre [(validate-args-macro slider-args-desc args "slider")]} (let [model (deref-or-value model) min (deref-or-value min) max (deref-or-value max) step (deref-or-value step) disabled? (deref-or-value disabled?)] [box :class "rc-slider-wrapper" :align :start :child [:input (merge {:class (str "rc-slider " class) :type "range" ;:orient "vertical" ;; Make Firefox slider vertical (doesn't work because React ignores it, I think) :style (merge (flex-child-style "none") {;:-webkit-appearance "slider-vertical" ;; TODO: Make a :orientation (:horizontal/:vertical) option ;:writing-mode "bt-lr" ;; Make IE slider vertical :width (or width "400px") :cursor (if disabled? "default" "pointer")} style) :min min :max max :step step :value model :disabled disabled? :on-change (handler-fn (on-change (js/Number (-> event .-target .-value))))} attr)]])) ;; ------------------------------------------------------------------------------------ ;; Component: progress-bar ;; ------------------------------------------------------------------------------------ (def progress-bar-args-desc [{:name :model :required true :type "double | string | atom" :validate-fn number-or-string? :description "current value of the slider. A number between 0 and 100"} {:name :width :required false :default "100%" :type "string" :validate-fn string? :description "a CSS width"} {:name :striped? :required false :default false :type "boolean" :description "when true, the progress section is a set of animated stripes"} {:name :bar-class :required false :type "string" :validate-fn string? :description "CSS class name(s) for the actual progress bar itself, space separated"} {:name :class :required false :type "string" :validate-fn string? :description "CSS class names, space separated (applies to the progress-bar, not the wrapping div)"} {:name :style :required false :type "CSS style map" :validate-fn css-style? :description "CSS styles to add or override (applies to the progress-bar, not the wrapping div)"} {:name :attr :required false :type "HTML attr map" :validate-fn html-attr? :description [:span "HTML attributes, like " [:code ":on-mouse-move"] [:br] "No " [:code ":class"] " or " [:code ":style"] "allowed (applies to the progress-bar, not the wrapping div)"]}]) (defn progress-bar "Render a bootstrap styled progress bar" [& {:keys [model width striped? class bar-class style attr] :or {width "100%"} :as args}] {:pre [(validate-args-macro progress-bar-args-desc args "progress-bar")]} (let [model (deref-or-value model)] [box :class "rc-progress-bar-wrapper" :align :start :child [:div (merge {:class (str "rc-progress-bar progress " class) :style (merge (flex-child-style "none") {:width width} style)} attr) [:div {:class (str "progress-bar " (when striped? "progress-bar-striped active ") bar-class) :role "progressbar" :style {:width (str model "%") :transition "none"}} ;; Default BS transitions cause the progress bar to lag behind (str model "%")]]]))
true
(ns re-com.misc (:require-macros [re-com.core :refer [handler-fn]]) (:require [re-com.util :refer [deref-or-value px]] [re-com.popover :refer [popover-tooltip]] [re-com.box :refer [h-box v-box box gap line flex-child-style align-style]] [re-com.validate :refer [input-status-type? input-status-types-list regex? string-or-hiccup? css-style? html-attr? number-or-string? string-or-atom? nillable-string-or-atom? throbber-size? throbber-sizes-list] :refer-macros [validate-args-macro]] [reagent.core :as reagent])) ;; ------------------------------------------------------------------------------------ ;; Component: throbber ;; ------------------------------------------------------------------------------------ (def throbber-args-desc [{:name :size :required false :default :regular :type "keyword" :validate-fn throbber-size? :description [:span "one of " throbber-sizes-list]} {:name :color :required false :default "#999" :type "string" :validate-fn string? :description "CSS color"} {:name :class :required false :type "string" :validate-fn string? :description "CSS class names, space separated (applies to the throbber, not the wrapping div)"} {:name :style :required false :type "CSS style map" :validate-fn css-style? :description "CSS styles to add or override (applies to the throbber, not the wrapping div)"} {:name :attr :required false :type "HTML attr map" :validate-fn html-attr? :description [:span "HTML attributes, like " [:code ":on-mouse-move"] [:br] "No " [:code ":class"] " or " [:code ":style"] "allowed (applies to the throbber, not the wrapping div)"]}]) (defn throbber "Render an animated throbber using CSS" [& {:keys [size color class style attr] :as args}] {:pre [(validate-args-macro throbber-args-desc args "throbber")]} (let [seg (fn [] [:li (when color {:style {:background-color color}})])] [box :class "rc-throbber-wrapper" :align :start :child [:ul (merge {:class (str "rc-throbber loader " (case size :regular "" :smaller "smaller " :small "small " :large "large " "") class) :style style} attr) [seg] [seg] [seg] [seg] [seg] [seg] [seg] [seg]]])) ;; Each :li element in [seg] represents one of the eight circles in the throbber ;; ------------------------------------------------------------------------------------ ;; Component: input-text ;; ------------------------------------------------------------------------------------ (def input-text-args-desc [{:name :model :required true :type "string/nil | atom" :validate-fn nillable-string-or-atom? :description "text of the input (can be atom or value/nil)"} {:name :on-change :required true :type "string -> nil" :validate-fn fn? :description [:span [:code ":change-on-blur?"] " controls when it is called. Passed the current input string"]} {:name :status :required false :type "keyword" :validate-fn input-status-type? :description [:span "validation status. " [:code "nil/omitted"] " for normal status or one of: " input-status-types-list]} {:name :status-icon? :required false :default false :type "boolean" :description [:span "when true, display an icon to match " [:code ":status"] " (no icon for nil)"]} {:name :status-tooltip :required false :type "string" :validate-fn string? :description "displayed in status icon's tooltip"} {:name :placeholder :required false :type "string" :validate-fn string? :description "background text shown when empty"} {:name :width :required false :default "250px" :type "string" :validate-fn string? :description "standard CSS width setting for this input"} {:name :height :required false :type "string" :validate-fn string? :description "standard CSS height setting for this input"} {:name :rows :required false :default 3 :type "integer | string" :validate-fn number-or-string? :description "ONLY applies to 'input-textarea': the number of rows of text to show"} {:name :change-on-blur? :required false :default true :type "boolean | atom" :description [:span "when true, invoke " [:code ":on-change"] " function on blur, otherwise on every change (character by character)"]} {:name :on-alter :required false :type "string -> string" :validate-fn fn? :description "called with the new value to alter it immediately"} {:name :validation-regex :required false :type "regex" :validate-fn regex? :description "user input is only accepted if it would result in a string that matches this regular expression"} {:name :disabled? :required false :default false :type "boolean | atom" :description "if true, the user can't interact (input anything)"} {:name :class :required false :type "string" :validate-fn string? :description "CSS class names, space separated (applies to the textbox, not the wrapping div)"} {:name :style :required false :type "CSS style map" :validate-fn css-style? :description "CSS styles to add or override (applies to the textbox, not the wrapping div)"} {:name :attr :required false :type "HTML attr map" :validate-fn html-attr? :description [:span "HTML attributes, like " [:code ":on-mouse-move"] [:br] "No " [:code ":class"] " or " [:code ":style"] "allowed (applies to the textbox, not the wrapping div)"]} {:name :input-type :required false :type "keyword" :validate-fn keyword? :description [:span "ONLY applies to super function 'base-input-text': either " [:code ":input"] ", " [:code ":password"] " or " [:code ":textarea"]]}]) ;; Sample regex's: ;; - #"^(-{0,1})(\d*)$" ;; Signed integer ;; - #"^(\d{0,2})$|^(\d{0,2}\.\d{0,1})$" ;; Specific numeric value ##.# ;; - #"^.{0,8}$" ;; 8 chars max ;; - #"^[0-9a-fA-F]*$" ;; Hex number ;; - #"^(\d{0,2})()()$|^(\d{0,1})(:{0,1})(\d{0,2})$|^(\d{0,2})(:{0,1})(\d{0,2})$" ;; Time input (defn- input-text-base "Returns markup for a basic text input label" [& {:keys [model input-type] :as args}] {:pre [(validate-args-macro input-text-args-desc args "input-text")]} (let [external-model (reagent/atom (deref-or-value model)) ;; Holds the last known external value of model, to detect external model changes internal-model (reagent/atom (if (nil? @external-model) "" @external-model))] ;; Create a new atom from the model to be used internally (avoid nil) (fn [& {:keys [model on-change status status-icon? status-tooltip placeholder width height rows change-on-blur? on-alter validation-regex disabled? class style attr] :or {change-on-blur? true, on-alter identity} :as args}] {:pre [(validate-args-macro input-text-args-desc args "input-text")]} (let [latest-ext-model (deref-or-value model) disabled? (deref-or-value disabled?) change-on-blur? (deref-or-value change-on-blur?) showing? (reagent/atom false)] (when (not= @external-model latest-ext-model) ;; Has model changed externally? (reset! external-model latest-ext-model) (reset! internal-model latest-ext-model)) [h-box :class "rc-input-text " :align :start :width (if width width "250px") :children [[:div {:class (str "rc-input-text-inner " ;; form-group (case status :success "has-success " :warning "has-warning " :error "has-error " "") (when (and status status-icon?) "has-feedback")) :style (flex-child-style "auto")} [(if (= input-type :password) :input input-type) (merge {:class (str "form-control " class) :type (case input-type :input "text" :password "PI:PASSWORD:<PASSWORD>END_PI" nil) :rows (when (= input-type :textarea) (or rows 3)) :style (merge (flex-child-style "none") {:height height :padding-right "12px"} ;; override for when icon exists style) :placeholder placeholder :value @internal-model :disabled disabled? :on-change (handler-fn (let [new-val-orig (-> event .-target .-value) new-val (on-alter new-val-orig)] (when (not= new-val new-val-orig) (set! (-> event .-target .-value) new-val)) (when (and on-change (not disabled?) (if validation-regex (re-find validation-regex new-val) true)) (reset! internal-model new-val) (when-not change-on-blur? (reset! external-model @internal-model) (on-change @internal-model))))) :on-blur (handler-fn (when (and on-change change-on-blur? (not= @internal-model @external-model)) (reset! external-model @internal-model) (on-change @internal-model))) :on-key-up (handler-fn (if disabled? (.preventDefault event) (case (.-which event) 13 (when on-change (reset! external-model @internal-model) (on-change @internal-model)) 27 (reset! internal-model @external-model) true)))} attr)]] (when (and status-icon? status) (let [icon-class (case status :success "zmdi-check-circle" :warning "zmdi-alert-triangle" :error "zmdi-alert-circle zmdi-spinner" :validating "zmdi-hc-spin zmdi-rotate-right zmdi-spinner")] (if status-tooltip [popover-tooltip :label status-tooltip :position :right-center :status status ;:width "200px" :showing? showing? :anchor (if (= :validating status) [throbber :size :regular :class "smaller" :attr {:on-mouse-over (handler-fn (when (and status-icon? status) (reset! showing? true))) :on-mouse-out (handler-fn (reset! showing? false))}] [:i {:class (str "zmdi zmdi-hc-fw " icon-class " form-control-feedback") :style {:position "static" :height "auto" :opacity (if (and status-icon? status) "1" "0")} :on-mouse-over (handler-fn (when (and status-icon? status) (reset! showing? true))) :on-mouse-out (handler-fn (reset! showing? false))}]) :style (merge (flex-child-style "none") (align-style :align-self :center) {:font-size "130%" :margin-left "4px"})] (if (= :validating status) [throbber :size :regular :class "smaller"] [:i {:class (str "zmdi zmdi-hc-fw " icon-class " form-control-feedback") :style (merge (flex-child-style "none") (align-style :align-self :center) {:position "static" :font-size "130%" :margin-left "4px" :opacity (if (and status-icon? status) "1" "0") :height "auto"}) :title status-tooltip}]))))]])))) (defn input-text [& args] (apply input-text-base :input-type :input args)) (defn input-password [& args] (apply input-text-base :input-type :password args)) (defn input-textarea [& args] (apply input-text-base :input-type :textarea args)) ;; ------------------------------------------------------------------------------------ ;; Component: checkbox ;; ------------------------------------------------------------------------------------ (def checkbox-args-desc [{:name :model :required true :type "boolean | atom" :description "holds state of the checkbox when it is called"} {:name :on-change :required true :type "boolean -> nil" :validate-fn fn? :description "called when the checkbox is clicked. Passed the new value of the checkbox"} {:name :label :required false :type "string | hiccup" :validate-fn string-or-hiccup? :description "the label shown to the right"} {:name :disabled? :required false :default false :type "boolean | atom" :description "if true, user interaction is disabled"} {:name :label-class :required false :type "string" :validate-fn string? :description "CSS class names (applies to the label)"} {:name :label-style :required false :type "CSS style map" :validate-fn css-style? :description "CSS style map (applies to the label)"} {:name :class :required false :type "string" :validate-fn string? :description "CSS class names, space separated (applies to the checkbox, not the wrapping div)"} {:name :style :required false :type "CSS style map" :validate-fn css-style? :description "CSS style map (applies to the checkbox, not the wrapping div)"} {:name :attr :required false :type "HTML attr map" :validate-fn html-attr? :description [:span "HTML attributes, like " [:code ":on-mouse-move"] [:br] "No " [:code ":class"] " or " [:code ":style"] "allowed (applies to the checkbox, not the wrapping div)"]}]) ;; TODO: when disabled?, should the text appear "disabled". (defn checkbox "I return the markup for a checkbox, with an optional RHS label" [& {:keys [model on-change label disabled? label-class label-style class style attr] :as args}] {:pre [(validate-args-macro checkbox-args-desc args "checkbox")]} (let [cursor "default" model (deref-or-value model) disabled? (deref-or-value disabled?) callback-fn #(when (and on-change (not disabled?)) (on-change (not model)))] ;; call on-change with either true or false [h-box :class "rc-checkbox-wrapper noselect" :align :start :children [[:input (merge {:class (str "rc-checkbox " class) :type "checkbox" :style (merge (flex-child-style "none") {:cursor cursor} style) :disabled disabled? :checked (boolean model) :on-change (handler-fn (callback-fn))} attr)] (when label [:span {:class label-class :style (merge (flex-child-style "none") {:padding-left "8px" :cursor cursor} label-style) :on-click (handler-fn (callback-fn))} label])]])) ;; ------------------------------------------------------------------------------------ ;; Component: radio-button ;; ------------------------------------------------------------------------------------ (def radio-button-args-desc [{:name :model :required true :type "anything | atom" :description [:span "selected value of the radio button group. See also " [:code ":value"]]} {:name :value :required false :type "anything" :description [:span "if " [:code ":model"] " equals " [:code ":value"] " then this radio button is selected"]} {:name :on-change :required true :type "anything -> nil" :validate-fn fn? :description [:span "called when the radio button is clicked. Passed " [:code ":value"]]} {:name :label :required false :type "string | hiccup" :validate-fn string-or-hiccup? :description "the label shown to the right"} {:name :disabled? :required false :default false :type "boolean | atom" :description "if true, the user can't click the radio button"} {:name :label-class :required false :type "string" :validate-fn string? :description "CSS class names (applies to the label)"} {:name :label-style :required false :type "CSS style map" :validate-fn css-style? :description "CSS style map (applies to the label)"} {:name :class :required false :type "string" :validate-fn string? :description "CSS class names, space separated (applies to the radio-button, not the wrapping div)"} {:name :style :required false :type "CSS style map" :validate-fn css-style? :description "CSS style map (applies to the radio-button, not the wrapping div)"} {:name :attr :required false :type "HTML attr map" :validate-fn html-attr? :description [:span "HTML attributes, like " [:code ":on-mouse-move"] [:br] "No " [:code ":class"] " or " [:code ":style"] "allowed (applies to the radio-button, not the wrapping div)"]}]) (defn radio-button "I return the markup for a radio button, with an optional RHS label" [& {:keys [model value on-change label disabled? label-class label-style class style attr] :as args}] {:pre [(validate-args-macro radio-button-args-desc args "radio-button")]} (let [cursor "default" model (deref-or-value model) disabled? (deref-or-value disabled?) callback-fn #(when (and on-change (not disabled?)) (on-change value))] ;; call on-change with the :value arg [h-box :class "rc-radio-button-wrapper noselect" :align :start :children [[:input (merge {:class (str "rc-radio-button " class) :style (merge (flex-child-style "none") {:cursor cursor} style) :type "radio" :disabled disabled? :checked (= model value) :on-change (handler-fn (callback-fn))} attr)] (when label [:span {:class label-class :style (merge (flex-child-style "none") {:padding-left "8px" :cursor cursor} label-style) :on-click (handler-fn (callback-fn))} label])]])) ;; ------------------------------------------------------------------------------------ ;; Component: slider ;; ------------------------------------------------------------------------------------ (def slider-args-desc [{:name :model :required true :type "double | string | atom" :validate-fn number-or-string? :description "current value of the slider"} {:name :on-change :required true :type "double -> nil" :validate-fn fn? :description "called when the slider is moved. Passed the new value of the slider"} {:name :min :required false :default 0 :type "double | string | atom" :validate-fn number-or-string? :description "the minimum value of the slider"} {:name :max :required false :default 100 :type "double | string | atom" :validate-fn number-or-string? :description "the maximum value of the slider"} {:name :step :required false :default 1 :type "double | string | atom" :validate-fn number-or-string? :description "step value between min and max"} {:name :width :required false :default "400px" :type "string" :validate-fn string? :description "standard CSS width setting for the slider"} {:name :disabled? :required false :default false :type "boolean | atom" :description "if true, the user can't change the slider"} {:name :class :required false :type "string" :validate-fn string? :description "CSS class names, space separated (applies to the slider, not the wrapping div)"} {:name :style :required false :type "CSS style map" :validate-fn css-style? :description "CSS styles to add or override (applies to the slider, not the wrapping div)"} {:name :attr :required false :type "HTML attr map" :validate-fn html-attr? :description [:span "HTML attributes, like " [:code ":on-mouse-move"] [:br] "No " [:code ":class"] " or " [:code ":style"] "allowed (applies to the slider, not the wrapping div)"]}]) (defn slider "Returns markup for an HTML5 slider input" [& {:keys [model min max step width on-change disabled? class style attr] :or {min 0 max 100} :as args}] {:pre [(validate-args-macro slider-args-desc args "slider")]} (let [model (deref-or-value model) min (deref-or-value min) max (deref-or-value max) step (deref-or-value step) disabled? (deref-or-value disabled?)] [box :class "rc-slider-wrapper" :align :start :child [:input (merge {:class (str "rc-slider " class) :type "range" ;:orient "vertical" ;; Make Firefox slider vertical (doesn't work because React ignores it, I think) :style (merge (flex-child-style "none") {;:-webkit-appearance "slider-vertical" ;; TODO: Make a :orientation (:horizontal/:vertical) option ;:writing-mode "bt-lr" ;; Make IE slider vertical :width (or width "400px") :cursor (if disabled? "default" "pointer")} style) :min min :max max :step step :value model :disabled disabled? :on-change (handler-fn (on-change (js/Number (-> event .-target .-value))))} attr)]])) ;; ------------------------------------------------------------------------------------ ;; Component: progress-bar ;; ------------------------------------------------------------------------------------ (def progress-bar-args-desc [{:name :model :required true :type "double | string | atom" :validate-fn number-or-string? :description "current value of the slider. A number between 0 and 100"} {:name :width :required false :default "100%" :type "string" :validate-fn string? :description "a CSS width"} {:name :striped? :required false :default false :type "boolean" :description "when true, the progress section is a set of animated stripes"} {:name :bar-class :required false :type "string" :validate-fn string? :description "CSS class name(s) for the actual progress bar itself, space separated"} {:name :class :required false :type "string" :validate-fn string? :description "CSS class names, space separated (applies to the progress-bar, not the wrapping div)"} {:name :style :required false :type "CSS style map" :validate-fn css-style? :description "CSS styles to add or override (applies to the progress-bar, not the wrapping div)"} {:name :attr :required false :type "HTML attr map" :validate-fn html-attr? :description [:span "HTML attributes, like " [:code ":on-mouse-move"] [:br] "No " [:code ":class"] " or " [:code ":style"] "allowed (applies to the progress-bar, not the wrapping div)"]}]) (defn progress-bar "Render a bootstrap styled progress bar" [& {:keys [model width striped? class bar-class style attr] :or {width "100%"} :as args}] {:pre [(validate-args-macro progress-bar-args-desc args "progress-bar")]} (let [model (deref-or-value model)] [box :class "rc-progress-bar-wrapper" :align :start :child [:div (merge {:class (str "rc-progress-bar progress " class) :style (merge (flex-child-style "none") {:width width} style)} attr) [:div {:class (str "progress-bar " (when striped? "progress-bar-striped active ") bar-class) :role "progressbar" :style {:width (str model "%") :transition "none"}} ;; Default BS transitions cause the progress bar to lag behind (str model "%")]]]))
[ { "context": "il dispatch value and in signatures.\"\n :author \"palisades dot lakes at gmail dot com\"\n :version \"2017-12-13\"}\n (:require [clojure.t", "end": 280, "score": 0.8985888957977295, "start": 244, "tag": "EMAIL", "value": "palisades dot lakes at gmail dot com" } ]
src/test/clojure/palisades/lakes/dynafun/test/nil.clj
palisades-lakes/dynamic-functions
3
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.dynafun.test.nil {:doc "Test nil dispatch value and in signatures." :author "palisades dot lakes at gmail dot com" :version "2017-12-13"} (:require [clojure.test :as test] [palisades.lakes.dynafun.core :as d]) (:import [java.util Collection] [clojure.lang IFn])) ;; mvn clojure:test -Dtest=palisades.lakes.multimethods.test.nil ;;---------------------------------------------------------------- (test/deftest class0 (d/dynafun count0 {}) (d/defmethod count0 [^{:tag nil} x] 0) (d/defmethod count0 [^Collection x] (.size x)) (test/is (== 0 (count0 nil))) (test/is (== 0 (count0 []))) (test/is (== 2 (count0 [:a :b])))) ;;---------------------------------------------------------------- (defn- square (^long [^long x] (* x x)) ([^long x ^long y] [(* x x) (* y y)]) ([^long x ^long y ^long z] [(* x x) (* y y) (* z z)])) ;;---------------------------------------------------------------- (test/deftest signature0 (d/dynafun map0 {}) (d/defmethod map0 [^{:tag nil} f ^{:tag nil} x0] nil) (d/defmethod map0 [^IFn _ ^{:tag nil} _] nil) (d/defmethod map0 [^{:tag nil} _ ^Collection _] nil) (d/defmethod map0 [^IFn f ^Collection x0] (mapv f x0)) (d/defmethod map0 [^IFn f ^Collection x0 ^Collection x1] (mapv f x0 x1)) (d/defmethod map0 [^IFn _ ^{:tag nil} _ ^Collection _] nil) (d/defmethod map0 [^IFn _ ^Collection _ ^{:tag nil} _] nil) (d/defmethod map0 [^{:tag nil} _ ^{:tag nil} _ ^Collection _] nil) (d/defmethod map0 [^IFn _ ^{:tag nil} _ ^{:tag nil} _] nil) (d/defmethod map0 [^{:tag nil} _ ^{:tag nil} _ ^{:tag nil} _] nil) ;; Doesn't support arity > 3 yet #_(d/defmethod map0 [^IFn f ^Collection x0 ^Collection x1 ^Collection x2] (mapv f x0 x1 x2)) #_(d/defmethod map0 [^IFn f ^{:tag nil} x0 ^Collection x1 ^Collection x2] nil) #_(d/defmethod map0 [^{:tag nil} f ^Collection x0 ^Collection x1 ^Collection x2] nil) #_(d/defmethod map0 [^IFn f ^Collection x0 ^{:tag nil} x1 ^Collection x2] nil) #_(d/defmethod map0 [^IFn f ^{:tag nil} x0 ^{:tag nil} x1 ^Collection x2] nil) #_(d/defmethod map0 [^IFn f ^{:tag nil} x0 ^{:tag nil} x1 ^{:tag nil} x2] nil) #_(d/defmethod map0 [^{:tag nil} f ^{:tag nil} x0 ^{:tag nil} x1 ^{:tag nil} x2] nil) (test/is (nil? (map0 square nil))) (test/is (nil? (map0 nil nil))) (test/is (nil? (map0 square nil [2 4]))) (test/is (nil? (map0 nil nil [3 5]))) (test/is (nil? (map0 nil nil nil))) (test/is (nil? (map0 square nil nil))) (test/is (nil? (map0 square nil [2 4]))) (test/is (= [[1 4][4 16]] (map0 square [1 2] [2 4]))) #_(test/is (nil? (map0 nil [1 2] [2 4] [3 5]))) #_(test/is (nil? (map0 nil nil nil nil))) #_(test/is (nil? (map0 square nil nil [3 5]))) #_(test/is (= [[1 4 9][4 16 25]] (map0 square [1 2] [2 4] [3 5]))) ) ;;----------------------------------------------------------------
55630
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.dynafun.test.nil {:doc "Test nil dispatch value and in signatures." :author "<EMAIL>" :version "2017-12-13"} (:require [clojure.test :as test] [palisades.lakes.dynafun.core :as d]) (:import [java.util Collection] [clojure.lang IFn])) ;; mvn clojure:test -Dtest=palisades.lakes.multimethods.test.nil ;;---------------------------------------------------------------- (test/deftest class0 (d/dynafun count0 {}) (d/defmethod count0 [^{:tag nil} x] 0) (d/defmethod count0 [^Collection x] (.size x)) (test/is (== 0 (count0 nil))) (test/is (== 0 (count0 []))) (test/is (== 2 (count0 [:a :b])))) ;;---------------------------------------------------------------- (defn- square (^long [^long x] (* x x)) ([^long x ^long y] [(* x x) (* y y)]) ([^long x ^long y ^long z] [(* x x) (* y y) (* z z)])) ;;---------------------------------------------------------------- (test/deftest signature0 (d/dynafun map0 {}) (d/defmethod map0 [^{:tag nil} f ^{:tag nil} x0] nil) (d/defmethod map0 [^IFn _ ^{:tag nil} _] nil) (d/defmethod map0 [^{:tag nil} _ ^Collection _] nil) (d/defmethod map0 [^IFn f ^Collection x0] (mapv f x0)) (d/defmethod map0 [^IFn f ^Collection x0 ^Collection x1] (mapv f x0 x1)) (d/defmethod map0 [^IFn _ ^{:tag nil} _ ^Collection _] nil) (d/defmethod map0 [^IFn _ ^Collection _ ^{:tag nil} _] nil) (d/defmethod map0 [^{:tag nil} _ ^{:tag nil} _ ^Collection _] nil) (d/defmethod map0 [^IFn _ ^{:tag nil} _ ^{:tag nil} _] nil) (d/defmethod map0 [^{:tag nil} _ ^{:tag nil} _ ^{:tag nil} _] nil) ;; Doesn't support arity > 3 yet #_(d/defmethod map0 [^IFn f ^Collection x0 ^Collection x1 ^Collection x2] (mapv f x0 x1 x2)) #_(d/defmethod map0 [^IFn f ^{:tag nil} x0 ^Collection x1 ^Collection x2] nil) #_(d/defmethod map0 [^{:tag nil} f ^Collection x0 ^Collection x1 ^Collection x2] nil) #_(d/defmethod map0 [^IFn f ^Collection x0 ^{:tag nil} x1 ^Collection x2] nil) #_(d/defmethod map0 [^IFn f ^{:tag nil} x0 ^{:tag nil} x1 ^Collection x2] nil) #_(d/defmethod map0 [^IFn f ^{:tag nil} x0 ^{:tag nil} x1 ^{:tag nil} x2] nil) #_(d/defmethod map0 [^{:tag nil} f ^{:tag nil} x0 ^{:tag nil} x1 ^{:tag nil} x2] nil) (test/is (nil? (map0 square nil))) (test/is (nil? (map0 nil nil))) (test/is (nil? (map0 square nil [2 4]))) (test/is (nil? (map0 nil nil [3 5]))) (test/is (nil? (map0 nil nil nil))) (test/is (nil? (map0 square nil nil))) (test/is (nil? (map0 square nil [2 4]))) (test/is (= [[1 4][4 16]] (map0 square [1 2] [2 4]))) #_(test/is (nil? (map0 nil [1 2] [2 4] [3 5]))) #_(test/is (nil? (map0 nil nil nil nil))) #_(test/is (nil? (map0 square nil nil [3 5]))) #_(test/is (= [[1 4 9][4 16 25]] (map0 square [1 2] [2 4] [3 5]))) ) ;;----------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.dynafun.test.nil {:doc "Test nil dispatch value and in signatures." :author "PI:EMAIL:<EMAIL>END_PI" :version "2017-12-13"} (:require [clojure.test :as test] [palisades.lakes.dynafun.core :as d]) (:import [java.util Collection] [clojure.lang IFn])) ;; mvn clojure:test -Dtest=palisades.lakes.multimethods.test.nil ;;---------------------------------------------------------------- (test/deftest class0 (d/dynafun count0 {}) (d/defmethod count0 [^{:tag nil} x] 0) (d/defmethod count0 [^Collection x] (.size x)) (test/is (== 0 (count0 nil))) (test/is (== 0 (count0 []))) (test/is (== 2 (count0 [:a :b])))) ;;---------------------------------------------------------------- (defn- square (^long [^long x] (* x x)) ([^long x ^long y] [(* x x) (* y y)]) ([^long x ^long y ^long z] [(* x x) (* y y) (* z z)])) ;;---------------------------------------------------------------- (test/deftest signature0 (d/dynafun map0 {}) (d/defmethod map0 [^{:tag nil} f ^{:tag nil} x0] nil) (d/defmethod map0 [^IFn _ ^{:tag nil} _] nil) (d/defmethod map0 [^{:tag nil} _ ^Collection _] nil) (d/defmethod map0 [^IFn f ^Collection x0] (mapv f x0)) (d/defmethod map0 [^IFn f ^Collection x0 ^Collection x1] (mapv f x0 x1)) (d/defmethod map0 [^IFn _ ^{:tag nil} _ ^Collection _] nil) (d/defmethod map0 [^IFn _ ^Collection _ ^{:tag nil} _] nil) (d/defmethod map0 [^{:tag nil} _ ^{:tag nil} _ ^Collection _] nil) (d/defmethod map0 [^IFn _ ^{:tag nil} _ ^{:tag nil} _] nil) (d/defmethod map0 [^{:tag nil} _ ^{:tag nil} _ ^{:tag nil} _] nil) ;; Doesn't support arity > 3 yet #_(d/defmethod map0 [^IFn f ^Collection x0 ^Collection x1 ^Collection x2] (mapv f x0 x1 x2)) #_(d/defmethod map0 [^IFn f ^{:tag nil} x0 ^Collection x1 ^Collection x2] nil) #_(d/defmethod map0 [^{:tag nil} f ^Collection x0 ^Collection x1 ^Collection x2] nil) #_(d/defmethod map0 [^IFn f ^Collection x0 ^{:tag nil} x1 ^Collection x2] nil) #_(d/defmethod map0 [^IFn f ^{:tag nil} x0 ^{:tag nil} x1 ^Collection x2] nil) #_(d/defmethod map0 [^IFn f ^{:tag nil} x0 ^{:tag nil} x1 ^{:tag nil} x2] nil) #_(d/defmethod map0 [^{:tag nil} f ^{:tag nil} x0 ^{:tag nil} x1 ^{:tag nil} x2] nil) (test/is (nil? (map0 square nil))) (test/is (nil? (map0 nil nil))) (test/is (nil? (map0 square nil [2 4]))) (test/is (nil? (map0 nil nil [3 5]))) (test/is (nil? (map0 nil nil nil))) (test/is (nil? (map0 square nil nil))) (test/is (nil? (map0 square nil [2 4]))) (test/is (= [[1 4][4 16]] (map0 square [1 2] [2 4]))) #_(test/is (nil? (map0 nil [1 2] [2 4] [3 5]))) #_(test/is (nil? (map0 nil nil nil nil))) #_(test/is (nil? (map0 square nil nil [3 5]))) #_(test/is (= [[1 4 9][4 16 25]] (map0 square [1 2] [2 4] [3 5]))) ) ;;----------------------------------------------------------------
[ { "context": ";;Copyright (c) 2017 Rafik Naccache <rafik@fekr.tech>\n;;Distributed under the MIT Lic", "end": 35, "score": 0.999866783618927, "start": 21, "tag": "NAME", "value": "Rafik Naccache" }, { "context": ";;Copyright (c) 2017 Rafik Naccache <rafik@fekr.tech>\n;;Distributed under the MIT License\n(ns postagga", "end": 52, "score": 0.9999321103096008, "start": 37, "tag": "EMAIL", "value": "rafik@fekr.tech" } ]
test/postagga/trie_test.cljc
jffrydsr/postagga
93
;;Copyright (c) 2017 Rafik Naccache <rafik@fekr.tech> ;;Distributed under the MIT License (ns postagga.trie-test (:require [clojure.test :refer :all] [postagga.trie :refer :all])) (deftest build-trie-test (testing "Build Trie") (is (= {} (build-trie []))) (is (= {"h" {:nb 1, :next {"e" {:nb 1, :next {"l" {:nb 1, :next {"l" {:nb 1, :next {"o" {:nb 1, :end true}}}}}}}}}} (build-trie ["hello"]))) (is (= {"h" {:nb 2, :next {"e" {:nb 2, :next {"l" {:nb 2, :next {"l" {:nb 1, :next {"o" {:nb 1, :end true}}} "p" {:nb 1, :end true}}}}}}}} (build-trie ["hello","help"]))) (is (= {"h" {:nb 2, :next {"e" {:nb 2, :next {"l" {:nb 2, :next {"l" {:nb 2, :end true, :next {"o" {:nb 1, :end true}}} }}}}}}} (build-trie ["hello","hell"])))) (deftest completions-test (testing "Completsions") (let [trie (build-trie [])] (is (= nil (completions trie nil))) ; TODO: maybe it would be better if result was [] (is (= nil (completions trie ""))) ; TODO: maybe it would be better if result was [] (is (= nil (completions trie "hello")))) ; TODO: maybe it would be better if result was [] (let [trie (build-trie ["hello"])] (is (= ["hello"] (completions trie nil))) (is (= ["hello"] (completions trie ""))) (is (= ["hello"] (completions trie "h"))) (is (= ["hello"] (completions trie "he"))) (is (= ["hello"] (completions trie "hel"))) (is (= ["hello"] (completions trie "hell"))) (is (= nil (completions trie "hello"))) ; TODO: maybe this should be ["hello"]? (Or at leat []) (is (= nil (completions trie "world")))) ; TODO: maybe [] would be better... (let [trie (build-trie ["hello" "hell" "help"])] (is (= ["hell" "help" "hello"] (completions trie nil))) (is (= ["hell" "help" "hello"] (completions trie ""))) (is (= ["hell" "help" "hello"] (completions trie "h"))) (is (= ["hell" "help" "hello"] (completions trie "he"))) (is (= ["hell" "help" "hello"] (completions trie "hel"))) (is (= ["hello"] (completions trie "hell"))) ; TODO: maybe "hell" should be included too (is (= nil (completions trie "hello"))) ; TODO: maybe this should be ["hello"]? (Or at leat []) (is (= nil (completions trie "world")))) ; TODO: maybe [] would be better... (let [trie (build-trie ["hello" "world"])] (is (= ["world" "hello"] (completions trie nil))) (is (= ["world"] (completions trie "wo")))))
115522
;;Copyright (c) 2017 <NAME> <<EMAIL>> ;;Distributed under the MIT License (ns postagga.trie-test (:require [clojure.test :refer :all] [postagga.trie :refer :all])) (deftest build-trie-test (testing "Build Trie") (is (= {} (build-trie []))) (is (= {"h" {:nb 1, :next {"e" {:nb 1, :next {"l" {:nb 1, :next {"l" {:nb 1, :next {"o" {:nb 1, :end true}}}}}}}}}} (build-trie ["hello"]))) (is (= {"h" {:nb 2, :next {"e" {:nb 2, :next {"l" {:nb 2, :next {"l" {:nb 1, :next {"o" {:nb 1, :end true}}} "p" {:nb 1, :end true}}}}}}}} (build-trie ["hello","help"]))) (is (= {"h" {:nb 2, :next {"e" {:nb 2, :next {"l" {:nb 2, :next {"l" {:nb 2, :end true, :next {"o" {:nb 1, :end true}}} }}}}}}} (build-trie ["hello","hell"])))) (deftest completions-test (testing "Completsions") (let [trie (build-trie [])] (is (= nil (completions trie nil))) ; TODO: maybe it would be better if result was [] (is (= nil (completions trie ""))) ; TODO: maybe it would be better if result was [] (is (= nil (completions trie "hello")))) ; TODO: maybe it would be better if result was [] (let [trie (build-trie ["hello"])] (is (= ["hello"] (completions trie nil))) (is (= ["hello"] (completions trie ""))) (is (= ["hello"] (completions trie "h"))) (is (= ["hello"] (completions trie "he"))) (is (= ["hello"] (completions trie "hel"))) (is (= ["hello"] (completions trie "hell"))) (is (= nil (completions trie "hello"))) ; TODO: maybe this should be ["hello"]? (Or at leat []) (is (= nil (completions trie "world")))) ; TODO: maybe [] would be better... (let [trie (build-trie ["hello" "hell" "help"])] (is (= ["hell" "help" "hello"] (completions trie nil))) (is (= ["hell" "help" "hello"] (completions trie ""))) (is (= ["hell" "help" "hello"] (completions trie "h"))) (is (= ["hell" "help" "hello"] (completions trie "he"))) (is (= ["hell" "help" "hello"] (completions trie "hel"))) (is (= ["hello"] (completions trie "hell"))) ; TODO: maybe "hell" should be included too (is (= nil (completions trie "hello"))) ; TODO: maybe this should be ["hello"]? (Or at leat []) (is (= nil (completions trie "world")))) ; TODO: maybe [] would be better... (let [trie (build-trie ["hello" "world"])] (is (= ["world" "hello"] (completions trie nil))) (is (= ["world"] (completions trie "wo")))))
true
;;Copyright (c) 2017 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ;;Distributed under the MIT License (ns postagga.trie-test (:require [clojure.test :refer :all] [postagga.trie :refer :all])) (deftest build-trie-test (testing "Build Trie") (is (= {} (build-trie []))) (is (= {"h" {:nb 1, :next {"e" {:nb 1, :next {"l" {:nb 1, :next {"l" {:nb 1, :next {"o" {:nb 1, :end true}}}}}}}}}} (build-trie ["hello"]))) (is (= {"h" {:nb 2, :next {"e" {:nb 2, :next {"l" {:nb 2, :next {"l" {:nb 1, :next {"o" {:nb 1, :end true}}} "p" {:nb 1, :end true}}}}}}}} (build-trie ["hello","help"]))) (is (= {"h" {:nb 2, :next {"e" {:nb 2, :next {"l" {:nb 2, :next {"l" {:nb 2, :end true, :next {"o" {:nb 1, :end true}}} }}}}}}} (build-trie ["hello","hell"])))) (deftest completions-test (testing "Completsions") (let [trie (build-trie [])] (is (= nil (completions trie nil))) ; TODO: maybe it would be better if result was [] (is (= nil (completions trie ""))) ; TODO: maybe it would be better if result was [] (is (= nil (completions trie "hello")))) ; TODO: maybe it would be better if result was [] (let [trie (build-trie ["hello"])] (is (= ["hello"] (completions trie nil))) (is (= ["hello"] (completions trie ""))) (is (= ["hello"] (completions trie "h"))) (is (= ["hello"] (completions trie "he"))) (is (= ["hello"] (completions trie "hel"))) (is (= ["hello"] (completions trie "hell"))) (is (= nil (completions trie "hello"))) ; TODO: maybe this should be ["hello"]? (Or at leat []) (is (= nil (completions trie "world")))) ; TODO: maybe [] would be better... (let [trie (build-trie ["hello" "hell" "help"])] (is (= ["hell" "help" "hello"] (completions trie nil))) (is (= ["hell" "help" "hello"] (completions trie ""))) (is (= ["hell" "help" "hello"] (completions trie "h"))) (is (= ["hell" "help" "hello"] (completions trie "he"))) (is (= ["hell" "help" "hello"] (completions trie "hel"))) (is (= ["hello"] (completions trie "hell"))) ; TODO: maybe "hell" should be included too (is (= nil (completions trie "hello"))) ; TODO: maybe this should be ["hello"]? (Or at leat []) (is (= nil (completions trie "world")))) ; TODO: maybe [] would be better... (let [trie (build-trie ["hello" "world"])] (is (= ["world" "hello"] (completions trie nil))) (is (= ["world"] (completions trie "wo")))))
[ { "context": ", so I would\n advise you read [1] first.\n\n [1] Falkenhainer, B., Forbus, K. & Gentner, D. (1989). The structure-ma", "end": 1546, "score": 0.9991666078567505, "start": 1531, "tag": "NAME", "value": "Falkenhainer, B" }, { "context": "ise you read [1] first.\n\n [1] Falkenhainer, B., Forbus, K. & Gentner, D. (1989). The structure-mapping\n ", "end": 1558, "score": 0.99853515625, "start": 1549, "tag": "NAME", "value": "Forbus, K" }, { "context": "[1] first.\n\n [1] Falkenhainer, B., Forbus, K. & Gentner, D. (1989). The structure-mapping\n engine: ", "end": 1572, "score": 0.9989757537841797, "start": 1562, "tag": "NAME", "value": "Gentner, D" } ]
src/sme_clj/core.clj
svdm/SME-clj
6
(ns sme-clj.core "Structure mapping engine core functionality. Reimplements SME (as described in [1]) for the most part, in Clojure instead of (rather ancient and difficult to read) Common Lisp. There are some differences in certain areas, such as GMap merging and scoring. It is also likely to be slower, as it has not been profiled or optimised at all. The main differences: - GMap merging differs in two of the steps, but results should be more complete than the original algorithm, if they differ at all. - Inference generation has some limitations, and has not received as much development and testing as other areas (as it was not used in the research for which this SME implementation was developed). - Scoring of GMaps is much simpler. It does not use complex evidence rules in a belief maintenance system as in [1]. Instead, GMaps are scored on structure using a trickle-down algorithm that rewards large structures. The basic usage is as follows: 1. Define predicates, entities, and concept graphs using 'sme-clj.typedef. 2. Run 'sme-clj.core/match with the base and target graphs as arguments. 3. The 'match function returns the resulting GMaps. See the 'match docstring for more. Also look at the example in the sme-clj.example namespace. If you are not yet familiar with the general structure and terminology of the original SME algorithm, it will be hard to understand this stuff, so I would advise you read [1] first. [1] Falkenhainer, B., Forbus, K. & Gentner, D. (1989). The structure-mapping engine: algorithm and examples. Artificial Intelligence, 41, 1-62." (:require [clojure.set :as set] [clojure.contrib.set :as c.set] [clojure.contrib.combinatorics :as comb]) (:use sme-clj.typedef sme-clj.ruledef)) ;;;; ;;;; GENERATING MATCH HYPOTHESES ;;;; ;; Note: "mh" = match hypothesis (defn apply-filter-rules "Apply :filter rules from a ruleset to the base and target expressions. Return a set of match hypotheses." [base-expr target-expr rules] (-> (map (fn [rule] ;; map rule over every possible expression pairing (remove nil? (map #(rule (% 0) (% 1)) (for [bx base-expr, tx target-expr] [bx tx])))) (:filter rules)) flatten set)) (defn apply-intern-rules "Apply :intern rules to a set of match hypotheses generated by :filter rules, and see if new MHs are created. For every new MH, also apply the :intern rules to it. Return the resulting set of MHs." [mhs ruleset] (let [rules (:intern ruleset)] (loop [todo (seq mhs) ; treat todo as seq stack result (set mhs)] ; result as final mh set (if-let [mh (first todo)] ;; test this MH on all intern rules, adding new matches to todo list (let [matches (->> (map #(% mh) rules) flatten (remove nil?) set)] (recur (concat (next todo) matches) (set/union result matches))) ;; set of all MHs tested on intern rules result)))) (defn create-match-hypotheses "Apply rules from a ruleset to base and target to generate match hypotheses for the graphs." [base target rules] (-> (apply-filter-rules (:graph base) (:graph target) rules) (apply-intern-rules rules))) ;;;; ;;;; FORMING GMAPS ;;;; ;; The below proves useful when checking consistency and such. (defn build-hypothesis-structure "Creates a map from MHs to their structural information. So retrieving the match hypotheses is done with 'keys, while the structural info can be accessed with 'vals or 'get." [mhs] (let [add-as (fn [m k mh] (update-in m [k (k mh)] set/union #{mh})) ;; cache of base/target expressions mapped to their mh smap (reduce (fn [s mh] (-> s (add-as :base mh) (add-as :target mh))) {:base {}, :target {}} mhs) {bmap :base, tmap :target} smap] (reduce (fn build-mh-structure [structure mh] (assoc structure mh ;; initial emaps is just ourselves if we are one, for the rest ;; this will be filled later {:emaps (if (is-expression? mh) #{} #{mh}) ;; nogood is every mh mapping same target or base :nogood (-> (set/union (get bmap (:base mh) #{}) (get tmap (:target mh)) #{}) (disj mh)) ; not nogood of ourselves ;; our children are mhs that map our arguments (so children ;; does not equal our entire set of descendants) :children (if (is-expression? mh) (set (mapcat (fn [b t] (set/intersection (get bmap b #{}) (get tmap t #{}))) (expression-args (:base mh)) (expression-args (:target mh)))) #{}) })) {} mhs))) ;; For each expression without emaps, recursively add the union of its ;; children's emaps and nogoods. (defn propagate-from-emaps "Extends structural MH information of each expression without emaps by recursively adding the union of its children's emaps and nogoods to it. Essentially flows up the structural information." [mh-structure] (letfn [(propagate [mstr mh] (if (seq (:emaps (get mstr mh))) mstr (let [kids (:children (get mstr mh)) mstr-kids (reduce propagate mstr kids) kids-struct (vals (select-keys mstr-kids kids))] (update-in mstr-kids [mh] #(merge-with set/union %1 %2) {:emaps (reduce set/union (map :emaps kids-struct)) :nogood (reduce set/union (map :nogood kids-struct))}))))] (reduce propagate mh-structure (keys mh-structure)))) (defn consistent? "True if an MH is consistent, meaning none of its emaps are in its nogoods." ([{:keys [emaps nogood] :as mstr-entry}] (empty? (set/intersection emaps nogood))) ([mh mstr] (consistent? (get mstr mh)))) (defn find-roots "Returns only the root hypotheses, ie. those that are not children of any other hypothesis." [mh-structure] (let [all-children (reduce #(set/union %1 (:children %2)) #{} (vals mh-structure))] (filter #(not (contains? all-children %)) (keys mh-structure)))) (defn collect-children "Returns a set of all descendants of a root." [root mh-structure] (letfn [(collect [mh] (if (is-emap? mh) [mh] (cons mh (mapcat collect (:children (get mh-structure mh))))))] (set (collect root)))) (defn make-gmap "Returns a gmap with the root and all of its descendants." [root mh-structure] (make-GMap (collect-children root mh-structure) (merge {:roots #{root}} ;; gmap's nogoods/emaps are those of its root(s) (select-keys (get mh-structure root) [:nogood :emaps])))) (defn compute-initial-gmaps "Given match hypothesis information, builds a set of initial gmaps. Returns a map with the :mh-structure and the :gmaps set." [mh-structure] (->> (find-roots mh-structure) (reduce (fn form-gmap [gmaps root] (if (consistent? (get mh-structure root)) (conj gmaps (make-gmap root mh-structure)) (if-let [kids (seq (:children (get mh-structure root)))] (set/union gmaps (set (mapcat #(form-gmap #{} %) kids))) gmaps))) #{}) (hash-map :mh-structure mh-structure :gmaps))) (defn gmaps-consistent? "Two gmaps are consistent if none of their elements are in the NoGood set of the other." [gm-a gm-b] (and (empty? (set/intersection (:mhs gm-a) (:nogood (:structure gm-b)))) (empty? (set/intersection (:mhs gm-b) (:nogood (:structure gm-a)))))) (defn gmap-sets-consistent? "True if both collections of gmaps are fully consistent with each other." [coll-a coll-b] (every? true? (map (fn [gm-b] (every? true? (map #(gmaps-consistent? gm-b %) coll-a))) coll-b))) (defn gmap-set-internally-consistent? "True if the given set of gmaps is internally consistent." [gmap-set] (gmap-sets-consistent? gmap-set gmap-set)) ;; NOTE: SME's second merge step seems rather complex compared to its benefits. ;; Its results will already be generated in a third step we will be performing ;; that is more exhaustive than SME performs at that point. Therefore step 2 is ;; unnecessary here and we skip it. ;; The below is a very naive implementation, performance-wise. (defn combine-gmaps "Combine all gmaps in all maximal, consistent ways." [data] (let [consistent-sets (->> (comb/subsets (:gmaps data)) (remove empty?) (filter gmap-set-internally-consistent?) (map set))] (->> (remove (fn [gms-a] (some (fn [gms-b] (and (not= gms-a gms-b) (c.set/subset? gms-a gms-b))) consistent-sets)) consistent-sets) (assoc data :gmaps)))) (defn merge-gmaps "Given a collection of sets of gmaps, merges the gmaps in each set into a single gmap." [data] (letfn [(gather-gm [{:keys [mhs structure] :as total} gm] (assoc total :mhs (set/union mhs (:mhs gm)) :structure (merge-with set/union structure (:structure gm)))) (reduce-to-gm [gm-set] (let [args (reduce gather-gm {:mhs #{} :structure {}} gm-set)] (make-GMap (:mhs args) (:structure args))))] (->> (map reduce-to-gm (:gmaps data)) (assoc data :gmaps)))) (letfn [(round [n] (.setScale (bigdec n) 2 BigDecimal/ROUND_HALF_UP))] (defn emaps-equal? "Special equals function for entities that rounds floating point numbers to two decimals before comparing them, to avoid rounding errors affecting equality." [a b] (and (= (keys a) (keys b)) (every? true? (map (fn [x y] (if (and (number? x) (number? y)) (== (round x) (round y)) (= x y))) (vals a) (vals b)))))) ;; Entities may have keys that are implementation details. Bind this var to a ;; seq of those keys to ignore them in emap matching. (def unmatched-keys nil) (defn matching-emaps "Returns seq of MHs that are emaps of which the entities are equal." [{:as gmap, :keys [mhs]}] (filter #(and (is-emap? %) (emaps-equal? (apply dissoc (:base %) unmatched-keys) (apply dissoc (:target %) unmatched-keys))) mhs)) (defn score-gmap "Computes SES and emap scores for a gmap. The emap score is not in the original SME. It simply counts how many entities match in their content." [{:keys [mh-structure] :as data} gm] (letfn [(score-mh [mh depth] ;; simplified trickle-down SES (if-let [kids (seq (:children (get mh-structure mh)))] (reduce + depth (map #(score-mh % (inc depth)) kids)) depth))] (assoc gm :score (reduce + (count (:mhs gm)) (map #(score-mh % 0) (:roots (:structure gm)))) :emap-matches (count (matching-emaps gm))))) ;;; Inference generation below. Not used in TCG model. (defn gmap-inferences "Generates maximal inferences for a given gmap, based on SME algorithm." [gmap {base :graph}] (let [mh-bases (set (map :base (:mhs gmap))) unmatched (set/difference (set base) mh-bases) ancestors (set/select #(ancestor? mh-bases %) unmatched)] (set/difference (set (mapcat get-descendants ancestors)) mh-bases))) (defn generate-inferences "Appends :inferences to gmaps in given data, for a given base graph." [data base] (->> (map #(assoc % :inferences (gmap-inferences % base)) (:gmaps data)) (assoc data :gmaps))) ;; On inference integration, recursive method: ;; ;; Starting at inference root: ;; 1. If expr/pred exists as :base of an MH ;; 1.a then return :target of the MH ;; 1.b else return (cons pred (map f args)) ;; ;; This will return a relation expression for in the target gmap. All new parts ;; of the inference expression (ie. the inferences in Falkenhainer's terms) will ;; be included in the new relation, with all base predicates that were mapped ;; replaced with their targets. That way, the inferences are linked up in the ;; target graph. ;; Note that the behaviour of the original SME that concerns the creation of ;; "skolem" entities when transfering inferences is not implemented. ;; ;; Inference generation in general was not as relevant in the original purpose ;; of this implementation, hence it is less tested etc. (defn transfer-gmap-inferences "Attempt to transfer inferences to the target of the gmap." [{:as gmap, :keys [inferences mhs]}] ;; This exception setup is ugly, but is a simple and efficient way of aborting ;; the whole inference transferring process for this gmap. Monads would ;; perhaps work as well (or CPS). (try (let [pairs (zipmap (map :base mhs) (map :target mhs)) transfer (fn transfer [expr] (if-let [t (get pairs expr)] t (if (entity? expr) (throw (RuntimeException. "cannot infer entities")) (cons (expression-functor expr) (doall (map transfer (expression-args expr)))))))] (assoc gmap :transferred (doall (map transfer inferences)))) (catch RuntimeException e gmap))) (defn transfer-inferences [data] (->> (map transfer-gmap-inferences (:gmaps data)) (assoc data :gmaps))) (defn finalize-gmaps "Computes additional information about the gmaps we have found and stores it in the gmaps." [data base target] (->> (:gmaps data) (map #(score-gmap data %)) ; scores (map #(assoc % :mapping {:base base :target target})) ; what we mappped (assoc data :gmaps))) (defn match "Attempts to find a structure mapping between base and target using an implementation of the SME algorithm. Returns a map with the following: :mh-structure All MHs created for the mapping. :gmaps Collection of GMaps, which represent analogical mappings. Keys available in the returned GMaps: :mhs Collection of match hypotheses that form the GMap. :structure Map from each MH to a map with structural information. Keys: :emaps, :nogoods, :children. :mapping Original structures that were mapped, :base and :target. :score Structural evaluation score (SES), simple implementation. :inferences Maximal set of potential inferences. :transferred Inferences transferred to target, ready to be added into the target's concept graph. For example: (map :score (match b t)) -> seq of gmap scores." ([base target rules] (-> (create-match-hypotheses base target rules) build-hypothesis-structure propagate-from-emaps compute-initial-gmaps combine-gmaps merge-gmaps (finalize-gmaps base target) (generate-inferences base) transfer-inferences )) ([base target] (match base target literal-similarity)))
30769
(ns sme-clj.core "Structure mapping engine core functionality. Reimplements SME (as described in [1]) for the most part, in Clojure instead of (rather ancient and difficult to read) Common Lisp. There are some differences in certain areas, such as GMap merging and scoring. It is also likely to be slower, as it has not been profiled or optimised at all. The main differences: - GMap merging differs in two of the steps, but results should be more complete than the original algorithm, if they differ at all. - Inference generation has some limitations, and has not received as much development and testing as other areas (as it was not used in the research for which this SME implementation was developed). - Scoring of GMaps is much simpler. It does not use complex evidence rules in a belief maintenance system as in [1]. Instead, GMaps are scored on structure using a trickle-down algorithm that rewards large structures. The basic usage is as follows: 1. Define predicates, entities, and concept graphs using 'sme-clj.typedef. 2. Run 'sme-clj.core/match with the base and target graphs as arguments. 3. The 'match function returns the resulting GMaps. See the 'match docstring for more. Also look at the example in the sme-clj.example namespace. If you are not yet familiar with the general structure and terminology of the original SME algorithm, it will be hard to understand this stuff, so I would advise you read [1] first. [1] <NAME>., <NAME>. & <NAME>. (1989). The structure-mapping engine: algorithm and examples. Artificial Intelligence, 41, 1-62." (:require [clojure.set :as set] [clojure.contrib.set :as c.set] [clojure.contrib.combinatorics :as comb]) (:use sme-clj.typedef sme-clj.ruledef)) ;;;; ;;;; GENERATING MATCH HYPOTHESES ;;;; ;; Note: "mh" = match hypothesis (defn apply-filter-rules "Apply :filter rules from a ruleset to the base and target expressions. Return a set of match hypotheses." [base-expr target-expr rules] (-> (map (fn [rule] ;; map rule over every possible expression pairing (remove nil? (map #(rule (% 0) (% 1)) (for [bx base-expr, tx target-expr] [bx tx])))) (:filter rules)) flatten set)) (defn apply-intern-rules "Apply :intern rules to a set of match hypotheses generated by :filter rules, and see if new MHs are created. For every new MH, also apply the :intern rules to it. Return the resulting set of MHs." [mhs ruleset] (let [rules (:intern ruleset)] (loop [todo (seq mhs) ; treat todo as seq stack result (set mhs)] ; result as final mh set (if-let [mh (first todo)] ;; test this MH on all intern rules, adding new matches to todo list (let [matches (->> (map #(% mh) rules) flatten (remove nil?) set)] (recur (concat (next todo) matches) (set/union result matches))) ;; set of all MHs tested on intern rules result)))) (defn create-match-hypotheses "Apply rules from a ruleset to base and target to generate match hypotheses for the graphs." [base target rules] (-> (apply-filter-rules (:graph base) (:graph target) rules) (apply-intern-rules rules))) ;;;; ;;;; FORMING GMAPS ;;;; ;; The below proves useful when checking consistency and such. (defn build-hypothesis-structure "Creates a map from MHs to their structural information. So retrieving the match hypotheses is done with 'keys, while the structural info can be accessed with 'vals or 'get." [mhs] (let [add-as (fn [m k mh] (update-in m [k (k mh)] set/union #{mh})) ;; cache of base/target expressions mapped to their mh smap (reduce (fn [s mh] (-> s (add-as :base mh) (add-as :target mh))) {:base {}, :target {}} mhs) {bmap :base, tmap :target} smap] (reduce (fn build-mh-structure [structure mh] (assoc structure mh ;; initial emaps is just ourselves if we are one, for the rest ;; this will be filled later {:emaps (if (is-expression? mh) #{} #{mh}) ;; nogood is every mh mapping same target or base :nogood (-> (set/union (get bmap (:base mh) #{}) (get tmap (:target mh)) #{}) (disj mh)) ; not nogood of ourselves ;; our children are mhs that map our arguments (so children ;; does not equal our entire set of descendants) :children (if (is-expression? mh) (set (mapcat (fn [b t] (set/intersection (get bmap b #{}) (get tmap t #{}))) (expression-args (:base mh)) (expression-args (:target mh)))) #{}) })) {} mhs))) ;; For each expression without emaps, recursively add the union of its ;; children's emaps and nogoods. (defn propagate-from-emaps "Extends structural MH information of each expression without emaps by recursively adding the union of its children's emaps and nogoods to it. Essentially flows up the structural information." [mh-structure] (letfn [(propagate [mstr mh] (if (seq (:emaps (get mstr mh))) mstr (let [kids (:children (get mstr mh)) mstr-kids (reduce propagate mstr kids) kids-struct (vals (select-keys mstr-kids kids))] (update-in mstr-kids [mh] #(merge-with set/union %1 %2) {:emaps (reduce set/union (map :emaps kids-struct)) :nogood (reduce set/union (map :nogood kids-struct))}))))] (reduce propagate mh-structure (keys mh-structure)))) (defn consistent? "True if an MH is consistent, meaning none of its emaps are in its nogoods." ([{:keys [emaps nogood] :as mstr-entry}] (empty? (set/intersection emaps nogood))) ([mh mstr] (consistent? (get mstr mh)))) (defn find-roots "Returns only the root hypotheses, ie. those that are not children of any other hypothesis." [mh-structure] (let [all-children (reduce #(set/union %1 (:children %2)) #{} (vals mh-structure))] (filter #(not (contains? all-children %)) (keys mh-structure)))) (defn collect-children "Returns a set of all descendants of a root." [root mh-structure] (letfn [(collect [mh] (if (is-emap? mh) [mh] (cons mh (mapcat collect (:children (get mh-structure mh))))))] (set (collect root)))) (defn make-gmap "Returns a gmap with the root and all of its descendants." [root mh-structure] (make-GMap (collect-children root mh-structure) (merge {:roots #{root}} ;; gmap's nogoods/emaps are those of its root(s) (select-keys (get mh-structure root) [:nogood :emaps])))) (defn compute-initial-gmaps "Given match hypothesis information, builds a set of initial gmaps. Returns a map with the :mh-structure and the :gmaps set." [mh-structure] (->> (find-roots mh-structure) (reduce (fn form-gmap [gmaps root] (if (consistent? (get mh-structure root)) (conj gmaps (make-gmap root mh-structure)) (if-let [kids (seq (:children (get mh-structure root)))] (set/union gmaps (set (mapcat #(form-gmap #{} %) kids))) gmaps))) #{}) (hash-map :mh-structure mh-structure :gmaps))) (defn gmaps-consistent? "Two gmaps are consistent if none of their elements are in the NoGood set of the other." [gm-a gm-b] (and (empty? (set/intersection (:mhs gm-a) (:nogood (:structure gm-b)))) (empty? (set/intersection (:mhs gm-b) (:nogood (:structure gm-a)))))) (defn gmap-sets-consistent? "True if both collections of gmaps are fully consistent with each other." [coll-a coll-b] (every? true? (map (fn [gm-b] (every? true? (map #(gmaps-consistent? gm-b %) coll-a))) coll-b))) (defn gmap-set-internally-consistent? "True if the given set of gmaps is internally consistent." [gmap-set] (gmap-sets-consistent? gmap-set gmap-set)) ;; NOTE: SME's second merge step seems rather complex compared to its benefits. ;; Its results will already be generated in a third step we will be performing ;; that is more exhaustive than SME performs at that point. Therefore step 2 is ;; unnecessary here and we skip it. ;; The below is a very naive implementation, performance-wise. (defn combine-gmaps "Combine all gmaps in all maximal, consistent ways." [data] (let [consistent-sets (->> (comb/subsets (:gmaps data)) (remove empty?) (filter gmap-set-internally-consistent?) (map set))] (->> (remove (fn [gms-a] (some (fn [gms-b] (and (not= gms-a gms-b) (c.set/subset? gms-a gms-b))) consistent-sets)) consistent-sets) (assoc data :gmaps)))) (defn merge-gmaps "Given a collection of sets of gmaps, merges the gmaps in each set into a single gmap." [data] (letfn [(gather-gm [{:keys [mhs structure] :as total} gm] (assoc total :mhs (set/union mhs (:mhs gm)) :structure (merge-with set/union structure (:structure gm)))) (reduce-to-gm [gm-set] (let [args (reduce gather-gm {:mhs #{} :structure {}} gm-set)] (make-GMap (:mhs args) (:structure args))))] (->> (map reduce-to-gm (:gmaps data)) (assoc data :gmaps)))) (letfn [(round [n] (.setScale (bigdec n) 2 BigDecimal/ROUND_HALF_UP))] (defn emaps-equal? "Special equals function for entities that rounds floating point numbers to two decimals before comparing them, to avoid rounding errors affecting equality." [a b] (and (= (keys a) (keys b)) (every? true? (map (fn [x y] (if (and (number? x) (number? y)) (== (round x) (round y)) (= x y))) (vals a) (vals b)))))) ;; Entities may have keys that are implementation details. Bind this var to a ;; seq of those keys to ignore them in emap matching. (def unmatched-keys nil) (defn matching-emaps "Returns seq of MHs that are emaps of which the entities are equal." [{:as gmap, :keys [mhs]}] (filter #(and (is-emap? %) (emaps-equal? (apply dissoc (:base %) unmatched-keys) (apply dissoc (:target %) unmatched-keys))) mhs)) (defn score-gmap "Computes SES and emap scores for a gmap. The emap score is not in the original SME. It simply counts how many entities match in their content." [{:keys [mh-structure] :as data} gm] (letfn [(score-mh [mh depth] ;; simplified trickle-down SES (if-let [kids (seq (:children (get mh-structure mh)))] (reduce + depth (map #(score-mh % (inc depth)) kids)) depth))] (assoc gm :score (reduce + (count (:mhs gm)) (map #(score-mh % 0) (:roots (:structure gm)))) :emap-matches (count (matching-emaps gm))))) ;;; Inference generation below. Not used in TCG model. (defn gmap-inferences "Generates maximal inferences for a given gmap, based on SME algorithm." [gmap {base :graph}] (let [mh-bases (set (map :base (:mhs gmap))) unmatched (set/difference (set base) mh-bases) ancestors (set/select #(ancestor? mh-bases %) unmatched)] (set/difference (set (mapcat get-descendants ancestors)) mh-bases))) (defn generate-inferences "Appends :inferences to gmaps in given data, for a given base graph." [data base] (->> (map #(assoc % :inferences (gmap-inferences % base)) (:gmaps data)) (assoc data :gmaps))) ;; On inference integration, recursive method: ;; ;; Starting at inference root: ;; 1. If expr/pred exists as :base of an MH ;; 1.a then return :target of the MH ;; 1.b else return (cons pred (map f args)) ;; ;; This will return a relation expression for in the target gmap. All new parts ;; of the inference expression (ie. the inferences in Falkenhainer's terms) will ;; be included in the new relation, with all base predicates that were mapped ;; replaced with their targets. That way, the inferences are linked up in the ;; target graph. ;; Note that the behaviour of the original SME that concerns the creation of ;; "skolem" entities when transfering inferences is not implemented. ;; ;; Inference generation in general was not as relevant in the original purpose ;; of this implementation, hence it is less tested etc. (defn transfer-gmap-inferences "Attempt to transfer inferences to the target of the gmap." [{:as gmap, :keys [inferences mhs]}] ;; This exception setup is ugly, but is a simple and efficient way of aborting ;; the whole inference transferring process for this gmap. Monads would ;; perhaps work as well (or CPS). (try (let [pairs (zipmap (map :base mhs) (map :target mhs)) transfer (fn transfer [expr] (if-let [t (get pairs expr)] t (if (entity? expr) (throw (RuntimeException. "cannot infer entities")) (cons (expression-functor expr) (doall (map transfer (expression-args expr)))))))] (assoc gmap :transferred (doall (map transfer inferences)))) (catch RuntimeException e gmap))) (defn transfer-inferences [data] (->> (map transfer-gmap-inferences (:gmaps data)) (assoc data :gmaps))) (defn finalize-gmaps "Computes additional information about the gmaps we have found and stores it in the gmaps." [data base target] (->> (:gmaps data) (map #(score-gmap data %)) ; scores (map #(assoc % :mapping {:base base :target target})) ; what we mappped (assoc data :gmaps))) (defn match "Attempts to find a structure mapping between base and target using an implementation of the SME algorithm. Returns a map with the following: :mh-structure All MHs created for the mapping. :gmaps Collection of GMaps, which represent analogical mappings. Keys available in the returned GMaps: :mhs Collection of match hypotheses that form the GMap. :structure Map from each MH to a map with structural information. Keys: :emaps, :nogoods, :children. :mapping Original structures that were mapped, :base and :target. :score Structural evaluation score (SES), simple implementation. :inferences Maximal set of potential inferences. :transferred Inferences transferred to target, ready to be added into the target's concept graph. For example: (map :score (match b t)) -> seq of gmap scores." ([base target rules] (-> (create-match-hypotheses base target rules) build-hypothesis-structure propagate-from-emaps compute-initial-gmaps combine-gmaps merge-gmaps (finalize-gmaps base target) (generate-inferences base) transfer-inferences )) ([base target] (match base target literal-similarity)))
true
(ns sme-clj.core "Structure mapping engine core functionality. Reimplements SME (as described in [1]) for the most part, in Clojure instead of (rather ancient and difficult to read) Common Lisp. There are some differences in certain areas, such as GMap merging and scoring. It is also likely to be slower, as it has not been profiled or optimised at all. The main differences: - GMap merging differs in two of the steps, but results should be more complete than the original algorithm, if they differ at all. - Inference generation has some limitations, and has not received as much development and testing as other areas (as it was not used in the research for which this SME implementation was developed). - Scoring of GMaps is much simpler. It does not use complex evidence rules in a belief maintenance system as in [1]. Instead, GMaps are scored on structure using a trickle-down algorithm that rewards large structures. The basic usage is as follows: 1. Define predicates, entities, and concept graphs using 'sme-clj.typedef. 2. Run 'sme-clj.core/match with the base and target graphs as arguments. 3. The 'match function returns the resulting GMaps. See the 'match docstring for more. Also look at the example in the sme-clj.example namespace. If you are not yet familiar with the general structure and terminology of the original SME algorithm, it will be hard to understand this stuff, so I would advise you read [1] first. [1] PI:NAME:<NAME>END_PI., PI:NAME:<NAME>END_PI. & PI:NAME:<NAME>END_PI. (1989). The structure-mapping engine: algorithm and examples. Artificial Intelligence, 41, 1-62." (:require [clojure.set :as set] [clojure.contrib.set :as c.set] [clojure.contrib.combinatorics :as comb]) (:use sme-clj.typedef sme-clj.ruledef)) ;;;; ;;;; GENERATING MATCH HYPOTHESES ;;;; ;; Note: "mh" = match hypothesis (defn apply-filter-rules "Apply :filter rules from a ruleset to the base and target expressions. Return a set of match hypotheses." [base-expr target-expr rules] (-> (map (fn [rule] ;; map rule over every possible expression pairing (remove nil? (map #(rule (% 0) (% 1)) (for [bx base-expr, tx target-expr] [bx tx])))) (:filter rules)) flatten set)) (defn apply-intern-rules "Apply :intern rules to a set of match hypotheses generated by :filter rules, and see if new MHs are created. For every new MH, also apply the :intern rules to it. Return the resulting set of MHs." [mhs ruleset] (let [rules (:intern ruleset)] (loop [todo (seq mhs) ; treat todo as seq stack result (set mhs)] ; result as final mh set (if-let [mh (first todo)] ;; test this MH on all intern rules, adding new matches to todo list (let [matches (->> (map #(% mh) rules) flatten (remove nil?) set)] (recur (concat (next todo) matches) (set/union result matches))) ;; set of all MHs tested on intern rules result)))) (defn create-match-hypotheses "Apply rules from a ruleset to base and target to generate match hypotheses for the graphs." [base target rules] (-> (apply-filter-rules (:graph base) (:graph target) rules) (apply-intern-rules rules))) ;;;; ;;;; FORMING GMAPS ;;;; ;; The below proves useful when checking consistency and such. (defn build-hypothesis-structure "Creates a map from MHs to their structural information. So retrieving the match hypotheses is done with 'keys, while the structural info can be accessed with 'vals or 'get." [mhs] (let [add-as (fn [m k mh] (update-in m [k (k mh)] set/union #{mh})) ;; cache of base/target expressions mapped to their mh smap (reduce (fn [s mh] (-> s (add-as :base mh) (add-as :target mh))) {:base {}, :target {}} mhs) {bmap :base, tmap :target} smap] (reduce (fn build-mh-structure [structure mh] (assoc structure mh ;; initial emaps is just ourselves if we are one, for the rest ;; this will be filled later {:emaps (if (is-expression? mh) #{} #{mh}) ;; nogood is every mh mapping same target or base :nogood (-> (set/union (get bmap (:base mh) #{}) (get tmap (:target mh)) #{}) (disj mh)) ; not nogood of ourselves ;; our children are mhs that map our arguments (so children ;; does not equal our entire set of descendants) :children (if (is-expression? mh) (set (mapcat (fn [b t] (set/intersection (get bmap b #{}) (get tmap t #{}))) (expression-args (:base mh)) (expression-args (:target mh)))) #{}) })) {} mhs))) ;; For each expression without emaps, recursively add the union of its ;; children's emaps and nogoods. (defn propagate-from-emaps "Extends structural MH information of each expression without emaps by recursively adding the union of its children's emaps and nogoods to it. Essentially flows up the structural information." [mh-structure] (letfn [(propagate [mstr mh] (if (seq (:emaps (get mstr mh))) mstr (let [kids (:children (get mstr mh)) mstr-kids (reduce propagate mstr kids) kids-struct (vals (select-keys mstr-kids kids))] (update-in mstr-kids [mh] #(merge-with set/union %1 %2) {:emaps (reduce set/union (map :emaps kids-struct)) :nogood (reduce set/union (map :nogood kids-struct))}))))] (reduce propagate mh-structure (keys mh-structure)))) (defn consistent? "True if an MH is consistent, meaning none of its emaps are in its nogoods." ([{:keys [emaps nogood] :as mstr-entry}] (empty? (set/intersection emaps nogood))) ([mh mstr] (consistent? (get mstr mh)))) (defn find-roots "Returns only the root hypotheses, ie. those that are not children of any other hypothesis." [mh-structure] (let [all-children (reduce #(set/union %1 (:children %2)) #{} (vals mh-structure))] (filter #(not (contains? all-children %)) (keys mh-structure)))) (defn collect-children "Returns a set of all descendants of a root." [root mh-structure] (letfn [(collect [mh] (if (is-emap? mh) [mh] (cons mh (mapcat collect (:children (get mh-structure mh))))))] (set (collect root)))) (defn make-gmap "Returns a gmap with the root and all of its descendants." [root mh-structure] (make-GMap (collect-children root mh-structure) (merge {:roots #{root}} ;; gmap's nogoods/emaps are those of its root(s) (select-keys (get mh-structure root) [:nogood :emaps])))) (defn compute-initial-gmaps "Given match hypothesis information, builds a set of initial gmaps. Returns a map with the :mh-structure and the :gmaps set." [mh-structure] (->> (find-roots mh-structure) (reduce (fn form-gmap [gmaps root] (if (consistent? (get mh-structure root)) (conj gmaps (make-gmap root mh-structure)) (if-let [kids (seq (:children (get mh-structure root)))] (set/union gmaps (set (mapcat #(form-gmap #{} %) kids))) gmaps))) #{}) (hash-map :mh-structure mh-structure :gmaps))) (defn gmaps-consistent? "Two gmaps are consistent if none of their elements are in the NoGood set of the other." [gm-a gm-b] (and (empty? (set/intersection (:mhs gm-a) (:nogood (:structure gm-b)))) (empty? (set/intersection (:mhs gm-b) (:nogood (:structure gm-a)))))) (defn gmap-sets-consistent? "True if both collections of gmaps are fully consistent with each other." [coll-a coll-b] (every? true? (map (fn [gm-b] (every? true? (map #(gmaps-consistent? gm-b %) coll-a))) coll-b))) (defn gmap-set-internally-consistent? "True if the given set of gmaps is internally consistent." [gmap-set] (gmap-sets-consistent? gmap-set gmap-set)) ;; NOTE: SME's second merge step seems rather complex compared to its benefits. ;; Its results will already be generated in a third step we will be performing ;; that is more exhaustive than SME performs at that point. Therefore step 2 is ;; unnecessary here and we skip it. ;; The below is a very naive implementation, performance-wise. (defn combine-gmaps "Combine all gmaps in all maximal, consistent ways." [data] (let [consistent-sets (->> (comb/subsets (:gmaps data)) (remove empty?) (filter gmap-set-internally-consistent?) (map set))] (->> (remove (fn [gms-a] (some (fn [gms-b] (and (not= gms-a gms-b) (c.set/subset? gms-a gms-b))) consistent-sets)) consistent-sets) (assoc data :gmaps)))) (defn merge-gmaps "Given a collection of sets of gmaps, merges the gmaps in each set into a single gmap." [data] (letfn [(gather-gm [{:keys [mhs structure] :as total} gm] (assoc total :mhs (set/union mhs (:mhs gm)) :structure (merge-with set/union structure (:structure gm)))) (reduce-to-gm [gm-set] (let [args (reduce gather-gm {:mhs #{} :structure {}} gm-set)] (make-GMap (:mhs args) (:structure args))))] (->> (map reduce-to-gm (:gmaps data)) (assoc data :gmaps)))) (letfn [(round [n] (.setScale (bigdec n) 2 BigDecimal/ROUND_HALF_UP))] (defn emaps-equal? "Special equals function for entities that rounds floating point numbers to two decimals before comparing them, to avoid rounding errors affecting equality." [a b] (and (= (keys a) (keys b)) (every? true? (map (fn [x y] (if (and (number? x) (number? y)) (== (round x) (round y)) (= x y))) (vals a) (vals b)))))) ;; Entities may have keys that are implementation details. Bind this var to a ;; seq of those keys to ignore them in emap matching. (def unmatched-keys nil) (defn matching-emaps "Returns seq of MHs that are emaps of which the entities are equal." [{:as gmap, :keys [mhs]}] (filter #(and (is-emap? %) (emaps-equal? (apply dissoc (:base %) unmatched-keys) (apply dissoc (:target %) unmatched-keys))) mhs)) (defn score-gmap "Computes SES and emap scores for a gmap. The emap score is not in the original SME. It simply counts how many entities match in their content." [{:keys [mh-structure] :as data} gm] (letfn [(score-mh [mh depth] ;; simplified trickle-down SES (if-let [kids (seq (:children (get mh-structure mh)))] (reduce + depth (map #(score-mh % (inc depth)) kids)) depth))] (assoc gm :score (reduce + (count (:mhs gm)) (map #(score-mh % 0) (:roots (:structure gm)))) :emap-matches (count (matching-emaps gm))))) ;;; Inference generation below. Not used in TCG model. (defn gmap-inferences "Generates maximal inferences for a given gmap, based on SME algorithm." [gmap {base :graph}] (let [mh-bases (set (map :base (:mhs gmap))) unmatched (set/difference (set base) mh-bases) ancestors (set/select #(ancestor? mh-bases %) unmatched)] (set/difference (set (mapcat get-descendants ancestors)) mh-bases))) (defn generate-inferences "Appends :inferences to gmaps in given data, for a given base graph." [data base] (->> (map #(assoc % :inferences (gmap-inferences % base)) (:gmaps data)) (assoc data :gmaps))) ;; On inference integration, recursive method: ;; ;; Starting at inference root: ;; 1. If expr/pred exists as :base of an MH ;; 1.a then return :target of the MH ;; 1.b else return (cons pred (map f args)) ;; ;; This will return a relation expression for in the target gmap. All new parts ;; of the inference expression (ie. the inferences in Falkenhainer's terms) will ;; be included in the new relation, with all base predicates that were mapped ;; replaced with their targets. That way, the inferences are linked up in the ;; target graph. ;; Note that the behaviour of the original SME that concerns the creation of ;; "skolem" entities when transfering inferences is not implemented. ;; ;; Inference generation in general was not as relevant in the original purpose ;; of this implementation, hence it is less tested etc. (defn transfer-gmap-inferences "Attempt to transfer inferences to the target of the gmap." [{:as gmap, :keys [inferences mhs]}] ;; This exception setup is ugly, but is a simple and efficient way of aborting ;; the whole inference transferring process for this gmap. Monads would ;; perhaps work as well (or CPS). (try (let [pairs (zipmap (map :base mhs) (map :target mhs)) transfer (fn transfer [expr] (if-let [t (get pairs expr)] t (if (entity? expr) (throw (RuntimeException. "cannot infer entities")) (cons (expression-functor expr) (doall (map transfer (expression-args expr)))))))] (assoc gmap :transferred (doall (map transfer inferences)))) (catch RuntimeException e gmap))) (defn transfer-inferences [data] (->> (map transfer-gmap-inferences (:gmaps data)) (assoc data :gmaps))) (defn finalize-gmaps "Computes additional information about the gmaps we have found and stores it in the gmaps." [data base target] (->> (:gmaps data) (map #(score-gmap data %)) ; scores (map #(assoc % :mapping {:base base :target target})) ; what we mappped (assoc data :gmaps))) (defn match "Attempts to find a structure mapping between base and target using an implementation of the SME algorithm. Returns a map with the following: :mh-structure All MHs created for the mapping. :gmaps Collection of GMaps, which represent analogical mappings. Keys available in the returned GMaps: :mhs Collection of match hypotheses that form the GMap. :structure Map from each MH to a map with structural information. Keys: :emaps, :nogoods, :children. :mapping Original structures that were mapped, :base and :target. :score Structural evaluation score (SES), simple implementation. :inferences Maximal set of potential inferences. :transferred Inferences transferred to target, ready to be added into the target's concept graph. For example: (map :score (match b t)) -> seq of gmap scores." ([base target rules] (-> (create-match-hypotheses base target rules) build-hypothesis-structure propagate-from-emaps compute-initial-gmaps combine-gmaps merge-gmaps (finalize-gmaps base target) (generate-inferences base) transfer-inferences )) ([base target] (match base target literal-similarity)))
[ { "context": "ument:\n\n ```javascript\n sprite.setData({ name: 'Red Gem Stone', level: 2, owner: 'Link', gold: 50 });\n ```\n\n ", "end": 12176, "score": 0.9857856631278992, "start": 12163, "tag": "NAME", "value": "Red Gem Stone" }, { "context": "r example, if you updated an existing key called `PlayerLives` then it would emit the event `changedata-PlayerL", "end": 12744, "score": 0.9756506085395813, "start": 12733, "tag": "KEY", "value": "PlayerLives" } ]
src/phzr/game_objects/game_object.cljs
sjcasey21/phzr
1
(ns phzr.game-objects.game-object (:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]] [phzr.impl.extend :as ex] [cljsjs.phaser]) (:refer-clojure :exclude [update])) (defn ->GameObject " Parameters: * scene (Phaser.Scene) - The Scene to which this Game Object belongs. * type (string) - A textual representation of the type of Game Object, i.e. `sprite`." ([scene type] (js/Phaser.GameObjects.GameObject. (clj->phaser scene) (clj->phaser type)))) (defn add-listener "Add a listener for a given event. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * event (string | symbol) - The event name. * fn (function) - The listener function. * context (*) {optional} - The context to invoke the listener with. Returns: Phaser.Events.EventEmitter - `this`." ([game-object event fn] (phaser->clj (.addListener game-object (clj->phaser event) (clj->phaser fn)))) ([game-object event fn context] (phaser->clj (.addListener game-object (clj->phaser event) (clj->phaser fn) (clj->phaser context))))) (defn destroy "Destroys this Game Object removing it from the Display List and Update List and severing all ties to parent resources. Also removes itself from the Input Manager and Physics Manager if previously enabled. Use this to remove a Game Object from your game if you don't ever plan to use it again. As long as no reference to it exists within your own code it should become free for garbage collection by the browser. If you just want to temporarily disable an object then look at using the Game Object Pool instead of destroying it, as destroyed objects cannot be resurrected. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * from-scene (boolean) {optional} - Is this Game Object being destroyed as the result of a Scene shutdown?" ([game-object] (phaser->clj (.destroy game-object))) ([game-object from-scene] (phaser->clj (.destroy game-object (clj->phaser from-scene))))) (defn disable-interactive "If this Game Object has previously been enabled for input, this will disable it. An object that is disabled for input stops processing or being considered for input events, but can be turned back on again at any time by simply calling `setInteractive()` with no arguments provided. If want to completely remove interaction from this Game Object then use `removeInteractive` instead. Returns: this - This GameObject." ([game-object] (phaser->clj (.disableInteractive game-object)))) (defn emit "Calls each of the listeners registered for a given event. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * event (string | symbol) - The event name. * args (*) {optional} - Additional arguments that will be passed to the event handler. Returns: boolean - `true` if the event had listeners, else `false`." ([game-object event] (phaser->clj (.emit game-object (clj->phaser event)))) ([game-object event args] (phaser->clj (.emit game-object (clj->phaser event) (clj->phaser args))))) (defn event-names "Return an array listing the events for which the emitter has registered listeners. Returns: array - " ([game-object] (phaser->clj (.eventNames game-object)))) (defn get-data "Retrieves the value for the given key in this Game Objects Data Manager, or undefined if it doesn't exist. You can also access values via the `values` object. For example, if you had a key called `gold` you can do either: ```javascript sprite.getData('gold'); ``` Or access the value directly: ```javascript sprite.data.values.gold; ``` You can also pass in an array of keys, in which case an array of values will be returned: ```javascript sprite.getData([ 'gold', 'armor', 'health' ]); ``` This approach is useful for destructuring arrays in ES6. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * key (string | Array.<string>) - The key of the value to retrieve, or an array of keys. Returns: * - The value belonging to the given key, or an array of values, the order of which will match the input array." ([game-object key] (phaser->clj (.getData game-object (clj->phaser key))))) (defn get-index-list "Returns an array containing the display list index of either this Game Object, or if it has one, its parent Container. It then iterates up through all of the parent containers until it hits the root of the display list (which is index 0 in the returned array). Used internally by the InputPlugin but also useful if you wish to find out the display depth of this Game Object and all of its ancestors. Returns: Array.<integer> - An array of display list position indexes." ([game-object] (phaser->clj (.getIndexList game-object)))) (defn listener-count "Return the number of listeners listening to a given event. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * event (string | symbol) - The event name. Returns: number - The number of listeners." ([game-object event] (phaser->clj (.listenerCount game-object (clj->phaser event))))) (defn listeners "Return the listeners registered for a given event. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * event (string | symbol) - The event name. Returns: array - The registered listeners." ([game-object event] (phaser->clj (.listeners game-object (clj->phaser event))))) (defn off "Remove the listeners of a given event. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * event (string | symbol) - The event name. * fn (function) {optional} - Only remove the listeners that match this function. * context (*) {optional} - Only remove the listeners that have this context. * once (boolean) {optional} - Only remove one-time listeners. Returns: Phaser.Events.EventEmitter - `this`." ([game-object event] (phaser->clj (.off game-object (clj->phaser event)))) ([game-object event fn] (phaser->clj (.off game-object (clj->phaser event) (clj->phaser fn)))) ([game-object event fn context] (phaser->clj (.off game-object (clj->phaser event) (clj->phaser fn) (clj->phaser context)))) ([game-object event fn context once] (phaser->clj (.off game-object (clj->phaser event) (clj->phaser fn) (clj->phaser context) (clj->phaser once))))) (defn on "Add a listener for a given event. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * event (string | symbol) - The event name. * fn (function) - The listener function. * context (*) {optional} - The context to invoke the listener with. Returns: Phaser.Events.EventEmitter - `this`." ([game-object event fn] (phaser->clj (.on game-object (clj->phaser event) (clj->phaser fn)))) ([game-object event fn context] (phaser->clj (.on game-object (clj->phaser event) (clj->phaser fn) (clj->phaser context))))) (defn once "Add a one-time listener for a given event. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * event (string | symbol) - The event name. * fn (function) - The listener function. * context (*) {optional} - The context to invoke the listener with. Returns: Phaser.Events.EventEmitter - `this`." ([game-object event fn] (phaser->clj (.once game-object (clj->phaser event) (clj->phaser fn)))) ([game-object event fn context] (phaser->clj (.once game-object (clj->phaser event) (clj->phaser fn) (clj->phaser context))))) (defn remove-all-listeners "Remove all listeners, or those of the specified event. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * event (string | symbol) {optional} - The event name. Returns: Phaser.Events.EventEmitter - `this`." ([game-object] (phaser->clj (.removeAllListeners game-object))) ([game-object event] (phaser->clj (.removeAllListeners game-object (clj->phaser event))))) (defn remove-interactive "If this Game Object has previously been enabled for input, this will queue it for removal, causing it to no longer be interactive. The removal happens on the next game step, it is not immediate. The Interactive Object that was assigned to this Game Object will be destroyed, removed from the Input Manager and cleared from this Game Object. If you wish to re-enable this Game Object at a later date you will need to re-create its InteractiveObject by calling `setInteractive` again. If you wish to only temporarily stop an object from receiving input then use `disableInteractive` instead, as that toggles the interactive state, where-as this erases it completely. If you wish to resize a hit area, don't remove and then set it as being interactive. Instead, access the hitarea object directly and resize the shape being used. I.e.: `sprite.input.hitArea.setSize(width, height)` (assuming the shape is a Rectangle, which it is by default.) Returns: this - This GameObject." ([game-object] (phaser->clj (.removeInteractive game-object)))) (defn remove-listener "Remove the listeners of a given event. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * event (string | symbol) - The event name. * fn (function) {optional} - Only remove the listeners that match this function. * context (*) {optional} - Only remove the listeners that have this context. * once (boolean) {optional} - Only remove one-time listeners. Returns: Phaser.Events.EventEmitter - `this`." ([game-object event] (phaser->clj (.removeListener game-object (clj->phaser event)))) ([game-object event fn] (phaser->clj (.removeListener game-object (clj->phaser event) (clj->phaser fn)))) ([game-object event fn context] (phaser->clj (.removeListener game-object (clj->phaser event) (clj->phaser fn) (clj->phaser context)))) ([game-object event fn context once] (phaser->clj (.removeListener game-object (clj->phaser event) (clj->phaser fn) (clj->phaser context) (clj->phaser once))))) (defn set-active "Sets the `active` property of this Game Object and returns this Game Object for further chaining. A Game Object with its `active` property set to `true` will be updated by the Scenes UpdateList. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * value (boolean) - True if this Game Object should be set as active, false if not. Returns: this - This GameObject." ([game-object value] (phaser->clj (.setActive game-object (clj->phaser value))))) (defn set-data "Allows you to store a key value pair within this Game Objects Data Manager. If the Game Object has not been enabled for data (via `setDataEnabled`) then it will be enabled before setting the value. If the key doesn't already exist in the Data Manager then it is created. ```javascript sprite.setData('name', 'Red Gem Stone'); ``` You can also pass in an object of key value pairs as the first argument: ```javascript sprite.setData({ name: 'Red Gem Stone', level: 2, owner: 'Link', gold: 50 }); ``` To get a value back again you can call `getData`: ```javascript sprite.getData('gold'); ``` Or you can access the value directly via the `values` property, where it works like any other variable: ```javascript sprite.data.values.gold += 50; ``` When the value is first set, a `setdata` event is emitted from this Game Object. If the key already exists, a `changedata` event is emitted instead, along an event named after the key. For example, if you updated an existing key called `PlayerLives` then it would emit the event `changedata-PlayerLives`. These events will be emitted regardless if you use this method to set the value, or the direct `values` setter. Please note that the data keys are case-sensitive and must be valid JavaScript Object property strings. This means the keys `gold` and `Gold` are treated as two unique values within the Data Manager. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * key (string | object) - The key to set the value for. Or an object of key value pairs. If an object the `data` argument is ignored. * data (*) {optional} - The value to set for the given key. If an object is provided as the key this argument is ignored. Returns: this - This GameObject." ([game-object key] (phaser->clj (.setData game-object (clj->phaser key)))) ([game-object key data] (phaser->clj (.setData game-object (clj->phaser key) (clj->phaser data))))) (defn set-data-enabled "Adds a Data Manager component to this Game Object. Returns: this - This GameObject." ([game-object] (phaser->clj (.setDataEnabled game-object)))) (defn set-interactive "Pass this Game Object to the Input Manager to enable it for Input. Input works by using hit areas, these are nearly always geometric shapes, such as rectangles or circles, that act as the hit area for the Game Object. However, you can provide your own hit area shape and callback, should you wish to handle some more advanced input detection. If no arguments are provided it will try and create a rectangle hit area based on the texture frame the Game Object is using. If this isn't a texture-bound object, such as a Graphics or BitmapText object, this will fail, and you'll need to provide a specific shape for it to use. You can also provide an Input Configuration Object as the only argument to this method. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * shape (Phaser.Types.Input.InputConfiguration | any) {optional} - Either an input configuration object, or a geometric shape that defines the hit area for the Game Object. If not specified a Rectangle will be used. * callback (Phaser.Types.Input.HitAreaCallback) {optional} - A callback to be invoked when the Game Object is interacted with. If you provide a shape you must also provide a callback. * drop-zone (boolean) {optional} - Should this Game Object be treated as a drop zone target? Returns: this - This GameObject." ([game-object] (phaser->clj (.setInteractive game-object))) ([game-object shape] (phaser->clj (.setInteractive game-object (clj->phaser shape)))) ([game-object shape callback] (phaser->clj (.setInteractive game-object (clj->phaser shape) (clj->phaser callback)))) ([game-object shape callback drop-zone] (phaser->clj (.setInteractive game-object (clj->phaser shape) (clj->phaser callback) (clj->phaser drop-zone))))) (defn set-name "Sets the `name` property of this Game Object and returns this Game Object for further chaining. The `name` property is not populated by Phaser and is presented for your own use. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * value (string) - The name to be given to this Game Object. Returns: this - This GameObject." ([game-object value] (phaser->clj (.setName game-object (clj->phaser value))))) (defn set-state "Sets the current state of this Game Object. Phaser itself will never modify the State of a Game Object, although plugins may do so. For example, a Game Object could change from a state of 'moving', to 'attacking', to 'dead'. The state value should typically be an integer (ideally mapped to a constant in your game code), but could also be a string. It is recommended to keep it light and simple. If you need to store complex data about your Game Object, look at using the Data Component instead. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * value (integer | string) - The state of the Game Object. Returns: this - This GameObject." ([game-object value] (phaser->clj (.setState game-object (clj->phaser value))))) (defn shutdown "Removes all listeners." ([game-object] (phaser->clj (.shutdown game-object)))) (defn to-json "Returns a JSON representation of the Game Object. Returns: Phaser.Types.GameObjects.JSONGameObject - A JSON representation of the Game Object." ([game-object] (phaser->clj (.toJSON game-object)))) (defn update "To be overridden by custom GameObjects. Allows base objects to be used in a Pool. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * args (*) {optional} - args" ([game-object] (phaser->clj (.update game-object))) ([game-object args] (phaser->clj (.update game-object (clj->phaser args))))) (defn will-render "Compares the renderMask with the renderFlags to see if this Game Object will render or not. Also checks the Game Object against the given Cameras exclusion list. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * camera (Phaser.Cameras.Scene2D.Camera) - The Camera to check against this Game Object. Returns: boolean - True if the Game Object should be rendered, otherwise false." ([game-object camera] (phaser->clj (.willRender game-object (clj->phaser camera)))))
113283
(ns phzr.game-objects.game-object (:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]] [phzr.impl.extend :as ex] [cljsjs.phaser]) (:refer-clojure :exclude [update])) (defn ->GameObject " Parameters: * scene (Phaser.Scene) - The Scene to which this Game Object belongs. * type (string) - A textual representation of the type of Game Object, i.e. `sprite`." ([scene type] (js/Phaser.GameObjects.GameObject. (clj->phaser scene) (clj->phaser type)))) (defn add-listener "Add a listener for a given event. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * event (string | symbol) - The event name. * fn (function) - The listener function. * context (*) {optional} - The context to invoke the listener with. Returns: Phaser.Events.EventEmitter - `this`." ([game-object event fn] (phaser->clj (.addListener game-object (clj->phaser event) (clj->phaser fn)))) ([game-object event fn context] (phaser->clj (.addListener game-object (clj->phaser event) (clj->phaser fn) (clj->phaser context))))) (defn destroy "Destroys this Game Object removing it from the Display List and Update List and severing all ties to parent resources. Also removes itself from the Input Manager and Physics Manager if previously enabled. Use this to remove a Game Object from your game if you don't ever plan to use it again. As long as no reference to it exists within your own code it should become free for garbage collection by the browser. If you just want to temporarily disable an object then look at using the Game Object Pool instead of destroying it, as destroyed objects cannot be resurrected. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * from-scene (boolean) {optional} - Is this Game Object being destroyed as the result of a Scene shutdown?" ([game-object] (phaser->clj (.destroy game-object))) ([game-object from-scene] (phaser->clj (.destroy game-object (clj->phaser from-scene))))) (defn disable-interactive "If this Game Object has previously been enabled for input, this will disable it. An object that is disabled for input stops processing or being considered for input events, but can be turned back on again at any time by simply calling `setInteractive()` with no arguments provided. If want to completely remove interaction from this Game Object then use `removeInteractive` instead. Returns: this - This GameObject." ([game-object] (phaser->clj (.disableInteractive game-object)))) (defn emit "Calls each of the listeners registered for a given event. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * event (string | symbol) - The event name. * args (*) {optional} - Additional arguments that will be passed to the event handler. Returns: boolean - `true` if the event had listeners, else `false`." ([game-object event] (phaser->clj (.emit game-object (clj->phaser event)))) ([game-object event args] (phaser->clj (.emit game-object (clj->phaser event) (clj->phaser args))))) (defn event-names "Return an array listing the events for which the emitter has registered listeners. Returns: array - " ([game-object] (phaser->clj (.eventNames game-object)))) (defn get-data "Retrieves the value for the given key in this Game Objects Data Manager, or undefined if it doesn't exist. You can also access values via the `values` object. For example, if you had a key called `gold` you can do either: ```javascript sprite.getData('gold'); ``` Or access the value directly: ```javascript sprite.data.values.gold; ``` You can also pass in an array of keys, in which case an array of values will be returned: ```javascript sprite.getData([ 'gold', 'armor', 'health' ]); ``` This approach is useful for destructuring arrays in ES6. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * key (string | Array.<string>) - The key of the value to retrieve, or an array of keys. Returns: * - The value belonging to the given key, or an array of values, the order of which will match the input array." ([game-object key] (phaser->clj (.getData game-object (clj->phaser key))))) (defn get-index-list "Returns an array containing the display list index of either this Game Object, or if it has one, its parent Container. It then iterates up through all of the parent containers until it hits the root of the display list (which is index 0 in the returned array). Used internally by the InputPlugin but also useful if you wish to find out the display depth of this Game Object and all of its ancestors. Returns: Array.<integer> - An array of display list position indexes." ([game-object] (phaser->clj (.getIndexList game-object)))) (defn listener-count "Return the number of listeners listening to a given event. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * event (string | symbol) - The event name. Returns: number - The number of listeners." ([game-object event] (phaser->clj (.listenerCount game-object (clj->phaser event))))) (defn listeners "Return the listeners registered for a given event. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * event (string | symbol) - The event name. Returns: array - The registered listeners." ([game-object event] (phaser->clj (.listeners game-object (clj->phaser event))))) (defn off "Remove the listeners of a given event. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * event (string | symbol) - The event name. * fn (function) {optional} - Only remove the listeners that match this function. * context (*) {optional} - Only remove the listeners that have this context. * once (boolean) {optional} - Only remove one-time listeners. Returns: Phaser.Events.EventEmitter - `this`." ([game-object event] (phaser->clj (.off game-object (clj->phaser event)))) ([game-object event fn] (phaser->clj (.off game-object (clj->phaser event) (clj->phaser fn)))) ([game-object event fn context] (phaser->clj (.off game-object (clj->phaser event) (clj->phaser fn) (clj->phaser context)))) ([game-object event fn context once] (phaser->clj (.off game-object (clj->phaser event) (clj->phaser fn) (clj->phaser context) (clj->phaser once))))) (defn on "Add a listener for a given event. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * event (string | symbol) - The event name. * fn (function) - The listener function. * context (*) {optional} - The context to invoke the listener with. Returns: Phaser.Events.EventEmitter - `this`." ([game-object event fn] (phaser->clj (.on game-object (clj->phaser event) (clj->phaser fn)))) ([game-object event fn context] (phaser->clj (.on game-object (clj->phaser event) (clj->phaser fn) (clj->phaser context))))) (defn once "Add a one-time listener for a given event. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * event (string | symbol) - The event name. * fn (function) - The listener function. * context (*) {optional} - The context to invoke the listener with. Returns: Phaser.Events.EventEmitter - `this`." ([game-object event fn] (phaser->clj (.once game-object (clj->phaser event) (clj->phaser fn)))) ([game-object event fn context] (phaser->clj (.once game-object (clj->phaser event) (clj->phaser fn) (clj->phaser context))))) (defn remove-all-listeners "Remove all listeners, or those of the specified event. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * event (string | symbol) {optional} - The event name. Returns: Phaser.Events.EventEmitter - `this`." ([game-object] (phaser->clj (.removeAllListeners game-object))) ([game-object event] (phaser->clj (.removeAllListeners game-object (clj->phaser event))))) (defn remove-interactive "If this Game Object has previously been enabled for input, this will queue it for removal, causing it to no longer be interactive. The removal happens on the next game step, it is not immediate. The Interactive Object that was assigned to this Game Object will be destroyed, removed from the Input Manager and cleared from this Game Object. If you wish to re-enable this Game Object at a later date you will need to re-create its InteractiveObject by calling `setInteractive` again. If you wish to only temporarily stop an object from receiving input then use `disableInteractive` instead, as that toggles the interactive state, where-as this erases it completely. If you wish to resize a hit area, don't remove and then set it as being interactive. Instead, access the hitarea object directly and resize the shape being used. I.e.: `sprite.input.hitArea.setSize(width, height)` (assuming the shape is a Rectangle, which it is by default.) Returns: this - This GameObject." ([game-object] (phaser->clj (.removeInteractive game-object)))) (defn remove-listener "Remove the listeners of a given event. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * event (string | symbol) - The event name. * fn (function) {optional} - Only remove the listeners that match this function. * context (*) {optional} - Only remove the listeners that have this context. * once (boolean) {optional} - Only remove one-time listeners. Returns: Phaser.Events.EventEmitter - `this`." ([game-object event] (phaser->clj (.removeListener game-object (clj->phaser event)))) ([game-object event fn] (phaser->clj (.removeListener game-object (clj->phaser event) (clj->phaser fn)))) ([game-object event fn context] (phaser->clj (.removeListener game-object (clj->phaser event) (clj->phaser fn) (clj->phaser context)))) ([game-object event fn context once] (phaser->clj (.removeListener game-object (clj->phaser event) (clj->phaser fn) (clj->phaser context) (clj->phaser once))))) (defn set-active "Sets the `active` property of this Game Object and returns this Game Object for further chaining. A Game Object with its `active` property set to `true` will be updated by the Scenes UpdateList. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * value (boolean) - True if this Game Object should be set as active, false if not. Returns: this - This GameObject." ([game-object value] (phaser->clj (.setActive game-object (clj->phaser value))))) (defn set-data "Allows you to store a key value pair within this Game Objects Data Manager. If the Game Object has not been enabled for data (via `setDataEnabled`) then it will be enabled before setting the value. If the key doesn't already exist in the Data Manager then it is created. ```javascript sprite.setData('name', 'Red Gem Stone'); ``` You can also pass in an object of key value pairs as the first argument: ```javascript sprite.setData({ name: '<NAME>', level: 2, owner: 'Link', gold: 50 }); ``` To get a value back again you can call `getData`: ```javascript sprite.getData('gold'); ``` Or you can access the value directly via the `values` property, where it works like any other variable: ```javascript sprite.data.values.gold += 50; ``` When the value is first set, a `setdata` event is emitted from this Game Object. If the key already exists, a `changedata` event is emitted instead, along an event named after the key. For example, if you updated an existing key called `<KEY>` then it would emit the event `changedata-PlayerLives`. These events will be emitted regardless if you use this method to set the value, or the direct `values` setter. Please note that the data keys are case-sensitive and must be valid JavaScript Object property strings. This means the keys `gold` and `Gold` are treated as two unique values within the Data Manager. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * key (string | object) - The key to set the value for. Or an object of key value pairs. If an object the `data` argument is ignored. * data (*) {optional} - The value to set for the given key. If an object is provided as the key this argument is ignored. Returns: this - This GameObject." ([game-object key] (phaser->clj (.setData game-object (clj->phaser key)))) ([game-object key data] (phaser->clj (.setData game-object (clj->phaser key) (clj->phaser data))))) (defn set-data-enabled "Adds a Data Manager component to this Game Object. Returns: this - This GameObject." ([game-object] (phaser->clj (.setDataEnabled game-object)))) (defn set-interactive "Pass this Game Object to the Input Manager to enable it for Input. Input works by using hit areas, these are nearly always geometric shapes, such as rectangles or circles, that act as the hit area for the Game Object. However, you can provide your own hit area shape and callback, should you wish to handle some more advanced input detection. If no arguments are provided it will try and create a rectangle hit area based on the texture frame the Game Object is using. If this isn't a texture-bound object, such as a Graphics or BitmapText object, this will fail, and you'll need to provide a specific shape for it to use. You can also provide an Input Configuration Object as the only argument to this method. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * shape (Phaser.Types.Input.InputConfiguration | any) {optional} - Either an input configuration object, or a geometric shape that defines the hit area for the Game Object. If not specified a Rectangle will be used. * callback (Phaser.Types.Input.HitAreaCallback) {optional} - A callback to be invoked when the Game Object is interacted with. If you provide a shape you must also provide a callback. * drop-zone (boolean) {optional} - Should this Game Object be treated as a drop zone target? Returns: this - This GameObject." ([game-object] (phaser->clj (.setInteractive game-object))) ([game-object shape] (phaser->clj (.setInteractive game-object (clj->phaser shape)))) ([game-object shape callback] (phaser->clj (.setInteractive game-object (clj->phaser shape) (clj->phaser callback)))) ([game-object shape callback drop-zone] (phaser->clj (.setInteractive game-object (clj->phaser shape) (clj->phaser callback) (clj->phaser drop-zone))))) (defn set-name "Sets the `name` property of this Game Object and returns this Game Object for further chaining. The `name` property is not populated by Phaser and is presented for your own use. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * value (string) - The name to be given to this Game Object. Returns: this - This GameObject." ([game-object value] (phaser->clj (.setName game-object (clj->phaser value))))) (defn set-state "Sets the current state of this Game Object. Phaser itself will never modify the State of a Game Object, although plugins may do so. For example, a Game Object could change from a state of 'moving', to 'attacking', to 'dead'. The state value should typically be an integer (ideally mapped to a constant in your game code), but could also be a string. It is recommended to keep it light and simple. If you need to store complex data about your Game Object, look at using the Data Component instead. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * value (integer | string) - The state of the Game Object. Returns: this - This GameObject." ([game-object value] (phaser->clj (.setState game-object (clj->phaser value))))) (defn shutdown "Removes all listeners." ([game-object] (phaser->clj (.shutdown game-object)))) (defn to-json "Returns a JSON representation of the Game Object. Returns: Phaser.Types.GameObjects.JSONGameObject - A JSON representation of the Game Object." ([game-object] (phaser->clj (.toJSON game-object)))) (defn update "To be overridden by custom GameObjects. Allows base objects to be used in a Pool. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * args (*) {optional} - args" ([game-object] (phaser->clj (.update game-object))) ([game-object args] (phaser->clj (.update game-object (clj->phaser args))))) (defn will-render "Compares the renderMask with the renderFlags to see if this Game Object will render or not. Also checks the Game Object against the given Cameras exclusion list. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * camera (Phaser.Cameras.Scene2D.Camera) - The Camera to check against this Game Object. Returns: boolean - True if the Game Object should be rendered, otherwise false." ([game-object camera] (phaser->clj (.willRender game-object (clj->phaser camera)))))
true
(ns phzr.game-objects.game-object (:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]] [phzr.impl.extend :as ex] [cljsjs.phaser]) (:refer-clojure :exclude [update])) (defn ->GameObject " Parameters: * scene (Phaser.Scene) - The Scene to which this Game Object belongs. * type (string) - A textual representation of the type of Game Object, i.e. `sprite`." ([scene type] (js/Phaser.GameObjects.GameObject. (clj->phaser scene) (clj->phaser type)))) (defn add-listener "Add a listener for a given event. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * event (string | symbol) - The event name. * fn (function) - The listener function. * context (*) {optional} - The context to invoke the listener with. Returns: Phaser.Events.EventEmitter - `this`." ([game-object event fn] (phaser->clj (.addListener game-object (clj->phaser event) (clj->phaser fn)))) ([game-object event fn context] (phaser->clj (.addListener game-object (clj->phaser event) (clj->phaser fn) (clj->phaser context))))) (defn destroy "Destroys this Game Object removing it from the Display List and Update List and severing all ties to parent resources. Also removes itself from the Input Manager and Physics Manager if previously enabled. Use this to remove a Game Object from your game if you don't ever plan to use it again. As long as no reference to it exists within your own code it should become free for garbage collection by the browser. If you just want to temporarily disable an object then look at using the Game Object Pool instead of destroying it, as destroyed objects cannot be resurrected. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * from-scene (boolean) {optional} - Is this Game Object being destroyed as the result of a Scene shutdown?" ([game-object] (phaser->clj (.destroy game-object))) ([game-object from-scene] (phaser->clj (.destroy game-object (clj->phaser from-scene))))) (defn disable-interactive "If this Game Object has previously been enabled for input, this will disable it. An object that is disabled for input stops processing or being considered for input events, but can be turned back on again at any time by simply calling `setInteractive()` with no arguments provided. If want to completely remove interaction from this Game Object then use `removeInteractive` instead. Returns: this - This GameObject." ([game-object] (phaser->clj (.disableInteractive game-object)))) (defn emit "Calls each of the listeners registered for a given event. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * event (string | symbol) - The event name. * args (*) {optional} - Additional arguments that will be passed to the event handler. Returns: boolean - `true` if the event had listeners, else `false`." ([game-object event] (phaser->clj (.emit game-object (clj->phaser event)))) ([game-object event args] (phaser->clj (.emit game-object (clj->phaser event) (clj->phaser args))))) (defn event-names "Return an array listing the events for which the emitter has registered listeners. Returns: array - " ([game-object] (phaser->clj (.eventNames game-object)))) (defn get-data "Retrieves the value for the given key in this Game Objects Data Manager, or undefined if it doesn't exist. You can also access values via the `values` object. For example, if you had a key called `gold` you can do either: ```javascript sprite.getData('gold'); ``` Or access the value directly: ```javascript sprite.data.values.gold; ``` You can also pass in an array of keys, in which case an array of values will be returned: ```javascript sprite.getData([ 'gold', 'armor', 'health' ]); ``` This approach is useful for destructuring arrays in ES6. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * key (string | Array.<string>) - The key of the value to retrieve, or an array of keys. Returns: * - The value belonging to the given key, or an array of values, the order of which will match the input array." ([game-object key] (phaser->clj (.getData game-object (clj->phaser key))))) (defn get-index-list "Returns an array containing the display list index of either this Game Object, or if it has one, its parent Container. It then iterates up through all of the parent containers until it hits the root of the display list (which is index 0 in the returned array). Used internally by the InputPlugin but also useful if you wish to find out the display depth of this Game Object and all of its ancestors. Returns: Array.<integer> - An array of display list position indexes." ([game-object] (phaser->clj (.getIndexList game-object)))) (defn listener-count "Return the number of listeners listening to a given event. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * event (string | symbol) - The event name. Returns: number - The number of listeners." ([game-object event] (phaser->clj (.listenerCount game-object (clj->phaser event))))) (defn listeners "Return the listeners registered for a given event. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * event (string | symbol) - The event name. Returns: array - The registered listeners." ([game-object event] (phaser->clj (.listeners game-object (clj->phaser event))))) (defn off "Remove the listeners of a given event. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * event (string | symbol) - The event name. * fn (function) {optional} - Only remove the listeners that match this function. * context (*) {optional} - Only remove the listeners that have this context. * once (boolean) {optional} - Only remove one-time listeners. Returns: Phaser.Events.EventEmitter - `this`." ([game-object event] (phaser->clj (.off game-object (clj->phaser event)))) ([game-object event fn] (phaser->clj (.off game-object (clj->phaser event) (clj->phaser fn)))) ([game-object event fn context] (phaser->clj (.off game-object (clj->phaser event) (clj->phaser fn) (clj->phaser context)))) ([game-object event fn context once] (phaser->clj (.off game-object (clj->phaser event) (clj->phaser fn) (clj->phaser context) (clj->phaser once))))) (defn on "Add a listener for a given event. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * event (string | symbol) - The event name. * fn (function) - The listener function. * context (*) {optional} - The context to invoke the listener with. Returns: Phaser.Events.EventEmitter - `this`." ([game-object event fn] (phaser->clj (.on game-object (clj->phaser event) (clj->phaser fn)))) ([game-object event fn context] (phaser->clj (.on game-object (clj->phaser event) (clj->phaser fn) (clj->phaser context))))) (defn once "Add a one-time listener for a given event. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * event (string | symbol) - The event name. * fn (function) - The listener function. * context (*) {optional} - The context to invoke the listener with. Returns: Phaser.Events.EventEmitter - `this`." ([game-object event fn] (phaser->clj (.once game-object (clj->phaser event) (clj->phaser fn)))) ([game-object event fn context] (phaser->clj (.once game-object (clj->phaser event) (clj->phaser fn) (clj->phaser context))))) (defn remove-all-listeners "Remove all listeners, or those of the specified event. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * event (string | symbol) {optional} - The event name. Returns: Phaser.Events.EventEmitter - `this`." ([game-object] (phaser->clj (.removeAllListeners game-object))) ([game-object event] (phaser->clj (.removeAllListeners game-object (clj->phaser event))))) (defn remove-interactive "If this Game Object has previously been enabled for input, this will queue it for removal, causing it to no longer be interactive. The removal happens on the next game step, it is not immediate. The Interactive Object that was assigned to this Game Object will be destroyed, removed from the Input Manager and cleared from this Game Object. If you wish to re-enable this Game Object at a later date you will need to re-create its InteractiveObject by calling `setInteractive` again. If you wish to only temporarily stop an object from receiving input then use `disableInteractive` instead, as that toggles the interactive state, where-as this erases it completely. If you wish to resize a hit area, don't remove and then set it as being interactive. Instead, access the hitarea object directly and resize the shape being used. I.e.: `sprite.input.hitArea.setSize(width, height)` (assuming the shape is a Rectangle, which it is by default.) Returns: this - This GameObject." ([game-object] (phaser->clj (.removeInteractive game-object)))) (defn remove-listener "Remove the listeners of a given event. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * event (string | symbol) - The event name. * fn (function) {optional} - Only remove the listeners that match this function. * context (*) {optional} - Only remove the listeners that have this context. * once (boolean) {optional} - Only remove one-time listeners. Returns: Phaser.Events.EventEmitter - `this`." ([game-object event] (phaser->clj (.removeListener game-object (clj->phaser event)))) ([game-object event fn] (phaser->clj (.removeListener game-object (clj->phaser event) (clj->phaser fn)))) ([game-object event fn context] (phaser->clj (.removeListener game-object (clj->phaser event) (clj->phaser fn) (clj->phaser context)))) ([game-object event fn context once] (phaser->clj (.removeListener game-object (clj->phaser event) (clj->phaser fn) (clj->phaser context) (clj->phaser once))))) (defn set-active "Sets the `active` property of this Game Object and returns this Game Object for further chaining. A Game Object with its `active` property set to `true` will be updated by the Scenes UpdateList. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * value (boolean) - True if this Game Object should be set as active, false if not. Returns: this - This GameObject." ([game-object value] (phaser->clj (.setActive game-object (clj->phaser value))))) (defn set-data "Allows you to store a key value pair within this Game Objects Data Manager. If the Game Object has not been enabled for data (via `setDataEnabled`) then it will be enabled before setting the value. If the key doesn't already exist in the Data Manager then it is created. ```javascript sprite.setData('name', 'Red Gem Stone'); ``` You can also pass in an object of key value pairs as the first argument: ```javascript sprite.setData({ name: 'PI:NAME:<NAME>END_PI', level: 2, owner: 'Link', gold: 50 }); ``` To get a value back again you can call `getData`: ```javascript sprite.getData('gold'); ``` Or you can access the value directly via the `values` property, where it works like any other variable: ```javascript sprite.data.values.gold += 50; ``` When the value is first set, a `setdata` event is emitted from this Game Object. If the key already exists, a `changedata` event is emitted instead, along an event named after the key. For example, if you updated an existing key called `PI:KEY:<KEY>END_PI` then it would emit the event `changedata-PlayerLives`. These events will be emitted regardless if you use this method to set the value, or the direct `values` setter. Please note that the data keys are case-sensitive and must be valid JavaScript Object property strings. This means the keys `gold` and `Gold` are treated as two unique values within the Data Manager. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * key (string | object) - The key to set the value for. Or an object of key value pairs. If an object the `data` argument is ignored. * data (*) {optional} - The value to set for the given key. If an object is provided as the key this argument is ignored. Returns: this - This GameObject." ([game-object key] (phaser->clj (.setData game-object (clj->phaser key)))) ([game-object key data] (phaser->clj (.setData game-object (clj->phaser key) (clj->phaser data))))) (defn set-data-enabled "Adds a Data Manager component to this Game Object. Returns: this - This GameObject." ([game-object] (phaser->clj (.setDataEnabled game-object)))) (defn set-interactive "Pass this Game Object to the Input Manager to enable it for Input. Input works by using hit areas, these are nearly always geometric shapes, such as rectangles or circles, that act as the hit area for the Game Object. However, you can provide your own hit area shape and callback, should you wish to handle some more advanced input detection. If no arguments are provided it will try and create a rectangle hit area based on the texture frame the Game Object is using. If this isn't a texture-bound object, such as a Graphics or BitmapText object, this will fail, and you'll need to provide a specific shape for it to use. You can also provide an Input Configuration Object as the only argument to this method. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * shape (Phaser.Types.Input.InputConfiguration | any) {optional} - Either an input configuration object, or a geometric shape that defines the hit area for the Game Object. If not specified a Rectangle will be used. * callback (Phaser.Types.Input.HitAreaCallback) {optional} - A callback to be invoked when the Game Object is interacted with. If you provide a shape you must also provide a callback. * drop-zone (boolean) {optional} - Should this Game Object be treated as a drop zone target? Returns: this - This GameObject." ([game-object] (phaser->clj (.setInteractive game-object))) ([game-object shape] (phaser->clj (.setInteractive game-object (clj->phaser shape)))) ([game-object shape callback] (phaser->clj (.setInteractive game-object (clj->phaser shape) (clj->phaser callback)))) ([game-object shape callback drop-zone] (phaser->clj (.setInteractive game-object (clj->phaser shape) (clj->phaser callback) (clj->phaser drop-zone))))) (defn set-name "Sets the `name` property of this Game Object and returns this Game Object for further chaining. The `name` property is not populated by Phaser and is presented for your own use. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * value (string) - The name to be given to this Game Object. Returns: this - This GameObject." ([game-object value] (phaser->clj (.setName game-object (clj->phaser value))))) (defn set-state "Sets the current state of this Game Object. Phaser itself will never modify the State of a Game Object, although plugins may do so. For example, a Game Object could change from a state of 'moving', to 'attacking', to 'dead'. The state value should typically be an integer (ideally mapped to a constant in your game code), but could also be a string. It is recommended to keep it light and simple. If you need to store complex data about your Game Object, look at using the Data Component instead. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * value (integer | string) - The state of the Game Object. Returns: this - This GameObject." ([game-object value] (phaser->clj (.setState game-object (clj->phaser value))))) (defn shutdown "Removes all listeners." ([game-object] (phaser->clj (.shutdown game-object)))) (defn to-json "Returns a JSON representation of the Game Object. Returns: Phaser.Types.GameObjects.JSONGameObject - A JSON representation of the Game Object." ([game-object] (phaser->clj (.toJSON game-object)))) (defn update "To be overridden by custom GameObjects. Allows base objects to be used in a Pool. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * args (*) {optional} - args" ([game-object] (phaser->clj (.update game-object))) ([game-object args] (phaser->clj (.update game-object (clj->phaser args))))) (defn will-render "Compares the renderMask with the renderFlags to see if this Game Object will render or not. Also checks the Game Object against the given Cameras exclusion list. Parameters: * game-object (Phaser.GameObjects.GameObject) - Targeted instance for method * camera (Phaser.Cameras.Scene2D.Camera) - The Camera to check against this Game Object. Returns: boolean - True if the Game Object should be rendered, otherwise false." ([game-object camera] (phaser->clj (.willRender game-object (clj->phaser camera)))))
[ { "context": " be done on two expressions.\"\n :author \"Sean Dawson\"}\n nanoweave.ast.binary-arithmetic\n (:require [s", "end": 133, "score": 0.9998384714126587, "start": 122, "tag": "NAME", "value": "Sean Dawson" } ]
src/nanoweave/ast/binary_arithmetic.clj
NoxHarmonium/nanoweave
0
(ns ^{:doc "Syntax that represents arithmetic operations that can be done on two expressions." :author "Sean Dawson"} nanoweave.ast.binary-arithmetic (:require [schema.core :as s] [nanoweave.ast.base :refer [Resolvable]])) (s/defrecord AddOp [left :- Resolvable right :- Resolvable]) (s/defrecord SubOp [left :- Resolvable right :- Resolvable]) (s/defrecord MultOp [left :- Resolvable right :- Resolvable]) (s/defrecord DivOp [left :- Resolvable right :- Resolvable]) (s/defrecord ModOp [left :- Resolvable right :- Resolvable])
24156
(ns ^{:doc "Syntax that represents arithmetic operations that can be done on two expressions." :author "<NAME>"} nanoweave.ast.binary-arithmetic (:require [schema.core :as s] [nanoweave.ast.base :refer [Resolvable]])) (s/defrecord AddOp [left :- Resolvable right :- Resolvable]) (s/defrecord SubOp [left :- Resolvable right :- Resolvable]) (s/defrecord MultOp [left :- Resolvable right :- Resolvable]) (s/defrecord DivOp [left :- Resolvable right :- Resolvable]) (s/defrecord ModOp [left :- Resolvable right :- Resolvable])
true
(ns ^{:doc "Syntax that represents arithmetic operations that can be done on two expressions." :author "PI:NAME:<NAME>END_PI"} nanoweave.ast.binary-arithmetic (:require [schema.core :as s] [nanoweave.ast.base :refer [Resolvable]])) (s/defrecord AddOp [left :- Resolvable right :- Resolvable]) (s/defrecord SubOp [left :- Resolvable right :- Resolvable]) (s/defrecord MultOp [left :- Resolvable right :- Resolvable]) (s/defrecord DivOp [left :- Resolvable right :- Resolvable]) (s/defrecord ModOp [left :- Resolvable right :- Resolvable])
[ { "context": " (json/write-str {:apiKey \"testKey\" :user_email \"email1@email.com\" :user_name \"testName\"})) ;TODO change away from ", "end": 9906, "score": 0.9991467595100403, "start": 9890, "tag": "EMAIL", "value": "email1@email.com" }, { "context": "stKey\" :user_email \"email1@email.com\" :user_name \"testName\"})) ;TODO change away from being mocked\n\n ;; Pub", "end": 9928, "score": 0.9297285079956055, "start": 9920, "tag": "USERNAME", "value": "testName" }, { "context": " [:br]\n [:a {:href \"https://github.com/lsenjov/hphelper\"} \"Source Code\"][:br]\n ]]))\n\n", "end": 16098, "score": 0.9991379380226135, "start": 16091, "tag": "USERNAME", "value": "lsenjov" } ]
src/hphelper/server/handler.clj
lsenjov/hphelper
2
(ns hphelper.server.handler (:require [compojure.core :refer :all] [compojure.route :as route] [ring.middleware.defaults :refer [wrap-defaults api-defaults]] [taoensso.timbre :as log] [clojure.data.json :as json] ;; Standalone server [org.httpkit.server] ;; Character handling [hphelper.server.chargen.generator :as cgen] [hphelper.server.chargen.charform :as cform] [hphelper.server.chargen.print :as cprint] [hphelper.server.chargen.select :as csel] ;; Scenario handling [hphelper.server.scengen.scenform :as sform] [hphelper.server.scengen.generator :as sgen] [hphelper.server.scengen.print :as sprint] [hphelper.server.scengen.select :as ssel] [hphelper.server.shared.saveload :as sl] [hiccup.core :refer :all] ;; Shared items [hphelper.server.shared.sql :as sql] ;; Sector Generator [hphelper.server.sectorgen.generator :as secgen] ;; Live paranoia [hphelper.server.live.view :as lview] [hphelper.server.live.api :as lapi] ;; For hiding items from players [hphelper.server.shared.encrypt :as c] ;; Since this will slowly be changing to an api, json is coming [clojure.data.json :as json] ;; Allowing cross-site requests [ring.middleware.cors :refer [wrap-cors]] ;; For turning on and off asserts [clojure.spec.alpha :as s] ) (:gen-class)) ;; Set logging level to info, so we don't overload the server with logging (log/set-level! :info) (log/info "Compile asserts is set to:" s/*compile-asserts*) (log/info "System property is:" (System/getProperty "clojure.spec.compile-asserts")) (defn- parse-long "Parses a long, returns 0 if fails" [^String i] (try (Long/parseLong i) (catch NumberFormatException e (log/error "parse-long: could not parse:" i "Returning 0 instead.") 0) ) ) (defroutes app-routes ;; CHARACTERS ;; Show page to select from list or create new character (GET "/char/" {params :params baseURL :context} (if (:char_id params) (cprint/html-print-sheet-one-page (sl/load-char-from-db (:char_id params))) (csel/print-select-page baseURL))) ;; Select options to create a new character (GET "/char/gen/" {baseURL :context} (cform/html-select-page)) ;; Create a new character from the options above and save it (POST "/char/gen/" {params :params} (html [:div (-> params (cform/convert-to-char) (cgen/create-character) (sl/save-char-to-db) (sl/load-char-from-db) (cprint/html-print-sheet-one-page)) ])) ;; Upload a new character, return the character as edn under the :char tag (POST "/api/char/new/" request (let [body (ring.util.request/body-string request)] (log/trace "/api/char/new/ body:" body) (let [charid (-> body ;; Change to a map format with the char edn in :newchar clojure.edn/read-string ;; Get the char edn :newchar ;; Transform to an actual character file clojure.edn/read-string ;; New characters need drawbacks and mutations (cgen/create-character) ;; Save to db, store the id in charid (sl/save-char-to-db) )] (-> charid (sl/load-char-from-db) ;; Add the id from the database to the character ;(assoc :char_id charid) ; Should already be done upon loading pr-str ((fn [s] {:char s})) json/write-str ) ) ) ) ;; TODO currently just creates a new character slot each time, need to update the old one? ;; Returns the character (POST "/api/char/update/" request (let [c (-> request ring.util.request/body-string ;; Change to a map format with the char edn in :newchar clojure.edn/read-string ;; Get the char edn :newchar ;; Transform to an actual character file clojure.edn/read-string ) charid (:char_id c) ] (log/trace "/api/char/update/" "charid:" charid "character:") ;; Update it (if charid (do (log/trace "Updating character" charid "in database.") (sl/update-char (int charid) c) (json/write-str {:status "okay"}) ) (do (log/error "Could not update character" charid "in database.") (json/write-str {:status "error"}) ) ) ) ) ;; Display a character (GET "/char/print/" {params :params} (cprint/html-print-sheet-one-page (sl/load-char-from-db (:char_id params)))) ;; Gets the edn representation of a character (GET "/api/char/get/" {{charid :char_id} :params} (do (log/trace "Getting character id:" charid) (pr-str (sl/load-char-from-db (Integer/parseInt charid))))) (GET "/api/char/get-filtered/" {{filter-string :filter_string} :params} (do (log/tracef "Getting characters for filter string '%s'" filter-string) (pr-str (sl/get-filtered-char-list filter-string)))) ;; SCENARIOS ;; Show page to create a new scenario, or select a partially completed or fully completed scenario ;; If contains a :scen_id, loads completed scenario and allows options for printing parts or all (GET "/scen/" {params :params baseURL :context} (if (params :scen_id) (ssel/print-crisis-page (params :scen_id) baseURL) (ssel/print-select-page baseURL))) ;; Show page to create a new scenario (GET "/scen/gen/" {baseURL :context} (sform/html-select-page baseURL)) ;; Create a brand new scenario without programmers picked (POST "/scen/gen/" {params :params baseURL :context} (-> params (sform/from-select-to-scenmap) (sgen/create-scenario) (sl/save-scen-to-db) ((partial sform/html-scen-to-full-page baseURL)))) ;; Get scenario without programmers in order to pick programmers (GET "/scen/full/" {params :params baseURL :context} (sform/html-scen-to-full-page baseURL (:scen_id params))) ;; Add programmers to scenario and create a new record (POST "/scen/full/" {params :params baseURL :context} (-> params (sform/from-scenmap-to-full) (sl/save-fullscen-to-db) (ssel/print-crisis-page baseURL))) ;; Prints an entire scenario with options, including sheets for each character if desired (GET "/scen/print/" {params :params} (sprint/html-print-optional (sl/load-fullscen-from-db (params :scen_id)) (keys params))) ;; Prints a single session sheet for a character for a specific character (GET "/scen/print/char/" {params :params} (log/trace "Char sheet params:" params) (let [scen (sl/load-fullscen-from-db (Integer/parseInt (:scen_id params)))] (println (:hps scen)) (sprint/html-print-player-sheet scen ((:hps scen) (Integer/parseInt (:p_id params)))))) ;; Character Creation (GET "/api/db/get-societies/" {params :params} (log/trace "/api/db/get-societies/") (json/write-str (sql/get-society-all)) ) (GET "/api/db/get-mutations/" {params :params} (log/trace "/api/db/get-mutations/") (json/write-str (sql/get-mutation-all)) ) (GET "/api/db/get-drawbacks/" {params :params} (log/trace "/api/db/get-drawbacks/") (json/write-str (sql/get-drawback-all)) ) (GET "/api/db/get-skills/" {params :params} (log/trace "/api/db/get-skills/") (json/write-str (sql/get-skills-all)) ) ;; Hacky way to print a player's entire player sheet (GET "/player/:scen_id/:p_id/" {{scen_id :scen_id p_id :p_id} :params baseURL :context} (let [scen (sl/load-fullscen-from-db (c/int-show (Integer/parseInt scen_id)))] (sprint/html-print-player-sheet scen ((:hps scen) (c/int-show (Integer/parseInt p_id)))))) ;; Prints the minion sheet from a single scenario (GET "/minions/:scen_id/" {{scen_id :scen_id} :params baseURL :context} (sprint/html-print-optional (sl/load-fullscen-from-db (c/int-show (Integer/parseInt scen_id))) '(:minions))) ;; SECTORGEN ;; Prints 7 randomly generated sectors (GET "/sectorgen/" [] (secgen/html-print-neighbours 7)) ;; LIVE (GET "/live/new/:scen_id/" {{scen_id :scen_id} :params headers :headers baseURL :context :as all} (lview/new-game baseURL scen_id)) (GET "/live/view/:uuid/" {{uid :uuid} :params baseURL :context} (lview/view-game baseURL uid)) (GET "/live/view/:uuid/:confirm/" {{uid :uuid confirm :confirm} :params baseURL :context} (lview/edit-game baseURL uid confirm)) (GET "/live/view/:uuid/:confirm/:index/:amount/" {{uid :uuid confirm :confirm index :index amount :amount} :params baseURL :context} (lview/edit-game baseURL uid confirm index amount)) (GET "/live/playerview/:guid/:uuid/" {{guid :guid uuid :uuid} :params baseURL :context} (lview/view-game-player baseURL guid uuid)) ;; API ;; User login/logout (GET "/api/user/login/" {{:keys [email password]} :params} ;(json/write-str {:error "Not Implemented"})) ;TODO (json/write-str {:apiKey "testKey" :user_email "email1@email.com" :user_name "testName"})) ;TODO change away from being mocked ;; Public endpoints (GET "/api/public/:gameUuid/updates/:lastUpdated/" {{gameUuid :gameUuid userUuid :userUuid lastUpdated :lastUpdated} :params} (json/write-str (lapi/get-updated-public gameUuid (parse-long lastUpdated)))) (GET "/api/public/updates/" {{:keys [gameUuid userUuid lastUpdated]} :params} (json/write-str (lapi/get-updated-public gameUuid (parse-long lastUpdated)))) (GET "/api/public/:gameUuid/indicies/" {{gameUuid :gameUuid userUuid :userUuid} :params} (json/write-str (lapi/get-indicies gameUuid))) (GET "/api/public/:gameUuid/news/" {{gameUuid :gameUuid userUuid :userUuid} :params} (json/write-str (lapi/get-news gameUuid))) (GET "/api/public/:gameUuid/cbay/" {{gameUuid :gameUuid userUuid :userUuid} :params} (json/write-str (lapi/get-cbay gameUuid))) (GET "/api/public/:gameUuid/access/" {{gameUuid :gameUuid userUuid :userUuid} :params} (json/write-str (lapi/get-current-access gameUuid))) (GET "/api/public/:gameUuid/minions/" {{gameUuid :gameUuid userUuid :userUuid} :params} (json/write-str (lapi/get-minions gameUuid))) ;; Player endpoints ;; New api (GET "/api/player/updates/" {{:keys [gameUuid userUuid lastUpdated]} :params} (json/write-str (lapi/get-updated-player gameUuid userUuid (parse-long lastUpdated)))) (GET "/api/player/purchaseminion/" {{:keys [gameUuid userUuid sgid minionid]} :params} (json/write-str (lapi/player-buy-minion gameUuid userUuid sgid minionid))) (GET "/api/player/callminion/" {{:keys [gameUuid userUuid sgid minionid privateCall]} :params} (json/write-str (lapi/player-call-minion gameUuid userUuid sgid minionid privateCall))) (GET "/api/player/sendaccess/" {{:keys [gameUuid userUuid playerto amount]} :params} (json/write-str (lapi/player-send-access gameUuid userUuid playerto amount))) (GET "/api/player/trade-investments/" {{:keys [gameUuid userUuid group amount]} :params} (json/write-str (lapi/player-trade-investment gameUuid userUuid group amount))) (GET "/api/player/add-minion/" {{:keys [gameUuid userUuid sgid minionName minionClearance minionDesc]} :params} (json/write-str (lapi/player-add-custom-minion gameUuid userUuid sgid minionName minionClearance minionDesc))) ;; Old api (GET "/api/player/:gameUuid/:userUuid/updates/:lastUpdated/" {{gameUuid :gameUuid userUuid :userUuid lastUpdated :lastUpdated} :params} (json/write-str (lapi/get-updated-player gameUuid userUuid (parse-long lastUpdated)))) (GET "/api/player/:gameUuid/:userUuid/charsheet/" {{gameUuid :gameUuid userUuid :userUuid} :params} (json/write-str (lapi/get-player-character-sheet gameUuid userUuid))) (GET "/api/player/:gameUuid/:userUuid/societymissions/" {{gameUuid :gameUuid userUuid :userUuid} :params} (json/write-str (lapi/get-player-society-missions gameUuid userUuid))) (GET "/api/player/:gameUuid/:userUuid/minions/" {{gameUuid :gameUuid userUuid :userUuid} :params} (json/write-str (lapi/get-minions gameUuid userUuid))) ;; Admin endpoints ;; New api (GET "/api/admin/updates/" {{:keys [gameUuid userUuid lastUpdated]} :params} (json/write-str (lapi/get-updated-admin gameUuid userUuid (parse-long lastUpdated)))) (GET "/api/admin/set-sg-owner/" {{:keys [gameUuid userUuid sgid newOwner]} :params} (json/write-str (lapi/admin-set-sg-owner gameUuid userUuid sgid newOwner))) (GET "/api/admin/modify-index/" {{:keys [gameUuid userUuid ind amount]} :params} (lapi/admin-modify-index gameUuid userUuid ind amount)) (GET "/api/admin/modify-access/" {{:keys [gameUuid userUuid player amount]} :params} (lapi/admin-modify-access gameUuid userUuid player amount)) (GET "/api/admin/modify-public-standing/" {{:keys [gameUuid userUuid player amount]} :params} (log/trace "modify-public-standing:" gameUuid userUuid player amount) (json/write-str (lapi/admin-modify-public-standing gameUuid userUuid player amount))) (GET "/api/admin/sync-chars/" ;; Saves characters to the database {{:keys [gameUuid userUuid]} :params} (json/write-str (lapi/sync-chars gameUuid userUuid))) (GET "/api/admin/lock-zone/" ;; Locks or unlocks a zone {{:keys [gameUuid userUuid status]} :params} (json/write-str (lapi/admin-lock-zone gameUuid userUuid status))) (GET "/api/admin/call/next/" ;; Moves to the next call {{:keys [gameUuid userUuid]} :params} (json/write-str (lapi/admin-call-next gameUuid userUuid))) (GET "/api/admin/character/zap/" ;; Zaps a player {{:keys [gameUuid userUuid player]} :params} (json/write-str (lapi/admin-zap-character gameUuid userUuid player))) ;; Old api (GET "/api/admin/:gameUuid/:userUuid/debug/" {{gameUuid :gameUuid userUuid :userUuid} :params} (lapi/admin-debug gameUuid userUuid)) (GET "/api/admin/:gameUuid/:userUuid/valid/" {{gameUuid :gameUuid userUuid :userUuid} :params} (lapi/admin-validate-spec gameUuid userUuid)) (GET "/api/admin/:gameUuid/:userUuid/modify-index/:ind/:amount/" {{gameUuid :gameUuid userUuid :userUuid ind :ind amount :amount} :params} (lapi/admin-modify-index gameUuid userUuid ind amount)) (GET "/api/admin/:gameUuid/:userUuid/minions/" {{gameUuid :gameUuid userUuid :userUuid} :params} (json/write-str (lapi/get-minions gameUuid userUuid))) (GET "/api/admin/:gameUuid/:userUuid/set-sg-owner/:sgid/:new-owner/" {{gameUuid :gameUuid userUuid :userUuid sgid :sgid newOwner :new-owner} :params} (json/write-str (lapi/admin-set-sg-owner gameUuid userUuid sgid newOwner))) ;; OTHER ;; Simple directs to the above (GET "/" {baseURL :context} (html [:html [:body [:a {:href (str baseURL "/scen/")} "Scenario Generator"][:br] [:a {:href (str baseURL "/char/")} "Character Generator"][:br] [:a {:href (str baseURL "/sectorgen/")} "Sector Generator"][:br] [:br] [:a {:href "https://github.com/lsenjov/hphelper"} "Source Code"][:br] ]])) ;; Turn on or off trace logging (GET "/admin/tracking/trace/" [] (do (log/set-level! :trace) "Logging set to trace.")) (GET "/admin/tracking/info/" [] (do (log/set-level! :info) "Logging set to info.")) (GET "/admin/spec/on/" [] (do (s/check-asserts true) "Asserts turned on.")) (GET "/admin/spec/off/" [] (do (s/check-asserts false) "Asserts turned off.")) (route/resources "/") (ANY "*" {{host "host" :as headers} :headers uri :uri :as all} (do (log/error "Invalid path. Host:" host "Uri:" uri) (json/write-str {:status "error" :message "Invalid endpoint"}))) ) (def app (-> app-routes (wrap-defaults api-defaults) ring.middleware.session/wrap-session ;; Allows cross-site requests for development purposes. Eventually will remove ;(wrap-cors #".*") ) ) (defn -main "Entry when not using it as an uberwar" [& _] (println "Starting Webserver") (org.httpkit.server/run-server app {:port 3000})) (comment ;; Turn on debug goodness (log/set-level! :trace) ;; Starts the server (def debug-server (org.httpkit.server/run-server app {:port 3000})) ;; Shuts down the server (debug-server) )
86224
(ns hphelper.server.handler (:require [compojure.core :refer :all] [compojure.route :as route] [ring.middleware.defaults :refer [wrap-defaults api-defaults]] [taoensso.timbre :as log] [clojure.data.json :as json] ;; Standalone server [org.httpkit.server] ;; Character handling [hphelper.server.chargen.generator :as cgen] [hphelper.server.chargen.charform :as cform] [hphelper.server.chargen.print :as cprint] [hphelper.server.chargen.select :as csel] ;; Scenario handling [hphelper.server.scengen.scenform :as sform] [hphelper.server.scengen.generator :as sgen] [hphelper.server.scengen.print :as sprint] [hphelper.server.scengen.select :as ssel] [hphelper.server.shared.saveload :as sl] [hiccup.core :refer :all] ;; Shared items [hphelper.server.shared.sql :as sql] ;; Sector Generator [hphelper.server.sectorgen.generator :as secgen] ;; Live paranoia [hphelper.server.live.view :as lview] [hphelper.server.live.api :as lapi] ;; For hiding items from players [hphelper.server.shared.encrypt :as c] ;; Since this will slowly be changing to an api, json is coming [clojure.data.json :as json] ;; Allowing cross-site requests [ring.middleware.cors :refer [wrap-cors]] ;; For turning on and off asserts [clojure.spec.alpha :as s] ) (:gen-class)) ;; Set logging level to info, so we don't overload the server with logging (log/set-level! :info) (log/info "Compile asserts is set to:" s/*compile-asserts*) (log/info "System property is:" (System/getProperty "clojure.spec.compile-asserts")) (defn- parse-long "Parses a long, returns 0 if fails" [^String i] (try (Long/parseLong i) (catch NumberFormatException e (log/error "parse-long: could not parse:" i "Returning 0 instead.") 0) ) ) (defroutes app-routes ;; CHARACTERS ;; Show page to select from list or create new character (GET "/char/" {params :params baseURL :context} (if (:char_id params) (cprint/html-print-sheet-one-page (sl/load-char-from-db (:char_id params))) (csel/print-select-page baseURL))) ;; Select options to create a new character (GET "/char/gen/" {baseURL :context} (cform/html-select-page)) ;; Create a new character from the options above and save it (POST "/char/gen/" {params :params} (html [:div (-> params (cform/convert-to-char) (cgen/create-character) (sl/save-char-to-db) (sl/load-char-from-db) (cprint/html-print-sheet-one-page)) ])) ;; Upload a new character, return the character as edn under the :char tag (POST "/api/char/new/" request (let [body (ring.util.request/body-string request)] (log/trace "/api/char/new/ body:" body) (let [charid (-> body ;; Change to a map format with the char edn in :newchar clojure.edn/read-string ;; Get the char edn :newchar ;; Transform to an actual character file clojure.edn/read-string ;; New characters need drawbacks and mutations (cgen/create-character) ;; Save to db, store the id in charid (sl/save-char-to-db) )] (-> charid (sl/load-char-from-db) ;; Add the id from the database to the character ;(assoc :char_id charid) ; Should already be done upon loading pr-str ((fn [s] {:char s})) json/write-str ) ) ) ) ;; TODO currently just creates a new character slot each time, need to update the old one? ;; Returns the character (POST "/api/char/update/" request (let [c (-> request ring.util.request/body-string ;; Change to a map format with the char edn in :newchar clojure.edn/read-string ;; Get the char edn :newchar ;; Transform to an actual character file clojure.edn/read-string ) charid (:char_id c) ] (log/trace "/api/char/update/" "charid:" charid "character:") ;; Update it (if charid (do (log/trace "Updating character" charid "in database.") (sl/update-char (int charid) c) (json/write-str {:status "okay"}) ) (do (log/error "Could not update character" charid "in database.") (json/write-str {:status "error"}) ) ) ) ) ;; Display a character (GET "/char/print/" {params :params} (cprint/html-print-sheet-one-page (sl/load-char-from-db (:char_id params)))) ;; Gets the edn representation of a character (GET "/api/char/get/" {{charid :char_id} :params} (do (log/trace "Getting character id:" charid) (pr-str (sl/load-char-from-db (Integer/parseInt charid))))) (GET "/api/char/get-filtered/" {{filter-string :filter_string} :params} (do (log/tracef "Getting characters for filter string '%s'" filter-string) (pr-str (sl/get-filtered-char-list filter-string)))) ;; SCENARIOS ;; Show page to create a new scenario, or select a partially completed or fully completed scenario ;; If contains a :scen_id, loads completed scenario and allows options for printing parts or all (GET "/scen/" {params :params baseURL :context} (if (params :scen_id) (ssel/print-crisis-page (params :scen_id) baseURL) (ssel/print-select-page baseURL))) ;; Show page to create a new scenario (GET "/scen/gen/" {baseURL :context} (sform/html-select-page baseURL)) ;; Create a brand new scenario without programmers picked (POST "/scen/gen/" {params :params baseURL :context} (-> params (sform/from-select-to-scenmap) (sgen/create-scenario) (sl/save-scen-to-db) ((partial sform/html-scen-to-full-page baseURL)))) ;; Get scenario without programmers in order to pick programmers (GET "/scen/full/" {params :params baseURL :context} (sform/html-scen-to-full-page baseURL (:scen_id params))) ;; Add programmers to scenario and create a new record (POST "/scen/full/" {params :params baseURL :context} (-> params (sform/from-scenmap-to-full) (sl/save-fullscen-to-db) (ssel/print-crisis-page baseURL))) ;; Prints an entire scenario with options, including sheets for each character if desired (GET "/scen/print/" {params :params} (sprint/html-print-optional (sl/load-fullscen-from-db (params :scen_id)) (keys params))) ;; Prints a single session sheet for a character for a specific character (GET "/scen/print/char/" {params :params} (log/trace "Char sheet params:" params) (let [scen (sl/load-fullscen-from-db (Integer/parseInt (:scen_id params)))] (println (:hps scen)) (sprint/html-print-player-sheet scen ((:hps scen) (Integer/parseInt (:p_id params)))))) ;; Character Creation (GET "/api/db/get-societies/" {params :params} (log/trace "/api/db/get-societies/") (json/write-str (sql/get-society-all)) ) (GET "/api/db/get-mutations/" {params :params} (log/trace "/api/db/get-mutations/") (json/write-str (sql/get-mutation-all)) ) (GET "/api/db/get-drawbacks/" {params :params} (log/trace "/api/db/get-drawbacks/") (json/write-str (sql/get-drawback-all)) ) (GET "/api/db/get-skills/" {params :params} (log/trace "/api/db/get-skills/") (json/write-str (sql/get-skills-all)) ) ;; Hacky way to print a player's entire player sheet (GET "/player/:scen_id/:p_id/" {{scen_id :scen_id p_id :p_id} :params baseURL :context} (let [scen (sl/load-fullscen-from-db (c/int-show (Integer/parseInt scen_id)))] (sprint/html-print-player-sheet scen ((:hps scen) (c/int-show (Integer/parseInt p_id)))))) ;; Prints the minion sheet from a single scenario (GET "/minions/:scen_id/" {{scen_id :scen_id} :params baseURL :context} (sprint/html-print-optional (sl/load-fullscen-from-db (c/int-show (Integer/parseInt scen_id))) '(:minions))) ;; SECTORGEN ;; Prints 7 randomly generated sectors (GET "/sectorgen/" [] (secgen/html-print-neighbours 7)) ;; LIVE (GET "/live/new/:scen_id/" {{scen_id :scen_id} :params headers :headers baseURL :context :as all} (lview/new-game baseURL scen_id)) (GET "/live/view/:uuid/" {{uid :uuid} :params baseURL :context} (lview/view-game baseURL uid)) (GET "/live/view/:uuid/:confirm/" {{uid :uuid confirm :confirm} :params baseURL :context} (lview/edit-game baseURL uid confirm)) (GET "/live/view/:uuid/:confirm/:index/:amount/" {{uid :uuid confirm :confirm index :index amount :amount} :params baseURL :context} (lview/edit-game baseURL uid confirm index amount)) (GET "/live/playerview/:guid/:uuid/" {{guid :guid uuid :uuid} :params baseURL :context} (lview/view-game-player baseURL guid uuid)) ;; API ;; User login/logout (GET "/api/user/login/" {{:keys [email password]} :params} ;(json/write-str {:error "Not Implemented"})) ;TODO (json/write-str {:apiKey "testKey" :user_email "<EMAIL>" :user_name "testName"})) ;TODO change away from being mocked ;; Public endpoints (GET "/api/public/:gameUuid/updates/:lastUpdated/" {{gameUuid :gameUuid userUuid :userUuid lastUpdated :lastUpdated} :params} (json/write-str (lapi/get-updated-public gameUuid (parse-long lastUpdated)))) (GET "/api/public/updates/" {{:keys [gameUuid userUuid lastUpdated]} :params} (json/write-str (lapi/get-updated-public gameUuid (parse-long lastUpdated)))) (GET "/api/public/:gameUuid/indicies/" {{gameUuid :gameUuid userUuid :userUuid} :params} (json/write-str (lapi/get-indicies gameUuid))) (GET "/api/public/:gameUuid/news/" {{gameUuid :gameUuid userUuid :userUuid} :params} (json/write-str (lapi/get-news gameUuid))) (GET "/api/public/:gameUuid/cbay/" {{gameUuid :gameUuid userUuid :userUuid} :params} (json/write-str (lapi/get-cbay gameUuid))) (GET "/api/public/:gameUuid/access/" {{gameUuid :gameUuid userUuid :userUuid} :params} (json/write-str (lapi/get-current-access gameUuid))) (GET "/api/public/:gameUuid/minions/" {{gameUuid :gameUuid userUuid :userUuid} :params} (json/write-str (lapi/get-minions gameUuid))) ;; Player endpoints ;; New api (GET "/api/player/updates/" {{:keys [gameUuid userUuid lastUpdated]} :params} (json/write-str (lapi/get-updated-player gameUuid userUuid (parse-long lastUpdated)))) (GET "/api/player/purchaseminion/" {{:keys [gameUuid userUuid sgid minionid]} :params} (json/write-str (lapi/player-buy-minion gameUuid userUuid sgid minionid))) (GET "/api/player/callminion/" {{:keys [gameUuid userUuid sgid minionid privateCall]} :params} (json/write-str (lapi/player-call-minion gameUuid userUuid sgid minionid privateCall))) (GET "/api/player/sendaccess/" {{:keys [gameUuid userUuid playerto amount]} :params} (json/write-str (lapi/player-send-access gameUuid userUuid playerto amount))) (GET "/api/player/trade-investments/" {{:keys [gameUuid userUuid group amount]} :params} (json/write-str (lapi/player-trade-investment gameUuid userUuid group amount))) (GET "/api/player/add-minion/" {{:keys [gameUuid userUuid sgid minionName minionClearance minionDesc]} :params} (json/write-str (lapi/player-add-custom-minion gameUuid userUuid sgid minionName minionClearance minionDesc))) ;; Old api (GET "/api/player/:gameUuid/:userUuid/updates/:lastUpdated/" {{gameUuid :gameUuid userUuid :userUuid lastUpdated :lastUpdated} :params} (json/write-str (lapi/get-updated-player gameUuid userUuid (parse-long lastUpdated)))) (GET "/api/player/:gameUuid/:userUuid/charsheet/" {{gameUuid :gameUuid userUuid :userUuid} :params} (json/write-str (lapi/get-player-character-sheet gameUuid userUuid))) (GET "/api/player/:gameUuid/:userUuid/societymissions/" {{gameUuid :gameUuid userUuid :userUuid} :params} (json/write-str (lapi/get-player-society-missions gameUuid userUuid))) (GET "/api/player/:gameUuid/:userUuid/minions/" {{gameUuid :gameUuid userUuid :userUuid} :params} (json/write-str (lapi/get-minions gameUuid userUuid))) ;; Admin endpoints ;; New api (GET "/api/admin/updates/" {{:keys [gameUuid userUuid lastUpdated]} :params} (json/write-str (lapi/get-updated-admin gameUuid userUuid (parse-long lastUpdated)))) (GET "/api/admin/set-sg-owner/" {{:keys [gameUuid userUuid sgid newOwner]} :params} (json/write-str (lapi/admin-set-sg-owner gameUuid userUuid sgid newOwner))) (GET "/api/admin/modify-index/" {{:keys [gameUuid userUuid ind amount]} :params} (lapi/admin-modify-index gameUuid userUuid ind amount)) (GET "/api/admin/modify-access/" {{:keys [gameUuid userUuid player amount]} :params} (lapi/admin-modify-access gameUuid userUuid player amount)) (GET "/api/admin/modify-public-standing/" {{:keys [gameUuid userUuid player amount]} :params} (log/trace "modify-public-standing:" gameUuid userUuid player amount) (json/write-str (lapi/admin-modify-public-standing gameUuid userUuid player amount))) (GET "/api/admin/sync-chars/" ;; Saves characters to the database {{:keys [gameUuid userUuid]} :params} (json/write-str (lapi/sync-chars gameUuid userUuid))) (GET "/api/admin/lock-zone/" ;; Locks or unlocks a zone {{:keys [gameUuid userUuid status]} :params} (json/write-str (lapi/admin-lock-zone gameUuid userUuid status))) (GET "/api/admin/call/next/" ;; Moves to the next call {{:keys [gameUuid userUuid]} :params} (json/write-str (lapi/admin-call-next gameUuid userUuid))) (GET "/api/admin/character/zap/" ;; Zaps a player {{:keys [gameUuid userUuid player]} :params} (json/write-str (lapi/admin-zap-character gameUuid userUuid player))) ;; Old api (GET "/api/admin/:gameUuid/:userUuid/debug/" {{gameUuid :gameUuid userUuid :userUuid} :params} (lapi/admin-debug gameUuid userUuid)) (GET "/api/admin/:gameUuid/:userUuid/valid/" {{gameUuid :gameUuid userUuid :userUuid} :params} (lapi/admin-validate-spec gameUuid userUuid)) (GET "/api/admin/:gameUuid/:userUuid/modify-index/:ind/:amount/" {{gameUuid :gameUuid userUuid :userUuid ind :ind amount :amount} :params} (lapi/admin-modify-index gameUuid userUuid ind amount)) (GET "/api/admin/:gameUuid/:userUuid/minions/" {{gameUuid :gameUuid userUuid :userUuid} :params} (json/write-str (lapi/get-minions gameUuid userUuid))) (GET "/api/admin/:gameUuid/:userUuid/set-sg-owner/:sgid/:new-owner/" {{gameUuid :gameUuid userUuid :userUuid sgid :sgid newOwner :new-owner} :params} (json/write-str (lapi/admin-set-sg-owner gameUuid userUuid sgid newOwner))) ;; OTHER ;; Simple directs to the above (GET "/" {baseURL :context} (html [:html [:body [:a {:href (str baseURL "/scen/")} "Scenario Generator"][:br] [:a {:href (str baseURL "/char/")} "Character Generator"][:br] [:a {:href (str baseURL "/sectorgen/")} "Sector Generator"][:br] [:br] [:a {:href "https://github.com/lsenjov/hphelper"} "Source Code"][:br] ]])) ;; Turn on or off trace logging (GET "/admin/tracking/trace/" [] (do (log/set-level! :trace) "Logging set to trace.")) (GET "/admin/tracking/info/" [] (do (log/set-level! :info) "Logging set to info.")) (GET "/admin/spec/on/" [] (do (s/check-asserts true) "Asserts turned on.")) (GET "/admin/spec/off/" [] (do (s/check-asserts false) "Asserts turned off.")) (route/resources "/") (ANY "*" {{host "host" :as headers} :headers uri :uri :as all} (do (log/error "Invalid path. Host:" host "Uri:" uri) (json/write-str {:status "error" :message "Invalid endpoint"}))) ) (def app (-> app-routes (wrap-defaults api-defaults) ring.middleware.session/wrap-session ;; Allows cross-site requests for development purposes. Eventually will remove ;(wrap-cors #".*") ) ) (defn -main "Entry when not using it as an uberwar" [& _] (println "Starting Webserver") (org.httpkit.server/run-server app {:port 3000})) (comment ;; Turn on debug goodness (log/set-level! :trace) ;; Starts the server (def debug-server (org.httpkit.server/run-server app {:port 3000})) ;; Shuts down the server (debug-server) )
true
(ns hphelper.server.handler (:require [compojure.core :refer :all] [compojure.route :as route] [ring.middleware.defaults :refer [wrap-defaults api-defaults]] [taoensso.timbre :as log] [clojure.data.json :as json] ;; Standalone server [org.httpkit.server] ;; Character handling [hphelper.server.chargen.generator :as cgen] [hphelper.server.chargen.charform :as cform] [hphelper.server.chargen.print :as cprint] [hphelper.server.chargen.select :as csel] ;; Scenario handling [hphelper.server.scengen.scenform :as sform] [hphelper.server.scengen.generator :as sgen] [hphelper.server.scengen.print :as sprint] [hphelper.server.scengen.select :as ssel] [hphelper.server.shared.saveload :as sl] [hiccup.core :refer :all] ;; Shared items [hphelper.server.shared.sql :as sql] ;; Sector Generator [hphelper.server.sectorgen.generator :as secgen] ;; Live paranoia [hphelper.server.live.view :as lview] [hphelper.server.live.api :as lapi] ;; For hiding items from players [hphelper.server.shared.encrypt :as c] ;; Since this will slowly be changing to an api, json is coming [clojure.data.json :as json] ;; Allowing cross-site requests [ring.middleware.cors :refer [wrap-cors]] ;; For turning on and off asserts [clojure.spec.alpha :as s] ) (:gen-class)) ;; Set logging level to info, so we don't overload the server with logging (log/set-level! :info) (log/info "Compile asserts is set to:" s/*compile-asserts*) (log/info "System property is:" (System/getProperty "clojure.spec.compile-asserts")) (defn- parse-long "Parses a long, returns 0 if fails" [^String i] (try (Long/parseLong i) (catch NumberFormatException e (log/error "parse-long: could not parse:" i "Returning 0 instead.") 0) ) ) (defroutes app-routes ;; CHARACTERS ;; Show page to select from list or create new character (GET "/char/" {params :params baseURL :context} (if (:char_id params) (cprint/html-print-sheet-one-page (sl/load-char-from-db (:char_id params))) (csel/print-select-page baseURL))) ;; Select options to create a new character (GET "/char/gen/" {baseURL :context} (cform/html-select-page)) ;; Create a new character from the options above and save it (POST "/char/gen/" {params :params} (html [:div (-> params (cform/convert-to-char) (cgen/create-character) (sl/save-char-to-db) (sl/load-char-from-db) (cprint/html-print-sheet-one-page)) ])) ;; Upload a new character, return the character as edn under the :char tag (POST "/api/char/new/" request (let [body (ring.util.request/body-string request)] (log/trace "/api/char/new/ body:" body) (let [charid (-> body ;; Change to a map format with the char edn in :newchar clojure.edn/read-string ;; Get the char edn :newchar ;; Transform to an actual character file clojure.edn/read-string ;; New characters need drawbacks and mutations (cgen/create-character) ;; Save to db, store the id in charid (sl/save-char-to-db) )] (-> charid (sl/load-char-from-db) ;; Add the id from the database to the character ;(assoc :char_id charid) ; Should already be done upon loading pr-str ((fn [s] {:char s})) json/write-str ) ) ) ) ;; TODO currently just creates a new character slot each time, need to update the old one? ;; Returns the character (POST "/api/char/update/" request (let [c (-> request ring.util.request/body-string ;; Change to a map format with the char edn in :newchar clojure.edn/read-string ;; Get the char edn :newchar ;; Transform to an actual character file clojure.edn/read-string ) charid (:char_id c) ] (log/trace "/api/char/update/" "charid:" charid "character:") ;; Update it (if charid (do (log/trace "Updating character" charid "in database.") (sl/update-char (int charid) c) (json/write-str {:status "okay"}) ) (do (log/error "Could not update character" charid "in database.") (json/write-str {:status "error"}) ) ) ) ) ;; Display a character (GET "/char/print/" {params :params} (cprint/html-print-sheet-one-page (sl/load-char-from-db (:char_id params)))) ;; Gets the edn representation of a character (GET "/api/char/get/" {{charid :char_id} :params} (do (log/trace "Getting character id:" charid) (pr-str (sl/load-char-from-db (Integer/parseInt charid))))) (GET "/api/char/get-filtered/" {{filter-string :filter_string} :params} (do (log/tracef "Getting characters for filter string '%s'" filter-string) (pr-str (sl/get-filtered-char-list filter-string)))) ;; SCENARIOS ;; Show page to create a new scenario, or select a partially completed or fully completed scenario ;; If contains a :scen_id, loads completed scenario and allows options for printing parts or all (GET "/scen/" {params :params baseURL :context} (if (params :scen_id) (ssel/print-crisis-page (params :scen_id) baseURL) (ssel/print-select-page baseURL))) ;; Show page to create a new scenario (GET "/scen/gen/" {baseURL :context} (sform/html-select-page baseURL)) ;; Create a brand new scenario without programmers picked (POST "/scen/gen/" {params :params baseURL :context} (-> params (sform/from-select-to-scenmap) (sgen/create-scenario) (sl/save-scen-to-db) ((partial sform/html-scen-to-full-page baseURL)))) ;; Get scenario without programmers in order to pick programmers (GET "/scen/full/" {params :params baseURL :context} (sform/html-scen-to-full-page baseURL (:scen_id params))) ;; Add programmers to scenario and create a new record (POST "/scen/full/" {params :params baseURL :context} (-> params (sform/from-scenmap-to-full) (sl/save-fullscen-to-db) (ssel/print-crisis-page baseURL))) ;; Prints an entire scenario with options, including sheets for each character if desired (GET "/scen/print/" {params :params} (sprint/html-print-optional (sl/load-fullscen-from-db (params :scen_id)) (keys params))) ;; Prints a single session sheet for a character for a specific character (GET "/scen/print/char/" {params :params} (log/trace "Char sheet params:" params) (let [scen (sl/load-fullscen-from-db (Integer/parseInt (:scen_id params)))] (println (:hps scen)) (sprint/html-print-player-sheet scen ((:hps scen) (Integer/parseInt (:p_id params)))))) ;; Character Creation (GET "/api/db/get-societies/" {params :params} (log/trace "/api/db/get-societies/") (json/write-str (sql/get-society-all)) ) (GET "/api/db/get-mutations/" {params :params} (log/trace "/api/db/get-mutations/") (json/write-str (sql/get-mutation-all)) ) (GET "/api/db/get-drawbacks/" {params :params} (log/trace "/api/db/get-drawbacks/") (json/write-str (sql/get-drawback-all)) ) (GET "/api/db/get-skills/" {params :params} (log/trace "/api/db/get-skills/") (json/write-str (sql/get-skills-all)) ) ;; Hacky way to print a player's entire player sheet (GET "/player/:scen_id/:p_id/" {{scen_id :scen_id p_id :p_id} :params baseURL :context} (let [scen (sl/load-fullscen-from-db (c/int-show (Integer/parseInt scen_id)))] (sprint/html-print-player-sheet scen ((:hps scen) (c/int-show (Integer/parseInt p_id)))))) ;; Prints the minion sheet from a single scenario (GET "/minions/:scen_id/" {{scen_id :scen_id} :params baseURL :context} (sprint/html-print-optional (sl/load-fullscen-from-db (c/int-show (Integer/parseInt scen_id))) '(:minions))) ;; SECTORGEN ;; Prints 7 randomly generated sectors (GET "/sectorgen/" [] (secgen/html-print-neighbours 7)) ;; LIVE (GET "/live/new/:scen_id/" {{scen_id :scen_id} :params headers :headers baseURL :context :as all} (lview/new-game baseURL scen_id)) (GET "/live/view/:uuid/" {{uid :uuid} :params baseURL :context} (lview/view-game baseURL uid)) (GET "/live/view/:uuid/:confirm/" {{uid :uuid confirm :confirm} :params baseURL :context} (lview/edit-game baseURL uid confirm)) (GET "/live/view/:uuid/:confirm/:index/:amount/" {{uid :uuid confirm :confirm index :index amount :amount} :params baseURL :context} (lview/edit-game baseURL uid confirm index amount)) (GET "/live/playerview/:guid/:uuid/" {{guid :guid uuid :uuid} :params baseURL :context} (lview/view-game-player baseURL guid uuid)) ;; API ;; User login/logout (GET "/api/user/login/" {{:keys [email password]} :params} ;(json/write-str {:error "Not Implemented"})) ;TODO (json/write-str {:apiKey "testKey" :user_email "PI:EMAIL:<EMAIL>END_PI" :user_name "testName"})) ;TODO change away from being mocked ;; Public endpoints (GET "/api/public/:gameUuid/updates/:lastUpdated/" {{gameUuid :gameUuid userUuid :userUuid lastUpdated :lastUpdated} :params} (json/write-str (lapi/get-updated-public gameUuid (parse-long lastUpdated)))) (GET "/api/public/updates/" {{:keys [gameUuid userUuid lastUpdated]} :params} (json/write-str (lapi/get-updated-public gameUuid (parse-long lastUpdated)))) (GET "/api/public/:gameUuid/indicies/" {{gameUuid :gameUuid userUuid :userUuid} :params} (json/write-str (lapi/get-indicies gameUuid))) (GET "/api/public/:gameUuid/news/" {{gameUuid :gameUuid userUuid :userUuid} :params} (json/write-str (lapi/get-news gameUuid))) (GET "/api/public/:gameUuid/cbay/" {{gameUuid :gameUuid userUuid :userUuid} :params} (json/write-str (lapi/get-cbay gameUuid))) (GET "/api/public/:gameUuid/access/" {{gameUuid :gameUuid userUuid :userUuid} :params} (json/write-str (lapi/get-current-access gameUuid))) (GET "/api/public/:gameUuid/minions/" {{gameUuid :gameUuid userUuid :userUuid} :params} (json/write-str (lapi/get-minions gameUuid))) ;; Player endpoints ;; New api (GET "/api/player/updates/" {{:keys [gameUuid userUuid lastUpdated]} :params} (json/write-str (lapi/get-updated-player gameUuid userUuid (parse-long lastUpdated)))) (GET "/api/player/purchaseminion/" {{:keys [gameUuid userUuid sgid minionid]} :params} (json/write-str (lapi/player-buy-minion gameUuid userUuid sgid minionid))) (GET "/api/player/callminion/" {{:keys [gameUuid userUuid sgid minionid privateCall]} :params} (json/write-str (lapi/player-call-minion gameUuid userUuid sgid minionid privateCall))) (GET "/api/player/sendaccess/" {{:keys [gameUuid userUuid playerto amount]} :params} (json/write-str (lapi/player-send-access gameUuid userUuid playerto amount))) (GET "/api/player/trade-investments/" {{:keys [gameUuid userUuid group amount]} :params} (json/write-str (lapi/player-trade-investment gameUuid userUuid group amount))) (GET "/api/player/add-minion/" {{:keys [gameUuid userUuid sgid minionName minionClearance minionDesc]} :params} (json/write-str (lapi/player-add-custom-minion gameUuid userUuid sgid minionName minionClearance minionDesc))) ;; Old api (GET "/api/player/:gameUuid/:userUuid/updates/:lastUpdated/" {{gameUuid :gameUuid userUuid :userUuid lastUpdated :lastUpdated} :params} (json/write-str (lapi/get-updated-player gameUuid userUuid (parse-long lastUpdated)))) (GET "/api/player/:gameUuid/:userUuid/charsheet/" {{gameUuid :gameUuid userUuid :userUuid} :params} (json/write-str (lapi/get-player-character-sheet gameUuid userUuid))) (GET "/api/player/:gameUuid/:userUuid/societymissions/" {{gameUuid :gameUuid userUuid :userUuid} :params} (json/write-str (lapi/get-player-society-missions gameUuid userUuid))) (GET "/api/player/:gameUuid/:userUuid/minions/" {{gameUuid :gameUuid userUuid :userUuid} :params} (json/write-str (lapi/get-minions gameUuid userUuid))) ;; Admin endpoints ;; New api (GET "/api/admin/updates/" {{:keys [gameUuid userUuid lastUpdated]} :params} (json/write-str (lapi/get-updated-admin gameUuid userUuid (parse-long lastUpdated)))) (GET "/api/admin/set-sg-owner/" {{:keys [gameUuid userUuid sgid newOwner]} :params} (json/write-str (lapi/admin-set-sg-owner gameUuid userUuid sgid newOwner))) (GET "/api/admin/modify-index/" {{:keys [gameUuid userUuid ind amount]} :params} (lapi/admin-modify-index gameUuid userUuid ind amount)) (GET "/api/admin/modify-access/" {{:keys [gameUuid userUuid player amount]} :params} (lapi/admin-modify-access gameUuid userUuid player amount)) (GET "/api/admin/modify-public-standing/" {{:keys [gameUuid userUuid player amount]} :params} (log/trace "modify-public-standing:" gameUuid userUuid player amount) (json/write-str (lapi/admin-modify-public-standing gameUuid userUuid player amount))) (GET "/api/admin/sync-chars/" ;; Saves characters to the database {{:keys [gameUuid userUuid]} :params} (json/write-str (lapi/sync-chars gameUuid userUuid))) (GET "/api/admin/lock-zone/" ;; Locks or unlocks a zone {{:keys [gameUuid userUuid status]} :params} (json/write-str (lapi/admin-lock-zone gameUuid userUuid status))) (GET "/api/admin/call/next/" ;; Moves to the next call {{:keys [gameUuid userUuid]} :params} (json/write-str (lapi/admin-call-next gameUuid userUuid))) (GET "/api/admin/character/zap/" ;; Zaps a player {{:keys [gameUuid userUuid player]} :params} (json/write-str (lapi/admin-zap-character gameUuid userUuid player))) ;; Old api (GET "/api/admin/:gameUuid/:userUuid/debug/" {{gameUuid :gameUuid userUuid :userUuid} :params} (lapi/admin-debug gameUuid userUuid)) (GET "/api/admin/:gameUuid/:userUuid/valid/" {{gameUuid :gameUuid userUuid :userUuid} :params} (lapi/admin-validate-spec gameUuid userUuid)) (GET "/api/admin/:gameUuid/:userUuid/modify-index/:ind/:amount/" {{gameUuid :gameUuid userUuid :userUuid ind :ind amount :amount} :params} (lapi/admin-modify-index gameUuid userUuid ind amount)) (GET "/api/admin/:gameUuid/:userUuid/minions/" {{gameUuid :gameUuid userUuid :userUuid} :params} (json/write-str (lapi/get-minions gameUuid userUuid))) (GET "/api/admin/:gameUuid/:userUuid/set-sg-owner/:sgid/:new-owner/" {{gameUuid :gameUuid userUuid :userUuid sgid :sgid newOwner :new-owner} :params} (json/write-str (lapi/admin-set-sg-owner gameUuid userUuid sgid newOwner))) ;; OTHER ;; Simple directs to the above (GET "/" {baseURL :context} (html [:html [:body [:a {:href (str baseURL "/scen/")} "Scenario Generator"][:br] [:a {:href (str baseURL "/char/")} "Character Generator"][:br] [:a {:href (str baseURL "/sectorgen/")} "Sector Generator"][:br] [:br] [:a {:href "https://github.com/lsenjov/hphelper"} "Source Code"][:br] ]])) ;; Turn on or off trace logging (GET "/admin/tracking/trace/" [] (do (log/set-level! :trace) "Logging set to trace.")) (GET "/admin/tracking/info/" [] (do (log/set-level! :info) "Logging set to info.")) (GET "/admin/spec/on/" [] (do (s/check-asserts true) "Asserts turned on.")) (GET "/admin/spec/off/" [] (do (s/check-asserts false) "Asserts turned off.")) (route/resources "/") (ANY "*" {{host "host" :as headers} :headers uri :uri :as all} (do (log/error "Invalid path. Host:" host "Uri:" uri) (json/write-str {:status "error" :message "Invalid endpoint"}))) ) (def app (-> app-routes (wrap-defaults api-defaults) ring.middleware.session/wrap-session ;; Allows cross-site requests for development purposes. Eventually will remove ;(wrap-cors #".*") ) ) (defn -main "Entry when not using it as an uberwar" [& _] (println "Starting Webserver") (org.httpkit.server/run-server app {:port 3000})) (comment ;; Turn on debug goodness (log/set-level! :trace) ;; Starts the server (def debug-server (org.httpkit.server/run-server app {:port 3000})) ;; Shuts down the server (debug-server) )
[ { "context": "atagramSocket)))\n\n(def server (atom nil))\n\n; TODO(Richo): Hardcoded single client. Add support for multip", "end": 382, "score": 0.7456691265106201, "start": 377, "tag": "NAME", "value": "Richo" } ]
middleware/server/src/middleware/server/udp.clj
GIRA/UziScript
15
(ns middleware.server.udp (:require [clojure.core.async :as a :refer [thread <!!]] [clojure.tools.logging :as log] [middleware.utils.json :as json] [middleware.device.controller :as device] [middleware.utils.config :as config]) (:import (java.net InetAddress DatagramPacket DatagramSocket))) (def server (atom nil)) ; TODO(Richo): Hardcoded single client. Add support for multiple clients (def ^:const SERVER_PORT 3232) (def ^:const CLIENT_PORT 3234) (def ^:private update-loop? (atom false)) (defn get-server-state [] (let [state @device/state] {:pins (-> state :pins :data vals) :globals (-> state :globals :data vals)})) (defn- send! [data] (when-let [^DatagramSocket udp @server] (let [^String json (json/encode data) buf (.getBytes json "utf8") packet (DatagramPacket. buf (count buf) (InetAddress/getByName "localhost") CLIENT_PORT)] (.send udp packet)))) (defn- start-incoming-thread [] (thread (let [buf (byte-array 256) packet (DatagramPacket. buf (count buf))] (loop [] (when @update-loop? (when-let [^DatagramSocket udp @server] (.receive udp packet) (let [msg (String. buf 0 (.getLength packet) "utf8") {:keys [action name value]} (json/decode msg)] (println ">>>" msg) (try (case action "init" (send! (get-server-state)) "set_pin_value" (device/set-pin-value name value) "set_global_value" (device/set-global-value name value)) (catch Throwable e (log/error "ERROR WHILE RECEIVING (udp) ->" e))))) (recur)))))) (defn- start-outgoing-thread [] (thread (loop [old-state nil] (when @update-loop? (let [new-state (get-server-state)] (when (not= old-state new-state) (send! new-state)) (<!! (a/timeout (config/get-in [:udp :interval] 10))) (recur new-state)))))) (defn start-update-loop [] (when (compare-and-set! update-loop? false true) (start-incoming-thread) (start-outgoing-thread))) (defn stop-update-loop [] (reset! update-loop? false)) (defn start [] (when (and (nil? @server) (config/get-in [:udp :enabled?] true)) (start-update-loop) (let [s (DatagramSocket. SERVER_PORT)] (reset! server s)))) (defn stop [] (when-let [^DatagramSocket s @server] (stop-update-loop) (reset! server nil) (.close s)))
10888
(ns middleware.server.udp (:require [clojure.core.async :as a :refer [thread <!!]] [clojure.tools.logging :as log] [middleware.utils.json :as json] [middleware.device.controller :as device] [middleware.utils.config :as config]) (:import (java.net InetAddress DatagramPacket DatagramSocket))) (def server (atom nil)) ; TODO(<NAME>): Hardcoded single client. Add support for multiple clients (def ^:const SERVER_PORT 3232) (def ^:const CLIENT_PORT 3234) (def ^:private update-loop? (atom false)) (defn get-server-state [] (let [state @device/state] {:pins (-> state :pins :data vals) :globals (-> state :globals :data vals)})) (defn- send! [data] (when-let [^DatagramSocket udp @server] (let [^String json (json/encode data) buf (.getBytes json "utf8") packet (DatagramPacket. buf (count buf) (InetAddress/getByName "localhost") CLIENT_PORT)] (.send udp packet)))) (defn- start-incoming-thread [] (thread (let [buf (byte-array 256) packet (DatagramPacket. buf (count buf))] (loop [] (when @update-loop? (when-let [^DatagramSocket udp @server] (.receive udp packet) (let [msg (String. buf 0 (.getLength packet) "utf8") {:keys [action name value]} (json/decode msg)] (println ">>>" msg) (try (case action "init" (send! (get-server-state)) "set_pin_value" (device/set-pin-value name value) "set_global_value" (device/set-global-value name value)) (catch Throwable e (log/error "ERROR WHILE RECEIVING (udp) ->" e))))) (recur)))))) (defn- start-outgoing-thread [] (thread (loop [old-state nil] (when @update-loop? (let [new-state (get-server-state)] (when (not= old-state new-state) (send! new-state)) (<!! (a/timeout (config/get-in [:udp :interval] 10))) (recur new-state)))))) (defn start-update-loop [] (when (compare-and-set! update-loop? false true) (start-incoming-thread) (start-outgoing-thread))) (defn stop-update-loop [] (reset! update-loop? false)) (defn start [] (when (and (nil? @server) (config/get-in [:udp :enabled?] true)) (start-update-loop) (let [s (DatagramSocket. SERVER_PORT)] (reset! server s)))) (defn stop [] (when-let [^DatagramSocket s @server] (stop-update-loop) (reset! server nil) (.close s)))
true
(ns middleware.server.udp (:require [clojure.core.async :as a :refer [thread <!!]] [clojure.tools.logging :as log] [middleware.utils.json :as json] [middleware.device.controller :as device] [middleware.utils.config :as config]) (:import (java.net InetAddress DatagramPacket DatagramSocket))) (def server (atom nil)) ; TODO(PI:NAME:<NAME>END_PI): Hardcoded single client. Add support for multiple clients (def ^:const SERVER_PORT 3232) (def ^:const CLIENT_PORT 3234) (def ^:private update-loop? (atom false)) (defn get-server-state [] (let [state @device/state] {:pins (-> state :pins :data vals) :globals (-> state :globals :data vals)})) (defn- send! [data] (when-let [^DatagramSocket udp @server] (let [^String json (json/encode data) buf (.getBytes json "utf8") packet (DatagramPacket. buf (count buf) (InetAddress/getByName "localhost") CLIENT_PORT)] (.send udp packet)))) (defn- start-incoming-thread [] (thread (let [buf (byte-array 256) packet (DatagramPacket. buf (count buf))] (loop [] (when @update-loop? (when-let [^DatagramSocket udp @server] (.receive udp packet) (let [msg (String. buf 0 (.getLength packet) "utf8") {:keys [action name value]} (json/decode msg)] (println ">>>" msg) (try (case action "init" (send! (get-server-state)) "set_pin_value" (device/set-pin-value name value) "set_global_value" (device/set-global-value name value)) (catch Throwable e (log/error "ERROR WHILE RECEIVING (udp) ->" e))))) (recur)))))) (defn- start-outgoing-thread [] (thread (loop [old-state nil] (when @update-loop? (let [new-state (get-server-state)] (when (not= old-state new-state) (send! new-state)) (<!! (a/timeout (config/get-in [:udp :interval] 10))) (recur new-state)))))) (defn start-update-loop [] (when (compare-and-set! update-loop? false true) (start-incoming-thread) (start-outgoing-thread))) (defn stop-update-loop [] (reset! update-loop? false)) (defn start [] (when (and (nil? @server) (config/get-in [:udp :enabled?] true)) (start-update-loop) (let [s (DatagramSocket. SERVER_PORT)] (reset! server s)))) (defn stop [] (when-let [^DatagramSocket s @server] (stop-update-loop) (reset! server nil) (.close s)))
[ { "context": "\n;;=> Japan\n\n\n(def p2 (cljbook.chapter05.Person. \"Nico\" \"France\"))\n;;=> #'chapter05.calling-from-java/p2", "end": 1657, "score": 0.996832013130188, "start": 1653, "tag": "NAME", "value": "Nico" }, { "context": "'chapter05.calling-from-java/p2\n(.getName p2)\n;;=> Nico\n(.getCountry p2)\n;;=> France\n\n(defprotocol IPoint", "end": 1731, "score": 0.8457069993019104, "start": 1727, "tag": "NAME", "value": "Nico" } ]
Chapter 05 Code/src/chapter05/calling_from_java.clj
PacktPublishing/Clojure-Programming-Cookbook
14
(ns chapter05.calling-from-java (:require [clojure.math.numeric-tower :as math]) (:require [clojure.reflect :refer [reflect]]) ) (defn get-instance-method[obj] (->> (reflect obj) :members ) ) (gen-class :name cljbook.chapter05.Hello :methods [^:static [hello [String] void]]) (defn- -hello [s] (println (str "Hello " s))) ;;(cljbook.chapter05.Hello/hello "makoto") (gen-class :name cljbook.chapter05.Person :state state :init init :prefix "-" :main false :constructors { [][] [String] [] [String String] []} :methods [ [setCountry [String] void] [getCountry [] String] [setName [String] void] [getName [] String]]) (defn -init ([] [[] (atom {:name nil :country nil})]) ([name] [[] (atom {:name name :country nil})]) ([name country] [[] (atom {:name name :country country})])) ;;=> #'chapter05.calling-from-java/-init (defn set-value [this key value] (swap! (.state this) into {key value})) ;;=> #'chapter05.calling-from-java/set-value (defn get-value [this key] (@(.state this) key)) (defn -setName [this name] (set-value this :name name)) (defn -getName [this] (get-value this :name)) (defn -setCountry [this country] (set-value this :country country)) (defn -getCountry [this] (get-value this :country)) #( (compile 'chapter05.calling-from-java) ;;=> chapter05.calling-from-java ) (def p1 (cljbook.chapter05.Person.)) ;;=> #'chapter05.calling-from-java/p1 (.getName p1) ;;=> makoto (.getCountry p1) ;;=> Japan (def p2 (cljbook.chapter05.Person. "Nico" "France")) ;;=> #'chapter05.calling-from-java/p2 (.getName p2) ;;=> Nico (.getCountry p2) ;;=> France (defprotocol IPoint "A simple protocol for flying" (move [self ^double x ^double y]) (^double distance [self]) ) ;;=> IPoint (defrecord Point [^double x ^double y]) (extend-protocol IPoint Point (move [self ^double x ^double y] (->Point (+ (.-x self) x)(+ (.-y self) y))) (distance [self] (math/sqrt (* (* (.-x self) (.-x self)) (* (.-y self) (.-y self))) ))) ;;=> nil (def pos1 (Point. 1 2)) ;;=> #'chapter03.protocols/pos1 [(.-x pos1)(.-y pos1)] ;;=> [1 2] (distance pos1) ;;=> 2.23606797749979 (distance pos1) (def pos2 (move pos1 1.0 2.0)) ;;=> #'chapter03.protocols/pos2 [(.-x pos2)(.-y pos2)] ;;=> [2 4] (distance pos2) ;;=> 4.47213595499958 (deftype Point3D [^double x y z]) (extend-protocol IPoint Point3D (move [self delta] (->Point3D (+ (.-x self) (delta 0))(+ (.-y self) (delta 1))(+ (.-z self) (delta 2)))) (distance [self] (math/sqrt (+ (* (.-x self) (.-x self)) (* (.-y self) (.-y self)) (* (.-z self) (.-z self)))))) (definterface MyInterface (^int add[^int v]) (^int sub[^int v]) ) (defprotocol MyProtocol1 (add[self v]) (sub[self v]) ) (def h1 (java.util.HashMap.)) (get-instance-method h1) (definterface Calculation (^long getX []) (^void setX [^long value]) (^long add [^long x]) (^long sub [^long x])) ;;=> chapter05.calling_from_java.Calculation (deftype MyInt [^long x] Calculation (getX [this] (.x this)) (setX [this val] (set! (.x this) val)) (add [this x] (+ (.x this) x)) (sub [this x] (- (.x this) x))) ;;=> chapter05.calling_from_java.MyInt (def myInt (MyInt. 15)) (.add myInt 30) ;;=> 45 (.sub myInt 11) ;;=> 4 (.getX myInt) ;;=> 15 (.setX myInt 10) ;;=> nil (.getX myInt) ;;=> 10 (get-instance-method (MyInt. 1)) (extend-protocol MyProtocol1 MyInt (add[self v] (+ (.x self) v)) (sub[self v] (- (.x self) v)) ) (extend-protocol MyProtocol1 (Class/forName "[J") (add[self v] (+ (.x self) v)) (sub[self v] (- (.x self) v)) ) (def i1 (MyInt. 1)) (.x i1) (add i1 1) (MyInt. 1) (class (int-array [1 2]))
31633
(ns chapter05.calling-from-java (:require [clojure.math.numeric-tower :as math]) (:require [clojure.reflect :refer [reflect]]) ) (defn get-instance-method[obj] (->> (reflect obj) :members ) ) (gen-class :name cljbook.chapter05.Hello :methods [^:static [hello [String] void]]) (defn- -hello [s] (println (str "Hello " s))) ;;(cljbook.chapter05.Hello/hello "makoto") (gen-class :name cljbook.chapter05.Person :state state :init init :prefix "-" :main false :constructors { [][] [String] [] [String String] []} :methods [ [setCountry [String] void] [getCountry [] String] [setName [String] void] [getName [] String]]) (defn -init ([] [[] (atom {:name nil :country nil})]) ([name] [[] (atom {:name name :country nil})]) ([name country] [[] (atom {:name name :country country})])) ;;=> #'chapter05.calling-from-java/-init (defn set-value [this key value] (swap! (.state this) into {key value})) ;;=> #'chapter05.calling-from-java/set-value (defn get-value [this key] (@(.state this) key)) (defn -setName [this name] (set-value this :name name)) (defn -getName [this] (get-value this :name)) (defn -setCountry [this country] (set-value this :country country)) (defn -getCountry [this] (get-value this :country)) #( (compile 'chapter05.calling-from-java) ;;=> chapter05.calling-from-java ) (def p1 (cljbook.chapter05.Person.)) ;;=> #'chapter05.calling-from-java/p1 (.getName p1) ;;=> makoto (.getCountry p1) ;;=> Japan (def p2 (cljbook.chapter05.Person. "<NAME>" "France")) ;;=> #'chapter05.calling-from-java/p2 (.getName p2) ;;=> <NAME> (.getCountry p2) ;;=> France (defprotocol IPoint "A simple protocol for flying" (move [self ^double x ^double y]) (^double distance [self]) ) ;;=> IPoint (defrecord Point [^double x ^double y]) (extend-protocol IPoint Point (move [self ^double x ^double y] (->Point (+ (.-x self) x)(+ (.-y self) y))) (distance [self] (math/sqrt (* (* (.-x self) (.-x self)) (* (.-y self) (.-y self))) ))) ;;=> nil (def pos1 (Point. 1 2)) ;;=> #'chapter03.protocols/pos1 [(.-x pos1)(.-y pos1)] ;;=> [1 2] (distance pos1) ;;=> 2.23606797749979 (distance pos1) (def pos2 (move pos1 1.0 2.0)) ;;=> #'chapter03.protocols/pos2 [(.-x pos2)(.-y pos2)] ;;=> [2 4] (distance pos2) ;;=> 4.47213595499958 (deftype Point3D [^double x y z]) (extend-protocol IPoint Point3D (move [self delta] (->Point3D (+ (.-x self) (delta 0))(+ (.-y self) (delta 1))(+ (.-z self) (delta 2)))) (distance [self] (math/sqrt (+ (* (.-x self) (.-x self)) (* (.-y self) (.-y self)) (* (.-z self) (.-z self)))))) (definterface MyInterface (^int add[^int v]) (^int sub[^int v]) ) (defprotocol MyProtocol1 (add[self v]) (sub[self v]) ) (def h1 (java.util.HashMap.)) (get-instance-method h1) (definterface Calculation (^long getX []) (^void setX [^long value]) (^long add [^long x]) (^long sub [^long x])) ;;=> chapter05.calling_from_java.Calculation (deftype MyInt [^long x] Calculation (getX [this] (.x this)) (setX [this val] (set! (.x this) val)) (add [this x] (+ (.x this) x)) (sub [this x] (- (.x this) x))) ;;=> chapter05.calling_from_java.MyInt (def myInt (MyInt. 15)) (.add myInt 30) ;;=> 45 (.sub myInt 11) ;;=> 4 (.getX myInt) ;;=> 15 (.setX myInt 10) ;;=> nil (.getX myInt) ;;=> 10 (get-instance-method (MyInt. 1)) (extend-protocol MyProtocol1 MyInt (add[self v] (+ (.x self) v)) (sub[self v] (- (.x self) v)) ) (extend-protocol MyProtocol1 (Class/forName "[J") (add[self v] (+ (.x self) v)) (sub[self v] (- (.x self) v)) ) (def i1 (MyInt. 1)) (.x i1) (add i1 1) (MyInt. 1) (class (int-array [1 2]))
true
(ns chapter05.calling-from-java (:require [clojure.math.numeric-tower :as math]) (:require [clojure.reflect :refer [reflect]]) ) (defn get-instance-method[obj] (->> (reflect obj) :members ) ) (gen-class :name cljbook.chapter05.Hello :methods [^:static [hello [String] void]]) (defn- -hello [s] (println (str "Hello " s))) ;;(cljbook.chapter05.Hello/hello "makoto") (gen-class :name cljbook.chapter05.Person :state state :init init :prefix "-" :main false :constructors { [][] [String] [] [String String] []} :methods [ [setCountry [String] void] [getCountry [] String] [setName [String] void] [getName [] String]]) (defn -init ([] [[] (atom {:name nil :country nil})]) ([name] [[] (atom {:name name :country nil})]) ([name country] [[] (atom {:name name :country country})])) ;;=> #'chapter05.calling-from-java/-init (defn set-value [this key value] (swap! (.state this) into {key value})) ;;=> #'chapter05.calling-from-java/set-value (defn get-value [this key] (@(.state this) key)) (defn -setName [this name] (set-value this :name name)) (defn -getName [this] (get-value this :name)) (defn -setCountry [this country] (set-value this :country country)) (defn -getCountry [this] (get-value this :country)) #( (compile 'chapter05.calling-from-java) ;;=> chapter05.calling-from-java ) (def p1 (cljbook.chapter05.Person.)) ;;=> #'chapter05.calling-from-java/p1 (.getName p1) ;;=> makoto (.getCountry p1) ;;=> Japan (def p2 (cljbook.chapter05.Person. "PI:NAME:<NAME>END_PI" "France")) ;;=> #'chapter05.calling-from-java/p2 (.getName p2) ;;=> PI:NAME:<NAME>END_PI (.getCountry p2) ;;=> France (defprotocol IPoint "A simple protocol for flying" (move [self ^double x ^double y]) (^double distance [self]) ) ;;=> IPoint (defrecord Point [^double x ^double y]) (extend-protocol IPoint Point (move [self ^double x ^double y] (->Point (+ (.-x self) x)(+ (.-y self) y))) (distance [self] (math/sqrt (* (* (.-x self) (.-x self)) (* (.-y self) (.-y self))) ))) ;;=> nil (def pos1 (Point. 1 2)) ;;=> #'chapter03.protocols/pos1 [(.-x pos1)(.-y pos1)] ;;=> [1 2] (distance pos1) ;;=> 2.23606797749979 (distance pos1) (def pos2 (move pos1 1.0 2.0)) ;;=> #'chapter03.protocols/pos2 [(.-x pos2)(.-y pos2)] ;;=> [2 4] (distance pos2) ;;=> 4.47213595499958 (deftype Point3D [^double x y z]) (extend-protocol IPoint Point3D (move [self delta] (->Point3D (+ (.-x self) (delta 0))(+ (.-y self) (delta 1))(+ (.-z self) (delta 2)))) (distance [self] (math/sqrt (+ (* (.-x self) (.-x self)) (* (.-y self) (.-y self)) (* (.-z self) (.-z self)))))) (definterface MyInterface (^int add[^int v]) (^int sub[^int v]) ) (defprotocol MyProtocol1 (add[self v]) (sub[self v]) ) (def h1 (java.util.HashMap.)) (get-instance-method h1) (definterface Calculation (^long getX []) (^void setX [^long value]) (^long add [^long x]) (^long sub [^long x])) ;;=> chapter05.calling_from_java.Calculation (deftype MyInt [^long x] Calculation (getX [this] (.x this)) (setX [this val] (set! (.x this) val)) (add [this x] (+ (.x this) x)) (sub [this x] (- (.x this) x))) ;;=> chapter05.calling_from_java.MyInt (def myInt (MyInt. 15)) (.add myInt 30) ;;=> 45 (.sub myInt 11) ;;=> 4 (.getX myInt) ;;=> 15 (.setX myInt 10) ;;=> nil (.getX myInt) ;;=> 10 (get-instance-method (MyInt. 1)) (extend-protocol MyProtocol1 MyInt (add[self v] (+ (.x self) v)) (sub[self v] (- (.x self) v)) ) (extend-protocol MyProtocol1 (Class/forName "[J") (add[self v] (+ (.x self) v)) (sub[self v] (- (.x self) v)) ) (def i1 (MyInt. 1)) (.x i1) (add i1 1) (MyInt. 1) (class (int-array [1 2]))
[ { "context": ";; Copyright 2016 Chris Rink\n;;\n;; Licensed under the Apache License, Version ", "end": 28, "score": 0.9998539090156555, "start": 18, "tag": "NAME", "value": "Chris Rink" } ]
src/clojure/repopreview/config.clj
chrisrink10/repopreview
0
;; Copyright 2016 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 repopreview.config (:require [clojure.spec.alpha :as s] [cprop.core :as cprop] [cprop.source :as source])) (s/def ::github (s/keys :req-un [:repopreview.github/api-key])) (s/def ::logging (s/keys :req-un [:repopreview.logging/level])) (s/def ::web-server (s/keys :req-un [:repopreview.web-server/port] :opt-un [:repopreview.web-server/ip :repopreview.web-server/thread :repopreview.web-server/queue-size :repopreview.web-server/max-body :repopreview.web-server/max-line])) (s/def ::repopreview (s/keys :req-un [::github ::logging ::web-server])) (s/def ::config (s/keys :req-un [::repopreview])) (defn read-env-config "Read the application configuration from the application defaults, environment variables, and any specified overrides. This function rebinds `*out*' to suppress `println' output from the cprop library. Returns the configuration formed by merging (1) the defaults, (2) environment variables, and (3) any overrides specified as an argument." [overrides] (binding [*out* (new java.io.StringWriter)] (cprop/load-config :merge [(source/from-env) overrides]))) (defn read-config "Read the application configuration using `read-env-config' and validate it against the config spec. Throws an exception if the spec fails. Returns the configuration otherwise." ([] (read-config {})) ([overrides] (let [config (read-env-config overrides)] (if (s/valid? ::config config) (:repopreview config) (throw (ex-info (s/explain-str ::config config) (s/explain-data ::config config))))))) (def config-cache (memoize read-config)) (defn config "Read configuration values from the cached environment config. If arguments are provided, they are treated as in `get-in' to access sub-sections of the configuration map." ([] (config-cache)) ([ks] (-> (config-cache) (get-in ks))) ([ks not-found] (-> (config-cache) (get-in ks not-found))))
41531
;; Copyright 2016 <NAME> ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns repopreview.config (:require [clojure.spec.alpha :as s] [cprop.core :as cprop] [cprop.source :as source])) (s/def ::github (s/keys :req-un [:repopreview.github/api-key])) (s/def ::logging (s/keys :req-un [:repopreview.logging/level])) (s/def ::web-server (s/keys :req-un [:repopreview.web-server/port] :opt-un [:repopreview.web-server/ip :repopreview.web-server/thread :repopreview.web-server/queue-size :repopreview.web-server/max-body :repopreview.web-server/max-line])) (s/def ::repopreview (s/keys :req-un [::github ::logging ::web-server])) (s/def ::config (s/keys :req-un [::repopreview])) (defn read-env-config "Read the application configuration from the application defaults, environment variables, and any specified overrides. This function rebinds `*out*' to suppress `println' output from the cprop library. Returns the configuration formed by merging (1) the defaults, (2) environment variables, and (3) any overrides specified as an argument." [overrides] (binding [*out* (new java.io.StringWriter)] (cprop/load-config :merge [(source/from-env) overrides]))) (defn read-config "Read the application configuration using `read-env-config' and validate it against the config spec. Throws an exception if the spec fails. Returns the configuration otherwise." ([] (read-config {})) ([overrides] (let [config (read-env-config overrides)] (if (s/valid? ::config config) (:repopreview config) (throw (ex-info (s/explain-str ::config config) (s/explain-data ::config config))))))) (def config-cache (memoize read-config)) (defn config "Read configuration values from the cached environment config. If arguments are provided, they are treated as in `get-in' to access sub-sections of the configuration map." ([] (config-cache)) ([ks] (-> (config-cache) (get-in ks))) ([ks not-found] (-> (config-cache) (get-in ks not-found))))
true
;; Copyright 2016 PI:NAME:<NAME>END_PI ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns repopreview.config (:require [clojure.spec.alpha :as s] [cprop.core :as cprop] [cprop.source :as source])) (s/def ::github (s/keys :req-un [:repopreview.github/api-key])) (s/def ::logging (s/keys :req-un [:repopreview.logging/level])) (s/def ::web-server (s/keys :req-un [:repopreview.web-server/port] :opt-un [:repopreview.web-server/ip :repopreview.web-server/thread :repopreview.web-server/queue-size :repopreview.web-server/max-body :repopreview.web-server/max-line])) (s/def ::repopreview (s/keys :req-un [::github ::logging ::web-server])) (s/def ::config (s/keys :req-un [::repopreview])) (defn read-env-config "Read the application configuration from the application defaults, environment variables, and any specified overrides. This function rebinds `*out*' to suppress `println' output from the cprop library. Returns the configuration formed by merging (1) the defaults, (2) environment variables, and (3) any overrides specified as an argument." [overrides] (binding [*out* (new java.io.StringWriter)] (cprop/load-config :merge [(source/from-env) overrides]))) (defn read-config "Read the application configuration using `read-env-config' and validate it against the config spec. Throws an exception if the spec fails. Returns the configuration otherwise." ([] (read-config {})) ([overrides] (let [config (read-env-config overrides)] (if (s/valid? ::config config) (:repopreview config) (throw (ex-info (s/explain-str ::config config) (s/explain-data ::config config))))))) (def config-cache (memoize read-config)) (defn config "Read configuration values from the cached environment config. If arguments are provided, they are treated as in `get-in' to access sub-sections of the configuration map." ([] (config-cache)) ([ks] (-> (config-cache) (get-in ks))) ([ks not-found] (-> (config-cache) (get-in ks not-found))))