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": "st nil :data-center)\n psa1 (dc/psa {:name \"alpha\" :data-type :string :value \"ab\"})\n psa2 (d", "end": 1584, "score": 0.7959569096565247, "start": 1579, "tag": "NAME", "value": "alpha" }, { "context": "string :value \"ab\"})\n psa2 (dc/psa {:name \"bravo\" :data-type :string :value \"bf\"})\n psa3 (d", "end": 1653, "score": 0.9701927900314331, "start": 1648, "tag": "NAME", "value": "bravo" }, { "context": "string :value \"bf\"})\n psa3 (dc/psa {:name \"charlie\" :data-type :string :value \"foo\"})\n psa4 (", "end": 1724, "score": 0.9922376871109009, "start": 1717, "tag": "NAME", "value": "charlie" }, { "context": "iable \"boost\"})\n personnel1 (dc/personnel \"Bob\" \"Hope\" \"bob.hope@nasa.gov\" \"TECHNICAL CONTACT\")\n", "end": 5294, "score": 0.9997531771659851, "start": 5291, "tag": "NAME", "value": "Bob" }, { "context": "\"boost\"})\n personnel1 (dc/personnel \"Bob\" \"Hope\" \"bob.hope@nasa.gov\" \"TECHNICAL CONTACT\")\n ", "end": 5301, "score": 0.9991877675056458, "start": 5297, "tag": "NAME", "value": "Hope" }, { "context": "})\n personnel1 (dc/personnel \"Bob\" \"Hope\" \"bob.hope@nasa.gov\" \"TECHNICAL CONTACT\")\n personnel2 (dc/pers", "end": 5321, "score": 0.9999309778213501, "start": 5304, "tag": "EMAIL", "value": "bob.hope@nasa.gov" }, { "context": "NICAL CONTACT\")\n personnel2 (dc/personnel \"Victor\" \"Fries\" \"victor.fries@nsidc.gov\" \"TECHNICAL CONT", "end": 5384, "score": 0.9998366832733154, "start": 5378, "tag": "NAME", "value": "Victor" }, { "context": "TACT\")\n personnel2 (dc/personnel \"Victor\" \"Fries\" \"victor.fries@nsidc.gov\" \"TECHNICAL CONTACT\")\n ", "end": 5392, "score": 0.9996801614761353, "start": 5387, "tag": "NAME", "value": "Fries" }, { "context": " personnel2 (dc/personnel \"Victor\" \"Fries\" \"victor.fries@nsidc.gov\" \"TECHNICAL CONTACT\")\n personnel3 (dc/pers", "end": 5417, "score": 0.9999300241470337, "start": 5395, "tag": "EMAIL", "value": "victor.fries@nsidc.gov" }, { "context": "NICAL CONTACT\")\n personnel3 (dc/personnel \"Otto\" \"Octavious\" \"otto.octavious@noaa.gov\")\n t", "end": 5478, "score": 0.9998410940170288, "start": 5474, "tag": "NAME", "value": "Otto" }, { "context": "ONTACT\")\n personnel3 (dc/personnel \"Otto\" \"Octavious\" \"otto.octavious@noaa.gov\")\n tdcs1 (dc/two", "end": 5490, "score": 0.9997434616088867, "start": 5481, "tag": "NAME", "value": "Octavious" }, { "context": " personnel3 (dc/personnel \"Otto\" \"Octavious\" \"otto.octavious@noaa.gov\")\n tdcs1 (dc/two-d \"XYZ\")\n tdcs2 (d", "end": 5516, "score": 0.9999281764030457, "start": 5493, "tag": "EMAIL", "value": "otto.octavious@noaa.gov" }, { "context": "))\n\n ;; search by contact persons\n \"Bob Hope\" [coll26]\n \"bob.hope@nasa.gov\" [coll26]\n ", "end": 10584, "score": 0.9996679425239563, "start": 10576, "tag": "NAME", "value": "Bob Hope" }, { "context": "tact persons\n \"Bob Hope\" [coll26]\n \"bob.hope@nasa.gov\" [coll26]\n \"Victor\" [coll27]\n \"vict", "end": 10621, "score": 0.9999208450317383, "start": 10604, "tag": "EMAIL", "value": "bob.hope@nasa.gov" }, { "context": "26]\n \"bob.hope@nasa.gov\" [coll26]\n \"Victor\" [coll27]\n \"victor.fries@nsidc.gov\" [coll2", "end": 10647, "score": 0.9989707469940186, "start": 10641, "tag": "NAME", "value": "Victor" }, { "context": ".gov\" [coll26]\n \"Victor\" [coll27]\n \"victor.fries@nsidc.gov\" [coll27]\n\n ;; search by data center conta", "end": 10689, "score": 0.9999212622642517, "start": 10667, "tag": "EMAIL", "value": "victor.fries@nsidc.gov" }, { "context": " ;; search by data center contact\n \"Octavious\" [coll25]\n\n \"ABC\" [coll2]\n \"place\" ", "end": 10760, "score": 0.991477906703949, "start": 10751, "tag": "NAME", "value": "Octavious" }, { "context": "\n ;; attributes\n ;; - name\n \"charlie\" [coll12]\n ;; - description\n \"Ge", "end": 12020, "score": 0.9910408854484558, "start": 12016, "tag": "NAME", "value": "char" }, { "context": " ;; attributes\n ;; - name\n \"charlie\" [coll12]\n ;; - description\n \"Gener", "end": 12023, "score": 0.6068161725997925, "start": 12020, "tag": "NAME", "value": "lie" } ]
system-int-test/test/cmr/system_int_test/search/collection_keyword_search_test.clj
sxu123/Common-Metadata-Repository
0
(ns cmr.system-int-test.search.collection-keyword-search-test "Integration test for CMR collection search by keyword terms" (:require [clojure.test :refer :all] [cmr.common.util :refer [are3]] [cmr.search.data.keywords-to-elastic :as k2e] [cmr.system-int-test.data2.collection :as dc] [cmr.system-int-test.data2.core :as d] [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.umm-spec.models.umm-collection-models :as um] [cmr.umm-spec.models.umm-common-models :as cm] [cmr.umm-spec.test.expected-conversion :as exp-conv])) (use-fixtures :each (ingest/reset-fixture {"provguid1" "PROV1" "provguid2" "PROV2" "provguid3" "PROV3" "provguid4" "PROV4" "provguid5" "PROV5"})) (deftest search-by-keywords (let [short-name-boost (k2e/get-boost nil :short-name) entry-id-boost (k2e/get-boost nil :entry-id) project-boost (k2e/get-boost nil :project) platform-boost (k2e/get-boost nil :platform) instrument-boost (k2e/get-boost nil :instrument) concept-id-boost (k2e/get-boost nil :concept-id) provider-boost (k2e/get-boost nil :provider) entry-title-boost (k2e/get-boost nil :entry-title) two-d-boost (k2e/get-boost nil :two-d-coord-name) processing-level-boost (k2e/get-boost nil :processing-level-id) science-keywords-boost (k2e/get-boost nil :science-keywords) data-center-boost (k2e/get-boost nil :data-center) psa1 (dc/psa {:name "alpha" :data-type :string :value "ab"}) psa2 (dc/psa {:name "bravo" :data-type :string :value "bf"}) psa3 (dc/psa {:name "charlie" :data-type :string :value "foo"}) psa4 (dc/psa {:name "case" :data-type :string :value "up"}) psa5 (dc/psa {:name "novalue" :data-type :string :description "description"}) p1 (dc/platform {:short-name "platform_SnB" :long-name "platform_Ln B" :instruments [(dc/instrument {:short-name "isnA" :long-name "ilnA" :technique "itechniqueA" :sensors [(dc/sensor {:short-name "ssnA" :long-name "slnA"}) (dc/sensor {:short-name "ssnD" :long-name "slnD" :technique "techniqueD"})]})]}) p2 (dc/platform {:short-name "platform_SnA spoonA" :long-name "platform_LnA" :characteristics [(dc/characteristic {:name "char1" :description "char1desc"}) (dc/characteristic {:name "char2" :description "char2desc"})] :instruments [(dc/instrument {:short-name "isnB" :long-name "ilnB" :technique "itechniqueB" :sensors [(dc/sensor {:short-name "ssnB" :long-name "slnB" :technique "techniqueB"}) (dc/sensor {:short-name "ssnC" :long-name "slnC" :technique "techniqueC"})]})]}) p3 (dc/platform {:short-name "spoonA"}) p4 (dc/platform {:short-name "SMAP" :instruments [(dc/instrument {:short-name "SMAP L-BAND RADIOMETER"})]}) p5 (dc/platform {:short-name "fo&nA"}) p6 (dc/platform {:short-name "spo~nA"}) p7 (dc/platform {:short-name "platform7" :instruments [(dc/instrument {:short-name "INST7"})]}) pboost (dc/platform {:short-name "boost"}) pr1 (dc/projects "project-short-name") pr2 (dc/projects "Proj-2") sk1 (dc/science-keyword {:category "Cat1" :topic "Topic1" :term "Term1" :variable-level-1 "Level1-1" :variable-level-2 "Level1-2" :variable-level-3 "Level1-3" :detailed-variable "SUPER DETAILED!"}) sk2 (dc/science-keyword {:category "Hurricane" :topic "Laser spoonA" :term "Extreme" :variable-level-1 "Level2-1" :variable-level-2 "Level2-2" :variable-level-3 "Level2-3"}) sk3 (dc/science-keyword {:category "Cat2" :topic "Topic1" :term "Term1" :variable-level-1 "Level3-1" :variable-level-2 "Level3-2" :variable-level-3 "Level3-3" :detailed-variable "S@PER"}) skboost (dc/science-keyword {:category "boost" :topic "boost" :term "boost" :variable-level-1 "boost" :variable-level-2 "boost" :variable-level-3 "boost" :detailed-variable "boost"}) personnel1 (dc/personnel "Bob" "Hope" "bob.hope@nasa.gov" "TECHNICAL CONTACT") personnel2 (dc/personnel "Victor" "Fries" "victor.fries@nsidc.gov" "TECHNICAL CONTACT") personnel3 (dc/personnel "Otto" "Octavious" "otto.octavious@noaa.gov") tdcs1 (dc/two-d "XYZ") tdcs2 (dc/two-d "twoduniq") org (dc/org :archive-center "Some&Place") url1 (dc/related-url {:url "http://cmr.earthdata.nasa.gov" :description "Earthdata"}) url2 (dc/related-url {:url "http://nsidc.org/" :description "Home page of National Snow and Ice Data Center"}) coll1 (d/ingest "PROV1" (dc/collection {:entry-title "coll1" :version-description "VersionDescription"})) coll2 (d/ingest "PROV1" (dc/collection {:entry-title "coll2" :short-name "ABC!XYZ" :version-id "V001"})) coll3 (d/ingest "PROV1" (dc/collection {:entry-title "coll3" :collection-data-type "OTHER"})) coll4 (d/ingest "PROV2" (dc/collection {:entry-title "coll4" :collection-data-type "OTHER"})) coll5 (d/ingest "PROV2" (dc/collection {:entry-title "coll5" :short-name "Space!Laser"})) coll6 (d/ingest "PROV2" (dc/collection {:entry-title "coll6" :organizations [org] :projects pr2 :platforms [p7]})) coll7 (d/ingest "PROV2" (dc/collection {:entry-title "coll7" :version-id "Laser"})) coll8 (d/ingest "PROV2" (dc/collection {:entry-title "coll8" :processing-level-id "PDQ123"})) coll9 (d/ingest "PROV2" (dc/collection {:entry-title "coll09" :science-keywords [sk1 sk2]})) coll10 (d/ingest "PROV2" (dc/collection {:entry-title "coll10" :spatial-keywords ["in out"] :science-keywords [sk3]})) coll11 (d/ingest "PROV2" (dc/collection {:entry-title "coll11" :platforms [p2 p3 p5 p6] :product-specific-attributes [psa5]})) coll12 (d/ingest "PROV2" (dc/collection {:entry-title "coll12" :product-specific-attributes [psa1 psa2 psa3 psa4]})) coll13 (d/ingest "PROV2" (dc/collection {:entry-title "coll13" :two-d-coordinate-systems [tdcs1 tdcs2]})) coll14 (d/ingest "PROV2" (dc/collection {:entry-title "coll14" :short-name "spoonA laser"})) coll15 (d/ingest "PROV2" (dc/collection {:entry-title "coll15" :processing-level-id "plid1" :collection-data-type "SCIENCE_QUALITY" :platforms [p1] :summary "summary" :temporal-keywords ["tk1" "tk2"]})) coll16 (d/ingest "PROV2" (dc/collection-dif {:short-name "entryid4"}) {:format :dif}) coll17 (d/ingest "PROV2" (dc/collection {:associated-difs ["DIF-1" "DIF-2"]})) coll18 (d/ingest "PROV2" (dc/collection {:short-name "SNFoobar"})) coll20 (d/ingest "PROV2" (dc/collection {:projects pr1 :entry-title "Mixed"})) coll21 (d/ingest "PROV2" (dc/collection {:entry-title "coll21" :short-name "Laser"})) coll22 (d/ingest "PROV2" (dc/collection {:collection-data-type "NEAR_REAL_TIME" :short-name "Mixed"})) coll23 (d/ingest "PROV1" (dc/collection {:entry-title "coll23" :short-name "\"Quoted\" collection"})) coll24 (d/ingest "PROV2" (dc/collection {:entry-title "coll24" :short-name "coll24" :platforms [p4]})) ;; Adding personnel here to test keyword search using DataCenter contacts coll25 (d/ingest "PROV2" (dc/collection {:entry-title "coll25" :related-urls [url1 url2] :personnel [personnel3]})) coll-boost (d/ingest "PROV2" (dc/collection {:entry-title "boost" :short-name "boost" :platforms [pboost] :science-keywords [skboost]})) coll26 (d/ingest "PROV4" (dc/collection-dif10 {:entry-title "coll26" :personnel [personnel1]}) {:format :dif10}) coll27 (d/ingest "PROV5" (dc/collection-dif10 {:entry-title "coll27" :personnel [personnel2]}) {:format :dif10})] (index/wait-until-indexed) (testing "search by keywords." (are [keyword-str items] (let [parameter-refs (search/find-refs :collection {:keyword keyword-str}) json-refs (search/find-refs-with-json-query :collection {} {:keyword keyword-str}) parameter-matches? (d/refs-match? items parameter-refs) json-matches? (d/refs-match? items json-refs)] (when-not parameter-matches? (println "Parameter search failed") (println "Expected:" (map :entry-title items)) (println "Actual:" (map :name (:refs parameter-refs)))) (when-not json-matches? (println "JSON Query search failed") (println "Expected:" (map :entry-title items)) (println "Actual:" (map :name (:refs json-refs)))) (and parameter-matches? json-matches?)) ;; search by contact persons "Bob Hope" [coll26] "bob.hope@nasa.gov" [coll26] "Victor" [coll27] "victor.fries@nsidc.gov" [coll27] ;; search by data center contact "Octavious" [coll25] "ABC" [coll2] "place" [coll6] "Laser" [coll21 coll5 coll7 coll9 coll14] "ABC V001" [coll2] "BLAH" [] "Space!Laser" [coll5] ;; Checking specific fields ;; provider "PROV1" [coll1 coll2 coll3 coll23] ;; entry title "coll1" [coll1] ;; entry id "ABC!XYZ_V001" [coll2] ;; short name "XYZ" [coll2 coll13] ;; version id "V001" [coll2] ;; version description "VersionDescription" [coll1] ;; processing level id "plid1" [coll15] ;; collection data type "SCIENCE_QUALITY" [coll15] ;; collection data type aliases for NEAR_REAL_TIME "NEAR_REAL_TIME" [coll22] "NRT" [coll22] "near_real_time" [coll22] "nrt" [coll22] "near-real-time" [coll22] "near real-time" [coll22] "near-real time" [coll22] ;; summary "summary" [coll15] ;; temporal keywords "tk1" [coll15] ;; spatial keywords "in" [coll10] ;; two d coord "xyz" [coll2 coll13] ;; archive center "some" [coll6] ;; attributes ;; - name "charlie" [coll12] ;; - description "Generated" [coll12] ;; description with no value - see CMR-1129 "description" [coll11] ;; Platforms ;; - short name "platform_SnA" [coll11] ;; - long name (from metadata - not from KMS) "platform_ln" [coll15] ;; - long name (from KMS - not from the metadata) "Soil Moisture Active and Passive Observatory" [coll24] ;; - characteristic name "char1" [coll11] "char2" [coll11] "char1 char2" [coll11] ;; - chracteristic description "char1desc" [coll11] "char2desc" [coll11] "char1desc char2desc" [coll11] ;; Instruments ;; - short name "isnA" [coll15] ;; - long name (from metadata - not from KMS) "ilnB" [coll11] ;; - long name (from KMS - not from metadata) "SMAP L-Band Radiometer" [coll24] ;; - technique "itechniqueB" [coll11] "itechniqueA" [coll15] ;; Sensors ;; - short name "ssnA" [coll15] ;; - long name "slnB" [coll11] ;; - technique "techniqueB" [coll11] "techniqueD" [coll15] "techniqueB techniqueC" [coll11] ;; Science keywords ;; - category "Cat1" [coll9] ;; - topic "Topic1" [coll9 coll10] ;; - term "Term1" [coll9 coll10] ;; - variable-levels "Level2-1" [coll9] "Level2-2" [coll9] "Level2-3" [coll9] ;; - detailed-variable "SUPER" [coll9] ;; Related URLs "earthdata" [coll25] "nsidc" [coll25 coll27] ;; Special characters are escaped before sending to Elastic "ABC~ZYX" [] "ABC~" [] "spo~nA" [coll11] "fo&nA" [coll11] "A.+&.+C" [] "S@PER" [coll10] ;; search by keywords using wildcard * "XY*" [coll2 coll13] "*aser" [coll21 coll5 coll7 coll9 coll14] "p*ce" [coll6] "NEA*REA*IME" [coll22] "nea*rea*ime" [coll22] "\"Quoted*" [coll23] ;; search by keywords using wildcard ? "XY?" [coll2 coll13] "?aser" [coll21 coll5 coll7 coll9 coll14] "p*ace" [coll6] "NEAR?REAL?TIME" [coll22] "near?real?time" [coll22])) (testing "Default boosts on fields" (are3 [params scores] (is (= (map #(/ % 2.0) scores) (map :score (:refs (search/find-refs :collection params))))) "short-name" {:keyword "SNFoobar"} [short-name-boost] "entry-id" {:keyword "ABC!XYZ_V001"} [entry-id-boost] "project short-name as keyword" {:keyword (:short-name (first pr1))} [project-boost] "project short-name as parameter" {:project (:short-name (first pr1))} [project-boost] "project long-name" {:keyword (:long-name (first pr1))} [project-boost] "platform short-name as keyword" {:keyword (:short-name p1)} [platform-boost] "platform short-name as parameter" {:platform (:short-name p1)} [platform-boost] "platform short-name as parameter with pattern" {:platform "*spoonA" "options[platform][pattern]" true} [platform-boost] "platform long-name (from metadata)" {:keyword (:long-name p1)} [platform-boost] "platform long-name (from KMS)" {:keyword "Soil Moisture Active and Passive Observatory"} [platform-boost] "instrument short-name as keyword" {:keyword (:short-name (first (:instruments p1)))} [instrument-boost] "instrument short-name as parameter" {:instrument (:short-name (first (:instruments p1)))} [instrument-boost] "instrument long-name (from metadata)" {:keyword (:long-name (first (:instruments p1)))} [instrument-boost] "instrument long-name (from KMS)" {:keyword "L-Band Radiometer"} [instrument-boost] ;; In UMM-C sensors are now instruments. All instruments (instruments + child instruments, ;; aka sensors) are indexed as both instruments and sensors until sensors search goes ;; away. Since they are instruments, there is no longer a sensor boost, but instrument ;; boost will be used. "sensor short-name as keyword" {:keyword (:short-name (first (:sensors (first (:instruments p1)))))} [instrument-boost] "sensor short-name as parameter" {:sensor (:short-name (first (:sensors (first (:instruments p1)))))} [instrument-boost] "sensor long-name" {:keyword (:long-name (first (:sensors (first (:instruments p1)))))} [instrument-boost] "temporal-keywords" {:keyword "tk1"} [(k2e/get-boost nil :temporal-keyword)] "spatial-keyword" {:keyword "in out"} [(k2e/get-boost nil :spatial-keyword)] "science-keywords as keyword" {:keyword (:category sk1)} [science-keywords-boost] "science-keywords category as parameter" {:science-keywords {:0 {:category (:category sk1)}}} [science-keywords-boost] "science-keywords topic as parameter" {:science-keywords {:0 {:topic (:topic sk1)}}} [science-keywords-boost science-keywords-boost] "science-keywords term as parameter" {:science-keywords {:0 {:term (:term sk1)}}} [science-keywords-boost science-keywords-boost] "science-keywords variable-level-1 as parameter" {:science-keywords {:0 {:variable-level-1 (:variable-level-1 sk1)}}} [science-keywords-boost] "science-keywords variable-level-2 as parameter" {:science-keywords {:0 {:variable-level-2 (:variable-level-2 sk1)}}} [science-keywords-boost] "science-keywords variable-level-3 as parameter" {:science-keywords {:0 {:variable-level-3 (:variable-level-3 sk1)}}} [science-keywords-boost] "science-keywords any as parameter" {:science-keywords {:0 {:any (:category sk1)}}} [science-keywords-boost] "2d coordinate system as keyword" {:keyword (:name tdcs2)} [two-d-boost] "2d coordinate system as parameter" {:two-d-coordinate-system-name (:name tdcs2)} [two-d-boost] "processing level id as keyword" {:keyword "PDQ123"} [processing-level-boost] "processing level id as parameter" {:processing-level-id "PDQ123"} [processing-level-boost] "data center as keyword" {:keyword (:org-name org)} [data-center-boost] "data center as parameter" {:data-center (:org-name org)} [data-center-boost] "archive center as parameter" {:archive-center (:org-name org)} [data-center-boost] "version-id" {:keyword "V001"} [(k2e/get-boost nil :version-id)] "entry-title" {:keyword "coll5"} [(k2e/get-boost nil :entry-title)] "provider-id" {:keyword "PROV1"} [provider-boost provider-boost provider-boost provider-boost])) (testing "Combine keyword and param boosts" ;; Check that the scores are very close to account for slight difference in ;; number coming from elastic. (are3 [params score] (is (< (Math/abs (double (- (/ score 2.0) (:score (first (:refs (search/find-refs :collection params))))))) 0.0000001)) "combine keyword, data center, and instrument" {:keyword "Proj-2" :data-center "Some&Place" :instrument "INST7"} (* project-boost data-center-boost instrument-boost) "instrument search and instrument keyword only results in one instrument boost" {:keyword "INST7" :instrument "INST7"} instrument-boost) (testing "Specified boosts on fields" (are3 [params scores] (is (= (map #(/ % 2.0) scores) (map :score (:refs (search/find-refs :collection params))))) "short-name" {:keyword "SNFoobar" :boosts {:short-name 2.0}} [2.0] "entry-id" {:keyword "ABC!XYZ_V001" :boosts {:entry-id 3.1}} [3.1] "project short-name" {:keyword (:short-name (first pr1)) :boosts {:project 3.0}} [3.0] "platform short-name" {:keyword (:short-name p1) :boosts {:platform 4.0}} [4.0] "instrument short-name" {:keyword (:short-name (first (:instruments p1))) :boosts {:instrument 5.0}} [5.0] ;; In UMM-C sensors are now instruments. All instruments (instruments + child instruments, ;; aka sensors) are indexed as both instruments and sensors until sensors search goes ;; away. Since they are instruments, there is no longer a sensor boost, but instrument ;; boost will be used. "sensor short-name" {:keyword (:short-name (first (:sensors (first (:instruments p1))))) :boosts {:instrument 6.0}} [6.0] "temporal-keywords" {:keyword "tk1" :boosts {:temporal-keyword 7.0}} [7.0] "spatial-keyword" {:keyword "in out" :boosts {:spatial-keyword 8.0}} [8.0] "science-keywords" {:keyword (:category sk1) :boosts {:science-keywords 9.0}} [9.0] "version-id" {:keyword "V001" :boosts {:version-id 10.0}} [10.0] "provider-id" {:keyword "PROV1" :boosts {:provider 10.0}} [10.0 10.0 10.0 10.0] "entry-title" {:keyword "coll5" :boosts {:entry-title 10.0}} [10.0] "mixed boosts" {:keyword "Mixed" :boosts {:short-name 10.0 :entry-title 11.0}} [11.0 10.0] "no defaults" {:keyword (:category sk1) :boosts {:include-defaults false}} [1.0] "matches all fields, do not include defaults" {:keyword "boost" :boosts {:short-name 5.0 :include-defaults false}} [5.0] "matches all fields, use defaults, but override short-name boost" {:keyword "boost" :boosts {:short-name 5.0 :include-defaults true}} [(* 5.0 entry-title-boost platform-boost science-keywords-boost)])) (testing "Setting boosts without keyword search is an error" (let [resp (search/find-refs :collection {:provider "PROV1" :page_size 5 :short_name "SNFoobar" :boosts {:short-name 2.0}}) {:keys [status errors]} resp] (is (= 400 status)) (is (= "Relevance boosting is only supported for keyword queries" (first errors))))) (testing "Boosting on invalid field" (let [resp (search/find-refs :collection {:provider "PROV1" :page_size 5 :keyword "Laser" :boosts {:foo 2.0}}) {:keys [status errors]} resp] (is (= 400 status)) (is (= "Cannot set relevance boost on field [foo]." (first errors))))) (testing "Boosting with non-numeric values is an error." (let [resp (search/find-refs :collection {:provider "PROV1" :page_size 5 :keyword "Laser" :boosts {:short-name "foo"}}) {:keys [status errors]} resp] (is (= 400 status)) (is (= "Relevance boost value [foo] for field [short_name] is not a number." (first errors))))) (testing "keyword number of keywords with wildcards exceeds the limit for the given max keyword string length." (let [resp (search/find-refs :collection {:provider "PROV1" :page_size 5 :keyword "000000000000000000000* 1* 2* 3* 4* 5* 6* 7* 8* 9* 10* 11* 12* 13* 14* 15* 16* 17* 18* 19* 20* 21* 22* 23* 24? 25* 26?" :boosts {:short-name 2.0}}) {:keys [status errors]} resp] (is (= 400 status)) (is (= "The CMR permits a maximum of 22 keywords with wildcards in a search, given the max length of the keyword being 22. Your query contains 27 keywords with wildcards" (first errors))))) (testing "keyword with too many wildcard is an error." (let [resp (search/find-refs :collection {:provider "PROV1" :page_size 5 :keyword "0* 1* 2* 3* 4* 5* 6* 7* 8* 9* 10* 11* 12* 13* 14* 15* 16* 17* 18* 19* 20* 21* 22* 23* 24* 25* 26* 27* 28* 29* 30?" :boosts {:short-name 2.0}}) {:keys [status errors]} resp] (is (= 400 status)) (is (= "Max number of keywords with wildcard allowed is 30" (first errors))))) (testing "sorted search" (are [params items] (let [refs (search/find-refs :collection params) matches? (d/refs-match-order? items refs)] (when-not matches? (println "Expected:" (map :entry-title items)) (println "Actual:" (map :name (:refs refs)))) matches?) {:keyword "Laser spoonA"} [coll9 coll14] {:keyword "La?er spoonA"} [coll9 coll14] {:keyword "L*er spo*A"} [coll9 coll14] {:keyword "L?s* s?o*A"} [coll9 coll14])) (testing "sorted search by keywords JSON query." (are [keyword-str items] (let [refs (search/find-refs-with-json-query :collection {} {:keyword keyword-str}) matches? (d/refs-match-order? items refs)] (when-not matches? (println "Expected:" (map :entry-title items)) (println "Actual:" (map :name (:refs refs)))) matches?) "Laser spoonA" [coll9 coll14])) (testing "sorted search by keywords with sort keys." (are [keyword-str sort-key items] (let [refs (search/find-refs :collection {:keyword keyword-str :sort-key sort-key}) matches? (d/refs-match-order? items refs)] (when-not matches? (println "Expected:" (map :entry-title items)) (println "Actual:" (map :name (:refs refs)))) matches?) "laser" "-entry-title" [coll7 coll5 coll21 coll14 coll9] "laser" "score" [coll21 coll5 coll7 coll9 coll14] "laser" "+score" [coll5 coll7 coll9 coll14 coll21] "laser" "-score" [coll21 coll5 coll7 coll9 coll14])) (testing "parameter search by keywords returns score" (let [refs (search/find-refs :collection {:keyword "Laser"})] (is (every? :score (:refs refs))))) (testing "JSON keywords search returns score" (let [refs (search/find-refs-with-json-query :collection {} {:keyword "Laser"})] (is (every? :score (:refs refs))))) (testing "search by multiple keywords returns an error." (let [resp (search/find-refs :collection {:provider "PROV1" :page_size 5 :keyword ["Laser" "spoon"]}) {:keys [status errors]} resp] (is (= 400 status)) (is (= "Parameter [keyword] must have a single value." (first errors))))) (testing "JSON negated keyword search does not return score" (let [refs (search/find-refs-with-json-query :collection {} {:not {:keyword "Laser"}})] (is (not-any? :score (:refs refs)))))))) ;; This test is separated out from the rest of the keyword search tests because we need to ;; ingest this UMM-SPEC collection but it contains some keyword values other tests are using. ;; This would break other tests when doing the keyword searches. (deftest search-by-more-keywords (let [coll1 (d/ingest "PROV1" (-> exp-conv/example-collection-record (assoc :AncillaryKeywords ["CMR2652AKW1" "CMR2652AKW2"]) (assoc :DOI (cm/map->DoiType {:DOI "doi" :Authority "auth"})) (assoc :DirectoryNames [(um/map->DirectoryNameType {:ShortName "CMR2654DNSN1" :LongName "CMR2654DNLN1"})]) (assoc :ISOTopicCategories ["environment" "health"]) (assoc :ShortName "CMR2652SN1") (assoc :EntryTitle "CMR2652ET1") (assoc :LocationKeywords [(um/map->LocationKeywordType {:Category "CONTINENT" :Type "ASIA" :Subregion1 "WESTERN ASIA" :Subregion2 "MIDDLE EAST" :Subregion3 "GAZA STRIP" :DetailedLocation "Testing Detailed Location"})])) {:format :umm-json :accept-format :json}) coll2 (d/ingest "PROV1" (-> exp-conv/example-collection-record (assoc :AncillaryKeywords ["CMR2652AKW3" "CMR2652AKW4"]) (assoc :DirectoryNames [(um/map->DirectoryNameType {:ShortName "CMR2654DNSN2" :LongName "CMR2654DNLN2"})]) (assoc :ISOTopicCategories ["biota"]) (assoc :ShortName "CMR2652SN2") (assoc :EntryTitle "CMR2652ET2")) {:format :umm-json :accept-format :json}) coll3 (d/ingest-concept-with-metadata-file "data/iso_mends/no_spatial_iso_collection.xml" {:provider-id "PROV1" :concept-type :collection :format-key :iso19115})] (index/wait-until-indexed) (testing "parameter searches" (are3 [keyword-str items] (let [parameter-refs (search/find-refs :collection {:keyword keyword-str})] (d/assert-refs-match items parameter-refs)) "testing parameter search by shortname keyword in collection whose xml file contains no SpatialExtent content" "NSIDC-0705" [coll3] "testing parameter search by existing ancillary keywords" "CMR2652AKW1" [coll1] "testing parameter search by existing DOI value" "dOI" [coll1] "testing parameter search by existing DirectoryNames keywords" "CMR2654DNSN1" [coll1] "testing parameter search by existing ancillary keywords" "CMR2652AKW4" [coll2] "testing parameter search by existing DirectoryNames keywords" "CMR2654DNLN2" [coll2] "testing parmaeter search by non-existing keywords" "CMR2652NOAKW" [] "testing iso-topic-category search - biota" "biota" [coll2] "testing iso-topic-category search - environment" "environment" [coll1] "testing iso-topic-category search - health" "health" [coll1] "testing detailed-location search - Testing Detailed Location" "Testing Detailed Location" [coll1])) (testing "Search collections by location keywords using JSON Query." (are3 [items search] (d/refs-match? items (search/find-refs-with-json-query :collection {} search)) "Testing detailed-location search" [coll1] {:location_keyword {:category "CONTINENT" :type "ASIA" :subregion_1 "WESTERN ASIA" :subregion_2 "MIDDLE EAST" :subregion_3 "GAZA STRIP" :detailed_location "Testing Detailed Location"}})) (testing "json query searchs" (are3 [keyword-str items] (let [json-refs (search/find-refs-with-json-query :collection {} {:keyword keyword-str})] (d/assert-refs-match items json-refs)) "testing json query search by shortname keyword in the collection whoes xml file contains no SpatialExtent content" "NSIDC-0705" [coll3] "testing json query search by existing ancillary keywords" "CMR2652AKW2" [coll1] "testing json query search by existing DirectoryNames keywords" "CMR2654DNLN1" [coll1] "testing json query search by existing ancillary keywords" "CMR2652AKW3" [coll2] "testing json query search by existing DirectoryNames keywords" "CMR2654DNSN2" [coll2] "testing json query search by non-existing keywords" "CMR2652NOAKW" [])))) ;; This tests that when searching by relevancy that if the score is the same short name ascending is used for ;; sorting the results and then if short name is the same version is used for sorting the results (deftest search-by-keywords-relevancy-sorting-includes-short-name-and-version (let [coll1 (d/ingest "PROV1" (dc/collection {:entry-title "MODIS/Terra Aerosol 5-Min L2 Swath 10km V5.1", :short-name "MOD04_L2", :version-id "5.1"})) coll2 (d/ingest "PROV1" (dc/collection {:entry-title "MODIS/Aqua Aerosol 5-Min L2 Swath 10km V5.1", :short-name "MYD04_L2", :version-id "5.1"})) coll3 (d/ingest "PROV1" (dc/collection {:entry-title "MODIS/Aqua Aerosol 5-Min L2 Swath 10km V006", :short-name "MYD04_L2", :version-id "6"})) coll4 (d/ingest "PROV1" (dc/collection {:entry-title "MODIS/Terra Aerosol 5-Min L2 Swath 10km V006", :short-name "MOD04_L2", :version-id "6"})) coll5 (d/ingest "PROV1" (dc/collection {:entry-title "MODIS/Aqua Total Precipitable Water Aerosol 5-Min L2 Swath 1km and 5km V5.1", :short-name "MYD05_L2", :version-id "5.1"})) coll6 (d/ingest "PROV1" (dc/collection {:entry-title "MODIS/Terra Total Precipitable Water Aerosol 5-Min L2 Swath 1km and 5km V5.1", :short-name "MOD05_L2", :version-id "5.1"})) coll7 (d/ingest "PROV1" (dc/collection {:entry-title "MODIS/Aqua Total Precipitable Water Aerosol 5-Min L2 Swath 1km and 5km V006", :short-name "MYD05_L2", :version-id "6"})) coll8 (d/ingest "PROV1" (dc/collection {:entry-title "MODIS/Terra Total Precipitable Water Aerosol 5-Min L2 Swath 1km and 5km V006", :short-name "MOD05_L2", :version-id "6"})) coll9 (d/ingest "PROV1" (dc/collection {:entry-title "MODIS Aerosol Other", :projects [(dc/project "MODIS" "ignored")] :platforms [(dc/platform {:short-name "MODIS"})] :short-name "Other", :version-id "1"}))] (index/wait-until-indexed) (let [refs (search/find-refs :collection {:keyword "modis aerosol"}) expected-order [coll9 ;; higher score ;; The scores of the rest of them are identical coll4 ;; MOD04_L2 6 coll1 ;; MOD04_L2 5.1 coll8 ;; MOD05_L2 6 coll6 ;; MOD05_L2 5.1 coll3 ;; MYD04_L2 6 coll2 ;; MYD04_L2 5.1 coll7 ;; MYD05_L2 6 coll5] ;; MYD05_L2 5.1 matched? (d/refs-match-order? expected-order refs)] (when-not matched? (println "Actual order: " (pr-str (map :id (:refs refs))))) (is matched?)))) (deftest search-by-keywords-with-special-chars ;; needed for special charatcter tests (let [coll-data [["coll00" "dummy && ||"] ["coll01" "begin!end"] ["coll02" "begin@end"] ["coll03" "begin#end"] ["coll04" "begin$end"] ["coll05" "begin%end"] ["coll06" "begin^end"] ["coll07" "begin&end"] ["coll08" "begin(end"] ["coll09" "begin)end"] ["coll10" "begin-end"] ["coll11" "begin=end"] ["coll12" "begin_end"] ["coll13" "begin+end"] ["coll14" "begin{end"] ["coll15" "begin}end"] ["coll16" "begin[end"] ["coll17" "begin]end"] ["coll18" "begin|end"] ["coll19" "begin\\end"] ["coll20" "begin;end"] ["coll21" "begin'end"] ["coll22" "begin.end"] ["coll23" "begin,end"] ["coll24" "begin/end"] ["coll25" "begin:end"] ["coll26" "begin\"end"] ["coll27" "begin<end"] ["coll28" "begin>end"] ["coll29" "begin?end"] ["coll30" "begin`end"] ["coll31" "begin~end"] ["coll32" "modis foobar"] ["coll33" "bleep blop blorp"] ["coll34" "abcdefghijklmnop"] ["coll35" "foo modis bar"] ["coll36" "akdi modis/terra dke"] ["coll37" "akdi modis-terra dke"] ["coll38" "Dataset with foobar"] ["coll39" "foo54"] ["coll40" "foo67"] ["coll41" "moding"] ["coll42" "outmoded"] ["coll43" "outmodising"] ["coll44" "out-modis-ed"] ["coll45" "carbon*oxygen"] ["coll46" "Dataset no withword"] ["coll47" "begin&&end"] ["coll48" "choco and taco"] ["coll49" "choco or taco"] ["coll50" "begin*end"]] colls (doall (for [[coll summary] coll-data] (d/ingest "PROV3" (dc/collection {:entry-title coll :summary summary}))))] (index/wait-until-indexed) (are [keyword-str indexes] (let [refs (search/find-refs :collection {:keyword keyword-str :page_size 51}) items (map (partial nth colls) indexes) matches? (d/refs-match? items refs)] (when-not matches? (println "Expected:" (map :entry-title items)) (println "Actual:" (map :name (:refs refs)))) matches?) "begin!end" [1] "begin\\end" [19] "begin<end" [27] "begin\\?end" [29] "begin~end" [31] "begin\\*end" [50] "begin" [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 47 50] "end" [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 47 50] "&&" [0] "||" [0] "AND" [48] "OR" [49])))
46953
(ns cmr.system-int-test.search.collection-keyword-search-test "Integration test for CMR collection search by keyword terms" (:require [clojure.test :refer :all] [cmr.common.util :refer [are3]] [cmr.search.data.keywords-to-elastic :as k2e] [cmr.system-int-test.data2.collection :as dc] [cmr.system-int-test.data2.core :as d] [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.umm-spec.models.umm-collection-models :as um] [cmr.umm-spec.models.umm-common-models :as cm] [cmr.umm-spec.test.expected-conversion :as exp-conv])) (use-fixtures :each (ingest/reset-fixture {"provguid1" "PROV1" "provguid2" "PROV2" "provguid3" "PROV3" "provguid4" "PROV4" "provguid5" "PROV5"})) (deftest search-by-keywords (let [short-name-boost (k2e/get-boost nil :short-name) entry-id-boost (k2e/get-boost nil :entry-id) project-boost (k2e/get-boost nil :project) platform-boost (k2e/get-boost nil :platform) instrument-boost (k2e/get-boost nil :instrument) concept-id-boost (k2e/get-boost nil :concept-id) provider-boost (k2e/get-boost nil :provider) entry-title-boost (k2e/get-boost nil :entry-title) two-d-boost (k2e/get-boost nil :two-d-coord-name) processing-level-boost (k2e/get-boost nil :processing-level-id) science-keywords-boost (k2e/get-boost nil :science-keywords) data-center-boost (k2e/get-boost nil :data-center) psa1 (dc/psa {:name "<NAME>" :data-type :string :value "ab"}) psa2 (dc/psa {:name "<NAME>" :data-type :string :value "bf"}) psa3 (dc/psa {:name "<NAME>" :data-type :string :value "foo"}) psa4 (dc/psa {:name "case" :data-type :string :value "up"}) psa5 (dc/psa {:name "novalue" :data-type :string :description "description"}) p1 (dc/platform {:short-name "platform_SnB" :long-name "platform_Ln B" :instruments [(dc/instrument {:short-name "isnA" :long-name "ilnA" :technique "itechniqueA" :sensors [(dc/sensor {:short-name "ssnA" :long-name "slnA"}) (dc/sensor {:short-name "ssnD" :long-name "slnD" :technique "techniqueD"})]})]}) p2 (dc/platform {:short-name "platform_SnA spoonA" :long-name "platform_LnA" :characteristics [(dc/characteristic {:name "char1" :description "char1desc"}) (dc/characteristic {:name "char2" :description "char2desc"})] :instruments [(dc/instrument {:short-name "isnB" :long-name "ilnB" :technique "itechniqueB" :sensors [(dc/sensor {:short-name "ssnB" :long-name "slnB" :technique "techniqueB"}) (dc/sensor {:short-name "ssnC" :long-name "slnC" :technique "techniqueC"})]})]}) p3 (dc/platform {:short-name "spoonA"}) p4 (dc/platform {:short-name "SMAP" :instruments [(dc/instrument {:short-name "SMAP L-BAND RADIOMETER"})]}) p5 (dc/platform {:short-name "fo&nA"}) p6 (dc/platform {:short-name "spo~nA"}) p7 (dc/platform {:short-name "platform7" :instruments [(dc/instrument {:short-name "INST7"})]}) pboost (dc/platform {:short-name "boost"}) pr1 (dc/projects "project-short-name") pr2 (dc/projects "Proj-2") sk1 (dc/science-keyword {:category "Cat1" :topic "Topic1" :term "Term1" :variable-level-1 "Level1-1" :variable-level-2 "Level1-2" :variable-level-3 "Level1-3" :detailed-variable "SUPER DETAILED!"}) sk2 (dc/science-keyword {:category "Hurricane" :topic "Laser spoonA" :term "Extreme" :variable-level-1 "Level2-1" :variable-level-2 "Level2-2" :variable-level-3 "Level2-3"}) sk3 (dc/science-keyword {:category "Cat2" :topic "Topic1" :term "Term1" :variable-level-1 "Level3-1" :variable-level-2 "Level3-2" :variable-level-3 "Level3-3" :detailed-variable "S@PER"}) skboost (dc/science-keyword {:category "boost" :topic "boost" :term "boost" :variable-level-1 "boost" :variable-level-2 "boost" :variable-level-3 "boost" :detailed-variable "boost"}) personnel1 (dc/personnel "<NAME>" "<NAME>" "<EMAIL>" "TECHNICAL CONTACT") personnel2 (dc/personnel "<NAME>" "<NAME>" "<EMAIL>" "TECHNICAL CONTACT") personnel3 (dc/personnel "<NAME>" "<NAME>" "<EMAIL>") tdcs1 (dc/two-d "XYZ") tdcs2 (dc/two-d "twoduniq") org (dc/org :archive-center "Some&Place") url1 (dc/related-url {:url "http://cmr.earthdata.nasa.gov" :description "Earthdata"}) url2 (dc/related-url {:url "http://nsidc.org/" :description "Home page of National Snow and Ice Data Center"}) coll1 (d/ingest "PROV1" (dc/collection {:entry-title "coll1" :version-description "VersionDescription"})) coll2 (d/ingest "PROV1" (dc/collection {:entry-title "coll2" :short-name "ABC!XYZ" :version-id "V001"})) coll3 (d/ingest "PROV1" (dc/collection {:entry-title "coll3" :collection-data-type "OTHER"})) coll4 (d/ingest "PROV2" (dc/collection {:entry-title "coll4" :collection-data-type "OTHER"})) coll5 (d/ingest "PROV2" (dc/collection {:entry-title "coll5" :short-name "Space!Laser"})) coll6 (d/ingest "PROV2" (dc/collection {:entry-title "coll6" :organizations [org] :projects pr2 :platforms [p7]})) coll7 (d/ingest "PROV2" (dc/collection {:entry-title "coll7" :version-id "Laser"})) coll8 (d/ingest "PROV2" (dc/collection {:entry-title "coll8" :processing-level-id "PDQ123"})) coll9 (d/ingest "PROV2" (dc/collection {:entry-title "coll09" :science-keywords [sk1 sk2]})) coll10 (d/ingest "PROV2" (dc/collection {:entry-title "coll10" :spatial-keywords ["in out"] :science-keywords [sk3]})) coll11 (d/ingest "PROV2" (dc/collection {:entry-title "coll11" :platforms [p2 p3 p5 p6] :product-specific-attributes [psa5]})) coll12 (d/ingest "PROV2" (dc/collection {:entry-title "coll12" :product-specific-attributes [psa1 psa2 psa3 psa4]})) coll13 (d/ingest "PROV2" (dc/collection {:entry-title "coll13" :two-d-coordinate-systems [tdcs1 tdcs2]})) coll14 (d/ingest "PROV2" (dc/collection {:entry-title "coll14" :short-name "spoonA laser"})) coll15 (d/ingest "PROV2" (dc/collection {:entry-title "coll15" :processing-level-id "plid1" :collection-data-type "SCIENCE_QUALITY" :platforms [p1] :summary "summary" :temporal-keywords ["tk1" "tk2"]})) coll16 (d/ingest "PROV2" (dc/collection-dif {:short-name "entryid4"}) {:format :dif}) coll17 (d/ingest "PROV2" (dc/collection {:associated-difs ["DIF-1" "DIF-2"]})) coll18 (d/ingest "PROV2" (dc/collection {:short-name "SNFoobar"})) coll20 (d/ingest "PROV2" (dc/collection {:projects pr1 :entry-title "Mixed"})) coll21 (d/ingest "PROV2" (dc/collection {:entry-title "coll21" :short-name "Laser"})) coll22 (d/ingest "PROV2" (dc/collection {:collection-data-type "NEAR_REAL_TIME" :short-name "Mixed"})) coll23 (d/ingest "PROV1" (dc/collection {:entry-title "coll23" :short-name "\"Quoted\" collection"})) coll24 (d/ingest "PROV2" (dc/collection {:entry-title "coll24" :short-name "coll24" :platforms [p4]})) ;; Adding personnel here to test keyword search using DataCenter contacts coll25 (d/ingest "PROV2" (dc/collection {:entry-title "coll25" :related-urls [url1 url2] :personnel [personnel3]})) coll-boost (d/ingest "PROV2" (dc/collection {:entry-title "boost" :short-name "boost" :platforms [pboost] :science-keywords [skboost]})) coll26 (d/ingest "PROV4" (dc/collection-dif10 {:entry-title "coll26" :personnel [personnel1]}) {:format :dif10}) coll27 (d/ingest "PROV5" (dc/collection-dif10 {:entry-title "coll27" :personnel [personnel2]}) {:format :dif10})] (index/wait-until-indexed) (testing "search by keywords." (are [keyword-str items] (let [parameter-refs (search/find-refs :collection {:keyword keyword-str}) json-refs (search/find-refs-with-json-query :collection {} {:keyword keyword-str}) parameter-matches? (d/refs-match? items parameter-refs) json-matches? (d/refs-match? items json-refs)] (when-not parameter-matches? (println "Parameter search failed") (println "Expected:" (map :entry-title items)) (println "Actual:" (map :name (:refs parameter-refs)))) (when-not json-matches? (println "JSON Query search failed") (println "Expected:" (map :entry-title items)) (println "Actual:" (map :name (:refs json-refs)))) (and parameter-matches? json-matches?)) ;; search by contact persons "<NAME>" [coll26] "<EMAIL>" [coll26] "<NAME>" [coll27] "<EMAIL>" [coll27] ;; search by data center contact "<NAME>" [coll25] "ABC" [coll2] "place" [coll6] "Laser" [coll21 coll5 coll7 coll9 coll14] "ABC V001" [coll2] "BLAH" [] "Space!Laser" [coll5] ;; Checking specific fields ;; provider "PROV1" [coll1 coll2 coll3 coll23] ;; entry title "coll1" [coll1] ;; entry id "ABC!XYZ_V001" [coll2] ;; short name "XYZ" [coll2 coll13] ;; version id "V001" [coll2] ;; version description "VersionDescription" [coll1] ;; processing level id "plid1" [coll15] ;; collection data type "SCIENCE_QUALITY" [coll15] ;; collection data type aliases for NEAR_REAL_TIME "NEAR_REAL_TIME" [coll22] "NRT" [coll22] "near_real_time" [coll22] "nrt" [coll22] "near-real-time" [coll22] "near real-time" [coll22] "near-real time" [coll22] ;; summary "summary" [coll15] ;; temporal keywords "tk1" [coll15] ;; spatial keywords "in" [coll10] ;; two d coord "xyz" [coll2 coll13] ;; archive center "some" [coll6] ;; attributes ;; - name "<NAME> <NAME>" [coll12] ;; - description "Generated" [coll12] ;; description with no value - see CMR-1129 "description" [coll11] ;; Platforms ;; - short name "platform_SnA" [coll11] ;; - long name (from metadata - not from KMS) "platform_ln" [coll15] ;; - long name (from KMS - not from the metadata) "Soil Moisture Active and Passive Observatory" [coll24] ;; - characteristic name "char1" [coll11] "char2" [coll11] "char1 char2" [coll11] ;; - chracteristic description "char1desc" [coll11] "char2desc" [coll11] "char1desc char2desc" [coll11] ;; Instruments ;; - short name "isnA" [coll15] ;; - long name (from metadata - not from KMS) "ilnB" [coll11] ;; - long name (from KMS - not from metadata) "SMAP L-Band Radiometer" [coll24] ;; - technique "itechniqueB" [coll11] "itechniqueA" [coll15] ;; Sensors ;; - short name "ssnA" [coll15] ;; - long name "slnB" [coll11] ;; - technique "techniqueB" [coll11] "techniqueD" [coll15] "techniqueB techniqueC" [coll11] ;; Science keywords ;; - category "Cat1" [coll9] ;; - topic "Topic1" [coll9 coll10] ;; - term "Term1" [coll9 coll10] ;; - variable-levels "Level2-1" [coll9] "Level2-2" [coll9] "Level2-3" [coll9] ;; - detailed-variable "SUPER" [coll9] ;; Related URLs "earthdata" [coll25] "nsidc" [coll25 coll27] ;; Special characters are escaped before sending to Elastic "ABC~ZYX" [] "ABC~" [] "spo~nA" [coll11] "fo&nA" [coll11] "A.+&.+C" [] "S@PER" [coll10] ;; search by keywords using wildcard * "XY*" [coll2 coll13] "*aser" [coll21 coll5 coll7 coll9 coll14] "p*ce" [coll6] "NEA*REA*IME" [coll22] "nea*rea*ime" [coll22] "\"Quoted*" [coll23] ;; search by keywords using wildcard ? "XY?" [coll2 coll13] "?aser" [coll21 coll5 coll7 coll9 coll14] "p*ace" [coll6] "NEAR?REAL?TIME" [coll22] "near?real?time" [coll22])) (testing "Default boosts on fields" (are3 [params scores] (is (= (map #(/ % 2.0) scores) (map :score (:refs (search/find-refs :collection params))))) "short-name" {:keyword "SNFoobar"} [short-name-boost] "entry-id" {:keyword "ABC!XYZ_V001"} [entry-id-boost] "project short-name as keyword" {:keyword (:short-name (first pr1))} [project-boost] "project short-name as parameter" {:project (:short-name (first pr1))} [project-boost] "project long-name" {:keyword (:long-name (first pr1))} [project-boost] "platform short-name as keyword" {:keyword (:short-name p1)} [platform-boost] "platform short-name as parameter" {:platform (:short-name p1)} [platform-boost] "platform short-name as parameter with pattern" {:platform "*spoonA" "options[platform][pattern]" true} [platform-boost] "platform long-name (from metadata)" {:keyword (:long-name p1)} [platform-boost] "platform long-name (from KMS)" {:keyword "Soil Moisture Active and Passive Observatory"} [platform-boost] "instrument short-name as keyword" {:keyword (:short-name (first (:instruments p1)))} [instrument-boost] "instrument short-name as parameter" {:instrument (:short-name (first (:instruments p1)))} [instrument-boost] "instrument long-name (from metadata)" {:keyword (:long-name (first (:instruments p1)))} [instrument-boost] "instrument long-name (from KMS)" {:keyword "L-Band Radiometer"} [instrument-boost] ;; In UMM-C sensors are now instruments. All instruments (instruments + child instruments, ;; aka sensors) are indexed as both instruments and sensors until sensors search goes ;; away. Since they are instruments, there is no longer a sensor boost, but instrument ;; boost will be used. "sensor short-name as keyword" {:keyword (:short-name (first (:sensors (first (:instruments p1)))))} [instrument-boost] "sensor short-name as parameter" {:sensor (:short-name (first (:sensors (first (:instruments p1)))))} [instrument-boost] "sensor long-name" {:keyword (:long-name (first (:sensors (first (:instruments p1)))))} [instrument-boost] "temporal-keywords" {:keyword "tk1"} [(k2e/get-boost nil :temporal-keyword)] "spatial-keyword" {:keyword "in out"} [(k2e/get-boost nil :spatial-keyword)] "science-keywords as keyword" {:keyword (:category sk1)} [science-keywords-boost] "science-keywords category as parameter" {:science-keywords {:0 {:category (:category sk1)}}} [science-keywords-boost] "science-keywords topic as parameter" {:science-keywords {:0 {:topic (:topic sk1)}}} [science-keywords-boost science-keywords-boost] "science-keywords term as parameter" {:science-keywords {:0 {:term (:term sk1)}}} [science-keywords-boost science-keywords-boost] "science-keywords variable-level-1 as parameter" {:science-keywords {:0 {:variable-level-1 (:variable-level-1 sk1)}}} [science-keywords-boost] "science-keywords variable-level-2 as parameter" {:science-keywords {:0 {:variable-level-2 (:variable-level-2 sk1)}}} [science-keywords-boost] "science-keywords variable-level-3 as parameter" {:science-keywords {:0 {:variable-level-3 (:variable-level-3 sk1)}}} [science-keywords-boost] "science-keywords any as parameter" {:science-keywords {:0 {:any (:category sk1)}}} [science-keywords-boost] "2d coordinate system as keyword" {:keyword (:name tdcs2)} [two-d-boost] "2d coordinate system as parameter" {:two-d-coordinate-system-name (:name tdcs2)} [two-d-boost] "processing level id as keyword" {:keyword "PDQ123"} [processing-level-boost] "processing level id as parameter" {:processing-level-id "PDQ123"} [processing-level-boost] "data center as keyword" {:keyword (:org-name org)} [data-center-boost] "data center as parameter" {:data-center (:org-name org)} [data-center-boost] "archive center as parameter" {:archive-center (:org-name org)} [data-center-boost] "version-id" {:keyword "V001"} [(k2e/get-boost nil :version-id)] "entry-title" {:keyword "coll5"} [(k2e/get-boost nil :entry-title)] "provider-id" {:keyword "PROV1"} [provider-boost provider-boost provider-boost provider-boost])) (testing "Combine keyword and param boosts" ;; Check that the scores are very close to account for slight difference in ;; number coming from elastic. (are3 [params score] (is (< (Math/abs (double (- (/ score 2.0) (:score (first (:refs (search/find-refs :collection params))))))) 0.0000001)) "combine keyword, data center, and instrument" {:keyword "Proj-2" :data-center "Some&Place" :instrument "INST7"} (* project-boost data-center-boost instrument-boost) "instrument search and instrument keyword only results in one instrument boost" {:keyword "INST7" :instrument "INST7"} instrument-boost) (testing "Specified boosts on fields" (are3 [params scores] (is (= (map #(/ % 2.0) scores) (map :score (:refs (search/find-refs :collection params))))) "short-name" {:keyword "SNFoobar" :boosts {:short-name 2.0}} [2.0] "entry-id" {:keyword "ABC!XYZ_V001" :boosts {:entry-id 3.1}} [3.1] "project short-name" {:keyword (:short-name (first pr1)) :boosts {:project 3.0}} [3.0] "platform short-name" {:keyword (:short-name p1) :boosts {:platform 4.0}} [4.0] "instrument short-name" {:keyword (:short-name (first (:instruments p1))) :boosts {:instrument 5.0}} [5.0] ;; In UMM-C sensors are now instruments. All instruments (instruments + child instruments, ;; aka sensors) are indexed as both instruments and sensors until sensors search goes ;; away. Since they are instruments, there is no longer a sensor boost, but instrument ;; boost will be used. "sensor short-name" {:keyword (:short-name (first (:sensors (first (:instruments p1))))) :boosts {:instrument 6.0}} [6.0] "temporal-keywords" {:keyword "tk1" :boosts {:temporal-keyword 7.0}} [7.0] "spatial-keyword" {:keyword "in out" :boosts {:spatial-keyword 8.0}} [8.0] "science-keywords" {:keyword (:category sk1) :boosts {:science-keywords 9.0}} [9.0] "version-id" {:keyword "V001" :boosts {:version-id 10.0}} [10.0] "provider-id" {:keyword "PROV1" :boosts {:provider 10.0}} [10.0 10.0 10.0 10.0] "entry-title" {:keyword "coll5" :boosts {:entry-title 10.0}} [10.0] "mixed boosts" {:keyword "Mixed" :boosts {:short-name 10.0 :entry-title 11.0}} [11.0 10.0] "no defaults" {:keyword (:category sk1) :boosts {:include-defaults false}} [1.0] "matches all fields, do not include defaults" {:keyword "boost" :boosts {:short-name 5.0 :include-defaults false}} [5.0] "matches all fields, use defaults, but override short-name boost" {:keyword "boost" :boosts {:short-name 5.0 :include-defaults true}} [(* 5.0 entry-title-boost platform-boost science-keywords-boost)])) (testing "Setting boosts without keyword search is an error" (let [resp (search/find-refs :collection {:provider "PROV1" :page_size 5 :short_name "SNFoobar" :boosts {:short-name 2.0}}) {:keys [status errors]} resp] (is (= 400 status)) (is (= "Relevance boosting is only supported for keyword queries" (first errors))))) (testing "Boosting on invalid field" (let [resp (search/find-refs :collection {:provider "PROV1" :page_size 5 :keyword "Laser" :boosts {:foo 2.0}}) {:keys [status errors]} resp] (is (= 400 status)) (is (= "Cannot set relevance boost on field [foo]." (first errors))))) (testing "Boosting with non-numeric values is an error." (let [resp (search/find-refs :collection {:provider "PROV1" :page_size 5 :keyword "Laser" :boosts {:short-name "foo"}}) {:keys [status errors]} resp] (is (= 400 status)) (is (= "Relevance boost value [foo] for field [short_name] is not a number." (first errors))))) (testing "keyword number of keywords with wildcards exceeds the limit for the given max keyword string length." (let [resp (search/find-refs :collection {:provider "PROV1" :page_size 5 :keyword "000000000000000000000* 1* 2* 3* 4* 5* 6* 7* 8* 9* 10* 11* 12* 13* 14* 15* 16* 17* 18* 19* 20* 21* 22* 23* 24? 25* 26?" :boosts {:short-name 2.0}}) {:keys [status errors]} resp] (is (= 400 status)) (is (= "The CMR permits a maximum of 22 keywords with wildcards in a search, given the max length of the keyword being 22. Your query contains 27 keywords with wildcards" (first errors))))) (testing "keyword with too many wildcard is an error." (let [resp (search/find-refs :collection {:provider "PROV1" :page_size 5 :keyword "0* 1* 2* 3* 4* 5* 6* 7* 8* 9* 10* 11* 12* 13* 14* 15* 16* 17* 18* 19* 20* 21* 22* 23* 24* 25* 26* 27* 28* 29* 30?" :boosts {:short-name 2.0}}) {:keys [status errors]} resp] (is (= 400 status)) (is (= "Max number of keywords with wildcard allowed is 30" (first errors))))) (testing "sorted search" (are [params items] (let [refs (search/find-refs :collection params) matches? (d/refs-match-order? items refs)] (when-not matches? (println "Expected:" (map :entry-title items)) (println "Actual:" (map :name (:refs refs)))) matches?) {:keyword "Laser spoonA"} [coll9 coll14] {:keyword "La?er spoonA"} [coll9 coll14] {:keyword "L*er spo*A"} [coll9 coll14] {:keyword "L?s* s?o*A"} [coll9 coll14])) (testing "sorted search by keywords JSON query." (are [keyword-str items] (let [refs (search/find-refs-with-json-query :collection {} {:keyword keyword-str}) matches? (d/refs-match-order? items refs)] (when-not matches? (println "Expected:" (map :entry-title items)) (println "Actual:" (map :name (:refs refs)))) matches?) "Laser spoonA" [coll9 coll14])) (testing "sorted search by keywords with sort keys." (are [keyword-str sort-key items] (let [refs (search/find-refs :collection {:keyword keyword-str :sort-key sort-key}) matches? (d/refs-match-order? items refs)] (when-not matches? (println "Expected:" (map :entry-title items)) (println "Actual:" (map :name (:refs refs)))) matches?) "laser" "-entry-title" [coll7 coll5 coll21 coll14 coll9] "laser" "score" [coll21 coll5 coll7 coll9 coll14] "laser" "+score" [coll5 coll7 coll9 coll14 coll21] "laser" "-score" [coll21 coll5 coll7 coll9 coll14])) (testing "parameter search by keywords returns score" (let [refs (search/find-refs :collection {:keyword "Laser"})] (is (every? :score (:refs refs))))) (testing "JSON keywords search returns score" (let [refs (search/find-refs-with-json-query :collection {} {:keyword "Laser"})] (is (every? :score (:refs refs))))) (testing "search by multiple keywords returns an error." (let [resp (search/find-refs :collection {:provider "PROV1" :page_size 5 :keyword ["Laser" "spoon"]}) {:keys [status errors]} resp] (is (= 400 status)) (is (= "Parameter [keyword] must have a single value." (first errors))))) (testing "JSON negated keyword search does not return score" (let [refs (search/find-refs-with-json-query :collection {} {:not {:keyword "Laser"}})] (is (not-any? :score (:refs refs)))))))) ;; This test is separated out from the rest of the keyword search tests because we need to ;; ingest this UMM-SPEC collection but it contains some keyword values other tests are using. ;; This would break other tests when doing the keyword searches. (deftest search-by-more-keywords (let [coll1 (d/ingest "PROV1" (-> exp-conv/example-collection-record (assoc :AncillaryKeywords ["CMR2652AKW1" "CMR2652AKW2"]) (assoc :DOI (cm/map->DoiType {:DOI "doi" :Authority "auth"})) (assoc :DirectoryNames [(um/map->DirectoryNameType {:ShortName "CMR2654DNSN1" :LongName "CMR2654DNLN1"})]) (assoc :ISOTopicCategories ["environment" "health"]) (assoc :ShortName "CMR2652SN1") (assoc :EntryTitle "CMR2652ET1") (assoc :LocationKeywords [(um/map->LocationKeywordType {:Category "CONTINENT" :Type "ASIA" :Subregion1 "WESTERN ASIA" :Subregion2 "MIDDLE EAST" :Subregion3 "GAZA STRIP" :DetailedLocation "Testing Detailed Location"})])) {:format :umm-json :accept-format :json}) coll2 (d/ingest "PROV1" (-> exp-conv/example-collection-record (assoc :AncillaryKeywords ["CMR2652AKW3" "CMR2652AKW4"]) (assoc :DirectoryNames [(um/map->DirectoryNameType {:ShortName "CMR2654DNSN2" :LongName "CMR2654DNLN2"})]) (assoc :ISOTopicCategories ["biota"]) (assoc :ShortName "CMR2652SN2") (assoc :EntryTitle "CMR2652ET2")) {:format :umm-json :accept-format :json}) coll3 (d/ingest-concept-with-metadata-file "data/iso_mends/no_spatial_iso_collection.xml" {:provider-id "PROV1" :concept-type :collection :format-key :iso19115})] (index/wait-until-indexed) (testing "parameter searches" (are3 [keyword-str items] (let [parameter-refs (search/find-refs :collection {:keyword keyword-str})] (d/assert-refs-match items parameter-refs)) "testing parameter search by shortname keyword in collection whose xml file contains no SpatialExtent content" "NSIDC-0705" [coll3] "testing parameter search by existing ancillary keywords" "CMR2652AKW1" [coll1] "testing parameter search by existing DOI value" "dOI" [coll1] "testing parameter search by existing DirectoryNames keywords" "CMR2654DNSN1" [coll1] "testing parameter search by existing ancillary keywords" "CMR2652AKW4" [coll2] "testing parameter search by existing DirectoryNames keywords" "CMR2654DNLN2" [coll2] "testing parmaeter search by non-existing keywords" "CMR2652NOAKW" [] "testing iso-topic-category search - biota" "biota" [coll2] "testing iso-topic-category search - environment" "environment" [coll1] "testing iso-topic-category search - health" "health" [coll1] "testing detailed-location search - Testing Detailed Location" "Testing Detailed Location" [coll1])) (testing "Search collections by location keywords using JSON Query." (are3 [items search] (d/refs-match? items (search/find-refs-with-json-query :collection {} search)) "Testing detailed-location search" [coll1] {:location_keyword {:category "CONTINENT" :type "ASIA" :subregion_1 "WESTERN ASIA" :subregion_2 "MIDDLE EAST" :subregion_3 "GAZA STRIP" :detailed_location "Testing Detailed Location"}})) (testing "json query searchs" (are3 [keyword-str items] (let [json-refs (search/find-refs-with-json-query :collection {} {:keyword keyword-str})] (d/assert-refs-match items json-refs)) "testing json query search by shortname keyword in the collection whoes xml file contains no SpatialExtent content" "NSIDC-0705" [coll3] "testing json query search by existing ancillary keywords" "CMR2652AKW2" [coll1] "testing json query search by existing DirectoryNames keywords" "CMR2654DNLN1" [coll1] "testing json query search by existing ancillary keywords" "CMR2652AKW3" [coll2] "testing json query search by existing DirectoryNames keywords" "CMR2654DNSN2" [coll2] "testing json query search by non-existing keywords" "CMR2652NOAKW" [])))) ;; This tests that when searching by relevancy that if the score is the same short name ascending is used for ;; sorting the results and then if short name is the same version is used for sorting the results (deftest search-by-keywords-relevancy-sorting-includes-short-name-and-version (let [coll1 (d/ingest "PROV1" (dc/collection {:entry-title "MODIS/Terra Aerosol 5-Min L2 Swath 10km V5.1", :short-name "MOD04_L2", :version-id "5.1"})) coll2 (d/ingest "PROV1" (dc/collection {:entry-title "MODIS/Aqua Aerosol 5-Min L2 Swath 10km V5.1", :short-name "MYD04_L2", :version-id "5.1"})) coll3 (d/ingest "PROV1" (dc/collection {:entry-title "MODIS/Aqua Aerosol 5-Min L2 Swath 10km V006", :short-name "MYD04_L2", :version-id "6"})) coll4 (d/ingest "PROV1" (dc/collection {:entry-title "MODIS/Terra Aerosol 5-Min L2 Swath 10km V006", :short-name "MOD04_L2", :version-id "6"})) coll5 (d/ingest "PROV1" (dc/collection {:entry-title "MODIS/Aqua Total Precipitable Water Aerosol 5-Min L2 Swath 1km and 5km V5.1", :short-name "MYD05_L2", :version-id "5.1"})) coll6 (d/ingest "PROV1" (dc/collection {:entry-title "MODIS/Terra Total Precipitable Water Aerosol 5-Min L2 Swath 1km and 5km V5.1", :short-name "MOD05_L2", :version-id "5.1"})) coll7 (d/ingest "PROV1" (dc/collection {:entry-title "MODIS/Aqua Total Precipitable Water Aerosol 5-Min L2 Swath 1km and 5km V006", :short-name "MYD05_L2", :version-id "6"})) coll8 (d/ingest "PROV1" (dc/collection {:entry-title "MODIS/Terra Total Precipitable Water Aerosol 5-Min L2 Swath 1km and 5km V006", :short-name "MOD05_L2", :version-id "6"})) coll9 (d/ingest "PROV1" (dc/collection {:entry-title "MODIS Aerosol Other", :projects [(dc/project "MODIS" "ignored")] :platforms [(dc/platform {:short-name "MODIS"})] :short-name "Other", :version-id "1"}))] (index/wait-until-indexed) (let [refs (search/find-refs :collection {:keyword "modis aerosol"}) expected-order [coll9 ;; higher score ;; The scores of the rest of them are identical coll4 ;; MOD04_L2 6 coll1 ;; MOD04_L2 5.1 coll8 ;; MOD05_L2 6 coll6 ;; MOD05_L2 5.1 coll3 ;; MYD04_L2 6 coll2 ;; MYD04_L2 5.1 coll7 ;; MYD05_L2 6 coll5] ;; MYD05_L2 5.1 matched? (d/refs-match-order? expected-order refs)] (when-not matched? (println "Actual order: " (pr-str (map :id (:refs refs))))) (is matched?)))) (deftest search-by-keywords-with-special-chars ;; needed for special charatcter tests (let [coll-data [["coll00" "dummy && ||"] ["coll01" "begin!end"] ["coll02" "begin@end"] ["coll03" "begin#end"] ["coll04" "begin$end"] ["coll05" "begin%end"] ["coll06" "begin^end"] ["coll07" "begin&end"] ["coll08" "begin(end"] ["coll09" "begin)end"] ["coll10" "begin-end"] ["coll11" "begin=end"] ["coll12" "begin_end"] ["coll13" "begin+end"] ["coll14" "begin{end"] ["coll15" "begin}end"] ["coll16" "begin[end"] ["coll17" "begin]end"] ["coll18" "begin|end"] ["coll19" "begin\\end"] ["coll20" "begin;end"] ["coll21" "begin'end"] ["coll22" "begin.end"] ["coll23" "begin,end"] ["coll24" "begin/end"] ["coll25" "begin:end"] ["coll26" "begin\"end"] ["coll27" "begin<end"] ["coll28" "begin>end"] ["coll29" "begin?end"] ["coll30" "begin`end"] ["coll31" "begin~end"] ["coll32" "modis foobar"] ["coll33" "bleep blop blorp"] ["coll34" "abcdefghijklmnop"] ["coll35" "foo modis bar"] ["coll36" "akdi modis/terra dke"] ["coll37" "akdi modis-terra dke"] ["coll38" "Dataset with foobar"] ["coll39" "foo54"] ["coll40" "foo67"] ["coll41" "moding"] ["coll42" "outmoded"] ["coll43" "outmodising"] ["coll44" "out-modis-ed"] ["coll45" "carbon*oxygen"] ["coll46" "Dataset no withword"] ["coll47" "begin&&end"] ["coll48" "choco and taco"] ["coll49" "choco or taco"] ["coll50" "begin*end"]] colls (doall (for [[coll summary] coll-data] (d/ingest "PROV3" (dc/collection {:entry-title coll :summary summary}))))] (index/wait-until-indexed) (are [keyword-str indexes] (let [refs (search/find-refs :collection {:keyword keyword-str :page_size 51}) items (map (partial nth colls) indexes) matches? (d/refs-match? items refs)] (when-not matches? (println "Expected:" (map :entry-title items)) (println "Actual:" (map :name (:refs refs)))) matches?) "begin!end" [1] "begin\\end" [19] "begin<end" [27] "begin\\?end" [29] "begin~end" [31] "begin\\*end" [50] "begin" [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 47 50] "end" [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 47 50] "&&" [0] "||" [0] "AND" [48] "OR" [49])))
true
(ns cmr.system-int-test.search.collection-keyword-search-test "Integration test for CMR collection search by keyword terms" (:require [clojure.test :refer :all] [cmr.common.util :refer [are3]] [cmr.search.data.keywords-to-elastic :as k2e] [cmr.system-int-test.data2.collection :as dc] [cmr.system-int-test.data2.core :as d] [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.umm-spec.models.umm-collection-models :as um] [cmr.umm-spec.models.umm-common-models :as cm] [cmr.umm-spec.test.expected-conversion :as exp-conv])) (use-fixtures :each (ingest/reset-fixture {"provguid1" "PROV1" "provguid2" "PROV2" "provguid3" "PROV3" "provguid4" "PROV4" "provguid5" "PROV5"})) (deftest search-by-keywords (let [short-name-boost (k2e/get-boost nil :short-name) entry-id-boost (k2e/get-boost nil :entry-id) project-boost (k2e/get-boost nil :project) platform-boost (k2e/get-boost nil :platform) instrument-boost (k2e/get-boost nil :instrument) concept-id-boost (k2e/get-boost nil :concept-id) provider-boost (k2e/get-boost nil :provider) entry-title-boost (k2e/get-boost nil :entry-title) two-d-boost (k2e/get-boost nil :two-d-coord-name) processing-level-boost (k2e/get-boost nil :processing-level-id) science-keywords-boost (k2e/get-boost nil :science-keywords) data-center-boost (k2e/get-boost nil :data-center) psa1 (dc/psa {:name "PI:NAME:<NAME>END_PI" :data-type :string :value "ab"}) psa2 (dc/psa {:name "PI:NAME:<NAME>END_PI" :data-type :string :value "bf"}) psa3 (dc/psa {:name "PI:NAME:<NAME>END_PI" :data-type :string :value "foo"}) psa4 (dc/psa {:name "case" :data-type :string :value "up"}) psa5 (dc/psa {:name "novalue" :data-type :string :description "description"}) p1 (dc/platform {:short-name "platform_SnB" :long-name "platform_Ln B" :instruments [(dc/instrument {:short-name "isnA" :long-name "ilnA" :technique "itechniqueA" :sensors [(dc/sensor {:short-name "ssnA" :long-name "slnA"}) (dc/sensor {:short-name "ssnD" :long-name "slnD" :technique "techniqueD"})]})]}) p2 (dc/platform {:short-name "platform_SnA spoonA" :long-name "platform_LnA" :characteristics [(dc/characteristic {:name "char1" :description "char1desc"}) (dc/characteristic {:name "char2" :description "char2desc"})] :instruments [(dc/instrument {:short-name "isnB" :long-name "ilnB" :technique "itechniqueB" :sensors [(dc/sensor {:short-name "ssnB" :long-name "slnB" :technique "techniqueB"}) (dc/sensor {:short-name "ssnC" :long-name "slnC" :technique "techniqueC"})]})]}) p3 (dc/platform {:short-name "spoonA"}) p4 (dc/platform {:short-name "SMAP" :instruments [(dc/instrument {:short-name "SMAP L-BAND RADIOMETER"})]}) p5 (dc/platform {:short-name "fo&nA"}) p6 (dc/platform {:short-name "spo~nA"}) p7 (dc/platform {:short-name "platform7" :instruments [(dc/instrument {:short-name "INST7"})]}) pboost (dc/platform {:short-name "boost"}) pr1 (dc/projects "project-short-name") pr2 (dc/projects "Proj-2") sk1 (dc/science-keyword {:category "Cat1" :topic "Topic1" :term "Term1" :variable-level-1 "Level1-1" :variable-level-2 "Level1-2" :variable-level-3 "Level1-3" :detailed-variable "SUPER DETAILED!"}) sk2 (dc/science-keyword {:category "Hurricane" :topic "Laser spoonA" :term "Extreme" :variable-level-1 "Level2-1" :variable-level-2 "Level2-2" :variable-level-3 "Level2-3"}) sk3 (dc/science-keyword {:category "Cat2" :topic "Topic1" :term "Term1" :variable-level-1 "Level3-1" :variable-level-2 "Level3-2" :variable-level-3 "Level3-3" :detailed-variable "S@PER"}) skboost (dc/science-keyword {:category "boost" :topic "boost" :term "boost" :variable-level-1 "boost" :variable-level-2 "boost" :variable-level-3 "boost" :detailed-variable "boost"}) personnel1 (dc/personnel "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:EMAIL:<EMAIL>END_PI" "TECHNICAL CONTACT") personnel2 (dc/personnel "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:EMAIL:<EMAIL>END_PI" "TECHNICAL CONTACT") personnel3 (dc/personnel "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:EMAIL:<EMAIL>END_PI") tdcs1 (dc/two-d "XYZ") tdcs2 (dc/two-d "twoduniq") org (dc/org :archive-center "Some&Place") url1 (dc/related-url {:url "http://cmr.earthdata.nasa.gov" :description "Earthdata"}) url2 (dc/related-url {:url "http://nsidc.org/" :description "Home page of National Snow and Ice Data Center"}) coll1 (d/ingest "PROV1" (dc/collection {:entry-title "coll1" :version-description "VersionDescription"})) coll2 (d/ingest "PROV1" (dc/collection {:entry-title "coll2" :short-name "ABC!XYZ" :version-id "V001"})) coll3 (d/ingest "PROV1" (dc/collection {:entry-title "coll3" :collection-data-type "OTHER"})) coll4 (d/ingest "PROV2" (dc/collection {:entry-title "coll4" :collection-data-type "OTHER"})) coll5 (d/ingest "PROV2" (dc/collection {:entry-title "coll5" :short-name "Space!Laser"})) coll6 (d/ingest "PROV2" (dc/collection {:entry-title "coll6" :organizations [org] :projects pr2 :platforms [p7]})) coll7 (d/ingest "PROV2" (dc/collection {:entry-title "coll7" :version-id "Laser"})) coll8 (d/ingest "PROV2" (dc/collection {:entry-title "coll8" :processing-level-id "PDQ123"})) coll9 (d/ingest "PROV2" (dc/collection {:entry-title "coll09" :science-keywords [sk1 sk2]})) coll10 (d/ingest "PROV2" (dc/collection {:entry-title "coll10" :spatial-keywords ["in out"] :science-keywords [sk3]})) coll11 (d/ingest "PROV2" (dc/collection {:entry-title "coll11" :platforms [p2 p3 p5 p6] :product-specific-attributes [psa5]})) coll12 (d/ingest "PROV2" (dc/collection {:entry-title "coll12" :product-specific-attributes [psa1 psa2 psa3 psa4]})) coll13 (d/ingest "PROV2" (dc/collection {:entry-title "coll13" :two-d-coordinate-systems [tdcs1 tdcs2]})) coll14 (d/ingest "PROV2" (dc/collection {:entry-title "coll14" :short-name "spoonA laser"})) coll15 (d/ingest "PROV2" (dc/collection {:entry-title "coll15" :processing-level-id "plid1" :collection-data-type "SCIENCE_QUALITY" :platforms [p1] :summary "summary" :temporal-keywords ["tk1" "tk2"]})) coll16 (d/ingest "PROV2" (dc/collection-dif {:short-name "entryid4"}) {:format :dif}) coll17 (d/ingest "PROV2" (dc/collection {:associated-difs ["DIF-1" "DIF-2"]})) coll18 (d/ingest "PROV2" (dc/collection {:short-name "SNFoobar"})) coll20 (d/ingest "PROV2" (dc/collection {:projects pr1 :entry-title "Mixed"})) coll21 (d/ingest "PROV2" (dc/collection {:entry-title "coll21" :short-name "Laser"})) coll22 (d/ingest "PROV2" (dc/collection {:collection-data-type "NEAR_REAL_TIME" :short-name "Mixed"})) coll23 (d/ingest "PROV1" (dc/collection {:entry-title "coll23" :short-name "\"Quoted\" collection"})) coll24 (d/ingest "PROV2" (dc/collection {:entry-title "coll24" :short-name "coll24" :platforms [p4]})) ;; Adding personnel here to test keyword search using DataCenter contacts coll25 (d/ingest "PROV2" (dc/collection {:entry-title "coll25" :related-urls [url1 url2] :personnel [personnel3]})) coll-boost (d/ingest "PROV2" (dc/collection {:entry-title "boost" :short-name "boost" :platforms [pboost] :science-keywords [skboost]})) coll26 (d/ingest "PROV4" (dc/collection-dif10 {:entry-title "coll26" :personnel [personnel1]}) {:format :dif10}) coll27 (d/ingest "PROV5" (dc/collection-dif10 {:entry-title "coll27" :personnel [personnel2]}) {:format :dif10})] (index/wait-until-indexed) (testing "search by keywords." (are [keyword-str items] (let [parameter-refs (search/find-refs :collection {:keyword keyword-str}) json-refs (search/find-refs-with-json-query :collection {} {:keyword keyword-str}) parameter-matches? (d/refs-match? items parameter-refs) json-matches? (d/refs-match? items json-refs)] (when-not parameter-matches? (println "Parameter search failed") (println "Expected:" (map :entry-title items)) (println "Actual:" (map :name (:refs parameter-refs)))) (when-not json-matches? (println "JSON Query search failed") (println "Expected:" (map :entry-title items)) (println "Actual:" (map :name (:refs json-refs)))) (and parameter-matches? json-matches?)) ;; search by contact persons "PI:NAME:<NAME>END_PI" [coll26] "PI:EMAIL:<EMAIL>END_PI" [coll26] "PI:NAME:<NAME>END_PI" [coll27] "PI:EMAIL:<EMAIL>END_PI" [coll27] ;; search by data center contact "PI:NAME:<NAME>END_PI" [coll25] "ABC" [coll2] "place" [coll6] "Laser" [coll21 coll5 coll7 coll9 coll14] "ABC V001" [coll2] "BLAH" [] "Space!Laser" [coll5] ;; Checking specific fields ;; provider "PROV1" [coll1 coll2 coll3 coll23] ;; entry title "coll1" [coll1] ;; entry id "ABC!XYZ_V001" [coll2] ;; short name "XYZ" [coll2 coll13] ;; version id "V001" [coll2] ;; version description "VersionDescription" [coll1] ;; processing level id "plid1" [coll15] ;; collection data type "SCIENCE_QUALITY" [coll15] ;; collection data type aliases for NEAR_REAL_TIME "NEAR_REAL_TIME" [coll22] "NRT" [coll22] "near_real_time" [coll22] "nrt" [coll22] "near-real-time" [coll22] "near real-time" [coll22] "near-real time" [coll22] ;; summary "summary" [coll15] ;; temporal keywords "tk1" [coll15] ;; spatial keywords "in" [coll10] ;; two d coord "xyz" [coll2 coll13] ;; archive center "some" [coll6] ;; attributes ;; - name "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI" [coll12] ;; - description "Generated" [coll12] ;; description with no value - see CMR-1129 "description" [coll11] ;; Platforms ;; - short name "platform_SnA" [coll11] ;; - long name (from metadata - not from KMS) "platform_ln" [coll15] ;; - long name (from KMS - not from the metadata) "Soil Moisture Active and Passive Observatory" [coll24] ;; - characteristic name "char1" [coll11] "char2" [coll11] "char1 char2" [coll11] ;; - chracteristic description "char1desc" [coll11] "char2desc" [coll11] "char1desc char2desc" [coll11] ;; Instruments ;; - short name "isnA" [coll15] ;; - long name (from metadata - not from KMS) "ilnB" [coll11] ;; - long name (from KMS - not from metadata) "SMAP L-Band Radiometer" [coll24] ;; - technique "itechniqueB" [coll11] "itechniqueA" [coll15] ;; Sensors ;; - short name "ssnA" [coll15] ;; - long name "slnB" [coll11] ;; - technique "techniqueB" [coll11] "techniqueD" [coll15] "techniqueB techniqueC" [coll11] ;; Science keywords ;; - category "Cat1" [coll9] ;; - topic "Topic1" [coll9 coll10] ;; - term "Term1" [coll9 coll10] ;; - variable-levels "Level2-1" [coll9] "Level2-2" [coll9] "Level2-3" [coll9] ;; - detailed-variable "SUPER" [coll9] ;; Related URLs "earthdata" [coll25] "nsidc" [coll25 coll27] ;; Special characters are escaped before sending to Elastic "ABC~ZYX" [] "ABC~" [] "spo~nA" [coll11] "fo&nA" [coll11] "A.+&.+C" [] "S@PER" [coll10] ;; search by keywords using wildcard * "XY*" [coll2 coll13] "*aser" [coll21 coll5 coll7 coll9 coll14] "p*ce" [coll6] "NEA*REA*IME" [coll22] "nea*rea*ime" [coll22] "\"Quoted*" [coll23] ;; search by keywords using wildcard ? "XY?" [coll2 coll13] "?aser" [coll21 coll5 coll7 coll9 coll14] "p*ace" [coll6] "NEAR?REAL?TIME" [coll22] "near?real?time" [coll22])) (testing "Default boosts on fields" (are3 [params scores] (is (= (map #(/ % 2.0) scores) (map :score (:refs (search/find-refs :collection params))))) "short-name" {:keyword "SNFoobar"} [short-name-boost] "entry-id" {:keyword "ABC!XYZ_V001"} [entry-id-boost] "project short-name as keyword" {:keyword (:short-name (first pr1))} [project-boost] "project short-name as parameter" {:project (:short-name (first pr1))} [project-boost] "project long-name" {:keyword (:long-name (first pr1))} [project-boost] "platform short-name as keyword" {:keyword (:short-name p1)} [platform-boost] "platform short-name as parameter" {:platform (:short-name p1)} [platform-boost] "platform short-name as parameter with pattern" {:platform "*spoonA" "options[platform][pattern]" true} [platform-boost] "platform long-name (from metadata)" {:keyword (:long-name p1)} [platform-boost] "platform long-name (from KMS)" {:keyword "Soil Moisture Active and Passive Observatory"} [platform-boost] "instrument short-name as keyword" {:keyword (:short-name (first (:instruments p1)))} [instrument-boost] "instrument short-name as parameter" {:instrument (:short-name (first (:instruments p1)))} [instrument-boost] "instrument long-name (from metadata)" {:keyword (:long-name (first (:instruments p1)))} [instrument-boost] "instrument long-name (from KMS)" {:keyword "L-Band Radiometer"} [instrument-boost] ;; In UMM-C sensors are now instruments. All instruments (instruments + child instruments, ;; aka sensors) are indexed as both instruments and sensors until sensors search goes ;; away. Since they are instruments, there is no longer a sensor boost, but instrument ;; boost will be used. "sensor short-name as keyword" {:keyword (:short-name (first (:sensors (first (:instruments p1)))))} [instrument-boost] "sensor short-name as parameter" {:sensor (:short-name (first (:sensors (first (:instruments p1)))))} [instrument-boost] "sensor long-name" {:keyword (:long-name (first (:sensors (first (:instruments p1)))))} [instrument-boost] "temporal-keywords" {:keyword "tk1"} [(k2e/get-boost nil :temporal-keyword)] "spatial-keyword" {:keyword "in out"} [(k2e/get-boost nil :spatial-keyword)] "science-keywords as keyword" {:keyword (:category sk1)} [science-keywords-boost] "science-keywords category as parameter" {:science-keywords {:0 {:category (:category sk1)}}} [science-keywords-boost] "science-keywords topic as parameter" {:science-keywords {:0 {:topic (:topic sk1)}}} [science-keywords-boost science-keywords-boost] "science-keywords term as parameter" {:science-keywords {:0 {:term (:term sk1)}}} [science-keywords-boost science-keywords-boost] "science-keywords variable-level-1 as parameter" {:science-keywords {:0 {:variable-level-1 (:variable-level-1 sk1)}}} [science-keywords-boost] "science-keywords variable-level-2 as parameter" {:science-keywords {:0 {:variable-level-2 (:variable-level-2 sk1)}}} [science-keywords-boost] "science-keywords variable-level-3 as parameter" {:science-keywords {:0 {:variable-level-3 (:variable-level-3 sk1)}}} [science-keywords-boost] "science-keywords any as parameter" {:science-keywords {:0 {:any (:category sk1)}}} [science-keywords-boost] "2d coordinate system as keyword" {:keyword (:name tdcs2)} [two-d-boost] "2d coordinate system as parameter" {:two-d-coordinate-system-name (:name tdcs2)} [two-d-boost] "processing level id as keyword" {:keyword "PDQ123"} [processing-level-boost] "processing level id as parameter" {:processing-level-id "PDQ123"} [processing-level-boost] "data center as keyword" {:keyword (:org-name org)} [data-center-boost] "data center as parameter" {:data-center (:org-name org)} [data-center-boost] "archive center as parameter" {:archive-center (:org-name org)} [data-center-boost] "version-id" {:keyword "V001"} [(k2e/get-boost nil :version-id)] "entry-title" {:keyword "coll5"} [(k2e/get-boost nil :entry-title)] "provider-id" {:keyword "PROV1"} [provider-boost provider-boost provider-boost provider-boost])) (testing "Combine keyword and param boosts" ;; Check that the scores are very close to account for slight difference in ;; number coming from elastic. (are3 [params score] (is (< (Math/abs (double (- (/ score 2.0) (:score (first (:refs (search/find-refs :collection params))))))) 0.0000001)) "combine keyword, data center, and instrument" {:keyword "Proj-2" :data-center "Some&Place" :instrument "INST7"} (* project-boost data-center-boost instrument-boost) "instrument search and instrument keyword only results in one instrument boost" {:keyword "INST7" :instrument "INST7"} instrument-boost) (testing "Specified boosts on fields" (are3 [params scores] (is (= (map #(/ % 2.0) scores) (map :score (:refs (search/find-refs :collection params))))) "short-name" {:keyword "SNFoobar" :boosts {:short-name 2.0}} [2.0] "entry-id" {:keyword "ABC!XYZ_V001" :boosts {:entry-id 3.1}} [3.1] "project short-name" {:keyword (:short-name (first pr1)) :boosts {:project 3.0}} [3.0] "platform short-name" {:keyword (:short-name p1) :boosts {:platform 4.0}} [4.0] "instrument short-name" {:keyword (:short-name (first (:instruments p1))) :boosts {:instrument 5.0}} [5.0] ;; In UMM-C sensors are now instruments. All instruments (instruments + child instruments, ;; aka sensors) are indexed as both instruments and sensors until sensors search goes ;; away. Since they are instruments, there is no longer a sensor boost, but instrument ;; boost will be used. "sensor short-name" {:keyword (:short-name (first (:sensors (first (:instruments p1))))) :boosts {:instrument 6.0}} [6.0] "temporal-keywords" {:keyword "tk1" :boosts {:temporal-keyword 7.0}} [7.0] "spatial-keyword" {:keyword "in out" :boosts {:spatial-keyword 8.0}} [8.0] "science-keywords" {:keyword (:category sk1) :boosts {:science-keywords 9.0}} [9.0] "version-id" {:keyword "V001" :boosts {:version-id 10.0}} [10.0] "provider-id" {:keyword "PROV1" :boosts {:provider 10.0}} [10.0 10.0 10.0 10.0] "entry-title" {:keyword "coll5" :boosts {:entry-title 10.0}} [10.0] "mixed boosts" {:keyword "Mixed" :boosts {:short-name 10.0 :entry-title 11.0}} [11.0 10.0] "no defaults" {:keyword (:category sk1) :boosts {:include-defaults false}} [1.0] "matches all fields, do not include defaults" {:keyword "boost" :boosts {:short-name 5.0 :include-defaults false}} [5.0] "matches all fields, use defaults, but override short-name boost" {:keyword "boost" :boosts {:short-name 5.0 :include-defaults true}} [(* 5.0 entry-title-boost platform-boost science-keywords-boost)])) (testing "Setting boosts without keyword search is an error" (let [resp (search/find-refs :collection {:provider "PROV1" :page_size 5 :short_name "SNFoobar" :boosts {:short-name 2.0}}) {:keys [status errors]} resp] (is (= 400 status)) (is (= "Relevance boosting is only supported for keyword queries" (first errors))))) (testing "Boosting on invalid field" (let [resp (search/find-refs :collection {:provider "PROV1" :page_size 5 :keyword "Laser" :boosts {:foo 2.0}}) {:keys [status errors]} resp] (is (= 400 status)) (is (= "Cannot set relevance boost on field [foo]." (first errors))))) (testing "Boosting with non-numeric values is an error." (let [resp (search/find-refs :collection {:provider "PROV1" :page_size 5 :keyword "Laser" :boosts {:short-name "foo"}}) {:keys [status errors]} resp] (is (= 400 status)) (is (= "Relevance boost value [foo] for field [short_name] is not a number." (first errors))))) (testing "keyword number of keywords with wildcards exceeds the limit for the given max keyword string length." (let [resp (search/find-refs :collection {:provider "PROV1" :page_size 5 :keyword "000000000000000000000* 1* 2* 3* 4* 5* 6* 7* 8* 9* 10* 11* 12* 13* 14* 15* 16* 17* 18* 19* 20* 21* 22* 23* 24? 25* 26?" :boosts {:short-name 2.0}}) {:keys [status errors]} resp] (is (= 400 status)) (is (= "The CMR permits a maximum of 22 keywords with wildcards in a search, given the max length of the keyword being 22. Your query contains 27 keywords with wildcards" (first errors))))) (testing "keyword with too many wildcard is an error." (let [resp (search/find-refs :collection {:provider "PROV1" :page_size 5 :keyword "0* 1* 2* 3* 4* 5* 6* 7* 8* 9* 10* 11* 12* 13* 14* 15* 16* 17* 18* 19* 20* 21* 22* 23* 24* 25* 26* 27* 28* 29* 30?" :boosts {:short-name 2.0}}) {:keys [status errors]} resp] (is (= 400 status)) (is (= "Max number of keywords with wildcard allowed is 30" (first errors))))) (testing "sorted search" (are [params items] (let [refs (search/find-refs :collection params) matches? (d/refs-match-order? items refs)] (when-not matches? (println "Expected:" (map :entry-title items)) (println "Actual:" (map :name (:refs refs)))) matches?) {:keyword "Laser spoonA"} [coll9 coll14] {:keyword "La?er spoonA"} [coll9 coll14] {:keyword "L*er spo*A"} [coll9 coll14] {:keyword "L?s* s?o*A"} [coll9 coll14])) (testing "sorted search by keywords JSON query." (are [keyword-str items] (let [refs (search/find-refs-with-json-query :collection {} {:keyword keyword-str}) matches? (d/refs-match-order? items refs)] (when-not matches? (println "Expected:" (map :entry-title items)) (println "Actual:" (map :name (:refs refs)))) matches?) "Laser spoonA" [coll9 coll14])) (testing "sorted search by keywords with sort keys." (are [keyword-str sort-key items] (let [refs (search/find-refs :collection {:keyword keyword-str :sort-key sort-key}) matches? (d/refs-match-order? items refs)] (when-not matches? (println "Expected:" (map :entry-title items)) (println "Actual:" (map :name (:refs refs)))) matches?) "laser" "-entry-title" [coll7 coll5 coll21 coll14 coll9] "laser" "score" [coll21 coll5 coll7 coll9 coll14] "laser" "+score" [coll5 coll7 coll9 coll14 coll21] "laser" "-score" [coll21 coll5 coll7 coll9 coll14])) (testing "parameter search by keywords returns score" (let [refs (search/find-refs :collection {:keyword "Laser"})] (is (every? :score (:refs refs))))) (testing "JSON keywords search returns score" (let [refs (search/find-refs-with-json-query :collection {} {:keyword "Laser"})] (is (every? :score (:refs refs))))) (testing "search by multiple keywords returns an error." (let [resp (search/find-refs :collection {:provider "PROV1" :page_size 5 :keyword ["Laser" "spoon"]}) {:keys [status errors]} resp] (is (= 400 status)) (is (= "Parameter [keyword] must have a single value." (first errors))))) (testing "JSON negated keyword search does not return score" (let [refs (search/find-refs-with-json-query :collection {} {:not {:keyword "Laser"}})] (is (not-any? :score (:refs refs)))))))) ;; This test is separated out from the rest of the keyword search tests because we need to ;; ingest this UMM-SPEC collection but it contains some keyword values other tests are using. ;; This would break other tests when doing the keyword searches. (deftest search-by-more-keywords (let [coll1 (d/ingest "PROV1" (-> exp-conv/example-collection-record (assoc :AncillaryKeywords ["CMR2652AKW1" "CMR2652AKW2"]) (assoc :DOI (cm/map->DoiType {:DOI "doi" :Authority "auth"})) (assoc :DirectoryNames [(um/map->DirectoryNameType {:ShortName "CMR2654DNSN1" :LongName "CMR2654DNLN1"})]) (assoc :ISOTopicCategories ["environment" "health"]) (assoc :ShortName "CMR2652SN1") (assoc :EntryTitle "CMR2652ET1") (assoc :LocationKeywords [(um/map->LocationKeywordType {:Category "CONTINENT" :Type "ASIA" :Subregion1 "WESTERN ASIA" :Subregion2 "MIDDLE EAST" :Subregion3 "GAZA STRIP" :DetailedLocation "Testing Detailed Location"})])) {:format :umm-json :accept-format :json}) coll2 (d/ingest "PROV1" (-> exp-conv/example-collection-record (assoc :AncillaryKeywords ["CMR2652AKW3" "CMR2652AKW4"]) (assoc :DirectoryNames [(um/map->DirectoryNameType {:ShortName "CMR2654DNSN2" :LongName "CMR2654DNLN2"})]) (assoc :ISOTopicCategories ["biota"]) (assoc :ShortName "CMR2652SN2") (assoc :EntryTitle "CMR2652ET2")) {:format :umm-json :accept-format :json}) coll3 (d/ingest-concept-with-metadata-file "data/iso_mends/no_spatial_iso_collection.xml" {:provider-id "PROV1" :concept-type :collection :format-key :iso19115})] (index/wait-until-indexed) (testing "parameter searches" (are3 [keyword-str items] (let [parameter-refs (search/find-refs :collection {:keyword keyword-str})] (d/assert-refs-match items parameter-refs)) "testing parameter search by shortname keyword in collection whose xml file contains no SpatialExtent content" "NSIDC-0705" [coll3] "testing parameter search by existing ancillary keywords" "CMR2652AKW1" [coll1] "testing parameter search by existing DOI value" "dOI" [coll1] "testing parameter search by existing DirectoryNames keywords" "CMR2654DNSN1" [coll1] "testing parameter search by existing ancillary keywords" "CMR2652AKW4" [coll2] "testing parameter search by existing DirectoryNames keywords" "CMR2654DNLN2" [coll2] "testing parmaeter search by non-existing keywords" "CMR2652NOAKW" [] "testing iso-topic-category search - biota" "biota" [coll2] "testing iso-topic-category search - environment" "environment" [coll1] "testing iso-topic-category search - health" "health" [coll1] "testing detailed-location search - Testing Detailed Location" "Testing Detailed Location" [coll1])) (testing "Search collections by location keywords using JSON Query." (are3 [items search] (d/refs-match? items (search/find-refs-with-json-query :collection {} search)) "Testing detailed-location search" [coll1] {:location_keyword {:category "CONTINENT" :type "ASIA" :subregion_1 "WESTERN ASIA" :subregion_2 "MIDDLE EAST" :subregion_3 "GAZA STRIP" :detailed_location "Testing Detailed Location"}})) (testing "json query searchs" (are3 [keyword-str items] (let [json-refs (search/find-refs-with-json-query :collection {} {:keyword keyword-str})] (d/assert-refs-match items json-refs)) "testing json query search by shortname keyword in the collection whoes xml file contains no SpatialExtent content" "NSIDC-0705" [coll3] "testing json query search by existing ancillary keywords" "CMR2652AKW2" [coll1] "testing json query search by existing DirectoryNames keywords" "CMR2654DNLN1" [coll1] "testing json query search by existing ancillary keywords" "CMR2652AKW3" [coll2] "testing json query search by existing DirectoryNames keywords" "CMR2654DNSN2" [coll2] "testing json query search by non-existing keywords" "CMR2652NOAKW" [])))) ;; This tests that when searching by relevancy that if the score is the same short name ascending is used for ;; sorting the results and then if short name is the same version is used for sorting the results (deftest search-by-keywords-relevancy-sorting-includes-short-name-and-version (let [coll1 (d/ingest "PROV1" (dc/collection {:entry-title "MODIS/Terra Aerosol 5-Min L2 Swath 10km V5.1", :short-name "MOD04_L2", :version-id "5.1"})) coll2 (d/ingest "PROV1" (dc/collection {:entry-title "MODIS/Aqua Aerosol 5-Min L2 Swath 10km V5.1", :short-name "MYD04_L2", :version-id "5.1"})) coll3 (d/ingest "PROV1" (dc/collection {:entry-title "MODIS/Aqua Aerosol 5-Min L2 Swath 10km V006", :short-name "MYD04_L2", :version-id "6"})) coll4 (d/ingest "PROV1" (dc/collection {:entry-title "MODIS/Terra Aerosol 5-Min L2 Swath 10km V006", :short-name "MOD04_L2", :version-id "6"})) coll5 (d/ingest "PROV1" (dc/collection {:entry-title "MODIS/Aqua Total Precipitable Water Aerosol 5-Min L2 Swath 1km and 5km V5.1", :short-name "MYD05_L2", :version-id "5.1"})) coll6 (d/ingest "PROV1" (dc/collection {:entry-title "MODIS/Terra Total Precipitable Water Aerosol 5-Min L2 Swath 1km and 5km V5.1", :short-name "MOD05_L2", :version-id "5.1"})) coll7 (d/ingest "PROV1" (dc/collection {:entry-title "MODIS/Aqua Total Precipitable Water Aerosol 5-Min L2 Swath 1km and 5km V006", :short-name "MYD05_L2", :version-id "6"})) coll8 (d/ingest "PROV1" (dc/collection {:entry-title "MODIS/Terra Total Precipitable Water Aerosol 5-Min L2 Swath 1km and 5km V006", :short-name "MOD05_L2", :version-id "6"})) coll9 (d/ingest "PROV1" (dc/collection {:entry-title "MODIS Aerosol Other", :projects [(dc/project "MODIS" "ignored")] :platforms [(dc/platform {:short-name "MODIS"})] :short-name "Other", :version-id "1"}))] (index/wait-until-indexed) (let [refs (search/find-refs :collection {:keyword "modis aerosol"}) expected-order [coll9 ;; higher score ;; The scores of the rest of them are identical coll4 ;; MOD04_L2 6 coll1 ;; MOD04_L2 5.1 coll8 ;; MOD05_L2 6 coll6 ;; MOD05_L2 5.1 coll3 ;; MYD04_L2 6 coll2 ;; MYD04_L2 5.1 coll7 ;; MYD05_L2 6 coll5] ;; MYD05_L2 5.1 matched? (d/refs-match-order? expected-order refs)] (when-not matched? (println "Actual order: " (pr-str (map :id (:refs refs))))) (is matched?)))) (deftest search-by-keywords-with-special-chars ;; needed for special charatcter tests (let [coll-data [["coll00" "dummy && ||"] ["coll01" "begin!end"] ["coll02" "begin@end"] ["coll03" "begin#end"] ["coll04" "begin$end"] ["coll05" "begin%end"] ["coll06" "begin^end"] ["coll07" "begin&end"] ["coll08" "begin(end"] ["coll09" "begin)end"] ["coll10" "begin-end"] ["coll11" "begin=end"] ["coll12" "begin_end"] ["coll13" "begin+end"] ["coll14" "begin{end"] ["coll15" "begin}end"] ["coll16" "begin[end"] ["coll17" "begin]end"] ["coll18" "begin|end"] ["coll19" "begin\\end"] ["coll20" "begin;end"] ["coll21" "begin'end"] ["coll22" "begin.end"] ["coll23" "begin,end"] ["coll24" "begin/end"] ["coll25" "begin:end"] ["coll26" "begin\"end"] ["coll27" "begin<end"] ["coll28" "begin>end"] ["coll29" "begin?end"] ["coll30" "begin`end"] ["coll31" "begin~end"] ["coll32" "modis foobar"] ["coll33" "bleep blop blorp"] ["coll34" "abcdefghijklmnop"] ["coll35" "foo modis bar"] ["coll36" "akdi modis/terra dke"] ["coll37" "akdi modis-terra dke"] ["coll38" "Dataset with foobar"] ["coll39" "foo54"] ["coll40" "foo67"] ["coll41" "moding"] ["coll42" "outmoded"] ["coll43" "outmodising"] ["coll44" "out-modis-ed"] ["coll45" "carbon*oxygen"] ["coll46" "Dataset no withword"] ["coll47" "begin&&end"] ["coll48" "choco and taco"] ["coll49" "choco or taco"] ["coll50" "begin*end"]] colls (doall (for [[coll summary] coll-data] (d/ingest "PROV3" (dc/collection {:entry-title coll :summary summary}))))] (index/wait-until-indexed) (are [keyword-str indexes] (let [refs (search/find-refs :collection {:keyword keyword-str :page_size 51}) items (map (partial nth colls) indexes) matches? (d/refs-match? items refs)] (when-not matches? (println "Expected:" (map :entry-title items)) (println "Actual:" (map :name (:refs refs)))) matches?) "begin!end" [1] "begin\\end" [19] "begin<end" [27] "begin\\?end" [29] "begin~end" [31] "begin\\*end" [50] "begin" [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 47 50] "end" [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 47 50] "&&" [0] "||" [0] "AND" [48] "OR" [49])))
[ { "context": "e-query uri \"from hero with name = $name\" {:name \"Doom\"})\n details (get-in response [:hero :det", "end": 3263, "score": 0.9498031139373779, "start": 3259, "tag": "NAME", "value": "Doom" }, { "context": "-query uri \"from hero with name = $name\" {:name [\"Doom\"]})\n details (get-in response [:hero :de", "end": 3644, "score": 0.9997074604034424, "start": 3640, "tag": "NAME", "value": "Doom" }, { "context": "-query uri \"from hero with name = $name\" {:name [\"Doom\" \"Duke Nuken\"]})\n details (get-in respon", "end": 4036, "score": 0.9996563792228699, "start": 4032, "tag": "NAME", "value": "Doom" }, { "context": "uri \"from hero with name = $name\" {:name [\"Doom\" \"Duke Nuken\"]})\n details (get-in response [:hero :de", "end": 4049, "score": 0.9998618960380554, "start": 4039, "tag": "NAME", "value": "Duke Nuken" }, { "context": "(with-routes!\n {(route-request \"/hero\" {:name \"Dwayne \\\"The Rock\\\" Johnson\"}) (hero-route)}\n (let [r", "end": 13287, "score": 0.999516487121582, "start": 13281, "tag": "NAME", "value": "Dwayne" }, { "context": "tes!\n {(route-request \"/hero\" {:name \"Dwayne \\\"The Rock\\\" Johnson\"}) (hero-route)}\n (let [result (exec", "end": 13298, "score": 0.917460024356842, "start": 13290, "tag": "NAME", "value": "The Rock" }, { "context": "(route-request \"/hero\" {:name \"Dwayne \\\"The Rock\\\" Johnson\"}) (hero-route)}\n (let [result (execute-query ", "end": 13308, "score": 0.9822670221328735, "start": 13301, "tag": "NAME", "value": "Johnson" }, { "context": "e-query uri \"from hero with name = $name\" {:name \"Dwayne \\\"The Rock\\\" Johnson\"})]\n (is (= 200 (get-in", "end": 13406, "score": 0.999474823474884, "start": 13400, "tag": "NAME", "value": "Dwayne" }, { "context": "ri \"from hero with name = $name\" {:name \"Dwayne \\\"The Rock\\\" Johnson\"})]\n (is (= 200 (get-in result [:h", "end": 13417, "score": 0.9580295085906982, "start": 13409, "tag": "NAME", "value": "The Rock" }, { "context": "ero with name = $name\" {:name \"Dwayne \\\"The Rock\\\" Johnson\"})]\n (is (= 200 (get-in result [:hero :detai", "end": 13427, "score": 0.9931198358535767, "start": 13420, "tag": "NAME", "value": "Johnson" }, { "context": "(with-routes!\n {(route-request \"/hero\" {:name \"Bioman\"}) (hero-route)}\n (let [result (execute-query ", "end": 13582, "score": 0.998927116394043, "start": 13576, "tag": "NAME", "value": "Bioman" }, { "context": "e-query uri \"from hero with name = $name\" {:name \"Bioman\"} {:debugging true})]\n (is (= 200 (get-in re", "end": 13680, "score": 0.9993042945861816, "start": 13674, "tag": "NAME", "value": "Bioman" }, { "context": "-stub-body request) (json/generate-string {:name \"Jocker\"})))) (hero-route)}\n (let [result (execute-q", "end": 14503, "score": 0.9982597231864929, "start": 14497, "tag": "NAME", "value": "Jocker" }, { "context": "ecute-query uri \"to villain with id = 1, name = \\\"Jocker\\\"\")]\n (is (= 200 (get-in result [:villain ", "end": 14602, "score": 0.998177170753479, "start": 14596, "tag": "NAME", "value": "Jocker" }, { "context": "(with-routes!\n {(route-request \"/hero\" {:name \"Jiraiya\" :age \"45\"}) (hero-route)}\n (let [result (exec", "end": 14769, "score": 0.997914731502533, "start": 14762, "tag": "NAME", "value": "Jiraiya" }, { "context": "e-query uri \"from hero with $hero\" {:hero {:name \"Jiraiya\" :age 45}})]\n (is (= 200 (get-in result [:he", "end": 14878, "score": 0.9957036375999451, "start": 14871, "tag": "NAME", "value": "Jiraiya" }, { "context": "(with-routes!\n {(route-request \"/hero\" {:name \"Jiraiya\"}) (hero-route)\n (route-request \"/hero\" {:nam", "end": 15059, "score": 0.9958975315093994, "start": 15052, "tag": "NAME", "value": "Jiraiya" }, { "context": " (hero-route)\n (route-request \"/hero\" {:name \"Jaspion\"}) (hero-route)}\n (let [response (execute-quer", "end": 15119, "score": 0.9980592131614685, "start": 15112, "tag": "NAME", "value": "Jaspion" }, { "context": "-query uri \"from hero with $hero\" {:hero {:name [\"Jiraiya\" \"Jaspion\"]}})\n details (get-in response", "end": 15221, "score": 0.9952027797698975, "start": 15214, "tag": "NAME", "value": "Jiraiya" }, { "context": " \"from hero with $hero\" {:hero {:name [\"Jiraiya\" \"Jaspion\"]}})\n details (get-in response [:hero :d", "end": 15231, "score": 0.9964725971221924, "start": 15224, "tag": "NAME", "value": "Jaspion" }, { "context": "us])))\n (is (= {:hi \"I'm hero\", :sidekickId \"A20\" :villains [\"1\" \"2\"] :weapons [\"pen\" \"papel clip\"", "end": 16223, "score": 0.6059780120849609, "start": 16220, "tag": "USERNAME", "value": "A20" }, { "context": "UN\"}}]})}\n (route-request \"/sidekick\" {:id \"FIREGUN\"}) (sidekick-route)}\n (let [result (exe", "end": 20063, "score": 0.5356947779655457, "start": 20061, "tag": "NAME", "value": "FI" }, { "context": "\"}}]})}\n (route-request \"/sidekick\" {:id \"FIREGUN\"}) (sidekick-route)}\n (let [result (execute-", "end": 20068, "score": 0.785830020904541, "start": 20063, "tag": "USERNAME", "value": "REGUN" }, { "context": " \"/villain/1\" (route-response {:id \"1\" :name \"Lex\"})}\n (let [result (execute-query uri \"from her", "end": 20492, "score": 0.9978985786437988, "start": 20489, "tag": "NAME", "value": "Lex" }, { "context": "lain.id\")]\n (is (= {:villain {:id \"1\" :name \"Lex\"}} (get-in result [:heroes :result])))\n (is ", "end": 20690, "score": 0.9989801645278931, "start": 20687, "tag": "NAME", "value": "Lex" }, { "context": " \"/villain/1\" (route-response {:id \"1\" :name \"Lex\"})\n \"/villain/2\" (route-response {:id \"2\" :n", "end": 21007, "score": 0.9996174573898315, "start": 21004, "tag": "NAME", "value": "Lex" }, { "context": " \"/villain/2\" (route-response {:id \"2\" :name \"Zod\"})}\n (let [result (execute-query uri \"from her", "end": 21065, "score": 0.9939010143280029, "start": 21062, "tag": "NAME", "value": "Zod" }, { "context": "ns.id\")]\n (is (= {:villains [{:id \"1\" :name \"Lex\"} {:id \"2\" :name \"Zod\"}]} (get-in result [:heroes", "end": 21267, "score": 0.9996339082717896, "start": 21264, "tag": "NAME", "value": "Lex" }, { "context": "{:villains [{:id \"1\" :name \"Lex\"} {:id \"2\" :name \"Zod\"}]} (get-in result [:heroes :result])))\n (is", "end": 21289, "score": 0.9962109327316284, "start": 21286, "tag": "NAME", "value": "Zod" }, { "context": " \"/villain/1\" (route-response {:id \"1\" :name \"Lex\"})\n \"/villain/2\" (route-response {:id \"2\" :n", "end": 21619, "score": 0.9994859099388123, "start": 21616, "tag": "NAME", "value": "Lex" }, { "context": " \"/villain/2\" (route-response {:id \"2\" :name \"Zod\"})}\n (let [result (execute-query uri \"from her", "end": 21677, "score": 0.9860889911651611, "start": 21674, "tag": "NAME", "value": "Zod" }, { "context": "ns.id\")]\n (is (= {:villains [{:id \"1\" :name \"Lex\"} {:id \"2\" :name \"Zod\"}]} (get-in result [:heroes", "end": 21879, "score": 0.9996654987335205, "start": 21876, "tag": "NAME", "value": "Lex" }, { "context": "{:villains [{:id \"1\" :name \"Lex\"} {:id \"2\" :name \"Zod\"}]} (get-in result [:heroes :result])))\n (is", "end": 21901, "score": 0.9968920350074768, "start": 21898, "tag": "NAME", "value": "Zod" }, { "context": " \"/villain/1\" (route-response {:id \"1\" :name \"Lex\"})\n \"/villain/2\" (route-response {:id \"2\" :n", "end": 22303, "score": 0.9994359612464905, "start": 22300, "tag": "NAME", "value": "Lex" }, { "context": " \"/villain/2\" (route-response {:id \"2\" :name \"Zod\"})\n \"/villain/3\" (route-response {:id \"3\" :n", "end": 22361, "score": 0.6889621019363403, "start": 22358, "tag": "NAME", "value": "Zod" }, { "context": "]}]}])\n \"/villain/1\" (route-response {:name \"Lex\"})\n \"/villain/2\" {:status 500 :content-type ", "end": 28921, "score": 0.8244489431381226, "start": 28918, "tag": "NAME", "value": "Lex" }, { "context": "weapons\")]\n (is (= [{:villains [{:id {:name \"Lex\"} :weapons [{:error \"NOT_FOUND\"}]}\n ", "end": 29534, "score": 0.8917133808135986, "start": 29531, "tag": "NAME", "value": "Lex" } ]
test/integration/restql/restql_test.clj
MachadoLhes/restQL-core
2
(ns restql.restql-test (:require [clojure.test :refer :all] [restql.parser.core :as parser] [restql.core.api.restql :as restql] [byte-streams :as bs] [cheshire.core :as json] [stub-http.core :refer :all] [clojure.core.async :refer :all] [restql.test-util :refer [route-response route-request route-header]])) (defn get-stub-body [request] (val (first (:body request)))) (defn hero-route [] (route-response {:hi "I'm hero" :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]})) (defn hero-with-bag-route [] (route-response {:hi "I'm hero" :bag {:capacity 10}})) (defn sidekick-route [] (route-response {:hi "I'm sidekick"})) (defn product-route [id] (route-response {:product (str id)})) (defn heroes-route [] {:status 200 :content-type "application/json" :body (json/generate-string [{:hi "I'm hero" :villains ["1" "2"]} {:hi "I'm hero" :villains ["3" "4"]}])}) (defn villain-route [id] (route-response {:hi "I'm villain" :id (str id)})) (defn execute-query ([base-url query] (execute-query base-url query {} {})) ([base-url query params] (execute-query base-url query params {})) ([base-url query params options] (restql/execute-query :mappings {:hero (str base-url "/hero") :heroes (str base-url "/heroes") :weapons (str base-url "/weapons") :sidekick (str base-url "/sidekick") :villain (str base-url "/villain/:id") :weapon (str base-url "/weapon/:id") :product (str base-url "/product/:id") :product-price (str base-url "/price/:productId") :product-description (str base-url "/description/:productId") :fail "http://not.a.working.endpoint"} :query query :params params :options options))) (deftest simple-request (with-routes! {"/hero" (hero-route)} (let [result (execute-query uri "from hero")] (is (= 200 (get-in result [:hero :details :status]))) (is (= {:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]} (get-in result [:hero :result]))) (is (= "I'm hero" (get-in result [:hero :result :hi])))))) (deftest multiplexed-request (with-routes! {"/hero" (route-response {:villains ["1" "2"]}) "/villain/1" (villain-route "1") "/villain/2" (villain-route "2")} (let [result (execute-query uri "from hero\n from villain with id = hero.villains")] (is (= {:villains ["1" "2"]} (get-in result [:hero :result]))) (is (= [{:hi "I'm villain", :id "1"} {:hi "I'm villain", :id "2"}] (get-in result [:villain :result]))))) ; Test simple case with: single, list with one, list with two (with-routes! {"/hero" (hero-route)} (let [response (execute-query uri "from hero with name = $name" {:name "Doom"}) details (get-in response [:hero :details]) result (get-in response [:hero :result])] (is (= 200 (:status details))) (is (= {:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]} result)))) (with-routes! {"/hero" (hero-route)} (let [response (execute-query uri "from hero with name = $name" {:name ["Doom"]}) details (get-in response [:hero :details]) result (get-in response [:hero :result])] (is (= 200 (:status (first details)))) (is (= [{:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]}] result)))) (with-routes! {"/hero" (hero-route)} (let [response (execute-query uri "from hero with name = $name" {:name ["Doom" "Duke Nuken"]}) details (get-in response [:hero :details]) result (get-in response [:hero :result])] (is (= 200 (:status (first details)))) (is (= 200 (:status (second details)))) (is (= [{:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]} {:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]}] result)))) ;; Test simple case with list: single, list with one, list with two (with-routes! {"/hero" (route-response {:villains ["1" "2"]}) "/villain/1" (villain-route "1") "/villain/2" (villain-route "2")} (let [result (execute-query uri "from hero with id =1\nfrom villain with id = hero.villains")] (is (= 200 (:status (get-in result [:hero :details])))) (is (= 200 (:status (first (get-in result [:villain :details]))))) (is (= 200 (:status (second (get-in result [:villain :details]))))) (is (= {:villains ["1" "2"]} (get-in result [:hero :result]))) (is (= [{:hi "I'm villain", :id "1"} {:hi "I'm villain", :id "2"}] (get-in result [:villain :result]))))) (with-routes! {"/hero" (route-response {:villains ["1" "2"]}) "/villain/1" (villain-route "1") "/villain/2" (villain-route "2")} (let [result (execute-query uri "from hero with id =[1]\nfrom villain with id = hero.villains")] (is (= 200 (:status (first (get-in result [:hero :details]))))) (is (= 200 (:status (first (first (get-in result [:villain :details])))))) (is (= 200 (:status (second (first (get-in result [:villain :details])))))) (is (= [{:villains ["1" "2"]}] (get-in result [:hero :result]))) (is (= [[{:hi "I'm villain", :id "1"} {:hi "I'm villain", :id "2"}]] (get-in result [:villain :result]))))) (with-routes! {"/hero" (route-response {:villains ["1" "2"]}) "/villain/1" (villain-route "1") "/villain/2" (villain-route "2")} (let [result (execute-query uri "from hero with id =[1,2]\nfrom villain with id = hero.villains")] (is (= 200 (:status (first (get-in result [:hero :details]))))) (is (= 200 (:status (second (get-in result [:hero :details]))))) (is (= 200 (:status (first (first (get-in result [:villain :details])))))) (is (= 200 (:status (second (first (get-in result [:villain :details])))))) (is (= 200 (:status (first (second (get-in result [:villain :details])))))) (is (= 200 (:status (second (second (get-in result [:villain :details])))))) (is (= [{:villains ["1" "2"]} {:villains ["1" "2"]}] (get-in result [:hero :result]))) (is (= [[{:hi "I'm villain", :id "1"} {:hi "I'm villain", :id "2"}] [{:hi "I'm villain", :id "1"} {:hi "I'm villain", :id "2"}]] (get-in result [:villain :result]))))) (with-routes! {"/heroes" (route-response [{:villains ["1" "2"]} {:villains ["3" "4"]}]) "/villain/1" (villain-route "1") "/villain/2" (villain-route "2") "/villain/3" (villain-route "3") "/villain/4" (villain-route "4")} (let [result (execute-query uri "from heroes\nfrom villain with id = heroes.villains")] (is (= 200 (get-in result [:heroes :details :status]))) (is (= 200 (:status (first (first (get-in result [:villain :details])))))) (is (= 200 (:status (second (first (get-in result [:villain :details])))))) (is (= 200 (:status (first (second (get-in result [:villain :details])))))) (is (= 200 (:status (second (second (get-in result [:villain :details])))))) (is (= [{:villains ["1" "2"]} {:villains ["3" "4"]}] (get-in result [:heroes :result]))) (is (= [[{:hi "I'm villain", :id "1"} {:hi "I'm villain", :id "2"}] [{:hi "I'm villain", :id "3"} {:hi "I'm villain", :id "4"}]] (get-in result [:villain :result]))))) (with-routes! {"/hero" (route-response {:villains "1"}) "/villain/1" (route-response {:weapons ["dagger" "sword"]}) "/weapon/dagger" (route-response {:name "dagger"}) "/weapon/sword" (route-response {:name "sword"})} (let [result (execute-query uri "from hero\n from villain with id = hero.villains\n from weapon with id = villain.weapons")] (is (= {:villains "1"} (get-in result [:hero :result]))) (is (= {:weapons ["dagger" "sword"]} (get-in result [:villain :result]))) (is (= [{:name "dagger"} {:name "sword"}] (get-in result [:weapon :result]))))) (with-routes! {"/hero" (route-response {:villains ["1"]}) "/villain/1" (route-response {:weapons ["dagger" "sword"]}) "/weapon/dagger" (route-response {:name "dagger"}) "/weapon/sword" (route-response {:name "sword"})} (let [result (execute-query uri "from hero\n from villain with id = hero.villains\n from weapon with id = villain.weapons")] (is (= {:villains ["1"]} (get-in result [:hero :result]))) (is (= [{:weapons ["dagger" "sword"]}] (get-in result [:villain :result]))) (is (= [[{:name "dagger"} {:name "sword"}]] (get-in result [:weapon :result]))))) (testing "With map->list->simple_value" (with-routes! {"/hero" (route-response {:villains [{:id "1" :weapon "DAGGER"}]}) "/villain/1" (route-response {:id "1"}) "/weapon/DAGGER" (route-response {:id "DAGGER"})} (let [result (execute-query uri "from hero \n from villain with id = hero.villains.id \n from weapon with id = hero.villains.weapon")] (is (= {:villains [{:id "1" :weapon "DAGGER"}]} (get-in result [:hero :result]))) (is (= [{:id "1"}] (get-in result [:villain :result]))) (is (= [{:id "DAGGER"}] (get-in result [:weapon :result])))))) (testing "With map->list->complex_value" (with-routes! {"/hero" (route-response {:villains [{:v {:id "1"}}]}) "/villain/{\"id\":\"1\"}" (route-response {:id "1"})} (let [result (execute-query uri "from hero \n from villain with id = hero.villains.v")] (is (= {:villains [{:v {:id "1"}}]} (get-in result [:hero :result]))) (is (= [{:id "1"}] (get-in result [:villain :result])))))) (testing "With list->map->list->simple_value and list->map->list->complex_value" (with-routes! {"/heroes" (route-response [{:villains [{:id "1" :weapons ["DAGGER"]}]}]) "/villain/1" (route-response {:id "1"}) "/weapon/DAGGER" (route-response {:id "DAGGER"})} (let [result (execute-query uri "from heroes\n from villain with id = heroes.villains.id\n from weapon with id = heroes.villains.weapons")] (is (= [{:villains [{:id "1" :weapons ["DAGGER"]}]}] (get-in result [:heroes :result]))) (is (= [[{:id "1"}]] (get-in result [:villain :result]))) (is (= [[[{:id "DAGGER"}]]] (get-in result [:weapon :result]))))))) (deftest request-with-ignore-errors-should-have-ignore-errors-in-metadata (with-routes! {"/hero" (assoc (hero-route) :status 500)} (let [result (execute-query uri "from hero ignore-errors")] (is (= 500 (get-in result [:hero :details :status]))) (is (= {:ignore-errors "ignore"} (get-in result [:hero :details :metadata])))))) (deftest error-request-with-ignore-errors-shouldnt-throw-exception (with-routes! {"/hero" (assoc (hero-route) :status 500)} (let [result (execute-query uri "from hero ignore-errors")] (is (= 500 (get-in result [:hero :details :status]))) (is (= {:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]} (get-in result [:hero :result])))))) (deftest request-with-encoder (with-routes! {(route-request "/hero" {:bag {:capacity 10}}) (hero-route)} (let [result (execute-query uri "from hero with bag = {capacity: 10} -> json")] (is (= 200 (get-in result [:hero :details :status]))) (is (= {:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]} (get-in result [:hero :result]))))) (with-routes! {(route-request "/hero" {:bag "[10,20]"}) (hero-route)} (let [result (execute-query uri "from hero with bag = [10, 20] -> flatten -> json")] (is (= 200 (get-in result [:hero :details :status]))) (is (= {:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]} (get-in result [:hero :result])))))) (deftest request-with-encoder-2 (with-routes! {"/hero" (hero-with-bag-route) (route-request "/sidekick" {:bag {:capacity 10}}) (sidekick-route)} (let [result (execute-query uri "from hero \n from sidekick with bag = hero.bag -> json")] (is (= 200 (get-in result [:hero :details :status]))) (is (= {:hi "I'm hero", :bag {:capacity 10}} (get-in result [:hero :result]))) (is (= 200 (get-in result [:sidekick :details :status]))) (is (= {:hi "I'm sidekick"} (get-in result [:sidekick :result])))))) (deftest request-with-quoted-param (with-routes! {(route-request "/hero" {:name "Dwayne \"The Rock\" Johnson"}) (hero-route)} (let [result (execute-query uri "from hero with name = $name" {:name "Dwayne \"The Rock\" Johnson"})] (is (= 200 (get-in result [:hero :details :status])))))) (deftest request-with-debug (with-routes! {(route-request "/hero" {:name "Bioman"}) (hero-route)} (let [result (execute-query uri "from hero with name = $name" {:name "Bioman"} {:debugging true})] (is (= 200 (get-in result [:hero :details :status])) (contains? (get-in result [:hero :details]) :debug))))) (deftest execute-query-post (testing "Execute post with simple body" (with-routes! {(fn [request] (and (= (:path request) "/hero") (= (:method request) "POST") (= (get-stub-body request) (json/generate-string {:id 1})))) (hero-route)} (let [result (execute-query uri "to hero with id = 1")] (is (= 200 (get-in result [:hero :details :status])))))) (testing "Execute post with simple body and path var" (with-routes! {(fn [request] (and (= (:path request) "/villain/1") (= (:method request) "POST") (= (get-stub-body request) (json/generate-string {:name "Jocker"})))) (hero-route)} (let [result (execute-query uri "to villain with id = 1, name = \"Jocker\"")] (is (= 200 (get-in result [:villain :details :status]))))))) (deftest request-with-param-map (with-routes! {(route-request "/hero" {:name "Jiraiya" :age "45"}) (hero-route)} (let [result (execute-query uri "from hero with $hero" {:hero {:name "Jiraiya" :age 45}})] (is (= 200 (get-in result [:hero :details :status])))))) (deftest request-with-multiplexed-param-map (with-routes! {(route-request "/hero" {:name "Jiraiya"}) (hero-route) (route-request "/hero" {:name "Jaspion"}) (hero-route)} (let [response (execute-query uri "from hero with $hero" {:hero {:name ["Jiraiya" "Jaspion"]}}) details (get-in response [:hero :details]) result (get-in response [:hero :result])] (is (= 200 (:status (first details)))) (is (= 200 (:status (second details)))) (is (= [{:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]} {:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]}] result))))) (deftest timeout-request-should-return-408 (with-routes! {"/hero" (assoc (hero-route) :delay 500)} (let [result (execute-query uri "from hero timeout 100")] (is (= 408 (get-in result [:hero :details :status]))) (is (= {:message "RequestTimeoutException"} (get-in result [:hero :result])))))) (deftest chained-call (with-routes! {"/hero" (hero-route) "/sidekick" (sidekick-route)} (let [result (execute-query uri "from hero\nfrom sidekick")] (is (= 200 (get-in result [:hero :details :status]))) (is (= {:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]} (get-in result [:hero :result]))) (is (= 200 (get-in result [:sidekick :details :status]))) (is (= {:hi "I'm sidekick"} (get-in result [:sidekick :result])))))) (deftest with-params (with-routes! {"/product/1234" (product-route 1234)} (let [result (execute-query uri "from product with id = $id" {:id "1234"})] (is (= 200 (get-in result [:product :details :status]))) (is (= {:product "1234"} (get-in result [:product :result])))))) (deftest failing-request-debug-mode (let [uri "http://not.a.working.endpoint" result (execute-query uri "from fail" {} {:debugging true})] (is (= 0 (get-in result [:fail :details :status]))) (is (= "http://not.a.working.endpoint" (get-in result [:fail :details :debug :url]))) (is (= 5000 (get-in result [:fail :details :debug :timeout]))))) (deftest shouldnt-throw-exeption-if-chainned-resource-timeout-and-ignore-error (with-routes! {"/hero" (hero-route)} {"/sideck" (assoc (sidekick-route) :delay 200)} (let [result (execute-query uri "from hero\nfrom sidekick timeout 100 with id = hero.sidekickId ignore-errors")] (is (= 200 (get-in result [:hero :details :status]))) (is (= {:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]} (get-in result [:hero :result]))) (is (= 408 (get-in result [:sidekick :details :status]))) (is (not (nil? (get-in result [:sidekick :result :message]))))))) (deftest request-with-overlapping-headers (testing "Query without query headers" (with-routes! {(route-header "/hero" {"test" "test"}) (hero-route)} (let [result (execute-query uri "from hero" {} {:forward-headers {"restql-query-control" "ad-hoc", "test" "test", "accept" "*/*"}})] (is (= 200 (get-in result [:hero :details :status])))))) (testing "Replacing request headers with query headers" (with-routes! {(route-header "/hero" {"test" "diff"}) (hero-route)} (let [result (execute-query uri "from hero \nheaders Test = \"diff\"" {} {:forward-headers {"restql-query-control" "ad-hoc", "test" "test", "accept" "*/*"}})] (is (= 200 (get-in result [:hero :details :status])))))) (testing "One request with fowarded-headers, one request with query headers" (with-routes! {(route-header "/hero" {"test" "test"}) (hero-route) (route-header "/sidekick" {"test" "diff"}) (sidekick-route)} (let [result (execute-query uri "from hero \nfrom sidekick\nheaders Test = \"diff\"" {} {:forward-headers {"restql-query-control" "ad-hoc", "test" "test", "accept" "*/*"}})] (is (= 200 (get-in result [:hero :details :status])))))) ) (deftest request-with-flatten (testing "Flatten single value" (with-routes! {"/hero" (hero-route) (route-request "/sidekick" {:id "I'm hero"}) (sidekick-route)} (let [result (execute-query uri "from hero \n from sidekick with id = hero.hi -> flatten")] (is (= 200 (get-in result [:hero :details :status]))) (is (= 200 (get-in result [:sidekick :details :status])))))) (testing "Flatten list value" (with-routes! {"/hero" (hero-route) (route-request "/sidekick" {:id "2"}) (sidekick-route)} (let [result (execute-query uri "from hero \n from sidekick with id = hero.villains -> flatten")] (is (= 200 (get-in result [:hero :details :status]))) (is (= 200 (get-in result [:sidekick :details :status])))))) (testing "Flatten path list value" (with-routes! {"/hero" {:status 200 :body (json/generate-string {:villains [{:id "1" :weapon {:name "FINGGER"}} {:id "2" :weapon {:name "FIREGUN"}}]})} (route-request "/sidekick" {:id "FIREGUN"}) (sidekick-route)} (let [result (execute-query uri "from hero \n from sidekick with id = hero.villains.weapon.name -> flatten")] (is (= 200 (get-in result [:hero :details :status]))) (is (= 200 (get-in result [:sidekick :details :status]))))))) (deftest request-with-in (with-routes! {"/heroes" (route-response {:villain {:id "1"}}) "/villain/1" (route-response {:id "1" :name "Lex"})} (let [result (execute-query uri "from heroes\n from villain in heroes.villain with id = heroes.villain.id")] (is (= {:villain {:id "1" :name "Lex"}} (get-in result [:heroes :result]))) (is (nil? (get-in result [:villain :result]))) (is (get-in result [:heroes :details])) (is (get-in result [:villain :details])))) (with-routes! {"/heroes" (route-response {:villains ["1" "2"]}) "/villain/1" (route-response {:id "1" :name "Lex"}) "/villain/2" (route-response {:id "2" :name "Zod"})} (let [result (execute-query uri "from heroes\n from villain in heroes.villains with id = heroes.villains.id")] (is (= {:villains [{:id "1" :name "Lex"} {:id "2" :name "Zod"}]} (get-in result [:heroes :result]))) (is (nil? (get-in result [:villain :result]))) (is (get-in result [:heroes :details])) (is (get-in result [:villain :details])))) (with-routes! {"/heroes" (route-response {:villains [{:id "1"} {:id "2"}]}) "/villain/1" (route-response {:id "1" :name "Lex"}) "/villain/2" (route-response {:id "2" :name "Zod"})} (let [result (execute-query uri "from heroes\n from villain in heroes.villains with id = heroes.villains.id")] (is (= {:villains [{:id "1" :name "Lex"} {:id "2" :name "Zod"}]} (get-in result [:heroes :result]))) (is (nil? (get-in result [:villain :result]))) (is (get-in result [:heroes :details])) (is (get-in result [:villain :details])))) (with-routes! {"/heroes" (route-response [{:villains [{:id "1"} {:id "2"}]} {:villains [{:id "3"} {:id "4"}]}]) "/villain/1" (route-response {:id "1" :name "Lex"}) "/villain/2" (route-response {:id "2" :name "Zod"}) "/villain/3" (route-response {:id "3" :name "Elektra"}) "/villain/4" (route-response {:id "4" :name "Dracula"})} (let [result (execute-query uri "from heroes\n from villain in heroes.villains with id = heroes.villains.id")] (is (= [{:villains [{:id "1" :name "Lex"} {:id "2" :name "Zod"}]} {:villains [{:id "3" :name "Elektra"} {:id "4" :name "Dracula"}]}] (get-in result [:heroes :result]))) (is (nil? (get-in result [:villain :result]))) (is (get-in result [:heroes :details])) (is (get-in result [:villain :details])))) (with-routes! {"/heroes" (route-response [{:villains [{:id "1" :weapons ["DAGGER"]} {:id "2" :weapons ["GUN"]}]} {:villains [{:id "3" :weapons ["SWORD"]} {:id "4" :weapons ["SHOTGUN"]}]}]) "/villain/1" (route-response {:name "Lex"}) "/villain/2" (route-response {:name "Zod"}) "/villain/3" (route-response {:name "Elektra"}) "/villain/4" (route-response {:name "Dracula"}) "/weapon/DAGGER" (route-response {:id "DAGGER"}) "/weapon/GUN" (route-response {:id "GUN"}) "/weapon/SWORD" (route-response {:id "SWORD"}) "/weapon/SHOTGUN" (route-response {:id "SHOTGUN"})} (let [result (execute-query uri "from heroes\n from villain in heroes.villains.id with id = heroes.villains.id\n from weapon in heroes.villains.weapons with id = heroes.villains.weapons")] (is (= [{:villains [{:id {:name "Lex"} :weapons [{:id "DAGGER"}]} {:id {:name "Zod"} :weapons [{:id "GUN"}]}]} {:villains [{:id {:name "Elektra"} :weapons [{:id "SWORD"}]} {:id {:name "Dracula"} :weapons [{:id "SHOTGUN"}]}]}] (get-in result [:heroes :result]))) (is (nil? (get-in result [:villain :result]))) (is (nil? (get-in result [:weapon :result]))) (is (get-in result [:heroes :details])) (is (get-in result [:villain :details])) (is (get-in result [:weapon :details])))) (with-routes! {"/heroes" (route-response [{:villains [{:id "1"}]}]) "/villain/1" (route-response {:name "1" :weapons ["DAGGER"]}) "/villain/2" (route-response {:name "2" :weapons ["GUN"]}) "/villain/3" (route-response {:name "3" :weapons ["SHOTGUN"]}) "/villain/4" (route-response {:name "4" :weapons ["SWORD"]}) "/weapon/DAGGER" (route-response {:id "DAGGER"}) "/weapon/GUN" (route-response {:id "GUN"}) "/weapon/SHOTGUN" (route-response {:id "SHOTGUN"}) "/weapon/SWORD" (route-response {:id "SWORD"})} (let [result (execute-query uri "from heroes\n from villain with id = [1,2,3,4]\n from weapon in villain.weapons with id = villain.weapons")] (is (= [{:villains [{:id "1"}]}] (get-in result [:heroes :result]))) (is (= [{:name "1", :weapons [{:id "DAGGER"}]} {:name "2", :weapons [{:id "GUN"}]} {:name "3", :weapons [{:id "SHOTGUN"}]} {:name "4", :weapons [{:id "SWORD"}]}] (get-in result [:villain :result]))) (is (nil? (get-in result [:weapon :result]))) (is (get-in result [:heroes :details])) (is (get-in result [:villain :details])) (is (get-in result [:weapon :details])))) (with-routes! {"/heroes" (route-response [{:villains [{:id "1"} {:id "2"}]} {:villains [{:id "3"} {:id "4"}]}]) "/villain/1" (route-response {:name "1" :weapons ["DAGGER"]}) "/villain/2" (route-response {:name "2" :weapons ["GUN"]}) "/villain/3" (route-response {:name "3" :weapons ["SHOTGUN"]}) "/villain/4" (route-response {:name "4" :weapons ["SWORD"]}) "/weapon/DAGGER" (route-response {:id "DAGGER"}) "/weapon/GUN" (route-response {:id "GUN"}) "/weapon/SHOTGUN" (route-response {:id "SHOTGUN"}) "/weapon/SWORD" (route-response {:id "SWORD"})} (let [result (execute-query uri "from heroes\n from villain with id = heroes.villains.id\n from weapon in villain.weapons with id = villain.weapons")] (is (= [{:villains [{:id "1"} {:id "2"}]} {:villains [{:id "3"} {:id "4"}]}] (get-in result [:heroes :result]))) (is (= [[{:name "1", :weapons [{:id "DAGGER"}]} {:name "2", :weapons [{:id "GUN"}]}] [{:name "3", :weapons [{:id "SHOTGUN"}]} {:name "4", :weapons [{:id "SWORD"}]}]] (get-in result [:villain :result]))) (is (nil? (get-in result [:weapon :result]))) (is (get-in result [:heroes :details])) (is (get-in result [:villain :details])) (is (get-in result [:weapon :details])))) (with-routes! {"/heroes" (route-response [{:villains [{:id "1"} {:id "2"}]} {:villains [{:id "3"} {:id "4"}]}]) "/villain/1" (route-response {:name "1" :weapons ["DAGGER"]}) "/villain/2" (route-response {:name "2" :weapons ["GUN"]}) "/villain/3" (route-response {:name "3" :weapons ["SHOTGUN"]}) "/villain/4" (route-response {:name "4" :weapons ["SWORD"]}) "/weapon/DAGGER" (route-response {:id "DAGGER"}) "/weapon/GUN" (route-response {:id "GUN"}) "/weapon/SHOTGUN" (route-response {:id "SHOTGUN"}) "/weapon/SWORD" (route-response {:id "SWORD"})} (let [result (execute-query uri "from heroes\n from villain in heroes.villains with id = heroes.villains.id\n from weapon in heroes.villains.weapons with id = villain.weapons")] (is (= [{:villains [{:name "1", :weapons [{:id "DAGGER"}]} {:name "2", :weapons [{:id "GUN"}]}]} {:villains [{:name "3", :weapons [{:id "SHOTGUN"}]} {:name "4", :weapons [{:id "SWORD"}]}]}] (get-in result [:heroes :result]))) (is (nil? (get-in result [:villain :result]))) (is (nil? (get-in result [:weapon :result]))) (is (get-in result [:heroes :details])) (is (get-in result [:villain :details])) (is (get-in result [:weapon :details])))) (with-routes! {"/heroes" (route-response [{:villains [{:id "1" :weapons ["DAGGER"]} {:id "2" :weapons ["GUN"]}]}]) "/villain/1" (route-response {:name "Lex"}) "/villain/2" {:status 500 :content-type "application/json" :body (json/generate-string {:error "UNEXPECTED_ERROR"})} "/weapon/GUN" (route-response {:id "GUN"}) "/weapon/DAGGER" {:status 404 :content-type "application/json" :body (json/generate-string {:error "NOT_FOUND"})}} (let [result (execute-query uri "from heroes\n from villain in heroes.villains.id with id = heroes.villains.id\n from weapon in heroes.villains.weapons with id = heroes.villains.weapons")] (is (= [{:villains [{:id {:name "Lex"} :weapons [{:error "NOT_FOUND"}]} {:id {:error "UNEXPECTED_ERROR"} :weapons [{:id "GUN"}]}]}] (get-in result [:heroes :result]))) (is (nil? (get-in result [:villain :result]))) (is (nil? (get-in result [:weapon :result]))) (is (get-in result [:heroes :details])) (is (get-in result [:villain :details])) (is (get-in result [:weapon :details])))) (with-routes! {"/heroes" (route-response [{:villains [{:id "1"} {:id "2"}]} {:villains [{:id "3"} {:id "4"}]}]) "/weapon/1" (route-response {:id "DAGGER"}) "/weapon/2" (route-response {:id "GUN"}) "/weapon/3" (route-response {:id "SHOTGUN"}) "/weapon/4" (route-response {:id "SWORD"})} (let [result (execute-query uri "from heroes\n from weapon in heroes.villains.weapons with id = heroes.villains.id")] (is (= [{:villains [{:id "1", :weapons {:id "DAGGER"}} {:id "2", :weapons {:id "GUN"}}]} {:villains [{:id "3", :weapons {:id "SHOTGUN"}} {:id "4", :weapons {:id "SWORD"}}]}] (get-in result [:heroes :result]))) (is (nil? (get-in result [:weapon :result]))) (is (get-in result [:heroes :details])) (is (get-in result [:weapon :details]))))) (deftest with-list-param (testing "List with single value" (with-routes! {(route-request "/hero" {:id "1"}) (route-response {:villains []})} (let [result (execute-query uri "from hero with id = [\"1\"]")] (is (= 200 (:status (first (get-in result [:hero :details]))))) (is (= [{:villains []}] (get-in result [:hero :result])))))) (testing "List with multiple value" (with-routes! {(route-request "/hero" {:id "1"}) (route-response {:villains ["a"]}) (route-request "/hero" {:id "2"}) (route-response {:villains ["b"]})} (let [result (execute-query uri "from hero with id = [\"1\", \"2\"]")] (is (= 200 (:status (first (get-in result [:hero :details]))))) (is (= 200 (:status (second (get-in result [:hero :details]))))) (is (= [{:villains ["a"]} {:villains ["b"]}] (get-in result [:hero :result])))))) (testing "List with single map value" (with-routes! {(route-request "/hero" {:id {:num "1"}}) (route-response {:villains []})} (let [result (execute-query uri "from hero with id = [{num: \"1\"}]")] (is (= 200 (:status (first (get-in result [:hero :details]))))) (is (= [{:villains []}] (get-in result [:hero :result])))))) (testing "List with multiple map value" (with-routes! {(route-request "/hero" {:id {:num "1"}}) (route-response {:villains ["a"]}) (route-request "/hero" {:id {:num "2"}}) (route-response {:villains ["b"]})} (let [result (execute-query uri "from hero with id = [{num: \"1\"},{num: \"2\"}]")] (is (= 200 (:status (first (get-in result [:hero :details]))))) (is (= 200 (:status (second (get-in result [:hero :details]))))) (is (= [{:villains ["a"]} {:villains ["b"]}] (get-in result [:hero :result])))))) (testing "List flatten multiple value" (with-routes! {(route-request "/hero" {:id "2"}) (route-response {:villains ["b"]})} (let [result (execute-query uri "from hero with id = [\"1\", \"2\"] -> flatten")] (is (= 200 (:status (get-in result [:hero :details])))) (is (= {:villains ["b"]} (get-in result [:hero :result])))))) (testing "Map with multiple flatten map value" (with-routes! {(route-request "/hero" {:id {:num "2"}}) (route-response {:villains ["b"]})} (let [result (execute-query uri "from hero with id = [{num: \"1\"},{num: \"2\"}] -> flatten")] (is (= 200 (:status (get-in result [:hero :details])))) (is (= {:villains ["b"]} (get-in result [:hero :result]))))))) (deftest request-with-nested-multiplex-and-flatten (testing "Nested map multiplexed" (with-routes! {(route-request "/weapons") (route-response {:swords [{:name "1"} {:name "2"}] :types {:typeId "8"} :source "MAGICAL"}) (route-request "/sidekick" {:weapon {:name "1" :typeId "8" :invisible false} :source "MAGICAL"}) (route-response {:ok "Yeap!"}) (route-request "/sidekick" {:weapon {:name "2" :typeId "8" :invisible false} :source "MAGICAL"}) (route-response {:ok "Yeah!"})} (let [result (execute-query uri "from weapons hidden\n from sidekick\n with\n source = weapons.source\n weapon = {\n name: weapons.swords.name,\n typeId: weapons.types.typeId,\n invisible: false\n }")] (is (= {:ok "Yeap!"} (first (get-in result [:sidekick :result])))) (is (= {:ok "Yeah!"} (second (get-in result [:sidekick :result]))))))) (testing "Nested map multiplexed with value flattened" (with-routes! {(route-request "/weapons") (route-response {:swords [{:name "1"} {:name "2"}] :types [{:typeId "7"} {:typeId "8"} {:typeId "9"}] :source "MAGICAL"}) (route-request "/sidekick" {:weapon {:name ["1","2"] :typeId "7" :invisible false} :source "MAGICAL"}) (route-response {:ok "Yeap"}) (route-request "/sidekick" {:weapon {:name ["1","2"] :typeId "8" :invisible false} :source "MAGICAL"}) (route-response {:ok "Yeap"}) (route-request "/sidekick" {:weapon {:name ["1","2"] :typeId "9" :invisible false} :source "MAGICAL"}) (route-response {:ok "Yeap"})} (let [result (execute-query uri "from weapons hidden\n from sidekick\n with\n source = weapons.source\n weapon = {\n name: weapons.swords.name -> flatten,\n typeId: weapons.types.typeId,\n invisible: false\n }")] (is (= [{:ok "Yeap"}{:ok "Yeap"}{:ok "Yeap"}] (get-in result [:sidekick :result])))))) (testing "Nested map multiplexed flattened" (with-routes! {(route-request "/weapons") (route-response {:swords [{:name "1"} {:name "2"}] :types [{:typeId "7"} {:typeId "8"} {:typeId "9"}] :source "MAGICAL"}) (route-request "/sidekick" {:weapon {:name "2" :typeId "8" :invisible false} :source "MAGICAL"}) (route-response {:ok "Yeap"})} (let [result (execute-query uri "from weapons hidden\n from sidekick\n with\n source = weapons.source\n weapon = {\n name: weapons.swords.name,\n typeId: weapons.types.typeId,\n invisible: false\n } -> flatten")] (is (= {:ok "Yeap"} (get-in result [:sidekick :result])))))) (testing "Nested map multiplexed flattened with value flattened" (with-routes! {(route-request "/weapons") (route-response {:swords [{:name "1"} {:name "2"}] :types [{:typeId "7"} {:typeId "8"}] :source "MAGICAL"}) (route-request "/sidekick" {:weapon {:name ["1","2"] :typeId "8" :invisible false} :source "MAGICAL"}) (route-response {:ok "Yeap"})} (let [result (execute-query uri "from weapons hidden\n from sidekick\n with\n source = weapons.source\n weapon = {\n name: weapons.swords.name -> flatten,\n typeId: weapons.types.typeId,\n invisible: false\n } -> flatten")] (is (= {:ok "Yeap"} (get-in result [:sidekick :result])))))))
110556
(ns restql.restql-test (:require [clojure.test :refer :all] [restql.parser.core :as parser] [restql.core.api.restql :as restql] [byte-streams :as bs] [cheshire.core :as json] [stub-http.core :refer :all] [clojure.core.async :refer :all] [restql.test-util :refer [route-response route-request route-header]])) (defn get-stub-body [request] (val (first (:body request)))) (defn hero-route [] (route-response {:hi "I'm hero" :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]})) (defn hero-with-bag-route [] (route-response {:hi "I'm hero" :bag {:capacity 10}})) (defn sidekick-route [] (route-response {:hi "I'm sidekick"})) (defn product-route [id] (route-response {:product (str id)})) (defn heroes-route [] {:status 200 :content-type "application/json" :body (json/generate-string [{:hi "I'm hero" :villains ["1" "2"]} {:hi "I'm hero" :villains ["3" "4"]}])}) (defn villain-route [id] (route-response {:hi "I'm villain" :id (str id)})) (defn execute-query ([base-url query] (execute-query base-url query {} {})) ([base-url query params] (execute-query base-url query params {})) ([base-url query params options] (restql/execute-query :mappings {:hero (str base-url "/hero") :heroes (str base-url "/heroes") :weapons (str base-url "/weapons") :sidekick (str base-url "/sidekick") :villain (str base-url "/villain/:id") :weapon (str base-url "/weapon/:id") :product (str base-url "/product/:id") :product-price (str base-url "/price/:productId") :product-description (str base-url "/description/:productId") :fail "http://not.a.working.endpoint"} :query query :params params :options options))) (deftest simple-request (with-routes! {"/hero" (hero-route)} (let [result (execute-query uri "from hero")] (is (= 200 (get-in result [:hero :details :status]))) (is (= {:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]} (get-in result [:hero :result]))) (is (= "I'm hero" (get-in result [:hero :result :hi])))))) (deftest multiplexed-request (with-routes! {"/hero" (route-response {:villains ["1" "2"]}) "/villain/1" (villain-route "1") "/villain/2" (villain-route "2")} (let [result (execute-query uri "from hero\n from villain with id = hero.villains")] (is (= {:villains ["1" "2"]} (get-in result [:hero :result]))) (is (= [{:hi "I'm villain", :id "1"} {:hi "I'm villain", :id "2"}] (get-in result [:villain :result]))))) ; Test simple case with: single, list with one, list with two (with-routes! {"/hero" (hero-route)} (let [response (execute-query uri "from hero with name = $name" {:name "<NAME>"}) details (get-in response [:hero :details]) result (get-in response [:hero :result])] (is (= 200 (:status details))) (is (= {:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]} result)))) (with-routes! {"/hero" (hero-route)} (let [response (execute-query uri "from hero with name = $name" {:name ["<NAME>"]}) details (get-in response [:hero :details]) result (get-in response [:hero :result])] (is (= 200 (:status (first details)))) (is (= [{:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]}] result)))) (with-routes! {"/hero" (hero-route)} (let [response (execute-query uri "from hero with name = $name" {:name ["<NAME>" "<NAME>"]}) details (get-in response [:hero :details]) result (get-in response [:hero :result])] (is (= 200 (:status (first details)))) (is (= 200 (:status (second details)))) (is (= [{:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]} {:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]}] result)))) ;; Test simple case with list: single, list with one, list with two (with-routes! {"/hero" (route-response {:villains ["1" "2"]}) "/villain/1" (villain-route "1") "/villain/2" (villain-route "2")} (let [result (execute-query uri "from hero with id =1\nfrom villain with id = hero.villains")] (is (= 200 (:status (get-in result [:hero :details])))) (is (= 200 (:status (first (get-in result [:villain :details]))))) (is (= 200 (:status (second (get-in result [:villain :details]))))) (is (= {:villains ["1" "2"]} (get-in result [:hero :result]))) (is (= [{:hi "I'm villain", :id "1"} {:hi "I'm villain", :id "2"}] (get-in result [:villain :result]))))) (with-routes! {"/hero" (route-response {:villains ["1" "2"]}) "/villain/1" (villain-route "1") "/villain/2" (villain-route "2")} (let [result (execute-query uri "from hero with id =[1]\nfrom villain with id = hero.villains")] (is (= 200 (:status (first (get-in result [:hero :details]))))) (is (= 200 (:status (first (first (get-in result [:villain :details])))))) (is (= 200 (:status (second (first (get-in result [:villain :details])))))) (is (= [{:villains ["1" "2"]}] (get-in result [:hero :result]))) (is (= [[{:hi "I'm villain", :id "1"} {:hi "I'm villain", :id "2"}]] (get-in result [:villain :result]))))) (with-routes! {"/hero" (route-response {:villains ["1" "2"]}) "/villain/1" (villain-route "1") "/villain/2" (villain-route "2")} (let [result (execute-query uri "from hero with id =[1,2]\nfrom villain with id = hero.villains")] (is (= 200 (:status (first (get-in result [:hero :details]))))) (is (= 200 (:status (second (get-in result [:hero :details]))))) (is (= 200 (:status (first (first (get-in result [:villain :details])))))) (is (= 200 (:status (second (first (get-in result [:villain :details])))))) (is (= 200 (:status (first (second (get-in result [:villain :details])))))) (is (= 200 (:status (second (second (get-in result [:villain :details])))))) (is (= [{:villains ["1" "2"]} {:villains ["1" "2"]}] (get-in result [:hero :result]))) (is (= [[{:hi "I'm villain", :id "1"} {:hi "I'm villain", :id "2"}] [{:hi "I'm villain", :id "1"} {:hi "I'm villain", :id "2"}]] (get-in result [:villain :result]))))) (with-routes! {"/heroes" (route-response [{:villains ["1" "2"]} {:villains ["3" "4"]}]) "/villain/1" (villain-route "1") "/villain/2" (villain-route "2") "/villain/3" (villain-route "3") "/villain/4" (villain-route "4")} (let [result (execute-query uri "from heroes\nfrom villain with id = heroes.villains")] (is (= 200 (get-in result [:heroes :details :status]))) (is (= 200 (:status (first (first (get-in result [:villain :details])))))) (is (= 200 (:status (second (first (get-in result [:villain :details])))))) (is (= 200 (:status (first (second (get-in result [:villain :details])))))) (is (= 200 (:status (second (second (get-in result [:villain :details])))))) (is (= [{:villains ["1" "2"]} {:villains ["3" "4"]}] (get-in result [:heroes :result]))) (is (= [[{:hi "I'm villain", :id "1"} {:hi "I'm villain", :id "2"}] [{:hi "I'm villain", :id "3"} {:hi "I'm villain", :id "4"}]] (get-in result [:villain :result]))))) (with-routes! {"/hero" (route-response {:villains "1"}) "/villain/1" (route-response {:weapons ["dagger" "sword"]}) "/weapon/dagger" (route-response {:name "dagger"}) "/weapon/sword" (route-response {:name "sword"})} (let [result (execute-query uri "from hero\n from villain with id = hero.villains\n from weapon with id = villain.weapons")] (is (= {:villains "1"} (get-in result [:hero :result]))) (is (= {:weapons ["dagger" "sword"]} (get-in result [:villain :result]))) (is (= [{:name "dagger"} {:name "sword"}] (get-in result [:weapon :result]))))) (with-routes! {"/hero" (route-response {:villains ["1"]}) "/villain/1" (route-response {:weapons ["dagger" "sword"]}) "/weapon/dagger" (route-response {:name "dagger"}) "/weapon/sword" (route-response {:name "sword"})} (let [result (execute-query uri "from hero\n from villain with id = hero.villains\n from weapon with id = villain.weapons")] (is (= {:villains ["1"]} (get-in result [:hero :result]))) (is (= [{:weapons ["dagger" "sword"]}] (get-in result [:villain :result]))) (is (= [[{:name "dagger"} {:name "sword"}]] (get-in result [:weapon :result]))))) (testing "With map->list->simple_value" (with-routes! {"/hero" (route-response {:villains [{:id "1" :weapon "DAGGER"}]}) "/villain/1" (route-response {:id "1"}) "/weapon/DAGGER" (route-response {:id "DAGGER"})} (let [result (execute-query uri "from hero \n from villain with id = hero.villains.id \n from weapon with id = hero.villains.weapon")] (is (= {:villains [{:id "1" :weapon "DAGGER"}]} (get-in result [:hero :result]))) (is (= [{:id "1"}] (get-in result [:villain :result]))) (is (= [{:id "DAGGER"}] (get-in result [:weapon :result])))))) (testing "With map->list->complex_value" (with-routes! {"/hero" (route-response {:villains [{:v {:id "1"}}]}) "/villain/{\"id\":\"1\"}" (route-response {:id "1"})} (let [result (execute-query uri "from hero \n from villain with id = hero.villains.v")] (is (= {:villains [{:v {:id "1"}}]} (get-in result [:hero :result]))) (is (= [{:id "1"}] (get-in result [:villain :result])))))) (testing "With list->map->list->simple_value and list->map->list->complex_value" (with-routes! {"/heroes" (route-response [{:villains [{:id "1" :weapons ["DAGGER"]}]}]) "/villain/1" (route-response {:id "1"}) "/weapon/DAGGER" (route-response {:id "DAGGER"})} (let [result (execute-query uri "from heroes\n from villain with id = heroes.villains.id\n from weapon with id = heroes.villains.weapons")] (is (= [{:villains [{:id "1" :weapons ["DAGGER"]}]}] (get-in result [:heroes :result]))) (is (= [[{:id "1"}]] (get-in result [:villain :result]))) (is (= [[[{:id "DAGGER"}]]] (get-in result [:weapon :result]))))))) (deftest request-with-ignore-errors-should-have-ignore-errors-in-metadata (with-routes! {"/hero" (assoc (hero-route) :status 500)} (let [result (execute-query uri "from hero ignore-errors")] (is (= 500 (get-in result [:hero :details :status]))) (is (= {:ignore-errors "ignore"} (get-in result [:hero :details :metadata])))))) (deftest error-request-with-ignore-errors-shouldnt-throw-exception (with-routes! {"/hero" (assoc (hero-route) :status 500)} (let [result (execute-query uri "from hero ignore-errors")] (is (= 500 (get-in result [:hero :details :status]))) (is (= {:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]} (get-in result [:hero :result])))))) (deftest request-with-encoder (with-routes! {(route-request "/hero" {:bag {:capacity 10}}) (hero-route)} (let [result (execute-query uri "from hero with bag = {capacity: 10} -> json")] (is (= 200 (get-in result [:hero :details :status]))) (is (= {:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]} (get-in result [:hero :result]))))) (with-routes! {(route-request "/hero" {:bag "[10,20]"}) (hero-route)} (let [result (execute-query uri "from hero with bag = [10, 20] -> flatten -> json")] (is (= 200 (get-in result [:hero :details :status]))) (is (= {:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]} (get-in result [:hero :result])))))) (deftest request-with-encoder-2 (with-routes! {"/hero" (hero-with-bag-route) (route-request "/sidekick" {:bag {:capacity 10}}) (sidekick-route)} (let [result (execute-query uri "from hero \n from sidekick with bag = hero.bag -> json")] (is (= 200 (get-in result [:hero :details :status]))) (is (= {:hi "I'm hero", :bag {:capacity 10}} (get-in result [:hero :result]))) (is (= 200 (get-in result [:sidekick :details :status]))) (is (= {:hi "I'm sidekick"} (get-in result [:sidekick :result])))))) (deftest request-with-quoted-param (with-routes! {(route-request "/hero" {:name "<NAME> \"<NAME>\" <NAME>"}) (hero-route)} (let [result (execute-query uri "from hero with name = $name" {:name "<NAME> \"<NAME>\" <NAME>"})] (is (= 200 (get-in result [:hero :details :status])))))) (deftest request-with-debug (with-routes! {(route-request "/hero" {:name "<NAME>"}) (hero-route)} (let [result (execute-query uri "from hero with name = $name" {:name "<NAME>"} {:debugging true})] (is (= 200 (get-in result [:hero :details :status])) (contains? (get-in result [:hero :details]) :debug))))) (deftest execute-query-post (testing "Execute post with simple body" (with-routes! {(fn [request] (and (= (:path request) "/hero") (= (:method request) "POST") (= (get-stub-body request) (json/generate-string {:id 1})))) (hero-route)} (let [result (execute-query uri "to hero with id = 1")] (is (= 200 (get-in result [:hero :details :status])))))) (testing "Execute post with simple body and path var" (with-routes! {(fn [request] (and (= (:path request) "/villain/1") (= (:method request) "POST") (= (get-stub-body request) (json/generate-string {:name "<NAME>"})))) (hero-route)} (let [result (execute-query uri "to villain with id = 1, name = \"<NAME>\"")] (is (= 200 (get-in result [:villain :details :status]))))))) (deftest request-with-param-map (with-routes! {(route-request "/hero" {:name "<NAME>" :age "45"}) (hero-route)} (let [result (execute-query uri "from hero with $hero" {:hero {:name "<NAME>" :age 45}})] (is (= 200 (get-in result [:hero :details :status])))))) (deftest request-with-multiplexed-param-map (with-routes! {(route-request "/hero" {:name "<NAME>"}) (hero-route) (route-request "/hero" {:name "<NAME>"}) (hero-route)} (let [response (execute-query uri "from hero with $hero" {:hero {:name ["<NAME>" "<NAME>"]}}) details (get-in response [:hero :details]) result (get-in response [:hero :result])] (is (= 200 (:status (first details)))) (is (= 200 (:status (second details)))) (is (= [{:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]} {:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]}] result))))) (deftest timeout-request-should-return-408 (with-routes! {"/hero" (assoc (hero-route) :delay 500)} (let [result (execute-query uri "from hero timeout 100")] (is (= 408 (get-in result [:hero :details :status]))) (is (= {:message "RequestTimeoutException"} (get-in result [:hero :result])))))) (deftest chained-call (with-routes! {"/hero" (hero-route) "/sidekick" (sidekick-route)} (let [result (execute-query uri "from hero\nfrom sidekick")] (is (= 200 (get-in result [:hero :details :status]))) (is (= {:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]} (get-in result [:hero :result]))) (is (= 200 (get-in result [:sidekick :details :status]))) (is (= {:hi "I'm sidekick"} (get-in result [:sidekick :result])))))) (deftest with-params (with-routes! {"/product/1234" (product-route 1234)} (let [result (execute-query uri "from product with id = $id" {:id "1234"})] (is (= 200 (get-in result [:product :details :status]))) (is (= {:product "1234"} (get-in result [:product :result])))))) (deftest failing-request-debug-mode (let [uri "http://not.a.working.endpoint" result (execute-query uri "from fail" {} {:debugging true})] (is (= 0 (get-in result [:fail :details :status]))) (is (= "http://not.a.working.endpoint" (get-in result [:fail :details :debug :url]))) (is (= 5000 (get-in result [:fail :details :debug :timeout]))))) (deftest shouldnt-throw-exeption-if-chainned-resource-timeout-and-ignore-error (with-routes! {"/hero" (hero-route)} {"/sideck" (assoc (sidekick-route) :delay 200)} (let [result (execute-query uri "from hero\nfrom sidekick timeout 100 with id = hero.sidekickId ignore-errors")] (is (= 200 (get-in result [:hero :details :status]))) (is (= {:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]} (get-in result [:hero :result]))) (is (= 408 (get-in result [:sidekick :details :status]))) (is (not (nil? (get-in result [:sidekick :result :message]))))))) (deftest request-with-overlapping-headers (testing "Query without query headers" (with-routes! {(route-header "/hero" {"test" "test"}) (hero-route)} (let [result (execute-query uri "from hero" {} {:forward-headers {"restql-query-control" "ad-hoc", "test" "test", "accept" "*/*"}})] (is (= 200 (get-in result [:hero :details :status])))))) (testing "Replacing request headers with query headers" (with-routes! {(route-header "/hero" {"test" "diff"}) (hero-route)} (let [result (execute-query uri "from hero \nheaders Test = \"diff\"" {} {:forward-headers {"restql-query-control" "ad-hoc", "test" "test", "accept" "*/*"}})] (is (= 200 (get-in result [:hero :details :status])))))) (testing "One request with fowarded-headers, one request with query headers" (with-routes! {(route-header "/hero" {"test" "test"}) (hero-route) (route-header "/sidekick" {"test" "diff"}) (sidekick-route)} (let [result (execute-query uri "from hero \nfrom sidekick\nheaders Test = \"diff\"" {} {:forward-headers {"restql-query-control" "ad-hoc", "test" "test", "accept" "*/*"}})] (is (= 200 (get-in result [:hero :details :status])))))) ) (deftest request-with-flatten (testing "Flatten single value" (with-routes! {"/hero" (hero-route) (route-request "/sidekick" {:id "I'm hero"}) (sidekick-route)} (let [result (execute-query uri "from hero \n from sidekick with id = hero.hi -> flatten")] (is (= 200 (get-in result [:hero :details :status]))) (is (= 200 (get-in result [:sidekick :details :status])))))) (testing "Flatten list value" (with-routes! {"/hero" (hero-route) (route-request "/sidekick" {:id "2"}) (sidekick-route)} (let [result (execute-query uri "from hero \n from sidekick with id = hero.villains -> flatten")] (is (= 200 (get-in result [:hero :details :status]))) (is (= 200 (get-in result [:sidekick :details :status])))))) (testing "Flatten path list value" (with-routes! {"/hero" {:status 200 :body (json/generate-string {:villains [{:id "1" :weapon {:name "FINGGER"}} {:id "2" :weapon {:name "FIREGUN"}}]})} (route-request "/sidekick" {:id "<NAME>REGUN"}) (sidekick-route)} (let [result (execute-query uri "from hero \n from sidekick with id = hero.villains.weapon.name -> flatten")] (is (= 200 (get-in result [:hero :details :status]))) (is (= 200 (get-in result [:sidekick :details :status]))))))) (deftest request-with-in (with-routes! {"/heroes" (route-response {:villain {:id "1"}}) "/villain/1" (route-response {:id "1" :name "<NAME>"})} (let [result (execute-query uri "from heroes\n from villain in heroes.villain with id = heroes.villain.id")] (is (= {:villain {:id "1" :name "<NAME>"}} (get-in result [:heroes :result]))) (is (nil? (get-in result [:villain :result]))) (is (get-in result [:heroes :details])) (is (get-in result [:villain :details])))) (with-routes! {"/heroes" (route-response {:villains ["1" "2"]}) "/villain/1" (route-response {:id "1" :name "<NAME>"}) "/villain/2" (route-response {:id "2" :name "<NAME>"})} (let [result (execute-query uri "from heroes\n from villain in heroes.villains with id = heroes.villains.id")] (is (= {:villains [{:id "1" :name "<NAME>"} {:id "2" :name "<NAME>"}]} (get-in result [:heroes :result]))) (is (nil? (get-in result [:villain :result]))) (is (get-in result [:heroes :details])) (is (get-in result [:villain :details])))) (with-routes! {"/heroes" (route-response {:villains [{:id "1"} {:id "2"}]}) "/villain/1" (route-response {:id "1" :name "<NAME>"}) "/villain/2" (route-response {:id "2" :name "<NAME>"})} (let [result (execute-query uri "from heroes\n from villain in heroes.villains with id = heroes.villains.id")] (is (= {:villains [{:id "1" :name "<NAME>"} {:id "2" :name "<NAME>"}]} (get-in result [:heroes :result]))) (is (nil? (get-in result [:villain :result]))) (is (get-in result [:heroes :details])) (is (get-in result [:villain :details])))) (with-routes! {"/heroes" (route-response [{:villains [{:id "1"} {:id "2"}]} {:villains [{:id "3"} {:id "4"}]}]) "/villain/1" (route-response {:id "1" :name "<NAME>"}) "/villain/2" (route-response {:id "2" :name "<NAME>"}) "/villain/3" (route-response {:id "3" :name "Elektra"}) "/villain/4" (route-response {:id "4" :name "Dracula"})} (let [result (execute-query uri "from heroes\n from villain in heroes.villains with id = heroes.villains.id")] (is (= [{:villains [{:id "1" :name "Lex"} {:id "2" :name "Zod"}]} {:villains [{:id "3" :name "Elektra"} {:id "4" :name "Dracula"}]}] (get-in result [:heroes :result]))) (is (nil? (get-in result [:villain :result]))) (is (get-in result [:heroes :details])) (is (get-in result [:villain :details])))) (with-routes! {"/heroes" (route-response [{:villains [{:id "1" :weapons ["DAGGER"]} {:id "2" :weapons ["GUN"]}]} {:villains [{:id "3" :weapons ["SWORD"]} {:id "4" :weapons ["SHOTGUN"]}]}]) "/villain/1" (route-response {:name "Lex"}) "/villain/2" (route-response {:name "Zod"}) "/villain/3" (route-response {:name "Elektra"}) "/villain/4" (route-response {:name "Dracula"}) "/weapon/DAGGER" (route-response {:id "DAGGER"}) "/weapon/GUN" (route-response {:id "GUN"}) "/weapon/SWORD" (route-response {:id "SWORD"}) "/weapon/SHOTGUN" (route-response {:id "SHOTGUN"})} (let [result (execute-query uri "from heroes\n from villain in heroes.villains.id with id = heroes.villains.id\n from weapon in heroes.villains.weapons with id = heroes.villains.weapons")] (is (= [{:villains [{:id {:name "Lex"} :weapons [{:id "DAGGER"}]} {:id {:name "Zod"} :weapons [{:id "GUN"}]}]} {:villains [{:id {:name "Elektra"} :weapons [{:id "SWORD"}]} {:id {:name "Dracula"} :weapons [{:id "SHOTGUN"}]}]}] (get-in result [:heroes :result]))) (is (nil? (get-in result [:villain :result]))) (is (nil? (get-in result [:weapon :result]))) (is (get-in result [:heroes :details])) (is (get-in result [:villain :details])) (is (get-in result [:weapon :details])))) (with-routes! {"/heroes" (route-response [{:villains [{:id "1"}]}]) "/villain/1" (route-response {:name "1" :weapons ["DAGGER"]}) "/villain/2" (route-response {:name "2" :weapons ["GUN"]}) "/villain/3" (route-response {:name "3" :weapons ["SHOTGUN"]}) "/villain/4" (route-response {:name "4" :weapons ["SWORD"]}) "/weapon/DAGGER" (route-response {:id "DAGGER"}) "/weapon/GUN" (route-response {:id "GUN"}) "/weapon/SHOTGUN" (route-response {:id "SHOTGUN"}) "/weapon/SWORD" (route-response {:id "SWORD"})} (let [result (execute-query uri "from heroes\n from villain with id = [1,2,3,4]\n from weapon in villain.weapons with id = villain.weapons")] (is (= [{:villains [{:id "1"}]}] (get-in result [:heroes :result]))) (is (= [{:name "1", :weapons [{:id "DAGGER"}]} {:name "2", :weapons [{:id "GUN"}]} {:name "3", :weapons [{:id "SHOTGUN"}]} {:name "4", :weapons [{:id "SWORD"}]}] (get-in result [:villain :result]))) (is (nil? (get-in result [:weapon :result]))) (is (get-in result [:heroes :details])) (is (get-in result [:villain :details])) (is (get-in result [:weapon :details])))) (with-routes! {"/heroes" (route-response [{:villains [{:id "1"} {:id "2"}]} {:villains [{:id "3"} {:id "4"}]}]) "/villain/1" (route-response {:name "1" :weapons ["DAGGER"]}) "/villain/2" (route-response {:name "2" :weapons ["GUN"]}) "/villain/3" (route-response {:name "3" :weapons ["SHOTGUN"]}) "/villain/4" (route-response {:name "4" :weapons ["SWORD"]}) "/weapon/DAGGER" (route-response {:id "DAGGER"}) "/weapon/GUN" (route-response {:id "GUN"}) "/weapon/SHOTGUN" (route-response {:id "SHOTGUN"}) "/weapon/SWORD" (route-response {:id "SWORD"})} (let [result (execute-query uri "from heroes\n from villain with id = heroes.villains.id\n from weapon in villain.weapons with id = villain.weapons")] (is (= [{:villains [{:id "1"} {:id "2"}]} {:villains [{:id "3"} {:id "4"}]}] (get-in result [:heroes :result]))) (is (= [[{:name "1", :weapons [{:id "DAGGER"}]} {:name "2", :weapons [{:id "GUN"}]}] [{:name "3", :weapons [{:id "SHOTGUN"}]} {:name "4", :weapons [{:id "SWORD"}]}]] (get-in result [:villain :result]))) (is (nil? (get-in result [:weapon :result]))) (is (get-in result [:heroes :details])) (is (get-in result [:villain :details])) (is (get-in result [:weapon :details])))) (with-routes! {"/heroes" (route-response [{:villains [{:id "1"} {:id "2"}]} {:villains [{:id "3"} {:id "4"}]}]) "/villain/1" (route-response {:name "1" :weapons ["DAGGER"]}) "/villain/2" (route-response {:name "2" :weapons ["GUN"]}) "/villain/3" (route-response {:name "3" :weapons ["SHOTGUN"]}) "/villain/4" (route-response {:name "4" :weapons ["SWORD"]}) "/weapon/DAGGER" (route-response {:id "DAGGER"}) "/weapon/GUN" (route-response {:id "GUN"}) "/weapon/SHOTGUN" (route-response {:id "SHOTGUN"}) "/weapon/SWORD" (route-response {:id "SWORD"})} (let [result (execute-query uri "from heroes\n from villain in heroes.villains with id = heroes.villains.id\n from weapon in heroes.villains.weapons with id = villain.weapons")] (is (= [{:villains [{:name "1", :weapons [{:id "DAGGER"}]} {:name "2", :weapons [{:id "GUN"}]}]} {:villains [{:name "3", :weapons [{:id "SHOTGUN"}]} {:name "4", :weapons [{:id "SWORD"}]}]}] (get-in result [:heroes :result]))) (is (nil? (get-in result [:villain :result]))) (is (nil? (get-in result [:weapon :result]))) (is (get-in result [:heroes :details])) (is (get-in result [:villain :details])) (is (get-in result [:weapon :details])))) (with-routes! {"/heroes" (route-response [{:villains [{:id "1" :weapons ["DAGGER"]} {:id "2" :weapons ["GUN"]}]}]) "/villain/1" (route-response {:name "<NAME>"}) "/villain/2" {:status 500 :content-type "application/json" :body (json/generate-string {:error "UNEXPECTED_ERROR"})} "/weapon/GUN" (route-response {:id "GUN"}) "/weapon/DAGGER" {:status 404 :content-type "application/json" :body (json/generate-string {:error "NOT_FOUND"})}} (let [result (execute-query uri "from heroes\n from villain in heroes.villains.id with id = heroes.villains.id\n from weapon in heroes.villains.weapons with id = heroes.villains.weapons")] (is (= [{:villains [{:id {:name "<NAME>"} :weapons [{:error "NOT_FOUND"}]} {:id {:error "UNEXPECTED_ERROR"} :weapons [{:id "GUN"}]}]}] (get-in result [:heroes :result]))) (is (nil? (get-in result [:villain :result]))) (is (nil? (get-in result [:weapon :result]))) (is (get-in result [:heroes :details])) (is (get-in result [:villain :details])) (is (get-in result [:weapon :details])))) (with-routes! {"/heroes" (route-response [{:villains [{:id "1"} {:id "2"}]} {:villains [{:id "3"} {:id "4"}]}]) "/weapon/1" (route-response {:id "DAGGER"}) "/weapon/2" (route-response {:id "GUN"}) "/weapon/3" (route-response {:id "SHOTGUN"}) "/weapon/4" (route-response {:id "SWORD"})} (let [result (execute-query uri "from heroes\n from weapon in heroes.villains.weapons with id = heroes.villains.id")] (is (= [{:villains [{:id "1", :weapons {:id "DAGGER"}} {:id "2", :weapons {:id "GUN"}}]} {:villains [{:id "3", :weapons {:id "SHOTGUN"}} {:id "4", :weapons {:id "SWORD"}}]}] (get-in result [:heroes :result]))) (is (nil? (get-in result [:weapon :result]))) (is (get-in result [:heroes :details])) (is (get-in result [:weapon :details]))))) (deftest with-list-param (testing "List with single value" (with-routes! {(route-request "/hero" {:id "1"}) (route-response {:villains []})} (let [result (execute-query uri "from hero with id = [\"1\"]")] (is (= 200 (:status (first (get-in result [:hero :details]))))) (is (= [{:villains []}] (get-in result [:hero :result])))))) (testing "List with multiple value" (with-routes! {(route-request "/hero" {:id "1"}) (route-response {:villains ["a"]}) (route-request "/hero" {:id "2"}) (route-response {:villains ["b"]})} (let [result (execute-query uri "from hero with id = [\"1\", \"2\"]")] (is (= 200 (:status (first (get-in result [:hero :details]))))) (is (= 200 (:status (second (get-in result [:hero :details]))))) (is (= [{:villains ["a"]} {:villains ["b"]}] (get-in result [:hero :result])))))) (testing "List with single map value" (with-routes! {(route-request "/hero" {:id {:num "1"}}) (route-response {:villains []})} (let [result (execute-query uri "from hero with id = [{num: \"1\"}]")] (is (= 200 (:status (first (get-in result [:hero :details]))))) (is (= [{:villains []}] (get-in result [:hero :result])))))) (testing "List with multiple map value" (with-routes! {(route-request "/hero" {:id {:num "1"}}) (route-response {:villains ["a"]}) (route-request "/hero" {:id {:num "2"}}) (route-response {:villains ["b"]})} (let [result (execute-query uri "from hero with id = [{num: \"1\"},{num: \"2\"}]")] (is (= 200 (:status (first (get-in result [:hero :details]))))) (is (= 200 (:status (second (get-in result [:hero :details]))))) (is (= [{:villains ["a"]} {:villains ["b"]}] (get-in result [:hero :result])))))) (testing "List flatten multiple value" (with-routes! {(route-request "/hero" {:id "2"}) (route-response {:villains ["b"]})} (let [result (execute-query uri "from hero with id = [\"1\", \"2\"] -> flatten")] (is (= 200 (:status (get-in result [:hero :details])))) (is (= {:villains ["b"]} (get-in result [:hero :result])))))) (testing "Map with multiple flatten map value" (with-routes! {(route-request "/hero" {:id {:num "2"}}) (route-response {:villains ["b"]})} (let [result (execute-query uri "from hero with id = [{num: \"1\"},{num: \"2\"}] -> flatten")] (is (= 200 (:status (get-in result [:hero :details])))) (is (= {:villains ["b"]} (get-in result [:hero :result]))))))) (deftest request-with-nested-multiplex-and-flatten (testing "Nested map multiplexed" (with-routes! {(route-request "/weapons") (route-response {:swords [{:name "1"} {:name "2"}] :types {:typeId "8"} :source "MAGICAL"}) (route-request "/sidekick" {:weapon {:name "1" :typeId "8" :invisible false} :source "MAGICAL"}) (route-response {:ok "Yeap!"}) (route-request "/sidekick" {:weapon {:name "2" :typeId "8" :invisible false} :source "MAGICAL"}) (route-response {:ok "Yeah!"})} (let [result (execute-query uri "from weapons hidden\n from sidekick\n with\n source = weapons.source\n weapon = {\n name: weapons.swords.name,\n typeId: weapons.types.typeId,\n invisible: false\n }")] (is (= {:ok "Yeap!"} (first (get-in result [:sidekick :result])))) (is (= {:ok "Yeah!"} (second (get-in result [:sidekick :result]))))))) (testing "Nested map multiplexed with value flattened" (with-routes! {(route-request "/weapons") (route-response {:swords [{:name "1"} {:name "2"}] :types [{:typeId "7"} {:typeId "8"} {:typeId "9"}] :source "MAGICAL"}) (route-request "/sidekick" {:weapon {:name ["1","2"] :typeId "7" :invisible false} :source "MAGICAL"}) (route-response {:ok "Yeap"}) (route-request "/sidekick" {:weapon {:name ["1","2"] :typeId "8" :invisible false} :source "MAGICAL"}) (route-response {:ok "Yeap"}) (route-request "/sidekick" {:weapon {:name ["1","2"] :typeId "9" :invisible false} :source "MAGICAL"}) (route-response {:ok "Yeap"})} (let [result (execute-query uri "from weapons hidden\n from sidekick\n with\n source = weapons.source\n weapon = {\n name: weapons.swords.name -> flatten,\n typeId: weapons.types.typeId,\n invisible: false\n }")] (is (= [{:ok "Yeap"}{:ok "Yeap"}{:ok "Yeap"}] (get-in result [:sidekick :result])))))) (testing "Nested map multiplexed flattened" (with-routes! {(route-request "/weapons") (route-response {:swords [{:name "1"} {:name "2"}] :types [{:typeId "7"} {:typeId "8"} {:typeId "9"}] :source "MAGICAL"}) (route-request "/sidekick" {:weapon {:name "2" :typeId "8" :invisible false} :source "MAGICAL"}) (route-response {:ok "Yeap"})} (let [result (execute-query uri "from weapons hidden\n from sidekick\n with\n source = weapons.source\n weapon = {\n name: weapons.swords.name,\n typeId: weapons.types.typeId,\n invisible: false\n } -> flatten")] (is (= {:ok "Yeap"} (get-in result [:sidekick :result])))))) (testing "Nested map multiplexed flattened with value flattened" (with-routes! {(route-request "/weapons") (route-response {:swords [{:name "1"} {:name "2"}] :types [{:typeId "7"} {:typeId "8"}] :source "MAGICAL"}) (route-request "/sidekick" {:weapon {:name ["1","2"] :typeId "8" :invisible false} :source "MAGICAL"}) (route-response {:ok "Yeap"})} (let [result (execute-query uri "from weapons hidden\n from sidekick\n with\n source = weapons.source\n weapon = {\n name: weapons.swords.name -> flatten,\n typeId: weapons.types.typeId,\n invisible: false\n } -> flatten")] (is (= {:ok "Yeap"} (get-in result [:sidekick :result])))))))
true
(ns restql.restql-test (:require [clojure.test :refer :all] [restql.parser.core :as parser] [restql.core.api.restql :as restql] [byte-streams :as bs] [cheshire.core :as json] [stub-http.core :refer :all] [clojure.core.async :refer :all] [restql.test-util :refer [route-response route-request route-header]])) (defn get-stub-body [request] (val (first (:body request)))) (defn hero-route [] (route-response {:hi "I'm hero" :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]})) (defn hero-with-bag-route [] (route-response {:hi "I'm hero" :bag {:capacity 10}})) (defn sidekick-route [] (route-response {:hi "I'm sidekick"})) (defn product-route [id] (route-response {:product (str id)})) (defn heroes-route [] {:status 200 :content-type "application/json" :body (json/generate-string [{:hi "I'm hero" :villains ["1" "2"]} {:hi "I'm hero" :villains ["3" "4"]}])}) (defn villain-route [id] (route-response {:hi "I'm villain" :id (str id)})) (defn execute-query ([base-url query] (execute-query base-url query {} {})) ([base-url query params] (execute-query base-url query params {})) ([base-url query params options] (restql/execute-query :mappings {:hero (str base-url "/hero") :heroes (str base-url "/heroes") :weapons (str base-url "/weapons") :sidekick (str base-url "/sidekick") :villain (str base-url "/villain/:id") :weapon (str base-url "/weapon/:id") :product (str base-url "/product/:id") :product-price (str base-url "/price/:productId") :product-description (str base-url "/description/:productId") :fail "http://not.a.working.endpoint"} :query query :params params :options options))) (deftest simple-request (with-routes! {"/hero" (hero-route)} (let [result (execute-query uri "from hero")] (is (= 200 (get-in result [:hero :details :status]))) (is (= {:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]} (get-in result [:hero :result]))) (is (= "I'm hero" (get-in result [:hero :result :hi])))))) (deftest multiplexed-request (with-routes! {"/hero" (route-response {:villains ["1" "2"]}) "/villain/1" (villain-route "1") "/villain/2" (villain-route "2")} (let [result (execute-query uri "from hero\n from villain with id = hero.villains")] (is (= {:villains ["1" "2"]} (get-in result [:hero :result]))) (is (= [{:hi "I'm villain", :id "1"} {:hi "I'm villain", :id "2"}] (get-in result [:villain :result]))))) ; Test simple case with: single, list with one, list with two (with-routes! {"/hero" (hero-route)} (let [response (execute-query uri "from hero with name = $name" {:name "PI:NAME:<NAME>END_PI"}) details (get-in response [:hero :details]) result (get-in response [:hero :result])] (is (= 200 (:status details))) (is (= {:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]} result)))) (with-routes! {"/hero" (hero-route)} (let [response (execute-query uri "from hero with name = $name" {:name ["PI:NAME:<NAME>END_PI"]}) details (get-in response [:hero :details]) result (get-in response [:hero :result])] (is (= 200 (:status (first details)))) (is (= [{:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]}] result)))) (with-routes! {"/hero" (hero-route)} (let [response (execute-query uri "from hero with name = $name" {:name ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]}) details (get-in response [:hero :details]) result (get-in response [:hero :result])] (is (= 200 (:status (first details)))) (is (= 200 (:status (second details)))) (is (= [{:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]} {:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]}] result)))) ;; Test simple case with list: single, list with one, list with two (with-routes! {"/hero" (route-response {:villains ["1" "2"]}) "/villain/1" (villain-route "1") "/villain/2" (villain-route "2")} (let [result (execute-query uri "from hero with id =1\nfrom villain with id = hero.villains")] (is (= 200 (:status (get-in result [:hero :details])))) (is (= 200 (:status (first (get-in result [:villain :details]))))) (is (= 200 (:status (second (get-in result [:villain :details]))))) (is (= {:villains ["1" "2"]} (get-in result [:hero :result]))) (is (= [{:hi "I'm villain", :id "1"} {:hi "I'm villain", :id "2"}] (get-in result [:villain :result]))))) (with-routes! {"/hero" (route-response {:villains ["1" "2"]}) "/villain/1" (villain-route "1") "/villain/2" (villain-route "2")} (let [result (execute-query uri "from hero with id =[1]\nfrom villain with id = hero.villains")] (is (= 200 (:status (first (get-in result [:hero :details]))))) (is (= 200 (:status (first (first (get-in result [:villain :details])))))) (is (= 200 (:status (second (first (get-in result [:villain :details])))))) (is (= [{:villains ["1" "2"]}] (get-in result [:hero :result]))) (is (= [[{:hi "I'm villain", :id "1"} {:hi "I'm villain", :id "2"}]] (get-in result [:villain :result]))))) (with-routes! {"/hero" (route-response {:villains ["1" "2"]}) "/villain/1" (villain-route "1") "/villain/2" (villain-route "2")} (let [result (execute-query uri "from hero with id =[1,2]\nfrom villain with id = hero.villains")] (is (= 200 (:status (first (get-in result [:hero :details]))))) (is (= 200 (:status (second (get-in result [:hero :details]))))) (is (= 200 (:status (first (first (get-in result [:villain :details])))))) (is (= 200 (:status (second (first (get-in result [:villain :details])))))) (is (= 200 (:status (first (second (get-in result [:villain :details])))))) (is (= 200 (:status (second (second (get-in result [:villain :details])))))) (is (= [{:villains ["1" "2"]} {:villains ["1" "2"]}] (get-in result [:hero :result]))) (is (= [[{:hi "I'm villain", :id "1"} {:hi "I'm villain", :id "2"}] [{:hi "I'm villain", :id "1"} {:hi "I'm villain", :id "2"}]] (get-in result [:villain :result]))))) (with-routes! {"/heroes" (route-response [{:villains ["1" "2"]} {:villains ["3" "4"]}]) "/villain/1" (villain-route "1") "/villain/2" (villain-route "2") "/villain/3" (villain-route "3") "/villain/4" (villain-route "4")} (let [result (execute-query uri "from heroes\nfrom villain with id = heroes.villains")] (is (= 200 (get-in result [:heroes :details :status]))) (is (= 200 (:status (first (first (get-in result [:villain :details])))))) (is (= 200 (:status (second (first (get-in result [:villain :details])))))) (is (= 200 (:status (first (second (get-in result [:villain :details])))))) (is (= 200 (:status (second (second (get-in result [:villain :details])))))) (is (= [{:villains ["1" "2"]} {:villains ["3" "4"]}] (get-in result [:heroes :result]))) (is (= [[{:hi "I'm villain", :id "1"} {:hi "I'm villain", :id "2"}] [{:hi "I'm villain", :id "3"} {:hi "I'm villain", :id "4"}]] (get-in result [:villain :result]))))) (with-routes! {"/hero" (route-response {:villains "1"}) "/villain/1" (route-response {:weapons ["dagger" "sword"]}) "/weapon/dagger" (route-response {:name "dagger"}) "/weapon/sword" (route-response {:name "sword"})} (let [result (execute-query uri "from hero\n from villain with id = hero.villains\n from weapon with id = villain.weapons")] (is (= {:villains "1"} (get-in result [:hero :result]))) (is (= {:weapons ["dagger" "sword"]} (get-in result [:villain :result]))) (is (= [{:name "dagger"} {:name "sword"}] (get-in result [:weapon :result]))))) (with-routes! {"/hero" (route-response {:villains ["1"]}) "/villain/1" (route-response {:weapons ["dagger" "sword"]}) "/weapon/dagger" (route-response {:name "dagger"}) "/weapon/sword" (route-response {:name "sword"})} (let [result (execute-query uri "from hero\n from villain with id = hero.villains\n from weapon with id = villain.weapons")] (is (= {:villains ["1"]} (get-in result [:hero :result]))) (is (= [{:weapons ["dagger" "sword"]}] (get-in result [:villain :result]))) (is (= [[{:name "dagger"} {:name "sword"}]] (get-in result [:weapon :result]))))) (testing "With map->list->simple_value" (with-routes! {"/hero" (route-response {:villains [{:id "1" :weapon "DAGGER"}]}) "/villain/1" (route-response {:id "1"}) "/weapon/DAGGER" (route-response {:id "DAGGER"})} (let [result (execute-query uri "from hero \n from villain with id = hero.villains.id \n from weapon with id = hero.villains.weapon")] (is (= {:villains [{:id "1" :weapon "DAGGER"}]} (get-in result [:hero :result]))) (is (= [{:id "1"}] (get-in result [:villain :result]))) (is (= [{:id "DAGGER"}] (get-in result [:weapon :result])))))) (testing "With map->list->complex_value" (with-routes! {"/hero" (route-response {:villains [{:v {:id "1"}}]}) "/villain/{\"id\":\"1\"}" (route-response {:id "1"})} (let [result (execute-query uri "from hero \n from villain with id = hero.villains.v")] (is (= {:villains [{:v {:id "1"}}]} (get-in result [:hero :result]))) (is (= [{:id "1"}] (get-in result [:villain :result])))))) (testing "With list->map->list->simple_value and list->map->list->complex_value" (with-routes! {"/heroes" (route-response [{:villains [{:id "1" :weapons ["DAGGER"]}]}]) "/villain/1" (route-response {:id "1"}) "/weapon/DAGGER" (route-response {:id "DAGGER"})} (let [result (execute-query uri "from heroes\n from villain with id = heroes.villains.id\n from weapon with id = heroes.villains.weapons")] (is (= [{:villains [{:id "1" :weapons ["DAGGER"]}]}] (get-in result [:heroes :result]))) (is (= [[{:id "1"}]] (get-in result [:villain :result]))) (is (= [[[{:id "DAGGER"}]]] (get-in result [:weapon :result]))))))) (deftest request-with-ignore-errors-should-have-ignore-errors-in-metadata (with-routes! {"/hero" (assoc (hero-route) :status 500)} (let [result (execute-query uri "from hero ignore-errors")] (is (= 500 (get-in result [:hero :details :status]))) (is (= {:ignore-errors "ignore"} (get-in result [:hero :details :metadata])))))) (deftest error-request-with-ignore-errors-shouldnt-throw-exception (with-routes! {"/hero" (assoc (hero-route) :status 500)} (let [result (execute-query uri "from hero ignore-errors")] (is (= 500 (get-in result [:hero :details :status]))) (is (= {:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]} (get-in result [:hero :result])))))) (deftest request-with-encoder (with-routes! {(route-request "/hero" {:bag {:capacity 10}}) (hero-route)} (let [result (execute-query uri "from hero with bag = {capacity: 10} -> json")] (is (= 200 (get-in result [:hero :details :status]))) (is (= {:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]} (get-in result [:hero :result]))))) (with-routes! {(route-request "/hero" {:bag "[10,20]"}) (hero-route)} (let [result (execute-query uri "from hero with bag = [10, 20] -> flatten -> json")] (is (= 200 (get-in result [:hero :details :status]))) (is (= {:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]} (get-in result [:hero :result])))))) (deftest request-with-encoder-2 (with-routes! {"/hero" (hero-with-bag-route) (route-request "/sidekick" {:bag {:capacity 10}}) (sidekick-route)} (let [result (execute-query uri "from hero \n from sidekick with bag = hero.bag -> json")] (is (= 200 (get-in result [:hero :details :status]))) (is (= {:hi "I'm hero", :bag {:capacity 10}} (get-in result [:hero :result]))) (is (= 200 (get-in result [:sidekick :details :status]))) (is (= {:hi "I'm sidekick"} (get-in result [:sidekick :result])))))) (deftest request-with-quoted-param (with-routes! {(route-request "/hero" {:name "PI:NAME:<NAME>END_PI \"PI:NAME:<NAME>END_PI\" PI:NAME:<NAME>END_PI"}) (hero-route)} (let [result (execute-query uri "from hero with name = $name" {:name "PI:NAME:<NAME>END_PI \"PI:NAME:<NAME>END_PI\" PI:NAME:<NAME>END_PI"})] (is (= 200 (get-in result [:hero :details :status])))))) (deftest request-with-debug (with-routes! {(route-request "/hero" {:name "PI:NAME:<NAME>END_PI"}) (hero-route)} (let [result (execute-query uri "from hero with name = $name" {:name "PI:NAME:<NAME>END_PI"} {:debugging true})] (is (= 200 (get-in result [:hero :details :status])) (contains? (get-in result [:hero :details]) :debug))))) (deftest execute-query-post (testing "Execute post with simple body" (with-routes! {(fn [request] (and (= (:path request) "/hero") (= (:method request) "POST") (= (get-stub-body request) (json/generate-string {:id 1})))) (hero-route)} (let [result (execute-query uri "to hero with id = 1")] (is (= 200 (get-in result [:hero :details :status])))))) (testing "Execute post with simple body and path var" (with-routes! {(fn [request] (and (= (:path request) "/villain/1") (= (:method request) "POST") (= (get-stub-body request) (json/generate-string {:name "PI:NAME:<NAME>END_PI"})))) (hero-route)} (let [result (execute-query uri "to villain with id = 1, name = \"PI:NAME:<NAME>END_PI\"")] (is (= 200 (get-in result [:villain :details :status]))))))) (deftest request-with-param-map (with-routes! {(route-request "/hero" {:name "PI:NAME:<NAME>END_PI" :age "45"}) (hero-route)} (let [result (execute-query uri "from hero with $hero" {:hero {:name "PI:NAME:<NAME>END_PI" :age 45}})] (is (= 200 (get-in result [:hero :details :status])))))) (deftest request-with-multiplexed-param-map (with-routes! {(route-request "/hero" {:name "PI:NAME:<NAME>END_PI"}) (hero-route) (route-request "/hero" {:name "PI:NAME:<NAME>END_PI"}) (hero-route)} (let [response (execute-query uri "from hero with $hero" {:hero {:name ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]}}) details (get-in response [:hero :details]) result (get-in response [:hero :result])] (is (= 200 (:status (first details)))) (is (= 200 (:status (second details)))) (is (= [{:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]} {:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]}] result))))) (deftest timeout-request-should-return-408 (with-routes! {"/hero" (assoc (hero-route) :delay 500)} (let [result (execute-query uri "from hero timeout 100")] (is (= 408 (get-in result [:hero :details :status]))) (is (= {:message "RequestTimeoutException"} (get-in result [:hero :result])))))) (deftest chained-call (with-routes! {"/hero" (hero-route) "/sidekick" (sidekick-route)} (let [result (execute-query uri "from hero\nfrom sidekick")] (is (= 200 (get-in result [:hero :details :status]))) (is (= {:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]} (get-in result [:hero :result]))) (is (= 200 (get-in result [:sidekick :details :status]))) (is (= {:hi "I'm sidekick"} (get-in result [:sidekick :result])))))) (deftest with-params (with-routes! {"/product/1234" (product-route 1234)} (let [result (execute-query uri "from product with id = $id" {:id "1234"})] (is (= 200 (get-in result [:product :details :status]))) (is (= {:product "1234"} (get-in result [:product :result])))))) (deftest failing-request-debug-mode (let [uri "http://not.a.working.endpoint" result (execute-query uri "from fail" {} {:debugging true})] (is (= 0 (get-in result [:fail :details :status]))) (is (= "http://not.a.working.endpoint" (get-in result [:fail :details :debug :url]))) (is (= 5000 (get-in result [:fail :details :debug :timeout]))))) (deftest shouldnt-throw-exeption-if-chainned-resource-timeout-and-ignore-error (with-routes! {"/hero" (hero-route)} {"/sideck" (assoc (sidekick-route) :delay 200)} (let [result (execute-query uri "from hero\nfrom sidekick timeout 100 with id = hero.sidekickId ignore-errors")] (is (= 200 (get-in result [:hero :details :status]))) (is (= {:hi "I'm hero", :sidekickId "A20" :villains ["1" "2"] :weapons ["pen" "papel clip"]} (get-in result [:hero :result]))) (is (= 408 (get-in result [:sidekick :details :status]))) (is (not (nil? (get-in result [:sidekick :result :message]))))))) (deftest request-with-overlapping-headers (testing "Query without query headers" (with-routes! {(route-header "/hero" {"test" "test"}) (hero-route)} (let [result (execute-query uri "from hero" {} {:forward-headers {"restql-query-control" "ad-hoc", "test" "test", "accept" "*/*"}})] (is (= 200 (get-in result [:hero :details :status])))))) (testing "Replacing request headers with query headers" (with-routes! {(route-header "/hero" {"test" "diff"}) (hero-route)} (let [result (execute-query uri "from hero \nheaders Test = \"diff\"" {} {:forward-headers {"restql-query-control" "ad-hoc", "test" "test", "accept" "*/*"}})] (is (= 200 (get-in result [:hero :details :status])))))) (testing "One request with fowarded-headers, one request with query headers" (with-routes! {(route-header "/hero" {"test" "test"}) (hero-route) (route-header "/sidekick" {"test" "diff"}) (sidekick-route)} (let [result (execute-query uri "from hero \nfrom sidekick\nheaders Test = \"diff\"" {} {:forward-headers {"restql-query-control" "ad-hoc", "test" "test", "accept" "*/*"}})] (is (= 200 (get-in result [:hero :details :status])))))) ) (deftest request-with-flatten (testing "Flatten single value" (with-routes! {"/hero" (hero-route) (route-request "/sidekick" {:id "I'm hero"}) (sidekick-route)} (let [result (execute-query uri "from hero \n from sidekick with id = hero.hi -> flatten")] (is (= 200 (get-in result [:hero :details :status]))) (is (= 200 (get-in result [:sidekick :details :status])))))) (testing "Flatten list value" (with-routes! {"/hero" (hero-route) (route-request "/sidekick" {:id "2"}) (sidekick-route)} (let [result (execute-query uri "from hero \n from sidekick with id = hero.villains -> flatten")] (is (= 200 (get-in result [:hero :details :status]))) (is (= 200 (get-in result [:sidekick :details :status])))))) (testing "Flatten path list value" (with-routes! {"/hero" {:status 200 :body (json/generate-string {:villains [{:id "1" :weapon {:name "FINGGER"}} {:id "2" :weapon {:name "FIREGUN"}}]})} (route-request "/sidekick" {:id "PI:NAME:<NAME>END_PIREGUN"}) (sidekick-route)} (let [result (execute-query uri "from hero \n from sidekick with id = hero.villains.weapon.name -> flatten")] (is (= 200 (get-in result [:hero :details :status]))) (is (= 200 (get-in result [:sidekick :details :status]))))))) (deftest request-with-in (with-routes! {"/heroes" (route-response {:villain {:id "1"}}) "/villain/1" (route-response {:id "1" :name "PI:NAME:<NAME>END_PI"})} (let [result (execute-query uri "from heroes\n from villain in heroes.villain with id = heroes.villain.id")] (is (= {:villain {:id "1" :name "PI:NAME:<NAME>END_PI"}} (get-in result [:heroes :result]))) (is (nil? (get-in result [:villain :result]))) (is (get-in result [:heroes :details])) (is (get-in result [:villain :details])))) (with-routes! {"/heroes" (route-response {:villains ["1" "2"]}) "/villain/1" (route-response {:id "1" :name "PI:NAME:<NAME>END_PI"}) "/villain/2" (route-response {:id "2" :name "PI:NAME:<NAME>END_PI"})} (let [result (execute-query uri "from heroes\n from villain in heroes.villains with id = heroes.villains.id")] (is (= {:villains [{:id "1" :name "PI:NAME:<NAME>END_PI"} {:id "2" :name "PI:NAME:<NAME>END_PI"}]} (get-in result [:heroes :result]))) (is (nil? (get-in result [:villain :result]))) (is (get-in result [:heroes :details])) (is (get-in result [:villain :details])))) (with-routes! {"/heroes" (route-response {:villains [{:id "1"} {:id "2"}]}) "/villain/1" (route-response {:id "1" :name "PI:NAME:<NAME>END_PI"}) "/villain/2" (route-response {:id "2" :name "PI:NAME:<NAME>END_PI"})} (let [result (execute-query uri "from heroes\n from villain in heroes.villains with id = heroes.villains.id")] (is (= {:villains [{:id "1" :name "PI:NAME:<NAME>END_PI"} {:id "2" :name "PI:NAME:<NAME>END_PI"}]} (get-in result [:heroes :result]))) (is (nil? (get-in result [:villain :result]))) (is (get-in result [:heroes :details])) (is (get-in result [:villain :details])))) (with-routes! {"/heroes" (route-response [{:villains [{:id "1"} {:id "2"}]} {:villains [{:id "3"} {:id "4"}]}]) "/villain/1" (route-response {:id "1" :name "PI:NAME:<NAME>END_PI"}) "/villain/2" (route-response {:id "2" :name "PI:NAME:<NAME>END_PI"}) "/villain/3" (route-response {:id "3" :name "Elektra"}) "/villain/4" (route-response {:id "4" :name "Dracula"})} (let [result (execute-query uri "from heroes\n from villain in heroes.villains with id = heroes.villains.id")] (is (= [{:villains [{:id "1" :name "Lex"} {:id "2" :name "Zod"}]} {:villains [{:id "3" :name "Elektra"} {:id "4" :name "Dracula"}]}] (get-in result [:heroes :result]))) (is (nil? (get-in result [:villain :result]))) (is (get-in result [:heroes :details])) (is (get-in result [:villain :details])))) (with-routes! {"/heroes" (route-response [{:villains [{:id "1" :weapons ["DAGGER"]} {:id "2" :weapons ["GUN"]}]} {:villains [{:id "3" :weapons ["SWORD"]} {:id "4" :weapons ["SHOTGUN"]}]}]) "/villain/1" (route-response {:name "Lex"}) "/villain/2" (route-response {:name "Zod"}) "/villain/3" (route-response {:name "Elektra"}) "/villain/4" (route-response {:name "Dracula"}) "/weapon/DAGGER" (route-response {:id "DAGGER"}) "/weapon/GUN" (route-response {:id "GUN"}) "/weapon/SWORD" (route-response {:id "SWORD"}) "/weapon/SHOTGUN" (route-response {:id "SHOTGUN"})} (let [result (execute-query uri "from heroes\n from villain in heroes.villains.id with id = heroes.villains.id\n from weapon in heroes.villains.weapons with id = heroes.villains.weapons")] (is (= [{:villains [{:id {:name "Lex"} :weapons [{:id "DAGGER"}]} {:id {:name "Zod"} :weapons [{:id "GUN"}]}]} {:villains [{:id {:name "Elektra"} :weapons [{:id "SWORD"}]} {:id {:name "Dracula"} :weapons [{:id "SHOTGUN"}]}]}] (get-in result [:heroes :result]))) (is (nil? (get-in result [:villain :result]))) (is (nil? (get-in result [:weapon :result]))) (is (get-in result [:heroes :details])) (is (get-in result [:villain :details])) (is (get-in result [:weapon :details])))) (with-routes! {"/heroes" (route-response [{:villains [{:id "1"}]}]) "/villain/1" (route-response {:name "1" :weapons ["DAGGER"]}) "/villain/2" (route-response {:name "2" :weapons ["GUN"]}) "/villain/3" (route-response {:name "3" :weapons ["SHOTGUN"]}) "/villain/4" (route-response {:name "4" :weapons ["SWORD"]}) "/weapon/DAGGER" (route-response {:id "DAGGER"}) "/weapon/GUN" (route-response {:id "GUN"}) "/weapon/SHOTGUN" (route-response {:id "SHOTGUN"}) "/weapon/SWORD" (route-response {:id "SWORD"})} (let [result (execute-query uri "from heroes\n from villain with id = [1,2,3,4]\n from weapon in villain.weapons with id = villain.weapons")] (is (= [{:villains [{:id "1"}]}] (get-in result [:heroes :result]))) (is (= [{:name "1", :weapons [{:id "DAGGER"}]} {:name "2", :weapons [{:id "GUN"}]} {:name "3", :weapons [{:id "SHOTGUN"}]} {:name "4", :weapons [{:id "SWORD"}]}] (get-in result [:villain :result]))) (is (nil? (get-in result [:weapon :result]))) (is (get-in result [:heroes :details])) (is (get-in result [:villain :details])) (is (get-in result [:weapon :details])))) (with-routes! {"/heroes" (route-response [{:villains [{:id "1"} {:id "2"}]} {:villains [{:id "3"} {:id "4"}]}]) "/villain/1" (route-response {:name "1" :weapons ["DAGGER"]}) "/villain/2" (route-response {:name "2" :weapons ["GUN"]}) "/villain/3" (route-response {:name "3" :weapons ["SHOTGUN"]}) "/villain/4" (route-response {:name "4" :weapons ["SWORD"]}) "/weapon/DAGGER" (route-response {:id "DAGGER"}) "/weapon/GUN" (route-response {:id "GUN"}) "/weapon/SHOTGUN" (route-response {:id "SHOTGUN"}) "/weapon/SWORD" (route-response {:id "SWORD"})} (let [result (execute-query uri "from heroes\n from villain with id = heroes.villains.id\n from weapon in villain.weapons with id = villain.weapons")] (is (= [{:villains [{:id "1"} {:id "2"}]} {:villains [{:id "3"} {:id "4"}]}] (get-in result [:heroes :result]))) (is (= [[{:name "1", :weapons [{:id "DAGGER"}]} {:name "2", :weapons [{:id "GUN"}]}] [{:name "3", :weapons [{:id "SHOTGUN"}]} {:name "4", :weapons [{:id "SWORD"}]}]] (get-in result [:villain :result]))) (is (nil? (get-in result [:weapon :result]))) (is (get-in result [:heroes :details])) (is (get-in result [:villain :details])) (is (get-in result [:weapon :details])))) (with-routes! {"/heroes" (route-response [{:villains [{:id "1"} {:id "2"}]} {:villains [{:id "3"} {:id "4"}]}]) "/villain/1" (route-response {:name "1" :weapons ["DAGGER"]}) "/villain/2" (route-response {:name "2" :weapons ["GUN"]}) "/villain/3" (route-response {:name "3" :weapons ["SHOTGUN"]}) "/villain/4" (route-response {:name "4" :weapons ["SWORD"]}) "/weapon/DAGGER" (route-response {:id "DAGGER"}) "/weapon/GUN" (route-response {:id "GUN"}) "/weapon/SHOTGUN" (route-response {:id "SHOTGUN"}) "/weapon/SWORD" (route-response {:id "SWORD"})} (let [result (execute-query uri "from heroes\n from villain in heroes.villains with id = heroes.villains.id\n from weapon in heroes.villains.weapons with id = villain.weapons")] (is (= [{:villains [{:name "1", :weapons [{:id "DAGGER"}]} {:name "2", :weapons [{:id "GUN"}]}]} {:villains [{:name "3", :weapons [{:id "SHOTGUN"}]} {:name "4", :weapons [{:id "SWORD"}]}]}] (get-in result [:heroes :result]))) (is (nil? (get-in result [:villain :result]))) (is (nil? (get-in result [:weapon :result]))) (is (get-in result [:heroes :details])) (is (get-in result [:villain :details])) (is (get-in result [:weapon :details])))) (with-routes! {"/heroes" (route-response [{:villains [{:id "1" :weapons ["DAGGER"]} {:id "2" :weapons ["GUN"]}]}]) "/villain/1" (route-response {:name "PI:NAME:<NAME>END_PI"}) "/villain/2" {:status 500 :content-type "application/json" :body (json/generate-string {:error "UNEXPECTED_ERROR"})} "/weapon/GUN" (route-response {:id "GUN"}) "/weapon/DAGGER" {:status 404 :content-type "application/json" :body (json/generate-string {:error "NOT_FOUND"})}} (let [result (execute-query uri "from heroes\n from villain in heroes.villains.id with id = heroes.villains.id\n from weapon in heroes.villains.weapons with id = heroes.villains.weapons")] (is (= [{:villains [{:id {:name "PI:NAME:<NAME>END_PI"} :weapons [{:error "NOT_FOUND"}]} {:id {:error "UNEXPECTED_ERROR"} :weapons [{:id "GUN"}]}]}] (get-in result [:heroes :result]))) (is (nil? (get-in result [:villain :result]))) (is (nil? (get-in result [:weapon :result]))) (is (get-in result [:heroes :details])) (is (get-in result [:villain :details])) (is (get-in result [:weapon :details])))) (with-routes! {"/heroes" (route-response [{:villains [{:id "1"} {:id "2"}]} {:villains [{:id "3"} {:id "4"}]}]) "/weapon/1" (route-response {:id "DAGGER"}) "/weapon/2" (route-response {:id "GUN"}) "/weapon/3" (route-response {:id "SHOTGUN"}) "/weapon/4" (route-response {:id "SWORD"})} (let [result (execute-query uri "from heroes\n from weapon in heroes.villains.weapons with id = heroes.villains.id")] (is (= [{:villains [{:id "1", :weapons {:id "DAGGER"}} {:id "2", :weapons {:id "GUN"}}]} {:villains [{:id "3", :weapons {:id "SHOTGUN"}} {:id "4", :weapons {:id "SWORD"}}]}] (get-in result [:heroes :result]))) (is (nil? (get-in result [:weapon :result]))) (is (get-in result [:heroes :details])) (is (get-in result [:weapon :details]))))) (deftest with-list-param (testing "List with single value" (with-routes! {(route-request "/hero" {:id "1"}) (route-response {:villains []})} (let [result (execute-query uri "from hero with id = [\"1\"]")] (is (= 200 (:status (first (get-in result [:hero :details]))))) (is (= [{:villains []}] (get-in result [:hero :result])))))) (testing "List with multiple value" (with-routes! {(route-request "/hero" {:id "1"}) (route-response {:villains ["a"]}) (route-request "/hero" {:id "2"}) (route-response {:villains ["b"]})} (let [result (execute-query uri "from hero with id = [\"1\", \"2\"]")] (is (= 200 (:status (first (get-in result [:hero :details]))))) (is (= 200 (:status (second (get-in result [:hero :details]))))) (is (= [{:villains ["a"]} {:villains ["b"]}] (get-in result [:hero :result])))))) (testing "List with single map value" (with-routes! {(route-request "/hero" {:id {:num "1"}}) (route-response {:villains []})} (let [result (execute-query uri "from hero with id = [{num: \"1\"}]")] (is (= 200 (:status (first (get-in result [:hero :details]))))) (is (= [{:villains []}] (get-in result [:hero :result])))))) (testing "List with multiple map value" (with-routes! {(route-request "/hero" {:id {:num "1"}}) (route-response {:villains ["a"]}) (route-request "/hero" {:id {:num "2"}}) (route-response {:villains ["b"]})} (let [result (execute-query uri "from hero with id = [{num: \"1\"},{num: \"2\"}]")] (is (= 200 (:status (first (get-in result [:hero :details]))))) (is (= 200 (:status (second (get-in result [:hero :details]))))) (is (= [{:villains ["a"]} {:villains ["b"]}] (get-in result [:hero :result])))))) (testing "List flatten multiple value" (with-routes! {(route-request "/hero" {:id "2"}) (route-response {:villains ["b"]})} (let [result (execute-query uri "from hero with id = [\"1\", \"2\"] -> flatten")] (is (= 200 (:status (get-in result [:hero :details])))) (is (= {:villains ["b"]} (get-in result [:hero :result])))))) (testing "Map with multiple flatten map value" (with-routes! {(route-request "/hero" {:id {:num "2"}}) (route-response {:villains ["b"]})} (let [result (execute-query uri "from hero with id = [{num: \"1\"},{num: \"2\"}] -> flatten")] (is (= 200 (:status (get-in result [:hero :details])))) (is (= {:villains ["b"]} (get-in result [:hero :result]))))))) (deftest request-with-nested-multiplex-and-flatten (testing "Nested map multiplexed" (with-routes! {(route-request "/weapons") (route-response {:swords [{:name "1"} {:name "2"}] :types {:typeId "8"} :source "MAGICAL"}) (route-request "/sidekick" {:weapon {:name "1" :typeId "8" :invisible false} :source "MAGICAL"}) (route-response {:ok "Yeap!"}) (route-request "/sidekick" {:weapon {:name "2" :typeId "8" :invisible false} :source "MAGICAL"}) (route-response {:ok "Yeah!"})} (let [result (execute-query uri "from weapons hidden\n from sidekick\n with\n source = weapons.source\n weapon = {\n name: weapons.swords.name,\n typeId: weapons.types.typeId,\n invisible: false\n }")] (is (= {:ok "Yeap!"} (first (get-in result [:sidekick :result])))) (is (= {:ok "Yeah!"} (second (get-in result [:sidekick :result]))))))) (testing "Nested map multiplexed with value flattened" (with-routes! {(route-request "/weapons") (route-response {:swords [{:name "1"} {:name "2"}] :types [{:typeId "7"} {:typeId "8"} {:typeId "9"}] :source "MAGICAL"}) (route-request "/sidekick" {:weapon {:name ["1","2"] :typeId "7" :invisible false} :source "MAGICAL"}) (route-response {:ok "Yeap"}) (route-request "/sidekick" {:weapon {:name ["1","2"] :typeId "8" :invisible false} :source "MAGICAL"}) (route-response {:ok "Yeap"}) (route-request "/sidekick" {:weapon {:name ["1","2"] :typeId "9" :invisible false} :source "MAGICAL"}) (route-response {:ok "Yeap"})} (let [result (execute-query uri "from weapons hidden\n from sidekick\n with\n source = weapons.source\n weapon = {\n name: weapons.swords.name -> flatten,\n typeId: weapons.types.typeId,\n invisible: false\n }")] (is (= [{:ok "Yeap"}{:ok "Yeap"}{:ok "Yeap"}] (get-in result [:sidekick :result])))))) (testing "Nested map multiplexed flattened" (with-routes! {(route-request "/weapons") (route-response {:swords [{:name "1"} {:name "2"}] :types [{:typeId "7"} {:typeId "8"} {:typeId "9"}] :source "MAGICAL"}) (route-request "/sidekick" {:weapon {:name "2" :typeId "8" :invisible false} :source "MAGICAL"}) (route-response {:ok "Yeap"})} (let [result (execute-query uri "from weapons hidden\n from sidekick\n with\n source = weapons.source\n weapon = {\n name: weapons.swords.name,\n typeId: weapons.types.typeId,\n invisible: false\n } -> flatten")] (is (= {:ok "Yeap"} (get-in result [:sidekick :result])))))) (testing "Nested map multiplexed flattened with value flattened" (with-routes! {(route-request "/weapons") (route-response {:swords [{:name "1"} {:name "2"}] :types [{:typeId "7"} {:typeId "8"}] :source "MAGICAL"}) (route-request "/sidekick" {:weapon {:name ["1","2"] :typeId "8" :invisible false} :source "MAGICAL"}) (route-response {:ok "Yeap"})} (let [result (execute-query uri "from weapons hidden\n from sidekick\n with\n source = weapons.source\n weapon = {\n name: weapons.swords.name -> flatten,\n typeId: weapons.types.typeId,\n invisible: false\n } -> flatten")] (is (= {:ok "Yeap"} (get-in result [:sidekick :result])))))))
[ { "context": "rivate reconciliation-context\n {:users [{:email \"john@doe.com\"\n :first-name \"John\"\n :last", "end": 756, "score": 0.9999095797538757, "start": 744, "tag": "EMAIL", "value": "john@doe.com" }, { "context": " [{:email \"john@doe.com\"\n :first-name \"John\"\n :last-name \"Doe\"\n :passwo", "end": 787, "score": 0.9996559619903564, "start": 783, "tag": "NAME", "value": "John" }, { "context": " :first-name \"John\"\n :last-name \"Doe\"\n :password \"please01\"\n :pa", "end": 816, "score": 0.997251033782959, "start": 813, "tag": "NAME", "value": "Doe" }, { "context": " :last-name \"Doe\"\n :password \"please01\"\n :password-confirmation \"please01\"}]\n", "end": 849, "score": 0.9993267059326172, "start": 841, "tag": "PASSWORD", "value": "please01" }, { "context": "rd \"please01\"\n :password-confirmation \"please01\"}]\n :entities [{:name \"Personal\"}]\n :commodit", "end": 895, "score": 0.9993395805358887, "start": 887, "tag": "PASSWORD", "value": "please01" }, { "context": " \"Safeway\"\n :debit-account-id \"Groceries\"\n :credit-account-id \"Chec", "end": 2129, "score": 0.4682532548904419, "start": 2126, "tag": "NAME", "value": "roc" } ]
test/clj_money/models/reconciliations_test.clj
dgknght/clj-money
5
(ns clj-money.models.reconciliations-test (:require [clojure.test :refer [deftest use-fixtures is testing]] [clj-time.core :as t] [dgknght.app-lib.test] [clj-money.test-helpers :refer [reset-db]] [clj-money.test-context :refer [realize basic-context find-recon find-account find-transaction-item]] [clj-money.models.reconciliations :as reconciliations] [clj-money.models.transactions :as transactions])) (use-fixtures :each reset-db) (def ^:private reconciliation-context {:users [{:email "john@doe.com" :first-name "John" :last-name "Doe" :password "please01" :password-confirmation "please01"}] :entities [{:name "Personal"}] :commodities [{:name "US Dollar" :symbol "USD" :type :currency}] :accounts [{:name "Checking" :type :asset} {:name "Salary" :type :income} {:name "Rent" :type :expense} {:name "Groceries" :type :expense}] :transactions [{:transaction-date (t/local-date 2017 1 1) :description "Paycheck" :debit-account-id "Checking" :credit-account-id "Salary" :quantity 1000M} {:transaction-date (t/local-date 2017 1 2) :description "Landlord" :debit-account-id "Rent" :credit-account-id "Checking" :quantity 500M} {:transaction-date (t/local-date 2017 1 3) :description "Kroger" :debit-account-id "Groceries" :credit-account-id "Checking" :quantity 45M} {:transaction-date (t/local-date 2017 1 10) :description "Safeway" :debit-account-id "Groceries" :credit-account-id "Checking" :quantity 53M}]}) (def ^:private existing-reconciliation-context (assoc reconciliation-context :reconciliations [{:account-id "Checking" :end-of-period (t/local-date 2017 1 1) :balance 1000M :status :completed :item-refs [{:transaction-date (t/local-date 2017 1 1) :quantity 1000M}]}])) (def ^:private working-reconciliation-context (update-in existing-reconciliation-context [:reconciliations] #(conj % {:account-id "Checking" :end-of-period (t/local-date 2017 1 3) :balance 455M :status :new :item-refs [{:transaction-date (t/local-date 2017 1 2) :quantity 500M}]}))) (deftest create-a-reconciliation (let [context (realize reconciliation-context) checking (-> context :accounts first) reconciliation {:account-id (:id checking) :balance 447M :end-of-period (t/local-date 2017 1 31)} result (reconciliations/create reconciliation) retrieved (reconciliations/find-by {:account-id (:id checking)})] (is (valid? result)) (is retrieved "The reconciliation can be retrieved") (testing "transaction items are not marked as reconciled" (is (= #{false} (->> (:transactions context) (map transactions/reload) (mapcat :items) (filter #(= (:id checking) (:account-id %))) (map :reconciled?) set)) "None of the transaction items should be marked as reconcilied")))) (deftest create-a-completed-reconciliation (let [context (realize reconciliation-context) checking (-> context :accounts first) [paycheck landlord _ safeway] (->> context :transactions (mapcat :items) (filter #(= (:id checking) (:account-id %)))) reconciliation {:account-id (:id checking) :balance 447M :end-of-period (t/local-date 2017 1 31) :item-refs (map (juxt :id :transaction-date) [paycheck landlord safeway]) :status :completed} result (reconciliations/create reconciliation) retrieved (reconciliations/find-by {:account-id (:id checking)})] (is (valid? result)) (is retrieved "The reconciliation can be retrieved") (testing "transaction items are marked as reconciled" (is (= [true true false true] (->> (:transactions context) (map transactions/reload) (mapcat :items) (filter #(= (:id checking) (:account-id %))) (map :reconciled?))) "Each transaction item included in the reconciliation should be marked as reconciled")))) (deftest a-new-reconciliation-cannot-be-created-if-one-already-exists (let [context (realize working-reconciliation-context) checking (-> context :accounts first) result (reconciliations/create {:account-id (:id checking) :balance 1M :status :new :end-of-period (t/local-date 2017 2 28)})] (is (invalid? result [:account-id] "Account already has a reconciliation in progress")))) (deftest account-id-is-required (let [context (realize reconciliation-context) checking (-> context :accounts first) [paycheck landlord _ safeway] (->> context :transactions (mapcat :items) (filter #(= (:id checking) (:account-id %)))) result (reconciliations/create {:balance 447M :item-refs (map (juxt :id :transaction-date) [paycheck landlord safeway])})] (is (invalid? result [:account-id] "Account is required")))) (deftest end-of-period-is-required (let [context (realize reconciliation-context) checking (-> context :accounts first) [paycheck landlord _ safeway] (->> context :transactions (mapcat :items) (filter #(= (:id checking) (:account-id %)))) result (reconciliations/create {:balance 447M :item-refs (map (juxt :id :transaction-date) [paycheck landlord safeway])})] (is (invalid? result [:end-of-period] "End of period is required")))) (deftest end-of-period-must-come-after-the-previous-end-of-period (let [context (realize existing-reconciliation-context) checking (-> context :accounts first) reconciliation {:account-id (:id checking) :balance 447M :end-of-period (t/local-date 2016 12 31)} result (reconciliations/create reconciliation)] (is (invalid? result [:end-of-period] "End of period must be after that latest reconciliation")))) (deftest status-must-be-new-or-completed (let [context (realize reconciliation-context) checking (-> context :accounts first) [paycheck landlord _ safeway] (->> context :transactions (mapcat :items) (filter #(= (:id checking) (:account-id %)))) result (reconciliations/create {:account-id (:id checking) :end-of-period (t/local-date 2017 1 31) :status :bouncy :balance 447M :item-refs (map (juxt :id :transaction-date) [paycheck landlord safeway])})] (is (invalid? result [:status] "Status must be new or completed")))) (deftest item-refs-cannot-reference-items-that-belong-to-the-account-being-reconciled (let [context (realize reconciliation-context) [checking salary] (:accounts context) paycheck (->> context :transactions (mapcat :items) (filter #(= (:id salary) (:account-id %))) first) result (reconciliations/create {:account-id (:id checking) :end-of-period (t/local-date 2017 1 31) :balance 10M :item-refs [((juxt :id :transaction-date) paycheck)]})] (is (invalid? result [:item-refs] "All items must belong to the account being reconciled")))) (def ^:private parent-account-context (-> basic-context (update-in [:accounts] concat [{:name "Savings" :type :asset :entity-id "Personal"} {:name "Car" :type :asset :entity-id "Personal" :parent-id "Savings"} {:name "Reserve" :type :asset :entity-id "Personal" :parent-id "Savings"}]) (assoc :transactions [{:transaction-date (t/local-date 2015 1 1) :description "Paycheck" :items [{:action :credit :account-id "Salary" :quantity 1000M} {:action :debit :account-id "Car" :quantity 100M} {:action :debit :account-id "Reserve" :quantity 200M} {:action :debit :account-id "Checking" :quantity 700M}]}]))) (deftest item-refs-can-reference-items-that-belong-to-children-of-the-account-being-reconciled (let [ctx (realize parent-account-context) account (find-account ctx "Savings") items (transactions/search-items {:account-id (:id account) :transaction-date [:between (t/local-date 2015 1 1) (t/local-date 2015 1 31)]} {:include-children? true}) result (reconciliations/create {:account-id (:id account) :end-of-period (t/local-date 2015 1 31) :status :completed :balance 300M :item-refs (map (juxt :id :transaction-date) items)})] (is (valid? result)))) (def ^:private working-rec-context (assoc reconciliation-context :reconciliations [{:account-id "Checking" :end-of-period (t/local-date 2017 1 1) :balance 447M :status :new :item-refs [{:transaction-date (t/local-date 2017 1 1) :account-id "Salary" :quantity 1000M} {:transaction-date (t/local-date 2017 1 2) :account-id "Rent" :quantity 500M} {:transaction-date (t/local-date 2017 1 10) :account-id "Groceries" :quantity 53M}]}])) (deftest find-the-working-reconciliation (let [context (realize working-rec-context) checking (-> context :accounts first) reconciliation (reconciliations/find-working (:id checking))] (is reconciliation "A reconciliation is returned"))) (deftest transaction-item-can-only-belong-to-one-reconciliation (let [context (realize existing-reconciliation-context) checking (find-account context "Checking") item (->> (:transactions context) (mapcat :items) (filter #(= (:id checking) (:account-id %))) first) result (reconciliations/create {:account-id (:id checking) :end-of-period (t/local-date 2017 1 31) :balance 1500M :item-refs [((juxt :id :transaction-date) item)]})] (is (invalid? result [:item-refs] "No item can belong to another reconciliation")))) (deftest a-working-reconciliation-can-be-updated (let [context (realize working-reconciliation-context) recon (-> context :reconciliations last) result (reconciliations/update (assoc recon :balance 1499M)) retrieved (reconciliations/find recon)] (is (valid? result)) (is (= 1499M (:balance retrieved)) "The retrieved value has the correct balance after update"))) (deftest a-working-reconciliation-can-be-completed (let [context (realize working-reconciliation-context) previous-rec (find-recon context "Checking" (t/local-date 2017 1 1)) reconciliation (find-recon context "Checking" (t/local-date 2017 1 3)) checking (find-account context "Checking") item (find-transaction-item context (t/local-date 2017 1 3) 45M (:id checking)) updated (-> reconciliation (assoc :status :completed) (update-in [:item-refs] conj ((juxt :id :transaction-date) item))) result (reconciliations/update updated) retrieved (reconciliations/reload updated) checking-items (transactions/search-items {:account-id (:id checking) :transaction-date "2017"} {:sort [:transaction-date]})] (is (valid? result)) (is (= (:status retrieved) :completed) "The retrieved value has the correct satus") (testing "reconciled transaction items" (let [expected [{:transaction-date (t/local-date 2017 1 1) :quantity 1000M :reconciliation-id (:id previous-rec)} {:transaction-date (t/local-date 2017 1 2) :quantity 500M :reconciliation-id (:id retrieved)} {:transaction-date (t/local-date 2017 1 3) :quantity 45M :reconciliation-id (:id retrieved)} {:transaction-date (t/local-date 2017 1 10) :quantity 53M :reconciliation-id nil}] actual (map #(select-keys % [:transaction-date :quantity :reconciliation-id]) checking-items)] (is (= expected actual) "The correct transaction items are associated with the reconciliation"))))) (deftest cannot-create-a-completed-out-of-balance-reconciliation (let [context (realize reconciliation-context) checking (find-account context "Checking") result (reconciliations/create {:account-id (:id checking) :end-of-period (t/local-date 2017 1 31) :balance 101M :status :completed})] (is (invalid? result [:balance] "Balance must match the calculated balance")))) (deftest an-out-of-balance-reconciliation-cannot-be-updated-to-completed (let [context (realize working-reconciliation-context) checking (-> context :accounts first) reconciliation (-> context :reconciliations last) updated (-> reconciliation (assoc :status :completed) (update-in [:item-refs] #(conj % (->> context :transactions (mapcat :items) (filter (fn [i] (= (:id checking) (:account-id i)))) (map (juxt :id :transaction-date)) last)))) result (reconciliations/update updated)] (is (invalid? result [:balance] "Balance must match the calculated balance")))) (deftest a-completed-reconciliation-cannot-be-updated (let [context (realize existing-reconciliation-context) reconciliation (-> context :reconciliations first) result (reconciliations/update (assoc reconciliation :end-of-period (t/local-date 2017 1 2))) retrieved (reconciliations/reload reconciliation)] (is (invalid? result [:status] "A completed reconciliation cannot be updated")) (is (= 1000M (:balance retrieved)) "The new value is not saved"))) (deftest the-most-recent-completed-reconciliation-can-be-deleted (let [context (realize existing-reconciliation-context) reconciliation (-> context :reconciliations first) _ (reconciliations/delete reconciliation) retrieved (reconciliations/find reconciliation) items (transactions/select-items-by-reconciliation reconciliation)] (is (nil? retrieved) "The reconciliation cannot be retrieved after delete") (is (empty? items) "The reconciliation is not associated with any items after delete"))) (deftest a-working-reconciliation-can-be-deleted (let [context (realize working-reconciliation-context) reconciliation (-> context :reconciliations second) _ (reconciliations/delete reconciliation) retrieved (reconciliations/find reconciliation) items (transactions/select-items-by-reconciliation reconciliation)] (is (nil? retrieved) "The reconciliation cannot be retrieved after delete") (is (empty? items) "The reconciliation is not associated with any items after delete"))) (deftest a-reconciliation-that-is-not-the-most-recent-cannot-be-deleted (let [context (realize working-reconciliation-context) reconciliation (-> context :reconciliations first)] (is (thrown-with-msg? Exception #"Only the most recent reconciliation may be deleted" (reconciliations/delete reconciliation)) "an exception should be thrown") (is (reconciliations/find reconciliation) "The reconciliation can still be retrieved") (is (seq (transactions/select-items-by-reconciliation reconciliation)) "The transaction items are still associated with the reconciliation"))) (deftest check-if-a-transaction-can-be-deleted (let [context (realize existing-reconciliation-context) [t1 t2] (->> context :transactions (take 2) (map transactions/reload))] (is (not (transactions/can-delete? t1)) "A transaction with a reconciled item cannot be deleted") (is (transactions/can-delete? t2) "A transaction with no reconciled items can be deleted")))
103851
(ns clj-money.models.reconciliations-test (:require [clojure.test :refer [deftest use-fixtures is testing]] [clj-time.core :as t] [dgknght.app-lib.test] [clj-money.test-helpers :refer [reset-db]] [clj-money.test-context :refer [realize basic-context find-recon find-account find-transaction-item]] [clj-money.models.reconciliations :as reconciliations] [clj-money.models.transactions :as transactions])) (use-fixtures :each reset-db) (def ^:private reconciliation-context {:users [{:email "<EMAIL>" :first-name "<NAME>" :last-name "<NAME>" :password "<PASSWORD>" :password-confirmation "<PASSWORD>"}] :entities [{:name "Personal"}] :commodities [{:name "US Dollar" :symbol "USD" :type :currency}] :accounts [{:name "Checking" :type :asset} {:name "Salary" :type :income} {:name "Rent" :type :expense} {:name "Groceries" :type :expense}] :transactions [{:transaction-date (t/local-date 2017 1 1) :description "Paycheck" :debit-account-id "Checking" :credit-account-id "Salary" :quantity 1000M} {:transaction-date (t/local-date 2017 1 2) :description "Landlord" :debit-account-id "Rent" :credit-account-id "Checking" :quantity 500M} {:transaction-date (t/local-date 2017 1 3) :description "Kroger" :debit-account-id "Groceries" :credit-account-id "Checking" :quantity 45M} {:transaction-date (t/local-date 2017 1 10) :description "Safeway" :debit-account-id "G<NAME>eries" :credit-account-id "Checking" :quantity 53M}]}) (def ^:private existing-reconciliation-context (assoc reconciliation-context :reconciliations [{:account-id "Checking" :end-of-period (t/local-date 2017 1 1) :balance 1000M :status :completed :item-refs [{:transaction-date (t/local-date 2017 1 1) :quantity 1000M}]}])) (def ^:private working-reconciliation-context (update-in existing-reconciliation-context [:reconciliations] #(conj % {:account-id "Checking" :end-of-period (t/local-date 2017 1 3) :balance 455M :status :new :item-refs [{:transaction-date (t/local-date 2017 1 2) :quantity 500M}]}))) (deftest create-a-reconciliation (let [context (realize reconciliation-context) checking (-> context :accounts first) reconciliation {:account-id (:id checking) :balance 447M :end-of-period (t/local-date 2017 1 31)} result (reconciliations/create reconciliation) retrieved (reconciliations/find-by {:account-id (:id checking)})] (is (valid? result)) (is retrieved "The reconciliation can be retrieved") (testing "transaction items are not marked as reconciled" (is (= #{false} (->> (:transactions context) (map transactions/reload) (mapcat :items) (filter #(= (:id checking) (:account-id %))) (map :reconciled?) set)) "None of the transaction items should be marked as reconcilied")))) (deftest create-a-completed-reconciliation (let [context (realize reconciliation-context) checking (-> context :accounts first) [paycheck landlord _ safeway] (->> context :transactions (mapcat :items) (filter #(= (:id checking) (:account-id %)))) reconciliation {:account-id (:id checking) :balance 447M :end-of-period (t/local-date 2017 1 31) :item-refs (map (juxt :id :transaction-date) [paycheck landlord safeway]) :status :completed} result (reconciliations/create reconciliation) retrieved (reconciliations/find-by {:account-id (:id checking)})] (is (valid? result)) (is retrieved "The reconciliation can be retrieved") (testing "transaction items are marked as reconciled" (is (= [true true false true] (->> (:transactions context) (map transactions/reload) (mapcat :items) (filter #(= (:id checking) (:account-id %))) (map :reconciled?))) "Each transaction item included in the reconciliation should be marked as reconciled")))) (deftest a-new-reconciliation-cannot-be-created-if-one-already-exists (let [context (realize working-reconciliation-context) checking (-> context :accounts first) result (reconciliations/create {:account-id (:id checking) :balance 1M :status :new :end-of-period (t/local-date 2017 2 28)})] (is (invalid? result [:account-id] "Account already has a reconciliation in progress")))) (deftest account-id-is-required (let [context (realize reconciliation-context) checking (-> context :accounts first) [paycheck landlord _ safeway] (->> context :transactions (mapcat :items) (filter #(= (:id checking) (:account-id %)))) result (reconciliations/create {:balance 447M :item-refs (map (juxt :id :transaction-date) [paycheck landlord safeway])})] (is (invalid? result [:account-id] "Account is required")))) (deftest end-of-period-is-required (let [context (realize reconciliation-context) checking (-> context :accounts first) [paycheck landlord _ safeway] (->> context :transactions (mapcat :items) (filter #(= (:id checking) (:account-id %)))) result (reconciliations/create {:balance 447M :item-refs (map (juxt :id :transaction-date) [paycheck landlord safeway])})] (is (invalid? result [:end-of-period] "End of period is required")))) (deftest end-of-period-must-come-after-the-previous-end-of-period (let [context (realize existing-reconciliation-context) checking (-> context :accounts first) reconciliation {:account-id (:id checking) :balance 447M :end-of-period (t/local-date 2016 12 31)} result (reconciliations/create reconciliation)] (is (invalid? result [:end-of-period] "End of period must be after that latest reconciliation")))) (deftest status-must-be-new-or-completed (let [context (realize reconciliation-context) checking (-> context :accounts first) [paycheck landlord _ safeway] (->> context :transactions (mapcat :items) (filter #(= (:id checking) (:account-id %)))) result (reconciliations/create {:account-id (:id checking) :end-of-period (t/local-date 2017 1 31) :status :bouncy :balance 447M :item-refs (map (juxt :id :transaction-date) [paycheck landlord safeway])})] (is (invalid? result [:status] "Status must be new or completed")))) (deftest item-refs-cannot-reference-items-that-belong-to-the-account-being-reconciled (let [context (realize reconciliation-context) [checking salary] (:accounts context) paycheck (->> context :transactions (mapcat :items) (filter #(= (:id salary) (:account-id %))) first) result (reconciliations/create {:account-id (:id checking) :end-of-period (t/local-date 2017 1 31) :balance 10M :item-refs [((juxt :id :transaction-date) paycheck)]})] (is (invalid? result [:item-refs] "All items must belong to the account being reconciled")))) (def ^:private parent-account-context (-> basic-context (update-in [:accounts] concat [{:name "Savings" :type :asset :entity-id "Personal"} {:name "Car" :type :asset :entity-id "Personal" :parent-id "Savings"} {:name "Reserve" :type :asset :entity-id "Personal" :parent-id "Savings"}]) (assoc :transactions [{:transaction-date (t/local-date 2015 1 1) :description "Paycheck" :items [{:action :credit :account-id "Salary" :quantity 1000M} {:action :debit :account-id "Car" :quantity 100M} {:action :debit :account-id "Reserve" :quantity 200M} {:action :debit :account-id "Checking" :quantity 700M}]}]))) (deftest item-refs-can-reference-items-that-belong-to-children-of-the-account-being-reconciled (let [ctx (realize parent-account-context) account (find-account ctx "Savings") items (transactions/search-items {:account-id (:id account) :transaction-date [:between (t/local-date 2015 1 1) (t/local-date 2015 1 31)]} {:include-children? true}) result (reconciliations/create {:account-id (:id account) :end-of-period (t/local-date 2015 1 31) :status :completed :balance 300M :item-refs (map (juxt :id :transaction-date) items)})] (is (valid? result)))) (def ^:private working-rec-context (assoc reconciliation-context :reconciliations [{:account-id "Checking" :end-of-period (t/local-date 2017 1 1) :balance 447M :status :new :item-refs [{:transaction-date (t/local-date 2017 1 1) :account-id "Salary" :quantity 1000M} {:transaction-date (t/local-date 2017 1 2) :account-id "Rent" :quantity 500M} {:transaction-date (t/local-date 2017 1 10) :account-id "Groceries" :quantity 53M}]}])) (deftest find-the-working-reconciliation (let [context (realize working-rec-context) checking (-> context :accounts first) reconciliation (reconciliations/find-working (:id checking))] (is reconciliation "A reconciliation is returned"))) (deftest transaction-item-can-only-belong-to-one-reconciliation (let [context (realize existing-reconciliation-context) checking (find-account context "Checking") item (->> (:transactions context) (mapcat :items) (filter #(= (:id checking) (:account-id %))) first) result (reconciliations/create {:account-id (:id checking) :end-of-period (t/local-date 2017 1 31) :balance 1500M :item-refs [((juxt :id :transaction-date) item)]})] (is (invalid? result [:item-refs] "No item can belong to another reconciliation")))) (deftest a-working-reconciliation-can-be-updated (let [context (realize working-reconciliation-context) recon (-> context :reconciliations last) result (reconciliations/update (assoc recon :balance 1499M)) retrieved (reconciliations/find recon)] (is (valid? result)) (is (= 1499M (:balance retrieved)) "The retrieved value has the correct balance after update"))) (deftest a-working-reconciliation-can-be-completed (let [context (realize working-reconciliation-context) previous-rec (find-recon context "Checking" (t/local-date 2017 1 1)) reconciliation (find-recon context "Checking" (t/local-date 2017 1 3)) checking (find-account context "Checking") item (find-transaction-item context (t/local-date 2017 1 3) 45M (:id checking)) updated (-> reconciliation (assoc :status :completed) (update-in [:item-refs] conj ((juxt :id :transaction-date) item))) result (reconciliations/update updated) retrieved (reconciliations/reload updated) checking-items (transactions/search-items {:account-id (:id checking) :transaction-date "2017"} {:sort [:transaction-date]})] (is (valid? result)) (is (= (:status retrieved) :completed) "The retrieved value has the correct satus") (testing "reconciled transaction items" (let [expected [{:transaction-date (t/local-date 2017 1 1) :quantity 1000M :reconciliation-id (:id previous-rec)} {:transaction-date (t/local-date 2017 1 2) :quantity 500M :reconciliation-id (:id retrieved)} {:transaction-date (t/local-date 2017 1 3) :quantity 45M :reconciliation-id (:id retrieved)} {:transaction-date (t/local-date 2017 1 10) :quantity 53M :reconciliation-id nil}] actual (map #(select-keys % [:transaction-date :quantity :reconciliation-id]) checking-items)] (is (= expected actual) "The correct transaction items are associated with the reconciliation"))))) (deftest cannot-create-a-completed-out-of-balance-reconciliation (let [context (realize reconciliation-context) checking (find-account context "Checking") result (reconciliations/create {:account-id (:id checking) :end-of-period (t/local-date 2017 1 31) :balance 101M :status :completed})] (is (invalid? result [:balance] "Balance must match the calculated balance")))) (deftest an-out-of-balance-reconciliation-cannot-be-updated-to-completed (let [context (realize working-reconciliation-context) checking (-> context :accounts first) reconciliation (-> context :reconciliations last) updated (-> reconciliation (assoc :status :completed) (update-in [:item-refs] #(conj % (->> context :transactions (mapcat :items) (filter (fn [i] (= (:id checking) (:account-id i)))) (map (juxt :id :transaction-date)) last)))) result (reconciliations/update updated)] (is (invalid? result [:balance] "Balance must match the calculated balance")))) (deftest a-completed-reconciliation-cannot-be-updated (let [context (realize existing-reconciliation-context) reconciliation (-> context :reconciliations first) result (reconciliations/update (assoc reconciliation :end-of-period (t/local-date 2017 1 2))) retrieved (reconciliations/reload reconciliation)] (is (invalid? result [:status] "A completed reconciliation cannot be updated")) (is (= 1000M (:balance retrieved)) "The new value is not saved"))) (deftest the-most-recent-completed-reconciliation-can-be-deleted (let [context (realize existing-reconciliation-context) reconciliation (-> context :reconciliations first) _ (reconciliations/delete reconciliation) retrieved (reconciliations/find reconciliation) items (transactions/select-items-by-reconciliation reconciliation)] (is (nil? retrieved) "The reconciliation cannot be retrieved after delete") (is (empty? items) "The reconciliation is not associated with any items after delete"))) (deftest a-working-reconciliation-can-be-deleted (let [context (realize working-reconciliation-context) reconciliation (-> context :reconciliations second) _ (reconciliations/delete reconciliation) retrieved (reconciliations/find reconciliation) items (transactions/select-items-by-reconciliation reconciliation)] (is (nil? retrieved) "The reconciliation cannot be retrieved after delete") (is (empty? items) "The reconciliation is not associated with any items after delete"))) (deftest a-reconciliation-that-is-not-the-most-recent-cannot-be-deleted (let [context (realize working-reconciliation-context) reconciliation (-> context :reconciliations first)] (is (thrown-with-msg? Exception #"Only the most recent reconciliation may be deleted" (reconciliations/delete reconciliation)) "an exception should be thrown") (is (reconciliations/find reconciliation) "The reconciliation can still be retrieved") (is (seq (transactions/select-items-by-reconciliation reconciliation)) "The transaction items are still associated with the reconciliation"))) (deftest check-if-a-transaction-can-be-deleted (let [context (realize existing-reconciliation-context) [t1 t2] (->> context :transactions (take 2) (map transactions/reload))] (is (not (transactions/can-delete? t1)) "A transaction with a reconciled item cannot be deleted") (is (transactions/can-delete? t2) "A transaction with no reconciled items can be deleted")))
true
(ns clj-money.models.reconciliations-test (:require [clojure.test :refer [deftest use-fixtures is testing]] [clj-time.core :as t] [dgknght.app-lib.test] [clj-money.test-helpers :refer [reset-db]] [clj-money.test-context :refer [realize basic-context find-recon find-account find-transaction-item]] [clj-money.models.reconciliations :as reconciliations] [clj-money.models.transactions :as transactions])) (use-fixtures :each reset-db) (def ^:private reconciliation-context {:users [{:email "PI:EMAIL:<EMAIL>END_PI" :first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :password "PI:PASSWORD:<PASSWORD>END_PI" :password-confirmation "PI:PASSWORD:<PASSWORD>END_PI"}] :entities [{:name "Personal"}] :commodities [{:name "US Dollar" :symbol "USD" :type :currency}] :accounts [{:name "Checking" :type :asset} {:name "Salary" :type :income} {:name "Rent" :type :expense} {:name "Groceries" :type :expense}] :transactions [{:transaction-date (t/local-date 2017 1 1) :description "Paycheck" :debit-account-id "Checking" :credit-account-id "Salary" :quantity 1000M} {:transaction-date (t/local-date 2017 1 2) :description "Landlord" :debit-account-id "Rent" :credit-account-id "Checking" :quantity 500M} {:transaction-date (t/local-date 2017 1 3) :description "Kroger" :debit-account-id "Groceries" :credit-account-id "Checking" :quantity 45M} {:transaction-date (t/local-date 2017 1 10) :description "Safeway" :debit-account-id "GPI:NAME:<NAME>END_PIeries" :credit-account-id "Checking" :quantity 53M}]}) (def ^:private existing-reconciliation-context (assoc reconciliation-context :reconciliations [{:account-id "Checking" :end-of-period (t/local-date 2017 1 1) :balance 1000M :status :completed :item-refs [{:transaction-date (t/local-date 2017 1 1) :quantity 1000M}]}])) (def ^:private working-reconciliation-context (update-in existing-reconciliation-context [:reconciliations] #(conj % {:account-id "Checking" :end-of-period (t/local-date 2017 1 3) :balance 455M :status :new :item-refs [{:transaction-date (t/local-date 2017 1 2) :quantity 500M}]}))) (deftest create-a-reconciliation (let [context (realize reconciliation-context) checking (-> context :accounts first) reconciliation {:account-id (:id checking) :balance 447M :end-of-period (t/local-date 2017 1 31)} result (reconciliations/create reconciliation) retrieved (reconciliations/find-by {:account-id (:id checking)})] (is (valid? result)) (is retrieved "The reconciliation can be retrieved") (testing "transaction items are not marked as reconciled" (is (= #{false} (->> (:transactions context) (map transactions/reload) (mapcat :items) (filter #(= (:id checking) (:account-id %))) (map :reconciled?) set)) "None of the transaction items should be marked as reconcilied")))) (deftest create-a-completed-reconciliation (let [context (realize reconciliation-context) checking (-> context :accounts first) [paycheck landlord _ safeway] (->> context :transactions (mapcat :items) (filter #(= (:id checking) (:account-id %)))) reconciliation {:account-id (:id checking) :balance 447M :end-of-period (t/local-date 2017 1 31) :item-refs (map (juxt :id :transaction-date) [paycheck landlord safeway]) :status :completed} result (reconciliations/create reconciliation) retrieved (reconciliations/find-by {:account-id (:id checking)})] (is (valid? result)) (is retrieved "The reconciliation can be retrieved") (testing "transaction items are marked as reconciled" (is (= [true true false true] (->> (:transactions context) (map transactions/reload) (mapcat :items) (filter #(= (:id checking) (:account-id %))) (map :reconciled?))) "Each transaction item included in the reconciliation should be marked as reconciled")))) (deftest a-new-reconciliation-cannot-be-created-if-one-already-exists (let [context (realize working-reconciliation-context) checking (-> context :accounts first) result (reconciliations/create {:account-id (:id checking) :balance 1M :status :new :end-of-period (t/local-date 2017 2 28)})] (is (invalid? result [:account-id] "Account already has a reconciliation in progress")))) (deftest account-id-is-required (let [context (realize reconciliation-context) checking (-> context :accounts first) [paycheck landlord _ safeway] (->> context :transactions (mapcat :items) (filter #(= (:id checking) (:account-id %)))) result (reconciliations/create {:balance 447M :item-refs (map (juxt :id :transaction-date) [paycheck landlord safeway])})] (is (invalid? result [:account-id] "Account is required")))) (deftest end-of-period-is-required (let [context (realize reconciliation-context) checking (-> context :accounts first) [paycheck landlord _ safeway] (->> context :transactions (mapcat :items) (filter #(= (:id checking) (:account-id %)))) result (reconciliations/create {:balance 447M :item-refs (map (juxt :id :transaction-date) [paycheck landlord safeway])})] (is (invalid? result [:end-of-period] "End of period is required")))) (deftest end-of-period-must-come-after-the-previous-end-of-period (let [context (realize existing-reconciliation-context) checking (-> context :accounts first) reconciliation {:account-id (:id checking) :balance 447M :end-of-period (t/local-date 2016 12 31)} result (reconciliations/create reconciliation)] (is (invalid? result [:end-of-period] "End of period must be after that latest reconciliation")))) (deftest status-must-be-new-or-completed (let [context (realize reconciliation-context) checking (-> context :accounts first) [paycheck landlord _ safeway] (->> context :transactions (mapcat :items) (filter #(= (:id checking) (:account-id %)))) result (reconciliations/create {:account-id (:id checking) :end-of-period (t/local-date 2017 1 31) :status :bouncy :balance 447M :item-refs (map (juxt :id :transaction-date) [paycheck landlord safeway])})] (is (invalid? result [:status] "Status must be new or completed")))) (deftest item-refs-cannot-reference-items-that-belong-to-the-account-being-reconciled (let [context (realize reconciliation-context) [checking salary] (:accounts context) paycheck (->> context :transactions (mapcat :items) (filter #(= (:id salary) (:account-id %))) first) result (reconciliations/create {:account-id (:id checking) :end-of-period (t/local-date 2017 1 31) :balance 10M :item-refs [((juxt :id :transaction-date) paycheck)]})] (is (invalid? result [:item-refs] "All items must belong to the account being reconciled")))) (def ^:private parent-account-context (-> basic-context (update-in [:accounts] concat [{:name "Savings" :type :asset :entity-id "Personal"} {:name "Car" :type :asset :entity-id "Personal" :parent-id "Savings"} {:name "Reserve" :type :asset :entity-id "Personal" :parent-id "Savings"}]) (assoc :transactions [{:transaction-date (t/local-date 2015 1 1) :description "Paycheck" :items [{:action :credit :account-id "Salary" :quantity 1000M} {:action :debit :account-id "Car" :quantity 100M} {:action :debit :account-id "Reserve" :quantity 200M} {:action :debit :account-id "Checking" :quantity 700M}]}]))) (deftest item-refs-can-reference-items-that-belong-to-children-of-the-account-being-reconciled (let [ctx (realize parent-account-context) account (find-account ctx "Savings") items (transactions/search-items {:account-id (:id account) :transaction-date [:between (t/local-date 2015 1 1) (t/local-date 2015 1 31)]} {:include-children? true}) result (reconciliations/create {:account-id (:id account) :end-of-period (t/local-date 2015 1 31) :status :completed :balance 300M :item-refs (map (juxt :id :transaction-date) items)})] (is (valid? result)))) (def ^:private working-rec-context (assoc reconciliation-context :reconciliations [{:account-id "Checking" :end-of-period (t/local-date 2017 1 1) :balance 447M :status :new :item-refs [{:transaction-date (t/local-date 2017 1 1) :account-id "Salary" :quantity 1000M} {:transaction-date (t/local-date 2017 1 2) :account-id "Rent" :quantity 500M} {:transaction-date (t/local-date 2017 1 10) :account-id "Groceries" :quantity 53M}]}])) (deftest find-the-working-reconciliation (let [context (realize working-rec-context) checking (-> context :accounts first) reconciliation (reconciliations/find-working (:id checking))] (is reconciliation "A reconciliation is returned"))) (deftest transaction-item-can-only-belong-to-one-reconciliation (let [context (realize existing-reconciliation-context) checking (find-account context "Checking") item (->> (:transactions context) (mapcat :items) (filter #(= (:id checking) (:account-id %))) first) result (reconciliations/create {:account-id (:id checking) :end-of-period (t/local-date 2017 1 31) :balance 1500M :item-refs [((juxt :id :transaction-date) item)]})] (is (invalid? result [:item-refs] "No item can belong to another reconciliation")))) (deftest a-working-reconciliation-can-be-updated (let [context (realize working-reconciliation-context) recon (-> context :reconciliations last) result (reconciliations/update (assoc recon :balance 1499M)) retrieved (reconciliations/find recon)] (is (valid? result)) (is (= 1499M (:balance retrieved)) "The retrieved value has the correct balance after update"))) (deftest a-working-reconciliation-can-be-completed (let [context (realize working-reconciliation-context) previous-rec (find-recon context "Checking" (t/local-date 2017 1 1)) reconciliation (find-recon context "Checking" (t/local-date 2017 1 3)) checking (find-account context "Checking") item (find-transaction-item context (t/local-date 2017 1 3) 45M (:id checking)) updated (-> reconciliation (assoc :status :completed) (update-in [:item-refs] conj ((juxt :id :transaction-date) item))) result (reconciliations/update updated) retrieved (reconciliations/reload updated) checking-items (transactions/search-items {:account-id (:id checking) :transaction-date "2017"} {:sort [:transaction-date]})] (is (valid? result)) (is (= (:status retrieved) :completed) "The retrieved value has the correct satus") (testing "reconciled transaction items" (let [expected [{:transaction-date (t/local-date 2017 1 1) :quantity 1000M :reconciliation-id (:id previous-rec)} {:transaction-date (t/local-date 2017 1 2) :quantity 500M :reconciliation-id (:id retrieved)} {:transaction-date (t/local-date 2017 1 3) :quantity 45M :reconciliation-id (:id retrieved)} {:transaction-date (t/local-date 2017 1 10) :quantity 53M :reconciliation-id nil}] actual (map #(select-keys % [:transaction-date :quantity :reconciliation-id]) checking-items)] (is (= expected actual) "The correct transaction items are associated with the reconciliation"))))) (deftest cannot-create-a-completed-out-of-balance-reconciliation (let [context (realize reconciliation-context) checking (find-account context "Checking") result (reconciliations/create {:account-id (:id checking) :end-of-period (t/local-date 2017 1 31) :balance 101M :status :completed})] (is (invalid? result [:balance] "Balance must match the calculated balance")))) (deftest an-out-of-balance-reconciliation-cannot-be-updated-to-completed (let [context (realize working-reconciliation-context) checking (-> context :accounts first) reconciliation (-> context :reconciliations last) updated (-> reconciliation (assoc :status :completed) (update-in [:item-refs] #(conj % (->> context :transactions (mapcat :items) (filter (fn [i] (= (:id checking) (:account-id i)))) (map (juxt :id :transaction-date)) last)))) result (reconciliations/update updated)] (is (invalid? result [:balance] "Balance must match the calculated balance")))) (deftest a-completed-reconciliation-cannot-be-updated (let [context (realize existing-reconciliation-context) reconciliation (-> context :reconciliations first) result (reconciliations/update (assoc reconciliation :end-of-period (t/local-date 2017 1 2))) retrieved (reconciliations/reload reconciliation)] (is (invalid? result [:status] "A completed reconciliation cannot be updated")) (is (= 1000M (:balance retrieved)) "The new value is not saved"))) (deftest the-most-recent-completed-reconciliation-can-be-deleted (let [context (realize existing-reconciliation-context) reconciliation (-> context :reconciliations first) _ (reconciliations/delete reconciliation) retrieved (reconciliations/find reconciliation) items (transactions/select-items-by-reconciliation reconciliation)] (is (nil? retrieved) "The reconciliation cannot be retrieved after delete") (is (empty? items) "The reconciliation is not associated with any items after delete"))) (deftest a-working-reconciliation-can-be-deleted (let [context (realize working-reconciliation-context) reconciliation (-> context :reconciliations second) _ (reconciliations/delete reconciliation) retrieved (reconciliations/find reconciliation) items (transactions/select-items-by-reconciliation reconciliation)] (is (nil? retrieved) "The reconciliation cannot be retrieved after delete") (is (empty? items) "The reconciliation is not associated with any items after delete"))) (deftest a-reconciliation-that-is-not-the-most-recent-cannot-be-deleted (let [context (realize working-reconciliation-context) reconciliation (-> context :reconciliations first)] (is (thrown-with-msg? Exception #"Only the most recent reconciliation may be deleted" (reconciliations/delete reconciliation)) "an exception should be thrown") (is (reconciliations/find reconciliation) "The reconciliation can still be retrieved") (is (seq (transactions/select-items-by-reconciliation reconciliation)) "The transaction items are still associated with the reconciliation"))) (deftest check-if-a-transaction-can-be-deleted (let [context (realize existing-reconciliation-context) [t1 t2] (->> context :transactions (take 2) (map transactions/reload))] (is (not (transactions/can-delete? t1)) "A transaction with a reconciled item cannot be deleted") (is (transactions/can-delete? t2) "A transaction with no reconciled items can be deleted")))
[ { "context": "rigan.components.thymeleaf.interface\n {:author [\"David Harrigan\"]}\n (:require\n [online.harrigan.components.thy", "end": 78, "score": 0.9998859167098999, "start": 64, "tag": "NAME", "value": "David Harrigan" } ]
src/online/harrigan/components/thymeleaf/interface.clj
dharrigan/unresolved-var
0
(ns online.harrigan.components.thymeleaf.interface {:author ["David Harrigan"]} (:require [online.harrigan.components.thymeleaf.impl :as thymeleaf])) (set! *warn-on-reflection* true) (defn render ([viewname app-config] (render viewname nil app-config)) ([viewname data app-config] (thymeleaf/render viewname data app-config)))
67326
(ns online.harrigan.components.thymeleaf.interface {:author ["<NAME>"]} (:require [online.harrigan.components.thymeleaf.impl :as thymeleaf])) (set! *warn-on-reflection* true) (defn render ([viewname app-config] (render viewname nil app-config)) ([viewname data app-config] (thymeleaf/render viewname data app-config)))
true
(ns online.harrigan.components.thymeleaf.interface {:author ["PI:NAME:<NAME>END_PI"]} (:require [online.harrigan.components.thymeleaf.impl :as thymeleaf])) (set! *warn-on-reflection* true) (defn render ([viewname app-config] (render viewname nil app-config)) ([viewname data app-config] (thymeleaf/render viewname data app-config)))
[ { "context": "bulary is in module vocab.clj.\n;;;\n;;; Programmer: J van Donsel\n;;; December, 2016\n;;;\n(ns haiku.core\n (:require", "end": 132, "score": 0.9998543858528137, "start": 120, "tag": "NAME", "value": "J van Donsel" } ]
src/haiku/core.clj
jvandonsel/haiku
0
;;; Random haiku generator, using a simple sentence grammar. ;;; Vocabulary is in module vocab.clj. ;;; ;;; Programmer: J van Donsel ;;; December, 2016 ;;; (ns haiku.core (:require [clojure.string :as str]) (:use [haiku.vocab]) ) (defn pluralize-noun [w] (if (coll? w) (map pluralize-noun w) (if (contains? irregular-plurals w) (irregular-plurals w) (str/join (concat w "s"))) ) ) (defn pluralize-verb [w] (if (coll? w) (map pluralize-verb w) (if (contains? irregular-plurals w) (irregular-plurals w) (str/join (drop-last w))) ) ) ;; Applies function f to all values of the given map (defn update-map [m f] (reduce-kv (fn [acc k v] (assoc acc k (f v))) {} m) ) ;; Pluralization (def verbs-p-trans-map (update-map verbs-s-trans-map pluralize-verb)) (def verbs-p-trans (flatten (vals verbs-p-trans-map))) (def verbs-p-intrans-map (update-map verbs-s-intrans-map pluralize-verb)) (def verbs-p-intrans (flatten (vals verbs-p-intrans-map))) (def nouns-p-map (update-map nouns-s-map pluralize-noun) ) (def nouns-p (flatten (vals nouns-p-map))) ;; Chooses a random element from coll (defn CHOOSE-1 [coll] (rand-nth coll)) ;; chooses a random element from xs, where each element of xs contains [probability value] (defn CHOOSE-1-WEIGHTED [xs] (let [ ;; accumulate the weights stacked (reductions (fn [a b] [(+ (first a) (first b)) (second b)] ) xs) ;; pick a random value between 0.0 and 1.0 r (rand) ;; find the first accumulated weight over the random number x (first (filter #(> (first %) r) stacked)) ] (second x) ) ) ;; randomly either returns x or "". ;; p is probability of "" (defn OPT [p x] (if (< (rand) p) x "") ) ;; Grammar (defn gram-noun-phrase-singular [] [(CHOOSE-1 articles) (OPT 0.33 (CHOOSE-1 adjectives)) (CHOOSE-1 nouns-s)]) (defn gram-noun-phrase-singleton [] (CHOOSE-1 singleton-nouns)) (defn gram-noun-phrase-plural [] [(OPT 0.33 (CHOOSE-1 articles-plural)) (OPT 0.33 (CHOOSE-1 adjectives)) (CHOOSE-1 nouns-p)]) (defn gram-object-phrase [] (CHOOSE-1-WEIGHTED [[0.40 (gram-noun-phrase-singular)] [0.40 (gram-noun-phrase-plural)] [0.2 (gram-noun-phrase-singleton)]])) (defn gram-verb-phrase-sing-trans [] [(CHOOSE-1 verbs-s-trans) (gram-object-phrase) (OPT 0.33 (CHOOSE-1 adverbs))]) (defn gram-verb-phrase-sing-intrans [] [(CHOOSE-1 verbs-s-intrans) (OPT 0.33 (CHOOSE-1 adverbs))]) (defn gram-verb-phrase-sing [] (CHOOSE-1 [(gram-verb-phrase-sing-trans) (gram-verb-phrase-sing-intrans)])) (defn gram-verb-phrase-plural-trans [] [(CHOOSE-1 verbs-p-trans) (gram-object-phrase)]) (defn gram-verb-phrase-plural-intrans [] (CHOOSE-1 verbs-p-intrans)) (defn gram-verb-phrase-plural [] (CHOOSE-1 [(gram-verb-phrase-plural-trans) (gram-verb-phrase-plural-intrans)])) (defn gram-line [] (CHOOSE-1 [ [(gram-noun-phrase-singular) (gram-verb-phrase-sing)] [(gram-noun-phrase-plural) (gram-verb-phrase-plural)] [(gram-noun-phrase-singleton) (gram-verb-phrase-sing)] ])) ;; Given a scalar k and a collection, ;; generates a map of coll[0]->k, coll[1]->k... (defn gen-map [k coll] ( let [ lc (map str/lower-case coll) ;; generate [lc[0] k lc[1] k ...] kvs (concat (interpose k lc) [k]) ] (apply array-map kvs ) )) ;; Given a map of syllables to word lists, inverts the map ;; to generate a map of word to syllable count. (defn invert-word-map [m] (let [] (reduce-kv (fn [acc syllable-count words] (merge acc (gen-map syllable-count words))) {} m)) ) ;; Create a map of all words to their syllable counts. (def all-words ( merge (invert-word-map adjectives-map) (invert-word-map nouns-s-map) (invert-word-map nouns-p-map) (invert-word-map verbs-s-intrans-map) (invert-word-map verbs-s-trans-map) (invert-word-map verbs-p-intrans-map) (invert-word-map verbs-p-trans-map) (invert-word-map articles-map) (invert-word-map articles-plural-map) (invert-word-map singleton-nouns-map) (invert-word-map adverbs-map) ;; "an" doesn't appear in the articles list. it's applied in post-processing, but we need a syllable count for it. {"an" 1} )) ;; Returns the number of syllables for the given word (defn get-syllables [word] (let [lookup (get all-words (str/lower-case word))] (if (nil? lookup) 0 lookup) ) ) ;; Count the number of syllables in a sentence (a list of words) (defn count-sentence-syllables [words] (reduce + 0 (map get-syllables words))) (defn starts-with-vowel [word] (contains? #{"a" "e" "i" "o" "u"} (str/lower-case (first word)))) ;; Returns true if this word should use "an" instead of "a" (defn needs-an [word] (or (starts-with-vowel word) (contains? use-an word))) (defn remove-blanks [line] (remove empty? line)) ;; Change 'a' to 'an' if the next word starts with a vowel ;; or is in our set of words forced to use "an". (defn a-to-an [line] (let [n (count line)] (map-indexed (fn [i val] (let [done (>= i (dec n)) next-val (when-not done (nth line (inc i))) ] (if (= "a" val) (if (needs-an next-val) "an" "a") val) )) line ))) ;; Capitalizes the first letter of a word ;; (Don't use str/capitalize. It munges the case of the other letters.) (defn capitalize-word [word] (let [first-letter (first word) ] (str/join (cons (str/upper-case first-letter) (rest word))) ) ) ;; Capitalizes the first word in a line (defn capitalize-line [words] (let [ updated-word (capitalize-word (first words)) capitalized (cons updated-word (rest words)) ] capitalized ) ) ;; Some post-processing after creating our haiku (defn post-process-line [line] (let [ ;; get rid of empty words non-empty (remove-blanks line) ;; change 'a' to 'an' if the next word starts with a vowel fixed-articles (a-to-an non-empty) ] ;; capitalize first letter of line (capitalize-line fixed-articles) )) ;; Creates a single line from the given grammar function, respecting the syllable target. (defn create-line [gram syllable-target] (let [raw-line (flatten (gram)) clean-line (post-process-line raw-line) k (count-sentence-syllables clean-line)] ;; Brute force: if we didn't hit our syllable target, try again! (if (= syllable-target k) clean-line (recur gram syllable-target) ) )) ; Creates a haiku, 3 lines with syllable counts of 5,7,5. (defn create-haiku [] (let [ line1 (create-line gram-line 5) line2 (create-line gram-line 7) line3 (create-line gram-line 5) ] (list (str/join " " line1) (str/join " " line2) (str/join " " line3)) )) ;; Prints out each haiku line (defn -main [] (doall (map println (create-haiku))) nil )
69963
;;; Random haiku generator, using a simple sentence grammar. ;;; Vocabulary is in module vocab.clj. ;;; ;;; Programmer: <NAME> ;;; December, 2016 ;;; (ns haiku.core (:require [clojure.string :as str]) (:use [haiku.vocab]) ) (defn pluralize-noun [w] (if (coll? w) (map pluralize-noun w) (if (contains? irregular-plurals w) (irregular-plurals w) (str/join (concat w "s"))) ) ) (defn pluralize-verb [w] (if (coll? w) (map pluralize-verb w) (if (contains? irregular-plurals w) (irregular-plurals w) (str/join (drop-last w))) ) ) ;; Applies function f to all values of the given map (defn update-map [m f] (reduce-kv (fn [acc k v] (assoc acc k (f v))) {} m) ) ;; Pluralization (def verbs-p-trans-map (update-map verbs-s-trans-map pluralize-verb)) (def verbs-p-trans (flatten (vals verbs-p-trans-map))) (def verbs-p-intrans-map (update-map verbs-s-intrans-map pluralize-verb)) (def verbs-p-intrans (flatten (vals verbs-p-intrans-map))) (def nouns-p-map (update-map nouns-s-map pluralize-noun) ) (def nouns-p (flatten (vals nouns-p-map))) ;; Chooses a random element from coll (defn CHOOSE-1 [coll] (rand-nth coll)) ;; chooses a random element from xs, where each element of xs contains [probability value] (defn CHOOSE-1-WEIGHTED [xs] (let [ ;; accumulate the weights stacked (reductions (fn [a b] [(+ (first a) (first b)) (second b)] ) xs) ;; pick a random value between 0.0 and 1.0 r (rand) ;; find the first accumulated weight over the random number x (first (filter #(> (first %) r) stacked)) ] (second x) ) ) ;; randomly either returns x or "". ;; p is probability of "" (defn OPT [p x] (if (< (rand) p) x "") ) ;; Grammar (defn gram-noun-phrase-singular [] [(CHOOSE-1 articles) (OPT 0.33 (CHOOSE-1 adjectives)) (CHOOSE-1 nouns-s)]) (defn gram-noun-phrase-singleton [] (CHOOSE-1 singleton-nouns)) (defn gram-noun-phrase-plural [] [(OPT 0.33 (CHOOSE-1 articles-plural)) (OPT 0.33 (CHOOSE-1 adjectives)) (CHOOSE-1 nouns-p)]) (defn gram-object-phrase [] (CHOOSE-1-WEIGHTED [[0.40 (gram-noun-phrase-singular)] [0.40 (gram-noun-phrase-plural)] [0.2 (gram-noun-phrase-singleton)]])) (defn gram-verb-phrase-sing-trans [] [(CHOOSE-1 verbs-s-trans) (gram-object-phrase) (OPT 0.33 (CHOOSE-1 adverbs))]) (defn gram-verb-phrase-sing-intrans [] [(CHOOSE-1 verbs-s-intrans) (OPT 0.33 (CHOOSE-1 adverbs))]) (defn gram-verb-phrase-sing [] (CHOOSE-1 [(gram-verb-phrase-sing-trans) (gram-verb-phrase-sing-intrans)])) (defn gram-verb-phrase-plural-trans [] [(CHOOSE-1 verbs-p-trans) (gram-object-phrase)]) (defn gram-verb-phrase-plural-intrans [] (CHOOSE-1 verbs-p-intrans)) (defn gram-verb-phrase-plural [] (CHOOSE-1 [(gram-verb-phrase-plural-trans) (gram-verb-phrase-plural-intrans)])) (defn gram-line [] (CHOOSE-1 [ [(gram-noun-phrase-singular) (gram-verb-phrase-sing)] [(gram-noun-phrase-plural) (gram-verb-phrase-plural)] [(gram-noun-phrase-singleton) (gram-verb-phrase-sing)] ])) ;; Given a scalar k and a collection, ;; generates a map of coll[0]->k, coll[1]->k... (defn gen-map [k coll] ( let [ lc (map str/lower-case coll) ;; generate [lc[0] k lc[1] k ...] kvs (concat (interpose k lc) [k]) ] (apply array-map kvs ) )) ;; Given a map of syllables to word lists, inverts the map ;; to generate a map of word to syllable count. (defn invert-word-map [m] (let [] (reduce-kv (fn [acc syllable-count words] (merge acc (gen-map syllable-count words))) {} m)) ) ;; Create a map of all words to their syllable counts. (def all-words ( merge (invert-word-map adjectives-map) (invert-word-map nouns-s-map) (invert-word-map nouns-p-map) (invert-word-map verbs-s-intrans-map) (invert-word-map verbs-s-trans-map) (invert-word-map verbs-p-intrans-map) (invert-word-map verbs-p-trans-map) (invert-word-map articles-map) (invert-word-map articles-plural-map) (invert-word-map singleton-nouns-map) (invert-word-map adverbs-map) ;; "an" doesn't appear in the articles list. it's applied in post-processing, but we need a syllable count for it. {"an" 1} )) ;; Returns the number of syllables for the given word (defn get-syllables [word] (let [lookup (get all-words (str/lower-case word))] (if (nil? lookup) 0 lookup) ) ) ;; Count the number of syllables in a sentence (a list of words) (defn count-sentence-syllables [words] (reduce + 0 (map get-syllables words))) (defn starts-with-vowel [word] (contains? #{"a" "e" "i" "o" "u"} (str/lower-case (first word)))) ;; Returns true if this word should use "an" instead of "a" (defn needs-an [word] (or (starts-with-vowel word) (contains? use-an word))) (defn remove-blanks [line] (remove empty? line)) ;; Change 'a' to 'an' if the next word starts with a vowel ;; or is in our set of words forced to use "an". (defn a-to-an [line] (let [n (count line)] (map-indexed (fn [i val] (let [done (>= i (dec n)) next-val (when-not done (nth line (inc i))) ] (if (= "a" val) (if (needs-an next-val) "an" "a") val) )) line ))) ;; Capitalizes the first letter of a word ;; (Don't use str/capitalize. It munges the case of the other letters.) (defn capitalize-word [word] (let [first-letter (first word) ] (str/join (cons (str/upper-case first-letter) (rest word))) ) ) ;; Capitalizes the first word in a line (defn capitalize-line [words] (let [ updated-word (capitalize-word (first words)) capitalized (cons updated-word (rest words)) ] capitalized ) ) ;; Some post-processing after creating our haiku (defn post-process-line [line] (let [ ;; get rid of empty words non-empty (remove-blanks line) ;; change 'a' to 'an' if the next word starts with a vowel fixed-articles (a-to-an non-empty) ] ;; capitalize first letter of line (capitalize-line fixed-articles) )) ;; Creates a single line from the given grammar function, respecting the syllable target. (defn create-line [gram syllable-target] (let [raw-line (flatten (gram)) clean-line (post-process-line raw-line) k (count-sentence-syllables clean-line)] ;; Brute force: if we didn't hit our syllable target, try again! (if (= syllable-target k) clean-line (recur gram syllable-target) ) )) ; Creates a haiku, 3 lines with syllable counts of 5,7,5. (defn create-haiku [] (let [ line1 (create-line gram-line 5) line2 (create-line gram-line 7) line3 (create-line gram-line 5) ] (list (str/join " " line1) (str/join " " line2) (str/join " " line3)) )) ;; Prints out each haiku line (defn -main [] (doall (map println (create-haiku))) nil )
true
;;; Random haiku generator, using a simple sentence grammar. ;;; Vocabulary is in module vocab.clj. ;;; ;;; Programmer: PI:NAME:<NAME>END_PI ;;; December, 2016 ;;; (ns haiku.core (:require [clojure.string :as str]) (:use [haiku.vocab]) ) (defn pluralize-noun [w] (if (coll? w) (map pluralize-noun w) (if (contains? irregular-plurals w) (irregular-plurals w) (str/join (concat w "s"))) ) ) (defn pluralize-verb [w] (if (coll? w) (map pluralize-verb w) (if (contains? irregular-plurals w) (irregular-plurals w) (str/join (drop-last w))) ) ) ;; Applies function f to all values of the given map (defn update-map [m f] (reduce-kv (fn [acc k v] (assoc acc k (f v))) {} m) ) ;; Pluralization (def verbs-p-trans-map (update-map verbs-s-trans-map pluralize-verb)) (def verbs-p-trans (flatten (vals verbs-p-trans-map))) (def verbs-p-intrans-map (update-map verbs-s-intrans-map pluralize-verb)) (def verbs-p-intrans (flatten (vals verbs-p-intrans-map))) (def nouns-p-map (update-map nouns-s-map pluralize-noun) ) (def nouns-p (flatten (vals nouns-p-map))) ;; Chooses a random element from coll (defn CHOOSE-1 [coll] (rand-nth coll)) ;; chooses a random element from xs, where each element of xs contains [probability value] (defn CHOOSE-1-WEIGHTED [xs] (let [ ;; accumulate the weights stacked (reductions (fn [a b] [(+ (first a) (first b)) (second b)] ) xs) ;; pick a random value between 0.0 and 1.0 r (rand) ;; find the first accumulated weight over the random number x (first (filter #(> (first %) r) stacked)) ] (second x) ) ) ;; randomly either returns x or "". ;; p is probability of "" (defn OPT [p x] (if (< (rand) p) x "") ) ;; Grammar (defn gram-noun-phrase-singular [] [(CHOOSE-1 articles) (OPT 0.33 (CHOOSE-1 adjectives)) (CHOOSE-1 nouns-s)]) (defn gram-noun-phrase-singleton [] (CHOOSE-1 singleton-nouns)) (defn gram-noun-phrase-plural [] [(OPT 0.33 (CHOOSE-1 articles-plural)) (OPT 0.33 (CHOOSE-1 adjectives)) (CHOOSE-1 nouns-p)]) (defn gram-object-phrase [] (CHOOSE-1-WEIGHTED [[0.40 (gram-noun-phrase-singular)] [0.40 (gram-noun-phrase-plural)] [0.2 (gram-noun-phrase-singleton)]])) (defn gram-verb-phrase-sing-trans [] [(CHOOSE-1 verbs-s-trans) (gram-object-phrase) (OPT 0.33 (CHOOSE-1 adverbs))]) (defn gram-verb-phrase-sing-intrans [] [(CHOOSE-1 verbs-s-intrans) (OPT 0.33 (CHOOSE-1 adverbs))]) (defn gram-verb-phrase-sing [] (CHOOSE-1 [(gram-verb-phrase-sing-trans) (gram-verb-phrase-sing-intrans)])) (defn gram-verb-phrase-plural-trans [] [(CHOOSE-1 verbs-p-trans) (gram-object-phrase)]) (defn gram-verb-phrase-plural-intrans [] (CHOOSE-1 verbs-p-intrans)) (defn gram-verb-phrase-plural [] (CHOOSE-1 [(gram-verb-phrase-plural-trans) (gram-verb-phrase-plural-intrans)])) (defn gram-line [] (CHOOSE-1 [ [(gram-noun-phrase-singular) (gram-verb-phrase-sing)] [(gram-noun-phrase-plural) (gram-verb-phrase-plural)] [(gram-noun-phrase-singleton) (gram-verb-phrase-sing)] ])) ;; Given a scalar k and a collection, ;; generates a map of coll[0]->k, coll[1]->k... (defn gen-map [k coll] ( let [ lc (map str/lower-case coll) ;; generate [lc[0] k lc[1] k ...] kvs (concat (interpose k lc) [k]) ] (apply array-map kvs ) )) ;; Given a map of syllables to word lists, inverts the map ;; to generate a map of word to syllable count. (defn invert-word-map [m] (let [] (reduce-kv (fn [acc syllable-count words] (merge acc (gen-map syllable-count words))) {} m)) ) ;; Create a map of all words to their syllable counts. (def all-words ( merge (invert-word-map adjectives-map) (invert-word-map nouns-s-map) (invert-word-map nouns-p-map) (invert-word-map verbs-s-intrans-map) (invert-word-map verbs-s-trans-map) (invert-word-map verbs-p-intrans-map) (invert-word-map verbs-p-trans-map) (invert-word-map articles-map) (invert-word-map articles-plural-map) (invert-word-map singleton-nouns-map) (invert-word-map adverbs-map) ;; "an" doesn't appear in the articles list. it's applied in post-processing, but we need a syllable count for it. {"an" 1} )) ;; Returns the number of syllables for the given word (defn get-syllables [word] (let [lookup (get all-words (str/lower-case word))] (if (nil? lookup) 0 lookup) ) ) ;; Count the number of syllables in a sentence (a list of words) (defn count-sentence-syllables [words] (reduce + 0 (map get-syllables words))) (defn starts-with-vowel [word] (contains? #{"a" "e" "i" "o" "u"} (str/lower-case (first word)))) ;; Returns true if this word should use "an" instead of "a" (defn needs-an [word] (or (starts-with-vowel word) (contains? use-an word))) (defn remove-blanks [line] (remove empty? line)) ;; Change 'a' to 'an' if the next word starts with a vowel ;; or is in our set of words forced to use "an". (defn a-to-an [line] (let [n (count line)] (map-indexed (fn [i val] (let [done (>= i (dec n)) next-val (when-not done (nth line (inc i))) ] (if (= "a" val) (if (needs-an next-val) "an" "a") val) )) line ))) ;; Capitalizes the first letter of a word ;; (Don't use str/capitalize. It munges the case of the other letters.) (defn capitalize-word [word] (let [first-letter (first word) ] (str/join (cons (str/upper-case first-letter) (rest word))) ) ) ;; Capitalizes the first word in a line (defn capitalize-line [words] (let [ updated-word (capitalize-word (first words)) capitalized (cons updated-word (rest words)) ] capitalized ) ) ;; Some post-processing after creating our haiku (defn post-process-line [line] (let [ ;; get rid of empty words non-empty (remove-blanks line) ;; change 'a' to 'an' if the next word starts with a vowel fixed-articles (a-to-an non-empty) ] ;; capitalize first letter of line (capitalize-line fixed-articles) )) ;; Creates a single line from the given grammar function, respecting the syllable target. (defn create-line [gram syllable-target] (let [raw-line (flatten (gram)) clean-line (post-process-line raw-line) k (count-sentence-syllables clean-line)] ;; Brute force: if we didn't hit our syllable target, try again! (if (= syllable-target k) clean-line (recur gram syllable-target) ) )) ; Creates a haiku, 3 lines with syllable counts of 5,7,5. (defn create-haiku [] (let [ line1 (create-line gram-line 5) line2 (create-line gram-line 7) line3 (create-line gram-line 5) ] (list (str/join " " line1) (str/join " " line2) (str/join " " line3)) )) ;; Prints out each haiku line (defn -main [] (doall (map println (create-haiku))) nil )
[ { "context": "ect constructor\n \n (write/from-empty {:name \\\"chris\\\" :pet \\\"dog\\\"}\n (fn [] (java", "end": 3394, "score": 0.9912582635879517, "start": 3389, "tag": "NAME", "value": "chris" }, { "context": "creates the object from a map\n \n (-> {:name \\\"chris\\\" :age 30 :pets [{:name \\\"slurp\\\" :species \\\"dog\\", "end": 4875, "score": 0.9874569177627563, "start": 4870, "tag": "NAME", "value": "chris" }, { "context": "read/to-data))\n => (contains-in\n {:name \\\"chris\\\",\n :age 30,\n :pets [{:name \\\"slurp", "end": 5096, "score": 0.9939290285110474, "start": 5091, "tag": "NAME", "value": "chris" } ]
src/hara/object/framework/write.clj
zcaudate/hara
309
(ns hara.object.framework.write (:require [clojure.walk :as walk] [hara.core.base.enum :as enum] [hara.data :as data] [hara.protocol.object :as protocol.object] [hara.object.query :as query] [hara.object.element.util :as element.util] [hara.string :as string] [hara.function :as fn :refer [definvoke]])) (def ^:dynamic *transform* nil) (defonce +write-template+ '(fn <method> [obj val] (or (. obj (<method> val)) obj))) (definvoke meta-write "access read-attributes with caching (write/meta-write DogBuilder) => (contains {:class test.DogBuilder :empty fn?, :methods (contains {:name (contains {:type java.lang.String, :fn fn?})})})" {:added "3.0"} [:memoize] ([^Class cls] (assoc (protocol.object/-meta-write cls) :class cls))) (declare from-data) (defn write-fields "write fields of an object from reflection (-> (write/write-fields Dog) keys) => [:name :species]" {:added "3.0"} ([cls] (write-fields cls query/query-class)) ([cls query-fn] (->> (query-fn cls [:field]) (reduce (fn [out ele] (let [k (-> ele :name string/spear-type keyword) cls (.getType (get-in ele [:all :delegate]))] (assoc out k {:type cls :fn ele}))) {})))) (defn write-all-fields "all write fields of an object from reflection (hara.object/.* {}) (-> (write/write-all-fields {}) keys) => [:-hash :-hasheq :-meta :array]" {:added "3.0"} [cls] (write-fields cls query/query-instance-hierarchy)) (defn create-write-method "create a write method from the template (-> ((-> (write/create-write-method (reflect/query-class Cat [\"setName\" :#]) \"set\" write/+write-template+) second :fn) (test.Cat. \"spike\") \"fluffy\") (.getName)) => \"fluffy\"" {:added "3.0"} [ele prefix template] [(-> (:name ele) (subs (count prefix)) string/spear-type keyword) {:type (-> ele :params second) :fn (eval (walk/postwalk-replace {'<method> (symbol (:name ele))} template))}]) (defn write-setters "write fields of an object through setter methods (write/write-setters Dog) => {} (keys (write/write-setters DogBuilder)) => [:name]" {:added "3.0"} ([cls] (write-setters cls {})) ([cls opts] (write-setters cls opts query/query-class)) ([cls {:keys [prefix template] :or {prefix "set" template +write-template+}} query-fn] (->> [:method :instance :public (re-pattern (str "^" prefix ".+")) 2] (query-fn cls) (reduce (fn [out ele] (conj out (create-write-method ele prefix template))) {})))) (defn write-all-setters "write all setters of an object and base classes (write/write-all-setters Dog) => {} (keys (write/write-all-setters DogBuilder)) => [:name]" {:added "3.0"} ([cls] (write-all-setters cls {})) ([cls opts] (write-setters cls opts query/query-hierarchy))) (defn from-empty "creates the object from an empty object constructor (write/from-empty {:name \"chris\" :pet \"dog\"} (fn [] (java.util.Hashtable.)) {:name {:type String :fn (fn [obj v] (.put obj \"hello\" (keyword v)) obj)} :pet {:type String :fn (fn [obj v] (.put obj \"pet\" (keyword v)) obj)}}) => {\"pet\" :dog, \"hello\" :chris}" {:added "3.0"} [m empty methods] (let [obj (empty)] (reduce-kv (fn [obj k v] (if-let [{:keys [type] func :fn} (get methods k)] (func obj (from-data v type)) obj)) obj m))) (defn from-constructor "creates the object from a constructor (-> {:name \"spike\"} (write/from-constructor {:fn (fn [name] (Cat. name)) :params [:name]} {})) ;;=> #test.Cat{:name \"spike\", :species \"cat\"} " {:added "3.0"} [m {:keys [params] :as construct} methods] (let [obj (apply (:fn construct) (map m params))] (reduce-kv (fn [obj k v] (if-let [{:keys [type] func :fn} (get methods k)] (func obj (from-data v type)) obj)) obj (apply dissoc m params)))) (defn from-map "creates the object from a map (-> {:name \"chris\" :age 30 :pets [{:name \"slurp\" :species \"dog\"} {:name \"happy\" :species \"cat\"}]} (write/from-map Person) (read/to-data)) => (contains-in {:name \"chris\", :age 30, :pets [{:name \"slurp\"} {:name \"happy\"}]})" {:added "3.0"} [m ^Class cls] (let [m (if-let [rels (get *transform* type)] (data/transform-in m rels) m) {:keys [construct empty methods from-map] :as mobj} (meta-write cls)] (cond from-map (from-map m) empty (from-empty m empty methods) construct (from-constructor m construct methods) :else (throw (ex-info "Cannot convert from map" {:data m :type cls}))))) (defn from-data "creates the object from data (-> (write/from-data [\"hello\"] (Class/forName \"[Ljava.lang.String;\")) seq) => [\"hello\"]" {:added "3.0"} [arg ^Class cls] (let [^Class targ (type arg)] (cond ;; If there is a direct match (or (element.util/param-arg-match cls targ) (element.util/param-float-match cls targ)) arg ;; Special case for String/CharArray (and (string? arg) (= cls (Class/forName "[C"))) (.toCharArray arg) ;; Special case for Enums (enum/enum? cls) (if (string? arg) (enum/to-enum arg cls) (throw (ex-info "Only strings supported for Enums" {:input arg :type cls}))) ;; If there is a vector (and (vector? arg) (.isArray cls)) (let [cls (.getComponentType cls)] (->> arg (map #(from-data % cls)) (into-array cls))) :else (let [{:keys [from-clojure from-string from-vector] :as mobj} (meta-write cls)] (cond from-clojure (from-clojure arg) ;; If input is a string and there is a from-string method (and (string? arg) from-string) (from-string arg) ;; If input is a string and there is a from-string method (and (vector? arg) from-vector) (from-vector arg) ;; If the input is a map (map? arg) (from-map arg cls) :else (throw (Exception. (format "Problem converting %s to %s" arg cls))))))))
9388
(ns hara.object.framework.write (:require [clojure.walk :as walk] [hara.core.base.enum :as enum] [hara.data :as data] [hara.protocol.object :as protocol.object] [hara.object.query :as query] [hara.object.element.util :as element.util] [hara.string :as string] [hara.function :as fn :refer [definvoke]])) (def ^:dynamic *transform* nil) (defonce +write-template+ '(fn <method> [obj val] (or (. obj (<method> val)) obj))) (definvoke meta-write "access read-attributes with caching (write/meta-write DogBuilder) => (contains {:class test.DogBuilder :empty fn?, :methods (contains {:name (contains {:type java.lang.String, :fn fn?})})})" {:added "3.0"} [:memoize] ([^Class cls] (assoc (protocol.object/-meta-write cls) :class cls))) (declare from-data) (defn write-fields "write fields of an object from reflection (-> (write/write-fields Dog) keys) => [:name :species]" {:added "3.0"} ([cls] (write-fields cls query/query-class)) ([cls query-fn] (->> (query-fn cls [:field]) (reduce (fn [out ele] (let [k (-> ele :name string/spear-type keyword) cls (.getType (get-in ele [:all :delegate]))] (assoc out k {:type cls :fn ele}))) {})))) (defn write-all-fields "all write fields of an object from reflection (hara.object/.* {}) (-> (write/write-all-fields {}) keys) => [:-hash :-hasheq :-meta :array]" {:added "3.0"} [cls] (write-fields cls query/query-instance-hierarchy)) (defn create-write-method "create a write method from the template (-> ((-> (write/create-write-method (reflect/query-class Cat [\"setName\" :#]) \"set\" write/+write-template+) second :fn) (test.Cat. \"spike\") \"fluffy\") (.getName)) => \"fluffy\"" {:added "3.0"} [ele prefix template] [(-> (:name ele) (subs (count prefix)) string/spear-type keyword) {:type (-> ele :params second) :fn (eval (walk/postwalk-replace {'<method> (symbol (:name ele))} template))}]) (defn write-setters "write fields of an object through setter methods (write/write-setters Dog) => {} (keys (write/write-setters DogBuilder)) => [:name]" {:added "3.0"} ([cls] (write-setters cls {})) ([cls opts] (write-setters cls opts query/query-class)) ([cls {:keys [prefix template] :or {prefix "set" template +write-template+}} query-fn] (->> [:method :instance :public (re-pattern (str "^" prefix ".+")) 2] (query-fn cls) (reduce (fn [out ele] (conj out (create-write-method ele prefix template))) {})))) (defn write-all-setters "write all setters of an object and base classes (write/write-all-setters Dog) => {} (keys (write/write-all-setters DogBuilder)) => [:name]" {:added "3.0"} ([cls] (write-all-setters cls {})) ([cls opts] (write-setters cls opts query/query-hierarchy))) (defn from-empty "creates the object from an empty object constructor (write/from-empty {:name \"<NAME>\" :pet \"dog\"} (fn [] (java.util.Hashtable.)) {:name {:type String :fn (fn [obj v] (.put obj \"hello\" (keyword v)) obj)} :pet {:type String :fn (fn [obj v] (.put obj \"pet\" (keyword v)) obj)}}) => {\"pet\" :dog, \"hello\" :chris}" {:added "3.0"} [m empty methods] (let [obj (empty)] (reduce-kv (fn [obj k v] (if-let [{:keys [type] func :fn} (get methods k)] (func obj (from-data v type)) obj)) obj m))) (defn from-constructor "creates the object from a constructor (-> {:name \"spike\"} (write/from-constructor {:fn (fn [name] (Cat. name)) :params [:name]} {})) ;;=> #test.Cat{:name \"spike\", :species \"cat\"} " {:added "3.0"} [m {:keys [params] :as construct} methods] (let [obj (apply (:fn construct) (map m params))] (reduce-kv (fn [obj k v] (if-let [{:keys [type] func :fn} (get methods k)] (func obj (from-data v type)) obj)) obj (apply dissoc m params)))) (defn from-map "creates the object from a map (-> {:name \"<NAME>\" :age 30 :pets [{:name \"slurp\" :species \"dog\"} {:name \"happy\" :species \"cat\"}]} (write/from-map Person) (read/to-data)) => (contains-in {:name \"<NAME>\", :age 30, :pets [{:name \"slurp\"} {:name \"happy\"}]})" {:added "3.0"} [m ^Class cls] (let [m (if-let [rels (get *transform* type)] (data/transform-in m rels) m) {:keys [construct empty methods from-map] :as mobj} (meta-write cls)] (cond from-map (from-map m) empty (from-empty m empty methods) construct (from-constructor m construct methods) :else (throw (ex-info "Cannot convert from map" {:data m :type cls}))))) (defn from-data "creates the object from data (-> (write/from-data [\"hello\"] (Class/forName \"[Ljava.lang.String;\")) seq) => [\"hello\"]" {:added "3.0"} [arg ^Class cls] (let [^Class targ (type arg)] (cond ;; If there is a direct match (or (element.util/param-arg-match cls targ) (element.util/param-float-match cls targ)) arg ;; Special case for String/CharArray (and (string? arg) (= cls (Class/forName "[C"))) (.toCharArray arg) ;; Special case for Enums (enum/enum? cls) (if (string? arg) (enum/to-enum arg cls) (throw (ex-info "Only strings supported for Enums" {:input arg :type cls}))) ;; If there is a vector (and (vector? arg) (.isArray cls)) (let [cls (.getComponentType cls)] (->> arg (map #(from-data % cls)) (into-array cls))) :else (let [{:keys [from-clojure from-string from-vector] :as mobj} (meta-write cls)] (cond from-clojure (from-clojure arg) ;; If input is a string and there is a from-string method (and (string? arg) from-string) (from-string arg) ;; If input is a string and there is a from-string method (and (vector? arg) from-vector) (from-vector arg) ;; If the input is a map (map? arg) (from-map arg cls) :else (throw (Exception. (format "Problem converting %s to %s" arg cls))))))))
true
(ns hara.object.framework.write (:require [clojure.walk :as walk] [hara.core.base.enum :as enum] [hara.data :as data] [hara.protocol.object :as protocol.object] [hara.object.query :as query] [hara.object.element.util :as element.util] [hara.string :as string] [hara.function :as fn :refer [definvoke]])) (def ^:dynamic *transform* nil) (defonce +write-template+ '(fn <method> [obj val] (or (. obj (<method> val)) obj))) (definvoke meta-write "access read-attributes with caching (write/meta-write DogBuilder) => (contains {:class test.DogBuilder :empty fn?, :methods (contains {:name (contains {:type java.lang.String, :fn fn?})})})" {:added "3.0"} [:memoize] ([^Class cls] (assoc (protocol.object/-meta-write cls) :class cls))) (declare from-data) (defn write-fields "write fields of an object from reflection (-> (write/write-fields Dog) keys) => [:name :species]" {:added "3.0"} ([cls] (write-fields cls query/query-class)) ([cls query-fn] (->> (query-fn cls [:field]) (reduce (fn [out ele] (let [k (-> ele :name string/spear-type keyword) cls (.getType (get-in ele [:all :delegate]))] (assoc out k {:type cls :fn ele}))) {})))) (defn write-all-fields "all write fields of an object from reflection (hara.object/.* {}) (-> (write/write-all-fields {}) keys) => [:-hash :-hasheq :-meta :array]" {:added "3.0"} [cls] (write-fields cls query/query-instance-hierarchy)) (defn create-write-method "create a write method from the template (-> ((-> (write/create-write-method (reflect/query-class Cat [\"setName\" :#]) \"set\" write/+write-template+) second :fn) (test.Cat. \"spike\") \"fluffy\") (.getName)) => \"fluffy\"" {:added "3.0"} [ele prefix template] [(-> (:name ele) (subs (count prefix)) string/spear-type keyword) {:type (-> ele :params second) :fn (eval (walk/postwalk-replace {'<method> (symbol (:name ele))} template))}]) (defn write-setters "write fields of an object through setter methods (write/write-setters Dog) => {} (keys (write/write-setters DogBuilder)) => [:name]" {:added "3.0"} ([cls] (write-setters cls {})) ([cls opts] (write-setters cls opts query/query-class)) ([cls {:keys [prefix template] :or {prefix "set" template +write-template+}} query-fn] (->> [:method :instance :public (re-pattern (str "^" prefix ".+")) 2] (query-fn cls) (reduce (fn [out ele] (conj out (create-write-method ele prefix template))) {})))) (defn write-all-setters "write all setters of an object and base classes (write/write-all-setters Dog) => {} (keys (write/write-all-setters DogBuilder)) => [:name]" {:added "3.0"} ([cls] (write-all-setters cls {})) ([cls opts] (write-setters cls opts query/query-hierarchy))) (defn from-empty "creates the object from an empty object constructor (write/from-empty {:name \"PI:NAME:<NAME>END_PI\" :pet \"dog\"} (fn [] (java.util.Hashtable.)) {:name {:type String :fn (fn [obj v] (.put obj \"hello\" (keyword v)) obj)} :pet {:type String :fn (fn [obj v] (.put obj \"pet\" (keyword v)) obj)}}) => {\"pet\" :dog, \"hello\" :chris}" {:added "3.0"} [m empty methods] (let [obj (empty)] (reduce-kv (fn [obj k v] (if-let [{:keys [type] func :fn} (get methods k)] (func obj (from-data v type)) obj)) obj m))) (defn from-constructor "creates the object from a constructor (-> {:name \"spike\"} (write/from-constructor {:fn (fn [name] (Cat. name)) :params [:name]} {})) ;;=> #test.Cat{:name \"spike\", :species \"cat\"} " {:added "3.0"} [m {:keys [params] :as construct} methods] (let [obj (apply (:fn construct) (map m params))] (reduce-kv (fn [obj k v] (if-let [{:keys [type] func :fn} (get methods k)] (func obj (from-data v type)) obj)) obj (apply dissoc m params)))) (defn from-map "creates the object from a map (-> {:name \"PI:NAME:<NAME>END_PI\" :age 30 :pets [{:name \"slurp\" :species \"dog\"} {:name \"happy\" :species \"cat\"}]} (write/from-map Person) (read/to-data)) => (contains-in {:name \"PI:NAME:<NAME>END_PI\", :age 30, :pets [{:name \"slurp\"} {:name \"happy\"}]})" {:added "3.0"} [m ^Class cls] (let [m (if-let [rels (get *transform* type)] (data/transform-in m rels) m) {:keys [construct empty methods from-map] :as mobj} (meta-write cls)] (cond from-map (from-map m) empty (from-empty m empty methods) construct (from-constructor m construct methods) :else (throw (ex-info "Cannot convert from map" {:data m :type cls}))))) (defn from-data "creates the object from data (-> (write/from-data [\"hello\"] (Class/forName \"[Ljava.lang.String;\")) seq) => [\"hello\"]" {:added "3.0"} [arg ^Class cls] (let [^Class targ (type arg)] (cond ;; If there is a direct match (or (element.util/param-arg-match cls targ) (element.util/param-float-match cls targ)) arg ;; Special case for String/CharArray (and (string? arg) (= cls (Class/forName "[C"))) (.toCharArray arg) ;; Special case for Enums (enum/enum? cls) (if (string? arg) (enum/to-enum arg cls) (throw (ex-info "Only strings supported for Enums" {:input arg :type cls}))) ;; If there is a vector (and (vector? arg) (.isArray cls)) (let [cls (.getComponentType cls)] (->> arg (map #(from-data % cls)) (into-array cls))) :else (let [{:keys [from-clojure from-string from-vector] :as mobj} (meta-write cls)] (cond from-clojure (from-clojure arg) ;; If input is a string and there is a from-string method (and (string? arg) from-string) (from-string arg) ;; If input is a string and there is a from-string method (and (vector? arg) from-vector) (from-vector arg) ;; If the input is a map (map? arg) (from-map arg cls) :else (throw (Exception. (format "Problem converting %s to %s" arg cls))))))))
[ { "context": "; Copyright (c) 2012 Jochen Rau\n; \n; Permission is hereby granted, free of charge", "end": 31, "score": 0.9998596906661987, "start": 21, "tag": "NAME", "value": "Jochen Rau" }, { "context": "/07/improved_regex_for_matching_urls.\n;; Thanks to John Gruber who made this public domain.\n(def iri-regex #\"(?i", "end": 1300, "score": 0.7039546370506287, "start": 1289, "tag": "NAME", "value": "John Gruber" } ]
src/clj/knowledge/syntax/iri.clj
jocrau/knowl-edge
1
; Copyright (c) 2012 Jochen Rau ; ; Permission is hereby granted, free of charge, to any person obtaining a copy ; of this software and associated documentation files (the "Software"), to deal ; in the Software without restriction, including without limitation the rights ; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ; copies of the Software, and to permit persons to whom the Software is ; furnished to do so, subject to the following conditions: ; ; The above copyright notice and this permission notice shall be included in ; all copies or substantial portions of the Software. ; ; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN ; THE SOFTWARE. (ns knowledge.syntax.iri) ;; This (scary) regular expression matches arbritrary URLs and URIs). It was taken from http://daringfireball.net/2010/07/improved_regex_for_matching_urls. ;; Thanks to John Gruber who made this public domain. (def iri-regex #"(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))") (defn iri-string? [thing] (and (string? thing) (re-find iri-regex (name thing))))
6033
; Copyright (c) 2012 <NAME> ; ; Permission is hereby granted, free of charge, to any person obtaining a copy ; of this software and associated documentation files (the "Software"), to deal ; in the Software without restriction, including without limitation the rights ; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ; copies of the Software, and to permit persons to whom the Software is ; furnished to do so, subject to the following conditions: ; ; The above copyright notice and this permission notice shall be included in ; all copies or substantial portions of the Software. ; ; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN ; THE SOFTWARE. (ns knowledge.syntax.iri) ;; This (scary) regular expression matches arbritrary URLs and URIs). It was taken from http://daringfireball.net/2010/07/improved_regex_for_matching_urls. ;; Thanks to <NAME> who made this public domain. (def iri-regex #"(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))") (defn iri-string? [thing] (and (string? thing) (re-find iri-regex (name thing))))
true
; Copyright (c) 2012 PI:NAME:<NAME>END_PI ; ; Permission is hereby granted, free of charge, to any person obtaining a copy ; of this software and associated documentation files (the "Software"), to deal ; in the Software without restriction, including without limitation the rights ; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ; copies of the Software, and to permit persons to whom the Software is ; furnished to do so, subject to the following conditions: ; ; The above copyright notice and this permission notice shall be included in ; all copies or substantial portions of the Software. ; ; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN ; THE SOFTWARE. (ns knowledge.syntax.iri) ;; This (scary) regular expression matches arbritrary URLs and URIs). It was taken from http://daringfireball.net/2010/07/improved_regex_for_matching_urls. ;; Thanks to PI:NAME:<NAME>END_PI who made this public domain. (def iri-regex #"(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))") (defn iri-string? [thing] (and (string? thing) (re-find iri-regex (name thing))))
[ { "context": " 12\n 10\n :name \"Annie Lightbulb\"\n :skills {:guns-pistol {:level 3}", "end": 3207, "score": 0.9998561143875122, "start": 3192, "tag": "NAME", "value": "Annie Lightbulb" } ]
gurpsim/src/gurpsim/character.clj
nasfarley88/gurpsim
0
(ns gurpsim.character) (defn base-stat-value "Checks the value of a stat for a given keyword" [character stat] (+ (get-in character [stat :value]) (if (get-in character [stat :mod]) (get-in character [stat :mod]) 0))) (defn st "Check the value of st" [character] (base-stat-value character :st)) (defn iq "Check the value of iq" [character] (base-stat-value character :iq)) (defn dx "Check the value of dx" [character] (base-stat-value character :dx)) (defn ht "Check the value of ht" [character] (base-stat-value character :ht)) (defn basic-speed "Calculates basic speed" ([character] (basic-speed (base-stat-value character :dx) (base-stat-value character :ht))) ([dx ht] ;; TODO create multi arity function to take into account size etc. (float (/ (+ dx ht) 4))) ) (defn basic-move "Calculates basic move." [character] (int (basic-speed character))) (defn dodge "Calculates dodge." [character] ;; TODO include advantages like Enhanced Dodge (+ (basic-move character) 3) ) (defn get-level [character stat] (get-in character [stat :level])) (defn hp "Calculates max hp." [character] (+ (base-stat-value character :st) (get-in character [:hp :level]))) (defn current-hp "Calculates max hp." [character] (:current-hp character)) (defn per "Calculates max per." [character] (+ (base-stat-value character :iq) (get-in character [:per :level]))) (defn will "Calculates max will." [character] (+ (base-stat-value character :iq ) (get-in character [:will :level]))) (defn fp "Calculates max fp." [character] (+ (base-stat-value character :ht) (get-in character [:fp :level]))) (defn create "Create a skeleton character from the four stats" ([] (create 10 10 10 10)) ;; TODO create an arity that accepts only keys ([st dx iq ht & {:keys [ hp per will fp name advantages disadvantages skills quirks weapons armour ] :or { hp 0 per 0 will 0 fp 0 name "X" advantages {} disadvantages {} skills {} quirks {} weapons {} armour {}}}] { :name name :st {:value st} :dx {:value dx} :iq {:value iq} :ht {:value ht} :hp {:level hp} :current-hp st :per {:level per} :will {:level will} :fp {:level fp} :basic-speed {:level 0} :basic-move {:level 0} :advantages advantages :disadvantages disadvantages :skills skills :quirks quirks :weapons weapons :armour armour })) (def test-char (create 9 10 12 10 :name "Annie Lightbulb" :skills {:guns-pistol {:level 3}}))
71293
(ns gurpsim.character) (defn base-stat-value "Checks the value of a stat for a given keyword" [character stat] (+ (get-in character [stat :value]) (if (get-in character [stat :mod]) (get-in character [stat :mod]) 0))) (defn st "Check the value of st" [character] (base-stat-value character :st)) (defn iq "Check the value of iq" [character] (base-stat-value character :iq)) (defn dx "Check the value of dx" [character] (base-stat-value character :dx)) (defn ht "Check the value of ht" [character] (base-stat-value character :ht)) (defn basic-speed "Calculates basic speed" ([character] (basic-speed (base-stat-value character :dx) (base-stat-value character :ht))) ([dx ht] ;; TODO create multi arity function to take into account size etc. (float (/ (+ dx ht) 4))) ) (defn basic-move "Calculates basic move." [character] (int (basic-speed character))) (defn dodge "Calculates dodge." [character] ;; TODO include advantages like Enhanced Dodge (+ (basic-move character) 3) ) (defn get-level [character stat] (get-in character [stat :level])) (defn hp "Calculates max hp." [character] (+ (base-stat-value character :st) (get-in character [:hp :level]))) (defn current-hp "Calculates max hp." [character] (:current-hp character)) (defn per "Calculates max per." [character] (+ (base-stat-value character :iq) (get-in character [:per :level]))) (defn will "Calculates max will." [character] (+ (base-stat-value character :iq ) (get-in character [:will :level]))) (defn fp "Calculates max fp." [character] (+ (base-stat-value character :ht) (get-in character [:fp :level]))) (defn create "Create a skeleton character from the four stats" ([] (create 10 10 10 10)) ;; TODO create an arity that accepts only keys ([st dx iq ht & {:keys [ hp per will fp name advantages disadvantages skills quirks weapons armour ] :or { hp 0 per 0 will 0 fp 0 name "X" advantages {} disadvantages {} skills {} quirks {} weapons {} armour {}}}] { :name name :st {:value st} :dx {:value dx} :iq {:value iq} :ht {:value ht} :hp {:level hp} :current-hp st :per {:level per} :will {:level will} :fp {:level fp} :basic-speed {:level 0} :basic-move {:level 0} :advantages advantages :disadvantages disadvantages :skills skills :quirks quirks :weapons weapons :armour armour })) (def test-char (create 9 10 12 10 :name "<NAME>" :skills {:guns-pistol {:level 3}}))
true
(ns gurpsim.character) (defn base-stat-value "Checks the value of a stat for a given keyword" [character stat] (+ (get-in character [stat :value]) (if (get-in character [stat :mod]) (get-in character [stat :mod]) 0))) (defn st "Check the value of st" [character] (base-stat-value character :st)) (defn iq "Check the value of iq" [character] (base-stat-value character :iq)) (defn dx "Check the value of dx" [character] (base-stat-value character :dx)) (defn ht "Check the value of ht" [character] (base-stat-value character :ht)) (defn basic-speed "Calculates basic speed" ([character] (basic-speed (base-stat-value character :dx) (base-stat-value character :ht))) ([dx ht] ;; TODO create multi arity function to take into account size etc. (float (/ (+ dx ht) 4))) ) (defn basic-move "Calculates basic move." [character] (int (basic-speed character))) (defn dodge "Calculates dodge." [character] ;; TODO include advantages like Enhanced Dodge (+ (basic-move character) 3) ) (defn get-level [character stat] (get-in character [stat :level])) (defn hp "Calculates max hp." [character] (+ (base-stat-value character :st) (get-in character [:hp :level]))) (defn current-hp "Calculates max hp." [character] (:current-hp character)) (defn per "Calculates max per." [character] (+ (base-stat-value character :iq) (get-in character [:per :level]))) (defn will "Calculates max will." [character] (+ (base-stat-value character :iq ) (get-in character [:will :level]))) (defn fp "Calculates max fp." [character] (+ (base-stat-value character :ht) (get-in character [:fp :level]))) (defn create "Create a skeleton character from the four stats" ([] (create 10 10 10 10)) ;; TODO create an arity that accepts only keys ([st dx iq ht & {:keys [ hp per will fp name advantages disadvantages skills quirks weapons armour ] :or { hp 0 per 0 will 0 fp 0 name "X" advantages {} disadvantages {} skills {} quirks {} weapons {} armour {}}}] { :name name :st {:value st} :dx {:value dx} :iq {:value iq} :ht {:value ht} :hp {:level hp} :current-hp st :per {:level per} :will {:level will} :fp {:level fp} :basic-speed {:level 0} :basic-move {:level 0} :advantages advantages :disadvantages disadvantages :skills skills :quirks quirks :weapons weapons :armour armour })) (def test-char (create 9 10 12 10 :name "PI:NAME:<NAME>END_PI" :skills {:guns-pistol {:level 3}}))
[ { "context": "(shell {:cmd (str \"curl -L https://github.com/bcicen/ctop/releases/download/v\" version \"/ctop-\" versio", "end": 272, "score": 0.9986438155174255, "start": 266, "tag": "USERNAME", "value": "bcicen" }, { "context": "tr/join tmux-version [\"curl -L https://github.com/tmux/tmux/releases/download/\" \"/tmux-\" \".tar.gz -o tmu", "end": 2769, "score": 0.9981295466423035, "start": 2765, "tag": "USERNAME", "value": "tmux" }, { "context": "\n (shell {:cmd \"git clone https://github.com/tmux-plugins/tpm ~/.tmux/plugins/tpm\"\n :creates [\"$HO", "end": 3623, "score": 0.9993813633918762, "start": 3611, "tag": "USERNAME", "value": "tmux-plugins" }, { "context": " (str \"curl -L -o restic.bz2 https://github.com/restic/restic/releases/download/v\" version \"/restic_\" ve", "end": 4180, "score": 0.9994149804115295, "start": 4174, "tag": "USERNAME", "value": "restic" }, { "context": ":cmd (str \"curl -L -o nvim https://github.com/neovim/neovim/releases/download/v\" version \"/nvim.appima", "end": 5456, "score": 0.9992012977600098, "start": 5450, "tag": "USERNAME", "value": "neovim" }, { "context": "compose)\n (copy-secrets))\n\n(comment\n (ssh \"root@185.198.26.34:2016\"\n (get-fact)))\n\n(if-let [target (secon", "end": 6587, "score": 0.9997324347496033, "start": 6574, "tag": "IP_ADDRESS", "value": "185.198.26.34" } ]
scripts/provision.clj
mayoshia/throw-voice
49
#!/usr/bin/env spire (require '[clojure.string :as str] '[clojure.edn :as edn]) (defn install-git [] (comment (TODO "Need to install from source"))) (defn install-ctop [] (let [version "0.7.5"] (shell {:cmd (str "curl -L https://github.com/bcicen/ctop/releases/download/v" version "/ctop-" version "-linux-amd64 -o ctop") :dir "/usr/local/bin/" :creates ["/usr/local/bin/ctop"]}) (shell {:cmd "chmod +x ctop" :dir "/usr/local/bin/"}))) (defn install-docker "Install Docker Source: https://docs.docker.com/engine/install/ubuntu/ Source: https://docs.docker.com/engine/install/centos/#install-using-the-repository" [system] (on-distro :ubuntu (let [packages ["apt-transport-https" "ca-certificates" "curl" "gnupg-agent" "software-properties-common"]] (apt :install packages) (shell {:cmd "curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -"}) (shell {:cmd "lsb_release -cs"}) (apt-repo :present {:repo (str "deb [arch=amd64] https://download.docker.com/linux/ubuntu " (name (:codename system)) " stable") :filename "docker"}) (apt :update) (apt :install ["docker-ce" "docker-ce-cli" "containerd.io"])) :centos (do (shell {:cmd "yum install -y yum-utils"}) (shell {:cmd "yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo"}) (shell {:cmd "yum install -y docker-ce docker-ce-cli containerd.io"}) (shell {:cmd "systemctl start docker"})))) (defn install-docker-compose "Install Docker Compose" [uname] (let [{:keys [os platform]} uname version "1.27.4"] (shell {:cmd (str "curl -L https://github.com/docker/compose/releases/download/" version "/docker-compose-" os "-" platform " -o docker-compose") :dir "/usr/local/bin/" :creates ["/usr/local/bin/docker-compose"]}) (shell {:cmd "chmod +x docker-compose" :dir "/usr/local/bin/"}))) (defn install-local-persist "TODO: Install Docker Persist for Volumes" [] (shell {:cmd "curl -fsSL https://raw.githubusercontent.com/MatchbookLab/local-persist/master/scripts/install.sh | bash"})) (defn install-tmux "Install TMUX Source: http://witkowskibartosz.com/blog/update-your-tmux-to-latest-version.html" [] (on-distro :ubuntu (let [build-packages ["libevent-dev" "libncurses-dev"] tmux-version "3.0a" tmux-tarball (str "tmux-" tmux-version ".tar.gz")] (apt :install build-packages) (shell {:cmd (str/join tmux-version ["curl -L https://github.com/tmux/tmux/releases/download/" "/tmux-" ".tar.gz -o tmux-" ".tar.gz"]) :dir "/tmp" :creates [tmux-tarball]}) (let [build-directory (str "/tmp/tmux-" tmux-version)] (shell {:cmd (str "tar xf " tmux-tarball) :dir "/tmp" :creates [build-directory]}) (shell {:cmd "./configure" :dir build-directory}) (shell {:cmd "make" :dir build-directory}) (shell {:cmd "make install" :dir build-directory :creates ["/usr/local/bin/tmux"]}))) :centos (println "TODO: How to install from source?"))) (defn install-tpm "Install TPM" [] (shell {:cmd "git clone https://github.com/tmux-plugins/tpm ~/.tmux/plugins/tpm" :creates ["$HOME/.tmux/plugins/tpm"]}) (upload {:src "./conf/tmux.conf" :dest "$HOME/.tmux.conf" :mode 0755})) (defn install-restic "Install Restic Source: https://restic.readthedocs.io/en/stable/020_installation.html#official-binaries" [system] (let [{:keys [os platform]} system platform (case platform :x86_64 "amd64") version "0.11.0" working-dir "/tmp"] (shell {:cmd (str "curl -L -o restic.bz2 https://github.com/restic/restic/releases/download/v" version "/restic_" version "_" (name os) "_" platform ".bz2") :dir working-dir :creates ["restic.bz2"]}) (shell {:cmd "bzip2 -d restic.bz2" :dir working-dir :creates ["restic"]}) (shell {:cmd "chmod +x restic" :dir working-dir}) (shell {:cmd "mv restic /usr/local/bin/restic" :dir working-dir :creates ["/usr/local/bin/restic"]}) (shell {:cmd "/usr/local/bin/restic self-update"}))) (defn configure-restic-backups "TODO: Configure automatic backups" [] (shell {:cmd "mkdir -p /etc/restic"}) ;; Create environment files (upload {:src "./restic/b2_env.sh" :dest "/etc/restic/b2_env.sh" :mode 0755}) #_(upload {:src "./restic/restic_backup.sh" :dest "/usr/local/sbin/restic_backup.sh" :mode 0755}) #_(upload {:src "./restic/restic_check.sh" :dest "/usr/local/sbin/restic_check.sh" :mode 0755}) (upload {:src "./restic/b2_pw.txt" :dest "/etc/restic/b2_pw.txt" :mode 0600})) (defn install-neovim "Install NeoVim" [] (let [version "0.4.4"] (shell {:cmd (str "curl -L -o nvim https://github.com/neovim/neovim/releases/download/v" version "/nvim.appimage") :dir "/usr/local/bin" :creates ["/usr/local/bin/nvim"]}) (shell {:cmd "chmod +x nvim" :dir "/usr/local/bin"}) (shell {:cmd "ln -s /usr/local/bin/{nvim,vim}" :creates ["/usr/local/bin/vim"]}))) (defn create-directory-structure "Creates the expected directory structure" [] (let [base-dir "/opt/pawa/"] (doseq [dir ["database" "data/recordings" "logs"]] (shell {:cmd (str "mkdir -p " base-dir dir) :creates [(str base-dir dir)]})))) (defn copy-nginx-conf [] (upload {:src "./conf/nginx.conf" :dest "/opt/pawa/nginx.conf" :mode 0755})) (defn copy-docker-compose [] (upload {:src "./docker-compose.yml" :dest "/opt/pawa/docker-compose.yml" :mode 0755})) (defn copy-secrets [] (upload {:src "./conf/prod.env" :dest "/opt/pawa/.env" :mode 0655})) (defn setup-pawa [] (create-directory-structure) (copy-nginx-conf) (copy-docker-compose) (copy-secrets)) (comment (ssh "root@185.198.26.34:2016" (get-fact))) (if-let [target (second *command-line-args*)] (ssh target (let [facts (get-fact) packages ["build-essential" "mosh" "tree"]] (on-distro :ubuntu (do (apt :update) (apt :install packages)) :centos (do (shell {:cmd "dnf check-update"}) (shell {:cmd "dnf install -y mosh tree"}))) (install-ctop) (install-tmux) (install-tpm) (install-restic (:system facts)) (configure-restic-backups) (install-docker (:system facts)) (install-docker-compose (:uname facts)) (install-local-persist) (install-neovim) (setup-pawa))))
32242
#!/usr/bin/env spire (require '[clojure.string :as str] '[clojure.edn :as edn]) (defn install-git [] (comment (TODO "Need to install from source"))) (defn install-ctop [] (let [version "0.7.5"] (shell {:cmd (str "curl -L https://github.com/bcicen/ctop/releases/download/v" version "/ctop-" version "-linux-amd64 -o ctop") :dir "/usr/local/bin/" :creates ["/usr/local/bin/ctop"]}) (shell {:cmd "chmod +x ctop" :dir "/usr/local/bin/"}))) (defn install-docker "Install Docker Source: https://docs.docker.com/engine/install/ubuntu/ Source: https://docs.docker.com/engine/install/centos/#install-using-the-repository" [system] (on-distro :ubuntu (let [packages ["apt-transport-https" "ca-certificates" "curl" "gnupg-agent" "software-properties-common"]] (apt :install packages) (shell {:cmd "curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -"}) (shell {:cmd "lsb_release -cs"}) (apt-repo :present {:repo (str "deb [arch=amd64] https://download.docker.com/linux/ubuntu " (name (:codename system)) " stable") :filename "docker"}) (apt :update) (apt :install ["docker-ce" "docker-ce-cli" "containerd.io"])) :centos (do (shell {:cmd "yum install -y yum-utils"}) (shell {:cmd "yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo"}) (shell {:cmd "yum install -y docker-ce docker-ce-cli containerd.io"}) (shell {:cmd "systemctl start docker"})))) (defn install-docker-compose "Install Docker Compose" [uname] (let [{:keys [os platform]} uname version "1.27.4"] (shell {:cmd (str "curl -L https://github.com/docker/compose/releases/download/" version "/docker-compose-" os "-" platform " -o docker-compose") :dir "/usr/local/bin/" :creates ["/usr/local/bin/docker-compose"]}) (shell {:cmd "chmod +x docker-compose" :dir "/usr/local/bin/"}))) (defn install-local-persist "TODO: Install Docker Persist for Volumes" [] (shell {:cmd "curl -fsSL https://raw.githubusercontent.com/MatchbookLab/local-persist/master/scripts/install.sh | bash"})) (defn install-tmux "Install TMUX Source: http://witkowskibartosz.com/blog/update-your-tmux-to-latest-version.html" [] (on-distro :ubuntu (let [build-packages ["libevent-dev" "libncurses-dev"] tmux-version "3.0a" tmux-tarball (str "tmux-" tmux-version ".tar.gz")] (apt :install build-packages) (shell {:cmd (str/join tmux-version ["curl -L https://github.com/tmux/tmux/releases/download/" "/tmux-" ".tar.gz -o tmux-" ".tar.gz"]) :dir "/tmp" :creates [tmux-tarball]}) (let [build-directory (str "/tmp/tmux-" tmux-version)] (shell {:cmd (str "tar xf " tmux-tarball) :dir "/tmp" :creates [build-directory]}) (shell {:cmd "./configure" :dir build-directory}) (shell {:cmd "make" :dir build-directory}) (shell {:cmd "make install" :dir build-directory :creates ["/usr/local/bin/tmux"]}))) :centos (println "TODO: How to install from source?"))) (defn install-tpm "Install TPM" [] (shell {:cmd "git clone https://github.com/tmux-plugins/tpm ~/.tmux/plugins/tpm" :creates ["$HOME/.tmux/plugins/tpm"]}) (upload {:src "./conf/tmux.conf" :dest "$HOME/.tmux.conf" :mode 0755})) (defn install-restic "Install Restic Source: https://restic.readthedocs.io/en/stable/020_installation.html#official-binaries" [system] (let [{:keys [os platform]} system platform (case platform :x86_64 "amd64") version "0.11.0" working-dir "/tmp"] (shell {:cmd (str "curl -L -o restic.bz2 https://github.com/restic/restic/releases/download/v" version "/restic_" version "_" (name os) "_" platform ".bz2") :dir working-dir :creates ["restic.bz2"]}) (shell {:cmd "bzip2 -d restic.bz2" :dir working-dir :creates ["restic"]}) (shell {:cmd "chmod +x restic" :dir working-dir}) (shell {:cmd "mv restic /usr/local/bin/restic" :dir working-dir :creates ["/usr/local/bin/restic"]}) (shell {:cmd "/usr/local/bin/restic self-update"}))) (defn configure-restic-backups "TODO: Configure automatic backups" [] (shell {:cmd "mkdir -p /etc/restic"}) ;; Create environment files (upload {:src "./restic/b2_env.sh" :dest "/etc/restic/b2_env.sh" :mode 0755}) #_(upload {:src "./restic/restic_backup.sh" :dest "/usr/local/sbin/restic_backup.sh" :mode 0755}) #_(upload {:src "./restic/restic_check.sh" :dest "/usr/local/sbin/restic_check.sh" :mode 0755}) (upload {:src "./restic/b2_pw.txt" :dest "/etc/restic/b2_pw.txt" :mode 0600})) (defn install-neovim "Install NeoVim" [] (let [version "0.4.4"] (shell {:cmd (str "curl -L -o nvim https://github.com/neovim/neovim/releases/download/v" version "/nvim.appimage") :dir "/usr/local/bin" :creates ["/usr/local/bin/nvim"]}) (shell {:cmd "chmod +x nvim" :dir "/usr/local/bin"}) (shell {:cmd "ln -s /usr/local/bin/{nvim,vim}" :creates ["/usr/local/bin/vim"]}))) (defn create-directory-structure "Creates the expected directory structure" [] (let [base-dir "/opt/pawa/"] (doseq [dir ["database" "data/recordings" "logs"]] (shell {:cmd (str "mkdir -p " base-dir dir) :creates [(str base-dir dir)]})))) (defn copy-nginx-conf [] (upload {:src "./conf/nginx.conf" :dest "/opt/pawa/nginx.conf" :mode 0755})) (defn copy-docker-compose [] (upload {:src "./docker-compose.yml" :dest "/opt/pawa/docker-compose.yml" :mode 0755})) (defn copy-secrets [] (upload {:src "./conf/prod.env" :dest "/opt/pawa/.env" :mode 0655})) (defn setup-pawa [] (create-directory-structure) (copy-nginx-conf) (copy-docker-compose) (copy-secrets)) (comment (ssh "root@172.16.31.10:2016" (get-fact))) (if-let [target (second *command-line-args*)] (ssh target (let [facts (get-fact) packages ["build-essential" "mosh" "tree"]] (on-distro :ubuntu (do (apt :update) (apt :install packages)) :centos (do (shell {:cmd "dnf check-update"}) (shell {:cmd "dnf install -y mosh tree"}))) (install-ctop) (install-tmux) (install-tpm) (install-restic (:system facts)) (configure-restic-backups) (install-docker (:system facts)) (install-docker-compose (:uname facts)) (install-local-persist) (install-neovim) (setup-pawa))))
true
#!/usr/bin/env spire (require '[clojure.string :as str] '[clojure.edn :as edn]) (defn install-git [] (comment (TODO "Need to install from source"))) (defn install-ctop [] (let [version "0.7.5"] (shell {:cmd (str "curl -L https://github.com/bcicen/ctop/releases/download/v" version "/ctop-" version "-linux-amd64 -o ctop") :dir "/usr/local/bin/" :creates ["/usr/local/bin/ctop"]}) (shell {:cmd "chmod +x ctop" :dir "/usr/local/bin/"}))) (defn install-docker "Install Docker Source: https://docs.docker.com/engine/install/ubuntu/ Source: https://docs.docker.com/engine/install/centos/#install-using-the-repository" [system] (on-distro :ubuntu (let [packages ["apt-transport-https" "ca-certificates" "curl" "gnupg-agent" "software-properties-common"]] (apt :install packages) (shell {:cmd "curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -"}) (shell {:cmd "lsb_release -cs"}) (apt-repo :present {:repo (str "deb [arch=amd64] https://download.docker.com/linux/ubuntu " (name (:codename system)) " stable") :filename "docker"}) (apt :update) (apt :install ["docker-ce" "docker-ce-cli" "containerd.io"])) :centos (do (shell {:cmd "yum install -y yum-utils"}) (shell {:cmd "yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo"}) (shell {:cmd "yum install -y docker-ce docker-ce-cli containerd.io"}) (shell {:cmd "systemctl start docker"})))) (defn install-docker-compose "Install Docker Compose" [uname] (let [{:keys [os platform]} uname version "1.27.4"] (shell {:cmd (str "curl -L https://github.com/docker/compose/releases/download/" version "/docker-compose-" os "-" platform " -o docker-compose") :dir "/usr/local/bin/" :creates ["/usr/local/bin/docker-compose"]}) (shell {:cmd "chmod +x docker-compose" :dir "/usr/local/bin/"}))) (defn install-local-persist "TODO: Install Docker Persist for Volumes" [] (shell {:cmd "curl -fsSL https://raw.githubusercontent.com/MatchbookLab/local-persist/master/scripts/install.sh | bash"})) (defn install-tmux "Install TMUX Source: http://witkowskibartosz.com/blog/update-your-tmux-to-latest-version.html" [] (on-distro :ubuntu (let [build-packages ["libevent-dev" "libncurses-dev"] tmux-version "3.0a" tmux-tarball (str "tmux-" tmux-version ".tar.gz")] (apt :install build-packages) (shell {:cmd (str/join tmux-version ["curl -L https://github.com/tmux/tmux/releases/download/" "/tmux-" ".tar.gz -o tmux-" ".tar.gz"]) :dir "/tmp" :creates [tmux-tarball]}) (let [build-directory (str "/tmp/tmux-" tmux-version)] (shell {:cmd (str "tar xf " tmux-tarball) :dir "/tmp" :creates [build-directory]}) (shell {:cmd "./configure" :dir build-directory}) (shell {:cmd "make" :dir build-directory}) (shell {:cmd "make install" :dir build-directory :creates ["/usr/local/bin/tmux"]}))) :centos (println "TODO: How to install from source?"))) (defn install-tpm "Install TPM" [] (shell {:cmd "git clone https://github.com/tmux-plugins/tpm ~/.tmux/plugins/tpm" :creates ["$HOME/.tmux/plugins/tpm"]}) (upload {:src "./conf/tmux.conf" :dest "$HOME/.tmux.conf" :mode 0755})) (defn install-restic "Install Restic Source: https://restic.readthedocs.io/en/stable/020_installation.html#official-binaries" [system] (let [{:keys [os platform]} system platform (case platform :x86_64 "amd64") version "0.11.0" working-dir "/tmp"] (shell {:cmd (str "curl -L -o restic.bz2 https://github.com/restic/restic/releases/download/v" version "/restic_" version "_" (name os) "_" platform ".bz2") :dir working-dir :creates ["restic.bz2"]}) (shell {:cmd "bzip2 -d restic.bz2" :dir working-dir :creates ["restic"]}) (shell {:cmd "chmod +x restic" :dir working-dir}) (shell {:cmd "mv restic /usr/local/bin/restic" :dir working-dir :creates ["/usr/local/bin/restic"]}) (shell {:cmd "/usr/local/bin/restic self-update"}))) (defn configure-restic-backups "TODO: Configure automatic backups" [] (shell {:cmd "mkdir -p /etc/restic"}) ;; Create environment files (upload {:src "./restic/b2_env.sh" :dest "/etc/restic/b2_env.sh" :mode 0755}) #_(upload {:src "./restic/restic_backup.sh" :dest "/usr/local/sbin/restic_backup.sh" :mode 0755}) #_(upload {:src "./restic/restic_check.sh" :dest "/usr/local/sbin/restic_check.sh" :mode 0755}) (upload {:src "./restic/b2_pw.txt" :dest "/etc/restic/b2_pw.txt" :mode 0600})) (defn install-neovim "Install NeoVim" [] (let [version "0.4.4"] (shell {:cmd (str "curl -L -o nvim https://github.com/neovim/neovim/releases/download/v" version "/nvim.appimage") :dir "/usr/local/bin" :creates ["/usr/local/bin/nvim"]}) (shell {:cmd "chmod +x nvim" :dir "/usr/local/bin"}) (shell {:cmd "ln -s /usr/local/bin/{nvim,vim}" :creates ["/usr/local/bin/vim"]}))) (defn create-directory-structure "Creates the expected directory structure" [] (let [base-dir "/opt/pawa/"] (doseq [dir ["database" "data/recordings" "logs"]] (shell {:cmd (str "mkdir -p " base-dir dir) :creates [(str base-dir dir)]})))) (defn copy-nginx-conf [] (upload {:src "./conf/nginx.conf" :dest "/opt/pawa/nginx.conf" :mode 0755})) (defn copy-docker-compose [] (upload {:src "./docker-compose.yml" :dest "/opt/pawa/docker-compose.yml" :mode 0755})) (defn copy-secrets [] (upload {:src "./conf/prod.env" :dest "/opt/pawa/.env" :mode 0655})) (defn setup-pawa [] (create-directory-structure) (copy-nginx-conf) (copy-docker-compose) (copy-secrets)) (comment (ssh "root@PI:IP_ADDRESS:172.16.31.10END_PI:2016" (get-fact))) (if-let [target (second *command-line-args*)] (ssh target (let [facts (get-fact) packages ["build-essential" "mosh" "tree"]] (on-distro :ubuntu (do (apt :update) (apt :install packages)) :centos (do (shell {:cmd "dnf check-update"}) (shell {:cmd "dnf install -y mosh tree"}))) (install-ctop) (install-tmux) (install-tpm) (install-restic (:system facts)) (configure-restic-backups) (install-docker (:system facts)) (install-docker-compose (:uname facts)) (install-local-persist) (install-neovim) (setup-pawa))))
[ { "context": "(ns ^{ :doc \"Iface Wrappers\"\n :author \"Yannick Scherer\" }\n thrift-clj.gen.iface\n (:require [thrift-clj", "end": 60, "score": 0.9998459219932556, "start": 45, "tag": "NAME", "value": "Yannick Scherer" } ]
src/thrift_clj/gen/iface.clj
ipostelnik/thrift-clj
35
(ns ^{ :doc "Iface Wrappers" :author "Yannick Scherer" } thrift-clj.gen.iface (:require [thrift-clj.gen.core :as c] [thrift-clj.thrift.services :as s] [thrift-clj.utils.symbols :as u] [thrift-clj.utils.namespaces :as nsp])) ;; ## Iface ;; ;; The Service Interface is located at `<Service>$Iface`. It can be ;; accessed by creating a namespace that contains a single function ;; for each interface method, transparently converting between ;; Clojure and Thrift representations. (nsp/def-reload-indicator reload-iface?) (defn generate-thrift-iface-import "Generate single Iface import." [service-class iface-alias] (let [cls (u/full-class-symbol service-class) iface-cls (u/inner cls "Iface") mth (s/thrift-service-methods service-class) param-syms (repeatedly gensym) iface-sym (vary-meta (gensym "iface-") assoc :tag iface-cls)] `(do ~@(when (reload-iface? iface-cls) [`(nsp/internal-ns-remove '~iface-cls)]) (nsp/internal-ns ~iface-cls ~@(for [{:keys[name params]} mth] (let [params (take (count params) param-syms)] `(defn ~(symbol name) [~iface-sym ~@params] (c/->clj (. ~iface-sym ~(symbol name) ~@(map #(list `c/->thrift %) params))))))) (nsp/internal-ns-require '~iface-cls '~iface-alias)))) (defn generate-thrift-iface-imports "Generate Iface Namespace for the given Service-Class/Iface-Alias pairs." [service-map] (for [[service-class iface-alias] service-map] (let [iface-alias (or iface-alias (u/class-symbol service-class))] (generate-thrift-iface-import service-class iface-alias))))
11741
(ns ^{ :doc "Iface Wrappers" :author "<NAME>" } thrift-clj.gen.iface (:require [thrift-clj.gen.core :as c] [thrift-clj.thrift.services :as s] [thrift-clj.utils.symbols :as u] [thrift-clj.utils.namespaces :as nsp])) ;; ## Iface ;; ;; The Service Interface is located at `<Service>$Iface`. It can be ;; accessed by creating a namespace that contains a single function ;; for each interface method, transparently converting between ;; Clojure and Thrift representations. (nsp/def-reload-indicator reload-iface?) (defn generate-thrift-iface-import "Generate single Iface import." [service-class iface-alias] (let [cls (u/full-class-symbol service-class) iface-cls (u/inner cls "Iface") mth (s/thrift-service-methods service-class) param-syms (repeatedly gensym) iface-sym (vary-meta (gensym "iface-") assoc :tag iface-cls)] `(do ~@(when (reload-iface? iface-cls) [`(nsp/internal-ns-remove '~iface-cls)]) (nsp/internal-ns ~iface-cls ~@(for [{:keys[name params]} mth] (let [params (take (count params) param-syms)] `(defn ~(symbol name) [~iface-sym ~@params] (c/->clj (. ~iface-sym ~(symbol name) ~@(map #(list `c/->thrift %) params))))))) (nsp/internal-ns-require '~iface-cls '~iface-alias)))) (defn generate-thrift-iface-imports "Generate Iface Namespace for the given Service-Class/Iface-Alias pairs." [service-map] (for [[service-class iface-alias] service-map] (let [iface-alias (or iface-alias (u/class-symbol service-class))] (generate-thrift-iface-import service-class iface-alias))))
true
(ns ^{ :doc "Iface Wrappers" :author "PI:NAME:<NAME>END_PI" } thrift-clj.gen.iface (:require [thrift-clj.gen.core :as c] [thrift-clj.thrift.services :as s] [thrift-clj.utils.symbols :as u] [thrift-clj.utils.namespaces :as nsp])) ;; ## Iface ;; ;; The Service Interface is located at `<Service>$Iface`. It can be ;; accessed by creating a namespace that contains a single function ;; for each interface method, transparently converting between ;; Clojure and Thrift representations. (nsp/def-reload-indicator reload-iface?) (defn generate-thrift-iface-import "Generate single Iface import." [service-class iface-alias] (let [cls (u/full-class-symbol service-class) iface-cls (u/inner cls "Iface") mth (s/thrift-service-methods service-class) param-syms (repeatedly gensym) iface-sym (vary-meta (gensym "iface-") assoc :tag iface-cls)] `(do ~@(when (reload-iface? iface-cls) [`(nsp/internal-ns-remove '~iface-cls)]) (nsp/internal-ns ~iface-cls ~@(for [{:keys[name params]} mth] (let [params (take (count params) param-syms)] `(defn ~(symbol name) [~iface-sym ~@params] (c/->clj (. ~iface-sym ~(symbol name) ~@(map #(list `c/->thrift %) params))))))) (nsp/internal-ns-require '~iface-cls '~iface-alias)))) (defn generate-thrift-iface-imports "Generate Iface Namespace for the given Service-Class/Iface-Alias pairs." [service-map] (for [[service-class iface-alias] service-map] (let [iface-alias (or iface-alias (u/class-symbol service-class))] (generate-thrift-iface-import service-class iface-alias))))
[ { "context": " all modules\"\n :url \"https://github.com/thi-ng/geom\"\n :license {:name \"Apache Software Lic", "end": 158, "score": 0.9995222091674805, "start": 152, "tag": "USERNAME", "value": "thi-ng" }, { "context": " \"git\"\n :url \"https://github.com/thi-ng/geom\"}\n\n :min-lein-version \"2.4.0\"\n\n :dependenc", "end": 398, "score": 0.9994754791259766, "start": 392, "tag": "USERNAME", "value": "thi-ng" }, { "context": " [com.postspectacular/piksel \"0.1.4\"]]\n :plugin", "end": 1993, "score": 0.8390307426452637, "start": 1983, "tag": "USERNAME", "value": "pectacular" }, { "context": " [com.cemerick/clojurescript.test \"0.3.3\"]]\n ", "end": 2139, "score": 0.6768919229507446, "start": 2133, "tag": "USERNAME", "value": "merick" }, { "context": " [:developer\n [:name \"Karsten Schmidt\"]\n [:url \"http://thi.ng\"]\n ", "end": 4212, "score": 0.9998151659965515, "start": 4197, "tag": "NAME", "value": "Karsten Schmidt" } ]
project.clj
gaybro8777/geom
803
(defproject thi.ng/geom "1.0.0-RC4" :description "thi.ng geometry kit - meta project spec including all modules" :url "https://github.com/thi-ng/geom" :license {:name "Apache Software License" :url "http://www.apache.org/licenses/LICENSE-2.0" :distribution :repo} :scm {:name "git" :url "https://github.com/thi-ng/geom"} :min-lein-version "2.4.0" :dependencies [[org.clojure/clojure "1.9.0"] [org.clojure/clojurescript "1.10.238"] [thi.ng/color "1.4.0"] [thi.ng/dstruct "0.2.1"] [thi.ng/math "0.3.0"] [thi.ng/ndarray "0.3.2"] [thi.ng/shadergraph "0.3.0"] [thi.ng/strf "0.2.2"] [thi.ng/typedarrays "0.1.6"] [thi.ng/xerror "0.1.0"] [org.jogamp.gluegen/gluegen-rt "2.3.2"] [org.jogamp.jogl/jogl-all "2.3.2"] [cljs-log "0.2.2"] [hiccup "1.0.5"]] :perforate {:environments [{:namespaces [thi.ng.geom.bench.core.vector]}]} :profiles {:dev {:dependencies [[criterium "0.4.4"] [org.jogamp.gluegen/gluegen-rt "2.3.2" :classifier "natives-macosx-universal"] [org.jogamp.jogl/jogl-all "2.3.2" :classifier "natives-macosx-universal"] [org.jogamp.gluegen/gluegen-rt "2.3.2" :classifier "natives-windows-amd64"] [org.jogamp.jogl/jogl-all "2.3.2" :classifier "natives-windows-amd64"] [org.jogamp.gluegen/gluegen-rt "2.3.2" :classifier "natives-linux-amd64"] [org.jogamp.jogl/jogl-all "2.3.2" :classifier "natives-linux-amd64"] [com.postspectacular/piksel "0.1.4"]] :plugins [[lein-cljsbuild "1.1.7"] [com.cemerick/clojurescript.test "0.3.3"]] :node-dependencies [[benchmark "1.0.0"]] :global-vars {*warn-on-reflection* true} :jvm-opts ^:replace ["-Dclojure.compiler.direct-linking=false"] :aliases {"bench" ["with-profile" "bench" "do" "clean," "perforate," "cljsbuild" "test"]}} :bench {:dependencies [[perforate-x "0.1.0"]] :plugins [[perforate "0.3.4"] [lein-npm "0.6.2"]] :cljsbuild {:builds [{:id "bench" :source-paths ["src" "test" "benchmarks"] :notify-command ["node" "target/cljs/benchmark.js"] :compiler {:target :nodejs :output-to "target/cljs/benchmark.js" :optimizations :simple :pretty-print true}}] :test-commands {"unit-tests" ["phantomjs" :runner "target/geom.js"]}}}} :cljsbuild {:builds [{:id "simple" :source-paths ["src" "test" "examples/gl"] :compiler {:output-to "target/geom.js" :optimizations :whitespace :pretty-print true}} {:source-paths ["src" "examples/gl"] :id "prod" :compiler {:output-to "target/geom.js" :optimizations :advanced :pretty-print false}}] :test-commands {"unit-tests" ["phantomjs" :runner "target/geom.js"]}} :pom-addition [:developers [:developer [:name "Karsten Schmidt"] [:url "http://thi.ng"] [:timezone "0"]]])
38733
(defproject thi.ng/geom "1.0.0-RC4" :description "thi.ng geometry kit - meta project spec including all modules" :url "https://github.com/thi-ng/geom" :license {:name "Apache Software License" :url "http://www.apache.org/licenses/LICENSE-2.0" :distribution :repo} :scm {:name "git" :url "https://github.com/thi-ng/geom"} :min-lein-version "2.4.0" :dependencies [[org.clojure/clojure "1.9.0"] [org.clojure/clojurescript "1.10.238"] [thi.ng/color "1.4.0"] [thi.ng/dstruct "0.2.1"] [thi.ng/math "0.3.0"] [thi.ng/ndarray "0.3.2"] [thi.ng/shadergraph "0.3.0"] [thi.ng/strf "0.2.2"] [thi.ng/typedarrays "0.1.6"] [thi.ng/xerror "0.1.0"] [org.jogamp.gluegen/gluegen-rt "2.3.2"] [org.jogamp.jogl/jogl-all "2.3.2"] [cljs-log "0.2.2"] [hiccup "1.0.5"]] :perforate {:environments [{:namespaces [thi.ng.geom.bench.core.vector]}]} :profiles {:dev {:dependencies [[criterium "0.4.4"] [org.jogamp.gluegen/gluegen-rt "2.3.2" :classifier "natives-macosx-universal"] [org.jogamp.jogl/jogl-all "2.3.2" :classifier "natives-macosx-universal"] [org.jogamp.gluegen/gluegen-rt "2.3.2" :classifier "natives-windows-amd64"] [org.jogamp.jogl/jogl-all "2.3.2" :classifier "natives-windows-amd64"] [org.jogamp.gluegen/gluegen-rt "2.3.2" :classifier "natives-linux-amd64"] [org.jogamp.jogl/jogl-all "2.3.2" :classifier "natives-linux-amd64"] [com.postspectacular/piksel "0.1.4"]] :plugins [[lein-cljsbuild "1.1.7"] [com.cemerick/clojurescript.test "0.3.3"]] :node-dependencies [[benchmark "1.0.0"]] :global-vars {*warn-on-reflection* true} :jvm-opts ^:replace ["-Dclojure.compiler.direct-linking=false"] :aliases {"bench" ["with-profile" "bench" "do" "clean," "perforate," "cljsbuild" "test"]}} :bench {:dependencies [[perforate-x "0.1.0"]] :plugins [[perforate "0.3.4"] [lein-npm "0.6.2"]] :cljsbuild {:builds [{:id "bench" :source-paths ["src" "test" "benchmarks"] :notify-command ["node" "target/cljs/benchmark.js"] :compiler {:target :nodejs :output-to "target/cljs/benchmark.js" :optimizations :simple :pretty-print true}}] :test-commands {"unit-tests" ["phantomjs" :runner "target/geom.js"]}}}} :cljsbuild {:builds [{:id "simple" :source-paths ["src" "test" "examples/gl"] :compiler {:output-to "target/geom.js" :optimizations :whitespace :pretty-print true}} {:source-paths ["src" "examples/gl"] :id "prod" :compiler {:output-to "target/geom.js" :optimizations :advanced :pretty-print false}}] :test-commands {"unit-tests" ["phantomjs" :runner "target/geom.js"]}} :pom-addition [:developers [:developer [:name "<NAME>"] [:url "http://thi.ng"] [:timezone "0"]]])
true
(defproject thi.ng/geom "1.0.0-RC4" :description "thi.ng geometry kit - meta project spec including all modules" :url "https://github.com/thi-ng/geom" :license {:name "Apache Software License" :url "http://www.apache.org/licenses/LICENSE-2.0" :distribution :repo} :scm {:name "git" :url "https://github.com/thi-ng/geom"} :min-lein-version "2.4.0" :dependencies [[org.clojure/clojure "1.9.0"] [org.clojure/clojurescript "1.10.238"] [thi.ng/color "1.4.0"] [thi.ng/dstruct "0.2.1"] [thi.ng/math "0.3.0"] [thi.ng/ndarray "0.3.2"] [thi.ng/shadergraph "0.3.0"] [thi.ng/strf "0.2.2"] [thi.ng/typedarrays "0.1.6"] [thi.ng/xerror "0.1.0"] [org.jogamp.gluegen/gluegen-rt "2.3.2"] [org.jogamp.jogl/jogl-all "2.3.2"] [cljs-log "0.2.2"] [hiccup "1.0.5"]] :perforate {:environments [{:namespaces [thi.ng.geom.bench.core.vector]}]} :profiles {:dev {:dependencies [[criterium "0.4.4"] [org.jogamp.gluegen/gluegen-rt "2.3.2" :classifier "natives-macosx-universal"] [org.jogamp.jogl/jogl-all "2.3.2" :classifier "natives-macosx-universal"] [org.jogamp.gluegen/gluegen-rt "2.3.2" :classifier "natives-windows-amd64"] [org.jogamp.jogl/jogl-all "2.3.2" :classifier "natives-windows-amd64"] [org.jogamp.gluegen/gluegen-rt "2.3.2" :classifier "natives-linux-amd64"] [org.jogamp.jogl/jogl-all "2.3.2" :classifier "natives-linux-amd64"] [com.postspectacular/piksel "0.1.4"]] :plugins [[lein-cljsbuild "1.1.7"] [com.cemerick/clojurescript.test "0.3.3"]] :node-dependencies [[benchmark "1.0.0"]] :global-vars {*warn-on-reflection* true} :jvm-opts ^:replace ["-Dclojure.compiler.direct-linking=false"] :aliases {"bench" ["with-profile" "bench" "do" "clean," "perforate," "cljsbuild" "test"]}} :bench {:dependencies [[perforate-x "0.1.0"]] :plugins [[perforate "0.3.4"] [lein-npm "0.6.2"]] :cljsbuild {:builds [{:id "bench" :source-paths ["src" "test" "benchmarks"] :notify-command ["node" "target/cljs/benchmark.js"] :compiler {:target :nodejs :output-to "target/cljs/benchmark.js" :optimizations :simple :pretty-print true}}] :test-commands {"unit-tests" ["phantomjs" :runner "target/geom.js"]}}}} :cljsbuild {:builds [{:id "simple" :source-paths ["src" "test" "examples/gl"] :compiler {:output-to "target/geom.js" :optimizations :whitespace :pretty-print true}} {:source-paths ["src" "examples/gl"] :id "prod" :compiler {:output-to "target/geom.js" :optimizations :advanced :pretty-print false}}] :test-commands {"unit-tests" ["phantomjs" :runner "target/geom.js"]}} :pom-addition [:developers [:developer [:name "PI:NAME:<NAME>END_PI"] [:url "http://thi.ng"] [:timezone "0"]]])
[ { "context": ";\n; Copyright © 2021 Peter Monks\n;\n; Licensed under the Apache License, Version 2.", "end": 32, "score": 0.999522864818573, "start": 21, "tag": "NAME", "value": "Peter Monks" } ]
src/tools_convenience/api.clj
pmonks/tools-convenience
0
; ; Copyright © 2021 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 tools-convenience.api "Convenience fns for tools.build scripts." (:require [clojure.string :as s] [clojure.tools.build.api :as b])) (defmulti exec "Executes the given command line, expressed as either a string or a sequential (vector or list), optionally with other clojure.tools.build.api/process options as a second argument. Throws an ExceptionInfo on non-zero status code, containing the entire execution result (from clojure.tools.build.api/process) in the info map." {:arglists '([command-line] [command-line opts])} (fn [& args] (sequential? (first args)))) (defmethod exec true ([command-line] (exec command-line nil)) ([command-line opts] (when-let [command-line (seq (remove s/blank? command-line))] (let [result (b/process (into {:command-args command-line} opts))] (if (not= 0 (:exit result)) (throw (ex-info (str "Command '" (s/join " " command-line) "' failed (" (:exit result) ").") result)) result))))) (defmethod exec false ([command-line] (exec command-line nil)) ([command-line opts] (when-not (s/blank? command-line) (exec (s/split command-line #"\s+") opts)))) (defn- ensure-command-fn [command-name] (if-not (s/blank? command-name) (try (exec ["sh" "-c" (str "command -v " command-name)] {:out :capture :err :capture}) ; We have to use sh rather than command directly because Linux is stupid sometimes... true (catch clojure.lang.ExceptionInfo ei (throw (ex-info (str "Command '" command-name "' was not found.") {} ei)))) (throw (ex-info (str "No command name provided.") {})))) (def ^{:doc "Ensures that the given command is available (note: POSIX only). Returns true if it exists, throws an exception otherwise. Notes: * This fn is memoized, so calling it repeatedly with the same command-name will not hurt performance." :arglists '([command-name])} ensure-command (memoize ensure-command-fn)) (defn clojure "Execute clojure reproducibly (-Srepro) with the given args (strings)." [& args] (ensure-command "clojure") (if (> (count (filter (complement s/blank?) args)) 0) (exec (concat ["clojure" "-J-Dclojure.main.report=stderr" "-Srepro"] args)) (throw (ex-info "No clojure arguments provided, but at least one is required." {})))) ; Attempt to prevent clojure from dropping into a REPL, since that will cause everything to lock (defn clojure-silent "Execute clojure reproducibly (-Srepro) with the given args (strings), capturing and returning stdout and stderr (as a result map as per clojure.tools.build.api/process)." [& args] (ensure-command "clojure") (if (> (count (filter (complement s/blank?) args)) 0) (exec (concat ["clojure" "-J-Dclojure.main.report=stderr" "-Srepro"] args) {:out :capture :err :capture}) (throw (ex-info "No clojure arguments provided, but at least one is required." {})))) ; Attempt to prevent clojure from dropping into a REPL, since that will cause everything to lock (defn- safe-name "A nil-safe version of `name`. 🙄" [x] (when x (name x))) (defn git "Execute git with the given args (which can be strings or keywords), capturing and returning the output (stdout only)." [& args] (ensure-command "git") (if-let [args (seq (remove s/blank? (map safe-name args)))] (s/trim (str (:out (exec (concat ["git"] args) {:out :capture})))) (throw (ex-info "No git arguments provided, but they are mandatory." {})))) (defn git-current-branch "The current git branch." [] (git :branch "--show-current")) (defn git-current-commit "The sha of the current commit." [] (git :show "-s" "--format=%H")) (defn git-exact-tag "Returns the exact tag for the given sha (or current commit sha if not provided), or nil if there is no tag for that sha." ([] (try (git :describe "--tags" "--exact-match") (catch clojure.lang.ExceptionInfo _ nil))) ([sha] (try (git :describe "--tags" "--exact-match" sha) (catch clojure.lang.ExceptionInfo _ nil)))) (defn git-nearest-tag "The nearest tag to the current commit." [] (git :describe "--abbrev=0")) (defn git-tag-commit "Returns the commit sha for the given tag, or nil if the tag doesn't exist." [tag] (try (git :rev-list "-n" "1" tag) (catch clojure.lang.ExceptionInfo _ nil))) (defn git-remote "The URL of the origin server (if any). Note: includes the .git extension." [] (try (let [repo (git :config "--get" "remote.origin.url")] (when-not (s/blank? repo) repo)) (catch clojure.lang.ExceptionInfo _ nil)))
68142
; ; Copyright © 2021 <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 tools-convenience.api "Convenience fns for tools.build scripts." (:require [clojure.string :as s] [clojure.tools.build.api :as b])) (defmulti exec "Executes the given command line, expressed as either a string or a sequential (vector or list), optionally with other clojure.tools.build.api/process options as a second argument. Throws an ExceptionInfo on non-zero status code, containing the entire execution result (from clojure.tools.build.api/process) in the info map." {:arglists '([command-line] [command-line opts])} (fn [& args] (sequential? (first args)))) (defmethod exec true ([command-line] (exec command-line nil)) ([command-line opts] (when-let [command-line (seq (remove s/blank? command-line))] (let [result (b/process (into {:command-args command-line} opts))] (if (not= 0 (:exit result)) (throw (ex-info (str "Command '" (s/join " " command-line) "' failed (" (:exit result) ").") result)) result))))) (defmethod exec false ([command-line] (exec command-line nil)) ([command-line opts] (when-not (s/blank? command-line) (exec (s/split command-line #"\s+") opts)))) (defn- ensure-command-fn [command-name] (if-not (s/blank? command-name) (try (exec ["sh" "-c" (str "command -v " command-name)] {:out :capture :err :capture}) ; We have to use sh rather than command directly because Linux is stupid sometimes... true (catch clojure.lang.ExceptionInfo ei (throw (ex-info (str "Command '" command-name "' was not found.") {} ei)))) (throw (ex-info (str "No command name provided.") {})))) (def ^{:doc "Ensures that the given command is available (note: POSIX only). Returns true if it exists, throws an exception otherwise. Notes: * This fn is memoized, so calling it repeatedly with the same command-name will not hurt performance." :arglists '([command-name])} ensure-command (memoize ensure-command-fn)) (defn clojure "Execute clojure reproducibly (-Srepro) with the given args (strings)." [& args] (ensure-command "clojure") (if (> (count (filter (complement s/blank?) args)) 0) (exec (concat ["clojure" "-J-Dclojure.main.report=stderr" "-Srepro"] args)) (throw (ex-info "No clojure arguments provided, but at least one is required." {})))) ; Attempt to prevent clojure from dropping into a REPL, since that will cause everything to lock (defn clojure-silent "Execute clojure reproducibly (-Srepro) with the given args (strings), capturing and returning stdout and stderr (as a result map as per clojure.tools.build.api/process)." [& args] (ensure-command "clojure") (if (> (count (filter (complement s/blank?) args)) 0) (exec (concat ["clojure" "-J-Dclojure.main.report=stderr" "-Srepro"] args) {:out :capture :err :capture}) (throw (ex-info "No clojure arguments provided, but at least one is required." {})))) ; Attempt to prevent clojure from dropping into a REPL, since that will cause everything to lock (defn- safe-name "A nil-safe version of `name`. 🙄" [x] (when x (name x))) (defn git "Execute git with the given args (which can be strings or keywords), capturing and returning the output (stdout only)." [& args] (ensure-command "git") (if-let [args (seq (remove s/blank? (map safe-name args)))] (s/trim (str (:out (exec (concat ["git"] args) {:out :capture})))) (throw (ex-info "No git arguments provided, but they are mandatory." {})))) (defn git-current-branch "The current git branch." [] (git :branch "--show-current")) (defn git-current-commit "The sha of the current commit." [] (git :show "-s" "--format=%H")) (defn git-exact-tag "Returns the exact tag for the given sha (or current commit sha if not provided), or nil if there is no tag for that sha." ([] (try (git :describe "--tags" "--exact-match") (catch clojure.lang.ExceptionInfo _ nil))) ([sha] (try (git :describe "--tags" "--exact-match" sha) (catch clojure.lang.ExceptionInfo _ nil)))) (defn git-nearest-tag "The nearest tag to the current commit." [] (git :describe "--abbrev=0")) (defn git-tag-commit "Returns the commit sha for the given tag, or nil if the tag doesn't exist." [tag] (try (git :rev-list "-n" "1" tag) (catch clojure.lang.ExceptionInfo _ nil))) (defn git-remote "The URL of the origin server (if any). Note: includes the .git extension." [] (try (let [repo (git :config "--get" "remote.origin.url")] (when-not (s/blank? repo) repo)) (catch clojure.lang.ExceptionInfo _ nil)))
true
; ; Copyright © 2021 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 tools-convenience.api "Convenience fns for tools.build scripts." (:require [clojure.string :as s] [clojure.tools.build.api :as b])) (defmulti exec "Executes the given command line, expressed as either a string or a sequential (vector or list), optionally with other clojure.tools.build.api/process options as a second argument. Throws an ExceptionInfo on non-zero status code, containing the entire execution result (from clojure.tools.build.api/process) in the info map." {:arglists '([command-line] [command-line opts])} (fn [& args] (sequential? (first args)))) (defmethod exec true ([command-line] (exec command-line nil)) ([command-line opts] (when-let [command-line (seq (remove s/blank? command-line))] (let [result (b/process (into {:command-args command-line} opts))] (if (not= 0 (:exit result)) (throw (ex-info (str "Command '" (s/join " " command-line) "' failed (" (:exit result) ").") result)) result))))) (defmethod exec false ([command-line] (exec command-line nil)) ([command-line opts] (when-not (s/blank? command-line) (exec (s/split command-line #"\s+") opts)))) (defn- ensure-command-fn [command-name] (if-not (s/blank? command-name) (try (exec ["sh" "-c" (str "command -v " command-name)] {:out :capture :err :capture}) ; We have to use sh rather than command directly because Linux is stupid sometimes... true (catch clojure.lang.ExceptionInfo ei (throw (ex-info (str "Command '" command-name "' was not found.") {} ei)))) (throw (ex-info (str "No command name provided.") {})))) (def ^{:doc "Ensures that the given command is available (note: POSIX only). Returns true if it exists, throws an exception otherwise. Notes: * This fn is memoized, so calling it repeatedly with the same command-name will not hurt performance." :arglists '([command-name])} ensure-command (memoize ensure-command-fn)) (defn clojure "Execute clojure reproducibly (-Srepro) with the given args (strings)." [& args] (ensure-command "clojure") (if (> (count (filter (complement s/blank?) args)) 0) (exec (concat ["clojure" "-J-Dclojure.main.report=stderr" "-Srepro"] args)) (throw (ex-info "No clojure arguments provided, but at least one is required." {})))) ; Attempt to prevent clojure from dropping into a REPL, since that will cause everything to lock (defn clojure-silent "Execute clojure reproducibly (-Srepro) with the given args (strings), capturing and returning stdout and stderr (as a result map as per clojure.tools.build.api/process)." [& args] (ensure-command "clojure") (if (> (count (filter (complement s/blank?) args)) 0) (exec (concat ["clojure" "-J-Dclojure.main.report=stderr" "-Srepro"] args) {:out :capture :err :capture}) (throw (ex-info "No clojure arguments provided, but at least one is required." {})))) ; Attempt to prevent clojure from dropping into a REPL, since that will cause everything to lock (defn- safe-name "A nil-safe version of `name`. 🙄" [x] (when x (name x))) (defn git "Execute git with the given args (which can be strings or keywords), capturing and returning the output (stdout only)." [& args] (ensure-command "git") (if-let [args (seq (remove s/blank? (map safe-name args)))] (s/trim (str (:out (exec (concat ["git"] args) {:out :capture})))) (throw (ex-info "No git arguments provided, but they are mandatory." {})))) (defn git-current-branch "The current git branch." [] (git :branch "--show-current")) (defn git-current-commit "The sha of the current commit." [] (git :show "-s" "--format=%H")) (defn git-exact-tag "Returns the exact tag for the given sha (or current commit sha if not provided), or nil if there is no tag for that sha." ([] (try (git :describe "--tags" "--exact-match") (catch clojure.lang.ExceptionInfo _ nil))) ([sha] (try (git :describe "--tags" "--exact-match" sha) (catch clojure.lang.ExceptionInfo _ nil)))) (defn git-nearest-tag "The nearest tag to the current commit." [] (git :describe "--abbrev=0")) (defn git-tag-commit "Returns the commit sha for the given tag, or nil if the tag doesn't exist." [tag] (try (git :rev-list "-n" "1" tag) (catch clojure.lang.ExceptionInfo _ nil))) (defn git-remote "The URL of the origin server (if any). Note: includes the .git extension." [] (try (let [repo (git :config "--get" "remote.origin.url")] (when-not (s/blank? repo) repo)) (catch clojure.lang.ExceptionInfo _ nil)))
[ { "context": "tcp-client {:host \"riemann-host\"})))\n\n(def token \"xoxb-64790720018-RhD3YOsLWJ4yc13GlX0CDeQe\")\n(defn rcv-msg[evt]\n\t(-> @c (r/send-event {:serv", "end": 184, "score": 0.9992479681968689, "start": 143, "tag": "KEY", "value": "xoxb-64790720018-RhD3YOsLWJ4yc13GlX0CDeQe" } ]
Chapter 10 Code/riemaning/src/riemaning/slacking2.clj
PacktPublishing/Clojure-Programming-Cookbook
14
(use 'slack-rtm.core) (require '[riemann.client :as r]) ; slack to riemann (def c (atom (r/tcp-client {:host "riemann-host"}))) (def token "xoxb-64790720018-RhD3YOsLWJ4yc13GlX0CDeQe") (defn rcv-msg[evt] (-> @c (r/send-event {:service "slack" :description (:message evt)}))) (def rtm-conn (connect token :on-receive rcv-msg))
38300
(use 'slack-rtm.core) (require '[riemann.client :as r]) ; slack to riemann (def c (atom (r/tcp-client {:host "riemann-host"}))) (def token "<KEY>") (defn rcv-msg[evt] (-> @c (r/send-event {:service "slack" :description (:message evt)}))) (def rtm-conn (connect token :on-receive rcv-msg))
true
(use 'slack-rtm.core) (require '[riemann.client :as r]) ; slack to riemann (def c (atom (r/tcp-client {:host "riemann-host"}))) (def token "PI:KEY:<KEY>END_PI") (defn rcv-msg[evt] (-> @c (r/send-event {:service "slack" :description (:message evt)}))) (def rtm-conn (connect token :on-receive rcv-msg))
[ { "context": "footer\n [!db]\n [:footer\n [:div \"Copyright 2018 Luke Turner\"]\n [:div [:a {:href \"https://github.com/luketur", "end": 476, "score": 0.9998239278793335, "start": 465, "tag": "NAME", "value": "Luke Turner" }, { "context": "Turner\"]\n [:div [:a {:href \"https://github.com/luketurner/golem\"} \"Github\"]]])\n\n(defn component [!db", "end": 522, "score": 0.528991162776947, "start": 520, "tag": "USERNAME", "value": "uk" } ]
src/golem/ui/app.cljs
luketurner/golem
0
(ns golem.ui.app (:require [golem.ui.viewport :as viewport] [golem.ui.header :as header] [golem.ui.sidebar :as sidebar] [cljs.spec.alpha :as s])) (s/def ::ui (s/keys :req-un [:golem.ui.sidebar/sidebar :golem.ui.viewport/viewport])) (def default-state {:sidebar sidebar/default-state :viewport viewport/default-state}) (defn footer [!db] [:footer [:div "Copyright 2018 Luke Turner"] [:div [:a {:href "https://github.com/luketurner/golem"} "Github"]]]) (defn component [!db] (let [sidebar? @(sidebar/is-open? !db)] [:div.app-container [:div.app-header-container [header/component !db]] [:div.app-main-container (when sidebar? [:div.app-sidebar-container [sidebar/component !db]]) [viewport/component !db]] [:div.app-footer-container [footer !db]]]))
18263
(ns golem.ui.app (:require [golem.ui.viewport :as viewport] [golem.ui.header :as header] [golem.ui.sidebar :as sidebar] [cljs.spec.alpha :as s])) (s/def ::ui (s/keys :req-un [:golem.ui.sidebar/sidebar :golem.ui.viewport/viewport])) (def default-state {:sidebar sidebar/default-state :viewport viewport/default-state}) (defn footer [!db] [:footer [:div "Copyright 2018 <NAME>"] [:div [:a {:href "https://github.com/luketurner/golem"} "Github"]]]) (defn component [!db] (let [sidebar? @(sidebar/is-open? !db)] [:div.app-container [:div.app-header-container [header/component !db]] [:div.app-main-container (when sidebar? [:div.app-sidebar-container [sidebar/component !db]]) [viewport/component !db]] [:div.app-footer-container [footer !db]]]))
true
(ns golem.ui.app (:require [golem.ui.viewport :as viewport] [golem.ui.header :as header] [golem.ui.sidebar :as sidebar] [cljs.spec.alpha :as s])) (s/def ::ui (s/keys :req-un [:golem.ui.sidebar/sidebar :golem.ui.viewport/viewport])) (def default-state {:sidebar sidebar/default-state :viewport viewport/default-state}) (defn footer [!db] [:footer [:div "Copyright 2018 PI:NAME:<NAME>END_PI"] [:div [:a {:href "https://github.com/luketurner/golem"} "Github"]]]) (defn component [!db] (let [sidebar? @(sidebar/is-open? !db)] [:div.app-container [:div.app-header-container [header/component !db]] [:div.app-main-container (when sidebar? [:div.app-sidebar-container [sidebar/component !db]]) [viewport/component !db]] [:div.app-footer-container [footer !db]]]))
[ { "context": ";; Copyright (c) Nicola Mometto, Rich Hickey & contributors.\n;; The use and distr", "end": 31, "score": 0.9998592734336853, "start": 17, "tag": "NAME", "value": "Nicola Mometto" }, { "context": ";; Copyright (c) Nicola Mometto, Rich Hickey & contributors.\n;; The use and distribution terms", "end": 44, "score": 0.9998513460159302, "start": 33, "tag": "NAME", "value": "Rich Hickey" } ]
server/target/clojure/tools/analyzer/passes/trim.clj
OctavioBR/healthcheck
15
;; Copyright (c) Nicola Mometto, Rich Hickey & contributors. ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns clojure.tools.analyzer.passes.trim (:require [clojure.tools.analyzer.passes.elide-meta :refer [elide-meta]] [clojure.tools.analyzer.ast :refer [postwalk]])) (defmulti -trim :op) (defmethod -trim :default [ast] ast) (defn preserving-raw-forms [{:keys [form raw-forms] :as ast} body] (let [raw-forms (reverse (cons form raw-forms))] (update-in (into ast body) [:raw-forms] into raw-forms))) (defmethod -trim :do [{:keys [statements ret form] :as ast}] (if (and (every? :literal? statements) (not (:tag (meta form)))) (preserving-raw-forms (dissoc ast :children :statements :ret) ret) ast)) ;;TODO: letfn/loop (defmethod -trim :let [{:keys [bindings body form] :as ast}] (if (and (or (and (every? (comp :literal? :init) bindings) (:literal? body)) (empty? bindings)) (not (:tag (meta form)))) (preserving-raw-forms (dissoc ast :children :bindings :body) body) ast)) (defmethod -trim :try [{:keys [catches finally body form] :as ast}] (if (and (empty? catches) (empty? finally) (not (:tag (meta form)))) (preserving-raw-forms (dissoc ast :children :body :finally :catches) body) ast)) (defn trim "Trims the AST of unnecessary nodes, e.g. (do (do 1)) -> 1" {:pass-info {:walk :none :depends #{} :after #{#'elide-meta}}} [ast] (postwalk ast -trim))
32221
;; Copyright (c) <NAME>, <NAME> & contributors. ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns clojure.tools.analyzer.passes.trim (:require [clojure.tools.analyzer.passes.elide-meta :refer [elide-meta]] [clojure.tools.analyzer.ast :refer [postwalk]])) (defmulti -trim :op) (defmethod -trim :default [ast] ast) (defn preserving-raw-forms [{:keys [form raw-forms] :as ast} body] (let [raw-forms (reverse (cons form raw-forms))] (update-in (into ast body) [:raw-forms] into raw-forms))) (defmethod -trim :do [{:keys [statements ret form] :as ast}] (if (and (every? :literal? statements) (not (:tag (meta form)))) (preserving-raw-forms (dissoc ast :children :statements :ret) ret) ast)) ;;TODO: letfn/loop (defmethod -trim :let [{:keys [bindings body form] :as ast}] (if (and (or (and (every? (comp :literal? :init) bindings) (:literal? body)) (empty? bindings)) (not (:tag (meta form)))) (preserving-raw-forms (dissoc ast :children :bindings :body) body) ast)) (defmethod -trim :try [{:keys [catches finally body form] :as ast}] (if (and (empty? catches) (empty? finally) (not (:tag (meta form)))) (preserving-raw-forms (dissoc ast :children :body :finally :catches) body) ast)) (defn trim "Trims the AST of unnecessary nodes, e.g. (do (do 1)) -> 1" {:pass-info {:walk :none :depends #{} :after #{#'elide-meta}}} [ast] (postwalk ast -trim))
true
;; Copyright (c) PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI & contributors. ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns clojure.tools.analyzer.passes.trim (:require [clojure.tools.analyzer.passes.elide-meta :refer [elide-meta]] [clojure.tools.analyzer.ast :refer [postwalk]])) (defmulti -trim :op) (defmethod -trim :default [ast] ast) (defn preserving-raw-forms [{:keys [form raw-forms] :as ast} body] (let [raw-forms (reverse (cons form raw-forms))] (update-in (into ast body) [:raw-forms] into raw-forms))) (defmethod -trim :do [{:keys [statements ret form] :as ast}] (if (and (every? :literal? statements) (not (:tag (meta form)))) (preserving-raw-forms (dissoc ast :children :statements :ret) ret) ast)) ;;TODO: letfn/loop (defmethod -trim :let [{:keys [bindings body form] :as ast}] (if (and (or (and (every? (comp :literal? :init) bindings) (:literal? body)) (empty? bindings)) (not (:tag (meta form)))) (preserving-raw-forms (dissoc ast :children :bindings :body) body) ast)) (defmethod -trim :try [{:keys [catches finally body form] :as ast}] (if (and (empty? catches) (empty? finally) (not (:tag (meta form)))) (preserving-raw-forms (dissoc ast :children :body :finally :catches) body) ast)) (defn trim "Trims the AST of unnecessary nodes, e.g. (do (do 1)) -> 1" {:pass-info {:walk :none :depends #{} :after #{#'elide-meta}}} [ast] (postwalk ast -trim))
[ { "context": "[env {}\n data #:user{:password \"1234567\" :username \"bob\"}\n f (::pc/mutate", "end": 845, "score": 0.9993791580200195, "start": 838, "tag": "PASSWORD", "value": "1234567" }, { "context": " data #:user{:password \"1234567\" :username \"bob\"}\n f (::pc/mutate mu.session/regi", "end": 861, "score": 0.953070878982544, "start": 858, "tag": "USERNAME", "value": "bob" }, { "context": "ser{:password m.users/default-password :username \"bob\"}\n response ((::pc/mutate mu.session/login", "end": 1281, "score": 0.85490483045578, "start": 1278, "tag": "USERNAME", "value": "bob" } ]
src/test/dinsro/mutations/session_test.clj
duck1123/dinsro
2
(ns dinsro.mutations.session-test (:require [clojure.test :refer [deftest use-fixtures]] [com.fulcrologic.rad.authorization :as auth] [com.wsscode.pathom.connect :as pc] [dinsro.model.users :as m.users] [dinsro.mutations.session :as mu.session] [dinsro.specs :as ds] [dinsro.test-helpers :as th] [fulcro-spec.check :as _] [fulcro-spec.core :refer [assertions]] [taoensso.timbre :as log])) (def schemata []) (use-fixtures :each (fn [f] (th/start-db f schemata))) (deftest do-register-success (let [password (ds/gen-key ::m.users/password) username (ds/gen-key ::m.users/name) response (mu.session/do-register username password)] (assertions (::m.users/name response) => username))) (deftest register-success (try (let [env {} data #:user{:password "1234567" :username "bob"} f (::pc/mutate mu.session/register) response (f env data)] (assertions (::m.users/name response) => (:user/username data) (::m.users/id response) =check=> (_/valid?* ::m.users/id))) (catch Exception ex (log/error ex "caught")))) (deftest login (let [env {:request {:session {}}} data #:user{:password m.users/default-password :username "bob"} response ((::pc/mutate mu.session/login) env data)] (assertions response => {::auth/provider :local ::auth/status :failed})))
115856
(ns dinsro.mutations.session-test (:require [clojure.test :refer [deftest use-fixtures]] [com.fulcrologic.rad.authorization :as auth] [com.wsscode.pathom.connect :as pc] [dinsro.model.users :as m.users] [dinsro.mutations.session :as mu.session] [dinsro.specs :as ds] [dinsro.test-helpers :as th] [fulcro-spec.check :as _] [fulcro-spec.core :refer [assertions]] [taoensso.timbre :as log])) (def schemata []) (use-fixtures :each (fn [f] (th/start-db f schemata))) (deftest do-register-success (let [password (ds/gen-key ::m.users/password) username (ds/gen-key ::m.users/name) response (mu.session/do-register username password)] (assertions (::m.users/name response) => username))) (deftest register-success (try (let [env {} data #:user{:password "<PASSWORD>" :username "bob"} f (::pc/mutate mu.session/register) response (f env data)] (assertions (::m.users/name response) => (:user/username data) (::m.users/id response) =check=> (_/valid?* ::m.users/id))) (catch Exception ex (log/error ex "caught")))) (deftest login (let [env {:request {:session {}}} data #:user{:password m.users/default-password :username "bob"} response ((::pc/mutate mu.session/login) env data)] (assertions response => {::auth/provider :local ::auth/status :failed})))
true
(ns dinsro.mutations.session-test (:require [clojure.test :refer [deftest use-fixtures]] [com.fulcrologic.rad.authorization :as auth] [com.wsscode.pathom.connect :as pc] [dinsro.model.users :as m.users] [dinsro.mutations.session :as mu.session] [dinsro.specs :as ds] [dinsro.test-helpers :as th] [fulcro-spec.check :as _] [fulcro-spec.core :refer [assertions]] [taoensso.timbre :as log])) (def schemata []) (use-fixtures :each (fn [f] (th/start-db f schemata))) (deftest do-register-success (let [password (ds/gen-key ::m.users/password) username (ds/gen-key ::m.users/name) response (mu.session/do-register username password)] (assertions (::m.users/name response) => username))) (deftest register-success (try (let [env {} data #:user{:password "PI:PASSWORD:<PASSWORD>END_PI" :username "bob"} f (::pc/mutate mu.session/register) response (f env data)] (assertions (::m.users/name response) => (:user/username data) (::m.users/id response) =check=> (_/valid?* ::m.users/id))) (catch Exception ex (log/error ex "caught")))) (deftest login (let [env {:request {:session {}}} data #:user{:password m.users/default-password :username "bob"} response ((::pc/mutate mu.session/login) env data)] (assertions response => {::auth/provider :local ::auth/status :failed})))
[ { "context": " \" <author>\"\n \" <name>John Doe</name>\"\n \" </author>\"\n ", "end": 849, "score": 0.9997454881668091, "start": 841, "tag": "NAME", "value": "John Doe" } ]
test/betterfeed/core_test.clj
oholiab/betterfeed
4
(ns betterfeed.core-test (:require [clojure.test :refer :all] [betterfeed.core :refer :all] [rss-utils.core :as rss] [clojure.java.io :as io] [clojure.data.zip.xml :as dzx] [clojure.zip :as zip])) (rss/define-atom-xmlns) (defn string->stream ([s] (string->stream s "UTF-8")) ([s encoding] (-> s (.getBytes encoding) (java.io.ByteArrayInputStream.)))) (def example-atom-str (clojure.string/join "\n" [ "<?xml version=\"1.0\" encoding=\"utf-8\"?>" "<feed xmlns=\"http://www.w3.org/2005/Atom\">" " <title>Example Feed</title>" " <link href=\"http://example.org/\"/>" " <updated>2003-12-13T18:30:02Z</updated>" " <author>" " <name>John Doe</name>" " </author>" " <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>" " <entry>" " <title>Atom-Powered Robots Run Amok</title>" " <link href=\"http://example.org/2003/12/13/atom03\"/>" " <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>" " <updated>2003-12-13T18:30:02Z</updated>" " <summary>Some text.</summary>" " </entry>" "</feed>"])) (def example-rss-str (clojure.string/join "\n" [ "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" "<rss version=\"2.0\">" " <channel>" " <title>W3Schools Home Page</title>" " <link>https://www.w3schools.com</link>" " <description>Free web building tutorials</description>" " <item>" " <title>RSS Tutorial</title>" " <link>https://www.w3schools.com/xml/xml_rss.asp</link>" " <description>New RSS tutorial on W3Schools</description>" " </item>" " <item>" " <title>XML Tutorial</title>" " <link>https://www.w3schools.com/xml</link>" " <description>New XML tutorial on W3Schools</description>" " </item>" " </channel>" "</rss>"])) (def example-atom (clojure.data.xml/parse (string->stream example-atom-str))) (def example-rss (clojure.data.xml/parse (string->stream example-rss-str))) ; FIXME: These two should be constructed data, otherwise they're being used to test the funcitons that produced them. (def atom-first-item (rss/zip-at-first-item example-atom)) (def rss-first-item (rss/zip-at-first-item example-rss)) (deftest test-get-host (testing "returns host part of url" (is (= (get-host "https://google.com/blarg") "google.com")) (is (= (get-host "http://google.com/") "google.com")))) (deftest test-resolve-redirect ; FIXME: This requires a network connection and outside behaviour (testing "will resolve a flaky remote redirect" (is (= (resolve-redirect "http://grimmwa.re") "https://www.grimmwa.re/")))) (deftest test-get-real-url ; FIXME: This requires a network connection and outside behaviour (testing "will resolve a flaky remote redirect when the domain is in the will-3xx ref" (dosync (ref-set will-3xx '("grimmwa.re"))) (is (= (get-real-url "http://grimmwa.re") "https://www.grimmwa.re/")) (is (= (get-real-url "http://anything-else.com") "http://anything-else.com")))) (deftest test-get-body-method (testing "Returns body method for domain in the body-method ref, or get-body for anything else" (defn blerg [x] x) (dosync (ref-set body-method {"grimmwa.re" blerg})) (is (= (get-body-method "https://grimmwa.re") blerg)) (is (= (get-body-method "https://google.com") get-body)))) (deftest test-fetch-local ; FIXME: This requires a network connection and outside behaviour (testing "works" (let [target-file "/tmp/betterfeed-test"] (is (= (fetch-local "https://google.com" target-file) "file:///tmp/betterfeed-test")) (is (= (.exists (clojure.java.io/as-file target-file)) true))))) (deftest test-get-link-from-item (testing "Gets the correct link form the item" (is (= (get-link-from-item rss-first-item) "https://www.w3schools.com/xml/xml_rss.asp")) ;FIXME: Make this work for atom ;(is (= (get-link-from-item atom-first-item) "https://www.w3schools.com/xml/xml_rss.asp")) )) (deftest test-update-item ; FIXME: this is a hot mess - make a convenience method for lookups (testing "creates a new item value" (is (= (-> (dzx/xml1-> rss-first-item :link) zip/node :content first) "https://www.w3schools.com/xml/xml_rss.asp")) (let [new-item (update-item rss-first-item :link "not here")] (is (= (-> (dzx/xml1-> new-item :link) zip/node :content first) "not here"))))) (deftest test-has-tag (testing "returns true when an item has a tag, otherwise false" (is (= (has-tag? :link rss-first-item) true)) (is (= (has-tag? ::atomfeed/link atom-first-item) true)) (is (= (has-tag? :linkogram rss-first-item) false)) (is (= (has-tag? :linkogram atom-first-item) false)))) (deftest test-insert-tag (testing "correctly inserts a missing tag" (is (= (has-tag? :linkogram rss-first-item) false)) (let [new-item (insert-tag rss-first-item :linkogram "bananas")] (is (= (has-tag? :linkogram new-item) true)) (is (= (-> (dzx/xml1-> new-item :linkogram) zip/node :content first) "bananas"))))) (deftest test-get-all-tag (testing "returns all values of tag type" (is (= (get-all-tag :link example-rss) '("https://www.w3schools.com/xml/xml_rss.asp" "https://www.w3schools.com/xml"))))) (deftest test-get-all-links (testing "returns all links from a feed" (is (= (get-all-links example-rss) '("https://www.w3schools.com/xml/xml_rss.asp" "https://www.w3schools.com/xml"))) ; FIXME: make work for atom #_(is (= (get-all-links example-atom) '("https://www.w3schools.com/xml/xml_rss.asp" "https://www.w3schools.com/xml"))) ))
63778
(ns betterfeed.core-test (:require [clojure.test :refer :all] [betterfeed.core :refer :all] [rss-utils.core :as rss] [clojure.java.io :as io] [clojure.data.zip.xml :as dzx] [clojure.zip :as zip])) (rss/define-atom-xmlns) (defn string->stream ([s] (string->stream s "UTF-8")) ([s encoding] (-> s (.getBytes encoding) (java.io.ByteArrayInputStream.)))) (def example-atom-str (clojure.string/join "\n" [ "<?xml version=\"1.0\" encoding=\"utf-8\"?>" "<feed xmlns=\"http://www.w3.org/2005/Atom\">" " <title>Example Feed</title>" " <link href=\"http://example.org/\"/>" " <updated>2003-12-13T18:30:02Z</updated>" " <author>" " <name><NAME></name>" " </author>" " <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>" " <entry>" " <title>Atom-Powered Robots Run Amok</title>" " <link href=\"http://example.org/2003/12/13/atom03\"/>" " <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>" " <updated>2003-12-13T18:30:02Z</updated>" " <summary>Some text.</summary>" " </entry>" "</feed>"])) (def example-rss-str (clojure.string/join "\n" [ "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" "<rss version=\"2.0\">" " <channel>" " <title>W3Schools Home Page</title>" " <link>https://www.w3schools.com</link>" " <description>Free web building tutorials</description>" " <item>" " <title>RSS Tutorial</title>" " <link>https://www.w3schools.com/xml/xml_rss.asp</link>" " <description>New RSS tutorial on W3Schools</description>" " </item>" " <item>" " <title>XML Tutorial</title>" " <link>https://www.w3schools.com/xml</link>" " <description>New XML tutorial on W3Schools</description>" " </item>" " </channel>" "</rss>"])) (def example-atom (clojure.data.xml/parse (string->stream example-atom-str))) (def example-rss (clojure.data.xml/parse (string->stream example-rss-str))) ; FIXME: These two should be constructed data, otherwise they're being used to test the funcitons that produced them. (def atom-first-item (rss/zip-at-first-item example-atom)) (def rss-first-item (rss/zip-at-first-item example-rss)) (deftest test-get-host (testing "returns host part of url" (is (= (get-host "https://google.com/blarg") "google.com")) (is (= (get-host "http://google.com/") "google.com")))) (deftest test-resolve-redirect ; FIXME: This requires a network connection and outside behaviour (testing "will resolve a flaky remote redirect" (is (= (resolve-redirect "http://grimmwa.re") "https://www.grimmwa.re/")))) (deftest test-get-real-url ; FIXME: This requires a network connection and outside behaviour (testing "will resolve a flaky remote redirect when the domain is in the will-3xx ref" (dosync (ref-set will-3xx '("grimmwa.re"))) (is (= (get-real-url "http://grimmwa.re") "https://www.grimmwa.re/")) (is (= (get-real-url "http://anything-else.com") "http://anything-else.com")))) (deftest test-get-body-method (testing "Returns body method for domain in the body-method ref, or get-body for anything else" (defn blerg [x] x) (dosync (ref-set body-method {"grimmwa.re" blerg})) (is (= (get-body-method "https://grimmwa.re") blerg)) (is (= (get-body-method "https://google.com") get-body)))) (deftest test-fetch-local ; FIXME: This requires a network connection and outside behaviour (testing "works" (let [target-file "/tmp/betterfeed-test"] (is (= (fetch-local "https://google.com" target-file) "file:///tmp/betterfeed-test")) (is (= (.exists (clojure.java.io/as-file target-file)) true))))) (deftest test-get-link-from-item (testing "Gets the correct link form the item" (is (= (get-link-from-item rss-first-item) "https://www.w3schools.com/xml/xml_rss.asp")) ;FIXME: Make this work for atom ;(is (= (get-link-from-item atom-first-item) "https://www.w3schools.com/xml/xml_rss.asp")) )) (deftest test-update-item ; FIXME: this is a hot mess - make a convenience method for lookups (testing "creates a new item value" (is (= (-> (dzx/xml1-> rss-first-item :link) zip/node :content first) "https://www.w3schools.com/xml/xml_rss.asp")) (let [new-item (update-item rss-first-item :link "not here")] (is (= (-> (dzx/xml1-> new-item :link) zip/node :content first) "not here"))))) (deftest test-has-tag (testing "returns true when an item has a tag, otherwise false" (is (= (has-tag? :link rss-first-item) true)) (is (= (has-tag? ::atomfeed/link atom-first-item) true)) (is (= (has-tag? :linkogram rss-first-item) false)) (is (= (has-tag? :linkogram atom-first-item) false)))) (deftest test-insert-tag (testing "correctly inserts a missing tag" (is (= (has-tag? :linkogram rss-first-item) false)) (let [new-item (insert-tag rss-first-item :linkogram "bananas")] (is (= (has-tag? :linkogram new-item) true)) (is (= (-> (dzx/xml1-> new-item :linkogram) zip/node :content first) "bananas"))))) (deftest test-get-all-tag (testing "returns all values of tag type" (is (= (get-all-tag :link example-rss) '("https://www.w3schools.com/xml/xml_rss.asp" "https://www.w3schools.com/xml"))))) (deftest test-get-all-links (testing "returns all links from a feed" (is (= (get-all-links example-rss) '("https://www.w3schools.com/xml/xml_rss.asp" "https://www.w3schools.com/xml"))) ; FIXME: make work for atom #_(is (= (get-all-links example-atom) '("https://www.w3schools.com/xml/xml_rss.asp" "https://www.w3schools.com/xml"))) ))
true
(ns betterfeed.core-test (:require [clojure.test :refer :all] [betterfeed.core :refer :all] [rss-utils.core :as rss] [clojure.java.io :as io] [clojure.data.zip.xml :as dzx] [clojure.zip :as zip])) (rss/define-atom-xmlns) (defn string->stream ([s] (string->stream s "UTF-8")) ([s encoding] (-> s (.getBytes encoding) (java.io.ByteArrayInputStream.)))) (def example-atom-str (clojure.string/join "\n" [ "<?xml version=\"1.0\" encoding=\"utf-8\"?>" "<feed xmlns=\"http://www.w3.org/2005/Atom\">" " <title>Example Feed</title>" " <link href=\"http://example.org/\"/>" " <updated>2003-12-13T18:30:02Z</updated>" " <author>" " <name>PI:NAME:<NAME>END_PI</name>" " </author>" " <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>" " <entry>" " <title>Atom-Powered Robots Run Amok</title>" " <link href=\"http://example.org/2003/12/13/atom03\"/>" " <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>" " <updated>2003-12-13T18:30:02Z</updated>" " <summary>Some text.</summary>" " </entry>" "</feed>"])) (def example-rss-str (clojure.string/join "\n" [ "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" "<rss version=\"2.0\">" " <channel>" " <title>W3Schools Home Page</title>" " <link>https://www.w3schools.com</link>" " <description>Free web building tutorials</description>" " <item>" " <title>RSS Tutorial</title>" " <link>https://www.w3schools.com/xml/xml_rss.asp</link>" " <description>New RSS tutorial on W3Schools</description>" " </item>" " <item>" " <title>XML Tutorial</title>" " <link>https://www.w3schools.com/xml</link>" " <description>New XML tutorial on W3Schools</description>" " </item>" " </channel>" "</rss>"])) (def example-atom (clojure.data.xml/parse (string->stream example-atom-str))) (def example-rss (clojure.data.xml/parse (string->stream example-rss-str))) ; FIXME: These two should be constructed data, otherwise they're being used to test the funcitons that produced them. (def atom-first-item (rss/zip-at-first-item example-atom)) (def rss-first-item (rss/zip-at-first-item example-rss)) (deftest test-get-host (testing "returns host part of url" (is (= (get-host "https://google.com/blarg") "google.com")) (is (= (get-host "http://google.com/") "google.com")))) (deftest test-resolve-redirect ; FIXME: This requires a network connection and outside behaviour (testing "will resolve a flaky remote redirect" (is (= (resolve-redirect "http://grimmwa.re") "https://www.grimmwa.re/")))) (deftest test-get-real-url ; FIXME: This requires a network connection and outside behaviour (testing "will resolve a flaky remote redirect when the domain is in the will-3xx ref" (dosync (ref-set will-3xx '("grimmwa.re"))) (is (= (get-real-url "http://grimmwa.re") "https://www.grimmwa.re/")) (is (= (get-real-url "http://anything-else.com") "http://anything-else.com")))) (deftest test-get-body-method (testing "Returns body method for domain in the body-method ref, or get-body for anything else" (defn blerg [x] x) (dosync (ref-set body-method {"grimmwa.re" blerg})) (is (= (get-body-method "https://grimmwa.re") blerg)) (is (= (get-body-method "https://google.com") get-body)))) (deftest test-fetch-local ; FIXME: This requires a network connection and outside behaviour (testing "works" (let [target-file "/tmp/betterfeed-test"] (is (= (fetch-local "https://google.com" target-file) "file:///tmp/betterfeed-test")) (is (= (.exists (clojure.java.io/as-file target-file)) true))))) (deftest test-get-link-from-item (testing "Gets the correct link form the item" (is (= (get-link-from-item rss-first-item) "https://www.w3schools.com/xml/xml_rss.asp")) ;FIXME: Make this work for atom ;(is (= (get-link-from-item atom-first-item) "https://www.w3schools.com/xml/xml_rss.asp")) )) (deftest test-update-item ; FIXME: this is a hot mess - make a convenience method for lookups (testing "creates a new item value" (is (= (-> (dzx/xml1-> rss-first-item :link) zip/node :content first) "https://www.w3schools.com/xml/xml_rss.asp")) (let [new-item (update-item rss-first-item :link "not here")] (is (= (-> (dzx/xml1-> new-item :link) zip/node :content first) "not here"))))) (deftest test-has-tag (testing "returns true when an item has a tag, otherwise false" (is (= (has-tag? :link rss-first-item) true)) (is (= (has-tag? ::atomfeed/link atom-first-item) true)) (is (= (has-tag? :linkogram rss-first-item) false)) (is (= (has-tag? :linkogram atom-first-item) false)))) (deftest test-insert-tag (testing "correctly inserts a missing tag" (is (= (has-tag? :linkogram rss-first-item) false)) (let [new-item (insert-tag rss-first-item :linkogram "bananas")] (is (= (has-tag? :linkogram new-item) true)) (is (= (-> (dzx/xml1-> new-item :linkogram) zip/node :content first) "bananas"))))) (deftest test-get-all-tag (testing "returns all values of tag type" (is (= (get-all-tag :link example-rss) '("https://www.w3schools.com/xml/xml_rss.asp" "https://www.w3schools.com/xml"))))) (deftest test-get-all-links (testing "returns all links from a feed" (is (= (get-all-links example-rss) '("https://www.w3schools.com/xml/xml_rss.asp" "https://www.w3schools.com/xml"))) ; FIXME: make work for atom #_(is (= (get-all-links example-atom) '("https://www.w3schools.com/xml/xml_rss.asp" "https://www.w3schools.com/xml"))) ))
[ { "context": "ri\n :credentialTemplate {:key \"foo\"\n :secret \"b", "end": 718, "score": 0.9795903563499451, "start": 715, "tag": "KEY", "value": "foo" }, { "context": "o\"\n :secret \"bar\"\n :connector {:", "end": 770, "score": 0.9543966054916382, "start": 767, "tag": "KEY", "value": "bar" }, { "context": "thod method\n :key \"foo\"\n :secret \"bar\"\n ", "end": 1576, "score": 0.9758302569389343, "start": 1573, "tag": "KEY", "value": "foo" }, { "context": "ey \"foo\"\n :secret \"bar\"\n :connector {:href \"connecto", "end": 1614, "score": 0.9856985211372375, "start": 1611, "tag": "KEY", "value": "bar" } ]
dummy-connector/config/test/com/sixsq/slipstream/ssclj/resources/spec/credential_template_cloud_dummy_test.cljc
slipstream/cimi-mf2c
0
(ns com.sixsq.slipstream.ssclj.resources.spec.credential-template-cloud-dummy-test (:require [clojure.test :refer :all] [com.sixsq.slipstream.ssclj.resources.credential-template :as ct] [com.sixsq.slipstream.ssclj.resources.spec.credential-template-cloud-dummy] [com.sixsq.slipstream.ssclj.resources.credential-template-cloud-dummy :refer [resource-acl credential-type method]] [clojure.spec.alpha :as s] [com.sixsq.slipstream.ssclj.resources.credential :as p] [clojure.spec.alpha :as s])) (def valid-acl resource-acl) (deftest test-credential-template-cloud-dummy-create-schema-check (let [root {:resourceURI p/resource-uri :credentialTemplate {:key "foo" :secret "bar" :connector {:href "connector/baz"} :quota 1}}] (is (s/valid? :cimi/credential-template.cloud-dummy-create root)) (doseq [k (into #{} (keys (dissoc root :resourceURI)))] (is (not (s/valid? :cimi/credential-template.cloud-dummy-create (dissoc root k))))))) (deftest test-credential-template-cloud-dummy-schema-check (let [timestamp "1972-10-08T10:00:00.0Z" root {:id (str ct/resource-url "/uuid") :resourceURI p/resource-uri :created timestamp :updated timestamp :acl valid-acl :type credential-type :method method :key "foo" :secret "bar" :connector {:href "connector/baz"} :quota 1}] (is (s/valid? :cimi/credential-template.cloud-dummy root)) (doseq [k (into #{} (keys root))] (is (not (s/valid? :cimi/credential-template.cloud-dummy (dissoc root k)))))))
94177
(ns com.sixsq.slipstream.ssclj.resources.spec.credential-template-cloud-dummy-test (:require [clojure.test :refer :all] [com.sixsq.slipstream.ssclj.resources.credential-template :as ct] [com.sixsq.slipstream.ssclj.resources.spec.credential-template-cloud-dummy] [com.sixsq.slipstream.ssclj.resources.credential-template-cloud-dummy :refer [resource-acl credential-type method]] [clojure.spec.alpha :as s] [com.sixsq.slipstream.ssclj.resources.credential :as p] [clojure.spec.alpha :as s])) (def valid-acl resource-acl) (deftest test-credential-template-cloud-dummy-create-schema-check (let [root {:resourceURI p/resource-uri :credentialTemplate {:key "<KEY>" :secret "<KEY>" :connector {:href "connector/baz"} :quota 1}}] (is (s/valid? :cimi/credential-template.cloud-dummy-create root)) (doseq [k (into #{} (keys (dissoc root :resourceURI)))] (is (not (s/valid? :cimi/credential-template.cloud-dummy-create (dissoc root k))))))) (deftest test-credential-template-cloud-dummy-schema-check (let [timestamp "1972-10-08T10:00:00.0Z" root {:id (str ct/resource-url "/uuid") :resourceURI p/resource-uri :created timestamp :updated timestamp :acl valid-acl :type credential-type :method method :key "<KEY>" :secret "<KEY>" :connector {:href "connector/baz"} :quota 1}] (is (s/valid? :cimi/credential-template.cloud-dummy root)) (doseq [k (into #{} (keys root))] (is (not (s/valid? :cimi/credential-template.cloud-dummy (dissoc root k)))))))
true
(ns com.sixsq.slipstream.ssclj.resources.spec.credential-template-cloud-dummy-test (:require [clojure.test :refer :all] [com.sixsq.slipstream.ssclj.resources.credential-template :as ct] [com.sixsq.slipstream.ssclj.resources.spec.credential-template-cloud-dummy] [com.sixsq.slipstream.ssclj.resources.credential-template-cloud-dummy :refer [resource-acl credential-type method]] [clojure.spec.alpha :as s] [com.sixsq.slipstream.ssclj.resources.credential :as p] [clojure.spec.alpha :as s])) (def valid-acl resource-acl) (deftest test-credential-template-cloud-dummy-create-schema-check (let [root {:resourceURI p/resource-uri :credentialTemplate {:key "PI:KEY:<KEY>END_PI" :secret "PI:KEY:<KEY>END_PI" :connector {:href "connector/baz"} :quota 1}}] (is (s/valid? :cimi/credential-template.cloud-dummy-create root)) (doseq [k (into #{} (keys (dissoc root :resourceURI)))] (is (not (s/valid? :cimi/credential-template.cloud-dummy-create (dissoc root k))))))) (deftest test-credential-template-cloud-dummy-schema-check (let [timestamp "1972-10-08T10:00:00.0Z" root {:id (str ct/resource-url "/uuid") :resourceURI p/resource-uri :created timestamp :updated timestamp :acl valid-acl :type credential-type :method method :key "PI:KEY:<KEY>END_PI" :secret "PI:KEY:<KEY>END_PI" :connector {:href "connector/baz"} :quota 1}] (is (s/valid? :cimi/credential-template.cloud-dummy root)) (doseq [k (into #{} (keys root))] (is (not (s/valid? :cimi/credential-template.cloud-dummy (dissoc root k)))))))
[ { "context": "(ns ^{:doc \"Tests for utils.clj\"\n :author \"Eric Weinstein <eric.q.weinstein@gmail.com>\"}\n quixote.utils-te", "end": 62, "score": 0.9998859167098999, "start": 48, "tag": "NAME", "value": "Eric Weinstein" }, { "context": "sts for utils.clj\"\n :author \"Eric Weinstein <eric.q.weinstein@gmail.com>\"}\n quixote.utils-test\n (:require [clojure.test", "end": 90, "score": 0.9999334812164307, "start": 64, "tag": "EMAIL", "value": "eric.q.weinstein@gmail.com" }, { "context": " :title \"Book A\"\n :author \"Author A\"\n :img \"http://www.example.com", "end": 387, "score": 0.8710225820541382, "start": 379, "tag": "NAME", "value": "Author A" }, { "context": " :title \"Book B\"\n :author \"Author B\"\n :img \"http://www.example.co", "end": 704, "score": 0.851609468460083, "start": 696, "tag": "NAME", "value": "Author B" }, { "context": " :title \"Book C\"\n :author \"Author C\"\n :img \"http://www.example.co", "end": 1027, "score": 0.5896228551864624, "start": 1019, "tag": "NAME", "value": "Author C" }, { "context": " :title \"Book A\"\n :author \"Author A\"\n :img \"http://www.example.co", "end": 1348, "score": 0.6571546792984009, "start": 1340, "tag": "NAME", "value": "Author A" }, { "context": " :title \"Book B\"\n :author \"Author B\"\n :img \"http://www.example.co", "end": 1670, "score": 0.7947732210159302, "start": 1662, "tag": "NAME", "value": "Author B" }, { "context": "00001\"\n [{:author \"Author A\"\n :available tru", "end": 2098, "score": 0.990955650806427, "start": 2090, "tag": "NAME", "value": "Author A" }, { "context": "ok A\"}\n {:author \"Author A\"\n :available fal", "end": 2340, "score": 0.9970589280128479, "start": 2332, "tag": "NAME", "value": "Author A" }, { "context": "00002\"\n [{:author \"Author B\"\n :available fal", "end": 2631, "score": 0.9962379932403564, "start": 2623, "tag": "NAME", "value": "Author B" }, { "context": "ok B\"}\n {:author \"Author B\"\n :available tru", "end": 2874, "score": 0.9967646598815918, "start": 2866, "tag": "NAME", "value": "Author B" }, { "context": "00003\"\n [{:author \"Author C\"\n :available tru", "end": 3164, "score": 0.9927588701248169, "start": 3156, "tag": "NAME", "value": "Author C" } ]
test/quixote/utils_test.clj
ericqweinstein/quixote
0
(ns ^{:doc "Tests for utils.clj" :author "Eric Weinstein <eric.q.weinstein@gmail.com>"} quixote.utils-test (:require [clojure.test :refer :all] [midje.sweet :refer :all] [quixote.utils :refer :all])) (def fixture-data [(sorted-map :isbn "978000000001" :search-result { :title "Book A" :author "Author A" :img "http://www.example.com/A" :store 0 :available true :price 11.99 } ) (sorted-map :isbn "978000000002" :search-result { :title "Book B" :author "Author B" :img "http://www.example.com/B" :store 0 :available false :price 11.99 } ) (sorted-map :isbn "978000000003" :search-result { :title "Book C" :author "Author C" :img "http://www.example.com/C" :store 0 :available true :price 11.99 } ) (sorted-map :isbn "978000000001" :search-result { :title "Book A" :author "Author A" :img "http://www.example.com/A" :store 1 :available false :price 10.99 } ) (sorted-map :isbn "978000000002" :search-result { :title "Book B" :author "Author B" :img "http://www.example.com/B" :store 1 :available true :price 12.99 } ) ] ) (facts "About manipulating book data" (fact "It converts data from search results to books with search result fields") (pivot fixture-data) => {"978000000001" [{:author "Author A" :available true :img "http://www.example.com/A" :price 11.99 :store 0 :title "Book A"} {:author "Author A" :available false :img "http://www.example.com/A" :price 10.99 :store 1 :title "Book A"}] "978000000002" [{:author "Author B" :available false :img "http://www.example.com/B" :price 11.99 :store 0 :title "Book B"} {:author "Author B" :available true :img "http://www.example.com/B" :price 12.99 :store 1 :title "Book B"}] "978000000003" [{:author "Author C" :available true :img "http://www.example.com/C" :price 11.99 :store 0 :title "Book C"}]})
38827
(ns ^{:doc "Tests for utils.clj" :author "<NAME> <<EMAIL>>"} quixote.utils-test (:require [clojure.test :refer :all] [midje.sweet :refer :all] [quixote.utils :refer :all])) (def fixture-data [(sorted-map :isbn "978000000001" :search-result { :title "Book A" :author "<NAME>" :img "http://www.example.com/A" :store 0 :available true :price 11.99 } ) (sorted-map :isbn "978000000002" :search-result { :title "Book B" :author "<NAME>" :img "http://www.example.com/B" :store 0 :available false :price 11.99 } ) (sorted-map :isbn "978000000003" :search-result { :title "Book C" :author "<NAME>" :img "http://www.example.com/C" :store 0 :available true :price 11.99 } ) (sorted-map :isbn "978000000001" :search-result { :title "Book A" :author "<NAME>" :img "http://www.example.com/A" :store 1 :available false :price 10.99 } ) (sorted-map :isbn "978000000002" :search-result { :title "Book B" :author "<NAME>" :img "http://www.example.com/B" :store 1 :available true :price 12.99 } ) ] ) (facts "About manipulating book data" (fact "It converts data from search results to books with search result fields") (pivot fixture-data) => {"978000000001" [{:author "<NAME>" :available true :img "http://www.example.com/A" :price 11.99 :store 0 :title "Book A"} {:author "<NAME>" :available false :img "http://www.example.com/A" :price 10.99 :store 1 :title "Book A"}] "978000000002" [{:author "<NAME>" :available false :img "http://www.example.com/B" :price 11.99 :store 0 :title "Book B"} {:author "<NAME>" :available true :img "http://www.example.com/B" :price 12.99 :store 1 :title "Book B"}] "978000000003" [{:author "<NAME>" :available true :img "http://www.example.com/C" :price 11.99 :store 0 :title "Book C"}]})
true
(ns ^{:doc "Tests for utils.clj" :author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"} quixote.utils-test (:require [clojure.test :refer :all] [midje.sweet :refer :all] [quixote.utils :refer :all])) (def fixture-data [(sorted-map :isbn "978000000001" :search-result { :title "Book A" :author "PI:NAME:<NAME>END_PI" :img "http://www.example.com/A" :store 0 :available true :price 11.99 } ) (sorted-map :isbn "978000000002" :search-result { :title "Book B" :author "PI:NAME:<NAME>END_PI" :img "http://www.example.com/B" :store 0 :available false :price 11.99 } ) (sorted-map :isbn "978000000003" :search-result { :title "Book C" :author "PI:NAME:<NAME>END_PI" :img "http://www.example.com/C" :store 0 :available true :price 11.99 } ) (sorted-map :isbn "978000000001" :search-result { :title "Book A" :author "PI:NAME:<NAME>END_PI" :img "http://www.example.com/A" :store 1 :available false :price 10.99 } ) (sorted-map :isbn "978000000002" :search-result { :title "Book B" :author "PI:NAME:<NAME>END_PI" :img "http://www.example.com/B" :store 1 :available true :price 12.99 } ) ] ) (facts "About manipulating book data" (fact "It converts data from search results to books with search result fields") (pivot fixture-data) => {"978000000001" [{:author "PI:NAME:<NAME>END_PI" :available true :img "http://www.example.com/A" :price 11.99 :store 0 :title "Book A"} {:author "PI:NAME:<NAME>END_PI" :available false :img "http://www.example.com/A" :price 10.99 :store 1 :title "Book A"}] "978000000002" [{:author "PI:NAME:<NAME>END_PI" :available false :img "http://www.example.com/B" :price 11.99 :store 0 :title "Book B"} {:author "PI:NAME:<NAME>END_PI" :available true :img "http://www.example.com/B" :price 12.99 :store 1 :title "Book B"}] "978000000003" [{:author "PI:NAME:<NAME>END_PI" :available true :img "http://www.example.com/C" :price 11.99 :store 0 :title "Book C"}]})
[ { "context": "; Copyright (c) 2020-present Walmart, Inc.\n;\n; Licensed under the Apache License, Vers", "end": 36, "score": 0.9326944351196289, "start": 29, "tag": "NAME", "value": "Walmart" } ]
src/com/walmartlabs/lacinia/pedestal/internal.clj
youngnh/lacinia-pedestal
0
; Copyright (c) 2020-present Walmart, Inc. ; ; Licensed under the Apache License, Version 2.0 (the "License") ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns ^:no-doc com.walmartlabs.lacinia.pedestal.internal "Internal utilties not part of the public API." (:require [clojure.core.async :refer [chan put!]] [cheshire.core :as cheshire] [com.walmartlabs.lacinia.util :as util] [com.walmartlabs.lacinia.parser :as parser] [clojure.string :as str] [com.walmartlabs.lacinia.validator :as validator] [com.walmartlabs.lacinia.constants :as constants] [com.walmartlabs.lacinia.resolve :as resolve] [com.walmartlabs.lacinia.executor :as executor] [io.pedestal.log :as log] [clojure.java.io :as io] [ring.util.response :as response] [io.pedestal.http.jetty.websockets :as ws] [io.pedestal.http :as http] [io.pedestal.interceptor.chain :as chain] [com.walmartlabs.lacinia.pedestal.subscriptions :as subscriptions])) (def ^:private parsed-query-key-path [:request :parsed-lacinia-query]) (defn parse-content-type "Parse `s` as an RFC 2616 media type." [s] (if-let [[_ type _ _ raw-params] (re-matches #"\s*(([^/]+)/([^ ;]+))\s*(\s*;.*)?" (str s))] {:content-type (keyword type) :content-type-params (->> (str/split (str raw-params) #"\s*;\s*") (keep identity) (remove str/blank?) (map #(str/split % #"=")) (mapcat (fn [[k v]] [(keyword (str/lower-case k)) (str/trim v)])) (apply hash-map))})) (defn content-type "Gets the content-type of a request. (without encoding)" [request] (when-let [content-type (get-in request [:headers "content-type"])] (:content-type (parse-content-type content-type)))) (defn on-leave-json-response [context] (let [body (get-in context [:response :body])] (if (map? body) (-> context (assoc-in [:response :headers "Content-Type"] "application/json") (update-in [:response :body] cheshire/generate-string)) context))) (defn failure-response "Generates a bad request Ring response." ([body] (failure-response 400 body)) ([status body] {:status status :headers {} :body body})) (defn message-as-errors [message] {:errors [{:message message}]}) (defn as-errors [exception] {:errors [(util/as-error-map exception)]}) (defn on-enter-query-parser [compiled-schema] (fn [context] (let [{:keys [graphql-query graphql-operation-name]} (:request context)] (try (let [actual-schema (if (map? compiled-schema) compiled-schema (compiled-schema)) parsed-query (parser/parse-query actual-schema graphql-query graphql-operation-name)] (assoc-in context parsed-query-key-path parsed-query)) (catch Exception e (assoc context :response (failure-response (as-errors e)))))))) (defn on-error-error-response [context ex] (let [{:keys [exception]} (ex-data ex)] (assoc context :response (failure-response 500 (as-errors exception))))) (defn on-enter-prepare-query [context] (try (let [{parsed-query :parsed-lacinia-query vars :graphql-vars} (:request context) prepared (parser/prepare-with-query-variables parsed-query vars) compiled-schema (get prepared constants/schema-key) errors (validator/validate compiled-schema prepared {})] (if (seq errors) (assoc context :response (failure-response {:errors errors})) (assoc-in context parsed-query-key-path prepared))) (catch Exception e (assoc context :response (failure-response (as-errors e)))))) (defn ^:private remove-status "Remove the :status key from the :extensions map; remove the :extensions key if that is now empty." [error-map] (if-not (contains? error-map :extensions) error-map (let [error-map' (update error-map :extensions dissoc :status)] (if (-> error-map' :extensions seq) error-map' (dissoc error-map' :extensions))))) (defn on-leave-status-conversion [context] (let [response (:response context) errors (get-in response [:body :errors]) statuses (keep #(-> % :extensions :status) errors)] (if (seq statuses) (let [max-status (reduce max (:status response) statuses)] (-> context (assoc-in [:response :status] max-status) (assoc-in [:response :body :errors] (map remove-status errors)))) context))) (defn ^:private apply-exception-to-context "Applies exception to context in the same way Pedestal would if thrown from a synchronous interceptor. Based on the (private) `io.pedestal.interceptor.chain/throwable->ex-info` function of pedestal" [{::chain/keys [execution-id] :as context} exception interceptor-name] (let [exception-str (pr-str (type exception)) msg (str exception-str " in Interceptor " interceptor-name " - " (ex-message exception)) wrapped-exception (ex-info msg (merge {:execution-id execution-id :stage :enter :interceptor interceptor-name :exception-type (keyword exception-str) :exception exception} (ex-data exception)) exception)] (assoc context ::chain/error wrapped-exception))) (defn ^:private apply-result-to-context [context result interceptor-name] ;; Lacinia changed the contract here in 0.36.0 (to support timeouts); the result ;; may be an exception thrown during initial processing of the query. (if (instance? Throwable result) (do (log/error :event :execution-exception :ex result) ;; Put error in the context map for error interceptors to consume ;; If unhandled, will end up in [[error-response-interceptor]] (apply-exception-to-context context result interceptor-name)) ;; When :data is missing, then a failure occurred during parsing or preparing ;; the request, which indicates a bad request, rather than some failure ;; during execution. (let [status (if (contains? result :data) 200 400) response {:status status :headers {} :body result}] (assoc context :response response)))) (defn ^:private execute-query [context] (let [request (:request context) {q :parsed-lacinia-query app-context :lacinia-app-context} request] (executor/execute-query (assoc app-context constants/parsed-query-key q)))) (defn on-enter-query-executor [interceptor-name] (fn [context] (let [resolver-result (execute-query context) *result (promise)] (resolve/on-deliver! resolver-result (fn [result] (deliver *result result))) (apply-result-to-context context @*result interceptor-name)))) (defn on-enter-async-query-executor [interceptor-name] (fn [context] (let [ch (chan 1) resolver-result (execute-query context)] (resolve/on-deliver! resolver-result (fn [result] (put! ch (apply-result-to-context context result interceptor-name)))) ch))) (defn on-enter-disallow-subscriptions [context] (if (-> context :request :parsed-lacinia-query parser/operations :type (= :subscription)) (assoc context :response (failure-response (message-as-errors "Subscription queries must be processed by the WebSockets endpoint."))) context)) (defn ^:private request-headers-string [headers] (str "{" (->> (assoc headers "Content-Type" "application/json") (map (fn [[k v]] (str \" (name k) "\": \"" (name v) \"))) (str/join ", ")) "}")) (defn graphiql-response [api-path subscriptions-path asset-path ide-headers ide-connection-params] (let [replacements {:asset-path asset-path :api-path api-path :subscriptions-path subscriptions-path :initial-connection-params (cheshire/generate-string ide-connection-params) :request-headers (request-headers-string ide-headers)}] (-> "com/walmartlabs/lacinia/pedestal/graphiql.html" io/resource slurp (str/replace #"\{\{(.+?)}}" (fn [[_ key]] (get replacements (keyword key) "--NO-MATCH--"))) response/response (response/content-type "text/html")))) (defn add-subscriptions-support [service-map compiled-schema subscriptions-path subscription-options] (assoc-in service-map [::http/container-options :context-configurator] ;; The listener-fn is responsible for creating the listener; it is passed ;; the request, response, and the ws-map. In sample code, the ws-map ;; has callbacks such as :on-connect and :on-text, but in our scenario ;; the callbacks are created by the listener-fn, so the value is nil. #(ws/add-ws-endpoints % {subscriptions-path nil} {:listener-fn (subscriptions/listener-fn-factory compiled-schema subscription-options)})))
120239
; Copyright (c) 2020-present <NAME>, Inc. ; ; Licensed under the Apache License, Version 2.0 (the "License") ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns ^:no-doc com.walmartlabs.lacinia.pedestal.internal "Internal utilties not part of the public API." (:require [clojure.core.async :refer [chan put!]] [cheshire.core :as cheshire] [com.walmartlabs.lacinia.util :as util] [com.walmartlabs.lacinia.parser :as parser] [clojure.string :as str] [com.walmartlabs.lacinia.validator :as validator] [com.walmartlabs.lacinia.constants :as constants] [com.walmartlabs.lacinia.resolve :as resolve] [com.walmartlabs.lacinia.executor :as executor] [io.pedestal.log :as log] [clojure.java.io :as io] [ring.util.response :as response] [io.pedestal.http.jetty.websockets :as ws] [io.pedestal.http :as http] [io.pedestal.interceptor.chain :as chain] [com.walmartlabs.lacinia.pedestal.subscriptions :as subscriptions])) (def ^:private parsed-query-key-path [:request :parsed-lacinia-query]) (defn parse-content-type "Parse `s` as an RFC 2616 media type." [s] (if-let [[_ type _ _ raw-params] (re-matches #"\s*(([^/]+)/([^ ;]+))\s*(\s*;.*)?" (str s))] {:content-type (keyword type) :content-type-params (->> (str/split (str raw-params) #"\s*;\s*") (keep identity) (remove str/blank?) (map #(str/split % #"=")) (mapcat (fn [[k v]] [(keyword (str/lower-case k)) (str/trim v)])) (apply hash-map))})) (defn content-type "Gets the content-type of a request. (without encoding)" [request] (when-let [content-type (get-in request [:headers "content-type"])] (:content-type (parse-content-type content-type)))) (defn on-leave-json-response [context] (let [body (get-in context [:response :body])] (if (map? body) (-> context (assoc-in [:response :headers "Content-Type"] "application/json") (update-in [:response :body] cheshire/generate-string)) context))) (defn failure-response "Generates a bad request Ring response." ([body] (failure-response 400 body)) ([status body] {:status status :headers {} :body body})) (defn message-as-errors [message] {:errors [{:message message}]}) (defn as-errors [exception] {:errors [(util/as-error-map exception)]}) (defn on-enter-query-parser [compiled-schema] (fn [context] (let [{:keys [graphql-query graphql-operation-name]} (:request context)] (try (let [actual-schema (if (map? compiled-schema) compiled-schema (compiled-schema)) parsed-query (parser/parse-query actual-schema graphql-query graphql-operation-name)] (assoc-in context parsed-query-key-path parsed-query)) (catch Exception e (assoc context :response (failure-response (as-errors e)))))))) (defn on-error-error-response [context ex] (let [{:keys [exception]} (ex-data ex)] (assoc context :response (failure-response 500 (as-errors exception))))) (defn on-enter-prepare-query [context] (try (let [{parsed-query :parsed-lacinia-query vars :graphql-vars} (:request context) prepared (parser/prepare-with-query-variables parsed-query vars) compiled-schema (get prepared constants/schema-key) errors (validator/validate compiled-schema prepared {})] (if (seq errors) (assoc context :response (failure-response {:errors errors})) (assoc-in context parsed-query-key-path prepared))) (catch Exception e (assoc context :response (failure-response (as-errors e)))))) (defn ^:private remove-status "Remove the :status key from the :extensions map; remove the :extensions key if that is now empty." [error-map] (if-not (contains? error-map :extensions) error-map (let [error-map' (update error-map :extensions dissoc :status)] (if (-> error-map' :extensions seq) error-map' (dissoc error-map' :extensions))))) (defn on-leave-status-conversion [context] (let [response (:response context) errors (get-in response [:body :errors]) statuses (keep #(-> % :extensions :status) errors)] (if (seq statuses) (let [max-status (reduce max (:status response) statuses)] (-> context (assoc-in [:response :status] max-status) (assoc-in [:response :body :errors] (map remove-status errors)))) context))) (defn ^:private apply-exception-to-context "Applies exception to context in the same way Pedestal would if thrown from a synchronous interceptor. Based on the (private) `io.pedestal.interceptor.chain/throwable->ex-info` function of pedestal" [{::chain/keys [execution-id] :as context} exception interceptor-name] (let [exception-str (pr-str (type exception)) msg (str exception-str " in Interceptor " interceptor-name " - " (ex-message exception)) wrapped-exception (ex-info msg (merge {:execution-id execution-id :stage :enter :interceptor interceptor-name :exception-type (keyword exception-str) :exception exception} (ex-data exception)) exception)] (assoc context ::chain/error wrapped-exception))) (defn ^:private apply-result-to-context [context result interceptor-name] ;; Lacinia changed the contract here in 0.36.0 (to support timeouts); the result ;; may be an exception thrown during initial processing of the query. (if (instance? Throwable result) (do (log/error :event :execution-exception :ex result) ;; Put error in the context map for error interceptors to consume ;; If unhandled, will end up in [[error-response-interceptor]] (apply-exception-to-context context result interceptor-name)) ;; When :data is missing, then a failure occurred during parsing or preparing ;; the request, which indicates a bad request, rather than some failure ;; during execution. (let [status (if (contains? result :data) 200 400) response {:status status :headers {} :body result}] (assoc context :response response)))) (defn ^:private execute-query [context] (let [request (:request context) {q :parsed-lacinia-query app-context :lacinia-app-context} request] (executor/execute-query (assoc app-context constants/parsed-query-key q)))) (defn on-enter-query-executor [interceptor-name] (fn [context] (let [resolver-result (execute-query context) *result (promise)] (resolve/on-deliver! resolver-result (fn [result] (deliver *result result))) (apply-result-to-context context @*result interceptor-name)))) (defn on-enter-async-query-executor [interceptor-name] (fn [context] (let [ch (chan 1) resolver-result (execute-query context)] (resolve/on-deliver! resolver-result (fn [result] (put! ch (apply-result-to-context context result interceptor-name)))) ch))) (defn on-enter-disallow-subscriptions [context] (if (-> context :request :parsed-lacinia-query parser/operations :type (= :subscription)) (assoc context :response (failure-response (message-as-errors "Subscription queries must be processed by the WebSockets endpoint."))) context)) (defn ^:private request-headers-string [headers] (str "{" (->> (assoc headers "Content-Type" "application/json") (map (fn [[k v]] (str \" (name k) "\": \"" (name v) \"))) (str/join ", ")) "}")) (defn graphiql-response [api-path subscriptions-path asset-path ide-headers ide-connection-params] (let [replacements {:asset-path asset-path :api-path api-path :subscriptions-path subscriptions-path :initial-connection-params (cheshire/generate-string ide-connection-params) :request-headers (request-headers-string ide-headers)}] (-> "com/walmartlabs/lacinia/pedestal/graphiql.html" io/resource slurp (str/replace #"\{\{(.+?)}}" (fn [[_ key]] (get replacements (keyword key) "--NO-MATCH--"))) response/response (response/content-type "text/html")))) (defn add-subscriptions-support [service-map compiled-schema subscriptions-path subscription-options] (assoc-in service-map [::http/container-options :context-configurator] ;; The listener-fn is responsible for creating the listener; it is passed ;; the request, response, and the ws-map. In sample code, the ws-map ;; has callbacks such as :on-connect and :on-text, but in our scenario ;; the callbacks are created by the listener-fn, so the value is nil. #(ws/add-ws-endpoints % {subscriptions-path nil} {:listener-fn (subscriptions/listener-fn-factory compiled-schema subscription-options)})))
true
; Copyright (c) 2020-present PI:NAME:<NAME>END_PI, Inc. ; ; Licensed under the Apache License, Version 2.0 (the "License") ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns ^:no-doc com.walmartlabs.lacinia.pedestal.internal "Internal utilties not part of the public API." (:require [clojure.core.async :refer [chan put!]] [cheshire.core :as cheshire] [com.walmartlabs.lacinia.util :as util] [com.walmartlabs.lacinia.parser :as parser] [clojure.string :as str] [com.walmartlabs.lacinia.validator :as validator] [com.walmartlabs.lacinia.constants :as constants] [com.walmartlabs.lacinia.resolve :as resolve] [com.walmartlabs.lacinia.executor :as executor] [io.pedestal.log :as log] [clojure.java.io :as io] [ring.util.response :as response] [io.pedestal.http.jetty.websockets :as ws] [io.pedestal.http :as http] [io.pedestal.interceptor.chain :as chain] [com.walmartlabs.lacinia.pedestal.subscriptions :as subscriptions])) (def ^:private parsed-query-key-path [:request :parsed-lacinia-query]) (defn parse-content-type "Parse `s` as an RFC 2616 media type." [s] (if-let [[_ type _ _ raw-params] (re-matches #"\s*(([^/]+)/([^ ;]+))\s*(\s*;.*)?" (str s))] {:content-type (keyword type) :content-type-params (->> (str/split (str raw-params) #"\s*;\s*") (keep identity) (remove str/blank?) (map #(str/split % #"=")) (mapcat (fn [[k v]] [(keyword (str/lower-case k)) (str/trim v)])) (apply hash-map))})) (defn content-type "Gets the content-type of a request. (without encoding)" [request] (when-let [content-type (get-in request [:headers "content-type"])] (:content-type (parse-content-type content-type)))) (defn on-leave-json-response [context] (let [body (get-in context [:response :body])] (if (map? body) (-> context (assoc-in [:response :headers "Content-Type"] "application/json") (update-in [:response :body] cheshire/generate-string)) context))) (defn failure-response "Generates a bad request Ring response." ([body] (failure-response 400 body)) ([status body] {:status status :headers {} :body body})) (defn message-as-errors [message] {:errors [{:message message}]}) (defn as-errors [exception] {:errors [(util/as-error-map exception)]}) (defn on-enter-query-parser [compiled-schema] (fn [context] (let [{:keys [graphql-query graphql-operation-name]} (:request context)] (try (let [actual-schema (if (map? compiled-schema) compiled-schema (compiled-schema)) parsed-query (parser/parse-query actual-schema graphql-query graphql-operation-name)] (assoc-in context parsed-query-key-path parsed-query)) (catch Exception e (assoc context :response (failure-response (as-errors e)))))))) (defn on-error-error-response [context ex] (let [{:keys [exception]} (ex-data ex)] (assoc context :response (failure-response 500 (as-errors exception))))) (defn on-enter-prepare-query [context] (try (let [{parsed-query :parsed-lacinia-query vars :graphql-vars} (:request context) prepared (parser/prepare-with-query-variables parsed-query vars) compiled-schema (get prepared constants/schema-key) errors (validator/validate compiled-schema prepared {})] (if (seq errors) (assoc context :response (failure-response {:errors errors})) (assoc-in context parsed-query-key-path prepared))) (catch Exception e (assoc context :response (failure-response (as-errors e)))))) (defn ^:private remove-status "Remove the :status key from the :extensions map; remove the :extensions key if that is now empty." [error-map] (if-not (contains? error-map :extensions) error-map (let [error-map' (update error-map :extensions dissoc :status)] (if (-> error-map' :extensions seq) error-map' (dissoc error-map' :extensions))))) (defn on-leave-status-conversion [context] (let [response (:response context) errors (get-in response [:body :errors]) statuses (keep #(-> % :extensions :status) errors)] (if (seq statuses) (let [max-status (reduce max (:status response) statuses)] (-> context (assoc-in [:response :status] max-status) (assoc-in [:response :body :errors] (map remove-status errors)))) context))) (defn ^:private apply-exception-to-context "Applies exception to context in the same way Pedestal would if thrown from a synchronous interceptor. Based on the (private) `io.pedestal.interceptor.chain/throwable->ex-info` function of pedestal" [{::chain/keys [execution-id] :as context} exception interceptor-name] (let [exception-str (pr-str (type exception)) msg (str exception-str " in Interceptor " interceptor-name " - " (ex-message exception)) wrapped-exception (ex-info msg (merge {:execution-id execution-id :stage :enter :interceptor interceptor-name :exception-type (keyword exception-str) :exception exception} (ex-data exception)) exception)] (assoc context ::chain/error wrapped-exception))) (defn ^:private apply-result-to-context [context result interceptor-name] ;; Lacinia changed the contract here in 0.36.0 (to support timeouts); the result ;; may be an exception thrown during initial processing of the query. (if (instance? Throwable result) (do (log/error :event :execution-exception :ex result) ;; Put error in the context map for error interceptors to consume ;; If unhandled, will end up in [[error-response-interceptor]] (apply-exception-to-context context result interceptor-name)) ;; When :data is missing, then a failure occurred during parsing or preparing ;; the request, which indicates a bad request, rather than some failure ;; during execution. (let [status (if (contains? result :data) 200 400) response {:status status :headers {} :body result}] (assoc context :response response)))) (defn ^:private execute-query [context] (let [request (:request context) {q :parsed-lacinia-query app-context :lacinia-app-context} request] (executor/execute-query (assoc app-context constants/parsed-query-key q)))) (defn on-enter-query-executor [interceptor-name] (fn [context] (let [resolver-result (execute-query context) *result (promise)] (resolve/on-deliver! resolver-result (fn [result] (deliver *result result))) (apply-result-to-context context @*result interceptor-name)))) (defn on-enter-async-query-executor [interceptor-name] (fn [context] (let [ch (chan 1) resolver-result (execute-query context)] (resolve/on-deliver! resolver-result (fn [result] (put! ch (apply-result-to-context context result interceptor-name)))) ch))) (defn on-enter-disallow-subscriptions [context] (if (-> context :request :parsed-lacinia-query parser/operations :type (= :subscription)) (assoc context :response (failure-response (message-as-errors "Subscription queries must be processed by the WebSockets endpoint."))) context)) (defn ^:private request-headers-string [headers] (str "{" (->> (assoc headers "Content-Type" "application/json") (map (fn [[k v]] (str \" (name k) "\": \"" (name v) \"))) (str/join ", ")) "}")) (defn graphiql-response [api-path subscriptions-path asset-path ide-headers ide-connection-params] (let [replacements {:asset-path asset-path :api-path api-path :subscriptions-path subscriptions-path :initial-connection-params (cheshire/generate-string ide-connection-params) :request-headers (request-headers-string ide-headers)}] (-> "com/walmartlabs/lacinia/pedestal/graphiql.html" io/resource slurp (str/replace #"\{\{(.+?)}}" (fn [[_ key]] (get replacements (keyword key) "--NO-MATCH--"))) response/response (response/content-type "text/html")))) (defn add-subscriptions-support [service-map compiled-schema subscriptions-path subscription-options] (assoc-in service-map [::http/container-options :context-configurator] ;; The listener-fn is responsible for creating the listener; it is passed ;; the request, response, and the ws-map. In sample code, the ws-map ;; has callbacks such as :on-connect and :on-text, but in our scenario ;; the callbacks are created by the listener-fn, so the value is nil. #(ws/add-ws-endpoints % {subscriptions-path nil} {:listener-fn (subscriptions/listener-fn-factory compiled-schema subscription-options)})))
[ { "context": "quest]]))\n\n(def registration-data\n {:first_name \"Testing\"\n :last_name \"Registration\"\n :email \"test.reg", "end": 227, "score": 0.9998469948768616, "start": 220, "tag": "NAME", "value": "Testing" }, { "context": "tion-data\n {:first_name \"Testing\"\n :last_name \"Registration\"\n :email \"test.registration@example.com\"\n :co", "end": 256, "score": 0.9998100399971008, "start": 244, "tag": "NAME", "value": "Registration" }, { "context": "\"Testing\"\n :last_name \"Registration\"\n :email \"test.registration@example.com\"\n :country \"US\"})\n\n(facts \"about user account r", "end": 298, "score": 0.9999262690544128, "start": 269, "tag": "EMAIL", "value": "test.registration@example.com" } ]
test_old/clj/salava/user/registration_test.clj
Vilikkki/salava
17
(ns salava.user.registration-test (:require [midje.sweet :refer :all] [salava.core.migrator :as migrator] [salava.test-utils :refer [test-api-request]])) (def registration-data {:first_name "Testing" :last_name "Registration" :email "test.registration@example.com" :country "US"}) (facts "about user account registration" (fact "email address must be valid" (:status (test-api-request :post "/user/register" (dissoc registration-data :email))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :email nil))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :email ""))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :email "not-valid-email-address"))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :email "not-valid-email-address@either"))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :email (str (apply str (repeat 252 "a")) "@a.a")))) => 400) (fact "first name must be valid" (:status (test-api-request :post "/user/register" (dissoc registration-data :first_name))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :first_name nil))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :first_name ""))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :first_name (apply str (repeat 256 "a"))))) => 400) (fact "last name must be valid" (:status (test-api-request :post "/user/register" (dissoc registration-data :last_name))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :last_name nil))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :last_name ""))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :last_name (apply str (repeat 256 "a"))))) => 400) (fact "country must be valid" (:status (test-api-request :post "/user/register" (dissoc registration-data :country))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :country nil))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :country ""))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :country "XX"))) => 400) (fact "user can create an account" (let [{:keys [status body]} (test-api-request :post "/user/register" registration-data)] status => 200 (:status body) => "success")) (fact "user can not create account, if email address is already taken" (let [{:keys [status body]} (test-api-request :post "/user/register" registration-data)] status => 200 (:status body) => "error"))) (migrator/reset-seeds (migrator/test-config))
107431
(ns salava.user.registration-test (:require [midje.sweet :refer :all] [salava.core.migrator :as migrator] [salava.test-utils :refer [test-api-request]])) (def registration-data {:first_name "<NAME>" :last_name "<NAME>" :email "<EMAIL>" :country "US"}) (facts "about user account registration" (fact "email address must be valid" (:status (test-api-request :post "/user/register" (dissoc registration-data :email))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :email nil))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :email ""))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :email "not-valid-email-address"))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :email "not-valid-email-address@either"))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :email (str (apply str (repeat 252 "a")) "@a.a")))) => 400) (fact "first name must be valid" (:status (test-api-request :post "/user/register" (dissoc registration-data :first_name))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :first_name nil))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :first_name ""))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :first_name (apply str (repeat 256 "a"))))) => 400) (fact "last name must be valid" (:status (test-api-request :post "/user/register" (dissoc registration-data :last_name))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :last_name nil))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :last_name ""))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :last_name (apply str (repeat 256 "a"))))) => 400) (fact "country must be valid" (:status (test-api-request :post "/user/register" (dissoc registration-data :country))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :country nil))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :country ""))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :country "XX"))) => 400) (fact "user can create an account" (let [{:keys [status body]} (test-api-request :post "/user/register" registration-data)] status => 200 (:status body) => "success")) (fact "user can not create account, if email address is already taken" (let [{:keys [status body]} (test-api-request :post "/user/register" registration-data)] status => 200 (:status body) => "error"))) (migrator/reset-seeds (migrator/test-config))
true
(ns salava.user.registration-test (:require [midje.sweet :refer :all] [salava.core.migrator :as migrator] [salava.test-utils :refer [test-api-request]])) (def registration-data {:first_name "PI:NAME:<NAME>END_PI" :last_name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI" :country "US"}) (facts "about user account registration" (fact "email address must be valid" (:status (test-api-request :post "/user/register" (dissoc registration-data :email))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :email nil))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :email ""))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :email "not-valid-email-address"))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :email "not-valid-email-address@either"))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :email (str (apply str (repeat 252 "a")) "@a.a")))) => 400) (fact "first name must be valid" (:status (test-api-request :post "/user/register" (dissoc registration-data :first_name))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :first_name nil))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :first_name ""))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :first_name (apply str (repeat 256 "a"))))) => 400) (fact "last name must be valid" (:status (test-api-request :post "/user/register" (dissoc registration-data :last_name))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :last_name nil))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :last_name ""))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :last_name (apply str (repeat 256 "a"))))) => 400) (fact "country must be valid" (:status (test-api-request :post "/user/register" (dissoc registration-data :country))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :country nil))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :country ""))) => 400 (:status (test-api-request :post "/user/register" (assoc registration-data :country "XX"))) => 400) (fact "user can create an account" (let [{:keys [status body]} (test-api-request :post "/user/register" registration-data)] status => 200 (:status body) => "success")) (fact "user can not create account, if email address is already taken" (let [{:keys [status body]} (test-api-request :post "/user/register" registration-data)] status => 200 (:status body) => "error"))) (migrator/reset-seeds (migrator/test-config))
[ { "context": "ch provider))]\n (do\n ;; TODO (dchelimsky,2020-05-22): consider optimization of\n ", "end": 663, "score": 0.9994543194770813, "start": 653, "tag": "USERNAME", "value": "dchelimsky" }, { "context": " {:access-key-id \"id\"\n :secret-", "end": 3343, "score": 0.6682279109954834, "start": 3341, "tag": "KEY", "value": "id" }, { "context": " :secret-access-key \"secret\"})\n :workflo", "end": 3411, "score": 0.8230405449867249, "start": 3405, "tag": "KEY", "value": "secret" } ]
src/cognitect/aws/flow/credentials_stack.clj
griffinbank/aws-api
0
(ns cognitect.aws.flow.credentials-stack (:require [cognitect.aws.client.shared :as shared] [cognitect.aws.flow :as flow] [cognitect.aws.credentials :as credentials])) (defn- prepend-queue [q items] (into (into clojure.lang.PersistentQueue/EMPTY items) q)) (defn- provider-step ([name cached-step provider] (provider-step name cached-step provider nil)) ([name cached-step provider report-anomaly?] {:name name :f (fn [context] (if (:credentials context) context (if-let [creds (credentials/valid-credentials (credentials/fetch provider))] (do ;; TODO (dchelimsky,2020-05-22): consider optimization of ;; dequeuing any subsequent credential provider steps. (when-not @cached-step (reset! cached-step (provider-step name cached-step provider))) (assoc context :credentials creds)) (if report-anomaly? {:cognitect.anomalies/category :cognitect.anomalies/incorrect :cognitect.anomalies/message "Unable to find credentials"} context))))})) (defn process-credentials [] (let [cached-step (atom nil)] {:name "process credentials" :f (fn [{:keys [http-client credentials-provider] :as context}] (update context ::flow/queue prepend-queue (cond credentials-provider [(provider-step "user provided credentials provider" cached-step credentials-provider :report-anomaly!)] @cached-step [@cached-step] :else [(provider-step "environment credentials provider" cached-step (credentials/environment-credentials-provider)) (provider-step "system properties credentials provider" cached-step (credentials/system-property-credentials-provider)) (provider-step "profile credentials provider" cached-step (credentials/profile-credentials-provider)) (provider-step "container credentials provider" cached-step (credentials/container-credentials-provider http-client)) (provider-step "instance profile credentials provider" cached-step (credentials/instance-profile-credentials-provider http-client) :report-anomaly!)])))})) (comment (require '[cognitect.aws.client.api :as aws] '[cognitect.aws.diagnostics :as diagnostics]) (def c (aws/client {})) (def steps [(process-credentials) {:name "hide password" :f (fn [context] (if (:credentials context) (assoc-in context [:credentials :aws/secret-access-key] "REDACTED") context))}]) (aws/invoke c {:workflow-steps steps}) (aws/invoke c {:credentials-provider (credentials/basic-credentials-provider {:access-key-id "id" :secret-access-key "secret"}) :workflow-steps steps}) (aws/invoke c {:credentials-provider (reify credentials/CredentialsProvider (fetch [_])) :workflow-steps steps}) (def res *1) (diagnostics/summarize-log res) (diagnostics/trace-key res :credentials) )
59720
(ns cognitect.aws.flow.credentials-stack (:require [cognitect.aws.client.shared :as shared] [cognitect.aws.flow :as flow] [cognitect.aws.credentials :as credentials])) (defn- prepend-queue [q items] (into (into clojure.lang.PersistentQueue/EMPTY items) q)) (defn- provider-step ([name cached-step provider] (provider-step name cached-step provider nil)) ([name cached-step provider report-anomaly?] {:name name :f (fn [context] (if (:credentials context) context (if-let [creds (credentials/valid-credentials (credentials/fetch provider))] (do ;; TODO (dchelimsky,2020-05-22): consider optimization of ;; dequeuing any subsequent credential provider steps. (when-not @cached-step (reset! cached-step (provider-step name cached-step provider))) (assoc context :credentials creds)) (if report-anomaly? {:cognitect.anomalies/category :cognitect.anomalies/incorrect :cognitect.anomalies/message "Unable to find credentials"} context))))})) (defn process-credentials [] (let [cached-step (atom nil)] {:name "process credentials" :f (fn [{:keys [http-client credentials-provider] :as context}] (update context ::flow/queue prepend-queue (cond credentials-provider [(provider-step "user provided credentials provider" cached-step credentials-provider :report-anomaly!)] @cached-step [@cached-step] :else [(provider-step "environment credentials provider" cached-step (credentials/environment-credentials-provider)) (provider-step "system properties credentials provider" cached-step (credentials/system-property-credentials-provider)) (provider-step "profile credentials provider" cached-step (credentials/profile-credentials-provider)) (provider-step "container credentials provider" cached-step (credentials/container-credentials-provider http-client)) (provider-step "instance profile credentials provider" cached-step (credentials/instance-profile-credentials-provider http-client) :report-anomaly!)])))})) (comment (require '[cognitect.aws.client.api :as aws] '[cognitect.aws.diagnostics :as diagnostics]) (def c (aws/client {})) (def steps [(process-credentials) {:name "hide password" :f (fn [context] (if (:credentials context) (assoc-in context [:credentials :aws/secret-access-key] "REDACTED") context))}]) (aws/invoke c {:workflow-steps steps}) (aws/invoke c {:credentials-provider (credentials/basic-credentials-provider {:access-key-id "<KEY>" :secret-access-key "<KEY>"}) :workflow-steps steps}) (aws/invoke c {:credentials-provider (reify credentials/CredentialsProvider (fetch [_])) :workflow-steps steps}) (def res *1) (diagnostics/summarize-log res) (diagnostics/trace-key res :credentials) )
true
(ns cognitect.aws.flow.credentials-stack (:require [cognitect.aws.client.shared :as shared] [cognitect.aws.flow :as flow] [cognitect.aws.credentials :as credentials])) (defn- prepend-queue [q items] (into (into clojure.lang.PersistentQueue/EMPTY items) q)) (defn- provider-step ([name cached-step provider] (provider-step name cached-step provider nil)) ([name cached-step provider report-anomaly?] {:name name :f (fn [context] (if (:credentials context) context (if-let [creds (credentials/valid-credentials (credentials/fetch provider))] (do ;; TODO (dchelimsky,2020-05-22): consider optimization of ;; dequeuing any subsequent credential provider steps. (when-not @cached-step (reset! cached-step (provider-step name cached-step provider))) (assoc context :credentials creds)) (if report-anomaly? {:cognitect.anomalies/category :cognitect.anomalies/incorrect :cognitect.anomalies/message "Unable to find credentials"} context))))})) (defn process-credentials [] (let [cached-step (atom nil)] {:name "process credentials" :f (fn [{:keys [http-client credentials-provider] :as context}] (update context ::flow/queue prepend-queue (cond credentials-provider [(provider-step "user provided credentials provider" cached-step credentials-provider :report-anomaly!)] @cached-step [@cached-step] :else [(provider-step "environment credentials provider" cached-step (credentials/environment-credentials-provider)) (provider-step "system properties credentials provider" cached-step (credentials/system-property-credentials-provider)) (provider-step "profile credentials provider" cached-step (credentials/profile-credentials-provider)) (provider-step "container credentials provider" cached-step (credentials/container-credentials-provider http-client)) (provider-step "instance profile credentials provider" cached-step (credentials/instance-profile-credentials-provider http-client) :report-anomaly!)])))})) (comment (require '[cognitect.aws.client.api :as aws] '[cognitect.aws.diagnostics :as diagnostics]) (def c (aws/client {})) (def steps [(process-credentials) {:name "hide password" :f (fn [context] (if (:credentials context) (assoc-in context [:credentials :aws/secret-access-key] "REDACTED") context))}]) (aws/invoke c {:workflow-steps steps}) (aws/invoke c {:credentials-provider (credentials/basic-credentials-provider {:access-key-id "PI:KEY:<KEY>END_PI" :secret-access-key "PI:KEY:<KEY>END_PI"}) :workflow-steps steps}) (aws/invoke c {:credentials-provider (reify credentials/CredentialsProvider (fetch [_])) :workflow-steps steps}) (def res *1) (diagnostics/summarize-log res) (diagnostics/trace-key res :credentials) )
[ { "context": "o prepends hello to names\"\n (prepend-hello [\"Mike\", \"Joe\", \"John\"]) => [\"Hello, Mike\", \"Hello, Joe\"", "end": 388, "score": 0.9997857809066772, "start": 384, "tag": "NAME", "value": "Mike" }, { "context": "ds hello to names\"\n (prepend-hello [\"Mike\", \"Joe\", \"John\"]) => [\"Hello, Mike\", \"Hello, Joe\", \"Hell", "end": 395, "score": 0.9997686147689819, "start": 392, "tag": "NAME", "value": "Joe" }, { "context": "o to names\"\n (prepend-hello [\"Mike\", \"Joe\", \"John\"]) => [\"Hello, Mike\", \"Hello, Joe\", \"Hello, John\"", "end": 403, "score": 0.9996782541275024, "start": 399, "tag": "NAME", "value": "John" }, { "context": "prepend-hello [\"Mike\", \"Joe\", \"John\"]) => [\"Hello, Mike\", \"Hello, Joe\", \"Hello, John\"]\n (prepend-hel", "end": 423, "score": 0.9996832013130188, "start": 419, "tag": "NAME", "value": "Mike" }, { "context": "\"Mike\", \"Joe\", \"John\"]) => [\"Hello, Mike\", \"Hello, Joe\", \"Hello, John\"]\n (prepend-hello [] => []))\n", "end": 437, "score": 0.9997538328170776, "start": 434, "tag": "NAME", "value": "Joe" }, { "context": " \"John\"]) => [\"Hello, Mike\", \"Hello, Joe\", \"Hello, John\"]\n (prepend-hello [] => []))\n\n(fact \"vowels-", "end": 452, "score": 0.9969243407249451, "start": 448, "tag": "NAME", "value": "John" } ]
ClojureExamples/test/mbfpp/test/oo/iterator/higher_order_functions.clj
cycle-chen/mbfpp-code
4
(ns mbfpp.test.oo.iterator.higher-order-functions (:use [mbfpp.oo.iterator.higher-order-functions]) (:use [midje.sweet])) (fact "sum-sequence sums a sequence" (sum-sequence [42, 100, 58]) => 200) (fact "sum-sequence doesn't allow the empty sequence" (sum-sequence []) => (throws AssertionError)) (fact "prepend-hello prepends hello to names" (prepend-hello ["Mike", "Joe", "John"]) => ["Hello, Mike", "Hello, Joe", "Hello, John"] (prepend-hello [] => [])) (fact "vowels-in-word returns a set of vowels in a word" (vowels-in-word "asdfe") => #{\a \e} (vowels-in-word "cfg") => #{})
107395
(ns mbfpp.test.oo.iterator.higher-order-functions (:use [mbfpp.oo.iterator.higher-order-functions]) (:use [midje.sweet])) (fact "sum-sequence sums a sequence" (sum-sequence [42, 100, 58]) => 200) (fact "sum-sequence doesn't allow the empty sequence" (sum-sequence []) => (throws AssertionError)) (fact "prepend-hello prepends hello to names" (prepend-hello ["<NAME>", "<NAME>", "<NAME>"]) => ["Hello, <NAME>", "Hello, <NAME>", "Hello, <NAME>"] (prepend-hello [] => [])) (fact "vowels-in-word returns a set of vowels in a word" (vowels-in-word "asdfe") => #{\a \e} (vowels-in-word "cfg") => #{})
true
(ns mbfpp.test.oo.iterator.higher-order-functions (:use [mbfpp.oo.iterator.higher-order-functions]) (:use [midje.sweet])) (fact "sum-sequence sums a sequence" (sum-sequence [42, 100, 58]) => 200) (fact "sum-sequence doesn't allow the empty sequence" (sum-sequence []) => (throws AssertionError)) (fact "prepend-hello prepends hello to names" (prepend-hello ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"]) => ["Hello, PI:NAME:<NAME>END_PI", "Hello, PI:NAME:<NAME>END_PI", "Hello, PI:NAME:<NAME>END_PI"] (prepend-hello [] => [])) (fact "vowels-in-word returns a set of vowels in a word" (vowels-in-word "asdfe") => #{\a \e} (vowels-in-word "cfg") => #{})
[ { "context": ";; Copyright (c) Nicola Mometto, Rich Hickey & contributors.\n;; The use and dis", "end": 33, "score": 0.9998553991317749, "start": 19, "tag": "NAME", "value": "Nicola Mometto" }, { "context": ";; Copyright (c) Nicola Mometto, Rich Hickey & contributors.\n;; The use and distribution ter", "end": 46, "score": 0.9998383522033691, "start": 35, "tag": "NAME", "value": "Rich Hickey" } ]
resources/public/js/out/cljs/tools/reader/impl/utils.cljs
yuppieghost/soul-talk
1
;; Copyright (c) Nicola Mometto, Rich Hickey & contributors. ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns cljs.tools.reader.impl.utils (:refer-clojure :exclude [char]) (:require [clojure.string :as string] [goog.string :as gstring])) (defn char [x] (when-not (nil? x) (cljs.core/char x))) (defn ^boolean ex-info? [ex] (instance? cljs.core.ExceptionInfo ex)) (defrecord ReaderConditional [splicing? form]) (defn ^boolean reader-conditional? "Return true if the value is the data representation of a reader conditional" [value] (instance? ReaderConditional value)) (defn reader-conditional "Construct a data representation of a reader conditional. If true, splicing? indicates read-cond-splicing." [form splicing?] (ReaderConditional. splicing? form)) (extend-protocol IPrintWithWriter ReaderConditional (-pr-writer [coll writer opts] (-write writer (str "#?" (when (:splicing? coll) "@"))) (pr-writer (:form coll) writer opts))) (def ws-rx #"[\s]") (defn ^boolean whitespace? "Checks whether a given character is whitespace" [ch] (when-not (nil? ch) (if (identical? ch \,) true (.test ws-rx ch)))) (defn ^boolean numeric? "Checks whether a given character is numeric" [ch] (when-not (nil? ch) (gstring/isNumeric ch))) (defn ^boolean newline? "Checks whether the character is a newline" [c] (or (identical? \newline c) (identical? "\n" c) (nil? c))) (defn desugar-meta "Resolves syntactical sugar in metadata" ;; could be combined with some other desugar? [f] (cond (keyword? f) {f true} (symbol? f) {:tag f} (string? f) {:tag f} :else f)) (def last-id (atom 0)) (defn next-id [] (swap! last-id inc)) (defn namespace-keys [ns keys] (for [key keys] (if (or (symbol? key) (keyword? key)) (let [[key-ns key-name] ((juxt namespace name) key) ->key (if (symbol? key) symbol keyword)] (cond (nil? key-ns) (->key ns key-name) (= "_" key-ns) (->key key-name) :else key)) key))) (defn second' [[a b]] (when-not a b)) (defn char-code [ch base] (let [code (js/parseInt ch base)] (if (js/isNaN code) -1 code)))
112021
;; Copyright (c) <NAME>, <NAME> & contributors. ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns cljs.tools.reader.impl.utils (:refer-clojure :exclude [char]) (:require [clojure.string :as string] [goog.string :as gstring])) (defn char [x] (when-not (nil? x) (cljs.core/char x))) (defn ^boolean ex-info? [ex] (instance? cljs.core.ExceptionInfo ex)) (defrecord ReaderConditional [splicing? form]) (defn ^boolean reader-conditional? "Return true if the value is the data representation of a reader conditional" [value] (instance? ReaderConditional value)) (defn reader-conditional "Construct a data representation of a reader conditional. If true, splicing? indicates read-cond-splicing." [form splicing?] (ReaderConditional. splicing? form)) (extend-protocol IPrintWithWriter ReaderConditional (-pr-writer [coll writer opts] (-write writer (str "#?" (when (:splicing? coll) "@"))) (pr-writer (:form coll) writer opts))) (def ws-rx #"[\s]") (defn ^boolean whitespace? "Checks whether a given character is whitespace" [ch] (when-not (nil? ch) (if (identical? ch \,) true (.test ws-rx ch)))) (defn ^boolean numeric? "Checks whether a given character is numeric" [ch] (when-not (nil? ch) (gstring/isNumeric ch))) (defn ^boolean newline? "Checks whether the character is a newline" [c] (or (identical? \newline c) (identical? "\n" c) (nil? c))) (defn desugar-meta "Resolves syntactical sugar in metadata" ;; could be combined with some other desugar? [f] (cond (keyword? f) {f true} (symbol? f) {:tag f} (string? f) {:tag f} :else f)) (def last-id (atom 0)) (defn next-id [] (swap! last-id inc)) (defn namespace-keys [ns keys] (for [key keys] (if (or (symbol? key) (keyword? key)) (let [[key-ns key-name] ((juxt namespace name) key) ->key (if (symbol? key) symbol keyword)] (cond (nil? key-ns) (->key ns key-name) (= "_" key-ns) (->key key-name) :else key)) key))) (defn second' [[a b]] (when-not a b)) (defn char-code [ch base] (let [code (js/parseInt ch base)] (if (js/isNaN code) -1 code)))
true
;; Copyright (c) PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI & contributors. ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns cljs.tools.reader.impl.utils (:refer-clojure :exclude [char]) (:require [clojure.string :as string] [goog.string :as gstring])) (defn char [x] (when-not (nil? x) (cljs.core/char x))) (defn ^boolean ex-info? [ex] (instance? cljs.core.ExceptionInfo ex)) (defrecord ReaderConditional [splicing? form]) (defn ^boolean reader-conditional? "Return true if the value is the data representation of a reader conditional" [value] (instance? ReaderConditional value)) (defn reader-conditional "Construct a data representation of a reader conditional. If true, splicing? indicates read-cond-splicing." [form splicing?] (ReaderConditional. splicing? form)) (extend-protocol IPrintWithWriter ReaderConditional (-pr-writer [coll writer opts] (-write writer (str "#?" (when (:splicing? coll) "@"))) (pr-writer (:form coll) writer opts))) (def ws-rx #"[\s]") (defn ^boolean whitespace? "Checks whether a given character is whitespace" [ch] (when-not (nil? ch) (if (identical? ch \,) true (.test ws-rx ch)))) (defn ^boolean numeric? "Checks whether a given character is numeric" [ch] (when-not (nil? ch) (gstring/isNumeric ch))) (defn ^boolean newline? "Checks whether the character is a newline" [c] (or (identical? \newline c) (identical? "\n" c) (nil? c))) (defn desugar-meta "Resolves syntactical sugar in metadata" ;; could be combined with some other desugar? [f] (cond (keyword? f) {f true} (symbol? f) {:tag f} (string? f) {:tag f} :else f)) (def last-id (atom 0)) (defn next-id [] (swap! last-id inc)) (defn namespace-keys [ns keys] (for [key keys] (if (or (symbol? key) (keyword? key)) (let [[key-ns key-name] ((juxt namespace name) key) ->key (if (symbol? key) symbol keyword)] (cond (nil? key-ns) (->key ns key-name) (= "_" key-ns) (->key key-name) :else key)) key))) (defn second' [[a b]] (when-not a b)) (defn char-code [ch base] (let [code (js/parseInt ch base)] (if (js/isNaN code) -1 code)))
[ { "context": ";;; Copyright 2012 Hubert Iwaniuk\n\n;;; Licensed under the Apache License, Version 2", "end": 33, "score": 0.9998878836631775, "start": 19, "tag": "NAME", "value": "Hubert Iwaniuk" }, { "context": " http.async client x509 certificates\"\n {:author \"Hubert Iwaniuk / Andrew Diamond / RoomKey.com\"}\n (:refer-clojur", "end": 700, "score": 0.9998942017555237, "start": 686, "tag": "NAME", "value": "Hubert Iwaniuk" }, { "context": "nt x509 certificates\"\n {:author \"Hubert Iwaniuk / Andrew Diamond / RoomKey.com\"}\n (:refer-clojure :exclude [await", "end": 717, "score": 0.99986332654953, "start": 703, "tag": "NAME", "value": "Andrew Diamond" }, { "context": "ificate.crt\")\n(def authtype \"RSA\")\n(def password \"secret\")\n(def ks-cert-alias \"my_test_cert\") ;; alias of", "end": 1478, "score": 0.9995309114456177, "start": 1472, "tag": "PASSWORD", "value": "secret" }, { "context": "-file\n :keystore-password password\n :certificate-file cert-", "end": 2760, "score": 0.9983100891113281, "start": 2752, "tag": "PASSWORD", "value": "password" }, { "context": "-file\n :keystore-password password\n :certificate-file cert-", "end": 3105, "score": 0.9979547262191772, "start": 3097, "tag": "PASSWORD", "value": "password" }, { "context": "s-file\n :keystore-password password\n :certificate-file cert-f", "end": 3789, "score": 0.9982861876487732, "start": 3781, "tag": "PASSWORD", "value": "password" } ]
test/http/async/client/cert_test.clj
slipset/http.async.client
116
;;; Copyright 2012 Hubert Iwaniuk ;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;; you may not use this file except in compliance with the License. ;;; You may obtain a copy of the License at ;;; http://www.apache.org/licenses/LICENSE-2.0 ;;; Unless required by applicable law or agreed to in writing, software ;;; distributed under the License is distributed on an "AS IS" BASIS, ;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;; See the License for the specific language governing permissions and ;;; limitations under the License. (ns http.async.client.cert-test "Testing of http.async client x509 certificates" {:author "Hubert Iwaniuk / Andrew Diamond / RoomKey.com"} (:refer-clojure :exclude [await send]) (:require [http.async.client :refer :all] [http.async.client.cert :refer :all] [clojure [test :refer :all] [stacktrace :refer [print-stack-trace]]]) (:import (org.asynchttpclient AsyncHttpClient DefaultAsyncHttpClient) (java.security KeyStore) (java.security.cert X509Certificate) (javax.net.ssl KeyManagerFactory SSLContext) (http.async.client.cert BlindTrustManager) (org.asynchttpclient.netty.ssl JsseSslEngineFactory))) (set! *warn-on-reflection* true) (def ks-file "test-resources/keystore.jks") (def cert-file "test-resources/certificate.crt") (def authtype "RSA") (def password "secret") (def ks-cert-alias "my_test_cert") ;; alias of cert built into key store (def other-cert-alias "other_cert") ;; alias for certificate.crt (defn load-test-certificate [] (load-x509-cert cert-file)) (defn load-test-keystore [] (load-keystore (resource-stream ks-file) password)) (deftest test-load-x509-cert (is (isa? (class (load-test-certificate)) X509Certificate))) (deftest test-load-keystore (is (= KeyStore (class (load-test-keystore))))) (deftest load-default-keystore (is (instance? KeyStore (load-keystore nil "whatever")))) (deftest test-blind-trust-manager (let [b (BlindTrustManager.) chain (into-array X509Certificate (list (load-test-certificate)))] (is (nil? (.checkClientTrusted b chain authtype))) (is (nil? (.checkServerTrusted b chain authtype))))) (deftest test-add-509-cert (let [ks (load-test-keystore) cert (load-test-certificate) ks (add-x509-cert ks other-cert-alias cert)] (is (= cert (.getCertificate ks other-cert-alias))))) (deftest test-key-manager-factory (let [kmf (key-manager-factory (load-test-keystore) password)] (is (= KeyManagerFactory (class kmf))))) (deftest test-ssl-context (let [ctx1 (ssl-context :keystore-file ks-file :keystore-password password :certificate-file cert-file :certificate-alias other-cert-alias :trust-managers [(BlindTrustManager.)]) ;; Make sure it works without :trust-managers param ctx2 (ssl-context :keystore-file ks-file :keystore-password password :certificate-file cert-file :certificate-alias other-cert-alias)] (is (= SSLContext (class ctx1))) (is (= SSLContext (class ctx2))))) (deftest context-with-default-keystore (is (instance? SSLContext (ssl-context :keystore-file nil :keystore-password nil :certificate-file cert-file :certificate-alias other-cert-alias :trust-managers [(BlindTrustManager.)])))) (deftest test-client (let [ctx (ssl-context :keystore-file ks-file :keystore-password password :certificate-file cert-file :certificate-alias other-cert-alias)] (with-open [client (create-client :ssl-context ctx)] (is (instance? AsyncHttpClient client)) ;; Make sure client is using the SSLContext we supplied (is (instance? JsseSslEngineFactory (-> client .getConfig .getSslEngineFactory))))))
86955
;;; Copyright 2012 <NAME> ;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;; you may not use this file except in compliance with the License. ;;; You may obtain a copy of the License at ;;; http://www.apache.org/licenses/LICENSE-2.0 ;;; Unless required by applicable law or agreed to in writing, software ;;; distributed under the License is distributed on an "AS IS" BASIS, ;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;; See the License for the specific language governing permissions and ;;; limitations under the License. (ns http.async.client.cert-test "Testing of http.async client x509 certificates" {:author "<NAME> / <NAME> / RoomKey.com"} (:refer-clojure :exclude [await send]) (:require [http.async.client :refer :all] [http.async.client.cert :refer :all] [clojure [test :refer :all] [stacktrace :refer [print-stack-trace]]]) (:import (org.asynchttpclient AsyncHttpClient DefaultAsyncHttpClient) (java.security KeyStore) (java.security.cert X509Certificate) (javax.net.ssl KeyManagerFactory SSLContext) (http.async.client.cert BlindTrustManager) (org.asynchttpclient.netty.ssl JsseSslEngineFactory))) (set! *warn-on-reflection* true) (def ks-file "test-resources/keystore.jks") (def cert-file "test-resources/certificate.crt") (def authtype "RSA") (def password "<PASSWORD>") (def ks-cert-alias "my_test_cert") ;; alias of cert built into key store (def other-cert-alias "other_cert") ;; alias for certificate.crt (defn load-test-certificate [] (load-x509-cert cert-file)) (defn load-test-keystore [] (load-keystore (resource-stream ks-file) password)) (deftest test-load-x509-cert (is (isa? (class (load-test-certificate)) X509Certificate))) (deftest test-load-keystore (is (= KeyStore (class (load-test-keystore))))) (deftest load-default-keystore (is (instance? KeyStore (load-keystore nil "whatever")))) (deftest test-blind-trust-manager (let [b (BlindTrustManager.) chain (into-array X509Certificate (list (load-test-certificate)))] (is (nil? (.checkClientTrusted b chain authtype))) (is (nil? (.checkServerTrusted b chain authtype))))) (deftest test-add-509-cert (let [ks (load-test-keystore) cert (load-test-certificate) ks (add-x509-cert ks other-cert-alias cert)] (is (= cert (.getCertificate ks other-cert-alias))))) (deftest test-key-manager-factory (let [kmf (key-manager-factory (load-test-keystore) password)] (is (= KeyManagerFactory (class kmf))))) (deftest test-ssl-context (let [ctx1 (ssl-context :keystore-file ks-file :keystore-password <PASSWORD> :certificate-file cert-file :certificate-alias other-cert-alias :trust-managers [(BlindTrustManager.)]) ;; Make sure it works without :trust-managers param ctx2 (ssl-context :keystore-file ks-file :keystore-password <PASSWORD> :certificate-file cert-file :certificate-alias other-cert-alias)] (is (= SSLContext (class ctx1))) (is (= SSLContext (class ctx2))))) (deftest context-with-default-keystore (is (instance? SSLContext (ssl-context :keystore-file nil :keystore-password nil :certificate-file cert-file :certificate-alias other-cert-alias :trust-managers [(BlindTrustManager.)])))) (deftest test-client (let [ctx (ssl-context :keystore-file ks-file :keystore-password <PASSWORD> :certificate-file cert-file :certificate-alias other-cert-alias)] (with-open [client (create-client :ssl-context ctx)] (is (instance? AsyncHttpClient client)) ;; Make sure client is using the SSLContext we supplied (is (instance? JsseSslEngineFactory (-> client .getConfig .getSslEngineFactory))))))
true
;;; Copyright 2012 PI:NAME:<NAME>END_PI ;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;; you may not use this file except in compliance with the License. ;;; You may obtain a copy of the License at ;;; http://www.apache.org/licenses/LICENSE-2.0 ;;; Unless required by applicable law or agreed to in writing, software ;;; distributed under the License is distributed on an "AS IS" BASIS, ;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;; See the License for the specific language governing permissions and ;;; limitations under the License. (ns http.async.client.cert-test "Testing of http.async client x509 certificates" {:author "PI:NAME:<NAME>END_PI / PI:NAME:<NAME>END_PI / RoomKey.com"} (:refer-clojure :exclude [await send]) (:require [http.async.client :refer :all] [http.async.client.cert :refer :all] [clojure [test :refer :all] [stacktrace :refer [print-stack-trace]]]) (:import (org.asynchttpclient AsyncHttpClient DefaultAsyncHttpClient) (java.security KeyStore) (java.security.cert X509Certificate) (javax.net.ssl KeyManagerFactory SSLContext) (http.async.client.cert BlindTrustManager) (org.asynchttpclient.netty.ssl JsseSslEngineFactory))) (set! *warn-on-reflection* true) (def ks-file "test-resources/keystore.jks") (def cert-file "test-resources/certificate.crt") (def authtype "RSA") (def password "PI:PASSWORD:<PASSWORD>END_PI") (def ks-cert-alias "my_test_cert") ;; alias of cert built into key store (def other-cert-alias "other_cert") ;; alias for certificate.crt (defn load-test-certificate [] (load-x509-cert cert-file)) (defn load-test-keystore [] (load-keystore (resource-stream ks-file) password)) (deftest test-load-x509-cert (is (isa? (class (load-test-certificate)) X509Certificate))) (deftest test-load-keystore (is (= KeyStore (class (load-test-keystore))))) (deftest load-default-keystore (is (instance? KeyStore (load-keystore nil "whatever")))) (deftest test-blind-trust-manager (let [b (BlindTrustManager.) chain (into-array X509Certificate (list (load-test-certificate)))] (is (nil? (.checkClientTrusted b chain authtype))) (is (nil? (.checkServerTrusted b chain authtype))))) (deftest test-add-509-cert (let [ks (load-test-keystore) cert (load-test-certificate) ks (add-x509-cert ks other-cert-alias cert)] (is (= cert (.getCertificate ks other-cert-alias))))) (deftest test-key-manager-factory (let [kmf (key-manager-factory (load-test-keystore) password)] (is (= KeyManagerFactory (class kmf))))) (deftest test-ssl-context (let [ctx1 (ssl-context :keystore-file ks-file :keystore-password PI:PASSWORD:<PASSWORD>END_PI :certificate-file cert-file :certificate-alias other-cert-alias :trust-managers [(BlindTrustManager.)]) ;; Make sure it works without :trust-managers param ctx2 (ssl-context :keystore-file ks-file :keystore-password PI:PASSWORD:<PASSWORD>END_PI :certificate-file cert-file :certificate-alias other-cert-alias)] (is (= SSLContext (class ctx1))) (is (= SSLContext (class ctx2))))) (deftest context-with-default-keystore (is (instance? SSLContext (ssl-context :keystore-file nil :keystore-password nil :certificate-file cert-file :certificate-alias other-cert-alias :trust-managers [(BlindTrustManager.)])))) (deftest test-client (let [ctx (ssl-context :keystore-file ks-file :keystore-password PI:PASSWORD:<PASSWORD>END_PI :certificate-file cert-file :certificate-alias other-cert-alias)] (with-open [client (create-client :ssl-context ctx)] (is (instance? AsyncHttpClient client)) ;; Make sure client is using the SSLContext we supplied (is (instance? JsseSslEngineFactory (-> client .getConfig .getSslEngineFactory))))))
[ { "context": " \"Distribute a release to GitHub.\"\n :author \"Paul Landes\"}\n zensols.ghrelease.dist\n (:import (org.kohs", "end": 71, "score": 0.9998739361763, "start": 60, "tag": "NAME", "value": "Paul Landes" }, { "context": " [\"-r\" \"--repo\" \"the repository identifier (ex: plandes/clj-ghrelease)\"\n :required \"<user/repo name>\"", "end": 6249, "score": 0.9476320743560791, "start": 6242, "tag": "USERNAME", "value": "plandes" } ]
src/clojure/zensols/ghrelease/dist.clj
plandes/clj-ghrelease
0
(ns ^{:doc "Distribute a release to GitHub." :author "Paul Landes"} zensols.ghrelease.dist (:import (org.kohsuke.github GitHub)) (:require [clojure.tools.logging :as log] [clojure.string :as s] [clojure.java.io :as io]) (:require [zensols.actioncli.log4j2 :as lu] [zensols.actioncli.dynamic :refer (defa-)] [zensols.actioncli.parse :refer (with-exception)]) (:require [zensols.ghrelease.changelog :as cl])) (defa- connection-inst) (defn- connection "Create a connection to GitHub" [] (swap! connection-inst #(or % (GitHub/connect)))) (defn- parse-tag [tag] (second (re-find #"^v?([0-9.]+)$" tag))) (defn- squash-version "Map a version string to a number with an order based on each major, minor and debug etc versions of the version. This is used by [[sort-version-tags]]." [version-string] (->> version-string parse-tag (#(s/split % #"[.]")) (map read-string) ((fn [vers] (map (fn [order ver] (->> (repeat order 10) (reduce *) (* ver))) (-> vers count range reverse) vers))) (reduce +))) (defn sort-version-tags "Sort version formats. They have the form: `v?[0-9.]+` (i.e. v0.0.1)." [tags] (sort (fn [a b] (compare (squash-version a) (squash-version b))) tags)) (defn repository "Return a repository by name, where name is <github user>/<repo name>." [repo-name] (log/debugf "looking up repo: %s" repo-name) (try (-> (connection) (.getRepository repo-name)) (catch ArrayIndexOutOfBoundsException e (-> (format "repository not found: %s" repo-name) (ex-info {:repo-name repo-name}) throw)))) (defn latest-tag "Find the latest (highest) for repository **repo**. See [[repository]]." [repo] (->> repo .listTags .iterator iterator-seq (map #(.getName %)) (filter #(parse-tag %)) sort-version-tags last)) (defn release "Look up release in repository **repo** with name (usually tag) **name**. See [[repository]]." [repo name] (log/debugf "looking up release %s in %s" name (.getName repo)) (->> repo .listReleases .iterator iterator-seq (filter #(= name (.getName %))) first)) (defn- changelog-description-github [repo changelog-key & {:keys [changelog-file-name] :or {changelog-file-name "CHANGELOG.md"}}] (try (-> repo (.getFileContent changelog-file-name) .read (cl/format-changelog-entry changelog-key)) (catch java.io.FileNotFoundException e nil))) (defn build-release "Build a release from repository **repo** for tag **tag**. Keys ---- * **:name** the name of the release to create; defaults to **tag** * **:changelog-resource** the CHANGELOG.md file to pull the description per **tag** * **:description** the description (in markup) for the release * **:prerelease?** Non-nil/false if this is a pre-release. See [[repository]]." [repo tag & {:keys [name changelog-resource description prerelease?]}] (log/infof "building release %s for %s" tag (.getName repo)) (let [changelog-key (parse-tag tag) description (or (and changelog-resource (cl/format-changelog-entry changelog-resource changelog-key)) (changelog-description-github repo changelog-key) description) builder (.createRelease repo tag)] (if name (.name builder name)) (if description (.body builder description)) (if prerelease? (.prerelease builder prerelease?)) (.create builder))) (defn upload-asset "Upload an asset to a release, which was created with [[release]]." [release file] (log/infof "uploading asset %s to %s" file (.getName release)) (.uploadAsset release file "application/octet-stream")) (defn- delete-release [repo release-name] (let [release (release repo release-name)] (if-not release (throw (ex-info (format "No such release %s found in repo %s" release-name (.getName repo)) {:repo repo :release-name release-name}))) (.delete release) (log/infof "release %s in %s deleted" release-name (.getName repo)))) (defn- distribute-release [repo-name asset-files & {:keys [delete? tag name changelog-resource description prerelease?] :or {delete? true}}] (log/infof "creatig distribution release for %s" repo-name) (let [repo (repository repo-name) tag (or tag (latest-tag repo)) name (or name tag) release (release repo name) release (cond (and (not delete?) release) (throw (ex-info (format "Release %s already exists" repo-name) {:repo-name repo-name :name name :tag tag})) (and delete? release) (do (delete-release repo name) nil) true release) release (or release (build-release repo name :name tag :changelog-resource changelog-resource :description description :prerelease? prerelease?))] (doseq [asset-file asset-files] (upload-asset release asset-file)) (log/infof "distribution complete: %s/%s" repo-name name))) (defn- args-to-files [args] (->> args (map (fn [arg] (let [file (io/file arg)] (if (or (.isDirectory file) (not (.exists file))) (-> (format "File does not exist: %s" file) (ex-info {:file file}) throw)) file))))) (def dist-command "CLI command to invoke hello world" {:description "create a GitHub release" :options [(lu/log-level-set-option) ["-r" "--repo" "the repository identifier (ex: plandes/clj-ghrelease)" :required "<user/repo name>" :missing "Missing required -r"] ["-t" "--tag" "the version format tag of the release (ex: v0.0.1)" :required "<v?[0-9.]+|latest>" :default "latest" :validate [parse-tag "Tag is not valid"]] ["-n" "--name" "the optional name of the release, which defaults to the latest tag" :required "<name>"] [nil "--nodelete" "don't delete current release if it exists already"] ["-d" "--description" "the optional description of the release" :required "<description>"] ["-c" "--changelog" "description is parsed from changelog (default to repo)" :required "<CHANGELOG.md>" :validate [#(.exists %) "No such file"] :parse-fn #(io/file %)] ["-p" "--prerelease" "indicate this is a pre-release"]] :app (fn [{:keys [repo tag name nodelete description prerelease changelog] :as opts} & args] (with-exception (let [tag (if (= "latest" tag) nil tag) files (args-to-files args)] (if (empty? files) (throw (ex-info "No files given" {}))) (distribute-release repo files :tag tag :name name :delete? (not nodelete) :changelog-resource changelog :description description :prerelease? prerelease))))})
86378
(ns ^{:doc "Distribute a release to GitHub." :author "<NAME>"} zensols.ghrelease.dist (:import (org.kohsuke.github GitHub)) (:require [clojure.tools.logging :as log] [clojure.string :as s] [clojure.java.io :as io]) (:require [zensols.actioncli.log4j2 :as lu] [zensols.actioncli.dynamic :refer (defa-)] [zensols.actioncli.parse :refer (with-exception)]) (:require [zensols.ghrelease.changelog :as cl])) (defa- connection-inst) (defn- connection "Create a connection to GitHub" [] (swap! connection-inst #(or % (GitHub/connect)))) (defn- parse-tag [tag] (second (re-find #"^v?([0-9.]+)$" tag))) (defn- squash-version "Map a version string to a number with an order based on each major, minor and debug etc versions of the version. This is used by [[sort-version-tags]]." [version-string] (->> version-string parse-tag (#(s/split % #"[.]")) (map read-string) ((fn [vers] (map (fn [order ver] (->> (repeat order 10) (reduce *) (* ver))) (-> vers count range reverse) vers))) (reduce +))) (defn sort-version-tags "Sort version formats. They have the form: `v?[0-9.]+` (i.e. v0.0.1)." [tags] (sort (fn [a b] (compare (squash-version a) (squash-version b))) tags)) (defn repository "Return a repository by name, where name is <github user>/<repo name>." [repo-name] (log/debugf "looking up repo: %s" repo-name) (try (-> (connection) (.getRepository repo-name)) (catch ArrayIndexOutOfBoundsException e (-> (format "repository not found: %s" repo-name) (ex-info {:repo-name repo-name}) throw)))) (defn latest-tag "Find the latest (highest) for repository **repo**. See [[repository]]." [repo] (->> repo .listTags .iterator iterator-seq (map #(.getName %)) (filter #(parse-tag %)) sort-version-tags last)) (defn release "Look up release in repository **repo** with name (usually tag) **name**. See [[repository]]." [repo name] (log/debugf "looking up release %s in %s" name (.getName repo)) (->> repo .listReleases .iterator iterator-seq (filter #(= name (.getName %))) first)) (defn- changelog-description-github [repo changelog-key & {:keys [changelog-file-name] :or {changelog-file-name "CHANGELOG.md"}}] (try (-> repo (.getFileContent changelog-file-name) .read (cl/format-changelog-entry changelog-key)) (catch java.io.FileNotFoundException e nil))) (defn build-release "Build a release from repository **repo** for tag **tag**. Keys ---- * **:name** the name of the release to create; defaults to **tag** * **:changelog-resource** the CHANGELOG.md file to pull the description per **tag** * **:description** the description (in markup) for the release * **:prerelease?** Non-nil/false if this is a pre-release. See [[repository]]." [repo tag & {:keys [name changelog-resource description prerelease?]}] (log/infof "building release %s for %s" tag (.getName repo)) (let [changelog-key (parse-tag tag) description (or (and changelog-resource (cl/format-changelog-entry changelog-resource changelog-key)) (changelog-description-github repo changelog-key) description) builder (.createRelease repo tag)] (if name (.name builder name)) (if description (.body builder description)) (if prerelease? (.prerelease builder prerelease?)) (.create builder))) (defn upload-asset "Upload an asset to a release, which was created with [[release]]." [release file] (log/infof "uploading asset %s to %s" file (.getName release)) (.uploadAsset release file "application/octet-stream")) (defn- delete-release [repo release-name] (let [release (release repo release-name)] (if-not release (throw (ex-info (format "No such release %s found in repo %s" release-name (.getName repo)) {:repo repo :release-name release-name}))) (.delete release) (log/infof "release %s in %s deleted" release-name (.getName repo)))) (defn- distribute-release [repo-name asset-files & {:keys [delete? tag name changelog-resource description prerelease?] :or {delete? true}}] (log/infof "creatig distribution release for %s" repo-name) (let [repo (repository repo-name) tag (or tag (latest-tag repo)) name (or name tag) release (release repo name) release (cond (and (not delete?) release) (throw (ex-info (format "Release %s already exists" repo-name) {:repo-name repo-name :name name :tag tag})) (and delete? release) (do (delete-release repo name) nil) true release) release (or release (build-release repo name :name tag :changelog-resource changelog-resource :description description :prerelease? prerelease?))] (doseq [asset-file asset-files] (upload-asset release asset-file)) (log/infof "distribution complete: %s/%s" repo-name name))) (defn- args-to-files [args] (->> args (map (fn [arg] (let [file (io/file arg)] (if (or (.isDirectory file) (not (.exists file))) (-> (format "File does not exist: %s" file) (ex-info {:file file}) throw)) file))))) (def dist-command "CLI command to invoke hello world" {:description "create a GitHub release" :options [(lu/log-level-set-option) ["-r" "--repo" "the repository identifier (ex: plandes/clj-ghrelease)" :required "<user/repo name>" :missing "Missing required -r"] ["-t" "--tag" "the version format tag of the release (ex: v0.0.1)" :required "<v?[0-9.]+|latest>" :default "latest" :validate [parse-tag "Tag is not valid"]] ["-n" "--name" "the optional name of the release, which defaults to the latest tag" :required "<name>"] [nil "--nodelete" "don't delete current release if it exists already"] ["-d" "--description" "the optional description of the release" :required "<description>"] ["-c" "--changelog" "description is parsed from changelog (default to repo)" :required "<CHANGELOG.md>" :validate [#(.exists %) "No such file"] :parse-fn #(io/file %)] ["-p" "--prerelease" "indicate this is a pre-release"]] :app (fn [{:keys [repo tag name nodelete description prerelease changelog] :as opts} & args] (with-exception (let [tag (if (= "latest" tag) nil tag) files (args-to-files args)] (if (empty? files) (throw (ex-info "No files given" {}))) (distribute-release repo files :tag tag :name name :delete? (not nodelete) :changelog-resource changelog :description description :prerelease? prerelease))))})
true
(ns ^{:doc "Distribute a release to GitHub." :author "PI:NAME:<NAME>END_PI"} zensols.ghrelease.dist (:import (org.kohsuke.github GitHub)) (:require [clojure.tools.logging :as log] [clojure.string :as s] [clojure.java.io :as io]) (:require [zensols.actioncli.log4j2 :as lu] [zensols.actioncli.dynamic :refer (defa-)] [zensols.actioncli.parse :refer (with-exception)]) (:require [zensols.ghrelease.changelog :as cl])) (defa- connection-inst) (defn- connection "Create a connection to GitHub" [] (swap! connection-inst #(or % (GitHub/connect)))) (defn- parse-tag [tag] (second (re-find #"^v?([0-9.]+)$" tag))) (defn- squash-version "Map a version string to a number with an order based on each major, minor and debug etc versions of the version. This is used by [[sort-version-tags]]." [version-string] (->> version-string parse-tag (#(s/split % #"[.]")) (map read-string) ((fn [vers] (map (fn [order ver] (->> (repeat order 10) (reduce *) (* ver))) (-> vers count range reverse) vers))) (reduce +))) (defn sort-version-tags "Sort version formats. They have the form: `v?[0-9.]+` (i.e. v0.0.1)." [tags] (sort (fn [a b] (compare (squash-version a) (squash-version b))) tags)) (defn repository "Return a repository by name, where name is <github user>/<repo name>." [repo-name] (log/debugf "looking up repo: %s" repo-name) (try (-> (connection) (.getRepository repo-name)) (catch ArrayIndexOutOfBoundsException e (-> (format "repository not found: %s" repo-name) (ex-info {:repo-name repo-name}) throw)))) (defn latest-tag "Find the latest (highest) for repository **repo**. See [[repository]]." [repo] (->> repo .listTags .iterator iterator-seq (map #(.getName %)) (filter #(parse-tag %)) sort-version-tags last)) (defn release "Look up release in repository **repo** with name (usually tag) **name**. See [[repository]]." [repo name] (log/debugf "looking up release %s in %s" name (.getName repo)) (->> repo .listReleases .iterator iterator-seq (filter #(= name (.getName %))) first)) (defn- changelog-description-github [repo changelog-key & {:keys [changelog-file-name] :or {changelog-file-name "CHANGELOG.md"}}] (try (-> repo (.getFileContent changelog-file-name) .read (cl/format-changelog-entry changelog-key)) (catch java.io.FileNotFoundException e nil))) (defn build-release "Build a release from repository **repo** for tag **tag**. Keys ---- * **:name** the name of the release to create; defaults to **tag** * **:changelog-resource** the CHANGELOG.md file to pull the description per **tag** * **:description** the description (in markup) for the release * **:prerelease?** Non-nil/false if this is a pre-release. See [[repository]]." [repo tag & {:keys [name changelog-resource description prerelease?]}] (log/infof "building release %s for %s" tag (.getName repo)) (let [changelog-key (parse-tag tag) description (or (and changelog-resource (cl/format-changelog-entry changelog-resource changelog-key)) (changelog-description-github repo changelog-key) description) builder (.createRelease repo tag)] (if name (.name builder name)) (if description (.body builder description)) (if prerelease? (.prerelease builder prerelease?)) (.create builder))) (defn upload-asset "Upload an asset to a release, which was created with [[release]]." [release file] (log/infof "uploading asset %s to %s" file (.getName release)) (.uploadAsset release file "application/octet-stream")) (defn- delete-release [repo release-name] (let [release (release repo release-name)] (if-not release (throw (ex-info (format "No such release %s found in repo %s" release-name (.getName repo)) {:repo repo :release-name release-name}))) (.delete release) (log/infof "release %s in %s deleted" release-name (.getName repo)))) (defn- distribute-release [repo-name asset-files & {:keys [delete? tag name changelog-resource description prerelease?] :or {delete? true}}] (log/infof "creatig distribution release for %s" repo-name) (let [repo (repository repo-name) tag (or tag (latest-tag repo)) name (or name tag) release (release repo name) release (cond (and (not delete?) release) (throw (ex-info (format "Release %s already exists" repo-name) {:repo-name repo-name :name name :tag tag})) (and delete? release) (do (delete-release repo name) nil) true release) release (or release (build-release repo name :name tag :changelog-resource changelog-resource :description description :prerelease? prerelease?))] (doseq [asset-file asset-files] (upload-asset release asset-file)) (log/infof "distribution complete: %s/%s" repo-name name))) (defn- args-to-files [args] (->> args (map (fn [arg] (let [file (io/file arg)] (if (or (.isDirectory file) (not (.exists file))) (-> (format "File does not exist: %s" file) (ex-info {:file file}) throw)) file))))) (def dist-command "CLI command to invoke hello world" {:description "create a GitHub release" :options [(lu/log-level-set-option) ["-r" "--repo" "the repository identifier (ex: plandes/clj-ghrelease)" :required "<user/repo name>" :missing "Missing required -r"] ["-t" "--tag" "the version format tag of the release (ex: v0.0.1)" :required "<v?[0-9.]+|latest>" :default "latest" :validate [parse-tag "Tag is not valid"]] ["-n" "--name" "the optional name of the release, which defaults to the latest tag" :required "<name>"] [nil "--nodelete" "don't delete current release if it exists already"] ["-d" "--description" "the optional description of the release" :required "<description>"] ["-c" "--changelog" "description is parsed from changelog (default to repo)" :required "<CHANGELOG.md>" :validate [#(.exists %) "No such file"] :parse-fn #(io/file %)] ["-p" "--prerelease" "indicate this is a pre-release"]] :app (fn [{:keys [repo tag name nodelete description prerelease changelog] :as opts} & args] (with-exception (let [tag (if (= "latest" tag) nil tag) files (args-to-files args)] (if (empty? files) (throw (ex-info "No files given" {}))) (distribute-release repo files :tag tag :name name :delete? (not nodelete) :changelog-resource changelog :description description :prerelease? prerelease))))})
[ { "context": "k-url\n;; AUTH => CLIENT /callback-url {:username \"joebloggs\" :accesstoken \"1234123o487\"}\n\n\n; SCENARIO 1\n; Giv", "end": 912, "score": 0.9996951818466187, "start": 903, "tag": "USERNAME", "value": "joebloggs" }, { "context": "callback-url {:username \"joebloggs\" :accesstoken \"1234123o487\"}\n\n\n; SCENARIO 1\n; Given the user is not logged i", "end": 939, "score": 0.9989013671875, "start": 928, "tag": "PASSWORD", "value": "1234123o487" }, { "context": "et auth-code\")\n state)))\n\n(def first-name \"Frank\")\n(def last-name \"Lasty\")\n(def email \"email@serve", "end": 2989, "score": 0.9994734525680542, "start": 2984, "tag": "NAME", "value": "Frank" }, { "context": "tate)))\n\n(def first-name \"Frank\")\n(def last-name \"Lasty\")\n(def email \"email@server.com\")\n(def password \"v", "end": 3013, "score": 0.9994395971298218, "start": 3008, "tag": "NAME", "value": "Lasty" }, { "context": "name \"Frank\")\n(def last-name \"Lasty\")\n(def email \"email@server.com\")\n(def password \"valid-password\")\n\n(defn setup [s", "end": 3044, "score": 0.9997913241386414, "start": 3028, "tag": "EMAIL", "value": "email@server.com" }, { "context": "y\")\n(def email \"email@server.com\")\n(def password \"valid-password\")\n\n(defn setup [stores]\n (let [client (cl-client", "end": 3076, "score": 0.9993365406990051, "start": 3062, "tag": "PASSWORD", "value": "valid-password" }, { "context": "des-content [ks/profile-page-profile-card-email] \"email@server.com\")\n (kc/selector-includes-conte", "end": 4692, "score": 0.997900664806366, "start": 4676, "tag": "EMAIL", "value": "email@server.com" }, { "context": "udes-content [ks/profile-page-profile-card-name] \"Frank Lasty\")\n (kc/selector-has-attribute-", "end": 4793, "score": 0.9998328685760498, "start": 4782, "tag": "NAME", "value": "Frank Lasty" }, { "context": " (k/fill-in ks/sign-in-password-input \"invalid-password\")\n (k/press ks/sign-in-submit)", "end": 9022, "score": 0.9990699887275696, "start": 9006, "tag": "PASSWORD", "value": "invalid-password" } ]
test/stonecutter/integration/kerodon/oauth.clj
d-cent/stonecutter
39
(ns stonecutter.integration.kerodon.oauth (:require [midje.sweet :refer :all] [kerodon.core :as k] [clojure.string :as string] [clauth.client :as cl-client] [stonecutter.db.storage :as s] [stonecutter.integration.kerodon.kerodon-checkers :as kc] [stonecutter.integration.kerodon.kerodon-selectors :as ks] [stonecutter.integration.integration-helpers :as ih] [stonecutter.test.test-helpers :as th] [stonecutter.config :as config])) ;; CLIENT => AUTH /authorisation?client-id=123&response_type=code&redirect_uri=callback-url ;; USER LOGIN (Auth Server) ;; ALLOW/DENY (Auth Server) (Leave for later) ;; AUTH => CLIENT /callback-url?auth-code=blah ;; CLIENT => AUTH /token?client-id=123&client-secret=secret&code=code&redirect_uri=callback-url ;; AUTH => CLIENT /callback-url {:username "joebloggs" :accesstoken "1234123o487"} ; SCENARIO 1 ; Given the user is not logged in, then auth server redirects user to log in page ; after user has logged in, then auth server makes http call to client ; SCENARIO 2 ; Given the user is logged in, then auth server makes http call to client wiht auth-code ; USER EXPERIENCE ; CLIENT: Click login (redirects to Stonecutter) ; STONECUTTER: Login with username and password (redirect to Client) ;<- Auth/Client conversation ; CLIENT: 'You are logged in' (defn browser-sends-authorisation-request-from-client-redirect [state client-id] (-> state (k/visit "/authorisation" :headers {"accept" "text/html"} :params {:client_id client-id :response_type "code" :redirect_uri "http://myclient.com/callback"}))) (defn get-auth-code [state] (when-let [location (-> state :response (get-in [:headers "Location"]))] (let [query-string (-> location (string/split #"\?") (peek)) auth-code (-> {:query-string query-string} (ring.middleware.params/params-request) (get-in [:params "code"]))] auth-code))) (defn client-sends-access-token-request [state client-id client-secret] (if-let [auth-code (get-auth-code state)] (-> state (dissoc :cookie-jar) ;; HTTP request so won't have browser cookie (k/visit "/api/token" :request-method :post :params {:grant_type "authorization_code" :redirect_uri "http://myclient.com/callback" :code auth-code :client_id client-id :client_secret client-secret})) (do (prn "============ Error: Unable to get auth-code") state))) (def first-name "Frank") (def last-name "Lasty") (def email "email@server.com") (def password "valid-password") (defn setup [stores] (let [client (cl-client/register-client (s/get-client-store stores) "myclient" "http://myclient.com") client-id (:client-id client) client-secret (:client-secret client) invalid-client-secret (string/reverse client-secret) user (-> (s/get-user-store stores) (th/store-user! email password))] {:client-id client-id :client-secret client-secret :client-name (:name client) :invalid-client-secret invalid-client-secret})) (defn print-debug [v] (prn "Kerodon:" v) v) (defn sign-in [state] (-> state (k/fill-in ks/sign-in-email-input email) (k/fill-in ks/sign-in-password-input password) (k/press ks/sign-in-submit))) (facts "user authorising client-apps" (facts "user can sign in through client" (ih/setup-db) (let [stores (s/create-in-memory-stores (ih/get-test-db-connection)) {:keys [client-id client-secret]} (setup stores)] (-> (k/session (ih/build-app {:stores-m stores})) (browser-sends-authorisation-request-from-client-redirect client-id) (kc/check-and-follow-redirect "to index") ;; login (kc/page-uri-is "/") sign-in ;; check redirect - should have auth_code (kc/check-and-follow-redirect "to authorisation") (kc/page-uri-is "/authorisation") (kc/selector-includes-content [ks/profile-page-profile-card-email] "email@server.com") (kc/selector-includes-content [ks/profile-page-profile-card-name] "Frank Lasty") (kc/selector-has-attribute-with-content [ks/profile-page-profile-card-image :img] :src config/default-profile-picture) (kc/check-and-press ks/authorise-share-profile-button) (kc/location-contains "callback?code=") (client-sends-access-token-request client-id client-secret) ; return 200 with new access_token (kc/response-has-access-token) (kc/response-has-user-info)))) (facts "user who has already authorised client does not need to authorise client again" (ih/setup-db) (let [stores (s/create-in-memory-stores (ih/get-test-db-connection)) {:keys [client-id client-secret client-name]} (setup stores)] (-> (k/session (ih/build-app {:stores-m stores})) ;; authorise client for the first time (browser-sends-authorisation-request-from-client-redirect client-id) (k/follow-redirect) sign-in (k/follow-redirect) (k/press ks/authorise-share-profile-button) ;; send authorisation request for the second time (browser-sends-authorisation-request-from-client-redirect client-id) (kc/location-contains "callback?code=") (client-sends-access-token-request client-id client-secret) ;; return 200 with new access_token (kc/response-has-access-token) (kc/response-has-user-info)))) (facts "user is redirected to authorisation-failure page when cancelling authorisation" (ih/setup-db) (let [stores (s/create-in-memory-stores (ih/get-test-db-connection)) {:keys [client-id client-secret]} (setup stores)] (-> (k/session (ih/build-app {:stores-m stores})) (browser-sends-authorisation-request-from-client-redirect client-id) (k/follow-redirect) ;; login (kc/page-uri-is "/") sign-in ;; check redirect - should have auth_code (k/follow-redirect) (kc/page-uri-is "/authorisation") (k/follow ks/authorise-cancel-link) (kc/page-uri-is "/authorise-failure") :response :status)) => 200)) (facts "no access token will be issued with invalid credentials" (facts "user cannot sign in with invalid client secret" (ih/setup-db) (let [stores (s/create-in-memory-stores (ih/get-test-db-connection)) {:keys [client-id invalid-client-secret]} (setup stores)] (-> (k/session (ih/build-app {:stores-m stores})) (browser-sends-authorisation-request-from-client-redirect client-id) (k/follow-redirect) ;; login (kc/page-uri-is "/") sign-in ;; check redirect - should have auth_code (k/follow-redirect) (kc/page-uri-is "/authorisation") (k/press ks/authorise-share-profile-button) (kc/location-contains "callback?code=") (client-sends-access-token-request client-id invalid-client-secret) :response :status)) => 400) (facts "user cannot sign in with invalid password" (ih/setup-db) (let [stores (s/create-in-memory-stores (ih/get-test-db-connection)) {:keys [client-id]} (setup stores)] (-> (k/session (ih/build-app {:stores-m stores})) (browser-sends-authorisation-request-from-client-redirect client-id) (k/follow-redirect) ;; login (kc/page-uri-is "/") (k/fill-in ks/sign-in-email-input email) (k/fill-in ks/sign-in-password-input "invalid-password") (k/press ks/sign-in-submit) :response :body)) => (contains "Invalid email address or password"))) (ih/teardown-db)
47442
(ns stonecutter.integration.kerodon.oauth (:require [midje.sweet :refer :all] [kerodon.core :as k] [clojure.string :as string] [clauth.client :as cl-client] [stonecutter.db.storage :as s] [stonecutter.integration.kerodon.kerodon-checkers :as kc] [stonecutter.integration.kerodon.kerodon-selectors :as ks] [stonecutter.integration.integration-helpers :as ih] [stonecutter.test.test-helpers :as th] [stonecutter.config :as config])) ;; CLIENT => AUTH /authorisation?client-id=123&response_type=code&redirect_uri=callback-url ;; USER LOGIN (Auth Server) ;; ALLOW/DENY (Auth Server) (Leave for later) ;; AUTH => CLIENT /callback-url?auth-code=blah ;; CLIENT => AUTH /token?client-id=123&client-secret=secret&code=code&redirect_uri=callback-url ;; AUTH => CLIENT /callback-url {:username "joebloggs" :accesstoken "<PASSWORD>"} ; SCENARIO 1 ; Given the user is not logged in, then auth server redirects user to log in page ; after user has logged in, then auth server makes http call to client ; SCENARIO 2 ; Given the user is logged in, then auth server makes http call to client wiht auth-code ; USER EXPERIENCE ; CLIENT: Click login (redirects to Stonecutter) ; STONECUTTER: Login with username and password (redirect to Client) ;<- Auth/Client conversation ; CLIENT: 'You are logged in' (defn browser-sends-authorisation-request-from-client-redirect [state client-id] (-> state (k/visit "/authorisation" :headers {"accept" "text/html"} :params {:client_id client-id :response_type "code" :redirect_uri "http://myclient.com/callback"}))) (defn get-auth-code [state] (when-let [location (-> state :response (get-in [:headers "Location"]))] (let [query-string (-> location (string/split #"\?") (peek)) auth-code (-> {:query-string query-string} (ring.middleware.params/params-request) (get-in [:params "code"]))] auth-code))) (defn client-sends-access-token-request [state client-id client-secret] (if-let [auth-code (get-auth-code state)] (-> state (dissoc :cookie-jar) ;; HTTP request so won't have browser cookie (k/visit "/api/token" :request-method :post :params {:grant_type "authorization_code" :redirect_uri "http://myclient.com/callback" :code auth-code :client_id client-id :client_secret client-secret})) (do (prn "============ Error: Unable to get auth-code") state))) (def first-name "<NAME>") (def last-name "<NAME>") (def email "<EMAIL>") (def password "<PASSWORD>") (defn setup [stores] (let [client (cl-client/register-client (s/get-client-store stores) "myclient" "http://myclient.com") client-id (:client-id client) client-secret (:client-secret client) invalid-client-secret (string/reverse client-secret) user (-> (s/get-user-store stores) (th/store-user! email password))] {:client-id client-id :client-secret client-secret :client-name (:name client) :invalid-client-secret invalid-client-secret})) (defn print-debug [v] (prn "Kerodon:" v) v) (defn sign-in [state] (-> state (k/fill-in ks/sign-in-email-input email) (k/fill-in ks/sign-in-password-input password) (k/press ks/sign-in-submit))) (facts "user authorising client-apps" (facts "user can sign in through client" (ih/setup-db) (let [stores (s/create-in-memory-stores (ih/get-test-db-connection)) {:keys [client-id client-secret]} (setup stores)] (-> (k/session (ih/build-app {:stores-m stores})) (browser-sends-authorisation-request-from-client-redirect client-id) (kc/check-and-follow-redirect "to index") ;; login (kc/page-uri-is "/") sign-in ;; check redirect - should have auth_code (kc/check-and-follow-redirect "to authorisation") (kc/page-uri-is "/authorisation") (kc/selector-includes-content [ks/profile-page-profile-card-email] "<EMAIL>") (kc/selector-includes-content [ks/profile-page-profile-card-name] "<NAME>") (kc/selector-has-attribute-with-content [ks/profile-page-profile-card-image :img] :src config/default-profile-picture) (kc/check-and-press ks/authorise-share-profile-button) (kc/location-contains "callback?code=") (client-sends-access-token-request client-id client-secret) ; return 200 with new access_token (kc/response-has-access-token) (kc/response-has-user-info)))) (facts "user who has already authorised client does not need to authorise client again" (ih/setup-db) (let [stores (s/create-in-memory-stores (ih/get-test-db-connection)) {:keys [client-id client-secret client-name]} (setup stores)] (-> (k/session (ih/build-app {:stores-m stores})) ;; authorise client for the first time (browser-sends-authorisation-request-from-client-redirect client-id) (k/follow-redirect) sign-in (k/follow-redirect) (k/press ks/authorise-share-profile-button) ;; send authorisation request for the second time (browser-sends-authorisation-request-from-client-redirect client-id) (kc/location-contains "callback?code=") (client-sends-access-token-request client-id client-secret) ;; return 200 with new access_token (kc/response-has-access-token) (kc/response-has-user-info)))) (facts "user is redirected to authorisation-failure page when cancelling authorisation" (ih/setup-db) (let [stores (s/create-in-memory-stores (ih/get-test-db-connection)) {:keys [client-id client-secret]} (setup stores)] (-> (k/session (ih/build-app {:stores-m stores})) (browser-sends-authorisation-request-from-client-redirect client-id) (k/follow-redirect) ;; login (kc/page-uri-is "/") sign-in ;; check redirect - should have auth_code (k/follow-redirect) (kc/page-uri-is "/authorisation") (k/follow ks/authorise-cancel-link) (kc/page-uri-is "/authorise-failure") :response :status)) => 200)) (facts "no access token will be issued with invalid credentials" (facts "user cannot sign in with invalid client secret" (ih/setup-db) (let [stores (s/create-in-memory-stores (ih/get-test-db-connection)) {:keys [client-id invalid-client-secret]} (setup stores)] (-> (k/session (ih/build-app {:stores-m stores})) (browser-sends-authorisation-request-from-client-redirect client-id) (k/follow-redirect) ;; login (kc/page-uri-is "/") sign-in ;; check redirect - should have auth_code (k/follow-redirect) (kc/page-uri-is "/authorisation") (k/press ks/authorise-share-profile-button) (kc/location-contains "callback?code=") (client-sends-access-token-request client-id invalid-client-secret) :response :status)) => 400) (facts "user cannot sign in with invalid password" (ih/setup-db) (let [stores (s/create-in-memory-stores (ih/get-test-db-connection)) {:keys [client-id]} (setup stores)] (-> (k/session (ih/build-app {:stores-m stores})) (browser-sends-authorisation-request-from-client-redirect client-id) (k/follow-redirect) ;; login (kc/page-uri-is "/") (k/fill-in ks/sign-in-email-input email) (k/fill-in ks/sign-in-password-input "<PASSWORD>") (k/press ks/sign-in-submit) :response :body)) => (contains "Invalid email address or password"))) (ih/teardown-db)
true
(ns stonecutter.integration.kerodon.oauth (:require [midje.sweet :refer :all] [kerodon.core :as k] [clojure.string :as string] [clauth.client :as cl-client] [stonecutter.db.storage :as s] [stonecutter.integration.kerodon.kerodon-checkers :as kc] [stonecutter.integration.kerodon.kerodon-selectors :as ks] [stonecutter.integration.integration-helpers :as ih] [stonecutter.test.test-helpers :as th] [stonecutter.config :as config])) ;; CLIENT => AUTH /authorisation?client-id=123&response_type=code&redirect_uri=callback-url ;; USER LOGIN (Auth Server) ;; ALLOW/DENY (Auth Server) (Leave for later) ;; AUTH => CLIENT /callback-url?auth-code=blah ;; CLIENT => AUTH /token?client-id=123&client-secret=secret&code=code&redirect_uri=callback-url ;; AUTH => CLIENT /callback-url {:username "joebloggs" :accesstoken "PI:PASSWORD:<PASSWORD>END_PI"} ; SCENARIO 1 ; Given the user is not logged in, then auth server redirects user to log in page ; after user has logged in, then auth server makes http call to client ; SCENARIO 2 ; Given the user is logged in, then auth server makes http call to client wiht auth-code ; USER EXPERIENCE ; CLIENT: Click login (redirects to Stonecutter) ; STONECUTTER: Login with username and password (redirect to Client) ;<- Auth/Client conversation ; CLIENT: 'You are logged in' (defn browser-sends-authorisation-request-from-client-redirect [state client-id] (-> state (k/visit "/authorisation" :headers {"accept" "text/html"} :params {:client_id client-id :response_type "code" :redirect_uri "http://myclient.com/callback"}))) (defn get-auth-code [state] (when-let [location (-> state :response (get-in [:headers "Location"]))] (let [query-string (-> location (string/split #"\?") (peek)) auth-code (-> {:query-string query-string} (ring.middleware.params/params-request) (get-in [:params "code"]))] auth-code))) (defn client-sends-access-token-request [state client-id client-secret] (if-let [auth-code (get-auth-code state)] (-> state (dissoc :cookie-jar) ;; HTTP request so won't have browser cookie (k/visit "/api/token" :request-method :post :params {:grant_type "authorization_code" :redirect_uri "http://myclient.com/callback" :code auth-code :client_id client-id :client_secret client-secret})) (do (prn "============ Error: Unable to get auth-code") state))) (def first-name "PI:NAME:<NAME>END_PI") (def last-name "PI:NAME:<NAME>END_PI") (def email "PI:EMAIL:<EMAIL>END_PI") (def password "PI:PASSWORD:<PASSWORD>END_PI") (defn setup [stores] (let [client (cl-client/register-client (s/get-client-store stores) "myclient" "http://myclient.com") client-id (:client-id client) client-secret (:client-secret client) invalid-client-secret (string/reverse client-secret) user (-> (s/get-user-store stores) (th/store-user! email password))] {:client-id client-id :client-secret client-secret :client-name (:name client) :invalid-client-secret invalid-client-secret})) (defn print-debug [v] (prn "Kerodon:" v) v) (defn sign-in [state] (-> state (k/fill-in ks/sign-in-email-input email) (k/fill-in ks/sign-in-password-input password) (k/press ks/sign-in-submit))) (facts "user authorising client-apps" (facts "user can sign in through client" (ih/setup-db) (let [stores (s/create-in-memory-stores (ih/get-test-db-connection)) {:keys [client-id client-secret]} (setup stores)] (-> (k/session (ih/build-app {:stores-m stores})) (browser-sends-authorisation-request-from-client-redirect client-id) (kc/check-and-follow-redirect "to index") ;; login (kc/page-uri-is "/") sign-in ;; check redirect - should have auth_code (kc/check-and-follow-redirect "to authorisation") (kc/page-uri-is "/authorisation") (kc/selector-includes-content [ks/profile-page-profile-card-email] "PI:EMAIL:<EMAIL>END_PI") (kc/selector-includes-content [ks/profile-page-profile-card-name] "PI:NAME:<NAME>END_PI") (kc/selector-has-attribute-with-content [ks/profile-page-profile-card-image :img] :src config/default-profile-picture) (kc/check-and-press ks/authorise-share-profile-button) (kc/location-contains "callback?code=") (client-sends-access-token-request client-id client-secret) ; return 200 with new access_token (kc/response-has-access-token) (kc/response-has-user-info)))) (facts "user who has already authorised client does not need to authorise client again" (ih/setup-db) (let [stores (s/create-in-memory-stores (ih/get-test-db-connection)) {:keys [client-id client-secret client-name]} (setup stores)] (-> (k/session (ih/build-app {:stores-m stores})) ;; authorise client for the first time (browser-sends-authorisation-request-from-client-redirect client-id) (k/follow-redirect) sign-in (k/follow-redirect) (k/press ks/authorise-share-profile-button) ;; send authorisation request for the second time (browser-sends-authorisation-request-from-client-redirect client-id) (kc/location-contains "callback?code=") (client-sends-access-token-request client-id client-secret) ;; return 200 with new access_token (kc/response-has-access-token) (kc/response-has-user-info)))) (facts "user is redirected to authorisation-failure page when cancelling authorisation" (ih/setup-db) (let [stores (s/create-in-memory-stores (ih/get-test-db-connection)) {:keys [client-id client-secret]} (setup stores)] (-> (k/session (ih/build-app {:stores-m stores})) (browser-sends-authorisation-request-from-client-redirect client-id) (k/follow-redirect) ;; login (kc/page-uri-is "/") sign-in ;; check redirect - should have auth_code (k/follow-redirect) (kc/page-uri-is "/authorisation") (k/follow ks/authorise-cancel-link) (kc/page-uri-is "/authorise-failure") :response :status)) => 200)) (facts "no access token will be issued with invalid credentials" (facts "user cannot sign in with invalid client secret" (ih/setup-db) (let [stores (s/create-in-memory-stores (ih/get-test-db-connection)) {:keys [client-id invalid-client-secret]} (setup stores)] (-> (k/session (ih/build-app {:stores-m stores})) (browser-sends-authorisation-request-from-client-redirect client-id) (k/follow-redirect) ;; login (kc/page-uri-is "/") sign-in ;; check redirect - should have auth_code (k/follow-redirect) (kc/page-uri-is "/authorisation") (k/press ks/authorise-share-profile-button) (kc/location-contains "callback?code=") (client-sends-access-token-request client-id invalid-client-secret) :response :status)) => 400) (facts "user cannot sign in with invalid password" (ih/setup-db) (let [stores (s/create-in-memory-stores (ih/get-test-db-connection)) {:keys [client-id]} (setup stores)] (-> (k/session (ih/build-app {:stores-m stores})) (browser-sends-authorisation-request-from-client-redirect client-id) (k/follow-redirect) ;; login (kc/page-uri-is "/") (k/fill-in ks/sign-in-email-input email) (k/fill-in ks/sign-in-password-input "PI:PASSWORD:<PASSWORD>END_PI") (k/press ks/sign-in-submit) :response :body)) => (contains "Invalid email address or password"))) (ih/teardown-db)
[ { "context": "ming is not about typing... it's about thinking. -Rich Hickey\"\n \"This could be the start of a beautiful progr", "end": 135, "score": 0.9998727440834045, "start": 124, "tag": "NAME", "value": "Rich Hickey" } ]
src/main/resources/archetype-resources/src/main/clojure/__packageInPathFormat__/core.clj
cenzhe/archetype-closed
0
(ns ${package}.core) (def fortune-cookies ["Happy Hacking!" "Programming is not about typing... it's about thinking. -Rich Hickey" "This could be the start of a beautiful program."]) (defn fortune [] (nth fortune-cookies (int (* (Math/random) 3))))
91213
(ns ${package}.core) (def fortune-cookies ["Happy Hacking!" "Programming is not about typing... it's about thinking. -<NAME>" "This could be the start of a beautiful program."]) (defn fortune [] (nth fortune-cookies (int (* (Math/random) 3))))
true
(ns ${package}.core) (def fortune-cookies ["Happy Hacking!" "Programming is not about typing... it's about thinking. -PI:NAME:<NAME>END_PI" "This could be the start of a beautiful program."]) (defn fortune [] (nth fortune-cookies (int (* (Math/random) 3))))
[ { "context": "numbered false}]]\n(def scoreboard\n (ova [{:name \"Bill\" :attempts 0 :score {:all ()}}\n {:name \"Jo", "end": 333, "score": 0.9996734857559204, "start": 329, "tag": "NAME", "value": "Bill" }, { "context": "ll\" :attempts 0 :score {:all ()}}\n {:name \"John\" :attempts 0 :score {:all ()}}\n {:name \"Sa", "end": 385, "score": 0.9996698498725891, "start": 381, "tag": "NAME", "value": "John" }, { "context": "hn\" :attempts 0 :score {:all ()}}\n {:name \"Sally\" :attempts 0 :score {:all ()}}\n {:name \"Fr", "end": 438, "score": 0.9996358156204224, "start": 433, "tag": "NAME", "value": "Sally" }, { "context": "ly\" :attempts 0 :score {:all ()}}\n {:name \"Fred\" :attempts 0 :score {:all ()}}]))\n\n\"#### update ", "end": 490, "score": 0.9997385740280151, "start": 486, "tag": "NAME", "value": "Fred" }, { "context": "ered false}]]\n(comment\n (sim! scoreboard)\n\n => [Sally is on attempt 1\n Bill is on attempt 1\n ", "end": 2764, "score": 0.9876914024353027, "start": 2759, "tag": "NAME", "value": "Sally" }, { "context": "im! scoreboard)\n\n => [Sally is on attempt 1\n Bill is on attempt 1\n Bill has a new highscore 3", "end": 2791, "score": 0.995004415512085, "start": 2787, "tag": "NAME", "value": "Bill" }, { "context": "y is on attempt 1\n Bill is on attempt 1\n Bill has a new highscore 35\n Sally has a new hig", "end": 2818, "score": 0.9903936982154846, "start": 2814, "tag": "NAME", "value": "Bill" }, { "context": "attempt 1\n Bill has a new highscore 35\n Sally has a new highscore 40\n John is on attempt ", "end": 2854, "score": 0.9795998334884644, "start": 2849, "tag": "NAME", "value": "Sally" }, { "context": "core 35\n Sally has a new highscore 40\n John is on attempt 1\n Fred is on attempt 1\n ", "end": 2889, "score": 0.9933600425720215, "start": 2885, "tag": "NAME", "value": "John" }, { "context": "new highscore 40\n John is on attempt 1\n Fred is on attempt 1\n Sally is on attempt 2\n ", "end": 2916, "score": 0.9949377775192261, "start": 2912, "tag": "NAME", "value": "Fred" }, { "context": "n is on attempt 1\n Fred is on attempt 1\n Sally is on attempt 2\n Fred has a new highscore 3", "end": 2944, "score": 0.9656144380569458, "start": 2939, "tag": "NAME", "value": "Sally" }, { "context": " is on attempt 1\n Sally is on attempt 2\n Fred has a new highscore 38\n John has a new high", "end": 2971, "score": 0.9897871017456055, "start": 2967, "tag": "NAME", "value": "Fred" }, { "context": "attempt 2\n Fred has a new highscore 38\n John has a new highscore 28\n Bill is on attempt ", "end": 3006, "score": 0.8629589080810547, "start": 3002, "tag": "NAME", "value": "John" }, { "context": "score 38\n John has a new highscore 28\n Bill is on attempt 2\n Fred is on attempt 2\n ", "end": 3041, "score": 0.9825633764266968, "start": 3037, "tag": "NAME", "value": "Bill" }, { "context": "new highscore 28\n Bill is on attempt 2\n Fred is on attempt 2\n John is on attempt 2\n ", "end": 3068, "score": 0.9916252493858337, "start": 3064, "tag": "NAME", "value": "Fred" }, { "context": "l is on attempt 2\n Fred is on attempt 2\n John is on attempt 2\n John is on attempt 3\n ", "end": 3095, "score": 0.9665459394454956, "start": 3091, "tag": "NAME", "value": "John" }, { "context": "d is on attempt 2\n John is on attempt 2\n John is on attempt 3\n Bill is on attempt 3\n ", "end": 3122, "score": 0.9111697673797607, "start": 3118, "tag": "NAME", "value": "John" }, { "context": "n is on attempt 2\n John is on attempt 3\n Bill is on attempt 3\n Sally is on attempt 3\n ", "end": 3149, "score": 0.974926769733429, "start": 3145, "tag": "NAME", "value": "Bill" }, { "context": "n is on attempt 3\n Bill is on attempt 3\n Sally is on attempt 3\n Bill has a new highscore 3", "end": 3177, "score": 0.9456291794776917, "start": 3172, "tag": "NAME", "value": "Sally" }, { "context": " is on attempt 3\n Sally is on attempt 3\n Bill has a new highscore 36\n Bill is on attempt ", "end": 3204, "score": 0.9709951281547546, "start": 3200, "tag": "NAME", "value": "Bill" }, { "context": "attempt 3\n Bill has a new highscore 36\n Bill is on attempt 4\n John is on attempt 4\n ", "end": 3239, "score": 0.9621784090995789, "start": 3235, "tag": "NAME", "value": "Bill" }, { "context": "new highscore 36\n Bill is on attempt 4\n John is on attempt 4\n Fred is on attempt 3\n ", "end": 3266, "score": 0.9738988280296326, "start": 3262, "tag": "NAME", "value": "John" }, { "context": "l is on attempt 4\n John is on attempt 4\n Fred is on attempt 3\n Sally is on attempt 4\n ", "end": 3293, "score": 0.9913139343261719, "start": 3289, "tag": "NAME", "value": "Fred" }, { "context": "n is on attempt 4\n Fred is on attempt 3\n Sally is on attempt 4\n Fred is on attempt 4\n ", "end": 3321, "score": 0.9661916494369507, "start": 3316, "tag": "NAME", "value": "Sally" }, { "context": " is on attempt 3\n Sally is on attempt 4\n Fred is on attempt 4\n John is on attempt 5\n ", "end": 3348, "score": 0.9884815216064453, "start": 3344, "tag": "NAME", "value": "Fred" }, { "context": "y is on attempt 4\n Fred is on attempt 4\n John is on attempt 5\n Sally is on attempt 5\n ", "end": 3375, "score": 0.9236317873001099, "start": 3371, "tag": "NAME", "value": "John" }, { "context": "d is on attempt 4\n John is on attempt 5\n Sally is on attempt 5\n Bill is on attempt 5\n ", "end": 3403, "score": 0.8866980075836182, "start": 3398, "tag": "NAME", "value": "Sally" }, { "context": " is on attempt 5\n Sally is on attempt 5\n Bill is on attempt 5\n Bill has a new highscore 3", "end": 3430, "score": 0.7497378587722778, "start": 3426, "tag": "NAME", "value": "Bill" }, { "context": "y is on attempt 5\n Bill is on attempt 5\n Bill has a new highscore 39\n Bill is on attempt ", "end": 3457, "score": 0.6678916811943054, "start": 3453, "tag": "NAME", "value": "Bill" }, { "context": "new highscore 39\n Bill is on attempt 6\n John has a new highscore 30\n Fred is on attempt ", "end": 3519, "score": 0.8440914750099182, "start": 3515, "tag": "NAME", "value": "John" }, { "context": "attempt 6\n John has a new highscore 30\n Fred is on attempt 5\n John is on attempt 6\n ", "end": 3554, "score": 0.9700527191162109, "start": 3550, "tag": "NAME", "value": "Fred" }, { "context": "d is on attempt 5\n John is on attempt 6\n Bill has a new highscore 41\n John is on attempt ", "end": 3608, "score": 0.5589249730110168, "start": 3604, "tag": "NAME", "value": "Bill" }, { "context": "ew highscore 45\n Sally is on attempt 1\n Fred is on attempt 1\n John is on attempt 1\n ", "end": 3960, "score": 0.9843933582305908, "start": 3956, "tag": "NAME", "value": "Fred" }, { "context": "y is on attempt 1\n Fred is on attempt 1\n John is on attempt 1\n Bill is on attempt 1\n ", "end": 3987, "score": 0.5125956535339355, "start": 3983, "tag": "NAME", "value": "John" }, { "context": " new highscore 3\n Bill is on attempt 2\n Fred has a new highscore 22\n John is on attempt ", "end": 4173, "score": 0.9932723045349121, "start": 4169, "tag": "NAME", "value": "Fred" }, { "context": "attempt 2\n Fred has a new highscore 22\n John is on attempt 2\n Bill has a new highscore 1", "end": 4208, "score": 0.6748613119125366, "start": 4204, "tag": "NAME", "value": "John" }, { "context": "new highscore 22\n John is on attempt 2\n Bill has a new highscore 18\n Fred is on attempt ", "end": 4235, "score": 0.8967153429985046, "start": 4231, "tag": "NAME", "value": "Bill" }, { "context": "attempt 2\n Bill has a new highscore 18\n Fred is on attempt 2\n Bill is on attempt 3\n ", "end": 4270, "score": 0.9406989812850952, "start": 4266, "tag": "NAME", "value": "Fred" }, { "context": "new highscore 18\n Fred is on attempt 2\n Bill is on attempt 3\n Sally is on attempt 2\n ", "end": 4297, "score": 0.7989261746406555, "start": 4293, "tag": "NAME", "value": "Bill" }, { "context": "y is on attempt 2\n John is on attempt 3\n Fred is on attempt 3\n Bill has a new highscore 3", "end": 4379, "score": 0.9549649953842163, "start": 4375, "tag": "NAME", "value": "Fred" }, { "context": "n is on attempt 3\n Fred is on attempt 3\n Bill has a new highscore 39\n Fred has a new high", "end": 4406, "score": 0.8462801575660706, "start": 4402, "tag": "NAME", "value": "Bill" }, { "context": "attempt 3\n Bill has a new highscore 39\n Fred has a new highscore 47\n Fred is on attempt ", "end": 4441, "score": 0.9702512621879578, "start": 4437, "tag": "NAME", "value": "Fred" }, { "context": "score 39\n Fred has a new highscore 47\n Fred is on attempt 4\n John is on attempt 4\n ", "end": 4476, "score": 0.963681161403656, "start": 4472, "tag": "NAME", "value": "Fred" }, { "context": "new highscore 47\n Fred is on attempt 4\n John is on attempt 4\n Bill is on attempt 4\n ", "end": 4503, "score": 0.5128030776977539, "start": 4499, "tag": "NAME", "value": "John" }, { "context": " is on attempt 4\n Sally is on attempt 3\n Fred is on attempt 5\n Sally is on attempt 4\n ", "end": 4585, "score": 0.9249885082244873, "start": 4581, "tag": "NAME", "value": "Fred" }, { "context": " highscore 45]\n\n (<< scoreboard)\n\n => [{:name \"Bill\", :attempts 9, :score {:highest 45, :all (45 44 3", "end": 5067, "score": 0.9977630376815796, "start": 5063, "tag": "NAME", "value": "Bill" }, { "context": ", :all (45 44 36 9 24 25 39 18 3)}}\n {:name \"John\", :attempts 7, :score {:highest 49, :all (20 37 3", "end": 5156, "score": 0.9973081946372986, "start": 5152, "tag": "NAME", "value": "John" }, { "context": "st 49, :all (20 37 32 8 48 37 49)}}\n {:name \"Sally\", :attempts 8, :score {:highest 49, :all (1 48 7 ", "end": 5241, "score": 0.9997646808624268, "start": 5236, "tag": "NAME", "value": "Sally" }, { "context": "t 49, :all (1 48 7 12 43 0 39 49)}}\n {:name \"Fred\", :attempts 5, :score {:highest 47, :all (16 40 4", "end": 5326, "score": 0.9997937083244324, "start": 5322, "tag": "NAME", "value": "Fred" } ]
test/midje_doc/ova_scoreboard_example.clj
zcaudate-archive/ova
0
(ns midje-doc.ova-scoreboard-example (:require [ova.core :refer :all] [midje.sweet :refer :all])) [[:chapter {:title "Scoreboard Example"}]] [[:section {:title "Setup"}]] "#### data - a scoreboard is used to track player attempts, scores and high-scores" [[{:numbered false}]] (def scoreboard (ova [{:name "Bill" :attempts 0 :score {:all ()}} {:name "John" :attempts 0 :score {:all ()}} {:name "Sally" :attempts 0 :score {:all ()}} {:name "Fred" :attempts 0 :score {:all ()}}])) "#### update notifiers - one to print when an attempt has been made to play a game - one to print when there is a new highscore" [[{:numbered false}]] (add-elem-change-watch scoreboard :notify-attempt [:attempts] (fn [k o r p n] ;; key, ova, ref, previous, next (println (:name @r) "is on attempt" n))) (add-elem-change-watch scoreboard :notify-high-score [:score :highest] (fn [k o r p n] (println (:name @r) "has a new highscore: " n))) "#### score watch - When there is a score update, check if it is the highest score. If it is, then update the highest score to the current score" [[{:numbered false}]] (add-elem-change-watch scoreboard :update-high-score [:score :all] (fn [k o r p n] (let [hs [:score :highest] high (get-in @r hs) current (first n)] (if (and current (or (nil? high) (< high current))) (dosync (alter r assoc-in hs current)))))) "#### game simulation - `sim-game` and `sim-n-games` are used to update the scoreboard - the time to finish the game is randomised - the wait-time between subsequent games is randomised - the score they get is also randomised " [[{:numbered false}]] (defn sim-game [scoreboard name] ;; increment number of attempts (dosync (!> scoreboard [:name name] (update-in [:attempts] inc))) ;; simulate game playing time (Thread/sleep (rand-int 500)) ;; conj the newest score at the start of the list (dosync (!> scoreboard [:name name] (update-in [:score :all] conj (rand-int 50))))) (defn sim-n-games [scoreboard name n] (when (> n 0) (Thread/sleep (rand-int 500)) (sim-game scoreboard name) (recur scoreboard name (dec n)))) "#### multi-threading - for each player on the scoreboard, they each play a random number of games simultaneously - the same scoreboard is used to keep track of state " [[{:numbered false}]] (defn sim! [scoreboard] (let [names (map :name scoreboard)] (doseq [nm names] (future (sim-n-games scoreboard nm (+ 5 (rand-int 5))))))) [[:section {:title "Simulation"}]] "A sample simulation is show below:" [[{:numbered false}]] (comment (sim! scoreboard) => [Sally is on attempt 1 Bill is on attempt 1 Bill has a new highscore 35 Sally has a new highscore 40 John is on attempt 1 Fred is on attempt 1 Sally is on attempt 2 Fred has a new highscore 38 John has a new highscore 28 Bill is on attempt 2 Fred is on attempt 2 John is on attempt 2 John is on attempt 3 Bill is on attempt 3 Sally is on attempt 3 Bill has a new highscore 36 Bill is on attempt 4 John is on attempt 4 Fred is on attempt 3 Sally is on attempt 4 Fred is on attempt 4 John is on attempt 5 Sally is on attempt 5 Bill is on attempt 5 Bill has a new highscore 39 Bill is on attempt 6 John has a new highscore 30 Fred is on attempt 5 John is on attempt 6 Bill has a new highscore 41 John is on attempt 7 Bill is on attempt 7 Sally is on attempt 6 John is on attempt 8 Sally is on attempt 7 Bill is on attempt 8 John is on attempt 9 John has a new highscore 39 Sally is on attempt 8 Bill has a new highscore 45 Sally is on attempt 1 Fred is on attempt 1 John is on attempt 1 Bill is on attempt 1 Sally has a new highscore 49 John has a new highscore 49 Bill has a new highscore 3 Bill is on attempt 2 Fred has a new highscore 22 John is on attempt 2 Bill has a new highscore 18 Fred is on attempt 2 Bill is on attempt 3 Sally is on attempt 2 John is on attempt 3 Fred is on attempt 3 Bill has a new highscore 39 Fred has a new highscore 47 Fred is on attempt 4 John is on attempt 4 Bill is on attempt 4 Sally is on attempt 3 Fred is on attempt 5 Sally is on attempt 4 John is on attempt 5 Bill is on attempt 5 Sally is on attempt 5 Bill is on attempt 6 John is on attempt 6 Sally is on attempt 6 Sally is on attempt 7 John is on attempt 7 Bill is on attempt 7 Bill is on attempt 8 Sally is on attempt 8 Bill has a new highscore 44 Bill is on attempt 9 Bill has a new highscore 45] (<< scoreboard) => [{:name "Bill", :attempts 9, :score {:highest 45, :all (45 44 36 9 24 25 39 18 3)}} {:name "John", :attempts 7, :score {:highest 49, :all (20 37 32 8 48 37 49)}} {:name "Sally", :attempts 8, :score {:highest 49, :all (1 48 7 12 43 0 39 49)}} {:name "Fred", :attempts 5, :score {:highest 47, :all (16 40 47 15 22)}}])
61849
(ns midje-doc.ova-scoreboard-example (:require [ova.core :refer :all] [midje.sweet :refer :all])) [[:chapter {:title "Scoreboard Example"}]] [[:section {:title "Setup"}]] "#### data - a scoreboard is used to track player attempts, scores and high-scores" [[{:numbered false}]] (def scoreboard (ova [{:name "<NAME>" :attempts 0 :score {:all ()}} {:name "<NAME>" :attempts 0 :score {:all ()}} {:name "<NAME>" :attempts 0 :score {:all ()}} {:name "<NAME>" :attempts 0 :score {:all ()}}])) "#### update notifiers - one to print when an attempt has been made to play a game - one to print when there is a new highscore" [[{:numbered false}]] (add-elem-change-watch scoreboard :notify-attempt [:attempts] (fn [k o r p n] ;; key, ova, ref, previous, next (println (:name @r) "is on attempt" n))) (add-elem-change-watch scoreboard :notify-high-score [:score :highest] (fn [k o r p n] (println (:name @r) "has a new highscore: " n))) "#### score watch - When there is a score update, check if it is the highest score. If it is, then update the highest score to the current score" [[{:numbered false}]] (add-elem-change-watch scoreboard :update-high-score [:score :all] (fn [k o r p n] (let [hs [:score :highest] high (get-in @r hs) current (first n)] (if (and current (or (nil? high) (< high current))) (dosync (alter r assoc-in hs current)))))) "#### game simulation - `sim-game` and `sim-n-games` are used to update the scoreboard - the time to finish the game is randomised - the wait-time between subsequent games is randomised - the score they get is also randomised " [[{:numbered false}]] (defn sim-game [scoreboard name] ;; increment number of attempts (dosync (!> scoreboard [:name name] (update-in [:attempts] inc))) ;; simulate game playing time (Thread/sleep (rand-int 500)) ;; conj the newest score at the start of the list (dosync (!> scoreboard [:name name] (update-in [:score :all] conj (rand-int 50))))) (defn sim-n-games [scoreboard name n] (when (> n 0) (Thread/sleep (rand-int 500)) (sim-game scoreboard name) (recur scoreboard name (dec n)))) "#### multi-threading - for each player on the scoreboard, they each play a random number of games simultaneously - the same scoreboard is used to keep track of state " [[{:numbered false}]] (defn sim! [scoreboard] (let [names (map :name scoreboard)] (doseq [nm names] (future (sim-n-games scoreboard nm (+ 5 (rand-int 5))))))) [[:section {:title "Simulation"}]] "A sample simulation is show below:" [[{:numbered false}]] (comment (sim! scoreboard) => [<NAME> is on attempt 1 <NAME> is on attempt 1 <NAME> has a new highscore 35 <NAME> has a new highscore 40 <NAME> is on attempt 1 <NAME> is on attempt 1 <NAME> is on attempt 2 <NAME> has a new highscore 38 <NAME> has a new highscore 28 <NAME> is on attempt 2 <NAME> is on attempt 2 <NAME> is on attempt 2 <NAME> is on attempt 3 <NAME> is on attempt 3 <NAME> is on attempt 3 <NAME> has a new highscore 36 <NAME> is on attempt 4 <NAME> is on attempt 4 <NAME> is on attempt 3 <NAME> is on attempt 4 <NAME> is on attempt 4 <NAME> is on attempt 5 <NAME> is on attempt 5 <NAME> is on attempt 5 <NAME> has a new highscore 39 Bill is on attempt 6 <NAME> has a new highscore 30 <NAME> is on attempt 5 John is on attempt 6 <NAME> has a new highscore 41 John is on attempt 7 Bill is on attempt 7 Sally is on attempt 6 John is on attempt 8 Sally is on attempt 7 Bill is on attempt 8 John is on attempt 9 John has a new highscore 39 Sally is on attempt 8 Bill has a new highscore 45 Sally is on attempt 1 <NAME> is on attempt 1 <NAME> is on attempt 1 Bill is on attempt 1 Sally has a new highscore 49 John has a new highscore 49 Bill has a new highscore 3 Bill is on attempt 2 <NAME> has a new highscore 22 <NAME> is on attempt 2 <NAME> has a new highscore 18 <NAME> is on attempt 2 <NAME> is on attempt 3 Sally is on attempt 2 John is on attempt 3 <NAME> is on attempt 3 <NAME> has a new highscore 39 <NAME> has a new highscore 47 <NAME> is on attempt 4 <NAME> is on attempt 4 Bill is on attempt 4 Sally is on attempt 3 <NAME> is on attempt 5 Sally is on attempt 4 John is on attempt 5 Bill is on attempt 5 Sally is on attempt 5 Bill is on attempt 6 John is on attempt 6 Sally is on attempt 6 Sally is on attempt 7 John is on attempt 7 Bill is on attempt 7 Bill is on attempt 8 Sally is on attempt 8 Bill has a new highscore 44 Bill is on attempt 9 Bill has a new highscore 45] (<< scoreboard) => [{:name "<NAME>", :attempts 9, :score {:highest 45, :all (45 44 36 9 24 25 39 18 3)}} {:name "<NAME>", :attempts 7, :score {:highest 49, :all (20 37 32 8 48 37 49)}} {:name "<NAME>", :attempts 8, :score {:highest 49, :all (1 48 7 12 43 0 39 49)}} {:name "<NAME>", :attempts 5, :score {:highest 47, :all (16 40 47 15 22)}}])
true
(ns midje-doc.ova-scoreboard-example (:require [ova.core :refer :all] [midje.sweet :refer :all])) [[:chapter {:title "Scoreboard Example"}]] [[:section {:title "Setup"}]] "#### data - a scoreboard is used to track player attempts, scores and high-scores" [[{:numbered false}]] (def scoreboard (ova [{:name "PI:NAME:<NAME>END_PI" :attempts 0 :score {:all ()}} {:name "PI:NAME:<NAME>END_PI" :attempts 0 :score {:all ()}} {:name "PI:NAME:<NAME>END_PI" :attempts 0 :score {:all ()}} {:name "PI:NAME:<NAME>END_PI" :attempts 0 :score {:all ()}}])) "#### update notifiers - one to print when an attempt has been made to play a game - one to print when there is a new highscore" [[{:numbered false}]] (add-elem-change-watch scoreboard :notify-attempt [:attempts] (fn [k o r p n] ;; key, ova, ref, previous, next (println (:name @r) "is on attempt" n))) (add-elem-change-watch scoreboard :notify-high-score [:score :highest] (fn [k o r p n] (println (:name @r) "has a new highscore: " n))) "#### score watch - When there is a score update, check if it is the highest score. If it is, then update the highest score to the current score" [[{:numbered false}]] (add-elem-change-watch scoreboard :update-high-score [:score :all] (fn [k o r p n] (let [hs [:score :highest] high (get-in @r hs) current (first n)] (if (and current (or (nil? high) (< high current))) (dosync (alter r assoc-in hs current)))))) "#### game simulation - `sim-game` and `sim-n-games` are used to update the scoreboard - the time to finish the game is randomised - the wait-time between subsequent games is randomised - the score they get is also randomised " [[{:numbered false}]] (defn sim-game [scoreboard name] ;; increment number of attempts (dosync (!> scoreboard [:name name] (update-in [:attempts] inc))) ;; simulate game playing time (Thread/sleep (rand-int 500)) ;; conj the newest score at the start of the list (dosync (!> scoreboard [:name name] (update-in [:score :all] conj (rand-int 50))))) (defn sim-n-games [scoreboard name n] (when (> n 0) (Thread/sleep (rand-int 500)) (sim-game scoreboard name) (recur scoreboard name (dec n)))) "#### multi-threading - for each player on the scoreboard, they each play a random number of games simultaneously - the same scoreboard is used to keep track of state " [[{:numbered false}]] (defn sim! [scoreboard] (let [names (map :name scoreboard)] (doseq [nm names] (future (sim-n-games scoreboard nm (+ 5 (rand-int 5))))))) [[:section {:title "Simulation"}]] "A sample simulation is show below:" [[{:numbered false}]] (comment (sim! scoreboard) => [PI:NAME:<NAME>END_PI is on attempt 1 PI:NAME:<NAME>END_PI is on attempt 1 PI:NAME:<NAME>END_PI has a new highscore 35 PI:NAME:<NAME>END_PI has a new highscore 40 PI:NAME:<NAME>END_PI is on attempt 1 PI:NAME:<NAME>END_PI is on attempt 1 PI:NAME:<NAME>END_PI is on attempt 2 PI:NAME:<NAME>END_PI has a new highscore 38 PI:NAME:<NAME>END_PI has a new highscore 28 PI:NAME:<NAME>END_PI is on attempt 2 PI:NAME:<NAME>END_PI is on attempt 2 PI:NAME:<NAME>END_PI is on attempt 2 PI:NAME:<NAME>END_PI is on attempt 3 PI:NAME:<NAME>END_PI is on attempt 3 PI:NAME:<NAME>END_PI is on attempt 3 PI:NAME:<NAME>END_PI has a new highscore 36 PI:NAME:<NAME>END_PI is on attempt 4 PI:NAME:<NAME>END_PI is on attempt 4 PI:NAME:<NAME>END_PI is on attempt 3 PI:NAME:<NAME>END_PI is on attempt 4 PI:NAME:<NAME>END_PI is on attempt 4 PI:NAME:<NAME>END_PI is on attempt 5 PI:NAME:<NAME>END_PI is on attempt 5 PI:NAME:<NAME>END_PI is on attempt 5 PI:NAME:<NAME>END_PI has a new highscore 39 Bill is on attempt 6 PI:NAME:<NAME>END_PI has a new highscore 30 PI:NAME:<NAME>END_PI is on attempt 5 John is on attempt 6 PI:NAME:<NAME>END_PI has a new highscore 41 John is on attempt 7 Bill is on attempt 7 Sally is on attempt 6 John is on attempt 8 Sally is on attempt 7 Bill is on attempt 8 John is on attempt 9 John has a new highscore 39 Sally is on attempt 8 Bill has a new highscore 45 Sally is on attempt 1 PI:NAME:<NAME>END_PI is on attempt 1 PI:NAME:<NAME>END_PI is on attempt 1 Bill is on attempt 1 Sally has a new highscore 49 John has a new highscore 49 Bill has a new highscore 3 Bill is on attempt 2 PI:NAME:<NAME>END_PI has a new highscore 22 PI:NAME:<NAME>END_PI is on attempt 2 PI:NAME:<NAME>END_PI has a new highscore 18 PI:NAME:<NAME>END_PI is on attempt 2 PI:NAME:<NAME>END_PI is on attempt 3 Sally is on attempt 2 John is on attempt 3 PI:NAME:<NAME>END_PI is on attempt 3 PI:NAME:<NAME>END_PI has a new highscore 39 PI:NAME:<NAME>END_PI has a new highscore 47 PI:NAME:<NAME>END_PI is on attempt 4 PI:NAME:<NAME>END_PI is on attempt 4 Bill is on attempt 4 Sally is on attempt 3 PI:NAME:<NAME>END_PI is on attempt 5 Sally is on attempt 4 John is on attempt 5 Bill is on attempt 5 Sally is on attempt 5 Bill is on attempt 6 John is on attempt 6 Sally is on attempt 6 Sally is on attempt 7 John is on attempt 7 Bill is on attempt 7 Bill is on attempt 8 Sally is on attempt 8 Bill has a new highscore 44 Bill is on attempt 9 Bill has a new highscore 45] (<< scoreboard) => [{:name "PI:NAME:<NAME>END_PI", :attempts 9, :score {:highest 45, :all (45 44 36 9 24 25 39 18 3)}} {:name "PI:NAME:<NAME>END_PI", :attempts 7, :score {:highest 49, :all (20 37 32 8 48 37 49)}} {:name "PI:NAME:<NAME>END_PI", :attempts 8, :score {:highest 49, :all (1 48 7 12 43 0 39 49)}} {:name "PI:NAME:<NAME>END_PI", :attempts 5, :score {:highest 47, :all (16 40 47 15 22)}}])
[ { "context": " :list/people [{:person/id 1, :person/name \"Sally\", :person/age 32}\n {:pers", "end": 396, "score": 0.9997459650039673, "start": 391, "tag": "NAME", "value": "Sally" }, { "context": " {:person/id 2, :person/name \"Joe\", :person/age 22}]},\n :enemies {:list/id :enemies", "end": 472, "score": 0.9997568130493164, "start": 469, "tag": "NAME", "value": "Joe" }, { "context": " :list/people [{:person/id 3, :person/name \"Fred\", :person/age 11}\n {:pers", "end": 616, "score": 0.9997693300247192, "start": 612, "tag": "NAME", "value": "Fred" }, { "context": " {:person/id 4, :person/name \"Bobby\", :person/age 55}]}}\n\n", "end": 694, "score": 0.9997425079345703, "start": 689, "tag": "NAME", "value": "Bobby" } ]
clj/ex/articles_fulcro/docs/4_9_1_db->tree.cljs
mertnuhoglu/study
1
=> (def state (com.fulcrologic.fulcro.application/current-state app.application/app)) #'cljs.user/state => (def query (com.fulcrologic.fulcro.components/get-query app.ui/Root)) #'cljs.user/query => (com.fulcrologic.fulcro.algorithms.denormalize/db->tree query state state) {:friends {:list/id :friends, :list/label "Friends", :list/people [{:person/id 1, :person/name "Sally", :person/age 32} {:person/id 2, :person/name "Joe", :person/age 22}]}, :enemies {:list/id :enemies, :list/label "Enemies", :list/people [{:person/id 3, :person/name "Fred", :person/age 11} {:person/id 4, :person/name "Bobby", :person/age 55}]}}
47807
=> (def state (com.fulcrologic.fulcro.application/current-state app.application/app)) #'cljs.user/state => (def query (com.fulcrologic.fulcro.components/get-query app.ui/Root)) #'cljs.user/query => (com.fulcrologic.fulcro.algorithms.denormalize/db->tree query state state) {:friends {:list/id :friends, :list/label "Friends", :list/people [{:person/id 1, :person/name "<NAME>", :person/age 32} {:person/id 2, :person/name "<NAME>", :person/age 22}]}, :enemies {:list/id :enemies, :list/label "Enemies", :list/people [{:person/id 3, :person/name "<NAME>", :person/age 11} {:person/id 4, :person/name "<NAME>", :person/age 55}]}}
true
=> (def state (com.fulcrologic.fulcro.application/current-state app.application/app)) #'cljs.user/state => (def query (com.fulcrologic.fulcro.components/get-query app.ui/Root)) #'cljs.user/query => (com.fulcrologic.fulcro.algorithms.denormalize/db->tree query state state) {:friends {:list/id :friends, :list/label "Friends", :list/people [{:person/id 1, :person/name "PI:NAME:<NAME>END_PI", :person/age 32} {:person/id 2, :person/name "PI:NAME:<NAME>END_PI", :person/age 22}]}, :enemies {:list/id :enemies, :list/label "Enemies", :list/people [{:person/id 3, :person/name "PI:NAME:<NAME>END_PI", :person/age 11} {:person/id 4, :person/name "PI:NAME:<NAME>END_PI", :person/age 55}]}}
[ { "context": "id3.basics-util :as util]\n ))\n\n(def cursor-key :b02-add-attrs-to-elem)\n\n(def height 100)\n(def width 100)\n\n", "end": 176, "score": 0.6246013641357422, "start": 168, "tag": "KEY", "value": "b02-add-" }, { "context": "cs-util :as util]\n ))\n\n(def cursor-key :b02-add-attrs-to-elem)\n\n(def height 100)\n(def width 100)\n\n(defn", "end": 181, "score": 0.4777020215988159, "start": 176, "tag": "PASSWORD", "value": "attrs" }, { "context": "il :as util]\n ))\n\n(def cursor-key :b02-add-attrs-to-elem)\n\n(def height 100)\n(def width 100)\n\n(defn ", "end": 181, "score": 0.5458946824073792, "start": 181, "tag": "KEY", "value": "" }, { "context": "l :as util]\n ))\n\n(def cursor-key :b02-add-attrs-to-elem)\n\n(def height 100)\n(def width 100)\n\n(defn ex", "end": 184, "score": 0.5067306756973267, "start": 182, "tag": "PASSWORD", "value": "to" }, { "context": ":as util]\n ))\n\n(def cursor-key :b02-add-attrs-to-elem)\n\n(def height 100)\n(def width 100)\n\n(defn exa", "end": 184, "score": 0.49645960330963135, "start": 184, "tag": "KEY", "value": "" }, { "context": "as util]\n ))\n\n(def cursor-key :b02-add-attrs-to-elem)\n\n(def height 100)\n(def width 100)\n\n(defn example", "end": 189, "score": 0.48303693532943726, "start": 185, "tag": "PASSWORD", "value": "elem" } ]
src/basics/rid3/b02_add_attrs_to_elem.cljs
ryanechternacht/rid3
153
(ns rid3.b02-add-attrs-to-elem (:require [reagent.core :as reagent] [rid3.core :as rid3 :refer [rid3->]] [rid3.basics-util :as util] )) (def cursor-key :b02-add-attrs-to-elem) (def height 100) (def width 100) (defn example [app-state] (let [viz-ratom (reagent/cursor app-state [cursor-key])] (fn [app-state] [:div [:h4 "2) Add attribute to the rect (fill)"] [util/link-source (name cursor-key)] [rid3/viz {:id "b02" :ratom viz-ratom :svg {:did-mount (fn [node ratom] (rid3-> node {:height height :width width}))} :pieces [{:kind :elem :class "some-element" :tag "rect" :did-mount (fn [node ratom] (rid3-> node {:x 0 :y 0 :height height :width width ;; You can add arbitrary attributes to ;; your element :fill "lightgrey"}))} ] }]])))
104938
(ns rid3.b02-add-attrs-to-elem (:require [reagent.core :as reagent] [rid3.core :as rid3 :refer [rid3->]] [rid3.basics-util :as util] )) (def cursor-key :<KEY> <PASSWORD> <KEY>-<PASSWORD> <KEY>-<PASSWORD>) (def height 100) (def width 100) (defn example [app-state] (let [viz-ratom (reagent/cursor app-state [cursor-key])] (fn [app-state] [:div [:h4 "2) Add attribute to the rect (fill)"] [util/link-source (name cursor-key)] [rid3/viz {:id "b02" :ratom viz-ratom :svg {:did-mount (fn [node ratom] (rid3-> node {:height height :width width}))} :pieces [{:kind :elem :class "some-element" :tag "rect" :did-mount (fn [node ratom] (rid3-> node {:x 0 :y 0 :height height :width width ;; You can add arbitrary attributes to ;; your element :fill "lightgrey"}))} ] }]])))
true
(ns rid3.b02-add-attrs-to-elem (:require [reagent.core :as reagent] [rid3.core :as rid3 :refer [rid3->]] [rid3.basics-util :as util] )) (def cursor-key :PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI-PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI-PI:PASSWORD:<PASSWORD>END_PI) (def height 100) (def width 100) (defn example [app-state] (let [viz-ratom (reagent/cursor app-state [cursor-key])] (fn [app-state] [:div [:h4 "2) Add attribute to the rect (fill)"] [util/link-source (name cursor-key)] [rid3/viz {:id "b02" :ratom viz-ratom :svg {:did-mount (fn [node ratom] (rid3-> node {:height height :width width}))} :pieces [{:kind :elem :class "some-element" :tag "rect" :did-mount (fn [node ratom] (rid3-> node {:x 0 :y 0 :height height :width width ;; You can add arbitrary attributes to ;; your element :fill "lightgrey"}))} ] }]])))
[ { "context": " \"{\\\"refresh_token\\\": \\\"test-token\\\"\"\n #(o/exchange", "end": 1167, "score": 0.5124881267547607, "start": 1163, "tag": "PASSWORD", "value": "test" }, { "context": " \"{\\\"refresh_token\\\": \\\"test-token\\\"\"\n #(o/exchange-auth-", "end": 1173, "score": 0.6265339851379395, "start": 1168, "tag": "KEY", "value": "token" }, { "context": " \"{\\\"access_token\\\": \\\"test-token\\\"\"\n #(o/refresh-token ", "end": 1792, "score": 0.8130808472633362, "start": 1782, "tag": "KEY", "value": "test-token" } ]
test/full/contacts_api_client/oauth_test.clj
fullcontact/contacts-api-clojure
1
(ns full.contacts-api-client.oauth-test (:use midje.sweet) (:require [full.contacts-api-client.oauth :as o] [full.contacts-api-client.util :as u] [ring.util.codec :refer [form-encode]] [full.contacts-api-client.test-helper :as h])) (facts "about oauth" (fact "get authorization url is correct" (let [client-id (h/str-random) state (h/str-random) redirect-uri (h/str-random) scope (h/str-random) expected (str u/base-url "/oauth/authorize?" (form-encode {:scope scope :client_id client-id :redirect_uri redirect-uri :state state})) actual (o/get-authorize-url :client-id client-id :scope scope :redirect-uri redirect-uri :state state)] (= expected actual) => true)) (fact "exchange-auth-code well-formed request" (let [client-id (h/str-random) client-secret (h/str-random) code (h/str-random) redirect-uri (h/str-random) result (h/with-mock-http "{\"refresh_token\": \"test-token\"" #(o/exchange-auth-code :client-id client-id :client-secret client-secret :code code :redirect-uri redirect-uri))] (h/verify result :params (list "/oauth.exchangeAuthCode" :form {:client_id client-id :client_secret client-secret :redirect_uri redirect-uri :code code})) => true)) (fact "refresh-token well-formed request" (let [client-id (h/str-random) client-secret (h/str-random) refresh-token (h/str-random) result (h/with-mock-http "{\"access_token\": \"test-token\"" #(o/refresh-token :client-id client-id :client-secret client-secret :refresh-token refresh-token))] (h/verify result :params (list "/oauth.refreshToken" :form {:client_id client-id :client_secret client-secret :refresh_token refresh-token})) => true)) (fact "verify-access-token well-formed request" (let [access-token (h/str-random) result (h/with-mock-http "{}" #(o/verify-access-token access-token))] (h/verify result :params (list "/oauth.verifyAccessToken" :form {:access_token access-token})) => true)))
43036
(ns full.contacts-api-client.oauth-test (:use midje.sweet) (:require [full.contacts-api-client.oauth :as o] [full.contacts-api-client.util :as u] [ring.util.codec :refer [form-encode]] [full.contacts-api-client.test-helper :as h])) (facts "about oauth" (fact "get authorization url is correct" (let [client-id (h/str-random) state (h/str-random) redirect-uri (h/str-random) scope (h/str-random) expected (str u/base-url "/oauth/authorize?" (form-encode {:scope scope :client_id client-id :redirect_uri redirect-uri :state state})) actual (o/get-authorize-url :client-id client-id :scope scope :redirect-uri redirect-uri :state state)] (= expected actual) => true)) (fact "exchange-auth-code well-formed request" (let [client-id (h/str-random) client-secret (h/str-random) code (h/str-random) redirect-uri (h/str-random) result (h/with-mock-http "{\"refresh_token\": \"<PASSWORD>-<KEY>\"" #(o/exchange-auth-code :client-id client-id :client-secret client-secret :code code :redirect-uri redirect-uri))] (h/verify result :params (list "/oauth.exchangeAuthCode" :form {:client_id client-id :client_secret client-secret :redirect_uri redirect-uri :code code})) => true)) (fact "refresh-token well-formed request" (let [client-id (h/str-random) client-secret (h/str-random) refresh-token (h/str-random) result (h/with-mock-http "{\"access_token\": \"<KEY>\"" #(o/refresh-token :client-id client-id :client-secret client-secret :refresh-token refresh-token))] (h/verify result :params (list "/oauth.refreshToken" :form {:client_id client-id :client_secret client-secret :refresh_token refresh-token})) => true)) (fact "verify-access-token well-formed request" (let [access-token (h/str-random) result (h/with-mock-http "{}" #(o/verify-access-token access-token))] (h/verify result :params (list "/oauth.verifyAccessToken" :form {:access_token access-token})) => true)))
true
(ns full.contacts-api-client.oauth-test (:use midje.sweet) (:require [full.contacts-api-client.oauth :as o] [full.contacts-api-client.util :as u] [ring.util.codec :refer [form-encode]] [full.contacts-api-client.test-helper :as h])) (facts "about oauth" (fact "get authorization url is correct" (let [client-id (h/str-random) state (h/str-random) redirect-uri (h/str-random) scope (h/str-random) expected (str u/base-url "/oauth/authorize?" (form-encode {:scope scope :client_id client-id :redirect_uri redirect-uri :state state})) actual (o/get-authorize-url :client-id client-id :scope scope :redirect-uri redirect-uri :state state)] (= expected actual) => true)) (fact "exchange-auth-code well-formed request" (let [client-id (h/str-random) client-secret (h/str-random) code (h/str-random) redirect-uri (h/str-random) result (h/with-mock-http "{\"refresh_token\": \"PI:PASSWORD:<PASSWORD>END_PI-PI:KEY:<KEY>END_PI\"" #(o/exchange-auth-code :client-id client-id :client-secret client-secret :code code :redirect-uri redirect-uri))] (h/verify result :params (list "/oauth.exchangeAuthCode" :form {:client_id client-id :client_secret client-secret :redirect_uri redirect-uri :code code})) => true)) (fact "refresh-token well-formed request" (let [client-id (h/str-random) client-secret (h/str-random) refresh-token (h/str-random) result (h/with-mock-http "{\"access_token\": \"PI:KEY:<KEY>END_PI\"" #(o/refresh-token :client-id client-id :client-secret client-secret :refresh-token refresh-token))] (h/verify result :params (list "/oauth.refreshToken" :form {:client_id client-id :client_secret client-secret :refresh_token refresh-token})) => true)) (fact "verify-access-token well-formed request" (let [access-token (h/str-random) result (h/with-mock-http "{}" #(o/verify-access-token access-token))] (h/verify result :params (list "/oauth.verifyAccessToken" :form {:access_token access-token})) => true)))
[ { "context": "er type and returns the key and value\n i.e. {:a '123'} -> {:a 123}\"\n [[k v]]\n (let [mapd-types (into", "end": 2141, "score": 0.8620372414588928, "start": 2138, "tag": "KEY", "value": "123" }, { "context": "urns the key and value\n i.e. {:a '123'} -> {:a 123}\"\n [[k v]]\n (let [mapd-types (into {} trip-type", "end": 2154, "score": 0.666467547416687, "start": 2153, "tag": "KEY", "value": "3" } ]
src/taxidata/input_impl_file.clj
brycemcd/nyctaxi-data-processing
0
(ns taxidata.input-impl-file "Imports taxi trips from a file. Files are expected to be UTF-8 encoded and records are expected to be separated by new lines (\r\n) and values are expected to be comma separated files" (:require [clj-time.format :as dttm_f] [taxidata.core :refer :all] )) ; NOTE: if/when another input type is created, these functions and trip-types ; should be moved to some sort of utility namespace. I found it to be more ; convenient to just leave them here for now and avoid having lots of windows ; open at the same time searching for these (defn to_int [value] (Integer. value)) (defn to_dec [value] (Double. value)) (defn to_dttm [value] (dttm_f/parse (dttm_f/formatters :mysql) value)) ; NOTE: mysql formatter is YYYYMMDD HH:mm::ss ; the functions that casts these values as the proper type (def trip-types "column names and primitives expected of the data in an ordered data structure" [[:vendor_id to_int] [:tpep_pickup_datetime to_dttm] [:tpep_dropoff_datetime to_dttm] [:passenger_count to_int] [:trip_distance to_dec] [:pickup_longitude to_dec] [:pickup_latitude to_dec] [:ratecode_id to_int] [:store_and_fwd_flag identity] [:dropoff_longitude to_dec] [:dropoff_latitude to_dec] [:payment_type to_int] [:fare_amount to_dec] [:extra to_dec] [:mta_tax to_dec] [:tip_amount to_dec] [:tolls_amount to_dec] [:improvement_surcharge to_dec] [:total_amount to_dec]]) (def trip-header "Just the keys of trip-types. Should be the same as a header in a data file" (map first trip-types)) (defrecord TaxiTrip [vendor_id tpep_pickup_datetime tpep_dropoff_datetime passenger_count trip_distance pickup_longitude pickup_latitude ratecode_id store_and_fwd_flag dropoff_longitude dropoff_latitude payment_type fare_amount extra mta_tax tip_amount tolls_amount improvement_surcharge total_amount]) (defn- split-row "splits a csv row on the comma" [row] (clojure.string/split row #",")) (defn- cast-keypair "converts a key's value into the proper type and returns the key and value i.e. {:a '123'} -> {:a 123}" [[k v]] (let [mapd-types (into {} trip-types)] {k ((k mapd-types) v)})) (defn- cast-row [mapd-row] (into {} (map cast-keypair mapd-row))) (defn is-file-header "if raw line matches the known header value of VendorID, then this line is header line" [line] ; TODO: add test (re-matches #"VendorID.*" (clojure.string/trim-newline line))) (defn create-trip "creates a TaxiTrip from a raw line of data in the file. If line passed in is a header line, it should be discarded" [line] ; convert the raw row into a map, then TaxiTrip with the wrong types cast (if-not (is-file-header line) (->> line split-row (zipmap trip-header) cast-row map->TaxiTrip))) ; NOTE: feels like I want a transducer here (defn create-trips-from-file "Buffers a file, creates TaxiTrips from each row in the file (default line separator as used in clojure.java.io/reader), calls a function on the row and then a callback on the result of the rowfx callbackfx = a function to call after the tripfx has been called on the TaxiTrip" [file callbackfx] (with-open [rdr (clojure.java.io/reader file)] (doseq [line (line-seq rdr)] (if-let [not-header (create-trip line)] (callbackfx not-header)))))
123046
(ns taxidata.input-impl-file "Imports taxi trips from a file. Files are expected to be UTF-8 encoded and records are expected to be separated by new lines (\r\n) and values are expected to be comma separated files" (:require [clj-time.format :as dttm_f] [taxidata.core :refer :all] )) ; NOTE: if/when another input type is created, these functions and trip-types ; should be moved to some sort of utility namespace. I found it to be more ; convenient to just leave them here for now and avoid having lots of windows ; open at the same time searching for these (defn to_int [value] (Integer. value)) (defn to_dec [value] (Double. value)) (defn to_dttm [value] (dttm_f/parse (dttm_f/formatters :mysql) value)) ; NOTE: mysql formatter is YYYYMMDD HH:mm::ss ; the functions that casts these values as the proper type (def trip-types "column names and primitives expected of the data in an ordered data structure" [[:vendor_id to_int] [:tpep_pickup_datetime to_dttm] [:tpep_dropoff_datetime to_dttm] [:passenger_count to_int] [:trip_distance to_dec] [:pickup_longitude to_dec] [:pickup_latitude to_dec] [:ratecode_id to_int] [:store_and_fwd_flag identity] [:dropoff_longitude to_dec] [:dropoff_latitude to_dec] [:payment_type to_int] [:fare_amount to_dec] [:extra to_dec] [:mta_tax to_dec] [:tip_amount to_dec] [:tolls_amount to_dec] [:improvement_surcharge to_dec] [:total_amount to_dec]]) (def trip-header "Just the keys of trip-types. Should be the same as a header in a data file" (map first trip-types)) (defrecord TaxiTrip [vendor_id tpep_pickup_datetime tpep_dropoff_datetime passenger_count trip_distance pickup_longitude pickup_latitude ratecode_id store_and_fwd_flag dropoff_longitude dropoff_latitude payment_type fare_amount extra mta_tax tip_amount tolls_amount improvement_surcharge total_amount]) (defn- split-row "splits a csv row on the comma" [row] (clojure.string/split row #",")) (defn- cast-keypair "converts a key's value into the proper type and returns the key and value i.e. {:a '<KEY>'} -> {:a 12<KEY>}" [[k v]] (let [mapd-types (into {} trip-types)] {k ((k mapd-types) v)})) (defn- cast-row [mapd-row] (into {} (map cast-keypair mapd-row))) (defn is-file-header "if raw line matches the known header value of VendorID, then this line is header line" [line] ; TODO: add test (re-matches #"VendorID.*" (clojure.string/trim-newline line))) (defn create-trip "creates a TaxiTrip from a raw line of data in the file. If line passed in is a header line, it should be discarded" [line] ; convert the raw row into a map, then TaxiTrip with the wrong types cast (if-not (is-file-header line) (->> line split-row (zipmap trip-header) cast-row map->TaxiTrip))) ; NOTE: feels like I want a transducer here (defn create-trips-from-file "Buffers a file, creates TaxiTrips from each row in the file (default line separator as used in clojure.java.io/reader), calls a function on the row and then a callback on the result of the rowfx callbackfx = a function to call after the tripfx has been called on the TaxiTrip" [file callbackfx] (with-open [rdr (clojure.java.io/reader file)] (doseq [line (line-seq rdr)] (if-let [not-header (create-trip line)] (callbackfx not-header)))))
true
(ns taxidata.input-impl-file "Imports taxi trips from a file. Files are expected to be UTF-8 encoded and records are expected to be separated by new lines (\r\n) and values are expected to be comma separated files" (:require [clj-time.format :as dttm_f] [taxidata.core :refer :all] )) ; NOTE: if/when another input type is created, these functions and trip-types ; should be moved to some sort of utility namespace. I found it to be more ; convenient to just leave them here for now and avoid having lots of windows ; open at the same time searching for these (defn to_int [value] (Integer. value)) (defn to_dec [value] (Double. value)) (defn to_dttm [value] (dttm_f/parse (dttm_f/formatters :mysql) value)) ; NOTE: mysql formatter is YYYYMMDD HH:mm::ss ; the functions that casts these values as the proper type (def trip-types "column names and primitives expected of the data in an ordered data structure" [[:vendor_id to_int] [:tpep_pickup_datetime to_dttm] [:tpep_dropoff_datetime to_dttm] [:passenger_count to_int] [:trip_distance to_dec] [:pickup_longitude to_dec] [:pickup_latitude to_dec] [:ratecode_id to_int] [:store_and_fwd_flag identity] [:dropoff_longitude to_dec] [:dropoff_latitude to_dec] [:payment_type to_int] [:fare_amount to_dec] [:extra to_dec] [:mta_tax to_dec] [:tip_amount to_dec] [:tolls_amount to_dec] [:improvement_surcharge to_dec] [:total_amount to_dec]]) (def trip-header "Just the keys of trip-types. Should be the same as a header in a data file" (map first trip-types)) (defrecord TaxiTrip [vendor_id tpep_pickup_datetime tpep_dropoff_datetime passenger_count trip_distance pickup_longitude pickup_latitude ratecode_id store_and_fwd_flag dropoff_longitude dropoff_latitude payment_type fare_amount extra mta_tax tip_amount tolls_amount improvement_surcharge total_amount]) (defn- split-row "splits a csv row on the comma" [row] (clojure.string/split row #",")) (defn- cast-keypair "converts a key's value into the proper type and returns the key and value i.e. {:a 'PI:KEY:<KEY>END_PI'} -> {:a 12PI:KEY:<KEY>END_PI}" [[k v]] (let [mapd-types (into {} trip-types)] {k ((k mapd-types) v)})) (defn- cast-row [mapd-row] (into {} (map cast-keypair mapd-row))) (defn is-file-header "if raw line matches the known header value of VendorID, then this line is header line" [line] ; TODO: add test (re-matches #"VendorID.*" (clojure.string/trim-newline line))) (defn create-trip "creates a TaxiTrip from a raw line of data in the file. If line passed in is a header line, it should be discarded" [line] ; convert the raw row into a map, then TaxiTrip with the wrong types cast (if-not (is-file-header line) (->> line split-row (zipmap trip-header) cast-row map->TaxiTrip))) ; NOTE: feels like I want a transducer here (defn create-trips-from-file "Buffers a file, creates TaxiTrips from each row in the file (default line separator as used in clojure.java.io/reader), calls a function on the row and then a callback on the result of the rowfx callbackfx = a function to call after the tripfx has been called on the TaxiTrip" [file callbackfx] (with-open [rdr (clojure.java.io/reader file)] (doseq [line (line-seq rdr)] (if-let [not-header (create-trip line)] (callbackfx not-header)))))
[ { "context": "chronous HTTP Client for Clojure\n\n; Copyright 2011 Hubert Iwaniuk\n;\n; Licensed under the Apache License, Version 2.", "end": 89, "score": 0.9998723864555359, "start": 75, "tag": "NAME", "value": "Hubert Iwaniuk" }, { "context": " \"Asynchronous HTTP Client - Clojure\"\n {:author \"Hubert Iwaniuk\"}\n (:refer-clojure :exclude [await])\n (:use [ht", "end": 722, "score": 0.9998831748962402, "start": 708, "tag": "NAME", "value": "Hubert Iwaniuk" }, { "context": "r - user name to be used\n :password - password to be used\n :realm - realm name to authenticate in", "end": 2326, "score": 0.9390148520469666, "start": 2307, "tag": "PASSWORD", "value": "password to be used" }, { "context": ":user - user name to be used\n :password - password to be used\n :realm - realm name to authenticate in\n ", "end": 6745, "score": 0.9798339605331421, "start": 6726, "tag": "PASSWORD", "value": "password to be used" } ]
src/clj/http/async/client.clj
pelerkejepit/async
0
;; ## client.clj -- Asynchronous HTTP Client for Clojure ; Copyright 2011 Hubert Iwaniuk ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns http.async.client "Asynchronous HTTP Client - Clojure" {:author "Hubert Iwaniuk"} (:refer-clojure :exclude [await]) (:use [http.async.client request headers util]) (:import (java.io ByteArrayOutputStream) (java.util.concurrent LinkedBlockingQueue) (com.ning.http.client AsyncHttpClient AsyncHttpClientConfig$Builder) (com.ning.http.client.providers.netty NettyAsyncHttpProviderConfig))) ;; # Client Lifecycle (defn create-client "Creates new Async Http Client. Arguments: - :compression-enabled :: enable HTTP compression - :connection-timeout :: connections timeout in ms - :follow-redirects :: enable following HTTP redirects - :idle-in-pool-timeout :: idle connection in pool timeout in ms - :keep-alive :: enable HTTP keep alive, enabled by default - :max-conns-per-host :: max number of polled connections per host - :max-conns-total :: max number of total connections held open by client - :max-redirects :: max nuber of redirects to follow - :proxy :: map with proxy configuration to be used :host - proxy host :port - proxy port :protocol - (optional) protocol to communicate with proxy, :http (default, if you provide no value) and :https are allowed :user - (optional) user name to use for proxy authentication, has to be provided with :password :password - (optional) password to use for proxy authentication, has to be provided with :user - :auth :: map with authentication to be used :type - either :basic or :digest :user - user name to be used :password - password to be used :realm - realm name to authenticate in :preemptive - assume authentication is required - :request-timeout :: request timeout in ms - :user-agent :: User-Agent branding string - :async-connect :: Execute connect asynchronously - :executor-service :: provide your own executor service for callbacks to be executed on - :ssl-context :: provide your own SSL Context" {:tag AsyncHttpClient} [& {:keys [compression-enabled connection-timeout follow-redirects idle-in-pool-timeout keep-alive max-conns-per-host max-conns-total max-redirects proxy auth request-timeout user-agent async-connect executor-service ssl-context]}] (AsyncHttpClient. (.build (let [b (AsyncHttpClientConfig$Builder.)] (when-not (nil? compression-enabled) (.setCompressionEnabled b compression-enabled)) (when connection-timeout (.setConnectionTimeoutInMs b connection-timeout)) (when-not (nil? follow-redirects) (.setFollowRedirects b follow-redirects)) (when idle-in-pool-timeout (.setIdleConnectionInPoolTimeoutInMs b idle-in-pool-timeout)) (when-not (nil? keep-alive) (.setAllowPoolingConnection b keep-alive)) (when max-conns-per-host (.setMaximumConnectionsPerHost b max-conns-per-host)) (when max-conns-total (.setMaximumConnectionsTotal b max-conns-total)) (when max-redirects (.setMaximumNumberOfRedirects b max-redirects)) (when async-connect (let [provider-config (doto (NettyAsyncHttpProviderConfig.) (.removeProperty NettyAsyncHttpProviderConfig/USE_BLOCKING_IO) (.addProperty NettyAsyncHttpProviderConfig/EXECUTE_ASYNC_CONNECT true))] (.setAsyncHttpClientProviderConfig b provider-config))) (when executor-service (.setExecutorService b executor-service)) (when proxy (set-proxy proxy b)) (when auth (set-realm auth b)) (when request-timeout (.setRequestTimeoutInMs b request-timeout)) (.setUserAgent b (if user-agent user-agent *user-agent*)) (when-not (nil? ssl-context) (.setSSLContext b ssl-context)) b)))) (defmacro ^{:private true} gen-methods [& methods] (list* 'do (map (fn [method#] (let [fn-name (symbol (.toUpperCase (name method#))) fn-doc (str "Sends asynchronously HTTP " fn-name " request to url. Returns a map: - :id - unique ID of request - :status - promise that once status is received is delivered, contains lazy map of: - :code - response code - :msg - response message - :protocol - protocol with version - :major - major version of protocol - :minor - minor version of protocol - :headers - promise that once headers are received is delivered, contains lazy map of: - :server - header names are keyworded, values stay not changed - :body - body of response, depends on request type, might be ByteArrayOutputStream or lazy sequence, use conveniece methods to extract it, like string - :done - promise that is delivered once receiving response has finished - :error - promise that is delivered if requesting resource failed, once delivered will contain Throwable. Arguments: - client - client created via create-client - url - URL to request - options - keyworded arguments: :query - map of query parameters, if value is vector than multiple values will be send as n=v1&n=v2 :headers - map of headers :body - body :cookies - cookies to send :proxy - map with proxy configuration to be used :host - proxy host :port - proxy port :protocol - (optional) protocol to communicate with proxy, :http (default, if you provide no value) and :https are allowed :user - (optional) user name to use for proxy authentication, has to be provided with :password :password - (optional) password to use for proxy authentication, has to be provided with :user :auth - map with authentication to be used :type - either :basic or :digest :user - user name to be used :password - password to be used :realm - realm name to authenticate in :timeout - request timeout in ms")] `(defn ~fn-name ~fn-doc [~'client #^String ~'url & {:as ~'options}] (apply execute-request ~'client (apply prepare-request ~method# ~'url (apply concat ~'options)) (apply concat *default-callbacks*))))) methods))) (gen-methods :get :post :put :delete :head :options) (defn request-stream "Consumes stream from given url. method - HTTP method to be used (:get, :post, ...) url - URL to set request to body-part-callback - callback that takes status (ref {}) of request and received body part as vector of bytes options - are optional and can contain :headers, :param, and :query (see prepare-request)." [client method #^String url body-part-callback & {:as options}] (apply execute-request client (apply prepare-request method url (apply concat options)) (apply concat (merge *default-callbacks* {:part body-part-callback})))) (defn stream-seq "Creates potentially infinite lazy sequence of Http Stream." [client method #^String url & {:as options}] (let [que (LinkedBlockingQueue.)] (apply execute-request client (apply prepare-request method url (apply concat options)) (apply concat (merge *default-callbacks* {:part (fn [_ baos] (.put que baos) [que :continue]) :completed (fn [_] (.put que ::done)) :error (fn [_ t] (.put que ::done) t)}))))) (defn failed? "Checks if request failed." [resp] (realized? (:error resp))) (defn done? "Checks if request is finished already (response receiving finished)." [resp] (realized? (:done resp))) (defn- safe-get [k r] (let [p (k r)] (if (or (realized? p) (not (or (failed? r) (done? r)))) @p))) (defn await "Waits for response processing to be finished. Returns same response." [response] (safe-get :done response) response) (defn headers "Gets headers. If headers have not yet been delivered and request hasn't failed waits for headers." [resp] (safe-get :headers resp)) (defn body "Gets body. If body have not yet been delivered and request hasn't failed waits for body." [resp] (let [b (safe-get :body resp)] (if (instance? LinkedBlockingQueue b) ((fn gen-next [] (lazy-seq (let [v (.take b)] (when-not (= ::done v) (cons v (gen-next))))))) b))) (defn- convert [#^ByteArrayOutputStream baos enc] (.toString baos enc)) (defn- convert-body [body enc] (if (seq? body) (map #(convert % enc) body) (convert body enc))) (def ^:private ^:dynamic *default-encoding* "UTF-8") (defn string "Converts response to string. Or converts body taking encoding from response." ([resp] (when-let [body (body resp)] (convert-body body (or (get-encoding (headers resp)) *default-encoding*)))) ([headers body] (convert-body body (or (get-encoding headers) *default-encoding*)))) (defn cookies "Gets cookies from response." [resp] (create-cookies (headers resp))) (defn status "Gets status if status was delivered." [resp] (safe-get :status resp)) (defn error "Returns Throwable if request processing failed." [resp] (if (failed? resp) @(:error resp))) (defn cancelled? "Checks if response has been cancelled." [resp] (when-let [f (:cancelled? (meta resp))] (f))) (defn cancel "Cancels response." [resp] (when-let [f (:cancel (meta resp))] (f))) (defn close "Closes client." ([client] (.close client)))
75505
;; ## client.clj -- Asynchronous HTTP Client for Clojure ; Copyright 2011 <NAME> ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns http.async.client "Asynchronous HTTP Client - Clojure" {:author "<NAME>"} (:refer-clojure :exclude [await]) (:use [http.async.client request headers util]) (:import (java.io ByteArrayOutputStream) (java.util.concurrent LinkedBlockingQueue) (com.ning.http.client AsyncHttpClient AsyncHttpClientConfig$Builder) (com.ning.http.client.providers.netty NettyAsyncHttpProviderConfig))) ;; # Client Lifecycle (defn create-client "Creates new Async Http Client. Arguments: - :compression-enabled :: enable HTTP compression - :connection-timeout :: connections timeout in ms - :follow-redirects :: enable following HTTP redirects - :idle-in-pool-timeout :: idle connection in pool timeout in ms - :keep-alive :: enable HTTP keep alive, enabled by default - :max-conns-per-host :: max number of polled connections per host - :max-conns-total :: max number of total connections held open by client - :max-redirects :: max nuber of redirects to follow - :proxy :: map with proxy configuration to be used :host - proxy host :port - proxy port :protocol - (optional) protocol to communicate with proxy, :http (default, if you provide no value) and :https are allowed :user - (optional) user name to use for proxy authentication, has to be provided with :password :password - (optional) password to use for proxy authentication, has to be provided with :user - :auth :: map with authentication to be used :type - either :basic or :digest :user - user name to be used :password - <PASSWORD> :realm - realm name to authenticate in :preemptive - assume authentication is required - :request-timeout :: request timeout in ms - :user-agent :: User-Agent branding string - :async-connect :: Execute connect asynchronously - :executor-service :: provide your own executor service for callbacks to be executed on - :ssl-context :: provide your own SSL Context" {:tag AsyncHttpClient} [& {:keys [compression-enabled connection-timeout follow-redirects idle-in-pool-timeout keep-alive max-conns-per-host max-conns-total max-redirects proxy auth request-timeout user-agent async-connect executor-service ssl-context]}] (AsyncHttpClient. (.build (let [b (AsyncHttpClientConfig$Builder.)] (when-not (nil? compression-enabled) (.setCompressionEnabled b compression-enabled)) (when connection-timeout (.setConnectionTimeoutInMs b connection-timeout)) (when-not (nil? follow-redirects) (.setFollowRedirects b follow-redirects)) (when idle-in-pool-timeout (.setIdleConnectionInPoolTimeoutInMs b idle-in-pool-timeout)) (when-not (nil? keep-alive) (.setAllowPoolingConnection b keep-alive)) (when max-conns-per-host (.setMaximumConnectionsPerHost b max-conns-per-host)) (when max-conns-total (.setMaximumConnectionsTotal b max-conns-total)) (when max-redirects (.setMaximumNumberOfRedirects b max-redirects)) (when async-connect (let [provider-config (doto (NettyAsyncHttpProviderConfig.) (.removeProperty NettyAsyncHttpProviderConfig/USE_BLOCKING_IO) (.addProperty NettyAsyncHttpProviderConfig/EXECUTE_ASYNC_CONNECT true))] (.setAsyncHttpClientProviderConfig b provider-config))) (when executor-service (.setExecutorService b executor-service)) (when proxy (set-proxy proxy b)) (when auth (set-realm auth b)) (when request-timeout (.setRequestTimeoutInMs b request-timeout)) (.setUserAgent b (if user-agent user-agent *user-agent*)) (when-not (nil? ssl-context) (.setSSLContext b ssl-context)) b)))) (defmacro ^{:private true} gen-methods [& methods] (list* 'do (map (fn [method#] (let [fn-name (symbol (.toUpperCase (name method#))) fn-doc (str "Sends asynchronously HTTP " fn-name " request to url. Returns a map: - :id - unique ID of request - :status - promise that once status is received is delivered, contains lazy map of: - :code - response code - :msg - response message - :protocol - protocol with version - :major - major version of protocol - :minor - minor version of protocol - :headers - promise that once headers are received is delivered, contains lazy map of: - :server - header names are keyworded, values stay not changed - :body - body of response, depends on request type, might be ByteArrayOutputStream or lazy sequence, use conveniece methods to extract it, like string - :done - promise that is delivered once receiving response has finished - :error - promise that is delivered if requesting resource failed, once delivered will contain Throwable. Arguments: - client - client created via create-client - url - URL to request - options - keyworded arguments: :query - map of query parameters, if value is vector than multiple values will be send as n=v1&n=v2 :headers - map of headers :body - body :cookies - cookies to send :proxy - map with proxy configuration to be used :host - proxy host :port - proxy port :protocol - (optional) protocol to communicate with proxy, :http (default, if you provide no value) and :https are allowed :user - (optional) user name to use for proxy authentication, has to be provided with :password :password - (optional) password to use for proxy authentication, has to be provided with :user :auth - map with authentication to be used :type - either :basic or :digest :user - user name to be used :password - <PASSWORD> :realm - realm name to authenticate in :timeout - request timeout in ms")] `(defn ~fn-name ~fn-doc [~'client #^String ~'url & {:as ~'options}] (apply execute-request ~'client (apply prepare-request ~method# ~'url (apply concat ~'options)) (apply concat *default-callbacks*))))) methods))) (gen-methods :get :post :put :delete :head :options) (defn request-stream "Consumes stream from given url. method - HTTP method to be used (:get, :post, ...) url - URL to set request to body-part-callback - callback that takes status (ref {}) of request and received body part as vector of bytes options - are optional and can contain :headers, :param, and :query (see prepare-request)." [client method #^String url body-part-callback & {:as options}] (apply execute-request client (apply prepare-request method url (apply concat options)) (apply concat (merge *default-callbacks* {:part body-part-callback})))) (defn stream-seq "Creates potentially infinite lazy sequence of Http Stream." [client method #^String url & {:as options}] (let [que (LinkedBlockingQueue.)] (apply execute-request client (apply prepare-request method url (apply concat options)) (apply concat (merge *default-callbacks* {:part (fn [_ baos] (.put que baos) [que :continue]) :completed (fn [_] (.put que ::done)) :error (fn [_ t] (.put que ::done) t)}))))) (defn failed? "Checks if request failed." [resp] (realized? (:error resp))) (defn done? "Checks if request is finished already (response receiving finished)." [resp] (realized? (:done resp))) (defn- safe-get [k r] (let [p (k r)] (if (or (realized? p) (not (or (failed? r) (done? r)))) @p))) (defn await "Waits for response processing to be finished. Returns same response." [response] (safe-get :done response) response) (defn headers "Gets headers. If headers have not yet been delivered and request hasn't failed waits for headers." [resp] (safe-get :headers resp)) (defn body "Gets body. If body have not yet been delivered and request hasn't failed waits for body." [resp] (let [b (safe-get :body resp)] (if (instance? LinkedBlockingQueue b) ((fn gen-next [] (lazy-seq (let [v (.take b)] (when-not (= ::done v) (cons v (gen-next))))))) b))) (defn- convert [#^ByteArrayOutputStream baos enc] (.toString baos enc)) (defn- convert-body [body enc] (if (seq? body) (map #(convert % enc) body) (convert body enc))) (def ^:private ^:dynamic *default-encoding* "UTF-8") (defn string "Converts response to string. Or converts body taking encoding from response." ([resp] (when-let [body (body resp)] (convert-body body (or (get-encoding (headers resp)) *default-encoding*)))) ([headers body] (convert-body body (or (get-encoding headers) *default-encoding*)))) (defn cookies "Gets cookies from response." [resp] (create-cookies (headers resp))) (defn status "Gets status if status was delivered." [resp] (safe-get :status resp)) (defn error "Returns Throwable if request processing failed." [resp] (if (failed? resp) @(:error resp))) (defn cancelled? "Checks if response has been cancelled." [resp] (when-let [f (:cancelled? (meta resp))] (f))) (defn cancel "Cancels response." [resp] (when-let [f (:cancel (meta resp))] (f))) (defn close "Closes client." ([client] (.close client)))
true
;; ## client.clj -- Asynchronous HTTP Client for Clojure ; Copyright 2011 PI:NAME:<NAME>END_PI ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns http.async.client "Asynchronous HTTP Client - Clojure" {:author "PI:NAME:<NAME>END_PI"} (:refer-clojure :exclude [await]) (:use [http.async.client request headers util]) (:import (java.io ByteArrayOutputStream) (java.util.concurrent LinkedBlockingQueue) (com.ning.http.client AsyncHttpClient AsyncHttpClientConfig$Builder) (com.ning.http.client.providers.netty NettyAsyncHttpProviderConfig))) ;; # Client Lifecycle (defn create-client "Creates new Async Http Client. Arguments: - :compression-enabled :: enable HTTP compression - :connection-timeout :: connections timeout in ms - :follow-redirects :: enable following HTTP redirects - :idle-in-pool-timeout :: idle connection in pool timeout in ms - :keep-alive :: enable HTTP keep alive, enabled by default - :max-conns-per-host :: max number of polled connections per host - :max-conns-total :: max number of total connections held open by client - :max-redirects :: max nuber of redirects to follow - :proxy :: map with proxy configuration to be used :host - proxy host :port - proxy port :protocol - (optional) protocol to communicate with proxy, :http (default, if you provide no value) and :https are allowed :user - (optional) user name to use for proxy authentication, has to be provided with :password :password - (optional) password to use for proxy authentication, has to be provided with :user - :auth :: map with authentication to be used :type - either :basic or :digest :user - user name to be used :password - PI:PASSWORD:<PASSWORD>END_PI :realm - realm name to authenticate in :preemptive - assume authentication is required - :request-timeout :: request timeout in ms - :user-agent :: User-Agent branding string - :async-connect :: Execute connect asynchronously - :executor-service :: provide your own executor service for callbacks to be executed on - :ssl-context :: provide your own SSL Context" {:tag AsyncHttpClient} [& {:keys [compression-enabled connection-timeout follow-redirects idle-in-pool-timeout keep-alive max-conns-per-host max-conns-total max-redirects proxy auth request-timeout user-agent async-connect executor-service ssl-context]}] (AsyncHttpClient. (.build (let [b (AsyncHttpClientConfig$Builder.)] (when-not (nil? compression-enabled) (.setCompressionEnabled b compression-enabled)) (when connection-timeout (.setConnectionTimeoutInMs b connection-timeout)) (when-not (nil? follow-redirects) (.setFollowRedirects b follow-redirects)) (when idle-in-pool-timeout (.setIdleConnectionInPoolTimeoutInMs b idle-in-pool-timeout)) (when-not (nil? keep-alive) (.setAllowPoolingConnection b keep-alive)) (when max-conns-per-host (.setMaximumConnectionsPerHost b max-conns-per-host)) (when max-conns-total (.setMaximumConnectionsTotal b max-conns-total)) (when max-redirects (.setMaximumNumberOfRedirects b max-redirects)) (when async-connect (let [provider-config (doto (NettyAsyncHttpProviderConfig.) (.removeProperty NettyAsyncHttpProviderConfig/USE_BLOCKING_IO) (.addProperty NettyAsyncHttpProviderConfig/EXECUTE_ASYNC_CONNECT true))] (.setAsyncHttpClientProviderConfig b provider-config))) (when executor-service (.setExecutorService b executor-service)) (when proxy (set-proxy proxy b)) (when auth (set-realm auth b)) (when request-timeout (.setRequestTimeoutInMs b request-timeout)) (.setUserAgent b (if user-agent user-agent *user-agent*)) (when-not (nil? ssl-context) (.setSSLContext b ssl-context)) b)))) (defmacro ^{:private true} gen-methods [& methods] (list* 'do (map (fn [method#] (let [fn-name (symbol (.toUpperCase (name method#))) fn-doc (str "Sends asynchronously HTTP " fn-name " request to url. Returns a map: - :id - unique ID of request - :status - promise that once status is received is delivered, contains lazy map of: - :code - response code - :msg - response message - :protocol - protocol with version - :major - major version of protocol - :minor - minor version of protocol - :headers - promise that once headers are received is delivered, contains lazy map of: - :server - header names are keyworded, values stay not changed - :body - body of response, depends on request type, might be ByteArrayOutputStream or lazy sequence, use conveniece methods to extract it, like string - :done - promise that is delivered once receiving response has finished - :error - promise that is delivered if requesting resource failed, once delivered will contain Throwable. Arguments: - client - client created via create-client - url - URL to request - options - keyworded arguments: :query - map of query parameters, if value is vector than multiple values will be send as n=v1&n=v2 :headers - map of headers :body - body :cookies - cookies to send :proxy - map with proxy configuration to be used :host - proxy host :port - proxy port :protocol - (optional) protocol to communicate with proxy, :http (default, if you provide no value) and :https are allowed :user - (optional) user name to use for proxy authentication, has to be provided with :password :password - (optional) password to use for proxy authentication, has to be provided with :user :auth - map with authentication to be used :type - either :basic or :digest :user - user name to be used :password - PI:PASSWORD:<PASSWORD>END_PI :realm - realm name to authenticate in :timeout - request timeout in ms")] `(defn ~fn-name ~fn-doc [~'client #^String ~'url & {:as ~'options}] (apply execute-request ~'client (apply prepare-request ~method# ~'url (apply concat ~'options)) (apply concat *default-callbacks*))))) methods))) (gen-methods :get :post :put :delete :head :options) (defn request-stream "Consumes stream from given url. method - HTTP method to be used (:get, :post, ...) url - URL to set request to body-part-callback - callback that takes status (ref {}) of request and received body part as vector of bytes options - are optional and can contain :headers, :param, and :query (see prepare-request)." [client method #^String url body-part-callback & {:as options}] (apply execute-request client (apply prepare-request method url (apply concat options)) (apply concat (merge *default-callbacks* {:part body-part-callback})))) (defn stream-seq "Creates potentially infinite lazy sequence of Http Stream." [client method #^String url & {:as options}] (let [que (LinkedBlockingQueue.)] (apply execute-request client (apply prepare-request method url (apply concat options)) (apply concat (merge *default-callbacks* {:part (fn [_ baos] (.put que baos) [que :continue]) :completed (fn [_] (.put que ::done)) :error (fn [_ t] (.put que ::done) t)}))))) (defn failed? "Checks if request failed." [resp] (realized? (:error resp))) (defn done? "Checks if request is finished already (response receiving finished)." [resp] (realized? (:done resp))) (defn- safe-get [k r] (let [p (k r)] (if (or (realized? p) (not (or (failed? r) (done? r)))) @p))) (defn await "Waits for response processing to be finished. Returns same response." [response] (safe-get :done response) response) (defn headers "Gets headers. If headers have not yet been delivered and request hasn't failed waits for headers." [resp] (safe-get :headers resp)) (defn body "Gets body. If body have not yet been delivered and request hasn't failed waits for body." [resp] (let [b (safe-get :body resp)] (if (instance? LinkedBlockingQueue b) ((fn gen-next [] (lazy-seq (let [v (.take b)] (when-not (= ::done v) (cons v (gen-next))))))) b))) (defn- convert [#^ByteArrayOutputStream baos enc] (.toString baos enc)) (defn- convert-body [body enc] (if (seq? body) (map #(convert % enc) body) (convert body enc))) (def ^:private ^:dynamic *default-encoding* "UTF-8") (defn string "Converts response to string. Or converts body taking encoding from response." ([resp] (when-let [body (body resp)] (convert-body body (or (get-encoding (headers resp)) *default-encoding*)))) ([headers body] (convert-body body (or (get-encoding headers) *default-encoding*)))) (defn cookies "Gets cookies from response." [resp] (create-cookies (headers resp))) (defn status "Gets status if status was delivered." [resp] (safe-get :status resp)) (defn error "Returns Throwable if request processing failed." [resp] (if (failed? resp) @(:error resp))) (defn cancelled? "Checks if response has been cancelled." [resp] (when-let [f (:cancelled? (meta resp))] (f))) (defn cancel "Cancels response." [resp] (when-let [f (:cancel (meta resp))] (f))) (defn close "Closes client." ([client] (.close client)))
[ { "context": "Logic: Satisfiability\n\n; Copyright (c) 2016 - 2017 Burkhardt Renz, THM. All rights reserved.\n; The use and distribu", "end": 106, "score": 0.9998744130134583, "start": 92, "tag": "NAME", "value": "Burkhardt Renz" } ]
src/lwb/ltl/sat.clj
esb-lwb/lwb
22
; lwb Logic WorkBench -- Linear Temporal Logic: Satisfiability ; Copyright (c) 2016 - 2017 Burkhardt Renz, THM. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php). ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. (ns lwb.ltl.sat (:require [lwb.ltl :refer :all] [lwb.ltl.buechi :as ba] [clojure.spec.alpha :as s] [clojure.set :as set])) ;; # Satisfiability in linear temporal logic ;; The basic steps are: ;; 1. Generate a Büchi automaton for the formula of LTL that has the property ;; that the infinite words accepted by the automaton i.e. the language of the ;; automaton are exactly the set of computations satisfying the formula. ;; 2. If the Büchi automaton is not empty, the formula is satisfiable, and we ;; construct a model, i.e. a Kripke structure for the formula. ;; #### Helper functions (defn node-label "Label for a node with `id` with edge from `from` in the Kripke structure for the automaton `ba`." [ba from id] (let [edge (ba/ids->edge ba from id) guard (:guard edge)] (if (set? guard) (set/select symbol? guard) #{}))) (defn- node-key "Keyword for a node with `id`" [id] (keyword (str "s_" id))) ;; #### Transformation of Büchi automaton into a corresponding Kripke structure ;; The idea: ;; 1. We determine a path from the init node of the automaton to a cycle that contains ;; an accepting state ;; 2. Then we use this path to construct a Kripke structure. (defn ba->ks "A Kripke structure is generated from a Büchi automaton as a model for the formula the automaton accepts." [ba] (let [literals (reduce set/union (filter set? (map :guard (:edges ba)))) atoms (set (map #(if (list? %) (second %) %) literals)) pathv (first (ba/paths ba)) nodes (mapv #(hash-map (node-key %2) (node-label ba %1 %2)) pathv (rest pathv)) nodes' (apply merge-with set/union nodes) initial (node-key (second pathv)) pathv' (if (ba/accepting? ba (second pathv)) (conj pathv (second pathv)) pathv) edges (set (map #(vector (node-key %1) (node-key %2)) (rest pathv') (rest (rest pathv')))) acc-nodes (distinct (filter #(ba/accepting? ba %) pathv)) acc-loops (set (map #(vector (node-key %) (node-key %)) (filter #(ba/loop? ba %) acc-nodes))) edges' (set/union edges acc-loops)] (hash-map :atoms atoms :nodes nodes' :initial initial :edges edges'))) ;; ## Satisfiability and validity for LTL formulas (defn sat "Gives a model for `phi` if the formula is satisfiable, nil otherwise." [phi] (let [ba (ba/ba phi)] (when (seq (:nodes ba)) (ba->ks ba)))) (s/fdef sat :args (s/cat :phi wff?) :ret (s/or :as/model nil?)) (defn sat? "Is `phi` satisfiable?" [phi] (if (nil? (sat phi)) false true)) (s/fdef sat? :args (s/cat :phi wff?) :ret boolean?) (defn valid? "Is `phi` valid?" [phi] (not (sat? (list 'not phi)))) (s/fdef valid? :args (s/cat :phi wff?) :ret boolean?)
81158
; lwb Logic WorkBench -- Linear Temporal Logic: Satisfiability ; Copyright (c) 2016 - 2017 <NAME>, THM. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php). ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. (ns lwb.ltl.sat (:require [lwb.ltl :refer :all] [lwb.ltl.buechi :as ba] [clojure.spec.alpha :as s] [clojure.set :as set])) ;; # Satisfiability in linear temporal logic ;; The basic steps are: ;; 1. Generate a Büchi automaton for the formula of LTL that has the property ;; that the infinite words accepted by the automaton i.e. the language of the ;; automaton are exactly the set of computations satisfying the formula. ;; 2. If the Büchi automaton is not empty, the formula is satisfiable, and we ;; construct a model, i.e. a Kripke structure for the formula. ;; #### Helper functions (defn node-label "Label for a node with `id` with edge from `from` in the Kripke structure for the automaton `ba`." [ba from id] (let [edge (ba/ids->edge ba from id) guard (:guard edge)] (if (set? guard) (set/select symbol? guard) #{}))) (defn- node-key "Keyword for a node with `id`" [id] (keyword (str "s_" id))) ;; #### Transformation of Büchi automaton into a corresponding Kripke structure ;; The idea: ;; 1. We determine a path from the init node of the automaton to a cycle that contains ;; an accepting state ;; 2. Then we use this path to construct a Kripke structure. (defn ba->ks "A Kripke structure is generated from a Büchi automaton as a model for the formula the automaton accepts." [ba] (let [literals (reduce set/union (filter set? (map :guard (:edges ba)))) atoms (set (map #(if (list? %) (second %) %) literals)) pathv (first (ba/paths ba)) nodes (mapv #(hash-map (node-key %2) (node-label ba %1 %2)) pathv (rest pathv)) nodes' (apply merge-with set/union nodes) initial (node-key (second pathv)) pathv' (if (ba/accepting? ba (second pathv)) (conj pathv (second pathv)) pathv) edges (set (map #(vector (node-key %1) (node-key %2)) (rest pathv') (rest (rest pathv')))) acc-nodes (distinct (filter #(ba/accepting? ba %) pathv)) acc-loops (set (map #(vector (node-key %) (node-key %)) (filter #(ba/loop? ba %) acc-nodes))) edges' (set/union edges acc-loops)] (hash-map :atoms atoms :nodes nodes' :initial initial :edges edges'))) ;; ## Satisfiability and validity for LTL formulas (defn sat "Gives a model for `phi` if the formula is satisfiable, nil otherwise." [phi] (let [ba (ba/ba phi)] (when (seq (:nodes ba)) (ba->ks ba)))) (s/fdef sat :args (s/cat :phi wff?) :ret (s/or :as/model nil?)) (defn sat? "Is `phi` satisfiable?" [phi] (if (nil? (sat phi)) false true)) (s/fdef sat? :args (s/cat :phi wff?) :ret boolean?) (defn valid? "Is `phi` valid?" [phi] (not (sat? (list 'not phi)))) (s/fdef valid? :args (s/cat :phi wff?) :ret boolean?)
true
; lwb Logic WorkBench -- Linear Temporal Logic: Satisfiability ; Copyright (c) 2016 - 2017 PI:NAME:<NAME>END_PI, THM. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php). ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. (ns lwb.ltl.sat (:require [lwb.ltl :refer :all] [lwb.ltl.buechi :as ba] [clojure.spec.alpha :as s] [clojure.set :as set])) ;; # Satisfiability in linear temporal logic ;; The basic steps are: ;; 1. Generate a Büchi automaton for the formula of LTL that has the property ;; that the infinite words accepted by the automaton i.e. the language of the ;; automaton are exactly the set of computations satisfying the formula. ;; 2. If the Büchi automaton is not empty, the formula is satisfiable, and we ;; construct a model, i.e. a Kripke structure for the formula. ;; #### Helper functions (defn node-label "Label for a node with `id` with edge from `from` in the Kripke structure for the automaton `ba`." [ba from id] (let [edge (ba/ids->edge ba from id) guard (:guard edge)] (if (set? guard) (set/select symbol? guard) #{}))) (defn- node-key "Keyword for a node with `id`" [id] (keyword (str "s_" id))) ;; #### Transformation of Büchi automaton into a corresponding Kripke structure ;; The idea: ;; 1. We determine a path from the init node of the automaton to a cycle that contains ;; an accepting state ;; 2. Then we use this path to construct a Kripke structure. (defn ba->ks "A Kripke structure is generated from a Büchi automaton as a model for the formula the automaton accepts." [ba] (let [literals (reduce set/union (filter set? (map :guard (:edges ba)))) atoms (set (map #(if (list? %) (second %) %) literals)) pathv (first (ba/paths ba)) nodes (mapv #(hash-map (node-key %2) (node-label ba %1 %2)) pathv (rest pathv)) nodes' (apply merge-with set/union nodes) initial (node-key (second pathv)) pathv' (if (ba/accepting? ba (second pathv)) (conj pathv (second pathv)) pathv) edges (set (map #(vector (node-key %1) (node-key %2)) (rest pathv') (rest (rest pathv')))) acc-nodes (distinct (filter #(ba/accepting? ba %) pathv)) acc-loops (set (map #(vector (node-key %) (node-key %)) (filter #(ba/loop? ba %) acc-nodes))) edges' (set/union edges acc-loops)] (hash-map :atoms atoms :nodes nodes' :initial initial :edges edges'))) ;; ## Satisfiability and validity for LTL formulas (defn sat "Gives a model for `phi` if the formula is satisfiable, nil otherwise." [phi] (let [ba (ba/ba phi)] (when (seq (:nodes ba)) (ba->ks ba)))) (s/fdef sat :args (s/cat :phi wff?) :ret (s/or :as/model nil?)) (defn sat? "Is `phi` satisfiable?" [phi] (if (nil? (sat phi)) false true)) (s/fdef sat? :args (s/cat :phi wff?) :ret boolean?) (defn valid? "Is `phi` valid?" [phi] (not (sat? (list 'not phi)))) (s/fdef valid? :args (s/cat :phi wff?) :ret boolean?)
[ { "context": ";; Copyright (c) 2010 Tom Crayford,\n;;\n;; Redistribution and use in source and binar", "end": 34, "score": 0.9998221397399902, "start": 22, "tag": "NAME", "value": "Tom Crayford" } ]
src/clojure_refactoring/support/paths.clj
tcrayford/clojure-refactoring
6
;; Copyright (c) 2010 Tom Crayford, ;; ;; 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 clojure-refactoring.support.paths (:import java.io.File)) ;;the below stolen from slime (defn- clean-windows-path [#^String path] ;; Decode file URI encoding and remove an opening slash from ;; /c:/program%20files/... in jar file URLs and file resources. (or (and (.startsWith (System/getProperty "os.name") "Windows") (second (re-matches #"^/([a-zA-Z]:/.*)$" path))) path)) (defn- slime-file-resource [#^java.net.URL resource] (clean-windows-path (.getFile resource))) (defn- slime-find-resource [#^String file] (let [resource (.getResource (clojure.lang.RT/baseLoader) file)] (slime-file-resource resource))) (defn slime-find-file [#^String file] (if (.isAbsolute (File. file)) file (slime-find-resource file))) (defn extract-filename [namespace] (str (.replaceAll (.replaceAll (name namespace) "-" "_") "\\." "/") ".clj")) (defn force-ns-name [namespace] (if (symbol? namespace) namespace (ns-name namespace))) (defn filename-from-ns [namespace] (-> namespace force-ns-name extract-filename slime-find-file))
49312
;; Copyright (c) 2010 <NAME>, ;; ;; 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 clojure-refactoring.support.paths (:import java.io.File)) ;;the below stolen from slime (defn- clean-windows-path [#^String path] ;; Decode file URI encoding and remove an opening slash from ;; /c:/program%20files/... in jar file URLs and file resources. (or (and (.startsWith (System/getProperty "os.name") "Windows") (second (re-matches #"^/([a-zA-Z]:/.*)$" path))) path)) (defn- slime-file-resource [#^java.net.URL resource] (clean-windows-path (.getFile resource))) (defn- slime-find-resource [#^String file] (let [resource (.getResource (clojure.lang.RT/baseLoader) file)] (slime-file-resource resource))) (defn slime-find-file [#^String file] (if (.isAbsolute (File. file)) file (slime-find-resource file))) (defn extract-filename [namespace] (str (.replaceAll (.replaceAll (name namespace) "-" "_") "\\." "/") ".clj")) (defn force-ns-name [namespace] (if (symbol? namespace) namespace (ns-name namespace))) (defn filename-from-ns [namespace] (-> namespace force-ns-name extract-filename slime-find-file))
true
;; Copyright (c) 2010 PI:NAME:<NAME>END_PI, ;; ;; 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 clojure-refactoring.support.paths (:import java.io.File)) ;;the below stolen from slime (defn- clean-windows-path [#^String path] ;; Decode file URI encoding and remove an opening slash from ;; /c:/program%20files/... in jar file URLs and file resources. (or (and (.startsWith (System/getProperty "os.name") "Windows") (second (re-matches #"^/([a-zA-Z]:/.*)$" path))) path)) (defn- slime-file-resource [#^java.net.URL resource] (clean-windows-path (.getFile resource))) (defn- slime-find-resource [#^String file] (let [resource (.getResource (clojure.lang.RT/baseLoader) file)] (slime-file-resource resource))) (defn slime-find-file [#^String file] (if (.isAbsolute (File. file)) file (slime-find-resource file))) (defn extract-filename [namespace] (str (.replaceAll (.replaceAll (name namespace) "-" "_") "\\." "/") ".clj")) (defn force-ns-name [namespace] (if (symbol? namespace) namespace (ns-name namespace))) (defn filename-from-ns [namespace] (-> namespace force-ns-name extract-filename slime-find-file))
[ { "context": "ser2-token (echo-util/login (system/context) \"user2\" [user2-group-id])\n _ (echo-util/ungrant ", "end": 1895, "score": 0.5067812204360962, "start": 1894, "tag": "USERNAME", "value": "2" }, { "context": "1})\n {:token \"mock-echo-system-token\"})\n _ (index/wait-until-indexed)\n ", "end": 5680, "score": 0.9774346351623535, "start": 5658, "tag": "PASSWORD", "value": "mock-echo-system-token" } ]
system-int-test/test/cmr/system_int_test/ingest/subscription_processing_test.clj
jaybarra/Common-Metadata-Repository
0
(ns cmr.system-int-test.ingest.subscription-processing-test "CMR subscription processing tests." (:require [clojure.test :refer :all] [cmr.ingest.services.jobs :as jobs] [cmr.mock-echo.client.echo-util :as echo-util] [cmr.system-int-test.data2.core :as data-core] [cmr.system-int-test.data2.granule :as data-granule] [cmr.system-int-test.data2.umm-spec-collection :as data-umm-c] [cmr.system-int-test.system :as system] [cmr.system-int-test.utils.index-util :as index] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.subscription-util :as subscription-util] [cmr.transmit.access-control :as access-control] [cmr.transmit.metadata-db :as mdb2])) (use-fixtures :each (join-fixtures [(ingest/reset-fixture {"provguid1" "PROV1" "provguid2" "PROV2" "provguid3" "PROV3"}) (subscription-util/grant-all-subscription-fixture {"provguid1" "PROV1" "provguid2" "PROV2"} [:read :update] [:read :update]) (subscription-util/grant-all-subscription-fixture {"provguid1" "PROV3"} [:read] [:read :update])])) (defn- trigger-process-subscriptions "Sets up process-subscriptions arguments. Calls process-subscriptions, returns granule concept-ids." [] (let [subscriptions (->> (mdb2/find-concepts (system/context) {:latest true} :subscription) (remove :deleted) (mapv #(select-keys % [:concept-id :extra-fields :metadata])))] (#'jobs/process-subscriptions (system/context) subscriptions))) (deftest ^:oracle subscription-email-processing-time-constraint-test (system/only-with-real-database (let [user2-group-id (echo-util/get-or-create-group (system/context) "group2") _user2-token (echo-util/login (system/context) "user2" [user2-group-id]) _ (echo-util/ungrant (system/context) (-> (access-control/search-for-acls (system/context) {:provider "PROV1" :identity-type "catalog_item"} {:token "mock-echo-system-token"}) :items first :concept_id)) _ (echo-util/grant (system/context) [{:group_id user2-group-id :permissions [:read]}] :catalog_item_identity {:provider_id "PROV1" :name "Provider collection/granule ACL" :collection_applicable true :granule_applicable true :granule_identifier {:access_value {:include_undefined_value true :min_value 1 :max_value 50}}}) ;; Setup collection coll1 (data-core/ingest-umm-spec-collection "PROV1" (data-umm-c/collection {:ShortName "coll1" :EntryTitle "entry-title1"}) {:token "mock-echo-system-token"}) _ (index/wait-until-indexed) ;; Setup subscriptions _ (subscription-util/ingest-subscription (subscription-util/make-subscription-concept {:Name "test_sub_prov1" :SubscriberId "user2" :CollectionConceptId (:concept-id coll1) :Query "provider=PROV1"}) {:token "mock-echo-system-token"})] (index/wait-until-indexed) (testing "First query executed does not have a last-notified-at and looks back 24 hours" (let [gran1 (data-core/ingest "PROV1" (data-granule/granule-with-umm-spec-collection coll1 (:concept-id coll1) {:granule-ur "Granule1" :access-value 1}) {:token "mock-echo-system-token"}) _ (index/wait-until-indexed) results (->> (trigger-process-subscriptions) (map #(nth % 1)) flatten (map :concept-id))] (is (= (:concept-id gran1) (first results))))) ;; force eval of lazy seq (is (not= nil (count (trigger-process-subscriptions)))) (testing "Second run finds only collections created since the last notification" (let [gran2 (data-core/ingest "PROV1" (data-granule/granule-with-umm-spec-collection coll1 (:concept-id coll1) {:granule-ur "Granule2" :access-value 1}) {:token "mock-echo-system-token"}) _ (index/wait-until-indexed) response (->> (trigger-process-subscriptions) (map #(nth % 1)) flatten (map :concept-id))] (is (= [(:concept-id gran2)] response)))))))
30056
(ns cmr.system-int-test.ingest.subscription-processing-test "CMR subscription processing tests." (:require [clojure.test :refer :all] [cmr.ingest.services.jobs :as jobs] [cmr.mock-echo.client.echo-util :as echo-util] [cmr.system-int-test.data2.core :as data-core] [cmr.system-int-test.data2.granule :as data-granule] [cmr.system-int-test.data2.umm-spec-collection :as data-umm-c] [cmr.system-int-test.system :as system] [cmr.system-int-test.utils.index-util :as index] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.subscription-util :as subscription-util] [cmr.transmit.access-control :as access-control] [cmr.transmit.metadata-db :as mdb2])) (use-fixtures :each (join-fixtures [(ingest/reset-fixture {"provguid1" "PROV1" "provguid2" "PROV2" "provguid3" "PROV3"}) (subscription-util/grant-all-subscription-fixture {"provguid1" "PROV1" "provguid2" "PROV2"} [:read :update] [:read :update]) (subscription-util/grant-all-subscription-fixture {"provguid1" "PROV3"} [:read] [:read :update])])) (defn- trigger-process-subscriptions "Sets up process-subscriptions arguments. Calls process-subscriptions, returns granule concept-ids." [] (let [subscriptions (->> (mdb2/find-concepts (system/context) {:latest true} :subscription) (remove :deleted) (mapv #(select-keys % [:concept-id :extra-fields :metadata])))] (#'jobs/process-subscriptions (system/context) subscriptions))) (deftest ^:oracle subscription-email-processing-time-constraint-test (system/only-with-real-database (let [user2-group-id (echo-util/get-or-create-group (system/context) "group2") _user2-token (echo-util/login (system/context) "user2" [user2-group-id]) _ (echo-util/ungrant (system/context) (-> (access-control/search-for-acls (system/context) {:provider "PROV1" :identity-type "catalog_item"} {:token "mock-echo-system-token"}) :items first :concept_id)) _ (echo-util/grant (system/context) [{:group_id user2-group-id :permissions [:read]}] :catalog_item_identity {:provider_id "PROV1" :name "Provider collection/granule ACL" :collection_applicable true :granule_applicable true :granule_identifier {:access_value {:include_undefined_value true :min_value 1 :max_value 50}}}) ;; Setup collection coll1 (data-core/ingest-umm-spec-collection "PROV1" (data-umm-c/collection {:ShortName "coll1" :EntryTitle "entry-title1"}) {:token "mock-echo-system-token"}) _ (index/wait-until-indexed) ;; Setup subscriptions _ (subscription-util/ingest-subscription (subscription-util/make-subscription-concept {:Name "test_sub_prov1" :SubscriberId "user2" :CollectionConceptId (:concept-id coll1) :Query "provider=PROV1"}) {:token "mock-echo-system-token"})] (index/wait-until-indexed) (testing "First query executed does not have a last-notified-at and looks back 24 hours" (let [gran1 (data-core/ingest "PROV1" (data-granule/granule-with-umm-spec-collection coll1 (:concept-id coll1) {:granule-ur "Granule1" :access-value 1}) {:token "mock-echo-system-token"}) _ (index/wait-until-indexed) results (->> (trigger-process-subscriptions) (map #(nth % 1)) flatten (map :concept-id))] (is (= (:concept-id gran1) (first results))))) ;; force eval of lazy seq (is (not= nil (count (trigger-process-subscriptions)))) (testing "Second run finds only collections created since the last notification" (let [gran2 (data-core/ingest "PROV1" (data-granule/granule-with-umm-spec-collection coll1 (:concept-id coll1) {:granule-ur "Granule2" :access-value 1}) {:token "<PASSWORD>"}) _ (index/wait-until-indexed) response (->> (trigger-process-subscriptions) (map #(nth % 1)) flatten (map :concept-id))] (is (= [(:concept-id gran2)] response)))))))
true
(ns cmr.system-int-test.ingest.subscription-processing-test "CMR subscription processing tests." (:require [clojure.test :refer :all] [cmr.ingest.services.jobs :as jobs] [cmr.mock-echo.client.echo-util :as echo-util] [cmr.system-int-test.data2.core :as data-core] [cmr.system-int-test.data2.granule :as data-granule] [cmr.system-int-test.data2.umm-spec-collection :as data-umm-c] [cmr.system-int-test.system :as system] [cmr.system-int-test.utils.index-util :as index] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.subscription-util :as subscription-util] [cmr.transmit.access-control :as access-control] [cmr.transmit.metadata-db :as mdb2])) (use-fixtures :each (join-fixtures [(ingest/reset-fixture {"provguid1" "PROV1" "provguid2" "PROV2" "provguid3" "PROV3"}) (subscription-util/grant-all-subscription-fixture {"provguid1" "PROV1" "provguid2" "PROV2"} [:read :update] [:read :update]) (subscription-util/grant-all-subscription-fixture {"provguid1" "PROV3"} [:read] [:read :update])])) (defn- trigger-process-subscriptions "Sets up process-subscriptions arguments. Calls process-subscriptions, returns granule concept-ids." [] (let [subscriptions (->> (mdb2/find-concepts (system/context) {:latest true} :subscription) (remove :deleted) (mapv #(select-keys % [:concept-id :extra-fields :metadata])))] (#'jobs/process-subscriptions (system/context) subscriptions))) (deftest ^:oracle subscription-email-processing-time-constraint-test (system/only-with-real-database (let [user2-group-id (echo-util/get-or-create-group (system/context) "group2") _user2-token (echo-util/login (system/context) "user2" [user2-group-id]) _ (echo-util/ungrant (system/context) (-> (access-control/search-for-acls (system/context) {:provider "PROV1" :identity-type "catalog_item"} {:token "mock-echo-system-token"}) :items first :concept_id)) _ (echo-util/grant (system/context) [{:group_id user2-group-id :permissions [:read]}] :catalog_item_identity {:provider_id "PROV1" :name "Provider collection/granule ACL" :collection_applicable true :granule_applicable true :granule_identifier {:access_value {:include_undefined_value true :min_value 1 :max_value 50}}}) ;; Setup collection coll1 (data-core/ingest-umm-spec-collection "PROV1" (data-umm-c/collection {:ShortName "coll1" :EntryTitle "entry-title1"}) {:token "mock-echo-system-token"}) _ (index/wait-until-indexed) ;; Setup subscriptions _ (subscription-util/ingest-subscription (subscription-util/make-subscription-concept {:Name "test_sub_prov1" :SubscriberId "user2" :CollectionConceptId (:concept-id coll1) :Query "provider=PROV1"}) {:token "mock-echo-system-token"})] (index/wait-until-indexed) (testing "First query executed does not have a last-notified-at and looks back 24 hours" (let [gran1 (data-core/ingest "PROV1" (data-granule/granule-with-umm-spec-collection coll1 (:concept-id coll1) {:granule-ur "Granule1" :access-value 1}) {:token "mock-echo-system-token"}) _ (index/wait-until-indexed) results (->> (trigger-process-subscriptions) (map #(nth % 1)) flatten (map :concept-id))] (is (= (:concept-id gran1) (first results))))) ;; force eval of lazy seq (is (not= nil (count (trigger-process-subscriptions)))) (testing "Second run finds only collections created since the last notification" (let [gran2 (data-core/ingest "PROV1" (data-granule/granule-with-umm-spec-collection coll1 (:concept-id coll1) {:granule-ur "Granule2" :access-value 1}) {:token "PI:PASSWORD:<PASSWORD>END_PI"}) _ (index/wait-until-indexed) response (->> (trigger-process-subscriptions) (map #(nth % 1)) flatten (map :concept-id))] (is (= [(:concept-id gran2)] response)))))))
[ { "context": "\n(let [id (atom 0)]\n (defn next-key []\n (str \"cnvs-\" (swap! id inc))))\n\n\n(defn set-dbg [dbg-path on-of", "end": 2886, "score": 0.9345922470092773, "start": 2880, "tag": "KEY", "value": "cnvs-\"" } ]
src/cljs/aerial/hanami/core.cljs
behrica/hanami
0
(ns aerial.hanami.core (:require [cljs.core.async :as async :refer (<! >! put! chan) :refer-macros [go go-loop]] [clojure.string :as cljstr] [com.rpl.specter :as sp] [aerial.hanasu.client :as cli] [aerial.hanasu.common :as com] [aerial.hanami.md2hiccup :as m2h] [aerial.hanami.common :as hc] [aerial.hanami.templates :as ht] ;; Vega & Vega-Lite [cljsjs.vega] [cljsjs.vega-lite] [cljsjs.vega-embed] [cljsjs.vega-tooltip] [reagent.core :as rgt] [re-com.core :as rcm :refer [h-box v-box box border gap line h-split v-split scroller button row-button md-icon-button md-circle-icon-button info-button input-text input-password input-textarea label title hyperlink-href p single-dropdown selection-list checkbox radio-button slider progress-bar throbber horizontal-bar-tabs vertical-bar-tabs modal-panel popover-content-wrapper popover-anchor-wrapper datepicker datepicker-dropdown] :refer-macros [handler-fn]] [re-com.box :refer [flex-child-style]] [re-com.dropdown :refer [filter-choices-by-keyword single-dropdown-args-desc]] [aerial.hanami.utils :refer [title2 href]] )) (def print-chan (async/chan 10)) (go-loop [msg (async/<! print-chan)] (js/console.log (print-str msg)) (recur (async/<! print-chan))) (defn printchan [& args] (async/put! print-chan (clojure.string/join " " args))) ;;; Need a _data_ database :/ ;;; ;;; This is needed to handle state NOT associated with component state ;;; or updates. In particular, to avoid triggering their renderings on ;;; completely irrelevant changes. ;;; ;;; First and foremost, no state _directly associated_ with the ;;; messaging system should have any impact on components!! ;;; (defonce data-db (atom {:dbg {}})) (defn update-ddb ([] (com/update-db data-db {})) ([keypath vorf] (com/update-db data-db keypath vorf)) ([kp1 vof1 kp2 vof2 & kps-vs] (apply com/update-db data-db kp1 vof1 kp2 vof2 kps-vs))) (defn get-ddb ([] (com/get-db data-db [])) ([key-path] (com/get-db data-db key-path))) (defonce app-db (rgt/atom {:dbg {}})) (def default-opts {:vgl {:export true :renderer "canvas" #_"svg" :mode "vega-lite" #_vega} :tab {:order :col :eltsper 2 :size "none"}}) (declare print-when) (defn update-adb ([] (com/update-db app-db :default-opts default-opts)) ([keypath vorf] #_(printchan [:db :update] "UPDATE-ADB " keypath vorf) (com/update-db app-db keypath vorf)) ([kp1 vof1 kp2 vof2 & kps-vs] (apply com/update-db app-db kp1 vof1 kp2 vof2 kps-vs))) (defn get-adb ([] (com/get-db app-db [])) ([key-path] #_(printchan [:db :get]"GET-ADB " key-path) (com/get-db app-db key-path))) (let [id (atom 0)] (defn next-key [] (str "cnvs-" (swap! id inc)))) (defn set-dbg [dbg-path on-off] (let [dbg-path (com/ev dbg-path) path (->> dbg-path (concat [:dbg]) vec)] (update-adb path on-off))) (defn dbgon [dbg-path] (set-dbg dbg-path true)) (defn dbgoff [dbg-path] (set-dbg dbg-path false)) (defn dbg? [dbg-path] (let [dbg-path (com/ev dbg-path) path (->> dbg-path (concat [:dbg]) vec)] (get-adb path))) (defn print-when [dbg-path & args] (when (dbg? dbg-path) (apply printchan args))) (defn md "Markdown to Hiccup with implicit support for handling LaTex via MathJax. Note: MathJax is _not_ supported in Hanami as it " [ & stg] (let [base-style {:flex "none", :width "450px", :min-width "450px"} x (first stg) stg (cljstr/join "\n" (if (map? x) (rest stg) stg)) stg (cljstr/replace stg "\\(" "\\\\(") stg (cljstr/replace stg "\\)" "\\\\)") style (->> (if (map? x) (x :style) {}) (merge base-style)) attr (if (map? x) (assoc x :style style) {:style style}) hiccup (vec (concat [:div.md attr] (rest (m2h/parse stg))))] (print-when [:md] :MD hiccup) hiccup)) ;;; Fix this. First 'refer :all' from re-com.core. Then use ns-publics ;;; and deref vars in the resulting map (to get the function objects) ;;; to make re-com-xref. (def re-com-xref (into {} (mapv vector '[h-box v-box box border gap line h-split v-split scroller flex-child-style button row-button md-icon-button md-circle-icon-button info-button input-text input-password input-textarea label title hyperlink-href p single-dropdown selection-list checkbox radio-button slider progress-bar throbber horizontal-bar-tabs vertical-bar-tabs modal-panel popover-content-wrapper popover-anchor-wrapper filter-choices-by-keyword single-dropdown-args-desc datepicker datepicker-dropdown md] [h-box v-box box border gap line h-split v-split scroller flex-child-style button row-button md-icon-button md-circle-icon-button info-button input-text input-password input-textarea label title hyperlink-href p single-dropdown selection-list checkbox radio-button slider progress-bar throbber horizontal-bar-tabs vertical-bar-tabs modal-panel popover-content-wrapper popover-anchor-wrapper filter-choices-by-keyword single-dropdown-args-desc datepicker datepicker-dropdown md]))) (defn xform-recom ([x k v & kvs] (let [kvs (->> kvs (partition-all 2) (map vec))] (xform-recom x (into re-com-xref (cons [k v] kvs))))) ([x kvs] (let [xlate-cb (-> :symxlate-cb get-adb first)] (sp/transform sp/ALL (fn[v] (cond (coll? v) (xform-recom v kvs) (symbol? v) (let [v (-> v name symbol)] (get kvs v (xlate-cb v))) :else (get kvs v v))) x)))) (declare get-cur-tab) (defn get-vspec ([vid] (get-vspec (get-cur-tab :id) vid)) ([tid vid] (sp/select-one [sp/ATOM :vspecs sp/ATOM tid vid] app-db))) (defn update-vspecs ([vid vspec] (update-vspecs (get-cur-tab :id) vid vspec)) ([tid vid vspec] (sp/setval [sp/ATOM :vspecs sp/ATOM tid vid] vspec app-db))) (defn get-vgview ([vid] (get-vgview (get-cur-tab :id) vid)) ([tid vid] (sp/select-one [sp/ATOM :vgviews sp/ATOM tid vid] app-db))) (defn get-vgviews ([] (sp/select-any [sp/ATOM :vgviews sp/ATOM] app-db)) ([tid] (sp/select-any [sp/ATOM :vgviews sp/ATOM tid] app-db))) (defn update-vgviews ([vid vgview] (update-vgviews (get-cur-tab :id) vid vgview)) ([tid vid vgview] (sp/setval [sp/ATOM :vgviews sp/ATOM tid vid] vgview app-db))) (defn del-vgviews ([] (sp/setval [sp/ATOM :vgviews sp/ATOM] {} app-db) true) ([tid] (sp/setval [sp/ATOM :vgviews sp/ATOM tid] sp/NONE app-db) true) ([tid vid] (sp/setval [sp/ATOM :vgviews sp/ATOM tid vid] sp/NONE app-db) true)) (defn get-tab-field ([tid] (sp/select-one [sp/ATOM :tabs :active sp/ATOM sp/ALL #(= (% :id) tid)] app-db)) ([tid field] (sp/select-one [sp/ATOM :tabs :active sp/ATOM sp/ALL #(= (% :id) tid) field] app-db))) (defn update-tab-field [tid field value] (sp/setval [sp/ATOM :tabs :active sp/ATOM sp/ALL #(= (% :id) tid) field] value app-db)) (defn get-tab-body [id] (select-keys (sp/select-one [sp/ATOM :tabs :active sp/ATOM sp/ALL #(= (% :id) id)] app-db) [:id :opts :specs])) (defn get-cur-tab ([] (get-tab-field (deref (get-adb [:tabs :current])))) ([field] (get-tab-field (deref (get-adb [:tabs :current])) field))) (defn set-cur-tab [tid] (sp/setval [sp/ATOM :tabs :current sp/ATOM] tid app-db)) (defn update-cur-tab [field value] (update-tab-field (deref (get-adb [:tabs :current])) field value)) (defn tab-pos [tid] (let [tabvec (sp/select [sp/ATOM :tabs :active sp/ATOM sp/ALL] app-db) cnt (count tabvec)] [(sp/select-one [sp/INDEXED-VALS #(-> % second :id (= tid)) sp/FIRST] tabvec) cnt tabvec])) (defn move-tab [tid dir] (assert (#{:left :right} dir) (str "dir '" dir "' must be :left or :right")) (let [tabval (get-tab-field tid) [idx cnt curtabs] (tab-pos tid) f (cond (and (= dir :left) (= idx 0)) :nop (and (= dir :right) (= idx (dec cnt))) :nop (= dir :left) dec (= dir :right) inc)] (when (not= f :nop) (let [v (sp/setval [sp/ALL #(= (% :id) tid)] hc/RMV curtabs) v (sp/setval (sp/before-index (f idx)) tabval v)] (sp/setval [sp/ATOM :tabs :active sp/ATOM] v app-db) v)))) (defn add-tab [tabval] (sp/setval [sp/ATOM :tabs :active sp/ATOM sp/AFTER-ELEM] tabval app-db) (set-cur-tab (tabval :id))) (defn replace-tab [tid newdef] (sp/setval [sp/ATOM :tabs :active sp/ATOM sp/ALL #(= (% :id) tid)] newdef app-db)) (defn del-tab [tid] (let [curid ((get-cur-tab) :id) cnt (count (sp/select [sp/ATOM :tabs :active sp/ATOM sp/ALL] app-db))] (sp/setval [sp/ATOM :tabs :active sp/ATOM sp/ALL #(= (% :id) tid)] hc/RMV app-db) (when (and (> cnt 0) (= tid curid)) (set-cur-tab (-> (sp/select [sp/ATOM :tabs :active sp/ATOM sp/ALL] app-db) first :id))))) (defn active-tabs [] (printchan :ACTIVE-TABS " called") (let [bar-cursor (rgt/cursor app-db [:tabs :bars]) curtab (get-cur-tab)] (if curtab @bar-cursor [:p]))) (defn header [msg] [title2 msg :class "title" ;;:margin-top "2px" :margin-bottom "1px" #_:style #_{:background-color "lightgreen"}]) (defn visualize [spec elem] (print-when [:vis :vis] :SPEC spec) (when spec (let [tid (-> spec :usermeta :tab :id) vid (-> spec :usermeta :vid) _ (printchan :VID vid) vopts (-> spec :usermeta :opts) vmode (get vopts :mode) default-hover (if (= vmode "vega-lite") false js/undefined) spec (clj->js spec) opts {:renderer (get vopts :renderer "canvas") :mode "vega" :hover (get vopts :hover default-hover) :defaultStyle true :scaleFactor (get vopts :scaleFactor 1) :actions {:export (get vopts :export false), :source (get vopts :source false), :editor (get vopts :editor false), :compiled false}} vega (if (= vmode "vega-lite") (->> spec js/vegaLite.compile .-spec) spec)] (-> (js/vegaEmbed elem vega (clj->js opts)) (.then (fn [res] (when vid (update-vgviews tid vid res.view)) #_(js/vegaTooltip.vega res.view spec) #_(js/vegaTooltip.vegaLite res.view spec))) (.catch (fn [err] (printchan err))))))) (defn vgl "Reagent component to render vega/vega-lite visualizations." [spec] (printchan "VGL called") (rgt/create-class {:display-name "VGL" :component-did-mount (fn [comp] (let [argv (rest (rgt/argv comp))] (printchan "Did-Mount: called") (visualize spec (rgt/dom-node comp)))) :component-did-update (fn [comp old-useless-argv] (printchan "Did-Update: called") ;; OK, this is a mess. 'new-useful-argv' is really only useful ;; in conjunction with old-useless-argv. Even then you may not ;; really get the data / args you want/need/expect. Only the ;; new-argv-2nd-way gives the complete argument set. (let [new-useful-argv (rgt/children comp) new-argv-2nd-way (rgt/argv comp) ; first elt some fn?!? new-spec (-> new-argv-2nd-way rest first)] (print-when [:vis :vgl :update] :ARGV1 new-useful-argv :ARGV2 (rest new-argv-2nd-way)) (visualize new-spec (rgt/dom-node comp)))) :reagent-render (fn [spec] (let [id (or (-> spec :usermeta :vid) (gensym "vid-")) elt (js/document.getElementById id)] (if elt elt [box :attr {:id id} :child [:div]])))})) (defn frameit [spec frame] (let [frame-cb (-> :frame-cb get-adb first) [spec frame] (frame-cb spec frame)] [v-box :attr {:id (frame :frameid)} :gap "10px" :children [[h-box :gap "5px" :children (frame :top)] [h-box :gap "5px" :children (if spec [[h-box :children (frame :left)] [vgl spec] [h-box :children (frame :right)]] [[h-box :children (frame :left)] [h-box :children (frame :right)]])] [h-box :gap "5px" :children (frame :bottom)]]])) (defn vis-list [tabid spec-frame-pairs opts] (let [layout (if (= (get-in opts [:order]) :row) h-box v-box) lgap (if (= layout h-box) (opts :cgap) (opts :rgap)) eltnum (get-in opts [:eltsper] 3) numspecs (count spec-frame-pairs) spec-chunks (->> spec-frame-pairs (partition-all eltnum) (mapv vec))] (printchan "VIS-LIST : " numspecs) (for [sub-pairs spec-chunks] [layout :size (get-in opts [:size] "auto") :gap lgap :children (for [[spec frame] sub-pairs] (do #_(js-delete spec "usermeta") (print-when [:vis :vis-list] :NSPEC spec frame) (frameit spec frame)))]))) (declare make-spec-frame-pairs) (defn add-to-tab-body [id picframe & {:keys [at position opts] :or {at :end position :after opts {}}}] (let [tbdy (get-tab-body id) opts (merge (tbdy :opts) opts) specs (tbdy :specs) pos (cond (= at :beg) 0 (= at :end) (dec (count specs)) :else (->> specs (keep-indexed (fn[idx item] (when (-> item :usermeta :frame :fid (= at)) idx))) first)) pos (if (= position :after) (inc pos) pos) newspecs (concat (take pos specs) [picframe] (drop pos specs)) s-f-pairs (make-spec-frame-pairs id opts newspecs)] (update-tab-field id :opts opts) (update-tab-field id :specs newspecs) (update-tab-field id :compvis (vis-list id s-f-pairs opts)) id)) (defn remove-from-tab-body [id fid] (let [tbdy (get-tab-body id) opts (tbdy :opts) specs (tbdy :specs) specs (remove #(-> % :usermeta :frame :fid (= fid)) specs) s-f-pairs (make-spec-frame-pairs id opts specs)] (update-tab-field id :specs specs) (update-tab-field id :compvis (vis-list id s-f-pairs opts)) id)) (defn update-frame [tid fid element content] (let [tbdy (get-tab-body tid) opts (tbdy :opts) specs (tbdy :specs) pos (->> specs (keep-indexed (fn[idx item] (when (-> item :usermeta :frame :fid (= fid)) idx))) first) newspec (if (= element :frame) content (assoc-in (nth specs pos) [:usermeta :frame element] content)) newspecs (concat (take pos specs) [newspec] ; splice in the updated spec (drop (inc pos) specs)) s-f-pairs (make-spec-frame-pairs tid opts newspecs)] (update-tab-field tid :specs newspecs) (update-tab-field tid :compvis (vis-list tid s-f-pairs opts)) tid)) ;;; The following two muck with the DOM directly and are not ;;; recommended. Probably should remove altogether, but leaving for ;;; right now. (defn get-frame-elements [fid] (let [fid (name fid) frame (js/document.getElementById fid) top (aget frame.childNodes 0) bottom (aget frame.childNodes 4) middle (aget frame.childNodes 2) left (aget middle.childNodes 0) vis (aget middle.childNodes 2) right (aget middle.childNodes 4)] {:top top, :bottom bottom, :left left, :right right, :vis vis})) (defn update-frame-element [fid element content] (let [fid (name fid) frame-element ((get-frame-elements fid) element) component content frame-cb (-> :frame-cb get-adb first)] (rgt/render component frame-element) (frame-cb {} {:frameid fid}))) (defn hanami [] (if-let [tabval (get-cur-tab)] (let [tabid (tabval :id) specs (tabval :specs) compvis (tabval :compvis) opts (tabval :opts (get-adb [:main :opts :tab])) frame-cb (-> :frame-cb get-adb first)] (cond compvis (do (printchan "hanami called - has compvis") (frame-cb) compvis) specs (let [spec-frame-pairs (tabval :spec-frame-pairs) ;;_ (printchan :SCPAIRS spec-frame-pairs) compvis (vis-list tabid spec-frame-pairs opts)] (printchan "hanami called - making compvis") (update-cur-tab :compvis compvis) compvis) :else [[:img {:src (get-adb [:main :img])}]])) [[:img {:src (get-adb [:main :img])}]])) (defn tabs [] (printchan "TABS called ...") (let [tabval (get-cur-tab) opts (or (and tabval (tabval :opts)) (get-adb [:main :opts :tab])) id (or (and tabval (str (name (tabval :id)) "-body")) "xHx") wrapfn (or (opts :wrapfn) identity) extfn (get-in opts [:extfn]) size (get-in opts [:size] "auto") order (get-in opts [:order] :col) layout (if (= order :row) v-box h-box) lgap (if (= layout v-box) (opts :rgap) (opts :cgap))] (printchan :OPTS opts) (if extfn (extfn tabval) (wrapfn [layout :attr {:id id} :size size :gap lgap :children (hanami)])))) (defn hanami-main [] (printchan "Hanami-main called ...") (let [inst-cursor (rgt/cursor app-db [:instrumentor]) instrumentor (first @inst-cursor) hd-cursor (rgt/cursor app-db [:header]) header (first @hd-cursor)] [v-box :gap "10px" :children [[v-box :gap "3px" :children [[header] [h-box :align :start :max-height "30px" :children [[gap :size "15px"] [active-tabs]]]]] [line] [tabs]]])) ;;; Messaging ---------------------------------------------------------------- (defn get-ws [] (->> (get-ddb []) keys (filter #(-> % type (= js/WebSocket))) first)) (defn get-chan [] (let [ws (get-ws) ch (when ws (get-ddb [ws :chan]))] ch)) ;; Send server msg (defn app-send [msg] (printchan "app-send: DEPRECATED, use 'send-msg'") (cli/send-msg (get-ws) msg)) (defn send-msg ([msg] (print-when [:msg :send] "Sending msg " msg) (cli/send-msg (get-ws) msg)) ([op data] (send-msg {:op op :data data}))) (defn merge-old-new-opts [oldopts newopts] (cond (and oldopts newopts) (if (or (oldopts :tab) (oldopts :vgl)) (sp/transform [(sp/submap [:vgl :tab]) sp/MAP-VALS] #(merge % newopts) oldopts) (merge oldopts newopts)) oldopts oldopts newopts newopts :else (get-adb [:main :opts]))) ;; Stop app (defn app-stop [] (let [ws (get-ws) ch (get-chan)] (when ch (go (async/>! ch {:op :stop :payload {:ws ws :cause :userstop}}))))) (defn init-tabs [] (update-adb [:tabs] (let [cur-ratom (rgt/atom nil) tabs-ratom (rgt/atom [])] {:current cur-ratom :active tabs-ratom :bars [horizontal-bar-tabs :model cur-ratom :tabs tabs-ratom :on-change #(reset! cur-ratom %)]}))) (defn register [{:keys [uid title logo img opts]}] (printchan "Registering " uid) (update-adb [:main :uid] uid [:main :title] title [:main :logo] logo [:main :img] img [:main :opts] (hc/xform opts) [:main :session-name] (rgt/atom "") [:vgl-as-vg] :rm [:vgviews] (atom {}) ; This should not have any reactive update [:vspecs] (rgt/atom {})) (init-tabs) (rgt/render [hanami-main] (get-adb :elem) #_(js/document.querySelector "#app"))) (defn update-opts [{:keys [main tab opts]}] (if main (update-adb [:main :opts] (merge-old-new-opts (get-adb [:main :opts]) opts)) (do (update-tab-field tab :opts (merge-old-new-opts (get-tab-field tab :opts) opts)) (update-tab-field tab :compvis sp/NONE)))) (defn empty-chart? [spec] (and (-> spec keys count (= 1)) (-> spec keys first (= :usermeta)))) (defn make-tabdefs [specs] (let [grps (group-by #(->> % :usermeta :tab :id) (com/ev specs))] (mapv (fn[[id specs]] (let [tab (->> specs first :usermeta :tab)] (assoc tab :specs (mapv (fn[spec] (dissoc spec :tab)) specs)))) grps))) (defn make-spec-frame-pairs [tid opts specs] (let [instrumentor (-> :instrumentor get-adb first)] (mapv #(do (when-let [vid (get-in % [:usermeta :vid])] (update-vspecs vid %)) (vector (if (empty-chart? %) nil %) (instrumentor {:tabid tid :spec % :opts opts}))) specs))) (defn update-tabs [specs] (let [tabdefs (make-tabdefs specs)] (mapv (fn [{:keys [id label opts specs] :as newdef}] (let [tid id oldef (get-tab-field tid) specs (when specs (->> specs com/ev)) main-opts (get-adb [:main :opts :tab]) instrumentor (-> :instrumentor get-adb first) spec-frame-pairs (make-spec-frame-pairs tid opts specs)] (if (not oldef) (add-tab (assoc newdef :opts (merge-old-new-opts main-opts opts) :spec-frame-pairs spec-frame-pairs :specs specs)) (let [oldopts (or (oldef :opts) main-opts)] (replace-tab tid {:id tid :label (or label (get-tab-field tid :label)) :opts (merge-old-new-opts oldopts opts) :spec-frame-pairs spec-frame-pairs :specs specs}))))) tabdefs))) (defn update-data "Originally meant as general updater of vis plot/chart data values. But to _render_ these, requires knowledge of the application pages/structure. So, this is not currently used. If we can figure out Vega chageSets and how they update, we may be able to make this a general op in Hanami." [data-maps app-fn] (printchan :UPDATE-DATA data-maps) (app-fn (mapv (fn [{:keys [usermeta data]}] (let [vid (usermeta :vid) spec (dissoc (get-vspec vid) :data)] (assoc-in spec [:data :values] data))) data-maps))) (defmulti user-msg :op) (defmethod user-msg :default [msg] (printchan msg)) (defn on-msg [ch ws hanami-msg] (let [{:keys [op data]} hanami-msg] (update-ddb [ws :line-info :rcvcnt] inc) (case op :register (do (register data) (user-msg {:op :app-init :data data})) :opts (update-opts data) :tabs (update-tabs data) #_:data #_(update-data data) :specs (let [{:keys [tab specs]} data] (update-tab-field tab :specs specs)) (user-msg {:op op :data data :ws ws :ch ch})))) (defn on-open [ch ws] (update-ddb ws {:chan ch, :line-info {:rcvcnt 0, :sntcnt 0, :errcnt 0}})) (defn message-dispatch [ch op payload] (case op :open (let [ws payload] (print-when [:msg :open] :CLIENT :open :ws ws) (on-open ch ws)) :close (let [{:keys [ws code reason]} payload] (print-when :CLIENT :RMTclose :payload payload) (go (async/put! ch {:op :stop :payload {:ws ws :cause :rmtclose}}))) :msg (let [{:keys [ws data]} payload] (print-when [:msg :msg] :CLIENT :msg :payload payload) (on-msg ch ws data)) :bpwait (let [{:keys [ws msg encode]} payload] (print-when [:msg :bpwait] :CLIENT "Waiting to send msg " msg) (go (async/<! (async/timeout 5000))) (print-when [:msg :bpwait] :CLIENT "Trying resend...") (cli/send-msg ws msg :encode encode)) :bpresume (print-when [:msg :bpresume] :CLIENT "BP Resume " payload) :sent (let [{:keys [ws msg]} payload] (print-when [:msg :sent] :CLIENT "Sent msg " msg) (update-ddb [ws :line-info :lastsnt] msg, [ws :line-info :sntcnt] inc)) :stop (let [{:keys [ws cause]} payload] (print-when [:msg :stop] :CLIENT "Stopping reads... Cause " cause) (cli/close-connection ws) (update-ddb ws :rm)) :error (let [{:keys [ws err]} payload] (printchan :CLIENT :error :payload payload) (update-ddb [ws :line-info :errcnt] inc)) (printchan :CLIENT :WTF :op op :payload payload))) (defn connect [host port] (go (let [uri (str "ws://" host ":" port "/ws") ch (async/<! (cli/open-connection uri))] (printchan "Opening client, reading msgs from " ch) (loop [msg (<! ch)] (let [{:keys [op payload]} msg] (message-dispatch ch op payload) (when (not= op :stop) (recur (<! ch)))))))) (defn set-session-name [name] (let [old-uid (get-adb [:main :uid]) name (if (= name "") (old-uid :name) name)] (sp/setval [sp/ATOM :main :session-name sp/ATOM] name app-db) (when (not= name (old-uid :name)) (update-adb [:main :uid :name] name) (send-msg {:op :set-session-name :data {:uid old-uid :new-name name}})))) (defn session-input [] (if (not= "" (sp/select-one [sp/ATOM :main :session-name sp/ATOM] app-db)) [:p] [input-text :model (get-adb [:main :session-name]) :on-change set-session-name :placeholder (get-adb [:main :uid :name]) :width "100px"])) (defn default-header-fn [] [h-box :gap "10px" :max-height "30px" :children [[gap :size "5px"] [:img {:src (get-adb [:main :logo])}] [title :level :level3 :label [:span.bold (get-adb [:main :title])]] #_[gap :size "5px"] [session-input] [gap :size "5px"] [title :level :level3 :label [:span.bold (get-adb [:main :uid :name])]] [gap :size "30px"]]]) (defn default-frame-cb ([]) ([spec frame] [spec frame])) (defn get-default-frame [] {:top [], :bottom [], :left [[box :size "0px" :child ""]], :right [[box :size "0px" :child ""]]}) (defn make-frame [udata curframe] (let [frameid (get-in udata [:frame :fid] (gensym "frame-"))] (merge (if (udata :frame) (let [default-frame (get-default-frame) framedef (udata :frame) frame-sides (dissoc framedef :fid :at :pos)] (print-when [:frames :make] :Frame-Maker frame-sides curframe) (update-adb [:dbg :frame] (->> (keys frame-sides) (reduce (fn[F k] (assoc F k (xform-recom (frame-sides k) re-com-xref))) default-frame))) (get-adb [:dbg :frame])) (get-default-frame)) (assoc curframe :frameid frameid)))) (defn default-instrumentor-fn [{:keys [tabid spec opts]}] (let [udata (spec :usermeta)] (print-when [:instrumentor] chan :UDATA udata :OPTS opts)) {}) (defn make-instrumentor [userfn] (fn [{:keys [tabid spec opts] :as m}] (make-frame (spec :usermeta) (userfn m)))) (defn start [& {:keys [elem host port header-fn instrumentor-fn frame-cb symxlate-cb] :or {host js/location.hostname header-fn default-header-fn instrumentor-fn default-instrumentor-fn frame-cb default-frame-cb symxlate-cb identity}}] (let [instfn (make-instrumentor instrumentor-fn)] (printchan "Element 'app' available, port " port) (app-stop) (update-adb :elem elem :symxlate-cb [symxlate-cb] :frame-cb [frame-cb] :instrumentor [instfn] :header [header-fn]) (connect host port))) (defn sv! "Mirror of server side hmi/sv! Here no need for messages. Just need to call `update-tabs` on the vector of vg/vgl-maps." [vgl-maps] (let [vgl-maps (com/ev vgl-maps)] (update-tabs vgl-maps) true)) (comment ;; Rich Comment!! ;; Always run this setup init for any testing (do (hc/update-defaults :USERDATA {:tab {:id :TID, :label :TLBL, :opts :TOPTS} :frame {:top :TOP, :bottom :BOTTOM, :left :LEFT, :right :RIGHT :fid :FID} :opts :OPTS :vid :VID, :msgop :MSGOP, :session-name :SESSION-NAME} :MSGOP :tabs, :SESSION-NAME "Exploring" :TID :expl1, :TLBL #(-> :TID % name cljstr/capitalize) :OPTS (hc/default-opts :vgl), :TOPTS (hc/default-opts :tab)) (defn bar-slider-fn [tid val] (let [tabval (get-tab-field tid) spec-frame-pairs (tabval :spec-frame-pairs)] (printchan "Slider update " val) (update-tab-field tid :compvis nil) (update-tab-field tid :spec-frame-pairs (mapv (fn[[spec frame]] (let [cljspec spec data (mapv (fn[m] (assoc m :b (+ (m :b) val))) (get-in cljspec [:data :values])) newspec (assoc-in cljspec [:data :values] data)] [newspec frame])) spec-frame-pairs)))) (defn test-instrumentor [{:keys [tabid spec opts]}] (printchan "Test Instrumentor called" :TID tabid #_:SPEC #_spec) (let [cljspec spec udata (cljspec :usermeta) default-frame (get-default-frame)] (update-adb [:udata] udata) (cond (not (map? udata)) [] (udata :slider) (let [sval (rgt/atom "0.0")] (printchan :SLIDER-INSTRUMENTOR) {:top (xform-recom (udata :slider) :m1 sval :oc1 #(do (bar-slider-fn tabid %) (reset! sval (str %))) :oc2 #(do (bar-slider-fn tabid (js/parseFloat %)) (reset! sval %)))}) (udata :test2) {:right [[gap :size "10px"] [v-box :children [[label :label "Select a demo"] [single-dropdown :choices (udata :test2) :on-change #(printchan "Dropdown: " %) :model nil :placeholder "Hi there" :width "100px"]]]]} :else {} ))) (start :elem (js/document.querySelector "#app") :instrumentor-fn test-instrumentor :port 3003)) ;; ======================================================================= ;; Testing new incremental tab bodies and user wrapping function support ;; Create a tab that includes a user defined WRAPFN (add-tab {:id :dists :label "Dists" :specs [] :opts {:order :row, :eltsper 1, :size "auto" :wrapfn (fn[hcomp] [h-split :panel-1 [box :child [input-textarea :model " 1234567890123456789012345678901234567890123456789012345678901234567890123456789" :width "650px" :rows 40 :on-change identity]] :panel-2 [scroller :max-height "800px" :max-width "1200px" :align :start :child hcomp] :initial-split "33%" :width "2048px"])}}) ;; Add some page/section title text (do (add-to-tab-body :dists (hc/xform ht/empty-chart :FID :dtitle :TOP '[[gap :size "50px"] [md "# Example Interactive Document Creation"]])) :done) ;; Render a graphic in it (add-to-tab-body :dists (hc/xform ht/bar-chart :TITLE "Top headline phrases" :TID :dists :FID :dhline :ELTSPER 1 :X :x-value :Y :y-value :YTYPE "nominal" :DATA [{:x-value 8961 :y-value "will make you"} {:x-value 4099 :y-value "this is why"} { :x-value 3199 :y-value "can we guess"} {:x-value 2398 :y-value "only X in"} {:x-value 1610 :y-value "the reason is"} {:x-value 1560 :y-value "are freaking out"} {:x-value 1425 :y-value "X stunning photos"} {:x-value 1388 :y-value "tears of joy"} {:x-value 1337 :y-value "is what happens"} {:x-value 1287 :y-value "make you cry"}])) ;; Add empty picture frame with all elements as MD (do (add-to-tab-body :dists (hc/xform ht/empty-chart :FID :dwrup1 :TOP '[[gap :size "200px"][md "# Header top"]] :BOTTOM '[[gap :size "200px"] [md "# Header bottom"]] :LEFT '[[gap :size "50px"] [md "### Header left"]] :RIGHT '[[md "### Header right"]])) :done) ;; Make some distribution data (def obsdist (let [obs [[0 9] [1 78] [2 305] [3 752] [4 1150] [5 1166] [6 899] [7 460] [8 644] [9 533] [10 504]] totcnt (->> obs (mapv second) (apply +)) pdist (map (fn[[k cnt]] [k (double (/ cnt totcnt))]) obs)] pdist)) ;; Add a picture to the tab (do (add-to-tab-body :dists (hc/xform ht/layer-chart :TID :dists :FID :dex1 :TITLE "A Real (obvserved) distribution with incorrect simple mean" :HEIGHT 400 :WIDTH 450 :LAYER [(hc/xform ht/bar-layer :XTITLE "Count" :YTITLE "Probability") (hc/xform ht/xrule-layer :AGG "mean")] :DATA (mapv (fn[[x y]] {:x x :y y :m 5.7}) obsdist))) :done) ;; Add some more 'writeup' (do (add-to-tab-body :dists (hc/xform ht/empty-chart :FID :dwrup2 :BOTTOM '[[gap :size "50px"] [md "# Fixed distribution Here we have corrected the mean by properly including item weights"]])) :done) (do (add-to-tab-body :dists (hc/xform ht/layer-chart :TID :dists :FID :dex2 :TITLE "The same distribution with correct weighted mean" :HEIGHT 400 :WIDTH 450 :LAYER [(hc/xform ht/bar-layer :XTITLE "Count" :YTITLE "Probability") (hc/xform ht/xrule-layer :X "m")] :DATA (mapv (fn[[x y]] {:x x :y y :m 5.7}) obsdist))) :done) ;; ======================================================================= ;; Direct noodling on the DOM - not recommended as subverts data flow of ;; Reagent/React (let [body (js/document.getElementById "expl1-body") lastchild body.lastChild div (js/document.createElement "div") _ (set! (.-id div) "mymd") component [h-box :children [[gap :size "20px" :width "20px"] [md " # Header 1 ## Header 2 ### Header 3, following is list * One * Two * Three"]]]] (.appendChild lastchild div) (rgt/render component lastchild.lastChild) (js/console.log lastchild) (js/console.log lastchild.lastChild)) (let [body (js/document.getElementById "expl1-body") lastchild body.lastChild] (js/console.log body) (js/console.log lastchild)) (let [body (js/document.getElementById "expl1-body") lastchild body.lastChild] (.appendChild lastchild (js/document.createElement "div")) (js/console.log lastchild) (js/console.log lastchild.lastChild)) (let [body (js/document.getElementById "expl1-body") lastchild body.lastChild component ""] (.remove lastchild.lastChild) (js/console.log lastchild) (js/console.log lastchild.lastChild)) (let [mymd (js/document.getElementById "mymd")] #_(.removeChild mymd.parentNode mymd) (.remove mymd)) (let [body (js/document.getElementById "expl1-body") lastchild body.lastChild mymd (js/document.getElementById "mymd")] (.insertBefore mymd lastchild)) ;; ======================================================================= ;; Old original db messing and testing of adding / updating tabs (get-adb [:test1 :sval]) (update-adb [:main :uid :name] "Hello") (add-tab {:id :p1 :label "BarChart" :opts {:order :col :eltsper 2 :size "none"} :specs [js/vglspec]}) (add-tab {:id :p2 :label "BarChart/Mean" :specs [js/vglspec3]}) (add-tab {:id :p3 :label "MultiChart" :specs [js/vglspec js/vglspec2 js/vglspec3 js/vglspec]}) (add-tab {:id :ttest :label "ToolTip" :specs js/ttest}) (add-tab {:id :geotest :label "GeoTest" :specs js/geotest}) (update-tab-field :geotest :specs js/geotest) (add-tab {:id :px :label "MultiChartSVG" :opts (merge-old-new-opts (get-adb [:defopts :tab]) {:size "auto"}) :specs [js/vglspec js/vglspec2 js/vglspec3 js/vglspec]}) (get-adb :tabs) {:op :tabs :data [{:id :px :label "MultiChartSVG" :opts {:size "auto"} :specs [js/vglspec js/vglspec2 js/vglspec3 js/vglspec]}]} )
39391
(ns aerial.hanami.core (:require [cljs.core.async :as async :refer (<! >! put! chan) :refer-macros [go go-loop]] [clojure.string :as cljstr] [com.rpl.specter :as sp] [aerial.hanasu.client :as cli] [aerial.hanasu.common :as com] [aerial.hanami.md2hiccup :as m2h] [aerial.hanami.common :as hc] [aerial.hanami.templates :as ht] ;; Vega & Vega-Lite [cljsjs.vega] [cljsjs.vega-lite] [cljsjs.vega-embed] [cljsjs.vega-tooltip] [reagent.core :as rgt] [re-com.core :as rcm :refer [h-box v-box box border gap line h-split v-split scroller button row-button md-icon-button md-circle-icon-button info-button input-text input-password input-textarea label title hyperlink-href p single-dropdown selection-list checkbox radio-button slider progress-bar throbber horizontal-bar-tabs vertical-bar-tabs modal-panel popover-content-wrapper popover-anchor-wrapper datepicker datepicker-dropdown] :refer-macros [handler-fn]] [re-com.box :refer [flex-child-style]] [re-com.dropdown :refer [filter-choices-by-keyword single-dropdown-args-desc]] [aerial.hanami.utils :refer [title2 href]] )) (def print-chan (async/chan 10)) (go-loop [msg (async/<! print-chan)] (js/console.log (print-str msg)) (recur (async/<! print-chan))) (defn printchan [& args] (async/put! print-chan (clojure.string/join " " args))) ;;; Need a _data_ database :/ ;;; ;;; This is needed to handle state NOT associated with component state ;;; or updates. In particular, to avoid triggering their renderings on ;;; completely irrelevant changes. ;;; ;;; First and foremost, no state _directly associated_ with the ;;; messaging system should have any impact on components!! ;;; (defonce data-db (atom {:dbg {}})) (defn update-ddb ([] (com/update-db data-db {})) ([keypath vorf] (com/update-db data-db keypath vorf)) ([kp1 vof1 kp2 vof2 & kps-vs] (apply com/update-db data-db kp1 vof1 kp2 vof2 kps-vs))) (defn get-ddb ([] (com/get-db data-db [])) ([key-path] (com/get-db data-db key-path))) (defonce app-db (rgt/atom {:dbg {}})) (def default-opts {:vgl {:export true :renderer "canvas" #_"svg" :mode "vega-lite" #_vega} :tab {:order :col :eltsper 2 :size "none"}}) (declare print-when) (defn update-adb ([] (com/update-db app-db :default-opts default-opts)) ([keypath vorf] #_(printchan [:db :update] "UPDATE-ADB " keypath vorf) (com/update-db app-db keypath vorf)) ([kp1 vof1 kp2 vof2 & kps-vs] (apply com/update-db app-db kp1 vof1 kp2 vof2 kps-vs))) (defn get-adb ([] (com/get-db app-db [])) ([key-path] #_(printchan [:db :get]"GET-ADB " key-path) (com/get-db app-db key-path))) (let [id (atom 0)] (defn next-key [] (str "<KEY> (swap! id inc)))) (defn set-dbg [dbg-path on-off] (let [dbg-path (com/ev dbg-path) path (->> dbg-path (concat [:dbg]) vec)] (update-adb path on-off))) (defn dbgon [dbg-path] (set-dbg dbg-path true)) (defn dbgoff [dbg-path] (set-dbg dbg-path false)) (defn dbg? [dbg-path] (let [dbg-path (com/ev dbg-path) path (->> dbg-path (concat [:dbg]) vec)] (get-adb path))) (defn print-when [dbg-path & args] (when (dbg? dbg-path) (apply printchan args))) (defn md "Markdown to Hiccup with implicit support for handling LaTex via MathJax. Note: MathJax is _not_ supported in Hanami as it " [ & stg] (let [base-style {:flex "none", :width "450px", :min-width "450px"} x (first stg) stg (cljstr/join "\n" (if (map? x) (rest stg) stg)) stg (cljstr/replace stg "\\(" "\\\\(") stg (cljstr/replace stg "\\)" "\\\\)") style (->> (if (map? x) (x :style) {}) (merge base-style)) attr (if (map? x) (assoc x :style style) {:style style}) hiccup (vec (concat [:div.md attr] (rest (m2h/parse stg))))] (print-when [:md] :MD hiccup) hiccup)) ;;; Fix this. First 'refer :all' from re-com.core. Then use ns-publics ;;; and deref vars in the resulting map (to get the function objects) ;;; to make re-com-xref. (def re-com-xref (into {} (mapv vector '[h-box v-box box border gap line h-split v-split scroller flex-child-style button row-button md-icon-button md-circle-icon-button info-button input-text input-password input-textarea label title hyperlink-href p single-dropdown selection-list checkbox radio-button slider progress-bar throbber horizontal-bar-tabs vertical-bar-tabs modal-panel popover-content-wrapper popover-anchor-wrapper filter-choices-by-keyword single-dropdown-args-desc datepicker datepicker-dropdown md] [h-box v-box box border gap line h-split v-split scroller flex-child-style button row-button md-icon-button md-circle-icon-button info-button input-text input-password input-textarea label title hyperlink-href p single-dropdown selection-list checkbox radio-button slider progress-bar throbber horizontal-bar-tabs vertical-bar-tabs modal-panel popover-content-wrapper popover-anchor-wrapper filter-choices-by-keyword single-dropdown-args-desc datepicker datepicker-dropdown md]))) (defn xform-recom ([x k v & kvs] (let [kvs (->> kvs (partition-all 2) (map vec))] (xform-recom x (into re-com-xref (cons [k v] kvs))))) ([x kvs] (let [xlate-cb (-> :symxlate-cb get-adb first)] (sp/transform sp/ALL (fn[v] (cond (coll? v) (xform-recom v kvs) (symbol? v) (let [v (-> v name symbol)] (get kvs v (xlate-cb v))) :else (get kvs v v))) x)))) (declare get-cur-tab) (defn get-vspec ([vid] (get-vspec (get-cur-tab :id) vid)) ([tid vid] (sp/select-one [sp/ATOM :vspecs sp/ATOM tid vid] app-db))) (defn update-vspecs ([vid vspec] (update-vspecs (get-cur-tab :id) vid vspec)) ([tid vid vspec] (sp/setval [sp/ATOM :vspecs sp/ATOM tid vid] vspec app-db))) (defn get-vgview ([vid] (get-vgview (get-cur-tab :id) vid)) ([tid vid] (sp/select-one [sp/ATOM :vgviews sp/ATOM tid vid] app-db))) (defn get-vgviews ([] (sp/select-any [sp/ATOM :vgviews sp/ATOM] app-db)) ([tid] (sp/select-any [sp/ATOM :vgviews sp/ATOM tid] app-db))) (defn update-vgviews ([vid vgview] (update-vgviews (get-cur-tab :id) vid vgview)) ([tid vid vgview] (sp/setval [sp/ATOM :vgviews sp/ATOM tid vid] vgview app-db))) (defn del-vgviews ([] (sp/setval [sp/ATOM :vgviews sp/ATOM] {} app-db) true) ([tid] (sp/setval [sp/ATOM :vgviews sp/ATOM tid] sp/NONE app-db) true) ([tid vid] (sp/setval [sp/ATOM :vgviews sp/ATOM tid vid] sp/NONE app-db) true)) (defn get-tab-field ([tid] (sp/select-one [sp/ATOM :tabs :active sp/ATOM sp/ALL #(= (% :id) tid)] app-db)) ([tid field] (sp/select-one [sp/ATOM :tabs :active sp/ATOM sp/ALL #(= (% :id) tid) field] app-db))) (defn update-tab-field [tid field value] (sp/setval [sp/ATOM :tabs :active sp/ATOM sp/ALL #(= (% :id) tid) field] value app-db)) (defn get-tab-body [id] (select-keys (sp/select-one [sp/ATOM :tabs :active sp/ATOM sp/ALL #(= (% :id) id)] app-db) [:id :opts :specs])) (defn get-cur-tab ([] (get-tab-field (deref (get-adb [:tabs :current])))) ([field] (get-tab-field (deref (get-adb [:tabs :current])) field))) (defn set-cur-tab [tid] (sp/setval [sp/ATOM :tabs :current sp/ATOM] tid app-db)) (defn update-cur-tab [field value] (update-tab-field (deref (get-adb [:tabs :current])) field value)) (defn tab-pos [tid] (let [tabvec (sp/select [sp/ATOM :tabs :active sp/ATOM sp/ALL] app-db) cnt (count tabvec)] [(sp/select-one [sp/INDEXED-VALS #(-> % second :id (= tid)) sp/FIRST] tabvec) cnt tabvec])) (defn move-tab [tid dir] (assert (#{:left :right} dir) (str "dir '" dir "' must be :left or :right")) (let [tabval (get-tab-field tid) [idx cnt curtabs] (tab-pos tid) f (cond (and (= dir :left) (= idx 0)) :nop (and (= dir :right) (= idx (dec cnt))) :nop (= dir :left) dec (= dir :right) inc)] (when (not= f :nop) (let [v (sp/setval [sp/ALL #(= (% :id) tid)] hc/RMV curtabs) v (sp/setval (sp/before-index (f idx)) tabval v)] (sp/setval [sp/ATOM :tabs :active sp/ATOM] v app-db) v)))) (defn add-tab [tabval] (sp/setval [sp/ATOM :tabs :active sp/ATOM sp/AFTER-ELEM] tabval app-db) (set-cur-tab (tabval :id))) (defn replace-tab [tid newdef] (sp/setval [sp/ATOM :tabs :active sp/ATOM sp/ALL #(= (% :id) tid)] newdef app-db)) (defn del-tab [tid] (let [curid ((get-cur-tab) :id) cnt (count (sp/select [sp/ATOM :tabs :active sp/ATOM sp/ALL] app-db))] (sp/setval [sp/ATOM :tabs :active sp/ATOM sp/ALL #(= (% :id) tid)] hc/RMV app-db) (when (and (> cnt 0) (= tid curid)) (set-cur-tab (-> (sp/select [sp/ATOM :tabs :active sp/ATOM sp/ALL] app-db) first :id))))) (defn active-tabs [] (printchan :ACTIVE-TABS " called") (let [bar-cursor (rgt/cursor app-db [:tabs :bars]) curtab (get-cur-tab)] (if curtab @bar-cursor [:p]))) (defn header [msg] [title2 msg :class "title" ;;:margin-top "2px" :margin-bottom "1px" #_:style #_{:background-color "lightgreen"}]) (defn visualize [spec elem] (print-when [:vis :vis] :SPEC spec) (when spec (let [tid (-> spec :usermeta :tab :id) vid (-> spec :usermeta :vid) _ (printchan :VID vid) vopts (-> spec :usermeta :opts) vmode (get vopts :mode) default-hover (if (= vmode "vega-lite") false js/undefined) spec (clj->js spec) opts {:renderer (get vopts :renderer "canvas") :mode "vega" :hover (get vopts :hover default-hover) :defaultStyle true :scaleFactor (get vopts :scaleFactor 1) :actions {:export (get vopts :export false), :source (get vopts :source false), :editor (get vopts :editor false), :compiled false}} vega (if (= vmode "vega-lite") (->> spec js/vegaLite.compile .-spec) spec)] (-> (js/vegaEmbed elem vega (clj->js opts)) (.then (fn [res] (when vid (update-vgviews tid vid res.view)) #_(js/vegaTooltip.vega res.view spec) #_(js/vegaTooltip.vegaLite res.view spec))) (.catch (fn [err] (printchan err))))))) (defn vgl "Reagent component to render vega/vega-lite visualizations." [spec] (printchan "VGL called") (rgt/create-class {:display-name "VGL" :component-did-mount (fn [comp] (let [argv (rest (rgt/argv comp))] (printchan "Did-Mount: called") (visualize spec (rgt/dom-node comp)))) :component-did-update (fn [comp old-useless-argv] (printchan "Did-Update: called") ;; OK, this is a mess. 'new-useful-argv' is really only useful ;; in conjunction with old-useless-argv. Even then you may not ;; really get the data / args you want/need/expect. Only the ;; new-argv-2nd-way gives the complete argument set. (let [new-useful-argv (rgt/children comp) new-argv-2nd-way (rgt/argv comp) ; first elt some fn?!? new-spec (-> new-argv-2nd-way rest first)] (print-when [:vis :vgl :update] :ARGV1 new-useful-argv :ARGV2 (rest new-argv-2nd-way)) (visualize new-spec (rgt/dom-node comp)))) :reagent-render (fn [spec] (let [id (or (-> spec :usermeta :vid) (gensym "vid-")) elt (js/document.getElementById id)] (if elt elt [box :attr {:id id} :child [:div]])))})) (defn frameit [spec frame] (let [frame-cb (-> :frame-cb get-adb first) [spec frame] (frame-cb spec frame)] [v-box :attr {:id (frame :frameid)} :gap "10px" :children [[h-box :gap "5px" :children (frame :top)] [h-box :gap "5px" :children (if spec [[h-box :children (frame :left)] [vgl spec] [h-box :children (frame :right)]] [[h-box :children (frame :left)] [h-box :children (frame :right)]])] [h-box :gap "5px" :children (frame :bottom)]]])) (defn vis-list [tabid spec-frame-pairs opts] (let [layout (if (= (get-in opts [:order]) :row) h-box v-box) lgap (if (= layout h-box) (opts :cgap) (opts :rgap)) eltnum (get-in opts [:eltsper] 3) numspecs (count spec-frame-pairs) spec-chunks (->> spec-frame-pairs (partition-all eltnum) (mapv vec))] (printchan "VIS-LIST : " numspecs) (for [sub-pairs spec-chunks] [layout :size (get-in opts [:size] "auto") :gap lgap :children (for [[spec frame] sub-pairs] (do #_(js-delete spec "usermeta") (print-when [:vis :vis-list] :NSPEC spec frame) (frameit spec frame)))]))) (declare make-spec-frame-pairs) (defn add-to-tab-body [id picframe & {:keys [at position opts] :or {at :end position :after opts {}}}] (let [tbdy (get-tab-body id) opts (merge (tbdy :opts) opts) specs (tbdy :specs) pos (cond (= at :beg) 0 (= at :end) (dec (count specs)) :else (->> specs (keep-indexed (fn[idx item] (when (-> item :usermeta :frame :fid (= at)) idx))) first)) pos (if (= position :after) (inc pos) pos) newspecs (concat (take pos specs) [picframe] (drop pos specs)) s-f-pairs (make-spec-frame-pairs id opts newspecs)] (update-tab-field id :opts opts) (update-tab-field id :specs newspecs) (update-tab-field id :compvis (vis-list id s-f-pairs opts)) id)) (defn remove-from-tab-body [id fid] (let [tbdy (get-tab-body id) opts (tbdy :opts) specs (tbdy :specs) specs (remove #(-> % :usermeta :frame :fid (= fid)) specs) s-f-pairs (make-spec-frame-pairs id opts specs)] (update-tab-field id :specs specs) (update-tab-field id :compvis (vis-list id s-f-pairs opts)) id)) (defn update-frame [tid fid element content] (let [tbdy (get-tab-body tid) opts (tbdy :opts) specs (tbdy :specs) pos (->> specs (keep-indexed (fn[idx item] (when (-> item :usermeta :frame :fid (= fid)) idx))) first) newspec (if (= element :frame) content (assoc-in (nth specs pos) [:usermeta :frame element] content)) newspecs (concat (take pos specs) [newspec] ; splice in the updated spec (drop (inc pos) specs)) s-f-pairs (make-spec-frame-pairs tid opts newspecs)] (update-tab-field tid :specs newspecs) (update-tab-field tid :compvis (vis-list tid s-f-pairs opts)) tid)) ;;; The following two muck with the DOM directly and are not ;;; recommended. Probably should remove altogether, but leaving for ;;; right now. (defn get-frame-elements [fid] (let [fid (name fid) frame (js/document.getElementById fid) top (aget frame.childNodes 0) bottom (aget frame.childNodes 4) middle (aget frame.childNodes 2) left (aget middle.childNodes 0) vis (aget middle.childNodes 2) right (aget middle.childNodes 4)] {:top top, :bottom bottom, :left left, :right right, :vis vis})) (defn update-frame-element [fid element content] (let [fid (name fid) frame-element ((get-frame-elements fid) element) component content frame-cb (-> :frame-cb get-adb first)] (rgt/render component frame-element) (frame-cb {} {:frameid fid}))) (defn hanami [] (if-let [tabval (get-cur-tab)] (let [tabid (tabval :id) specs (tabval :specs) compvis (tabval :compvis) opts (tabval :opts (get-adb [:main :opts :tab])) frame-cb (-> :frame-cb get-adb first)] (cond compvis (do (printchan "hanami called - has compvis") (frame-cb) compvis) specs (let [spec-frame-pairs (tabval :spec-frame-pairs) ;;_ (printchan :SCPAIRS spec-frame-pairs) compvis (vis-list tabid spec-frame-pairs opts)] (printchan "hanami called - making compvis") (update-cur-tab :compvis compvis) compvis) :else [[:img {:src (get-adb [:main :img])}]])) [[:img {:src (get-adb [:main :img])}]])) (defn tabs [] (printchan "TABS called ...") (let [tabval (get-cur-tab) opts (or (and tabval (tabval :opts)) (get-adb [:main :opts :tab])) id (or (and tabval (str (name (tabval :id)) "-body")) "xHx") wrapfn (or (opts :wrapfn) identity) extfn (get-in opts [:extfn]) size (get-in opts [:size] "auto") order (get-in opts [:order] :col) layout (if (= order :row) v-box h-box) lgap (if (= layout v-box) (opts :rgap) (opts :cgap))] (printchan :OPTS opts) (if extfn (extfn tabval) (wrapfn [layout :attr {:id id} :size size :gap lgap :children (hanami)])))) (defn hanami-main [] (printchan "Hanami-main called ...") (let [inst-cursor (rgt/cursor app-db [:instrumentor]) instrumentor (first @inst-cursor) hd-cursor (rgt/cursor app-db [:header]) header (first @hd-cursor)] [v-box :gap "10px" :children [[v-box :gap "3px" :children [[header] [h-box :align :start :max-height "30px" :children [[gap :size "15px"] [active-tabs]]]]] [line] [tabs]]])) ;;; Messaging ---------------------------------------------------------------- (defn get-ws [] (->> (get-ddb []) keys (filter #(-> % type (= js/WebSocket))) first)) (defn get-chan [] (let [ws (get-ws) ch (when ws (get-ddb [ws :chan]))] ch)) ;; Send server msg (defn app-send [msg] (printchan "app-send: DEPRECATED, use 'send-msg'") (cli/send-msg (get-ws) msg)) (defn send-msg ([msg] (print-when [:msg :send] "Sending msg " msg) (cli/send-msg (get-ws) msg)) ([op data] (send-msg {:op op :data data}))) (defn merge-old-new-opts [oldopts newopts] (cond (and oldopts newopts) (if (or (oldopts :tab) (oldopts :vgl)) (sp/transform [(sp/submap [:vgl :tab]) sp/MAP-VALS] #(merge % newopts) oldopts) (merge oldopts newopts)) oldopts oldopts newopts newopts :else (get-adb [:main :opts]))) ;; Stop app (defn app-stop [] (let [ws (get-ws) ch (get-chan)] (when ch (go (async/>! ch {:op :stop :payload {:ws ws :cause :userstop}}))))) (defn init-tabs [] (update-adb [:tabs] (let [cur-ratom (rgt/atom nil) tabs-ratom (rgt/atom [])] {:current cur-ratom :active tabs-ratom :bars [horizontal-bar-tabs :model cur-ratom :tabs tabs-ratom :on-change #(reset! cur-ratom %)]}))) (defn register [{:keys [uid title logo img opts]}] (printchan "Registering " uid) (update-adb [:main :uid] uid [:main :title] title [:main :logo] logo [:main :img] img [:main :opts] (hc/xform opts) [:main :session-name] (rgt/atom "") [:vgl-as-vg] :rm [:vgviews] (atom {}) ; This should not have any reactive update [:vspecs] (rgt/atom {})) (init-tabs) (rgt/render [hanami-main] (get-adb :elem) #_(js/document.querySelector "#app"))) (defn update-opts [{:keys [main tab opts]}] (if main (update-adb [:main :opts] (merge-old-new-opts (get-adb [:main :opts]) opts)) (do (update-tab-field tab :opts (merge-old-new-opts (get-tab-field tab :opts) opts)) (update-tab-field tab :compvis sp/NONE)))) (defn empty-chart? [spec] (and (-> spec keys count (= 1)) (-> spec keys first (= :usermeta)))) (defn make-tabdefs [specs] (let [grps (group-by #(->> % :usermeta :tab :id) (com/ev specs))] (mapv (fn[[id specs]] (let [tab (->> specs first :usermeta :tab)] (assoc tab :specs (mapv (fn[spec] (dissoc spec :tab)) specs)))) grps))) (defn make-spec-frame-pairs [tid opts specs] (let [instrumentor (-> :instrumentor get-adb first)] (mapv #(do (when-let [vid (get-in % [:usermeta :vid])] (update-vspecs vid %)) (vector (if (empty-chart? %) nil %) (instrumentor {:tabid tid :spec % :opts opts}))) specs))) (defn update-tabs [specs] (let [tabdefs (make-tabdefs specs)] (mapv (fn [{:keys [id label opts specs] :as newdef}] (let [tid id oldef (get-tab-field tid) specs (when specs (->> specs com/ev)) main-opts (get-adb [:main :opts :tab]) instrumentor (-> :instrumentor get-adb first) spec-frame-pairs (make-spec-frame-pairs tid opts specs)] (if (not oldef) (add-tab (assoc newdef :opts (merge-old-new-opts main-opts opts) :spec-frame-pairs spec-frame-pairs :specs specs)) (let [oldopts (or (oldef :opts) main-opts)] (replace-tab tid {:id tid :label (or label (get-tab-field tid :label)) :opts (merge-old-new-opts oldopts opts) :spec-frame-pairs spec-frame-pairs :specs specs}))))) tabdefs))) (defn update-data "Originally meant as general updater of vis plot/chart data values. But to _render_ these, requires knowledge of the application pages/structure. So, this is not currently used. If we can figure out Vega chageSets and how they update, we may be able to make this a general op in Hanami." [data-maps app-fn] (printchan :UPDATE-DATA data-maps) (app-fn (mapv (fn [{:keys [usermeta data]}] (let [vid (usermeta :vid) spec (dissoc (get-vspec vid) :data)] (assoc-in spec [:data :values] data))) data-maps))) (defmulti user-msg :op) (defmethod user-msg :default [msg] (printchan msg)) (defn on-msg [ch ws hanami-msg] (let [{:keys [op data]} hanami-msg] (update-ddb [ws :line-info :rcvcnt] inc) (case op :register (do (register data) (user-msg {:op :app-init :data data})) :opts (update-opts data) :tabs (update-tabs data) #_:data #_(update-data data) :specs (let [{:keys [tab specs]} data] (update-tab-field tab :specs specs)) (user-msg {:op op :data data :ws ws :ch ch})))) (defn on-open [ch ws] (update-ddb ws {:chan ch, :line-info {:rcvcnt 0, :sntcnt 0, :errcnt 0}})) (defn message-dispatch [ch op payload] (case op :open (let [ws payload] (print-when [:msg :open] :CLIENT :open :ws ws) (on-open ch ws)) :close (let [{:keys [ws code reason]} payload] (print-when :CLIENT :RMTclose :payload payload) (go (async/put! ch {:op :stop :payload {:ws ws :cause :rmtclose}}))) :msg (let [{:keys [ws data]} payload] (print-when [:msg :msg] :CLIENT :msg :payload payload) (on-msg ch ws data)) :bpwait (let [{:keys [ws msg encode]} payload] (print-when [:msg :bpwait] :CLIENT "Waiting to send msg " msg) (go (async/<! (async/timeout 5000))) (print-when [:msg :bpwait] :CLIENT "Trying resend...") (cli/send-msg ws msg :encode encode)) :bpresume (print-when [:msg :bpresume] :CLIENT "BP Resume " payload) :sent (let [{:keys [ws msg]} payload] (print-when [:msg :sent] :CLIENT "Sent msg " msg) (update-ddb [ws :line-info :lastsnt] msg, [ws :line-info :sntcnt] inc)) :stop (let [{:keys [ws cause]} payload] (print-when [:msg :stop] :CLIENT "Stopping reads... Cause " cause) (cli/close-connection ws) (update-ddb ws :rm)) :error (let [{:keys [ws err]} payload] (printchan :CLIENT :error :payload payload) (update-ddb [ws :line-info :errcnt] inc)) (printchan :CLIENT :WTF :op op :payload payload))) (defn connect [host port] (go (let [uri (str "ws://" host ":" port "/ws") ch (async/<! (cli/open-connection uri))] (printchan "Opening client, reading msgs from " ch) (loop [msg (<! ch)] (let [{:keys [op payload]} msg] (message-dispatch ch op payload) (when (not= op :stop) (recur (<! ch)))))))) (defn set-session-name [name] (let [old-uid (get-adb [:main :uid]) name (if (= name "") (old-uid :name) name)] (sp/setval [sp/ATOM :main :session-name sp/ATOM] name app-db) (when (not= name (old-uid :name)) (update-adb [:main :uid :name] name) (send-msg {:op :set-session-name :data {:uid old-uid :new-name name}})))) (defn session-input [] (if (not= "" (sp/select-one [sp/ATOM :main :session-name sp/ATOM] app-db)) [:p] [input-text :model (get-adb [:main :session-name]) :on-change set-session-name :placeholder (get-adb [:main :uid :name]) :width "100px"])) (defn default-header-fn [] [h-box :gap "10px" :max-height "30px" :children [[gap :size "5px"] [:img {:src (get-adb [:main :logo])}] [title :level :level3 :label [:span.bold (get-adb [:main :title])]] #_[gap :size "5px"] [session-input] [gap :size "5px"] [title :level :level3 :label [:span.bold (get-adb [:main :uid :name])]] [gap :size "30px"]]]) (defn default-frame-cb ([]) ([spec frame] [spec frame])) (defn get-default-frame [] {:top [], :bottom [], :left [[box :size "0px" :child ""]], :right [[box :size "0px" :child ""]]}) (defn make-frame [udata curframe] (let [frameid (get-in udata [:frame :fid] (gensym "frame-"))] (merge (if (udata :frame) (let [default-frame (get-default-frame) framedef (udata :frame) frame-sides (dissoc framedef :fid :at :pos)] (print-when [:frames :make] :Frame-Maker frame-sides curframe) (update-adb [:dbg :frame] (->> (keys frame-sides) (reduce (fn[F k] (assoc F k (xform-recom (frame-sides k) re-com-xref))) default-frame))) (get-adb [:dbg :frame])) (get-default-frame)) (assoc curframe :frameid frameid)))) (defn default-instrumentor-fn [{:keys [tabid spec opts]}] (let [udata (spec :usermeta)] (print-when [:instrumentor] chan :UDATA udata :OPTS opts)) {}) (defn make-instrumentor [userfn] (fn [{:keys [tabid spec opts] :as m}] (make-frame (spec :usermeta) (userfn m)))) (defn start [& {:keys [elem host port header-fn instrumentor-fn frame-cb symxlate-cb] :or {host js/location.hostname header-fn default-header-fn instrumentor-fn default-instrumentor-fn frame-cb default-frame-cb symxlate-cb identity}}] (let [instfn (make-instrumentor instrumentor-fn)] (printchan "Element 'app' available, port " port) (app-stop) (update-adb :elem elem :symxlate-cb [symxlate-cb] :frame-cb [frame-cb] :instrumentor [instfn] :header [header-fn]) (connect host port))) (defn sv! "Mirror of server side hmi/sv! Here no need for messages. Just need to call `update-tabs` on the vector of vg/vgl-maps." [vgl-maps] (let [vgl-maps (com/ev vgl-maps)] (update-tabs vgl-maps) true)) (comment ;; Rich Comment!! ;; Always run this setup init for any testing (do (hc/update-defaults :USERDATA {:tab {:id :TID, :label :TLBL, :opts :TOPTS} :frame {:top :TOP, :bottom :BOTTOM, :left :LEFT, :right :RIGHT :fid :FID} :opts :OPTS :vid :VID, :msgop :MSGOP, :session-name :SESSION-NAME} :MSGOP :tabs, :SESSION-NAME "Exploring" :TID :expl1, :TLBL #(-> :TID % name cljstr/capitalize) :OPTS (hc/default-opts :vgl), :TOPTS (hc/default-opts :tab)) (defn bar-slider-fn [tid val] (let [tabval (get-tab-field tid) spec-frame-pairs (tabval :spec-frame-pairs)] (printchan "Slider update " val) (update-tab-field tid :compvis nil) (update-tab-field tid :spec-frame-pairs (mapv (fn[[spec frame]] (let [cljspec spec data (mapv (fn[m] (assoc m :b (+ (m :b) val))) (get-in cljspec [:data :values])) newspec (assoc-in cljspec [:data :values] data)] [newspec frame])) spec-frame-pairs)))) (defn test-instrumentor [{:keys [tabid spec opts]}] (printchan "Test Instrumentor called" :TID tabid #_:SPEC #_spec) (let [cljspec spec udata (cljspec :usermeta) default-frame (get-default-frame)] (update-adb [:udata] udata) (cond (not (map? udata)) [] (udata :slider) (let [sval (rgt/atom "0.0")] (printchan :SLIDER-INSTRUMENTOR) {:top (xform-recom (udata :slider) :m1 sval :oc1 #(do (bar-slider-fn tabid %) (reset! sval (str %))) :oc2 #(do (bar-slider-fn tabid (js/parseFloat %)) (reset! sval %)))}) (udata :test2) {:right [[gap :size "10px"] [v-box :children [[label :label "Select a demo"] [single-dropdown :choices (udata :test2) :on-change #(printchan "Dropdown: " %) :model nil :placeholder "Hi there" :width "100px"]]]]} :else {} ))) (start :elem (js/document.querySelector "#app") :instrumentor-fn test-instrumentor :port 3003)) ;; ======================================================================= ;; Testing new incremental tab bodies and user wrapping function support ;; Create a tab that includes a user defined WRAPFN (add-tab {:id :dists :label "Dists" :specs [] :opts {:order :row, :eltsper 1, :size "auto" :wrapfn (fn[hcomp] [h-split :panel-1 [box :child [input-textarea :model " 1234567890123456789012345678901234567890123456789012345678901234567890123456789" :width "650px" :rows 40 :on-change identity]] :panel-2 [scroller :max-height "800px" :max-width "1200px" :align :start :child hcomp] :initial-split "33%" :width "2048px"])}}) ;; Add some page/section title text (do (add-to-tab-body :dists (hc/xform ht/empty-chart :FID :dtitle :TOP '[[gap :size "50px"] [md "# Example Interactive Document Creation"]])) :done) ;; Render a graphic in it (add-to-tab-body :dists (hc/xform ht/bar-chart :TITLE "Top headline phrases" :TID :dists :FID :dhline :ELTSPER 1 :X :x-value :Y :y-value :YTYPE "nominal" :DATA [{:x-value 8961 :y-value "will make you"} {:x-value 4099 :y-value "this is why"} { :x-value 3199 :y-value "can we guess"} {:x-value 2398 :y-value "only X in"} {:x-value 1610 :y-value "the reason is"} {:x-value 1560 :y-value "are freaking out"} {:x-value 1425 :y-value "X stunning photos"} {:x-value 1388 :y-value "tears of joy"} {:x-value 1337 :y-value "is what happens"} {:x-value 1287 :y-value "make you cry"}])) ;; Add empty picture frame with all elements as MD (do (add-to-tab-body :dists (hc/xform ht/empty-chart :FID :dwrup1 :TOP '[[gap :size "200px"][md "# Header top"]] :BOTTOM '[[gap :size "200px"] [md "# Header bottom"]] :LEFT '[[gap :size "50px"] [md "### Header left"]] :RIGHT '[[md "### Header right"]])) :done) ;; Make some distribution data (def obsdist (let [obs [[0 9] [1 78] [2 305] [3 752] [4 1150] [5 1166] [6 899] [7 460] [8 644] [9 533] [10 504]] totcnt (->> obs (mapv second) (apply +)) pdist (map (fn[[k cnt]] [k (double (/ cnt totcnt))]) obs)] pdist)) ;; Add a picture to the tab (do (add-to-tab-body :dists (hc/xform ht/layer-chart :TID :dists :FID :dex1 :TITLE "A Real (obvserved) distribution with incorrect simple mean" :HEIGHT 400 :WIDTH 450 :LAYER [(hc/xform ht/bar-layer :XTITLE "Count" :YTITLE "Probability") (hc/xform ht/xrule-layer :AGG "mean")] :DATA (mapv (fn[[x y]] {:x x :y y :m 5.7}) obsdist))) :done) ;; Add some more 'writeup' (do (add-to-tab-body :dists (hc/xform ht/empty-chart :FID :dwrup2 :BOTTOM '[[gap :size "50px"] [md "# Fixed distribution Here we have corrected the mean by properly including item weights"]])) :done) (do (add-to-tab-body :dists (hc/xform ht/layer-chart :TID :dists :FID :dex2 :TITLE "The same distribution with correct weighted mean" :HEIGHT 400 :WIDTH 450 :LAYER [(hc/xform ht/bar-layer :XTITLE "Count" :YTITLE "Probability") (hc/xform ht/xrule-layer :X "m")] :DATA (mapv (fn[[x y]] {:x x :y y :m 5.7}) obsdist))) :done) ;; ======================================================================= ;; Direct noodling on the DOM - not recommended as subverts data flow of ;; Reagent/React (let [body (js/document.getElementById "expl1-body") lastchild body.lastChild div (js/document.createElement "div") _ (set! (.-id div) "mymd") component [h-box :children [[gap :size "20px" :width "20px"] [md " # Header 1 ## Header 2 ### Header 3, following is list * One * Two * Three"]]]] (.appendChild lastchild div) (rgt/render component lastchild.lastChild) (js/console.log lastchild) (js/console.log lastchild.lastChild)) (let [body (js/document.getElementById "expl1-body") lastchild body.lastChild] (js/console.log body) (js/console.log lastchild)) (let [body (js/document.getElementById "expl1-body") lastchild body.lastChild] (.appendChild lastchild (js/document.createElement "div")) (js/console.log lastchild) (js/console.log lastchild.lastChild)) (let [body (js/document.getElementById "expl1-body") lastchild body.lastChild component ""] (.remove lastchild.lastChild) (js/console.log lastchild) (js/console.log lastchild.lastChild)) (let [mymd (js/document.getElementById "mymd")] #_(.removeChild mymd.parentNode mymd) (.remove mymd)) (let [body (js/document.getElementById "expl1-body") lastchild body.lastChild mymd (js/document.getElementById "mymd")] (.insertBefore mymd lastchild)) ;; ======================================================================= ;; Old original db messing and testing of adding / updating tabs (get-adb [:test1 :sval]) (update-adb [:main :uid :name] "Hello") (add-tab {:id :p1 :label "BarChart" :opts {:order :col :eltsper 2 :size "none"} :specs [js/vglspec]}) (add-tab {:id :p2 :label "BarChart/Mean" :specs [js/vglspec3]}) (add-tab {:id :p3 :label "MultiChart" :specs [js/vglspec js/vglspec2 js/vglspec3 js/vglspec]}) (add-tab {:id :ttest :label "ToolTip" :specs js/ttest}) (add-tab {:id :geotest :label "GeoTest" :specs js/geotest}) (update-tab-field :geotest :specs js/geotest) (add-tab {:id :px :label "MultiChartSVG" :opts (merge-old-new-opts (get-adb [:defopts :tab]) {:size "auto"}) :specs [js/vglspec js/vglspec2 js/vglspec3 js/vglspec]}) (get-adb :tabs) {:op :tabs :data [{:id :px :label "MultiChartSVG" :opts {:size "auto"} :specs [js/vglspec js/vglspec2 js/vglspec3 js/vglspec]}]} )
true
(ns aerial.hanami.core (:require [cljs.core.async :as async :refer (<! >! put! chan) :refer-macros [go go-loop]] [clojure.string :as cljstr] [com.rpl.specter :as sp] [aerial.hanasu.client :as cli] [aerial.hanasu.common :as com] [aerial.hanami.md2hiccup :as m2h] [aerial.hanami.common :as hc] [aerial.hanami.templates :as ht] ;; Vega & Vega-Lite [cljsjs.vega] [cljsjs.vega-lite] [cljsjs.vega-embed] [cljsjs.vega-tooltip] [reagent.core :as rgt] [re-com.core :as rcm :refer [h-box v-box box border gap line h-split v-split scroller button row-button md-icon-button md-circle-icon-button info-button input-text input-password input-textarea label title hyperlink-href p single-dropdown selection-list checkbox radio-button slider progress-bar throbber horizontal-bar-tabs vertical-bar-tabs modal-panel popover-content-wrapper popover-anchor-wrapper datepicker datepicker-dropdown] :refer-macros [handler-fn]] [re-com.box :refer [flex-child-style]] [re-com.dropdown :refer [filter-choices-by-keyword single-dropdown-args-desc]] [aerial.hanami.utils :refer [title2 href]] )) (def print-chan (async/chan 10)) (go-loop [msg (async/<! print-chan)] (js/console.log (print-str msg)) (recur (async/<! print-chan))) (defn printchan [& args] (async/put! print-chan (clojure.string/join " " args))) ;;; Need a _data_ database :/ ;;; ;;; This is needed to handle state NOT associated with component state ;;; or updates. In particular, to avoid triggering their renderings on ;;; completely irrelevant changes. ;;; ;;; First and foremost, no state _directly associated_ with the ;;; messaging system should have any impact on components!! ;;; (defonce data-db (atom {:dbg {}})) (defn update-ddb ([] (com/update-db data-db {})) ([keypath vorf] (com/update-db data-db keypath vorf)) ([kp1 vof1 kp2 vof2 & kps-vs] (apply com/update-db data-db kp1 vof1 kp2 vof2 kps-vs))) (defn get-ddb ([] (com/get-db data-db [])) ([key-path] (com/get-db data-db key-path))) (defonce app-db (rgt/atom {:dbg {}})) (def default-opts {:vgl {:export true :renderer "canvas" #_"svg" :mode "vega-lite" #_vega} :tab {:order :col :eltsper 2 :size "none"}}) (declare print-when) (defn update-adb ([] (com/update-db app-db :default-opts default-opts)) ([keypath vorf] #_(printchan [:db :update] "UPDATE-ADB " keypath vorf) (com/update-db app-db keypath vorf)) ([kp1 vof1 kp2 vof2 & kps-vs] (apply com/update-db app-db kp1 vof1 kp2 vof2 kps-vs))) (defn get-adb ([] (com/get-db app-db [])) ([key-path] #_(printchan [:db :get]"GET-ADB " key-path) (com/get-db app-db key-path))) (let [id (atom 0)] (defn next-key [] (str "PI:KEY:<KEY>END_PI (swap! id inc)))) (defn set-dbg [dbg-path on-off] (let [dbg-path (com/ev dbg-path) path (->> dbg-path (concat [:dbg]) vec)] (update-adb path on-off))) (defn dbgon [dbg-path] (set-dbg dbg-path true)) (defn dbgoff [dbg-path] (set-dbg dbg-path false)) (defn dbg? [dbg-path] (let [dbg-path (com/ev dbg-path) path (->> dbg-path (concat [:dbg]) vec)] (get-adb path))) (defn print-when [dbg-path & args] (when (dbg? dbg-path) (apply printchan args))) (defn md "Markdown to Hiccup with implicit support for handling LaTex via MathJax. Note: MathJax is _not_ supported in Hanami as it " [ & stg] (let [base-style {:flex "none", :width "450px", :min-width "450px"} x (first stg) stg (cljstr/join "\n" (if (map? x) (rest stg) stg)) stg (cljstr/replace stg "\\(" "\\\\(") stg (cljstr/replace stg "\\)" "\\\\)") style (->> (if (map? x) (x :style) {}) (merge base-style)) attr (if (map? x) (assoc x :style style) {:style style}) hiccup (vec (concat [:div.md attr] (rest (m2h/parse stg))))] (print-when [:md] :MD hiccup) hiccup)) ;;; Fix this. First 'refer :all' from re-com.core. Then use ns-publics ;;; and deref vars in the resulting map (to get the function objects) ;;; to make re-com-xref. (def re-com-xref (into {} (mapv vector '[h-box v-box box border gap line h-split v-split scroller flex-child-style button row-button md-icon-button md-circle-icon-button info-button input-text input-password input-textarea label title hyperlink-href p single-dropdown selection-list checkbox radio-button slider progress-bar throbber horizontal-bar-tabs vertical-bar-tabs modal-panel popover-content-wrapper popover-anchor-wrapper filter-choices-by-keyword single-dropdown-args-desc datepicker datepicker-dropdown md] [h-box v-box box border gap line h-split v-split scroller flex-child-style button row-button md-icon-button md-circle-icon-button info-button input-text input-password input-textarea label title hyperlink-href p single-dropdown selection-list checkbox radio-button slider progress-bar throbber horizontal-bar-tabs vertical-bar-tabs modal-panel popover-content-wrapper popover-anchor-wrapper filter-choices-by-keyword single-dropdown-args-desc datepicker datepicker-dropdown md]))) (defn xform-recom ([x k v & kvs] (let [kvs (->> kvs (partition-all 2) (map vec))] (xform-recom x (into re-com-xref (cons [k v] kvs))))) ([x kvs] (let [xlate-cb (-> :symxlate-cb get-adb first)] (sp/transform sp/ALL (fn[v] (cond (coll? v) (xform-recom v kvs) (symbol? v) (let [v (-> v name symbol)] (get kvs v (xlate-cb v))) :else (get kvs v v))) x)))) (declare get-cur-tab) (defn get-vspec ([vid] (get-vspec (get-cur-tab :id) vid)) ([tid vid] (sp/select-one [sp/ATOM :vspecs sp/ATOM tid vid] app-db))) (defn update-vspecs ([vid vspec] (update-vspecs (get-cur-tab :id) vid vspec)) ([tid vid vspec] (sp/setval [sp/ATOM :vspecs sp/ATOM tid vid] vspec app-db))) (defn get-vgview ([vid] (get-vgview (get-cur-tab :id) vid)) ([tid vid] (sp/select-one [sp/ATOM :vgviews sp/ATOM tid vid] app-db))) (defn get-vgviews ([] (sp/select-any [sp/ATOM :vgviews sp/ATOM] app-db)) ([tid] (sp/select-any [sp/ATOM :vgviews sp/ATOM tid] app-db))) (defn update-vgviews ([vid vgview] (update-vgviews (get-cur-tab :id) vid vgview)) ([tid vid vgview] (sp/setval [sp/ATOM :vgviews sp/ATOM tid vid] vgview app-db))) (defn del-vgviews ([] (sp/setval [sp/ATOM :vgviews sp/ATOM] {} app-db) true) ([tid] (sp/setval [sp/ATOM :vgviews sp/ATOM tid] sp/NONE app-db) true) ([tid vid] (sp/setval [sp/ATOM :vgviews sp/ATOM tid vid] sp/NONE app-db) true)) (defn get-tab-field ([tid] (sp/select-one [sp/ATOM :tabs :active sp/ATOM sp/ALL #(= (% :id) tid)] app-db)) ([tid field] (sp/select-one [sp/ATOM :tabs :active sp/ATOM sp/ALL #(= (% :id) tid) field] app-db))) (defn update-tab-field [tid field value] (sp/setval [sp/ATOM :tabs :active sp/ATOM sp/ALL #(= (% :id) tid) field] value app-db)) (defn get-tab-body [id] (select-keys (sp/select-one [sp/ATOM :tabs :active sp/ATOM sp/ALL #(= (% :id) id)] app-db) [:id :opts :specs])) (defn get-cur-tab ([] (get-tab-field (deref (get-adb [:tabs :current])))) ([field] (get-tab-field (deref (get-adb [:tabs :current])) field))) (defn set-cur-tab [tid] (sp/setval [sp/ATOM :tabs :current sp/ATOM] tid app-db)) (defn update-cur-tab [field value] (update-tab-field (deref (get-adb [:tabs :current])) field value)) (defn tab-pos [tid] (let [tabvec (sp/select [sp/ATOM :tabs :active sp/ATOM sp/ALL] app-db) cnt (count tabvec)] [(sp/select-one [sp/INDEXED-VALS #(-> % second :id (= tid)) sp/FIRST] tabvec) cnt tabvec])) (defn move-tab [tid dir] (assert (#{:left :right} dir) (str "dir '" dir "' must be :left or :right")) (let [tabval (get-tab-field tid) [idx cnt curtabs] (tab-pos tid) f (cond (and (= dir :left) (= idx 0)) :nop (and (= dir :right) (= idx (dec cnt))) :nop (= dir :left) dec (= dir :right) inc)] (when (not= f :nop) (let [v (sp/setval [sp/ALL #(= (% :id) tid)] hc/RMV curtabs) v (sp/setval (sp/before-index (f idx)) tabval v)] (sp/setval [sp/ATOM :tabs :active sp/ATOM] v app-db) v)))) (defn add-tab [tabval] (sp/setval [sp/ATOM :tabs :active sp/ATOM sp/AFTER-ELEM] tabval app-db) (set-cur-tab (tabval :id))) (defn replace-tab [tid newdef] (sp/setval [sp/ATOM :tabs :active sp/ATOM sp/ALL #(= (% :id) tid)] newdef app-db)) (defn del-tab [tid] (let [curid ((get-cur-tab) :id) cnt (count (sp/select [sp/ATOM :tabs :active sp/ATOM sp/ALL] app-db))] (sp/setval [sp/ATOM :tabs :active sp/ATOM sp/ALL #(= (% :id) tid)] hc/RMV app-db) (when (and (> cnt 0) (= tid curid)) (set-cur-tab (-> (sp/select [sp/ATOM :tabs :active sp/ATOM sp/ALL] app-db) first :id))))) (defn active-tabs [] (printchan :ACTIVE-TABS " called") (let [bar-cursor (rgt/cursor app-db [:tabs :bars]) curtab (get-cur-tab)] (if curtab @bar-cursor [:p]))) (defn header [msg] [title2 msg :class "title" ;;:margin-top "2px" :margin-bottom "1px" #_:style #_{:background-color "lightgreen"}]) (defn visualize [spec elem] (print-when [:vis :vis] :SPEC spec) (when spec (let [tid (-> spec :usermeta :tab :id) vid (-> spec :usermeta :vid) _ (printchan :VID vid) vopts (-> spec :usermeta :opts) vmode (get vopts :mode) default-hover (if (= vmode "vega-lite") false js/undefined) spec (clj->js spec) opts {:renderer (get vopts :renderer "canvas") :mode "vega" :hover (get vopts :hover default-hover) :defaultStyle true :scaleFactor (get vopts :scaleFactor 1) :actions {:export (get vopts :export false), :source (get vopts :source false), :editor (get vopts :editor false), :compiled false}} vega (if (= vmode "vega-lite") (->> spec js/vegaLite.compile .-spec) spec)] (-> (js/vegaEmbed elem vega (clj->js opts)) (.then (fn [res] (when vid (update-vgviews tid vid res.view)) #_(js/vegaTooltip.vega res.view spec) #_(js/vegaTooltip.vegaLite res.view spec))) (.catch (fn [err] (printchan err))))))) (defn vgl "Reagent component to render vega/vega-lite visualizations." [spec] (printchan "VGL called") (rgt/create-class {:display-name "VGL" :component-did-mount (fn [comp] (let [argv (rest (rgt/argv comp))] (printchan "Did-Mount: called") (visualize spec (rgt/dom-node comp)))) :component-did-update (fn [comp old-useless-argv] (printchan "Did-Update: called") ;; OK, this is a mess. 'new-useful-argv' is really only useful ;; in conjunction with old-useless-argv. Even then you may not ;; really get the data / args you want/need/expect. Only the ;; new-argv-2nd-way gives the complete argument set. (let [new-useful-argv (rgt/children comp) new-argv-2nd-way (rgt/argv comp) ; first elt some fn?!? new-spec (-> new-argv-2nd-way rest first)] (print-when [:vis :vgl :update] :ARGV1 new-useful-argv :ARGV2 (rest new-argv-2nd-way)) (visualize new-spec (rgt/dom-node comp)))) :reagent-render (fn [spec] (let [id (or (-> spec :usermeta :vid) (gensym "vid-")) elt (js/document.getElementById id)] (if elt elt [box :attr {:id id} :child [:div]])))})) (defn frameit [spec frame] (let [frame-cb (-> :frame-cb get-adb first) [spec frame] (frame-cb spec frame)] [v-box :attr {:id (frame :frameid)} :gap "10px" :children [[h-box :gap "5px" :children (frame :top)] [h-box :gap "5px" :children (if spec [[h-box :children (frame :left)] [vgl spec] [h-box :children (frame :right)]] [[h-box :children (frame :left)] [h-box :children (frame :right)]])] [h-box :gap "5px" :children (frame :bottom)]]])) (defn vis-list [tabid spec-frame-pairs opts] (let [layout (if (= (get-in opts [:order]) :row) h-box v-box) lgap (if (= layout h-box) (opts :cgap) (opts :rgap)) eltnum (get-in opts [:eltsper] 3) numspecs (count spec-frame-pairs) spec-chunks (->> spec-frame-pairs (partition-all eltnum) (mapv vec))] (printchan "VIS-LIST : " numspecs) (for [sub-pairs spec-chunks] [layout :size (get-in opts [:size] "auto") :gap lgap :children (for [[spec frame] sub-pairs] (do #_(js-delete spec "usermeta") (print-when [:vis :vis-list] :NSPEC spec frame) (frameit spec frame)))]))) (declare make-spec-frame-pairs) (defn add-to-tab-body [id picframe & {:keys [at position opts] :or {at :end position :after opts {}}}] (let [tbdy (get-tab-body id) opts (merge (tbdy :opts) opts) specs (tbdy :specs) pos (cond (= at :beg) 0 (= at :end) (dec (count specs)) :else (->> specs (keep-indexed (fn[idx item] (when (-> item :usermeta :frame :fid (= at)) idx))) first)) pos (if (= position :after) (inc pos) pos) newspecs (concat (take pos specs) [picframe] (drop pos specs)) s-f-pairs (make-spec-frame-pairs id opts newspecs)] (update-tab-field id :opts opts) (update-tab-field id :specs newspecs) (update-tab-field id :compvis (vis-list id s-f-pairs opts)) id)) (defn remove-from-tab-body [id fid] (let [tbdy (get-tab-body id) opts (tbdy :opts) specs (tbdy :specs) specs (remove #(-> % :usermeta :frame :fid (= fid)) specs) s-f-pairs (make-spec-frame-pairs id opts specs)] (update-tab-field id :specs specs) (update-tab-field id :compvis (vis-list id s-f-pairs opts)) id)) (defn update-frame [tid fid element content] (let [tbdy (get-tab-body tid) opts (tbdy :opts) specs (tbdy :specs) pos (->> specs (keep-indexed (fn[idx item] (when (-> item :usermeta :frame :fid (= fid)) idx))) first) newspec (if (= element :frame) content (assoc-in (nth specs pos) [:usermeta :frame element] content)) newspecs (concat (take pos specs) [newspec] ; splice in the updated spec (drop (inc pos) specs)) s-f-pairs (make-spec-frame-pairs tid opts newspecs)] (update-tab-field tid :specs newspecs) (update-tab-field tid :compvis (vis-list tid s-f-pairs opts)) tid)) ;;; The following two muck with the DOM directly and are not ;;; recommended. Probably should remove altogether, but leaving for ;;; right now. (defn get-frame-elements [fid] (let [fid (name fid) frame (js/document.getElementById fid) top (aget frame.childNodes 0) bottom (aget frame.childNodes 4) middle (aget frame.childNodes 2) left (aget middle.childNodes 0) vis (aget middle.childNodes 2) right (aget middle.childNodes 4)] {:top top, :bottom bottom, :left left, :right right, :vis vis})) (defn update-frame-element [fid element content] (let [fid (name fid) frame-element ((get-frame-elements fid) element) component content frame-cb (-> :frame-cb get-adb first)] (rgt/render component frame-element) (frame-cb {} {:frameid fid}))) (defn hanami [] (if-let [tabval (get-cur-tab)] (let [tabid (tabval :id) specs (tabval :specs) compvis (tabval :compvis) opts (tabval :opts (get-adb [:main :opts :tab])) frame-cb (-> :frame-cb get-adb first)] (cond compvis (do (printchan "hanami called - has compvis") (frame-cb) compvis) specs (let [spec-frame-pairs (tabval :spec-frame-pairs) ;;_ (printchan :SCPAIRS spec-frame-pairs) compvis (vis-list tabid spec-frame-pairs opts)] (printchan "hanami called - making compvis") (update-cur-tab :compvis compvis) compvis) :else [[:img {:src (get-adb [:main :img])}]])) [[:img {:src (get-adb [:main :img])}]])) (defn tabs [] (printchan "TABS called ...") (let [tabval (get-cur-tab) opts (or (and tabval (tabval :opts)) (get-adb [:main :opts :tab])) id (or (and tabval (str (name (tabval :id)) "-body")) "xHx") wrapfn (or (opts :wrapfn) identity) extfn (get-in opts [:extfn]) size (get-in opts [:size] "auto") order (get-in opts [:order] :col) layout (if (= order :row) v-box h-box) lgap (if (= layout v-box) (opts :rgap) (opts :cgap))] (printchan :OPTS opts) (if extfn (extfn tabval) (wrapfn [layout :attr {:id id} :size size :gap lgap :children (hanami)])))) (defn hanami-main [] (printchan "Hanami-main called ...") (let [inst-cursor (rgt/cursor app-db [:instrumentor]) instrumentor (first @inst-cursor) hd-cursor (rgt/cursor app-db [:header]) header (first @hd-cursor)] [v-box :gap "10px" :children [[v-box :gap "3px" :children [[header] [h-box :align :start :max-height "30px" :children [[gap :size "15px"] [active-tabs]]]]] [line] [tabs]]])) ;;; Messaging ---------------------------------------------------------------- (defn get-ws [] (->> (get-ddb []) keys (filter #(-> % type (= js/WebSocket))) first)) (defn get-chan [] (let [ws (get-ws) ch (when ws (get-ddb [ws :chan]))] ch)) ;; Send server msg (defn app-send [msg] (printchan "app-send: DEPRECATED, use 'send-msg'") (cli/send-msg (get-ws) msg)) (defn send-msg ([msg] (print-when [:msg :send] "Sending msg " msg) (cli/send-msg (get-ws) msg)) ([op data] (send-msg {:op op :data data}))) (defn merge-old-new-opts [oldopts newopts] (cond (and oldopts newopts) (if (or (oldopts :tab) (oldopts :vgl)) (sp/transform [(sp/submap [:vgl :tab]) sp/MAP-VALS] #(merge % newopts) oldopts) (merge oldopts newopts)) oldopts oldopts newopts newopts :else (get-adb [:main :opts]))) ;; Stop app (defn app-stop [] (let [ws (get-ws) ch (get-chan)] (when ch (go (async/>! ch {:op :stop :payload {:ws ws :cause :userstop}}))))) (defn init-tabs [] (update-adb [:tabs] (let [cur-ratom (rgt/atom nil) tabs-ratom (rgt/atom [])] {:current cur-ratom :active tabs-ratom :bars [horizontal-bar-tabs :model cur-ratom :tabs tabs-ratom :on-change #(reset! cur-ratom %)]}))) (defn register [{:keys [uid title logo img opts]}] (printchan "Registering " uid) (update-adb [:main :uid] uid [:main :title] title [:main :logo] logo [:main :img] img [:main :opts] (hc/xform opts) [:main :session-name] (rgt/atom "") [:vgl-as-vg] :rm [:vgviews] (atom {}) ; This should not have any reactive update [:vspecs] (rgt/atom {})) (init-tabs) (rgt/render [hanami-main] (get-adb :elem) #_(js/document.querySelector "#app"))) (defn update-opts [{:keys [main tab opts]}] (if main (update-adb [:main :opts] (merge-old-new-opts (get-adb [:main :opts]) opts)) (do (update-tab-field tab :opts (merge-old-new-opts (get-tab-field tab :opts) opts)) (update-tab-field tab :compvis sp/NONE)))) (defn empty-chart? [spec] (and (-> spec keys count (= 1)) (-> spec keys first (= :usermeta)))) (defn make-tabdefs [specs] (let [grps (group-by #(->> % :usermeta :tab :id) (com/ev specs))] (mapv (fn[[id specs]] (let [tab (->> specs first :usermeta :tab)] (assoc tab :specs (mapv (fn[spec] (dissoc spec :tab)) specs)))) grps))) (defn make-spec-frame-pairs [tid opts specs] (let [instrumentor (-> :instrumentor get-adb first)] (mapv #(do (when-let [vid (get-in % [:usermeta :vid])] (update-vspecs vid %)) (vector (if (empty-chart? %) nil %) (instrumentor {:tabid tid :spec % :opts opts}))) specs))) (defn update-tabs [specs] (let [tabdefs (make-tabdefs specs)] (mapv (fn [{:keys [id label opts specs] :as newdef}] (let [tid id oldef (get-tab-field tid) specs (when specs (->> specs com/ev)) main-opts (get-adb [:main :opts :tab]) instrumentor (-> :instrumentor get-adb first) spec-frame-pairs (make-spec-frame-pairs tid opts specs)] (if (not oldef) (add-tab (assoc newdef :opts (merge-old-new-opts main-opts opts) :spec-frame-pairs spec-frame-pairs :specs specs)) (let [oldopts (or (oldef :opts) main-opts)] (replace-tab tid {:id tid :label (or label (get-tab-field tid :label)) :opts (merge-old-new-opts oldopts opts) :spec-frame-pairs spec-frame-pairs :specs specs}))))) tabdefs))) (defn update-data "Originally meant as general updater of vis plot/chart data values. But to _render_ these, requires knowledge of the application pages/structure. So, this is not currently used. If we can figure out Vega chageSets and how they update, we may be able to make this a general op in Hanami." [data-maps app-fn] (printchan :UPDATE-DATA data-maps) (app-fn (mapv (fn [{:keys [usermeta data]}] (let [vid (usermeta :vid) spec (dissoc (get-vspec vid) :data)] (assoc-in spec [:data :values] data))) data-maps))) (defmulti user-msg :op) (defmethod user-msg :default [msg] (printchan msg)) (defn on-msg [ch ws hanami-msg] (let [{:keys [op data]} hanami-msg] (update-ddb [ws :line-info :rcvcnt] inc) (case op :register (do (register data) (user-msg {:op :app-init :data data})) :opts (update-opts data) :tabs (update-tabs data) #_:data #_(update-data data) :specs (let [{:keys [tab specs]} data] (update-tab-field tab :specs specs)) (user-msg {:op op :data data :ws ws :ch ch})))) (defn on-open [ch ws] (update-ddb ws {:chan ch, :line-info {:rcvcnt 0, :sntcnt 0, :errcnt 0}})) (defn message-dispatch [ch op payload] (case op :open (let [ws payload] (print-when [:msg :open] :CLIENT :open :ws ws) (on-open ch ws)) :close (let [{:keys [ws code reason]} payload] (print-when :CLIENT :RMTclose :payload payload) (go (async/put! ch {:op :stop :payload {:ws ws :cause :rmtclose}}))) :msg (let [{:keys [ws data]} payload] (print-when [:msg :msg] :CLIENT :msg :payload payload) (on-msg ch ws data)) :bpwait (let [{:keys [ws msg encode]} payload] (print-when [:msg :bpwait] :CLIENT "Waiting to send msg " msg) (go (async/<! (async/timeout 5000))) (print-when [:msg :bpwait] :CLIENT "Trying resend...") (cli/send-msg ws msg :encode encode)) :bpresume (print-when [:msg :bpresume] :CLIENT "BP Resume " payload) :sent (let [{:keys [ws msg]} payload] (print-when [:msg :sent] :CLIENT "Sent msg " msg) (update-ddb [ws :line-info :lastsnt] msg, [ws :line-info :sntcnt] inc)) :stop (let [{:keys [ws cause]} payload] (print-when [:msg :stop] :CLIENT "Stopping reads... Cause " cause) (cli/close-connection ws) (update-ddb ws :rm)) :error (let [{:keys [ws err]} payload] (printchan :CLIENT :error :payload payload) (update-ddb [ws :line-info :errcnt] inc)) (printchan :CLIENT :WTF :op op :payload payload))) (defn connect [host port] (go (let [uri (str "ws://" host ":" port "/ws") ch (async/<! (cli/open-connection uri))] (printchan "Opening client, reading msgs from " ch) (loop [msg (<! ch)] (let [{:keys [op payload]} msg] (message-dispatch ch op payload) (when (not= op :stop) (recur (<! ch)))))))) (defn set-session-name [name] (let [old-uid (get-adb [:main :uid]) name (if (= name "") (old-uid :name) name)] (sp/setval [sp/ATOM :main :session-name sp/ATOM] name app-db) (when (not= name (old-uid :name)) (update-adb [:main :uid :name] name) (send-msg {:op :set-session-name :data {:uid old-uid :new-name name}})))) (defn session-input [] (if (not= "" (sp/select-one [sp/ATOM :main :session-name sp/ATOM] app-db)) [:p] [input-text :model (get-adb [:main :session-name]) :on-change set-session-name :placeholder (get-adb [:main :uid :name]) :width "100px"])) (defn default-header-fn [] [h-box :gap "10px" :max-height "30px" :children [[gap :size "5px"] [:img {:src (get-adb [:main :logo])}] [title :level :level3 :label [:span.bold (get-adb [:main :title])]] #_[gap :size "5px"] [session-input] [gap :size "5px"] [title :level :level3 :label [:span.bold (get-adb [:main :uid :name])]] [gap :size "30px"]]]) (defn default-frame-cb ([]) ([spec frame] [spec frame])) (defn get-default-frame [] {:top [], :bottom [], :left [[box :size "0px" :child ""]], :right [[box :size "0px" :child ""]]}) (defn make-frame [udata curframe] (let [frameid (get-in udata [:frame :fid] (gensym "frame-"))] (merge (if (udata :frame) (let [default-frame (get-default-frame) framedef (udata :frame) frame-sides (dissoc framedef :fid :at :pos)] (print-when [:frames :make] :Frame-Maker frame-sides curframe) (update-adb [:dbg :frame] (->> (keys frame-sides) (reduce (fn[F k] (assoc F k (xform-recom (frame-sides k) re-com-xref))) default-frame))) (get-adb [:dbg :frame])) (get-default-frame)) (assoc curframe :frameid frameid)))) (defn default-instrumentor-fn [{:keys [tabid spec opts]}] (let [udata (spec :usermeta)] (print-when [:instrumentor] chan :UDATA udata :OPTS opts)) {}) (defn make-instrumentor [userfn] (fn [{:keys [tabid spec opts] :as m}] (make-frame (spec :usermeta) (userfn m)))) (defn start [& {:keys [elem host port header-fn instrumentor-fn frame-cb symxlate-cb] :or {host js/location.hostname header-fn default-header-fn instrumentor-fn default-instrumentor-fn frame-cb default-frame-cb symxlate-cb identity}}] (let [instfn (make-instrumentor instrumentor-fn)] (printchan "Element 'app' available, port " port) (app-stop) (update-adb :elem elem :symxlate-cb [symxlate-cb] :frame-cb [frame-cb] :instrumentor [instfn] :header [header-fn]) (connect host port))) (defn sv! "Mirror of server side hmi/sv! Here no need for messages. Just need to call `update-tabs` on the vector of vg/vgl-maps." [vgl-maps] (let [vgl-maps (com/ev vgl-maps)] (update-tabs vgl-maps) true)) (comment ;; Rich Comment!! ;; Always run this setup init for any testing (do (hc/update-defaults :USERDATA {:tab {:id :TID, :label :TLBL, :opts :TOPTS} :frame {:top :TOP, :bottom :BOTTOM, :left :LEFT, :right :RIGHT :fid :FID} :opts :OPTS :vid :VID, :msgop :MSGOP, :session-name :SESSION-NAME} :MSGOP :tabs, :SESSION-NAME "Exploring" :TID :expl1, :TLBL #(-> :TID % name cljstr/capitalize) :OPTS (hc/default-opts :vgl), :TOPTS (hc/default-opts :tab)) (defn bar-slider-fn [tid val] (let [tabval (get-tab-field tid) spec-frame-pairs (tabval :spec-frame-pairs)] (printchan "Slider update " val) (update-tab-field tid :compvis nil) (update-tab-field tid :spec-frame-pairs (mapv (fn[[spec frame]] (let [cljspec spec data (mapv (fn[m] (assoc m :b (+ (m :b) val))) (get-in cljspec [:data :values])) newspec (assoc-in cljspec [:data :values] data)] [newspec frame])) spec-frame-pairs)))) (defn test-instrumentor [{:keys [tabid spec opts]}] (printchan "Test Instrumentor called" :TID tabid #_:SPEC #_spec) (let [cljspec spec udata (cljspec :usermeta) default-frame (get-default-frame)] (update-adb [:udata] udata) (cond (not (map? udata)) [] (udata :slider) (let [sval (rgt/atom "0.0")] (printchan :SLIDER-INSTRUMENTOR) {:top (xform-recom (udata :slider) :m1 sval :oc1 #(do (bar-slider-fn tabid %) (reset! sval (str %))) :oc2 #(do (bar-slider-fn tabid (js/parseFloat %)) (reset! sval %)))}) (udata :test2) {:right [[gap :size "10px"] [v-box :children [[label :label "Select a demo"] [single-dropdown :choices (udata :test2) :on-change #(printchan "Dropdown: " %) :model nil :placeholder "Hi there" :width "100px"]]]]} :else {} ))) (start :elem (js/document.querySelector "#app") :instrumentor-fn test-instrumentor :port 3003)) ;; ======================================================================= ;; Testing new incremental tab bodies and user wrapping function support ;; Create a tab that includes a user defined WRAPFN (add-tab {:id :dists :label "Dists" :specs [] :opts {:order :row, :eltsper 1, :size "auto" :wrapfn (fn[hcomp] [h-split :panel-1 [box :child [input-textarea :model " 1234567890123456789012345678901234567890123456789012345678901234567890123456789" :width "650px" :rows 40 :on-change identity]] :panel-2 [scroller :max-height "800px" :max-width "1200px" :align :start :child hcomp] :initial-split "33%" :width "2048px"])}}) ;; Add some page/section title text (do (add-to-tab-body :dists (hc/xform ht/empty-chart :FID :dtitle :TOP '[[gap :size "50px"] [md "# Example Interactive Document Creation"]])) :done) ;; Render a graphic in it (add-to-tab-body :dists (hc/xform ht/bar-chart :TITLE "Top headline phrases" :TID :dists :FID :dhline :ELTSPER 1 :X :x-value :Y :y-value :YTYPE "nominal" :DATA [{:x-value 8961 :y-value "will make you"} {:x-value 4099 :y-value "this is why"} { :x-value 3199 :y-value "can we guess"} {:x-value 2398 :y-value "only X in"} {:x-value 1610 :y-value "the reason is"} {:x-value 1560 :y-value "are freaking out"} {:x-value 1425 :y-value "X stunning photos"} {:x-value 1388 :y-value "tears of joy"} {:x-value 1337 :y-value "is what happens"} {:x-value 1287 :y-value "make you cry"}])) ;; Add empty picture frame with all elements as MD (do (add-to-tab-body :dists (hc/xform ht/empty-chart :FID :dwrup1 :TOP '[[gap :size "200px"][md "# Header top"]] :BOTTOM '[[gap :size "200px"] [md "# Header bottom"]] :LEFT '[[gap :size "50px"] [md "### Header left"]] :RIGHT '[[md "### Header right"]])) :done) ;; Make some distribution data (def obsdist (let [obs [[0 9] [1 78] [2 305] [3 752] [4 1150] [5 1166] [6 899] [7 460] [8 644] [9 533] [10 504]] totcnt (->> obs (mapv second) (apply +)) pdist (map (fn[[k cnt]] [k (double (/ cnt totcnt))]) obs)] pdist)) ;; Add a picture to the tab (do (add-to-tab-body :dists (hc/xform ht/layer-chart :TID :dists :FID :dex1 :TITLE "A Real (obvserved) distribution with incorrect simple mean" :HEIGHT 400 :WIDTH 450 :LAYER [(hc/xform ht/bar-layer :XTITLE "Count" :YTITLE "Probability") (hc/xform ht/xrule-layer :AGG "mean")] :DATA (mapv (fn[[x y]] {:x x :y y :m 5.7}) obsdist))) :done) ;; Add some more 'writeup' (do (add-to-tab-body :dists (hc/xform ht/empty-chart :FID :dwrup2 :BOTTOM '[[gap :size "50px"] [md "# Fixed distribution Here we have corrected the mean by properly including item weights"]])) :done) (do (add-to-tab-body :dists (hc/xform ht/layer-chart :TID :dists :FID :dex2 :TITLE "The same distribution with correct weighted mean" :HEIGHT 400 :WIDTH 450 :LAYER [(hc/xform ht/bar-layer :XTITLE "Count" :YTITLE "Probability") (hc/xform ht/xrule-layer :X "m")] :DATA (mapv (fn[[x y]] {:x x :y y :m 5.7}) obsdist))) :done) ;; ======================================================================= ;; Direct noodling on the DOM - not recommended as subverts data flow of ;; Reagent/React (let [body (js/document.getElementById "expl1-body") lastchild body.lastChild div (js/document.createElement "div") _ (set! (.-id div) "mymd") component [h-box :children [[gap :size "20px" :width "20px"] [md " # Header 1 ## Header 2 ### Header 3, following is list * One * Two * Three"]]]] (.appendChild lastchild div) (rgt/render component lastchild.lastChild) (js/console.log lastchild) (js/console.log lastchild.lastChild)) (let [body (js/document.getElementById "expl1-body") lastchild body.lastChild] (js/console.log body) (js/console.log lastchild)) (let [body (js/document.getElementById "expl1-body") lastchild body.lastChild] (.appendChild lastchild (js/document.createElement "div")) (js/console.log lastchild) (js/console.log lastchild.lastChild)) (let [body (js/document.getElementById "expl1-body") lastchild body.lastChild component ""] (.remove lastchild.lastChild) (js/console.log lastchild) (js/console.log lastchild.lastChild)) (let [mymd (js/document.getElementById "mymd")] #_(.removeChild mymd.parentNode mymd) (.remove mymd)) (let [body (js/document.getElementById "expl1-body") lastchild body.lastChild mymd (js/document.getElementById "mymd")] (.insertBefore mymd lastchild)) ;; ======================================================================= ;; Old original db messing and testing of adding / updating tabs (get-adb [:test1 :sval]) (update-adb [:main :uid :name] "Hello") (add-tab {:id :p1 :label "BarChart" :opts {:order :col :eltsper 2 :size "none"} :specs [js/vglspec]}) (add-tab {:id :p2 :label "BarChart/Mean" :specs [js/vglspec3]}) (add-tab {:id :p3 :label "MultiChart" :specs [js/vglspec js/vglspec2 js/vglspec3 js/vglspec]}) (add-tab {:id :ttest :label "ToolTip" :specs js/ttest}) (add-tab {:id :geotest :label "GeoTest" :specs js/geotest}) (update-tab-field :geotest :specs js/geotest) (add-tab {:id :px :label "MultiChartSVG" :opts (merge-old-new-opts (get-adb [:defopts :tab]) {:size "auto"}) :specs [js/vglspec js/vglspec2 js/vglspec3 js/vglspec]}) (get-adb :tabs) {:op :tabs :data [{:id :px :label "MultiChartSVG" :opts {:size "auto"} :specs [js/vglspec js/vglspec2 js/vglspec3 js/vglspec]}]} )
[ { "context": "e-opts [\"--port=10\" \"--hosts=foo,bar,baz\" \"--name=Devon\"]\n (simple-spec [[:port :", "end": 4043, "score": 0.9305911660194397, "start": 4038, "tag": "USERNAME", "value": "Devon" }, { "context": " {:port 10 :hosts [\"foo\" \"bar\" \"baz\"] :name \"Devon\"})))\n\n (testing \"Boolean flag\"\n (is (= (p", "end": 4345, "score": 0.7218858003616333, "start": 4340, "tag": "NAME", "value": "Devon" } ]
test/cb/cljbeat/options_test.clj
chartbeat-labs/cljbeat-options
1
(ns cb.cljbeat.options-test (:require [clojure.test :refer :all] [clj-yaml.core :as yaml] [clojure.string :as str] [cb.cljbeat.options :refer [parse-opts simple-spec sstypemap options global-specs set-options! add-option-specs!]])) (def mock-yaml-file " int: 10 float: 1.5 list: - 1 - 2 - 3 ") (deftest test-parse-opts (let [mock-option-specs [["-f" "--foo NUMBER" "" :parse-fn #(Integer/parseInt %) :validate-fn number?] ["-b" "--bar NUMBER" "" :default 1 :parse-fn #(Integer/parseInt %)]] mock-help-args ["--help"] mock-invalid-args ["--foo=bar"] mock-valid-args ["--foo=10"] mock-valid-args-key :foo mock-valid-args-value 10 mock-yaml-string "bar: 2" mock-yaml-arg-key :bar mock-yaml-arg-value 2] (testing "Returns nil when --help is passed." (with-redefs-fn {#'println (fn [& args] nil)} #(is (nil? (parse-opts mock-help-args mock-option-specs))))) (testing "Returns nil when invalid args are passed." (with-redefs-fn {#'cb.cljbeat.options/print-failure (fn [& args] nil) #'cb.cljbeat.options/log-failure (fn [& args] nil)} #(is (nil? (parse-opts mock-invalid-args mock-option-specs))))) (testing "Successfully parses options when valid args are passed" (let [options (parse-opts mock-valid-args mock-option-specs)] (is (= (options mock-valid-args-key) mock-valid-args-value)))) (testing "Options successfully read from config file." (with-redefs-fn {#'clojure.core/slurp (fn [_] mock-yaml-string)} #(let [args (into mock-valid-args ["--config-file" "foo.yaml"]) options (parse-opts args mock-option-specs)] (is (= mock-yaml-arg-value (options mock-yaml-arg-key)))))) (testing "Type based parsing works with CLI and config file input." (with-redefs-fn {#'clojure.core/slurp (fn [_] mock-yaml-file)} #(let [args-cli ["-i" "10" "-f" "1.5" "-l" "1,2,3"] args-conf-file ["--config-file" "myconf.yaml"] specs [["-i" "--int X" nil :parse-fn (fn [i] (Integer/parseInt i))] ["-f" "--float X" nil :parse-fn (fn [f] (Float/parseFloat f))] ["-l" "--list X" nil :parse-fn (fn [s] (map (fn [i] (Integer/parseInt i)) (str/split s #",")))]] cli-options (parse-opts args-cli specs) file-options (parse-opts args-conf-file specs)] (is (= (:int cli-options) (:int file-options))) (is (= (:float cli-options) (:float file-options))) (is (= (:list cli-options) (:list file-options)))))))) (deftest test-simple-spec (let [int-parse-fn (second (sstypemap :int)) vector-parse-fn (second (sstypemap :vector)) not-blank? #(not (clojure.string/blank? %))] (testing "Parses simple spec into normal spec" (is (= (simple-spec [[:port :int "the port to serve on"] ["hosts" :vector "hosts to connect to"] [:name "string" :validate-fn not-blank?] [:debug :boolean]]) [[nil "--port INT" "the port to serve on" :parse-fn int-parse-fn] [nil "--hosts STRING1,STRING2,STRING3" "hosts to connect to" :parse-fn vector-parse-fn] [nil "--name STRING" "" :parse-fn nil :validate-fn not-blank?] [nil "--debug" "" :parse-fn nil]]))) (testing "Simple specs work with parse-opts" (is (= (parse-opts ["--port=10" "--hosts=foo,bar,baz" "--name=Devon"] (simple-spec [[:port :int "the port to serve on"] ["hosts" :vector "hosts to connect to"] [:name "string" :validate-fn not-blank?]])) {:port 10 :hosts ["foo" "bar" "baz"] :name "Devon"}))) (testing "Boolean flag" (is (= (parse-opts [] (simple-spec [[:debug :boolean]])) {})) (is (= (parse-opts ["--debug"] (simple-spec [[:debug :boolean]])) {:debug true}))))) (defn reset-globals! [] (reset! options {}) (reset! global-specs [])) (deftest test-global-specs (let [opt-specs1 (simple-spec [[:port :int :default 8000] [:host :string :default "localhost"] [:prefix :string]]) opt-specs2 (simple-spec [[:num-threads :int :default 10] [:log-file :string]])] (testing "add-option-specs sets defaults" (reset-globals!) (add-option-specs! opt-specs1) (is (= @options {:port 8000, :host "localhost"}))) (testing "accept added option specs" (reset-globals!) (add-option-specs! opt-specs1) (set-options! ["--prefix" "cb" "--port" "8080" "--log-file" "/var/log/opts.log"] opt-specs2) (is (= @options {:port 8080 :host "localhost" :num-threads 10 :log-file "/var/log/opts.log" :prefix "cb"})))) (reset-globals!))
58338
(ns cb.cljbeat.options-test (:require [clojure.test :refer :all] [clj-yaml.core :as yaml] [clojure.string :as str] [cb.cljbeat.options :refer [parse-opts simple-spec sstypemap options global-specs set-options! add-option-specs!]])) (def mock-yaml-file " int: 10 float: 1.5 list: - 1 - 2 - 3 ") (deftest test-parse-opts (let [mock-option-specs [["-f" "--foo NUMBER" "" :parse-fn #(Integer/parseInt %) :validate-fn number?] ["-b" "--bar NUMBER" "" :default 1 :parse-fn #(Integer/parseInt %)]] mock-help-args ["--help"] mock-invalid-args ["--foo=bar"] mock-valid-args ["--foo=10"] mock-valid-args-key :foo mock-valid-args-value 10 mock-yaml-string "bar: 2" mock-yaml-arg-key :bar mock-yaml-arg-value 2] (testing "Returns nil when --help is passed." (with-redefs-fn {#'println (fn [& args] nil)} #(is (nil? (parse-opts mock-help-args mock-option-specs))))) (testing "Returns nil when invalid args are passed." (with-redefs-fn {#'cb.cljbeat.options/print-failure (fn [& args] nil) #'cb.cljbeat.options/log-failure (fn [& args] nil)} #(is (nil? (parse-opts mock-invalid-args mock-option-specs))))) (testing "Successfully parses options when valid args are passed" (let [options (parse-opts mock-valid-args mock-option-specs)] (is (= (options mock-valid-args-key) mock-valid-args-value)))) (testing "Options successfully read from config file." (with-redefs-fn {#'clojure.core/slurp (fn [_] mock-yaml-string)} #(let [args (into mock-valid-args ["--config-file" "foo.yaml"]) options (parse-opts args mock-option-specs)] (is (= mock-yaml-arg-value (options mock-yaml-arg-key)))))) (testing "Type based parsing works with CLI and config file input." (with-redefs-fn {#'clojure.core/slurp (fn [_] mock-yaml-file)} #(let [args-cli ["-i" "10" "-f" "1.5" "-l" "1,2,3"] args-conf-file ["--config-file" "myconf.yaml"] specs [["-i" "--int X" nil :parse-fn (fn [i] (Integer/parseInt i))] ["-f" "--float X" nil :parse-fn (fn [f] (Float/parseFloat f))] ["-l" "--list X" nil :parse-fn (fn [s] (map (fn [i] (Integer/parseInt i)) (str/split s #",")))]] cli-options (parse-opts args-cli specs) file-options (parse-opts args-conf-file specs)] (is (= (:int cli-options) (:int file-options))) (is (= (:float cli-options) (:float file-options))) (is (= (:list cli-options) (:list file-options)))))))) (deftest test-simple-spec (let [int-parse-fn (second (sstypemap :int)) vector-parse-fn (second (sstypemap :vector)) not-blank? #(not (clojure.string/blank? %))] (testing "Parses simple spec into normal spec" (is (= (simple-spec [[:port :int "the port to serve on"] ["hosts" :vector "hosts to connect to"] [:name "string" :validate-fn not-blank?] [:debug :boolean]]) [[nil "--port INT" "the port to serve on" :parse-fn int-parse-fn] [nil "--hosts STRING1,STRING2,STRING3" "hosts to connect to" :parse-fn vector-parse-fn] [nil "--name STRING" "" :parse-fn nil :validate-fn not-blank?] [nil "--debug" "" :parse-fn nil]]))) (testing "Simple specs work with parse-opts" (is (= (parse-opts ["--port=10" "--hosts=foo,bar,baz" "--name=Devon"] (simple-spec [[:port :int "the port to serve on"] ["hosts" :vector "hosts to connect to"] [:name "string" :validate-fn not-blank?]])) {:port 10 :hosts ["foo" "bar" "baz"] :name "<NAME>"}))) (testing "Boolean flag" (is (= (parse-opts [] (simple-spec [[:debug :boolean]])) {})) (is (= (parse-opts ["--debug"] (simple-spec [[:debug :boolean]])) {:debug true}))))) (defn reset-globals! [] (reset! options {}) (reset! global-specs [])) (deftest test-global-specs (let [opt-specs1 (simple-spec [[:port :int :default 8000] [:host :string :default "localhost"] [:prefix :string]]) opt-specs2 (simple-spec [[:num-threads :int :default 10] [:log-file :string]])] (testing "add-option-specs sets defaults" (reset-globals!) (add-option-specs! opt-specs1) (is (= @options {:port 8000, :host "localhost"}))) (testing "accept added option specs" (reset-globals!) (add-option-specs! opt-specs1) (set-options! ["--prefix" "cb" "--port" "8080" "--log-file" "/var/log/opts.log"] opt-specs2) (is (= @options {:port 8080 :host "localhost" :num-threads 10 :log-file "/var/log/opts.log" :prefix "cb"})))) (reset-globals!))
true
(ns cb.cljbeat.options-test (:require [clojure.test :refer :all] [clj-yaml.core :as yaml] [clojure.string :as str] [cb.cljbeat.options :refer [parse-opts simple-spec sstypemap options global-specs set-options! add-option-specs!]])) (def mock-yaml-file " int: 10 float: 1.5 list: - 1 - 2 - 3 ") (deftest test-parse-opts (let [mock-option-specs [["-f" "--foo NUMBER" "" :parse-fn #(Integer/parseInt %) :validate-fn number?] ["-b" "--bar NUMBER" "" :default 1 :parse-fn #(Integer/parseInt %)]] mock-help-args ["--help"] mock-invalid-args ["--foo=bar"] mock-valid-args ["--foo=10"] mock-valid-args-key :foo mock-valid-args-value 10 mock-yaml-string "bar: 2" mock-yaml-arg-key :bar mock-yaml-arg-value 2] (testing "Returns nil when --help is passed." (with-redefs-fn {#'println (fn [& args] nil)} #(is (nil? (parse-opts mock-help-args mock-option-specs))))) (testing "Returns nil when invalid args are passed." (with-redefs-fn {#'cb.cljbeat.options/print-failure (fn [& args] nil) #'cb.cljbeat.options/log-failure (fn [& args] nil)} #(is (nil? (parse-opts mock-invalid-args mock-option-specs))))) (testing "Successfully parses options when valid args are passed" (let [options (parse-opts mock-valid-args mock-option-specs)] (is (= (options mock-valid-args-key) mock-valid-args-value)))) (testing "Options successfully read from config file." (with-redefs-fn {#'clojure.core/slurp (fn [_] mock-yaml-string)} #(let [args (into mock-valid-args ["--config-file" "foo.yaml"]) options (parse-opts args mock-option-specs)] (is (= mock-yaml-arg-value (options mock-yaml-arg-key)))))) (testing "Type based parsing works with CLI and config file input." (with-redefs-fn {#'clojure.core/slurp (fn [_] mock-yaml-file)} #(let [args-cli ["-i" "10" "-f" "1.5" "-l" "1,2,3"] args-conf-file ["--config-file" "myconf.yaml"] specs [["-i" "--int X" nil :parse-fn (fn [i] (Integer/parseInt i))] ["-f" "--float X" nil :parse-fn (fn [f] (Float/parseFloat f))] ["-l" "--list X" nil :parse-fn (fn [s] (map (fn [i] (Integer/parseInt i)) (str/split s #",")))]] cli-options (parse-opts args-cli specs) file-options (parse-opts args-conf-file specs)] (is (= (:int cli-options) (:int file-options))) (is (= (:float cli-options) (:float file-options))) (is (= (:list cli-options) (:list file-options)))))))) (deftest test-simple-spec (let [int-parse-fn (second (sstypemap :int)) vector-parse-fn (second (sstypemap :vector)) not-blank? #(not (clojure.string/blank? %))] (testing "Parses simple spec into normal spec" (is (= (simple-spec [[:port :int "the port to serve on"] ["hosts" :vector "hosts to connect to"] [:name "string" :validate-fn not-blank?] [:debug :boolean]]) [[nil "--port INT" "the port to serve on" :parse-fn int-parse-fn] [nil "--hosts STRING1,STRING2,STRING3" "hosts to connect to" :parse-fn vector-parse-fn] [nil "--name STRING" "" :parse-fn nil :validate-fn not-blank?] [nil "--debug" "" :parse-fn nil]]))) (testing "Simple specs work with parse-opts" (is (= (parse-opts ["--port=10" "--hosts=foo,bar,baz" "--name=Devon"] (simple-spec [[:port :int "the port to serve on"] ["hosts" :vector "hosts to connect to"] [:name "string" :validate-fn not-blank?]])) {:port 10 :hosts ["foo" "bar" "baz"] :name "PI:NAME:<NAME>END_PI"}))) (testing "Boolean flag" (is (= (parse-opts [] (simple-spec [[:debug :boolean]])) {})) (is (= (parse-opts ["--debug"] (simple-spec [[:debug :boolean]])) {:debug true}))))) (defn reset-globals! [] (reset! options {}) (reset! global-specs [])) (deftest test-global-specs (let [opt-specs1 (simple-spec [[:port :int :default 8000] [:host :string :default "localhost"] [:prefix :string]]) opt-specs2 (simple-spec [[:num-threads :int :default 10] [:log-file :string]])] (testing "add-option-specs sets defaults" (reset-globals!) (add-option-specs! opt-specs1) (is (= @options {:port 8000, :host "localhost"}))) (testing "accept added option specs" (reset-globals!) (add-option-specs! opt-specs1) (set-options! ["--prefix" "cb" "--port" "8080" "--log-file" "/var/log/opts.log"] opt-specs2) (is (= @options {:port 8080 :host "localhost" :num-threads 10 :log-file "/var/log/opts.log" :prefix "cb"})))) (reset-globals!))
[ { "context": " t-conn\n {:name \"Teppo\"\n :registrationDate \"12.12.2012\"\n ", "end": 681, "score": 0.9987972378730774, "start": 676, "tag": "NAME", "value": "Teppo" }, { "context": "trationDate \"12.12.2012\"\n :email \"teppo@gmail.com\"\n :website \"www.google.com\"\n ", "end": 770, "score": 0.9999245405197144, "start": 755, "tag": "EMAIL", "value": "teppo@gmail.com" }, { "context": " \"www.google.com\"\n :pass \"pass\"\n :phone \"0401234567\"\n ", "end": 852, "score": 0.9994039535522461, "start": 848, "tag": "PASSWORD", "value": "pass" }, { "context": "is (= {:id \"1\"\n :name \"Teppo\"\n :registrationDate \"12.12.2012\"\n ", "end": 1115, "score": 0.999494731426239, "start": 1110, "tag": "NAME", "value": "Teppo" }, { "context": "egistrationDate \"12.12.2012\"\n :email \"teppo@gmail.com\"\n :website \"www.google.com\"\n ", "end": 1196, "score": 0.9999255537986755, "start": 1181, "tag": "EMAIL", "value": "teppo@gmail.com" }, { "context": "te \"www.google.com\"\n :pass \"pass\"\n :phone \"0401234567\"\n ", "end": 1270, "score": 0.9993415474891663, "start": 1266, "tag": "PASSWORD", "value": "pass" } ]
test/clj/yritysten/test/db/core.clj
matiasrimm/Yritysten
0
(ns yritysten.test.db.core (:require [yritysten.db.core :refer [*db*] :as db] [luminus-migrations.core :as migrations] [clojure.test :refer :all] [clojure.java.jdbc :as jdbc] [yritysten.config :refer [env]] [mount.core :as mount])) (use-fixtures :once (fn [f] (mount/start #'yritysten.config/env #'yritysten.db.core/*db*) (migrations/migrate ["migrate"] (select-keys env [:database-url])) (f))) (deftest test-users (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (is (= 1 (db/create-business! t-conn {:name "Teppo" :registrationDate "12.12.2012" :email "teppo@gmail.com" :website "www.google.com" :pass "pass" :phone "0401234567" :companyForm "TMI" :detailsUri "www.details.fi" :bisDetailsUri "www.bisnessdetails.fi"}))) (is (= {:id "1" :name "Teppo" :registrationDate "12.12.2012" :email "teppo@gmail.com" :website "www.google.com" :pass "pass" :phone "0401234567" :companyForm "TMI" :detailsUri "www.details.fi" :bisDetailsUri "www.bisnessdetails.fi"} (db/get-user t-conn {:id "1"})))))
14553
(ns yritysten.test.db.core (:require [yritysten.db.core :refer [*db*] :as db] [luminus-migrations.core :as migrations] [clojure.test :refer :all] [clojure.java.jdbc :as jdbc] [yritysten.config :refer [env]] [mount.core :as mount])) (use-fixtures :once (fn [f] (mount/start #'yritysten.config/env #'yritysten.db.core/*db*) (migrations/migrate ["migrate"] (select-keys env [:database-url])) (f))) (deftest test-users (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (is (= 1 (db/create-business! t-conn {:name "<NAME>" :registrationDate "12.12.2012" :email "<EMAIL>" :website "www.google.com" :pass "<PASSWORD>" :phone "0401234567" :companyForm "TMI" :detailsUri "www.details.fi" :bisDetailsUri "www.bisnessdetails.fi"}))) (is (= {:id "1" :name "<NAME>" :registrationDate "12.12.2012" :email "<EMAIL>" :website "www.google.com" :pass "<PASSWORD>" :phone "0401234567" :companyForm "TMI" :detailsUri "www.details.fi" :bisDetailsUri "www.bisnessdetails.fi"} (db/get-user t-conn {:id "1"})))))
true
(ns yritysten.test.db.core (:require [yritysten.db.core :refer [*db*] :as db] [luminus-migrations.core :as migrations] [clojure.test :refer :all] [clojure.java.jdbc :as jdbc] [yritysten.config :refer [env]] [mount.core :as mount])) (use-fixtures :once (fn [f] (mount/start #'yritysten.config/env #'yritysten.db.core/*db*) (migrations/migrate ["migrate"] (select-keys env [:database-url])) (f))) (deftest test-users (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (is (= 1 (db/create-business! t-conn {:name "PI:NAME:<NAME>END_PI" :registrationDate "12.12.2012" :email "PI:EMAIL:<EMAIL>END_PI" :website "www.google.com" :pass "PI:PASSWORD:<PASSWORD>END_PI" :phone "0401234567" :companyForm "TMI" :detailsUri "www.details.fi" :bisDetailsUri "www.bisnessdetails.fi"}))) (is (= {:id "1" :name "PI:NAME:<NAME>END_PI" :registrationDate "12.12.2012" :email "PI:EMAIL:<EMAIL>END_PI" :website "www.google.com" :pass "PI:PASSWORD:<PASSWORD>END_PI" :phone "0401234567" :companyForm "TMI" :detailsUri "www.details.fi" :bisDetailsUri "www.bisnessdetails.fi"} (db/get-user t-conn {:id "1"})))))
[ { "context": "t-seq 1\n :id 2}\n {:event-id :name\n :name \"Your\"\n :event-seq 2\n :id 2}])\n\n(deftest test-tha", "end": 5577, "score": 0.6214636564254761, "start": 5573, "tag": "NAME", "value": "Your" }, { "context": "\"\n :iso \"DE\"\n :key-account \"Inna Shala\"\n :oenb-id-number \"8324301\"\n ", "end": 10008, "score": 0.9879521131515503, "start": 9998, "tag": "KEY", "value": "Inna Shala" }, { "context": "\"\n :iso \"DE\"\n :key-account \"Inna Shala\"\n :oenb-id-number \"8142262\"\n ", "end": 10870, "score": 0.988638699054718, "start": 10860, "tag": "KEY", "value": "Inna Shala" } ]
test/edd/test/fixture/dal_test.clj
raiffeisenbankinternational/edd-core
4
(ns edd.test.fixture.dal-test (:require [edd.test.fixture.dal :refer [verify-state ctx with-mock-dal pop-state peek-state verify-state-fn]] [edd.common :as common] [edd.search :as search] [edd.core :as edd] [edd.dal :as event-store] [edd.memory.event-store :as dal] [edd.elastic.view-store :as elastic-view] [edd.search :as view-store] [clojure.test :refer :all] [org.httpkit.client :as http] [edd.elastic.view-store :as elastic] [lambda.util :as util] [edd.test.fixture.dal :as mock] [lambda.uuid :as uuid])) (deftest when-store-and-load-events-then-ok (with-mock-dal (dal/store-event {:id 1 :info "info"}) (verify-state [{:id 1 :info "info"}] :event-store) (let [events (event-store/get-events (assoc ctx :id 1))] (is (= [{:id 1 :info "info"}] events))))) (deftest when-update-aggregate-then-ok (with-mock-dal (view-store/update-aggregate (assoc ctx :aggregate {:id 1 :payload "payload"})) (verify-state [{:id 1 :payload "payload"}] :aggregate-store) (view-store/update-aggregate (assoc ctx :aggregate {:id 1 :payload "payload2"})) (verify-state [{:id 1 :payload "payload2"}] :aggregate-store))) (deftest when-query-aggregate-with-unknown-condition-then-return-nothing (with-mock-dal (view-store/update-aggregate (assoc ctx :aggregate {:id 1 :payload "payload"})) (view-store/update-aggregate (assoc ctx :aggregate {:id 2 :payload "payload"})) (view-store/update-aggregate (assoc ctx :aggregate {:id 3 :payload "pa2"})) (is (= [{:id 3 :payload "pa2"}] (view-store/simple-search (assoc ctx :query {:id 3})))) (is (= [] (view-store/simple-search (assoc ctx :query {:id 4})))))) (deftest when-store-sequence-then-ok (with-mock-dal (dal/store-sequence {:id "id1"}) (dal/store-sequence {:id "id2"}) (verify-state [{:id "id1" :value 1} {:id "id2" :value 2}] :sequence-store) (is (= 1 (event-store/get-sequence-number-for-id (assoc ctx :id "id1")))) (is (= 2 (event-store/get-sequence-number-for-id (assoc ctx :id "id2")))) (is (= "id1" (event-store/get-id-for-sequence-number (assoc ctx :sequence 1)))) (is (= "id2" (event-store/get-id-for-sequence-number (assoc ctx :sequence 2)))))) (deftest when-sequnce-null-then-fail (with-mock-dal (is (thrown? AssertionError (dal/store-sequence {:id nil}))) (dal/store-sequence {:id "id2"}) (is (= "id2" (event-store/get-id-for-sequence-number (assoc ctx :sequence 1)))) (is (thrown? AssertionError (event-store/get-id-for-sequence-number (assoc ctx :sequence nil)))) (is (thrown? AssertionError (event-store/get-sequence-number-for-id (assoc ctx :id nil)))))) (deftest when-sequence-exists-then-exception (with-mock-dal (dal/store-sequence {:id 1}) (is (thrown? RuntimeException (dal/store-sequence {:id 1}))) (verify-state [{:id 1 :value 1}] :sequence-store))) (deftest when-store-identity-then-ok (with-mock-dal (dal/store-identity {:identity 1 :id 1}) (dal/store-identity {:identity 2 :id 2}) (verify-state [{:identity 1 :id 1} {:identity 2 :id 2}] :identity-store))) (deftest when-identity-exists-then-exception (with-mock-dal (dal/store-identity {:identity 1}) (is (thrown? RuntimeException (dal/store-identity {:identity 1}))) (verify-state [{:identity 1}] :identity-store))) (deftest when-store-command-then-ok (with-mock-dal (dal/store-command {:service "test-service" :payload "payload"}) (verify-state [{:service "test-service" :payload "payload"}] :command-store))) (deftest when-identity-exists-then-id-for-aggregate-can-be-fetched (with-mock-dal (dal/store-identity {:identity 1 :id 2}) (verify-state [{:identity 1 :id 2}] :identity-store) (is (= 2 (event-store/get-aggregate-id-by-identity (assoc ctx :identity 1)))))) (def events [{:event-id :name :name "Me" :event-seq 1 :id 2} {:event-id :name :name "Your" :event-seq 2 :id 2}]) (deftest test-that-events-can-be-fetched-by-aggregate-id (with-mock-dal (dal/store-event (first events)) (dal/store-event (second events)) (dal/store-event {:event-id :name :name "Bla" :event-seq 3 :id 4}) (verify-state (conj events {:event-id :name :name "Bla" :event-seq 3 :id 4}) :event-store) (is (= {:name "Your" :version 2 :id 2} (-> ctx (edd/reg-event :name (fn [state event] {:name (:name event) :id (:id event)})) (assoc :id 2) (common/get-by-id) :aggregate))))) (deftest when-no-result-by-id-return-nil (with-mock-dal (dal/store-event (first events)) (verify-state [(first events)] :event-store) (is (= {:aggregate nil} (select-keys (common/get-by-id (assoc ctx :id 5)) [:aggregate]))))) (deftest when-no-id-passed-in-return-nil (with-mock-dal (dal/store-event (first events)) (verify-state [(first events)] :event-store) (is (= nil (common/get-by-id ctx {}))))) (deftest verify-predefined-state (with-mock-dal {:event-store [{:event-id :e1}]} (verify-state [{:event-id :e1}] :event-store) (verify-state [] :command-store) (dal/store-event (first events)) (verify-state [{:event-id :e1} (first events)] :event-store) (is (= nil (:aggregate (common/get-by-id (assoc ctx :id 5))))) (is (= nil (:aggregate (common/get-by-id {:id 5})))))) (def v1 {:id 1 :at1 "val1-1" :at2 {:at3 "val1-3" :at4 "val1-4"}}) (def v2 {:id 2 :at1 "val2-1" :at2 {:at3 "val2-3" :at4 "val2-4"}}) (deftest test-simple-search-result (with-mock-dal (view-store/update-aggregate (assoc ctx :aggregate v1)) (view-store/update-aggregate (assoc ctx :aggregate v2)) (let [resp (view-store/simple-search (assoc ctx :query {:query-id :id1 :at1 "val2-1" :at2 {:at4 "val2-4"}}))] (is (= v2 (first resp)))))) (def e1 {:id 1 :event-seq 1}) (def e2 {:id 1 :event-seq 2}) (deftest test-event-seq-and-event-order (with-mock-dal (dal/store-event e1) (dal/store-event e2) (is (= 2 (event-store/get-max-event-seq (assoc ctx :id 1)))) (is (= 0 (event-store/get-max-event-seq (assoc ctx :id 3)))) (is (= [e1 e2] (event-store/get-events (assoc ctx :id 1)))))) (deftest test-reverse-event-order-1 (with-mock-dal (dal/store-event e1) (dal/store-event e2) (is (= [e1 e2] (event-store/get-events (assoc ctx :id 1)))))) (deftest test-reverse-event-order-2 (with-mock-dal {:command-store [{:cmd 1}] :event-store [{:event :bla}]} (is (= {:aggregate-store [] :command-store [{:cmd 1}] :event-store [{:event :bla}] :identity-store [] :sequence-store []} (peek-state))) (is (= [{:cmd 1}] (peek-state :command-store))) (is (= [{:event :bla}] (peek-state :event-store))) (is (= [{:event :bla}] (pop-state :event-store))) (is (= {:aggregate-store [] :command-store [{:cmd 1}] :event-store [] :identity-store [] :sequence-store []} (peek-state))))) (deftest test-simple-query (is (= {:size 600 :query {:bool {:must [{:term {:first.keyword "zeko"}} {:term {:last.two.keyword "d"}}]}}} (util/to-edn (elastic/create-simple-query {:first "zeko" :last {:two "d"}}))))) (def elk-objects [{:attrs {:cocunut "222996" :cognos "ABADEK" :company "Abade Immobilienleasing GmbH & Co Projekt Lauterbach KG, 65760 Eschborn (DE)" :ifrs "Group Corporates & Markets" :int "Financial Institution acc. CRR /BWG" :iso "DE" :key-account "Inna Shala" :oenb-id-number "8324301" :parent-id "#74094776-3cd9-4b48-9deb-4c38b3c96435" :parent-short-name "RLGMBH GROUP" :rbi-group-cocunut "222996" :rbi-knr "" :reporting-ccy "EUR" :share-in-% "6,00%" :short-code "ABADEKG" :short-name "ABADEKG" :sorter "Leasing Austria" :type ":booking-company"} :cocunut "222996" :id "#e1a1e96f-93bb-4fdd-9605-ef2b38c1c458" :parents ["#74094776-3cd9-4b48-9deb-4c38b3c96435"] :state ":detached"} {:attrs {:cocunut "188269" :cognos "ABADE" :company "Abade Immobilienleasing GmbH, 65760 Eschborn (DE)" :ifrs "Group Corporates & Markets" :int "Financial Institution acc. CRR /BWG" :iso "DE" :key-account "Inna Shala" :oenb-id-number "8142262" :parent-id "#74094776-3cd9-4b48-9deb-4c38b3c96435" :parent-short-name "RLGMBH GROUP" :rbi-group-cocunut "188269" :rbi-knr "" :reporting-ccy "EUR" :share-in-% "100,00%" :short-code "ABADE" :short-name "ABADE" :sorter "Leasing Austria" :type ":booking-company"} :cocunut "188269" :id "#7c30b6a3-2816-4378-8ed9-0b73b61012d4" :parents ["#74094776-3cd9-4b48-9deb-4c38b3c96435"] :state ":detached"}]) (def elk-response (future {:opts {:body (util/to-json {:size 600 :query {:bool {:must [{:match {:attrs.type ":booking-company"}}]}}}), :headers {"Content-Type" "application/json" "X-Amz-Date" "20200818T113334Z"}, :timeout 5000, :keepalive 300000, :method :post :url "https://vpc-mock.eu-central-1.es.amazonaws.com/glms_risk_taker_svc/_search"} :body (util/to-json {:took 42, :timed_out false, :_shards {:total 5, :successful 5, :skipped 0, :failed 0}, :hits {:total {:value 2, :relation "eq"}, :max_score 0.09304003, :hits [{:_index "glms_risk_taker_svc", :_type "_doc", :_id "e1a1e96f-93bb-4fdd-9605-ef2b38c1c458", :_score 0.09304003, :_source (first elk-objects)} {:_index "glms_risk_taker_svc", :_type "_doc", :_id "7c30b6a3-2816-4378-8ed9-0b73b61012d4", :_score 0.09304003, :_source (second elk-objects)}]}}) :headers {:access-control-allow-origin "*" :connection "keep-alive" :content-encoding "gzip"}, :status 200})) (deftest elastic-search (with-redefs [http/post (fn [url req] elk-response)] (is (= elk-objects (search/simple-search (-> {} (elastic-view/register) (assoc :service-name "test" :query {}))))))) (deftest when-identity-exists-then-exception (with-mock-dal (dal/store-identity {:id "id1" :identity 1}) (is (thrown? RuntimeException (dal/store-identity {:id "id1" :identity 1}))) (verify-state [{:id "id1" :identity 1}] :identity-store))) (deftest when-identity-exists-then-ok (with-mock-dal (dal/store-identity {:id "id1" :identity 1}) (dal/store-identity {:id "id1" :identity 2}) (verify-state [{:id "id1" :identity 1} {:id "id1" :identity 2}] :identity-store))) (deftest test-identity-generation (with-mock-dal {:identities {"id1" "some-id"}} (is (= "some-id" (common/create-identity "id1"))))) (deftest verify-state-fn-ok-test (with-mock-dal {:aggregate-store [{:a "a" :b "b"} {:a "c" :d "d"}]} (verify-state-fn :aggregate-store #(dissoc % :a) [{:b "b"} {:d "d"}]))) (deftest apply-cmd-test (with-mock-dal (let [id (uuid/gen) ctx (-> mock/ctx (edd/reg-cmd :test-cmd (fn [ctx cmd] {:event-id :1})) (edd/reg-cmd :test-cmd-fx (fn [ctx cmd] {:event-id :2})) (edd/reg-fx (fn [ctx [event]] (case (:event-id event) :1 [] :2 {:cmd-id :fx-cmd :attrs event}))))] (mock/apply-cmd ctx {:cmd-id :test-cmd :id id}) (is (= {:effects [] :events 1 :identities 0 :meta [{:test-cmd {:id id}}] :sequences 0 :success true} (mock/handle-cmd ctx {:cmd-id :test-cmd :id id}))) (is (= {:commands [] :events [{:event-id :1 :event-seq 3 :id id}] :identities [] :meta [{:test-cmd {:id id}}] :sequences []} (mock/get-commands-response ctx {:cmd-id :test-cmd :id id}))) (let [request-id (uuid/gen) interaction-id (uuid/gen)] (testing "Wirth included meta" (is (= {:commands [{:breadcrumbs [0 0] :commands [{:cmd-id :fx-cmd :attrs {:event-id :2 :id id}}] :interaction-id interaction-id :meta {:realm :realm2} :request-id request-id :service nil}] :events [{:event-id :2 :event-seq 4 :id id :meta {:realm :realm2} :request-id request-id :interaction-id interaction-id}] :identities [] :meta [{:test-cmd-fx {:id id}}] :sequences []} (mock/get-commands-response (assoc ctx :include-meta true :request-id request-id :interaction-id interaction-id) {:commands [{:cmd-id :test-cmd-fx :id id}] :meta {:realm :realm2} :request-id request-id :interaction-id interaction-id})))) (testing "Without including meta" (mock/verify-state :command-store [{:commands [{:cmd-id :fx-cmd :attrs {:event-id :2 :id id}}] :meta {:realm :realm2} :service nil}]) (is (= {:commands [{:breadcrumbs [0 0] :commands [{:cmd-id :fx-cmd :attrs {:event-id :2 :id id}}] :service nil}] :events [{:event-id :2 :event-seq 4 :id id}] :identities [] :meta [{:test-cmd-fx {:id id}}] :sequences []} (mock/get-commands-response (assoc ctx :request-id request-id :interaction-id interaction-id) {:commands [{:cmd-id :test-cmd-fx :id id}] :meta {:realm :realm2} :request-id request-id :interaction-id interaction-id})))))))) (defn my-command-handler [ctx cmd] (println "bAAAA")) (defn register [ctx] (-> ctx (edd/reg-cmd :cmd-1 my-command-handler :dps {:facility (fn [cmd] {:query-id :query-1 :identity (:external cmd)})}) (edd/reg-query :query-1 (fn [ctx query] (let [id (common/get-aggregate-id-by-identity ctx query)] (common/get-by-id ctx id)))))) (deftest test-identity-query (let [agg-id (uuid/gen)] (with-mock-dal {:identity-store [{:id agg-id :identity "ext-1"}] :aggregate-store [{:version 3 :id agg-id :attrs {:some :value}}]} (with-redefs [my-command-handler (fn [ctx cmd] (is (= {:attrs {:some :value} :id agg-id :version 3} (:facility ctx))) [])] (mock/apply-cmd (register ctx) {:cmd-id :cmd-1 :id (uuid/gen) :external "ext-1"})))))
109754
(ns edd.test.fixture.dal-test (:require [edd.test.fixture.dal :refer [verify-state ctx with-mock-dal pop-state peek-state verify-state-fn]] [edd.common :as common] [edd.search :as search] [edd.core :as edd] [edd.dal :as event-store] [edd.memory.event-store :as dal] [edd.elastic.view-store :as elastic-view] [edd.search :as view-store] [clojure.test :refer :all] [org.httpkit.client :as http] [edd.elastic.view-store :as elastic] [lambda.util :as util] [edd.test.fixture.dal :as mock] [lambda.uuid :as uuid])) (deftest when-store-and-load-events-then-ok (with-mock-dal (dal/store-event {:id 1 :info "info"}) (verify-state [{:id 1 :info "info"}] :event-store) (let [events (event-store/get-events (assoc ctx :id 1))] (is (= [{:id 1 :info "info"}] events))))) (deftest when-update-aggregate-then-ok (with-mock-dal (view-store/update-aggregate (assoc ctx :aggregate {:id 1 :payload "payload"})) (verify-state [{:id 1 :payload "payload"}] :aggregate-store) (view-store/update-aggregate (assoc ctx :aggregate {:id 1 :payload "payload2"})) (verify-state [{:id 1 :payload "payload2"}] :aggregate-store))) (deftest when-query-aggregate-with-unknown-condition-then-return-nothing (with-mock-dal (view-store/update-aggregate (assoc ctx :aggregate {:id 1 :payload "payload"})) (view-store/update-aggregate (assoc ctx :aggregate {:id 2 :payload "payload"})) (view-store/update-aggregate (assoc ctx :aggregate {:id 3 :payload "pa2"})) (is (= [{:id 3 :payload "pa2"}] (view-store/simple-search (assoc ctx :query {:id 3})))) (is (= [] (view-store/simple-search (assoc ctx :query {:id 4})))))) (deftest when-store-sequence-then-ok (with-mock-dal (dal/store-sequence {:id "id1"}) (dal/store-sequence {:id "id2"}) (verify-state [{:id "id1" :value 1} {:id "id2" :value 2}] :sequence-store) (is (= 1 (event-store/get-sequence-number-for-id (assoc ctx :id "id1")))) (is (= 2 (event-store/get-sequence-number-for-id (assoc ctx :id "id2")))) (is (= "id1" (event-store/get-id-for-sequence-number (assoc ctx :sequence 1)))) (is (= "id2" (event-store/get-id-for-sequence-number (assoc ctx :sequence 2)))))) (deftest when-sequnce-null-then-fail (with-mock-dal (is (thrown? AssertionError (dal/store-sequence {:id nil}))) (dal/store-sequence {:id "id2"}) (is (= "id2" (event-store/get-id-for-sequence-number (assoc ctx :sequence 1)))) (is (thrown? AssertionError (event-store/get-id-for-sequence-number (assoc ctx :sequence nil)))) (is (thrown? AssertionError (event-store/get-sequence-number-for-id (assoc ctx :id nil)))))) (deftest when-sequence-exists-then-exception (with-mock-dal (dal/store-sequence {:id 1}) (is (thrown? RuntimeException (dal/store-sequence {:id 1}))) (verify-state [{:id 1 :value 1}] :sequence-store))) (deftest when-store-identity-then-ok (with-mock-dal (dal/store-identity {:identity 1 :id 1}) (dal/store-identity {:identity 2 :id 2}) (verify-state [{:identity 1 :id 1} {:identity 2 :id 2}] :identity-store))) (deftest when-identity-exists-then-exception (with-mock-dal (dal/store-identity {:identity 1}) (is (thrown? RuntimeException (dal/store-identity {:identity 1}))) (verify-state [{:identity 1}] :identity-store))) (deftest when-store-command-then-ok (with-mock-dal (dal/store-command {:service "test-service" :payload "payload"}) (verify-state [{:service "test-service" :payload "payload"}] :command-store))) (deftest when-identity-exists-then-id-for-aggregate-can-be-fetched (with-mock-dal (dal/store-identity {:identity 1 :id 2}) (verify-state [{:identity 1 :id 2}] :identity-store) (is (= 2 (event-store/get-aggregate-id-by-identity (assoc ctx :identity 1)))))) (def events [{:event-id :name :name "Me" :event-seq 1 :id 2} {:event-id :name :name "<NAME>" :event-seq 2 :id 2}]) (deftest test-that-events-can-be-fetched-by-aggregate-id (with-mock-dal (dal/store-event (first events)) (dal/store-event (second events)) (dal/store-event {:event-id :name :name "Bla" :event-seq 3 :id 4}) (verify-state (conj events {:event-id :name :name "Bla" :event-seq 3 :id 4}) :event-store) (is (= {:name "Your" :version 2 :id 2} (-> ctx (edd/reg-event :name (fn [state event] {:name (:name event) :id (:id event)})) (assoc :id 2) (common/get-by-id) :aggregate))))) (deftest when-no-result-by-id-return-nil (with-mock-dal (dal/store-event (first events)) (verify-state [(first events)] :event-store) (is (= {:aggregate nil} (select-keys (common/get-by-id (assoc ctx :id 5)) [:aggregate]))))) (deftest when-no-id-passed-in-return-nil (with-mock-dal (dal/store-event (first events)) (verify-state [(first events)] :event-store) (is (= nil (common/get-by-id ctx {}))))) (deftest verify-predefined-state (with-mock-dal {:event-store [{:event-id :e1}]} (verify-state [{:event-id :e1}] :event-store) (verify-state [] :command-store) (dal/store-event (first events)) (verify-state [{:event-id :e1} (first events)] :event-store) (is (= nil (:aggregate (common/get-by-id (assoc ctx :id 5))))) (is (= nil (:aggregate (common/get-by-id {:id 5})))))) (def v1 {:id 1 :at1 "val1-1" :at2 {:at3 "val1-3" :at4 "val1-4"}}) (def v2 {:id 2 :at1 "val2-1" :at2 {:at3 "val2-3" :at4 "val2-4"}}) (deftest test-simple-search-result (with-mock-dal (view-store/update-aggregate (assoc ctx :aggregate v1)) (view-store/update-aggregate (assoc ctx :aggregate v2)) (let [resp (view-store/simple-search (assoc ctx :query {:query-id :id1 :at1 "val2-1" :at2 {:at4 "val2-4"}}))] (is (= v2 (first resp)))))) (def e1 {:id 1 :event-seq 1}) (def e2 {:id 1 :event-seq 2}) (deftest test-event-seq-and-event-order (with-mock-dal (dal/store-event e1) (dal/store-event e2) (is (= 2 (event-store/get-max-event-seq (assoc ctx :id 1)))) (is (= 0 (event-store/get-max-event-seq (assoc ctx :id 3)))) (is (= [e1 e2] (event-store/get-events (assoc ctx :id 1)))))) (deftest test-reverse-event-order-1 (with-mock-dal (dal/store-event e1) (dal/store-event e2) (is (= [e1 e2] (event-store/get-events (assoc ctx :id 1)))))) (deftest test-reverse-event-order-2 (with-mock-dal {:command-store [{:cmd 1}] :event-store [{:event :bla}]} (is (= {:aggregate-store [] :command-store [{:cmd 1}] :event-store [{:event :bla}] :identity-store [] :sequence-store []} (peek-state))) (is (= [{:cmd 1}] (peek-state :command-store))) (is (= [{:event :bla}] (peek-state :event-store))) (is (= [{:event :bla}] (pop-state :event-store))) (is (= {:aggregate-store [] :command-store [{:cmd 1}] :event-store [] :identity-store [] :sequence-store []} (peek-state))))) (deftest test-simple-query (is (= {:size 600 :query {:bool {:must [{:term {:first.keyword "zeko"}} {:term {:last.two.keyword "d"}}]}}} (util/to-edn (elastic/create-simple-query {:first "zeko" :last {:two "d"}}))))) (def elk-objects [{:attrs {:cocunut "222996" :cognos "ABADEK" :company "Abade Immobilienleasing GmbH & Co Projekt Lauterbach KG, 65760 Eschborn (DE)" :ifrs "Group Corporates & Markets" :int "Financial Institution acc. CRR /BWG" :iso "DE" :key-account "<KEY>" :oenb-id-number "8324301" :parent-id "#74094776-3cd9-4b48-9deb-4c38b3c96435" :parent-short-name "RLGMBH GROUP" :rbi-group-cocunut "222996" :rbi-knr "" :reporting-ccy "EUR" :share-in-% "6,00%" :short-code "ABADEKG" :short-name "ABADEKG" :sorter "Leasing Austria" :type ":booking-company"} :cocunut "222996" :id "#e1a1e96f-93bb-4fdd-9605-ef2b38c1c458" :parents ["#74094776-3cd9-4b48-9deb-4c38b3c96435"] :state ":detached"} {:attrs {:cocunut "188269" :cognos "ABADE" :company "Abade Immobilienleasing GmbH, 65760 Eschborn (DE)" :ifrs "Group Corporates & Markets" :int "Financial Institution acc. CRR /BWG" :iso "DE" :key-account "<KEY>" :oenb-id-number "8142262" :parent-id "#74094776-3cd9-4b48-9deb-4c38b3c96435" :parent-short-name "RLGMBH GROUP" :rbi-group-cocunut "188269" :rbi-knr "" :reporting-ccy "EUR" :share-in-% "100,00%" :short-code "ABADE" :short-name "ABADE" :sorter "Leasing Austria" :type ":booking-company"} :cocunut "188269" :id "#7c30b6a3-2816-4378-8ed9-0b73b61012d4" :parents ["#74094776-3cd9-4b48-9deb-4c38b3c96435"] :state ":detached"}]) (def elk-response (future {:opts {:body (util/to-json {:size 600 :query {:bool {:must [{:match {:attrs.type ":booking-company"}}]}}}), :headers {"Content-Type" "application/json" "X-Amz-Date" "20200818T113334Z"}, :timeout 5000, :keepalive 300000, :method :post :url "https://vpc-mock.eu-central-1.es.amazonaws.com/glms_risk_taker_svc/_search"} :body (util/to-json {:took 42, :timed_out false, :_shards {:total 5, :successful 5, :skipped 0, :failed 0}, :hits {:total {:value 2, :relation "eq"}, :max_score 0.09304003, :hits [{:_index "glms_risk_taker_svc", :_type "_doc", :_id "e1a1e96f-93bb-4fdd-9605-ef2b38c1c458", :_score 0.09304003, :_source (first elk-objects)} {:_index "glms_risk_taker_svc", :_type "_doc", :_id "7c30b6a3-2816-4378-8ed9-0b73b61012d4", :_score 0.09304003, :_source (second elk-objects)}]}}) :headers {:access-control-allow-origin "*" :connection "keep-alive" :content-encoding "gzip"}, :status 200})) (deftest elastic-search (with-redefs [http/post (fn [url req] elk-response)] (is (= elk-objects (search/simple-search (-> {} (elastic-view/register) (assoc :service-name "test" :query {}))))))) (deftest when-identity-exists-then-exception (with-mock-dal (dal/store-identity {:id "id1" :identity 1}) (is (thrown? RuntimeException (dal/store-identity {:id "id1" :identity 1}))) (verify-state [{:id "id1" :identity 1}] :identity-store))) (deftest when-identity-exists-then-ok (with-mock-dal (dal/store-identity {:id "id1" :identity 1}) (dal/store-identity {:id "id1" :identity 2}) (verify-state [{:id "id1" :identity 1} {:id "id1" :identity 2}] :identity-store))) (deftest test-identity-generation (with-mock-dal {:identities {"id1" "some-id"}} (is (= "some-id" (common/create-identity "id1"))))) (deftest verify-state-fn-ok-test (with-mock-dal {:aggregate-store [{:a "a" :b "b"} {:a "c" :d "d"}]} (verify-state-fn :aggregate-store #(dissoc % :a) [{:b "b"} {:d "d"}]))) (deftest apply-cmd-test (with-mock-dal (let [id (uuid/gen) ctx (-> mock/ctx (edd/reg-cmd :test-cmd (fn [ctx cmd] {:event-id :1})) (edd/reg-cmd :test-cmd-fx (fn [ctx cmd] {:event-id :2})) (edd/reg-fx (fn [ctx [event]] (case (:event-id event) :1 [] :2 {:cmd-id :fx-cmd :attrs event}))))] (mock/apply-cmd ctx {:cmd-id :test-cmd :id id}) (is (= {:effects [] :events 1 :identities 0 :meta [{:test-cmd {:id id}}] :sequences 0 :success true} (mock/handle-cmd ctx {:cmd-id :test-cmd :id id}))) (is (= {:commands [] :events [{:event-id :1 :event-seq 3 :id id}] :identities [] :meta [{:test-cmd {:id id}}] :sequences []} (mock/get-commands-response ctx {:cmd-id :test-cmd :id id}))) (let [request-id (uuid/gen) interaction-id (uuid/gen)] (testing "Wirth included meta" (is (= {:commands [{:breadcrumbs [0 0] :commands [{:cmd-id :fx-cmd :attrs {:event-id :2 :id id}}] :interaction-id interaction-id :meta {:realm :realm2} :request-id request-id :service nil}] :events [{:event-id :2 :event-seq 4 :id id :meta {:realm :realm2} :request-id request-id :interaction-id interaction-id}] :identities [] :meta [{:test-cmd-fx {:id id}}] :sequences []} (mock/get-commands-response (assoc ctx :include-meta true :request-id request-id :interaction-id interaction-id) {:commands [{:cmd-id :test-cmd-fx :id id}] :meta {:realm :realm2} :request-id request-id :interaction-id interaction-id})))) (testing "Without including meta" (mock/verify-state :command-store [{:commands [{:cmd-id :fx-cmd :attrs {:event-id :2 :id id}}] :meta {:realm :realm2} :service nil}]) (is (= {:commands [{:breadcrumbs [0 0] :commands [{:cmd-id :fx-cmd :attrs {:event-id :2 :id id}}] :service nil}] :events [{:event-id :2 :event-seq 4 :id id}] :identities [] :meta [{:test-cmd-fx {:id id}}] :sequences []} (mock/get-commands-response (assoc ctx :request-id request-id :interaction-id interaction-id) {:commands [{:cmd-id :test-cmd-fx :id id}] :meta {:realm :realm2} :request-id request-id :interaction-id interaction-id})))))))) (defn my-command-handler [ctx cmd] (println "bAAAA")) (defn register [ctx] (-> ctx (edd/reg-cmd :cmd-1 my-command-handler :dps {:facility (fn [cmd] {:query-id :query-1 :identity (:external cmd)})}) (edd/reg-query :query-1 (fn [ctx query] (let [id (common/get-aggregate-id-by-identity ctx query)] (common/get-by-id ctx id)))))) (deftest test-identity-query (let [agg-id (uuid/gen)] (with-mock-dal {:identity-store [{:id agg-id :identity "ext-1"}] :aggregate-store [{:version 3 :id agg-id :attrs {:some :value}}]} (with-redefs [my-command-handler (fn [ctx cmd] (is (= {:attrs {:some :value} :id agg-id :version 3} (:facility ctx))) [])] (mock/apply-cmd (register ctx) {:cmd-id :cmd-1 :id (uuid/gen) :external "ext-1"})))))
true
(ns edd.test.fixture.dal-test (:require [edd.test.fixture.dal :refer [verify-state ctx with-mock-dal pop-state peek-state verify-state-fn]] [edd.common :as common] [edd.search :as search] [edd.core :as edd] [edd.dal :as event-store] [edd.memory.event-store :as dal] [edd.elastic.view-store :as elastic-view] [edd.search :as view-store] [clojure.test :refer :all] [org.httpkit.client :as http] [edd.elastic.view-store :as elastic] [lambda.util :as util] [edd.test.fixture.dal :as mock] [lambda.uuid :as uuid])) (deftest when-store-and-load-events-then-ok (with-mock-dal (dal/store-event {:id 1 :info "info"}) (verify-state [{:id 1 :info "info"}] :event-store) (let [events (event-store/get-events (assoc ctx :id 1))] (is (= [{:id 1 :info "info"}] events))))) (deftest when-update-aggregate-then-ok (with-mock-dal (view-store/update-aggregate (assoc ctx :aggregate {:id 1 :payload "payload"})) (verify-state [{:id 1 :payload "payload"}] :aggregate-store) (view-store/update-aggregate (assoc ctx :aggregate {:id 1 :payload "payload2"})) (verify-state [{:id 1 :payload "payload2"}] :aggregate-store))) (deftest when-query-aggregate-with-unknown-condition-then-return-nothing (with-mock-dal (view-store/update-aggregate (assoc ctx :aggregate {:id 1 :payload "payload"})) (view-store/update-aggregate (assoc ctx :aggregate {:id 2 :payload "payload"})) (view-store/update-aggregate (assoc ctx :aggregate {:id 3 :payload "pa2"})) (is (= [{:id 3 :payload "pa2"}] (view-store/simple-search (assoc ctx :query {:id 3})))) (is (= [] (view-store/simple-search (assoc ctx :query {:id 4})))))) (deftest when-store-sequence-then-ok (with-mock-dal (dal/store-sequence {:id "id1"}) (dal/store-sequence {:id "id2"}) (verify-state [{:id "id1" :value 1} {:id "id2" :value 2}] :sequence-store) (is (= 1 (event-store/get-sequence-number-for-id (assoc ctx :id "id1")))) (is (= 2 (event-store/get-sequence-number-for-id (assoc ctx :id "id2")))) (is (= "id1" (event-store/get-id-for-sequence-number (assoc ctx :sequence 1)))) (is (= "id2" (event-store/get-id-for-sequence-number (assoc ctx :sequence 2)))))) (deftest when-sequnce-null-then-fail (with-mock-dal (is (thrown? AssertionError (dal/store-sequence {:id nil}))) (dal/store-sequence {:id "id2"}) (is (= "id2" (event-store/get-id-for-sequence-number (assoc ctx :sequence 1)))) (is (thrown? AssertionError (event-store/get-id-for-sequence-number (assoc ctx :sequence nil)))) (is (thrown? AssertionError (event-store/get-sequence-number-for-id (assoc ctx :id nil)))))) (deftest when-sequence-exists-then-exception (with-mock-dal (dal/store-sequence {:id 1}) (is (thrown? RuntimeException (dal/store-sequence {:id 1}))) (verify-state [{:id 1 :value 1}] :sequence-store))) (deftest when-store-identity-then-ok (with-mock-dal (dal/store-identity {:identity 1 :id 1}) (dal/store-identity {:identity 2 :id 2}) (verify-state [{:identity 1 :id 1} {:identity 2 :id 2}] :identity-store))) (deftest when-identity-exists-then-exception (with-mock-dal (dal/store-identity {:identity 1}) (is (thrown? RuntimeException (dal/store-identity {:identity 1}))) (verify-state [{:identity 1}] :identity-store))) (deftest when-store-command-then-ok (with-mock-dal (dal/store-command {:service "test-service" :payload "payload"}) (verify-state [{:service "test-service" :payload "payload"}] :command-store))) (deftest when-identity-exists-then-id-for-aggregate-can-be-fetched (with-mock-dal (dal/store-identity {:identity 1 :id 2}) (verify-state [{:identity 1 :id 2}] :identity-store) (is (= 2 (event-store/get-aggregate-id-by-identity (assoc ctx :identity 1)))))) (def events [{:event-id :name :name "Me" :event-seq 1 :id 2} {:event-id :name :name "PI:NAME:<NAME>END_PI" :event-seq 2 :id 2}]) (deftest test-that-events-can-be-fetched-by-aggregate-id (with-mock-dal (dal/store-event (first events)) (dal/store-event (second events)) (dal/store-event {:event-id :name :name "Bla" :event-seq 3 :id 4}) (verify-state (conj events {:event-id :name :name "Bla" :event-seq 3 :id 4}) :event-store) (is (= {:name "Your" :version 2 :id 2} (-> ctx (edd/reg-event :name (fn [state event] {:name (:name event) :id (:id event)})) (assoc :id 2) (common/get-by-id) :aggregate))))) (deftest when-no-result-by-id-return-nil (with-mock-dal (dal/store-event (first events)) (verify-state [(first events)] :event-store) (is (= {:aggregate nil} (select-keys (common/get-by-id (assoc ctx :id 5)) [:aggregate]))))) (deftest when-no-id-passed-in-return-nil (with-mock-dal (dal/store-event (first events)) (verify-state [(first events)] :event-store) (is (= nil (common/get-by-id ctx {}))))) (deftest verify-predefined-state (with-mock-dal {:event-store [{:event-id :e1}]} (verify-state [{:event-id :e1}] :event-store) (verify-state [] :command-store) (dal/store-event (first events)) (verify-state [{:event-id :e1} (first events)] :event-store) (is (= nil (:aggregate (common/get-by-id (assoc ctx :id 5))))) (is (= nil (:aggregate (common/get-by-id {:id 5})))))) (def v1 {:id 1 :at1 "val1-1" :at2 {:at3 "val1-3" :at4 "val1-4"}}) (def v2 {:id 2 :at1 "val2-1" :at2 {:at3 "val2-3" :at4 "val2-4"}}) (deftest test-simple-search-result (with-mock-dal (view-store/update-aggregate (assoc ctx :aggregate v1)) (view-store/update-aggregate (assoc ctx :aggregate v2)) (let [resp (view-store/simple-search (assoc ctx :query {:query-id :id1 :at1 "val2-1" :at2 {:at4 "val2-4"}}))] (is (= v2 (first resp)))))) (def e1 {:id 1 :event-seq 1}) (def e2 {:id 1 :event-seq 2}) (deftest test-event-seq-and-event-order (with-mock-dal (dal/store-event e1) (dal/store-event e2) (is (= 2 (event-store/get-max-event-seq (assoc ctx :id 1)))) (is (= 0 (event-store/get-max-event-seq (assoc ctx :id 3)))) (is (= [e1 e2] (event-store/get-events (assoc ctx :id 1)))))) (deftest test-reverse-event-order-1 (with-mock-dal (dal/store-event e1) (dal/store-event e2) (is (= [e1 e2] (event-store/get-events (assoc ctx :id 1)))))) (deftest test-reverse-event-order-2 (with-mock-dal {:command-store [{:cmd 1}] :event-store [{:event :bla}]} (is (= {:aggregate-store [] :command-store [{:cmd 1}] :event-store [{:event :bla}] :identity-store [] :sequence-store []} (peek-state))) (is (= [{:cmd 1}] (peek-state :command-store))) (is (= [{:event :bla}] (peek-state :event-store))) (is (= [{:event :bla}] (pop-state :event-store))) (is (= {:aggregate-store [] :command-store [{:cmd 1}] :event-store [] :identity-store [] :sequence-store []} (peek-state))))) (deftest test-simple-query (is (= {:size 600 :query {:bool {:must [{:term {:first.keyword "zeko"}} {:term {:last.two.keyword "d"}}]}}} (util/to-edn (elastic/create-simple-query {:first "zeko" :last {:two "d"}}))))) (def elk-objects [{:attrs {:cocunut "222996" :cognos "ABADEK" :company "Abade Immobilienleasing GmbH & Co Projekt Lauterbach KG, 65760 Eschborn (DE)" :ifrs "Group Corporates & Markets" :int "Financial Institution acc. CRR /BWG" :iso "DE" :key-account "PI:KEY:<KEY>END_PI" :oenb-id-number "8324301" :parent-id "#74094776-3cd9-4b48-9deb-4c38b3c96435" :parent-short-name "RLGMBH GROUP" :rbi-group-cocunut "222996" :rbi-knr "" :reporting-ccy "EUR" :share-in-% "6,00%" :short-code "ABADEKG" :short-name "ABADEKG" :sorter "Leasing Austria" :type ":booking-company"} :cocunut "222996" :id "#e1a1e96f-93bb-4fdd-9605-ef2b38c1c458" :parents ["#74094776-3cd9-4b48-9deb-4c38b3c96435"] :state ":detached"} {:attrs {:cocunut "188269" :cognos "ABADE" :company "Abade Immobilienleasing GmbH, 65760 Eschborn (DE)" :ifrs "Group Corporates & Markets" :int "Financial Institution acc. CRR /BWG" :iso "DE" :key-account "PI:KEY:<KEY>END_PI" :oenb-id-number "8142262" :parent-id "#74094776-3cd9-4b48-9deb-4c38b3c96435" :parent-short-name "RLGMBH GROUP" :rbi-group-cocunut "188269" :rbi-knr "" :reporting-ccy "EUR" :share-in-% "100,00%" :short-code "ABADE" :short-name "ABADE" :sorter "Leasing Austria" :type ":booking-company"} :cocunut "188269" :id "#7c30b6a3-2816-4378-8ed9-0b73b61012d4" :parents ["#74094776-3cd9-4b48-9deb-4c38b3c96435"] :state ":detached"}]) (def elk-response (future {:opts {:body (util/to-json {:size 600 :query {:bool {:must [{:match {:attrs.type ":booking-company"}}]}}}), :headers {"Content-Type" "application/json" "X-Amz-Date" "20200818T113334Z"}, :timeout 5000, :keepalive 300000, :method :post :url "https://vpc-mock.eu-central-1.es.amazonaws.com/glms_risk_taker_svc/_search"} :body (util/to-json {:took 42, :timed_out false, :_shards {:total 5, :successful 5, :skipped 0, :failed 0}, :hits {:total {:value 2, :relation "eq"}, :max_score 0.09304003, :hits [{:_index "glms_risk_taker_svc", :_type "_doc", :_id "e1a1e96f-93bb-4fdd-9605-ef2b38c1c458", :_score 0.09304003, :_source (first elk-objects)} {:_index "glms_risk_taker_svc", :_type "_doc", :_id "7c30b6a3-2816-4378-8ed9-0b73b61012d4", :_score 0.09304003, :_source (second elk-objects)}]}}) :headers {:access-control-allow-origin "*" :connection "keep-alive" :content-encoding "gzip"}, :status 200})) (deftest elastic-search (with-redefs [http/post (fn [url req] elk-response)] (is (= elk-objects (search/simple-search (-> {} (elastic-view/register) (assoc :service-name "test" :query {}))))))) (deftest when-identity-exists-then-exception (with-mock-dal (dal/store-identity {:id "id1" :identity 1}) (is (thrown? RuntimeException (dal/store-identity {:id "id1" :identity 1}))) (verify-state [{:id "id1" :identity 1}] :identity-store))) (deftest when-identity-exists-then-ok (with-mock-dal (dal/store-identity {:id "id1" :identity 1}) (dal/store-identity {:id "id1" :identity 2}) (verify-state [{:id "id1" :identity 1} {:id "id1" :identity 2}] :identity-store))) (deftest test-identity-generation (with-mock-dal {:identities {"id1" "some-id"}} (is (= "some-id" (common/create-identity "id1"))))) (deftest verify-state-fn-ok-test (with-mock-dal {:aggregate-store [{:a "a" :b "b"} {:a "c" :d "d"}]} (verify-state-fn :aggregate-store #(dissoc % :a) [{:b "b"} {:d "d"}]))) (deftest apply-cmd-test (with-mock-dal (let [id (uuid/gen) ctx (-> mock/ctx (edd/reg-cmd :test-cmd (fn [ctx cmd] {:event-id :1})) (edd/reg-cmd :test-cmd-fx (fn [ctx cmd] {:event-id :2})) (edd/reg-fx (fn [ctx [event]] (case (:event-id event) :1 [] :2 {:cmd-id :fx-cmd :attrs event}))))] (mock/apply-cmd ctx {:cmd-id :test-cmd :id id}) (is (= {:effects [] :events 1 :identities 0 :meta [{:test-cmd {:id id}}] :sequences 0 :success true} (mock/handle-cmd ctx {:cmd-id :test-cmd :id id}))) (is (= {:commands [] :events [{:event-id :1 :event-seq 3 :id id}] :identities [] :meta [{:test-cmd {:id id}}] :sequences []} (mock/get-commands-response ctx {:cmd-id :test-cmd :id id}))) (let [request-id (uuid/gen) interaction-id (uuid/gen)] (testing "Wirth included meta" (is (= {:commands [{:breadcrumbs [0 0] :commands [{:cmd-id :fx-cmd :attrs {:event-id :2 :id id}}] :interaction-id interaction-id :meta {:realm :realm2} :request-id request-id :service nil}] :events [{:event-id :2 :event-seq 4 :id id :meta {:realm :realm2} :request-id request-id :interaction-id interaction-id}] :identities [] :meta [{:test-cmd-fx {:id id}}] :sequences []} (mock/get-commands-response (assoc ctx :include-meta true :request-id request-id :interaction-id interaction-id) {:commands [{:cmd-id :test-cmd-fx :id id}] :meta {:realm :realm2} :request-id request-id :interaction-id interaction-id})))) (testing "Without including meta" (mock/verify-state :command-store [{:commands [{:cmd-id :fx-cmd :attrs {:event-id :2 :id id}}] :meta {:realm :realm2} :service nil}]) (is (= {:commands [{:breadcrumbs [0 0] :commands [{:cmd-id :fx-cmd :attrs {:event-id :2 :id id}}] :service nil}] :events [{:event-id :2 :event-seq 4 :id id}] :identities [] :meta [{:test-cmd-fx {:id id}}] :sequences []} (mock/get-commands-response (assoc ctx :request-id request-id :interaction-id interaction-id) {:commands [{:cmd-id :test-cmd-fx :id id}] :meta {:realm :realm2} :request-id request-id :interaction-id interaction-id})))))))) (defn my-command-handler [ctx cmd] (println "bAAAA")) (defn register [ctx] (-> ctx (edd/reg-cmd :cmd-1 my-command-handler :dps {:facility (fn [cmd] {:query-id :query-1 :identity (:external cmd)})}) (edd/reg-query :query-1 (fn [ctx query] (let [id (common/get-aggregate-id-by-identity ctx query)] (common/get-by-id ctx id)))))) (deftest test-identity-query (let [agg-id (uuid/gen)] (with-mock-dal {:identity-store [{:id agg-id :identity "ext-1"}] :aggregate-store [{:version 3 :id agg-id :attrs {:some :value}}]} (with-redefs [my-command-handler (fn [ctx cmd] (is (= {:attrs {:some :value} :id agg-id :version 3} (:facility ctx))) [])] (mock/apply-cmd (register ctx) {:cmd-id :cmd-1 :id (uuid/gen) :external "ext-1"})))))
[ { "context": "; Copyright 2020 Mark Wardle and Eldrix Ltd\n;\n; Licensed under the Apache Li", "end": 28, "score": 0.9998611807823181, "start": 17, "tag": "NAME", "value": "Mark Wardle" }, { "context": "ore))))\n\n(comment\n (import-dmd \"dmd3.db\" \"/Users/mark/Downloads/nhsbsa_dmd_12.1.0_20201214000001\")\n (d", "end": 4119, "score": 0.9002923965454102, "start": 4115, "tag": "USERNAME", "value": "mark" } ]
src/com/eldrix/hermes/ext/uk/dmd/store.clj
sidharthramesh/hermes
0
; Copyright 2020 Mark Wardle and Eldrix Ltd ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ;;;; (ns com.eldrix.hermes.ext.uk.dmd.store "A simple key value store for UK dm+d data. This is principally designed to be used as part of a wider SNOMED terminology server, so certain data are deliberately omitted by default." (:require [clojure.core.async :as a] [clojure.java.io :as io] [clojure.tools.logging.readable :as log] [com.eldrix.hermes.ext.uk.dmd.import :as dmd-import]) (:import (org.mapdb DB Serializer DBMaker BTreeMap) (java.io FileNotFoundException Closeable) (org.mapdb.serializer SerializerArrayTuple))) (deftype DmdStore [^DB db ^BTreeMap core ^BTreeMap lookups] Closeable (close [this] (.close ^DB (.db this)))) (defn open-dmd-store ([^String filename] (open-dmd-store filename {})) ([^String filename {:keys [read-only? skip-check?] :or {read-only? true}}] (when (and read-only? (not (.exists (io/as-file filename)))) (throw (FileNotFoundException. (str "file `" filename "` opened read-only but not found")))) (let [db (.make (cond-> (-> (DBMaker/fileDB filename) (.fileMmapEnable) (.closeOnJvmShutdown)) skip-check? (.checksumHeaderBypass) read-only? (.readOnly))) ;; core dm+d components are stored keyed with identifier core (.createOrOpen (.treeMap db "core" Serializer/LONG Serializer/JAVA)) ;; lookup tables are stored keyed with tableName-code as a string lookups (.createOrOpen (.treeMap db "lookups" Serializer/STRING Serializer/JAVA))] (->DmdStore db core lookups)))) ;; core dm+d components (derive :uk.nhs.dmd/VTM :uk.nhs.dmd/COMPONENT) (derive :uk.nhs.dmd/VMP :uk.nhs.dmd/COMPONENT) (derive :uk.nhs.dmd/AMP :uk.nhs.dmd/COMPONENT) (derive :uk.nhs.dmd/AMPP :uk.nhs.dmd/COMPONENT) (derive :uk.nhs.dmd/VMPP :uk.nhs.dmd/COMPONENT) (defmulti put "Store an arbitrary dm+d component into the backing store. Parameters: - store : DmdStore - m : component / VTM / VMP / VMPP / AMP / AMPP / TF / TFG" (fn [^DmdStore store m] (:TYPE m))) (defmethod put :uk.nhs.dmd/COMPONENT [^DmdStore store component] (.put ^BTreeMap (.core store) (:ID component) component)) (defmethod put :uk.nhs.dmd/LOOKUP [^DmdStore store lookup] (.put ^BTreeMap (.-lookups store) (name (:ID lookup)) (dissoc lookup :ID))) (defmethod put :default [^DmdStore store component] (let [[concept-id property] (:ID component)] (if-let [v (.get ^BTreeMap (.core store) concept-id)] (let [new-value (update v property (fn [old] ((fnil conj []) old (dissoc component :ID :TYPE))))] (.put ^BTreeMap (.core store) concept-id new-value)) (throw (ex-info "no existing component for id" {:id concept-id :component component}))))) (defn import-dmd [filename dir] (let [ch (a/chan) store (open-dmd-store filename {:read-only? false})] (a/thread (dmd-import/import-dmd dir ch {:exclude [:INGREDIENT :INGREDIENT]})) (loop [m (a/<!! ch)] (when m (try (put store m) (catch Exception e (throw (ex-info "failed to import" {:e e :component m})))) (recur (a/<!! ch)))) (log/debug "compacting data store") (.compact (.getStore ^BTreeMap (.core store))) (log/debug "import/compaction completed") (.close ^DB (.db store)))) (comment (import-dmd "dmd3.db" "/Users/mark/Downloads/nhsbsa_dmd_12.1.0_20201214000001") (def store (open-dmd-store "dmd3.db")) (.get (.core store) 39211611000001104) (.get (.core store) 39233511000001107) (.get (.lookups store) (name :VIRTUAL_PRODUCT_NON_AVAIL-0001)) (.get (.lookups store) (name :CONTROL_DRUG_CATEGORY-0000)) (.get (.lookups store) (name :ONT_FORM_ROUTE-0022)) (.lookups store) )
11612
; Copyright 2020 <NAME> and Eldrix Ltd ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ;;;; (ns com.eldrix.hermes.ext.uk.dmd.store "A simple key value store for UK dm+d data. This is principally designed to be used as part of a wider SNOMED terminology server, so certain data are deliberately omitted by default." (:require [clojure.core.async :as a] [clojure.java.io :as io] [clojure.tools.logging.readable :as log] [com.eldrix.hermes.ext.uk.dmd.import :as dmd-import]) (:import (org.mapdb DB Serializer DBMaker BTreeMap) (java.io FileNotFoundException Closeable) (org.mapdb.serializer SerializerArrayTuple))) (deftype DmdStore [^DB db ^BTreeMap core ^BTreeMap lookups] Closeable (close [this] (.close ^DB (.db this)))) (defn open-dmd-store ([^String filename] (open-dmd-store filename {})) ([^String filename {:keys [read-only? skip-check?] :or {read-only? true}}] (when (and read-only? (not (.exists (io/as-file filename)))) (throw (FileNotFoundException. (str "file `" filename "` opened read-only but not found")))) (let [db (.make (cond-> (-> (DBMaker/fileDB filename) (.fileMmapEnable) (.closeOnJvmShutdown)) skip-check? (.checksumHeaderBypass) read-only? (.readOnly))) ;; core dm+d components are stored keyed with identifier core (.createOrOpen (.treeMap db "core" Serializer/LONG Serializer/JAVA)) ;; lookup tables are stored keyed with tableName-code as a string lookups (.createOrOpen (.treeMap db "lookups" Serializer/STRING Serializer/JAVA))] (->DmdStore db core lookups)))) ;; core dm+d components (derive :uk.nhs.dmd/VTM :uk.nhs.dmd/COMPONENT) (derive :uk.nhs.dmd/VMP :uk.nhs.dmd/COMPONENT) (derive :uk.nhs.dmd/AMP :uk.nhs.dmd/COMPONENT) (derive :uk.nhs.dmd/AMPP :uk.nhs.dmd/COMPONENT) (derive :uk.nhs.dmd/VMPP :uk.nhs.dmd/COMPONENT) (defmulti put "Store an arbitrary dm+d component into the backing store. Parameters: - store : DmdStore - m : component / VTM / VMP / VMPP / AMP / AMPP / TF / TFG" (fn [^DmdStore store m] (:TYPE m))) (defmethod put :uk.nhs.dmd/COMPONENT [^DmdStore store component] (.put ^BTreeMap (.core store) (:ID component) component)) (defmethod put :uk.nhs.dmd/LOOKUP [^DmdStore store lookup] (.put ^BTreeMap (.-lookups store) (name (:ID lookup)) (dissoc lookup :ID))) (defmethod put :default [^DmdStore store component] (let [[concept-id property] (:ID component)] (if-let [v (.get ^BTreeMap (.core store) concept-id)] (let [new-value (update v property (fn [old] ((fnil conj []) old (dissoc component :ID :TYPE))))] (.put ^BTreeMap (.core store) concept-id new-value)) (throw (ex-info "no existing component for id" {:id concept-id :component component}))))) (defn import-dmd [filename dir] (let [ch (a/chan) store (open-dmd-store filename {:read-only? false})] (a/thread (dmd-import/import-dmd dir ch {:exclude [:INGREDIENT :INGREDIENT]})) (loop [m (a/<!! ch)] (when m (try (put store m) (catch Exception e (throw (ex-info "failed to import" {:e e :component m})))) (recur (a/<!! ch)))) (log/debug "compacting data store") (.compact (.getStore ^BTreeMap (.core store))) (log/debug "import/compaction completed") (.close ^DB (.db store)))) (comment (import-dmd "dmd3.db" "/Users/mark/Downloads/nhsbsa_dmd_12.1.0_20201214000001") (def store (open-dmd-store "dmd3.db")) (.get (.core store) 39211611000001104) (.get (.core store) 39233511000001107) (.get (.lookups store) (name :VIRTUAL_PRODUCT_NON_AVAIL-0001)) (.get (.lookups store) (name :CONTROL_DRUG_CATEGORY-0000)) (.get (.lookups store) (name :ONT_FORM_ROUTE-0022)) (.lookups store) )
true
; Copyright 2020 PI:NAME:<NAME>END_PI and Eldrix Ltd ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ;;;; (ns com.eldrix.hermes.ext.uk.dmd.store "A simple key value store for UK dm+d data. This is principally designed to be used as part of a wider SNOMED terminology server, so certain data are deliberately omitted by default." (:require [clojure.core.async :as a] [clojure.java.io :as io] [clojure.tools.logging.readable :as log] [com.eldrix.hermes.ext.uk.dmd.import :as dmd-import]) (:import (org.mapdb DB Serializer DBMaker BTreeMap) (java.io FileNotFoundException Closeable) (org.mapdb.serializer SerializerArrayTuple))) (deftype DmdStore [^DB db ^BTreeMap core ^BTreeMap lookups] Closeable (close [this] (.close ^DB (.db this)))) (defn open-dmd-store ([^String filename] (open-dmd-store filename {})) ([^String filename {:keys [read-only? skip-check?] :or {read-only? true}}] (when (and read-only? (not (.exists (io/as-file filename)))) (throw (FileNotFoundException. (str "file `" filename "` opened read-only but not found")))) (let [db (.make (cond-> (-> (DBMaker/fileDB filename) (.fileMmapEnable) (.closeOnJvmShutdown)) skip-check? (.checksumHeaderBypass) read-only? (.readOnly))) ;; core dm+d components are stored keyed with identifier core (.createOrOpen (.treeMap db "core" Serializer/LONG Serializer/JAVA)) ;; lookup tables are stored keyed with tableName-code as a string lookups (.createOrOpen (.treeMap db "lookups" Serializer/STRING Serializer/JAVA))] (->DmdStore db core lookups)))) ;; core dm+d components (derive :uk.nhs.dmd/VTM :uk.nhs.dmd/COMPONENT) (derive :uk.nhs.dmd/VMP :uk.nhs.dmd/COMPONENT) (derive :uk.nhs.dmd/AMP :uk.nhs.dmd/COMPONENT) (derive :uk.nhs.dmd/AMPP :uk.nhs.dmd/COMPONENT) (derive :uk.nhs.dmd/VMPP :uk.nhs.dmd/COMPONENT) (defmulti put "Store an arbitrary dm+d component into the backing store. Parameters: - store : DmdStore - m : component / VTM / VMP / VMPP / AMP / AMPP / TF / TFG" (fn [^DmdStore store m] (:TYPE m))) (defmethod put :uk.nhs.dmd/COMPONENT [^DmdStore store component] (.put ^BTreeMap (.core store) (:ID component) component)) (defmethod put :uk.nhs.dmd/LOOKUP [^DmdStore store lookup] (.put ^BTreeMap (.-lookups store) (name (:ID lookup)) (dissoc lookup :ID))) (defmethod put :default [^DmdStore store component] (let [[concept-id property] (:ID component)] (if-let [v (.get ^BTreeMap (.core store) concept-id)] (let [new-value (update v property (fn [old] ((fnil conj []) old (dissoc component :ID :TYPE))))] (.put ^BTreeMap (.core store) concept-id new-value)) (throw (ex-info "no existing component for id" {:id concept-id :component component}))))) (defn import-dmd [filename dir] (let [ch (a/chan) store (open-dmd-store filename {:read-only? false})] (a/thread (dmd-import/import-dmd dir ch {:exclude [:INGREDIENT :INGREDIENT]})) (loop [m (a/<!! ch)] (when m (try (put store m) (catch Exception e (throw (ex-info "failed to import" {:e e :component m})))) (recur (a/<!! ch)))) (log/debug "compacting data store") (.compact (.getStore ^BTreeMap (.core store))) (log/debug "import/compaction completed") (.close ^DB (.db store)))) (comment (import-dmd "dmd3.db" "/Users/mark/Downloads/nhsbsa_dmd_12.1.0_20201214000001") (def store (open-dmd-store "dmd3.db")) (.get (.core store) 39211611000001104) (.get (.core store) 39233511000001107) (.get (.lookups store) (name :VIRTUAL_PRODUCT_NON_AVAIL-0001)) (.get (.lookups store) (name :CONTROL_DRUG_CATEGORY-0000)) (.get (.lookups store) (name :ONT_FORM_ROUTE-0022)) (.lookups store) )
[ { "context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"wahpenayo at gmail dot com\" \n :date \"2017-12-04\"\n :doc \"simple pre", "end": 114, "score": 0.8661303520202637, "start": 88, "tag": "EMAIL", "value": "wahpenayo at gmail dot com" } ]
src/main/clojure/taigabench/pt.clj
wahpenayo/taigabench
0
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "wahpenayo at gmail dot com" :date "2017-12-04" :doc "simple prediction/truth datum" } taigabench.pt (:require [zana.api :as z])) ;;---------------------------------------------------------------- ;; TODO: just use deftype? (z/define-datum PredictionTruth [^float prediction ^float truth]) ;;---------------------------------------------------------------- (defn write-predictions [^clojure.lang.IFn$OD truth ^clojure.lang.IFn$OD predict ^Iterable trpr ^java.io.File file] (with-open [w (z/print-writer file)] (.println w "truth\tprediction") (z/mapc #(do (.print w (.invokePrim truth %)) (.print w ",") (.println w (.invokePrim predict %))) trpr))) ;;----------------------------------------------------------------
74479
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "<EMAIL>" :date "2017-12-04" :doc "simple prediction/truth datum" } taigabench.pt (:require [zana.api :as z])) ;;---------------------------------------------------------------- ;; TODO: just use deftype? (z/define-datum PredictionTruth [^float prediction ^float truth]) ;;---------------------------------------------------------------- (defn write-predictions [^clojure.lang.IFn$OD truth ^clojure.lang.IFn$OD predict ^Iterable trpr ^java.io.File file] (with-open [w (z/print-writer file)] (.println w "truth\tprediction") (z/mapc #(do (.print w (.invokePrim truth %)) (.print w ",") (.println w (.invokePrim predict %))) trpr))) ;;----------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "PI:EMAIL:<EMAIL>END_PI" :date "2017-12-04" :doc "simple prediction/truth datum" } taigabench.pt (:require [zana.api :as z])) ;;---------------------------------------------------------------- ;; TODO: just use deftype? (z/define-datum PredictionTruth [^float prediction ^float truth]) ;;---------------------------------------------------------------- (defn write-predictions [^clojure.lang.IFn$OD truth ^clojure.lang.IFn$OD predict ^Iterable trpr ^java.io.File file] (with-open [w (z/print-writer file)] (.println w "truth\tprediction") (z/mapc #(do (.print w (.invokePrim truth %)) (.print w ",") (.println w (.invokePrim predict %))) trpr))) ;;----------------------------------------------------------------
[ { "context": ";; Copyright (c) Rich Hickey. All rights reserved.\n;; The use and distributio", "end": 29, "score": 0.999800980091095, "start": 18, "tag": "NAME", "value": "Rich Hickey" } ]
examples/cordova_app/.lein-cljsbuild-compiler-0/clojure/browser/dom.cljs
cbilson/lein-robbie
5
;; Copyright (c) Rich Hickey. All rights reserved. ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns clojure.browser.dom (:require [goog.dom :as gdom])) (defn append [parent & children] (apply gdom/append parent children) parent) (defprotocol DOMBuilder (-element [this] [this attrs-or-children] [this attrs children])) (defn log [& args] (.log js/console (apply pr-str args))) (defn log-obj [obj] (.log js/console obj)) (extend-protocol DOMBuilder string (-element ([this] (log "string (-element " this ")") (cond (keyword? this) (gdom/createElement (name this)) :else (gdom/createTextNode (name this)))) ([this attrs-or-children] (log "string (-element " this " " attrs-or-children ")") (let [attrs (first attrs-or-children)] (if (map? attrs) (-element this attrs (rest attrs-or-children)) (-element this nil attrs-or-children)))) ([this attrs children] (log "string (-element " this " " attrs " " children ")") (let [str-attrs (if (and (map? attrs) (seq attrs)) (.-strobj (reduce (fn [m [k v]] (log "m = " m) (log "k = " k) (log "v = " v) (when (or (keyword? k) (string? k)) (assoc m (name k) v))) {} attrs)) nil)] (log-obj str-attrs) (if (seq children) (apply gdom/createDom (name this) str-attrs (map -element children)) (gdom/createDom (name this) str-attrs))))) Vector (-element [this] (log "Vector (-element " this ")") (let [tag (first this) attrs (second this) children (drop 2 this)] (if (map? attrs) (-element tag attrs children) (-element tag nil (rest this))))) js/Element (-element [this] (log "js/Element (-element " this ")") this)) (defn element ([tag-or-text] (log "(element " tag-or-text ")") (-element tag-or-text)) ([tag & children] (log "(element " tag " " children ")") (let [attrs (first children)] (if (map? attrs) (-element tag attrs (rest children)) (-element tag nil children))))) (defn remove-children "Remove all children from the element with the passed id." [id] (let [parent (gdom/getElement (name id))] (do (gdom/removeChildren parent)))) (defn get-element [id] (gdom/getElement (name id))) (defn html->dom [s] (gdom/htmlToDocumentFragment s)) (defn insert-at [parent child index] (gdom/insertChildAt parent child index)) (defn ensure-element "Coerce the argument to a dom element if possible." [e] (cond (keyword? e) (get-element e) (string? e) (html->dom e) :else e)) (defn replace-node "Replace old-node with new-node. old-node can be an element or a keyword which is the id of the node to replace. new-node can be an element or an html string." [old-node new-node] (let [old-node (ensure-element old-node) new-node (ensure-element new-node)] (gdom/replaceNode new-node old-node) new-node)) (defn set-text "Set the text content for the passed element returning the element. If a keyword is passed in the place of e, the element with that id will be used and returned." [e s] (gdom/setTextContent (ensure-element e) s)) (defn get-value "Get the value of an element." [e] (.-value (ensure-element e))) (defn set-properties "Set properties on an element" [e m] (gdom/setProperties (ensure-element e) (.-strobj m))) (defn set-value "Set the value property for an element." [e v] (set-properties e {"value" v})) (defn click-element [e] (.click (ensure-element e) ())) ;; TODO CSS class manipulation ;; TODO Query syntax
103243
;; Copyright (c) <NAME>. All rights reserved. ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns clojure.browser.dom (:require [goog.dom :as gdom])) (defn append [parent & children] (apply gdom/append parent children) parent) (defprotocol DOMBuilder (-element [this] [this attrs-or-children] [this attrs children])) (defn log [& args] (.log js/console (apply pr-str args))) (defn log-obj [obj] (.log js/console obj)) (extend-protocol DOMBuilder string (-element ([this] (log "string (-element " this ")") (cond (keyword? this) (gdom/createElement (name this)) :else (gdom/createTextNode (name this)))) ([this attrs-or-children] (log "string (-element " this " " attrs-or-children ")") (let [attrs (first attrs-or-children)] (if (map? attrs) (-element this attrs (rest attrs-or-children)) (-element this nil attrs-or-children)))) ([this attrs children] (log "string (-element " this " " attrs " " children ")") (let [str-attrs (if (and (map? attrs) (seq attrs)) (.-strobj (reduce (fn [m [k v]] (log "m = " m) (log "k = " k) (log "v = " v) (when (or (keyword? k) (string? k)) (assoc m (name k) v))) {} attrs)) nil)] (log-obj str-attrs) (if (seq children) (apply gdom/createDom (name this) str-attrs (map -element children)) (gdom/createDom (name this) str-attrs))))) Vector (-element [this] (log "Vector (-element " this ")") (let [tag (first this) attrs (second this) children (drop 2 this)] (if (map? attrs) (-element tag attrs children) (-element tag nil (rest this))))) js/Element (-element [this] (log "js/Element (-element " this ")") this)) (defn element ([tag-or-text] (log "(element " tag-or-text ")") (-element tag-or-text)) ([tag & children] (log "(element " tag " " children ")") (let [attrs (first children)] (if (map? attrs) (-element tag attrs (rest children)) (-element tag nil children))))) (defn remove-children "Remove all children from the element with the passed id." [id] (let [parent (gdom/getElement (name id))] (do (gdom/removeChildren parent)))) (defn get-element [id] (gdom/getElement (name id))) (defn html->dom [s] (gdom/htmlToDocumentFragment s)) (defn insert-at [parent child index] (gdom/insertChildAt parent child index)) (defn ensure-element "Coerce the argument to a dom element if possible." [e] (cond (keyword? e) (get-element e) (string? e) (html->dom e) :else e)) (defn replace-node "Replace old-node with new-node. old-node can be an element or a keyword which is the id of the node to replace. new-node can be an element or an html string." [old-node new-node] (let [old-node (ensure-element old-node) new-node (ensure-element new-node)] (gdom/replaceNode new-node old-node) new-node)) (defn set-text "Set the text content for the passed element returning the element. If a keyword is passed in the place of e, the element with that id will be used and returned." [e s] (gdom/setTextContent (ensure-element e) s)) (defn get-value "Get the value of an element." [e] (.-value (ensure-element e))) (defn set-properties "Set properties on an element" [e m] (gdom/setProperties (ensure-element e) (.-strobj m))) (defn set-value "Set the value property for an element." [e v] (set-properties e {"value" v})) (defn click-element [e] (.click (ensure-element e) ())) ;; TODO CSS class manipulation ;; TODO Query syntax
true
;; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved. ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns clojure.browser.dom (:require [goog.dom :as gdom])) (defn append [parent & children] (apply gdom/append parent children) parent) (defprotocol DOMBuilder (-element [this] [this attrs-or-children] [this attrs children])) (defn log [& args] (.log js/console (apply pr-str args))) (defn log-obj [obj] (.log js/console obj)) (extend-protocol DOMBuilder string (-element ([this] (log "string (-element " this ")") (cond (keyword? this) (gdom/createElement (name this)) :else (gdom/createTextNode (name this)))) ([this attrs-or-children] (log "string (-element " this " " attrs-or-children ")") (let [attrs (first attrs-or-children)] (if (map? attrs) (-element this attrs (rest attrs-or-children)) (-element this nil attrs-or-children)))) ([this attrs children] (log "string (-element " this " " attrs " " children ")") (let [str-attrs (if (and (map? attrs) (seq attrs)) (.-strobj (reduce (fn [m [k v]] (log "m = " m) (log "k = " k) (log "v = " v) (when (or (keyword? k) (string? k)) (assoc m (name k) v))) {} attrs)) nil)] (log-obj str-attrs) (if (seq children) (apply gdom/createDom (name this) str-attrs (map -element children)) (gdom/createDom (name this) str-attrs))))) Vector (-element [this] (log "Vector (-element " this ")") (let [tag (first this) attrs (second this) children (drop 2 this)] (if (map? attrs) (-element tag attrs children) (-element tag nil (rest this))))) js/Element (-element [this] (log "js/Element (-element " this ")") this)) (defn element ([tag-or-text] (log "(element " tag-or-text ")") (-element tag-or-text)) ([tag & children] (log "(element " tag " " children ")") (let [attrs (first children)] (if (map? attrs) (-element tag attrs (rest children)) (-element tag nil children))))) (defn remove-children "Remove all children from the element with the passed id." [id] (let [parent (gdom/getElement (name id))] (do (gdom/removeChildren parent)))) (defn get-element [id] (gdom/getElement (name id))) (defn html->dom [s] (gdom/htmlToDocumentFragment s)) (defn insert-at [parent child index] (gdom/insertChildAt parent child index)) (defn ensure-element "Coerce the argument to a dom element if possible." [e] (cond (keyword? e) (get-element e) (string? e) (html->dom e) :else e)) (defn replace-node "Replace old-node with new-node. old-node can be an element or a keyword which is the id of the node to replace. new-node can be an element or an html string." [old-node new-node] (let [old-node (ensure-element old-node) new-node (ensure-element new-node)] (gdom/replaceNode new-node old-node) new-node)) (defn set-text "Set the text content for the passed element returning the element. If a keyword is passed in the place of e, the element with that id will be used and returned." [e s] (gdom/setTextContent (ensure-element e) s)) (defn get-value "Get the value of an element." [e] (.-value (ensure-element e))) (defn set-properties "Set properties on an element" [e m] (gdom/setProperties (ensure-element e) (.-strobj m))) (defn set-value "Set the value property for an element." [e v] (set-properties e {"value" v})) (defn click-element [e] (.click (ensure-element e) ())) ;; TODO CSS class manipulation ;; TODO Query syntax
[ { "context": "et [user\n {:id 1\n :first_name \"Bob\"\n :last_name \"Bobberton\"\n :co", "end": 604, "score": 0.9997760653495789, "start": 601, "tag": "NAME", "value": "Bob" }, { "context": " :first_name \"Bob\"\n :last_name \"Bobberton\"\n :country_code \"CA\"\n :pass \"", "end": 638, "score": 0.9998071789741516, "start": 629, "tag": "NAME", "value": "Bobberton" }, { "context": "\"\n :country_code \"CA\"\n :pass \"secret\"}]\n (is (= 1 (add-user! user)))\n ;;exam", "end": 694, "score": 0.9792454242706299, "start": 688, "tag": "PASSWORD", "value": "secret" }, { "context": " {:pass \"secret\", :country_code \"CA\", :last_name \"Bobberton\", :first_name \"Bob\", :id 2}\n (get-use", "end": 837, "score": 0.9998210072517395, "start": 828, "tag": "NAME", "value": "Bobberton" }, { "context": "y_code \"CA\", :last_name \"Bobberton\", :first_name \"Bob\", :id 2}\n (get-user 1))))))\n\n(deftest", "end": 856, "score": 0.9997524619102478, "start": 853, "tag": "NAME", "value": "Bob" } ]
test/yesql_examples/core_test.clj
ClojureTO/yesql-with-tests
0
(ns yesql-examples.core-test (:require [clojure.test :refer :all] [clojure.java.io :as io] [yesql-examples.core :refer :all])) (defn reset-db! [] (letfn [(delete [f] (when (.exists f) (.delete f)))] (delete (io/file "store.db.trace.db")) (delete (io/file "store.db.mv.db")) (create-user-table db-spec))) (defn setup-test-db [f] (println "deleting users") (reset-db!) (f)) (use-fixtures :each setup-test-db) (deftest test-add-user (testing "Testing adding a new user" (let [user {:id 1 :first_name "Bob" :last_name "Bobberton" :country_code "CA" :pass "secret"}] (is (= 1 (add-user! user))) ;;example of a failing test (is (= {:pass "secret", :country_code "CA", :last_name "Bobberton", :first_name "Bob", :id 2} (get-user 1)))))) (deftest test-country-codes (is (= [{:count 0}] (users-by-country {:country_code ["CA"]}))))
113953
(ns yesql-examples.core-test (:require [clojure.test :refer :all] [clojure.java.io :as io] [yesql-examples.core :refer :all])) (defn reset-db! [] (letfn [(delete [f] (when (.exists f) (.delete f)))] (delete (io/file "store.db.trace.db")) (delete (io/file "store.db.mv.db")) (create-user-table db-spec))) (defn setup-test-db [f] (println "deleting users") (reset-db!) (f)) (use-fixtures :each setup-test-db) (deftest test-add-user (testing "Testing adding a new user" (let [user {:id 1 :first_name "<NAME>" :last_name "<NAME>" :country_code "CA" :pass "<PASSWORD>"}] (is (= 1 (add-user! user))) ;;example of a failing test (is (= {:pass "secret", :country_code "CA", :last_name "<NAME>", :first_name "<NAME>", :id 2} (get-user 1)))))) (deftest test-country-codes (is (= [{:count 0}] (users-by-country {:country_code ["CA"]}))))
true
(ns yesql-examples.core-test (:require [clojure.test :refer :all] [clojure.java.io :as io] [yesql-examples.core :refer :all])) (defn reset-db! [] (letfn [(delete [f] (when (.exists f) (.delete f)))] (delete (io/file "store.db.trace.db")) (delete (io/file "store.db.mv.db")) (create-user-table db-spec))) (defn setup-test-db [f] (println "deleting users") (reset-db!) (f)) (use-fixtures :each setup-test-db) (deftest test-add-user (testing "Testing adding a new user" (let [user {:id 1 :first_name "PI:NAME:<NAME>END_PI" :last_name "PI:NAME:<NAME>END_PI" :country_code "CA" :pass "PI:PASSWORD:<PASSWORD>END_PI"}] (is (= 1 (add-user! user))) ;;example of a failing test (is (= {:pass "secret", :country_code "CA", :last_name "PI:NAME:<NAME>END_PI", :first_name "PI:NAME:<NAME>END_PI", :id 2} (get-user 1)))))) (deftest test-country-codes (is (= [{:count 0}] (users-by-country {:country_code ["CA"]}))))
[ { "context": "ions\n and transform values.\", :author \"Sean Dawson\"}\n nanoweave.resolvers.base\n (:use [nanoweave.as", "end": 135, "score": 0.999859631061554, "start": 124, "tag": "NAME", "value": "Sean Dawson" } ]
src/nanoweave/resolvers/base.clj
NoxHarmonium/nanoweave
0
(ns ^{:doc "Provides functions to walk the AST parsed by the parsing functions and transform values.", :author "Sean Dawson"} nanoweave.resolvers.base (:use [nanoweave.ast.base :only [resolve-value Resolvable]])) (defn safe-resolve-value "Resolves the input if the given resolver is not nil and conforms to Resolvable, otherwise it will just return the input." [resolver input] (when (some? resolver) (if (satisfies? Resolvable resolver) (resolve-value resolver input) (println "Warning: Resolving unknown type: [" (type input) "] Will return nil")))) (defn handle-prop-access "A special case binary resolver. If the left side is an identifier then there is no existing value to access so it will get the value from scope. Otherwise it will just use the right side as a key to access the left side." [this input] (let [left (safe-resolve-value (:left this) input)] (safe-resolve-value (:right this) left))) (defn handle-bin-op "Binary resolver for generic binary operations." [this input op] (op (safe-resolve-value (:left this) input) (safe-resolve-value (:right this) input)))
80262
(ns ^{:doc "Provides functions to walk the AST parsed by the parsing functions and transform values.", :author "<NAME>"} nanoweave.resolvers.base (:use [nanoweave.ast.base :only [resolve-value Resolvable]])) (defn safe-resolve-value "Resolves the input if the given resolver is not nil and conforms to Resolvable, otherwise it will just return the input." [resolver input] (when (some? resolver) (if (satisfies? Resolvable resolver) (resolve-value resolver input) (println "Warning: Resolving unknown type: [" (type input) "] Will return nil")))) (defn handle-prop-access "A special case binary resolver. If the left side is an identifier then there is no existing value to access so it will get the value from scope. Otherwise it will just use the right side as a key to access the left side." [this input] (let [left (safe-resolve-value (:left this) input)] (safe-resolve-value (:right this) left))) (defn handle-bin-op "Binary resolver for generic binary operations." [this input op] (op (safe-resolve-value (:left this) input) (safe-resolve-value (:right this) input)))
true
(ns ^{:doc "Provides functions to walk the AST parsed by the parsing functions and transform values.", :author "PI:NAME:<NAME>END_PI"} nanoweave.resolvers.base (:use [nanoweave.ast.base :only [resolve-value Resolvable]])) (defn safe-resolve-value "Resolves the input if the given resolver is not nil and conforms to Resolvable, otherwise it will just return the input." [resolver input] (when (some? resolver) (if (satisfies? Resolvable resolver) (resolve-value resolver input) (println "Warning: Resolving unknown type: [" (type input) "] Will return nil")))) (defn handle-prop-access "A special case binary resolver. If the left side is an identifier then there is no existing value to access so it will get the value from scope. Otherwise it will just use the right side as a key to access the left side." [this input] (let [left (safe-resolve-value (:left this) input)] (safe-resolve-value (:right this) left))) (defn handle-bin-op "Binary resolver for generic binary operations." [this input op] (op (safe-resolve-value (:left this) input) (safe-resolve-value (:right this) input)))
[ { "context": "p://magiccards.info/scans/en/m11/211.jpg\", :name \"Ornithopter\", :url \"http://magiccards.info/m11/en/211.html\", ", "end": 1027, "score": 0.7010399103164673, "start": 1016, "tag": "NAME", "value": "Ornithopter" } ]
test/info/magiccards/test/scraper.clj
john2x/searchthecity
1
(ns info.magiccards.test.scraper (:require [clojure.test :refer :all] [info.magiccards.scraper :as scraper] [net.cgrand.enlive-html :as en]) (:use [clj-http.util :only [url-decode url-encode]]) (:import (java.io File))) (def thopters (scraper/query "thopter t:creature" 1)) (def goblins-page-2 (scraper/query "goblin" 2)) (def no-results (scraper/query "asdf" nil)) (def ornithopter (scraper/query "ornithopter" nil)) (def anger (scraper/query "!Anger" nil)) (deftest magiccardsinfo-test ; thopters! (is (= (map :name (:cards thopters)) ["Flowstone Thopter" "Ornithopter" "Roterothopter" "Spined Thopter" "Telethopter" "Thopter Assembly" "Thopter Squadron"])) ; pages (is (= (:pagination thopters) {:total-cards 7, :total-pages 1, :current-page 1, :cards-per-page 20})) ; pagination (is (= (:current-page (:pagination goblins-page-2)) 2)) ; single result (is (= {:cards [{:img "http://magiccards.info/scans/en/m11/211.jpg", :name "Ornithopter", :url "http://magiccards.info/m11/en/211.html", :attrs {:subtype "Thopter", :type "Artifact Creature", :cmc 0, :manacost 0, :loyalty nil, :toughness "2", :power "0"}, :rules-text "Flying", :flavor-text "Regardless of the century, plane, or species, developing artificers never fail to invent the ornithopter."}], :pagination nil} ornithopter)) ; no results (is (= {:cards nil :pagination nil} no-results)) (is (= 1 (count (:cards anger)))) )
32803
(ns info.magiccards.test.scraper (:require [clojure.test :refer :all] [info.magiccards.scraper :as scraper] [net.cgrand.enlive-html :as en]) (:use [clj-http.util :only [url-decode url-encode]]) (:import (java.io File))) (def thopters (scraper/query "thopter t:creature" 1)) (def goblins-page-2 (scraper/query "goblin" 2)) (def no-results (scraper/query "asdf" nil)) (def ornithopter (scraper/query "ornithopter" nil)) (def anger (scraper/query "!Anger" nil)) (deftest magiccardsinfo-test ; thopters! (is (= (map :name (:cards thopters)) ["Flowstone Thopter" "Ornithopter" "Roterothopter" "Spined Thopter" "Telethopter" "Thopter Assembly" "Thopter Squadron"])) ; pages (is (= (:pagination thopters) {:total-cards 7, :total-pages 1, :current-page 1, :cards-per-page 20})) ; pagination (is (= (:current-page (:pagination goblins-page-2)) 2)) ; single result (is (= {:cards [{:img "http://magiccards.info/scans/en/m11/211.jpg", :name "<NAME>", :url "http://magiccards.info/m11/en/211.html", :attrs {:subtype "Thopter", :type "Artifact Creature", :cmc 0, :manacost 0, :loyalty nil, :toughness "2", :power "0"}, :rules-text "Flying", :flavor-text "Regardless of the century, plane, or species, developing artificers never fail to invent the ornithopter."}], :pagination nil} ornithopter)) ; no results (is (= {:cards nil :pagination nil} no-results)) (is (= 1 (count (:cards anger)))) )
true
(ns info.magiccards.test.scraper (:require [clojure.test :refer :all] [info.magiccards.scraper :as scraper] [net.cgrand.enlive-html :as en]) (:use [clj-http.util :only [url-decode url-encode]]) (:import (java.io File))) (def thopters (scraper/query "thopter t:creature" 1)) (def goblins-page-2 (scraper/query "goblin" 2)) (def no-results (scraper/query "asdf" nil)) (def ornithopter (scraper/query "ornithopter" nil)) (def anger (scraper/query "!Anger" nil)) (deftest magiccardsinfo-test ; thopters! (is (= (map :name (:cards thopters)) ["Flowstone Thopter" "Ornithopter" "Roterothopter" "Spined Thopter" "Telethopter" "Thopter Assembly" "Thopter Squadron"])) ; pages (is (= (:pagination thopters) {:total-cards 7, :total-pages 1, :current-page 1, :cards-per-page 20})) ; pagination (is (= (:current-page (:pagination goblins-page-2)) 2)) ; single result (is (= {:cards [{:img "http://magiccards.info/scans/en/m11/211.jpg", :name "PI:NAME:<NAME>END_PI", :url "http://magiccards.info/m11/en/211.html", :attrs {:subtype "Thopter", :type "Artifact Creature", :cmc 0, :manacost 0, :loyalty nil, :toughness "2", :power "0"}, :rules-text "Flying", :flavor-text "Regardless of the century, plane, or species, developing artificers never fail to invent the ornithopter."}], :pagination nil} ornithopter)) ; no results (is (= {:cards nil :pagination nil} no-results)) (is (= 1 (count (:cards anger)))) )
[ { "context": "ers and s-expressions\"\n :url \"https://github.com/kkinnear/zprint\"\n :license {:name \"MIT License\",\n ", "end": 118, "score": 0.9997194409370422, "start": 110, "tag": "USERNAME", "value": "kkinnear" }, { "context": "//opensource.org/licenses/MIT\",\n :key \"mit\",\n :year 2015}\n :plugins\n [[lein-e", "end": 237, "score": 0.6716518402099609, "start": 234, "tag": "KEY", "value": "mit" }, { "context": "w\"]\n :scm {:name \"git\", :url \"https://github.com/kkinnear/zprint\"}\n :codox {:namespaces [zprint.core],\n ", "end": 1853, "score": 0.995819628238678, "start": 1845, "tag": "USERNAME", "value": "kkinnear" } ]
project.clj
rundis/zprint
0
(defproject zprint "0.5.4" :description "Pretty print zippers and s-expressions" :url "https://github.com/kkinnear/zprint" :license {:name "MIT License", :url "https://opensource.org/licenses/MIT", :key "mit", :year 2015} :plugins [[lein-expectations "0.0.8"] [lein-codox "0.10.3"] [lein-zprint "0.5.4"]] :profiles {:dev {:dependencies [#_[expectations "2.2.0-rc1"] #_[expectations "2.2.0-rc3"] [expectations "2.1.10"] [com.taoensso/tufte "1.1.1"] #_[org.clojure/clojurescript "1.9.946"] ;[rum "0.10.8"]; [better-cond "1.0.1"] [zpst "0.1.6"] [org.clojure/core.match "0.3.0-alpha5"] #_[clojure-future-spec "1.9.0-alpha17"]]}, :uberjar {;:aot [zprint.core zprint.main], ; For 1.9.0-alpha17, use this for the :aot value :aot [zprint.core zprint.main clojure.core.specs.alpha], :main zprint.main, :dependencies [#_[clojure-future-spec "1.9.0-alpha17"]], :omit-source true, :uberjar-name "zprint-filter-%s"}} ; Clojure 1.8 you can exclude all sources in the uberjar ; :uberjar-exclusions [#"\.(clj|java|txt)"] ; Clojure 1.9 requires the .clj files in the uberjar :uberjar-exclusions [#"\.(clj\.|java|cljs|txt)"] :jar-exclusions [#"\.(clj$|clj\.|java|txt|cljs)"] :zprint {:old? false} :jvm-opts ^:replace ["-server" "-Xms2048m" "-Xmx2048m" "-Xss500m" "-XX:-OmitStackTraceInFastThrow"] :scm {:name "git", :url "https://github.com/kkinnear/zprint"} :codox {:namespaces [zprint.core], :doc-files ["README.md" "doc/bang.md" "doc/graalvm.md" "doc/filter.md"], :metadata {:doc/format :markdown}} :dependencies [#_[org.clojure/clojure "1.10.0"] #_[org.clojure/clojure "1.10.2-alpha1"] [org.clojure/clojure "1.9.0"] #_[org.clojure/clojure "1.8.0"] [rewrite-cljs "0.4.4" :exclusions [[org.clojure/clojurescript]]] [rewrite-clj "0.6.1" :exclusions [[com.cemerick/austin]]]])
31847
(defproject zprint "0.5.4" :description "Pretty print zippers and s-expressions" :url "https://github.com/kkinnear/zprint" :license {:name "MIT License", :url "https://opensource.org/licenses/MIT", :key "<KEY>", :year 2015} :plugins [[lein-expectations "0.0.8"] [lein-codox "0.10.3"] [lein-zprint "0.5.4"]] :profiles {:dev {:dependencies [#_[expectations "2.2.0-rc1"] #_[expectations "2.2.0-rc3"] [expectations "2.1.10"] [com.taoensso/tufte "1.1.1"] #_[org.clojure/clojurescript "1.9.946"] ;[rum "0.10.8"]; [better-cond "1.0.1"] [zpst "0.1.6"] [org.clojure/core.match "0.3.0-alpha5"] #_[clojure-future-spec "1.9.0-alpha17"]]}, :uberjar {;:aot [zprint.core zprint.main], ; For 1.9.0-alpha17, use this for the :aot value :aot [zprint.core zprint.main clojure.core.specs.alpha], :main zprint.main, :dependencies [#_[clojure-future-spec "1.9.0-alpha17"]], :omit-source true, :uberjar-name "zprint-filter-%s"}} ; Clojure 1.8 you can exclude all sources in the uberjar ; :uberjar-exclusions [#"\.(clj|java|txt)"] ; Clojure 1.9 requires the .clj files in the uberjar :uberjar-exclusions [#"\.(clj\.|java|cljs|txt)"] :jar-exclusions [#"\.(clj$|clj\.|java|txt|cljs)"] :zprint {:old? false} :jvm-opts ^:replace ["-server" "-Xms2048m" "-Xmx2048m" "-Xss500m" "-XX:-OmitStackTraceInFastThrow"] :scm {:name "git", :url "https://github.com/kkinnear/zprint"} :codox {:namespaces [zprint.core], :doc-files ["README.md" "doc/bang.md" "doc/graalvm.md" "doc/filter.md"], :metadata {:doc/format :markdown}} :dependencies [#_[org.clojure/clojure "1.10.0"] #_[org.clojure/clojure "1.10.2-alpha1"] [org.clojure/clojure "1.9.0"] #_[org.clojure/clojure "1.8.0"] [rewrite-cljs "0.4.4" :exclusions [[org.clojure/clojurescript]]] [rewrite-clj "0.6.1" :exclusions [[com.cemerick/austin]]]])
true
(defproject zprint "0.5.4" :description "Pretty print zippers and s-expressions" :url "https://github.com/kkinnear/zprint" :license {:name "MIT License", :url "https://opensource.org/licenses/MIT", :key "PI:KEY:<KEY>END_PI", :year 2015} :plugins [[lein-expectations "0.0.8"] [lein-codox "0.10.3"] [lein-zprint "0.5.4"]] :profiles {:dev {:dependencies [#_[expectations "2.2.0-rc1"] #_[expectations "2.2.0-rc3"] [expectations "2.1.10"] [com.taoensso/tufte "1.1.1"] #_[org.clojure/clojurescript "1.9.946"] ;[rum "0.10.8"]; [better-cond "1.0.1"] [zpst "0.1.6"] [org.clojure/core.match "0.3.0-alpha5"] #_[clojure-future-spec "1.9.0-alpha17"]]}, :uberjar {;:aot [zprint.core zprint.main], ; For 1.9.0-alpha17, use this for the :aot value :aot [zprint.core zprint.main clojure.core.specs.alpha], :main zprint.main, :dependencies [#_[clojure-future-spec "1.9.0-alpha17"]], :omit-source true, :uberjar-name "zprint-filter-%s"}} ; Clojure 1.8 you can exclude all sources in the uberjar ; :uberjar-exclusions [#"\.(clj|java|txt)"] ; Clojure 1.9 requires the .clj files in the uberjar :uberjar-exclusions [#"\.(clj\.|java|cljs|txt)"] :jar-exclusions [#"\.(clj$|clj\.|java|txt|cljs)"] :zprint {:old? false} :jvm-opts ^:replace ["-server" "-Xms2048m" "-Xmx2048m" "-Xss500m" "-XX:-OmitStackTraceInFastThrow"] :scm {:name "git", :url "https://github.com/kkinnear/zprint"} :codox {:namespaces [zprint.core], :doc-files ["README.md" "doc/bang.md" "doc/graalvm.md" "doc/filter.md"], :metadata {:doc/format :markdown}} :dependencies [#_[org.clojure/clojure "1.10.0"] #_[org.clojure/clojure "1.10.2-alpha1"] [org.clojure/clojure "1.9.0"] #_[org.clojure/clojure "1.8.0"] [rewrite-cljs "0.4.4" :exclusions [[org.clojure/clojurescript]]] [rewrite-clj "0.6.1" :exclusions [[com.cemerick/austin]]]])
[ { "context": "d 0.1)\n\n(def rim-griffon (make ::starship {:name \"Rim Griffon\" :speed rim-griffon-speed}))\n(def malse (make ::a", "end": 217, "score": 0.9997667074203491, "start": 206, "tag": "NAME", "value": "Rim Griffon" }, { "context": "ffon-speed}))\n(def malse (make ::asteroid {:name \"Malse\" :speed malse-speed :gravitational-pull 1}))\n(def", "end": 288, "score": 0.9877354502677917, "start": 283, "tag": "NAME", "value": "Malse" }, { "context": "1}))\n(def lode-trader (make ::gaussjammer {:name \"Lode Trader\" :speed 30,\n ", "end": 390, "score": 0.9965385794639587, "start": 379, "tag": "NAME", "value": "Lode Trader" } ]
func-prog/fp-oo/test/sources/t_asteroids.clj
tannerwelsh/code-training
0
(ns sources.t-asteroids (:use midje.sweet)) (load-file "sources/asteroids.clj") (def rim-griffon-speed 1000) (def load-trader-speed 30) (def malse-speed 0.1) (def rim-griffon (make ::starship {:name "Rim Griffon" :speed rim-griffon-speed})) (def malse (make ::asteroid {:name "Malse" :speed malse-speed :gravitational-pull 1})) (def lode-trader (make ::gaussjammer {:name "Lode Trader" :speed 30, :drive-type "Ehrenhaft"})) (fact "nudging" (:speed (nudge rim-griffon 5)) => (+ rim-griffon-speed 5) (:speed (nudge malse 5)) => malse-speed) (fact "description" (description rim-griffon) => "the spritely Rim Griffon" (description malse) => "the asteroid Malse" (description lode-trader) => "the spritely Lode Trader") (fact "gravitational pull" (gravitational-pull rim-griffon) => (throws Exception) (gravitational-pull malse) => (:gravitational-pull malse)) (fact "drive type" (drive-type rim-griffon) => "Mannschenn" (drive-type malse) => (throws Exception) (drive-type lode-trader) => "Ehrenhaft") (fact "collide in object-oriented style" (collide-oo rim-griffon (with-speed 0 rim-griffon)) => [rim-griffon rim-griffon] (collide-oo rim-griffon malse) => [(stopped rim-griffon) malse] (collide-oo malse rim-griffon) => [malse (stopped rim-griffon)] (collide-oo malse (with-speed 8 malse)) => [malse (with-speed 8 malse)]) (fact "collide in multiple dispatch style" (collide rim-griffon (with-speed 0 rim-griffon)) => [rim-griffon rim-griffon] (collide rim-griffon malse) => [(stopped rim-griffon) malse] (collide malse rim-griffon) => [malse (stopped rim-griffon)] (collide malse (with-speed 8 malse)) => [malse (with-speed 8 malse)] (collide lode-trader rim-griffon) => [(stopped lode-trader) rim-griffon] (collide rim-griffon lode-trader) => [rim-griffon (stopped lode-trader)] (collide malse lode-trader) => [malse (stopped lode-trader)] (collide lode-trader lode-trader) => [(stopped lode-trader) (stopped lode-trader)]) (fact "nudging a lode trader" (:speed (nudge lode-trader 1)) => (* 2 (inc (:speed lode-trader))))
66474
(ns sources.t-asteroids (:use midje.sweet)) (load-file "sources/asteroids.clj") (def rim-griffon-speed 1000) (def load-trader-speed 30) (def malse-speed 0.1) (def rim-griffon (make ::starship {:name "<NAME>" :speed rim-griffon-speed})) (def malse (make ::asteroid {:name "<NAME>" :speed malse-speed :gravitational-pull 1})) (def lode-trader (make ::gaussjammer {:name "<NAME>" :speed 30, :drive-type "Ehrenhaft"})) (fact "nudging" (:speed (nudge rim-griffon 5)) => (+ rim-griffon-speed 5) (:speed (nudge malse 5)) => malse-speed) (fact "description" (description rim-griffon) => "the spritely Rim Griffon" (description malse) => "the asteroid Malse" (description lode-trader) => "the spritely Lode Trader") (fact "gravitational pull" (gravitational-pull rim-griffon) => (throws Exception) (gravitational-pull malse) => (:gravitational-pull malse)) (fact "drive type" (drive-type rim-griffon) => "Mannschenn" (drive-type malse) => (throws Exception) (drive-type lode-trader) => "Ehrenhaft") (fact "collide in object-oriented style" (collide-oo rim-griffon (with-speed 0 rim-griffon)) => [rim-griffon rim-griffon] (collide-oo rim-griffon malse) => [(stopped rim-griffon) malse] (collide-oo malse rim-griffon) => [malse (stopped rim-griffon)] (collide-oo malse (with-speed 8 malse)) => [malse (with-speed 8 malse)]) (fact "collide in multiple dispatch style" (collide rim-griffon (with-speed 0 rim-griffon)) => [rim-griffon rim-griffon] (collide rim-griffon malse) => [(stopped rim-griffon) malse] (collide malse rim-griffon) => [malse (stopped rim-griffon)] (collide malse (with-speed 8 malse)) => [malse (with-speed 8 malse)] (collide lode-trader rim-griffon) => [(stopped lode-trader) rim-griffon] (collide rim-griffon lode-trader) => [rim-griffon (stopped lode-trader)] (collide malse lode-trader) => [malse (stopped lode-trader)] (collide lode-trader lode-trader) => [(stopped lode-trader) (stopped lode-trader)]) (fact "nudging a lode trader" (:speed (nudge lode-trader 1)) => (* 2 (inc (:speed lode-trader))))
true
(ns sources.t-asteroids (:use midje.sweet)) (load-file "sources/asteroids.clj") (def rim-griffon-speed 1000) (def load-trader-speed 30) (def malse-speed 0.1) (def rim-griffon (make ::starship {:name "PI:NAME:<NAME>END_PI" :speed rim-griffon-speed})) (def malse (make ::asteroid {:name "PI:NAME:<NAME>END_PI" :speed malse-speed :gravitational-pull 1})) (def lode-trader (make ::gaussjammer {:name "PI:NAME:<NAME>END_PI" :speed 30, :drive-type "Ehrenhaft"})) (fact "nudging" (:speed (nudge rim-griffon 5)) => (+ rim-griffon-speed 5) (:speed (nudge malse 5)) => malse-speed) (fact "description" (description rim-griffon) => "the spritely Rim Griffon" (description malse) => "the asteroid Malse" (description lode-trader) => "the spritely Lode Trader") (fact "gravitational pull" (gravitational-pull rim-griffon) => (throws Exception) (gravitational-pull malse) => (:gravitational-pull malse)) (fact "drive type" (drive-type rim-griffon) => "Mannschenn" (drive-type malse) => (throws Exception) (drive-type lode-trader) => "Ehrenhaft") (fact "collide in object-oriented style" (collide-oo rim-griffon (with-speed 0 rim-griffon)) => [rim-griffon rim-griffon] (collide-oo rim-griffon malse) => [(stopped rim-griffon) malse] (collide-oo malse rim-griffon) => [malse (stopped rim-griffon)] (collide-oo malse (with-speed 8 malse)) => [malse (with-speed 8 malse)]) (fact "collide in multiple dispatch style" (collide rim-griffon (with-speed 0 rim-griffon)) => [rim-griffon rim-griffon] (collide rim-griffon malse) => [(stopped rim-griffon) malse] (collide malse rim-griffon) => [malse (stopped rim-griffon)] (collide malse (with-speed 8 malse)) => [malse (with-speed 8 malse)] (collide lode-trader rim-griffon) => [(stopped lode-trader) rim-griffon] (collide rim-griffon lode-trader) => [rim-griffon (stopped lode-trader)] (collide malse lode-trader) => [malse (stopped lode-trader)] (collide lode-trader lode-trader) => [(stopped lode-trader) (stopped lode-trader)]) (fact "nudging a lode trader" (:speed (nudge lode-trader 1)) => (* 2 (inc (:speed lode-trader))))
[ { "context": "\"/api/login\"\n :body {:username username\n :password password}\n ", "end": 3428, "score": 0.992279589176178, "start": 3420, "tag": "USERNAME", "value": "username" }, { "context": "ame username\n :password password}\n :headers {:Content-Type \"ap", "end": 3475, "score": 0.9989592432975769, "start": 3467, "tag": "PASSWORD", "value": "password" } ]
src/ui/login.cljs
victorb/cube-1
28
(ns ui.login (:require [re-frame.core :refer [dispatch reg-fx reg-event-fx reg-event-db subscribe reg-sub]] [reagent.cookies :as cookies] [day8.re-frame.tracing :refer-macros [fn-traced]])) (def cookie-name "login-token") (reg-sub :login/error (fn-traced [db _] (-> db :login :error))) (reg-sub :login/token (fn-traced [db _] (-> db :login :token))) (reg-sub :login/profile (fn-traced [db _] (-> db :login :profile))) (reg-sub :login/permissions (fn-traced [db _] (-> db :login :profile :permissions))) (reg-event-db :set-login-error (fn-traced [db [_ msg]] (assoc-in db [:login :error] msg))) (reg-event-db :set-profile (fn-traced [db [_ profile]] (assoc-in db [:login :profile] profile))) (reg-fx :get-cookie (fn-traced [v] (let [f (:callback v)] (f (cookies/get (:name v)))))) (reg-fx :delete-cookie (fn-traced [v] (cookies/remove! (:name v)))) (reg-event-fx :logout (fn-traced [cofx _] {:db (dissoc (:db cofx) :login) :delete-cookie {:name cookie-name} :dispatch-n [ ;; disconnect ws when logout happen ;; make sure it's connected again on login [:ws-disconnect] [:go-to-page "/login"]]})) (reg-fx :set-cookie (fn-traced [v] (cookies/set! (:name v) (:value v)))) (reg-event-fx :set-login-token (fn-traced [cofx [_ token]] (do (cljs.pprint/pprint token) {:db (assoc-in (:db cofx) [:login :token] token) :set-cookie {:name cookie-name :value token}}))) (reg-event-fx :check-logged-in (fn-traced [_ _] {:get-cookie {:name cookie-name :callback #(if (nil? %) (dispatch [:go-to-page "/login"]) (do (dispatch [:set-login-token %]) (dispatch [:get-profile-data]) (dispatch [:ws-connect])) )}})) (defn take-token-from-res [res] (.then (.json res) #(do (println "received res") (dispatch [:set-login-token (get (js->clj %) "token")]) (dispatch [:get-profile-data]) (dispatch [:go-to-page "/home"]) (dispatch [:ws-connect])))) (defn res->set-profile [res] (.then (.json res) #(do (println "my profile:") (dispatch [:set-profile (js->clj % :keywordize-keys true)])))) (reg-event-fx :get-profile-data (fn-traced [cofx _] {:http {:method "GET" :url "/api/profile" :headers {:Content-Type "application/json" :Authorization (str "Token " @(subscribe [:login/token]))} :on-success #(res->set-profile %)}})) (reg-event-fx :do-login (fn-traced [cofx [_ username password]] {:http {:method "POST" :url "/api/login" :body {:username username :password password} :headers {:Content-Type "application/json"} :on-success #(if (= 401 (.-status %)) (dispatch [:set-login-error "Wrong username/password"]) (take-token-from-res %))} :dispatch [:set-login-error nil] :dispatch-later [{:ms 2000 :dispatch [:set-login-error nil]}]}))
17409
(ns ui.login (:require [re-frame.core :refer [dispatch reg-fx reg-event-fx reg-event-db subscribe reg-sub]] [reagent.cookies :as cookies] [day8.re-frame.tracing :refer-macros [fn-traced]])) (def cookie-name "login-token") (reg-sub :login/error (fn-traced [db _] (-> db :login :error))) (reg-sub :login/token (fn-traced [db _] (-> db :login :token))) (reg-sub :login/profile (fn-traced [db _] (-> db :login :profile))) (reg-sub :login/permissions (fn-traced [db _] (-> db :login :profile :permissions))) (reg-event-db :set-login-error (fn-traced [db [_ msg]] (assoc-in db [:login :error] msg))) (reg-event-db :set-profile (fn-traced [db [_ profile]] (assoc-in db [:login :profile] profile))) (reg-fx :get-cookie (fn-traced [v] (let [f (:callback v)] (f (cookies/get (:name v)))))) (reg-fx :delete-cookie (fn-traced [v] (cookies/remove! (:name v)))) (reg-event-fx :logout (fn-traced [cofx _] {:db (dissoc (:db cofx) :login) :delete-cookie {:name cookie-name} :dispatch-n [ ;; disconnect ws when logout happen ;; make sure it's connected again on login [:ws-disconnect] [:go-to-page "/login"]]})) (reg-fx :set-cookie (fn-traced [v] (cookies/set! (:name v) (:value v)))) (reg-event-fx :set-login-token (fn-traced [cofx [_ token]] (do (cljs.pprint/pprint token) {:db (assoc-in (:db cofx) [:login :token] token) :set-cookie {:name cookie-name :value token}}))) (reg-event-fx :check-logged-in (fn-traced [_ _] {:get-cookie {:name cookie-name :callback #(if (nil? %) (dispatch [:go-to-page "/login"]) (do (dispatch [:set-login-token %]) (dispatch [:get-profile-data]) (dispatch [:ws-connect])) )}})) (defn take-token-from-res [res] (.then (.json res) #(do (println "received res") (dispatch [:set-login-token (get (js->clj %) "token")]) (dispatch [:get-profile-data]) (dispatch [:go-to-page "/home"]) (dispatch [:ws-connect])))) (defn res->set-profile [res] (.then (.json res) #(do (println "my profile:") (dispatch [:set-profile (js->clj % :keywordize-keys true)])))) (reg-event-fx :get-profile-data (fn-traced [cofx _] {:http {:method "GET" :url "/api/profile" :headers {:Content-Type "application/json" :Authorization (str "Token " @(subscribe [:login/token]))} :on-success #(res->set-profile %)}})) (reg-event-fx :do-login (fn-traced [cofx [_ username password]] {:http {:method "POST" :url "/api/login" :body {:username username :password <PASSWORD>} :headers {:Content-Type "application/json"} :on-success #(if (= 401 (.-status %)) (dispatch [:set-login-error "Wrong username/password"]) (take-token-from-res %))} :dispatch [:set-login-error nil] :dispatch-later [{:ms 2000 :dispatch [:set-login-error nil]}]}))
true
(ns ui.login (:require [re-frame.core :refer [dispatch reg-fx reg-event-fx reg-event-db subscribe reg-sub]] [reagent.cookies :as cookies] [day8.re-frame.tracing :refer-macros [fn-traced]])) (def cookie-name "login-token") (reg-sub :login/error (fn-traced [db _] (-> db :login :error))) (reg-sub :login/token (fn-traced [db _] (-> db :login :token))) (reg-sub :login/profile (fn-traced [db _] (-> db :login :profile))) (reg-sub :login/permissions (fn-traced [db _] (-> db :login :profile :permissions))) (reg-event-db :set-login-error (fn-traced [db [_ msg]] (assoc-in db [:login :error] msg))) (reg-event-db :set-profile (fn-traced [db [_ profile]] (assoc-in db [:login :profile] profile))) (reg-fx :get-cookie (fn-traced [v] (let [f (:callback v)] (f (cookies/get (:name v)))))) (reg-fx :delete-cookie (fn-traced [v] (cookies/remove! (:name v)))) (reg-event-fx :logout (fn-traced [cofx _] {:db (dissoc (:db cofx) :login) :delete-cookie {:name cookie-name} :dispatch-n [ ;; disconnect ws when logout happen ;; make sure it's connected again on login [:ws-disconnect] [:go-to-page "/login"]]})) (reg-fx :set-cookie (fn-traced [v] (cookies/set! (:name v) (:value v)))) (reg-event-fx :set-login-token (fn-traced [cofx [_ token]] (do (cljs.pprint/pprint token) {:db (assoc-in (:db cofx) [:login :token] token) :set-cookie {:name cookie-name :value token}}))) (reg-event-fx :check-logged-in (fn-traced [_ _] {:get-cookie {:name cookie-name :callback #(if (nil? %) (dispatch [:go-to-page "/login"]) (do (dispatch [:set-login-token %]) (dispatch [:get-profile-data]) (dispatch [:ws-connect])) )}})) (defn take-token-from-res [res] (.then (.json res) #(do (println "received res") (dispatch [:set-login-token (get (js->clj %) "token")]) (dispatch [:get-profile-data]) (dispatch [:go-to-page "/home"]) (dispatch [:ws-connect])))) (defn res->set-profile [res] (.then (.json res) #(do (println "my profile:") (dispatch [:set-profile (js->clj % :keywordize-keys true)])))) (reg-event-fx :get-profile-data (fn-traced [cofx _] {:http {:method "GET" :url "/api/profile" :headers {:Content-Type "application/json" :Authorization (str "Token " @(subscribe [:login/token]))} :on-success #(res->set-profile %)}})) (reg-event-fx :do-login (fn-traced [cofx [_ username password]] {:http {:method "POST" :url "/api/login" :body {:username username :password PI:PASSWORD:<PASSWORD>END_PI} :headers {:Content-Type "application/json"} :on-success #(if (= 401 (.-status %)) (dispatch [:set-login-error "Wrong username/password"]) (take-token-from-res %))} :dispatch [:set-login-error nil] :dispatch-later [{:ms 2000 :dispatch [:set-login-error nil]}]}))
[ { "context": "; Copyright (c) 2018-present Walmart, Inc.\n;\n; Licensed under the Apache License, ", "end": 32, "score": 0.7864537835121155, "start": 29, "tag": "NAME", "value": "Wal" } ]
src/com/walmartlabs/lacinia/pedestal/spec.clj
transducer/lacinia-pedestal
163
; Copyright (c) 2018-present Walmart, Inc. ; ; Licensed under the Apache License, Version 2.0 (the "License") ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns com.walmartlabs.lacinia.pedestal.spec "Common specifications." {:added "0.10.0"} (:require com.walmartlabs.lacinia.schema ; for CompiledSchema [clojure.core.async.impl.protocols :refer [Buffer]] io.pedestal.interceptor ; for Interceptor [clojure.spec.alpha :as s]) (:import (com.walmartlabs.lacinia.schema CompiledSchema) (io.pedestal.interceptor Interceptor))) (when (-> *clojure-version* :minor (< 9)) (require '[clojure.future :refer [pos-int?]])) (s/def ::compiled-schema (s/or :direct #(instance? CompiledSchema %) :indirect fn?)) (s/def ::interceptors (s/coll-of ::interceptor)) ;; This is a bit narrower than io.pedestal.interceptor's definition; we are excluding ;; things that can be turned into an interceptor (outside of map), to focus on there ;; being a valid name, which is important for com.walmartlabs.lacinia.pedestal/inject. ;; Lastly, we support a handler, which is typically at the end, and is like a nameless interceptor. (s/def ::interceptor (s/or :handler fn? :interceptor (s/and (s/nonconforming (s/or :interceptor #(instance? Interceptor %) :map map?)) #(-> % :name keyword?)))) (s/def ::app-context map?) (s/def ::buffer-or-n (s/or :buffer #(satisfies? Buffer %) :n pos-int?))
44626
; Copyright (c) 2018-present <NAME>mart, Inc. ; ; Licensed under the Apache License, Version 2.0 (the "License") ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns com.walmartlabs.lacinia.pedestal.spec "Common specifications." {:added "0.10.0"} (:require com.walmartlabs.lacinia.schema ; for CompiledSchema [clojure.core.async.impl.protocols :refer [Buffer]] io.pedestal.interceptor ; for Interceptor [clojure.spec.alpha :as s]) (:import (com.walmartlabs.lacinia.schema CompiledSchema) (io.pedestal.interceptor Interceptor))) (when (-> *clojure-version* :minor (< 9)) (require '[clojure.future :refer [pos-int?]])) (s/def ::compiled-schema (s/or :direct #(instance? CompiledSchema %) :indirect fn?)) (s/def ::interceptors (s/coll-of ::interceptor)) ;; This is a bit narrower than io.pedestal.interceptor's definition; we are excluding ;; things that can be turned into an interceptor (outside of map), to focus on there ;; being a valid name, which is important for com.walmartlabs.lacinia.pedestal/inject. ;; Lastly, we support a handler, which is typically at the end, and is like a nameless interceptor. (s/def ::interceptor (s/or :handler fn? :interceptor (s/and (s/nonconforming (s/or :interceptor #(instance? Interceptor %) :map map?)) #(-> % :name keyword?)))) (s/def ::app-context map?) (s/def ::buffer-or-n (s/or :buffer #(satisfies? Buffer %) :n pos-int?))
true
; Copyright (c) 2018-present PI:NAME:<NAME>END_PImart, Inc. ; ; Licensed under the Apache License, Version 2.0 (the "License") ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns com.walmartlabs.lacinia.pedestal.spec "Common specifications." {:added "0.10.0"} (:require com.walmartlabs.lacinia.schema ; for CompiledSchema [clojure.core.async.impl.protocols :refer [Buffer]] io.pedestal.interceptor ; for Interceptor [clojure.spec.alpha :as s]) (:import (com.walmartlabs.lacinia.schema CompiledSchema) (io.pedestal.interceptor Interceptor))) (when (-> *clojure-version* :minor (< 9)) (require '[clojure.future :refer [pos-int?]])) (s/def ::compiled-schema (s/or :direct #(instance? CompiledSchema %) :indirect fn?)) (s/def ::interceptors (s/coll-of ::interceptor)) ;; This is a bit narrower than io.pedestal.interceptor's definition; we are excluding ;; things that can be turned into an interceptor (outside of map), to focus on there ;; being a valid name, which is important for com.walmartlabs.lacinia.pedestal/inject. ;; Lastly, we support a handler, which is typically at the end, and is like a nameless interceptor. (s/def ::interceptor (s/or :handler fn? :interceptor (s/and (s/nonconforming (s/or :interceptor #(instance? Interceptor %) :map map?)) #(-> % :name keyword?)))) (s/def ::app-context map?) (s/def ::buffer-or-n (s/or :buffer #(satisfies? Buffer %) :n pos-int?))
[ { "context": "ail 不合法\"]]\n :password [[v/required :message \"密码不能为空\"]\n [v/min-count 7 :message \"密", "end": 685, "score": 0.7769134640693665, "start": 683, "tag": "PASSWORD", "value": "密码" } ]
src-cljc/soul_talk/auth_validate.cljc
neromous/Re_Frame_template_of_FamiliyCost
4
(ns soul-talk.auth-validate (:require [bouncer.core :as b] [bouncer.validators :as v] [taoensso.timbre :as log])) (defn reg-errors [{:keys [password] :as params}] (first (b/validate params :email [[v/required :message "email 不能为空"] [v/email :message "email 不合法"]] :password [[v/required :message "密码不能为空"] [v/min-count 7 :message "密码最少8位"]] :pass-confirm [[= password :message "两次密码必须一样"]]))) (defn login-errors [params] (first (b/validate params :email [[v/required :message "email 不能为空"] [v/email :message "email 不合法"]] :password [[v/required :message "密码不能为空"] [v/min-count 7 :message "密码最少8位"]])))
112924
(ns soul-talk.auth-validate (:require [bouncer.core :as b] [bouncer.validators :as v] [taoensso.timbre :as log])) (defn reg-errors [{:keys [password] :as params}] (first (b/validate params :email [[v/required :message "email 不能为空"] [v/email :message "email 不合法"]] :password [[v/required :message "密码不能为空"] [v/min-count 7 :message "密码最少8位"]] :pass-confirm [[= password :message "两次密码必须一样"]]))) (defn login-errors [params] (first (b/validate params :email [[v/required :message "email 不能为空"] [v/email :message "email 不合法"]] :password [[v/required :message "<PASSWORD>不能为空"] [v/min-count 7 :message "密码最少8位"]])))
true
(ns soul-talk.auth-validate (:require [bouncer.core :as b] [bouncer.validators :as v] [taoensso.timbre :as log])) (defn reg-errors [{:keys [password] :as params}] (first (b/validate params :email [[v/required :message "email 不能为空"] [v/email :message "email 不合法"]] :password [[v/required :message "密码不能为空"] [v/min-count 7 :message "密码最少8位"]] :pass-confirm [[= password :message "两次密码必须一样"]]))) (defn login-errors [params] (first (b/validate params :email [[v/required :message "email 不能为空"] [v/email :message "email 不合法"]] :password [[v/required :message "PI:PASSWORD:<PASSWORD>END_PI不能为空"] [v/min-count 7 :message "密码最少8位"]])))
[ { "context": ";; Copyright (c) 2010 Tom Crayford,\n;;\n;; Redistribution and use in source and binar", "end": 34, "score": 0.9998286962509155, "start": 22, "tag": "NAME", "value": "Tom Crayford" } ]
src/clojure_refactoring/rename.clj
tcrayford/clojure-refactoring
6
;; Copyright (c) 2010 Tom Crayford, ;; ;; 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 clojure-refactoring.rename (:use [clojure-refactoring.support replace] clojure-refactoring.ast.zip clojure-refactoring.support.find-bindings-above-node) (:require [clojure.zip :as zip]) (:require [clojure-refactoring.support.parser :as parser]) (:require [clojure-refactoring.ast :as ast])) (defn rename-in-ast [ast old new] (ast/replace-symbol-in-ast-node old new ast)) (defn rename [node old-name new-name] (let [ast (parser/parse node) old (symbol old-name) new (symbol new-name)] (ast/ast->string (rename-in-ast ast old new)))) (defn rename-node [loc new-name] (if ((bindings-above loc) (zip/node loc)) loc (zip/replace loc (ast/symbol new-name)))) (defn rename-non-shadowed [new-sym node old-name] (zip-walk (ast-zip node) #(if (= (zip/node %) (ast/symbol old-name)) (rename-node % new-sym) %))) (defn renaming-fn [old-var new-sym] "Returns a function for renaming nodes" (fn [node] (rename-non-shadowed new-sym node (.sym old-var)))) (defn global-rename [ns old-name new-name] "Sends a list of alists to emacs for processing as renames." (let [old-var (ns-resolve ns old-name)] (replace-callers old-var (renaming-fn old-var new-name))))
118876
;; Copyright (c) 2010 <NAME>, ;; ;; 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 clojure-refactoring.rename (:use [clojure-refactoring.support replace] clojure-refactoring.ast.zip clojure-refactoring.support.find-bindings-above-node) (:require [clojure.zip :as zip]) (:require [clojure-refactoring.support.parser :as parser]) (:require [clojure-refactoring.ast :as ast])) (defn rename-in-ast [ast old new] (ast/replace-symbol-in-ast-node old new ast)) (defn rename [node old-name new-name] (let [ast (parser/parse node) old (symbol old-name) new (symbol new-name)] (ast/ast->string (rename-in-ast ast old new)))) (defn rename-node [loc new-name] (if ((bindings-above loc) (zip/node loc)) loc (zip/replace loc (ast/symbol new-name)))) (defn rename-non-shadowed [new-sym node old-name] (zip-walk (ast-zip node) #(if (= (zip/node %) (ast/symbol old-name)) (rename-node % new-sym) %))) (defn renaming-fn [old-var new-sym] "Returns a function for renaming nodes" (fn [node] (rename-non-shadowed new-sym node (.sym old-var)))) (defn global-rename [ns old-name new-name] "Sends a list of alists to emacs for processing as renames." (let [old-var (ns-resolve ns old-name)] (replace-callers old-var (renaming-fn old-var new-name))))
true
;; Copyright (c) 2010 PI:NAME:<NAME>END_PI, ;; ;; 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 clojure-refactoring.rename (:use [clojure-refactoring.support replace] clojure-refactoring.ast.zip clojure-refactoring.support.find-bindings-above-node) (:require [clojure.zip :as zip]) (:require [clojure-refactoring.support.parser :as parser]) (:require [clojure-refactoring.ast :as ast])) (defn rename-in-ast [ast old new] (ast/replace-symbol-in-ast-node old new ast)) (defn rename [node old-name new-name] (let [ast (parser/parse node) old (symbol old-name) new (symbol new-name)] (ast/ast->string (rename-in-ast ast old new)))) (defn rename-node [loc new-name] (if ((bindings-above loc) (zip/node loc)) loc (zip/replace loc (ast/symbol new-name)))) (defn rename-non-shadowed [new-sym node old-name] (zip-walk (ast-zip node) #(if (= (zip/node %) (ast/symbol old-name)) (rename-node % new-sym) %))) (defn renaming-fn [old-var new-sym] "Returns a function for renaming nodes" (fn [node] (rename-non-shadowed new-sym node (.sym old-var)))) (defn global-rename [ns old-name new-name] "Sends a list of alists to emacs for processing as renames." (let [old-var (ns-resolve ns old-name)] (replace-callers old-var (renaming-fn old-var new-name))))
[ { "context": "able-sql])\n\t(jdbc/insert! pgdb :users {:username \"lindsaybluth\" :email \"lindsay@bluth.com\"})\n\t(jdbc/insert! pgdb", "end": 222, "score": 0.999655544757843, "start": 210, "tag": "USERNAME", "value": "lindsaybluth" }, { "context": "rt! pgdb :users {:username \"lindsaybluth\" :email \"lindsay@bluth.com\"})\n\t(jdbc/insert! pgdb :users {:username \"tobiasf", "end": 249, "score": 0.9999282360076904, "start": 232, "tag": "EMAIL", "value": "lindsay@bluth.com" }, { "context": "uth.com\"})\n\t(jdbc/insert! pgdb :users {:username \"tobiasfunke\" :email \"tobias@funke.com\"})\n\t(apply str (jdbc/qu", "end": 303, "score": 0.9996329545974731, "start": 292, "tag": "USERNAME", "value": "tobiasfunke" }, { "context": "ert! pgdb :users {:username \"tobiasfunke\" :email \"tobias@funke.com\"})\n\t(apply str (jdbc/query pgdb [\"select * from u", "end": 329, "score": 0.9999271631240845, "start": 313, "tag": "EMAIL", "value": "tobias@funke.com" } ]
sample/src/sample/core.clj
echelon60/sample_clojure_postgres
1
(ns sample.core (:gen-class)) (use 'clojure.tools.logging) (load-file "db/repl-connection.clj") (defn -main [username] (jdbc/execute! pgdb [create-users-table-sql]) (jdbc/insert! pgdb :users {:username "lindsaybluth" :email "lindsay@bluth.com"}) (jdbc/insert! pgdb :users {:username "tobiasfunke" :email "tobias@funke.com"}) (apply str (jdbc/query pgdb ["select * from users where username=?" username])))
17984
(ns sample.core (:gen-class)) (use 'clojure.tools.logging) (load-file "db/repl-connection.clj") (defn -main [username] (jdbc/execute! pgdb [create-users-table-sql]) (jdbc/insert! pgdb :users {:username "lindsaybluth" :email "<EMAIL>"}) (jdbc/insert! pgdb :users {:username "tobiasfunke" :email "<EMAIL>"}) (apply str (jdbc/query pgdb ["select * from users where username=?" username])))
true
(ns sample.core (:gen-class)) (use 'clojure.tools.logging) (load-file "db/repl-connection.clj") (defn -main [username] (jdbc/execute! pgdb [create-users-table-sql]) (jdbc/insert! pgdb :users {:username "lindsaybluth" :email "PI:EMAIL:<EMAIL>END_PI"}) (jdbc/insert! pgdb :users {:username "tobiasfunke" :email "PI:EMAIL:<EMAIL>END_PI"}) (apply str (jdbc/query pgdb ["select * from users where username=?" username])))
[ { "context": "))\n\n (testing \"person name creation\"\n (is (= \"Max\" (:given-names (contact-name/make \"Max\" \"Muster\")", "end": 486, "score": 0.9307862520217896, "start": 483, "tag": "NAME", "value": "Max" }, { "context": " (is (= \"Max\" (:given-names (contact-name/make \"Max\" \"Muster\"))))\n (is (= \"Max Fritz\" (:given-name", "end": 525, "score": 0.9988560676574707, "start": 522, "tag": "NAME", "value": "Max" }, { "context": " (= \"Max\" (:given-names (contact-name/make \"Max\" \"Muster\"))))\n (is (= \"Max Fritz\" (:given-names (contac", "end": 534, "score": 0.9958696365356445, "start": 528, "tag": "NAME", "value": "Muster" }, { "context": "(contact-name/make \"Max\" \"Muster\"))))\n (is (= \"Max Fritz\" (:given-names (contact-name/make \"Max Fritz\" \"Mu", "end": 561, "score": 0.999825119972229, "start": 552, "tag": "NAME", "value": "Max Fritz" }, { "context": " (= \"Max Fritz\" (:given-names (contact-name/make \"Max Fritz\" \"Muster\"))))\n (is (= \"Muster\" (:surnames (con", "end": 606, "score": 0.9998533725738525, "start": 597, "tag": "NAME", "value": "Max Fritz" }, { "context": "tz\" (:given-names (contact-name/make \"Max Fritz\" \"Muster\"))))\n (is (= \"Muster\" (:surnames (contact-name", "end": 615, "score": 0.9990468621253967, "start": 609, "tag": "NAME", "value": "Muster" }, { "context": " (is (= \"Muster\" (:surnames (contact-name/make \"Max\" \"Muster\")))))\n\n (testing \"company name creation", "end": 675, "score": 0.9985306262969971, "start": 672, "tag": "NAME", "value": "Max" }, { "context": " (= \"Muster\" (:surnames (contact-name/make \"Max\" \"Muster\")))))\n\n (testing \"company name creation\"\n (is", "end": 684, "score": 0.9067052006721497, "start": 678, "tag": "NAME", "value": "Muster" }, { "context": "ganization-name]}\n (contact-name/make \"Guckes Rohrka GbR\" \"Max\" \"Muster\")]\n\n (is (= \"Max\" given-n", "end": 1003, "score": 0.8746830821037292, "start": 992, "tag": "NAME", "value": "ckes Rohrka" }, { "context": " (contact-name/make \"Guckes Rohrka GbR\" \"Max\" \"Muster\")]\n\n (is (= \"Max\" given-names))\n ", "end": 1013, "score": 0.9997720718383789, "start": 1010, "tag": "NAME", "value": "Max" }, { "context": " (contact-name/make \"Guckes Rohrka GbR\" \"Max\" \"Muster\")]\n\n (is (= \"Max\" given-names))\n (is (=", "end": 1022, "score": 0.9988537430763245, "start": 1016, "tag": "NAME", "value": "Muster" }, { "context": "n \"Guckes Rohrka e.V.\")\n (is-organization \"Guckes Rohrka UG\")\n (is-organization \"Guckes Rohrka", "end": 1692, "score": 0.5226380825042725, "start": 1688, "tag": "NAME", "value": "ckes" }, { "context": ")))\n\n (testing \"person name parsing\"\n (is (= \"Max\" (:given-names (contact-name/parse \"Max Musterman", "end": 1801, "score": 0.9997873902320862, "start": 1798, "tag": "NAME", "value": "Max" }, { "context": " (is (= \"Max\" (:given-names (contact-name/parse \"Max Mustermann\"))))\n (is (= \"Max Wilhelm\" (:given-names (cont", "end": 1852, "score": 0.9997697472572327, "start": 1838, "tag": "NAME", "value": "Max Mustermann" }, { "context": "ntact-name/parse \"Max Mustermann\"))))\n (is (= \"Max Wilhelm\" (:given-names (contact-name/parse \"Max Wilhelm M", "end": 1881, "score": 0.9998099207878113, "start": 1870, "tag": "NAME", "value": "Max Wilhelm" }, { "context": " \"Max Wilhelm\" (:given-names (contact-name/parse \"Max Wilhelm Mustermann\"))))\n (is (= \"Mustermann\" (:surnames (contact-", "end": 1940, "score": 0.9998376965522766, "start": 1918, "tag": "NAME", "value": "Max Wilhelm Mustermann" }, { "context": "me/parse \"Max Wilhelm Mustermann\"))))\n (is (= \"Mustermann\" (:surnames (contact-name/parse \"Max Mustermann\")", "end": 1968, "score": 0.9997916221618652, "start": 1958, "tag": "NAME", "value": "Mustermann" }, { "context": "s (= \"Mustermann\" (:surnames (contact-name/parse \"Max Mustermann\"))))\n (is (= \"Mustermann-Meyer\" (:surnames (co", "end": 2016, "score": 0.9998408555984497, "start": 2002, "tag": "NAME", "value": "Max Mustermann" }, { "context": "ntact-name/parse \"Max Mustermann\"))))\n (is (= \"Mustermann-Meyer\" (:surnames (contact-name/parse \"Max Mustermann-M", "end": 2050, "score": 0.9997813105583191, "start": 2034, "tag": "NAME", "value": "Mustermann-Meyer" }, { "context": "Mustermann-Meyer\" (:surnames (contact-name/parse \"Max Mustermann-Meyer\"))))))\n", "end": 2104, "score": 0.9997875690460205, "start": 2084, "tag": "NAME", "value": "Max Mustermann-Meyer" } ]
test/address_decoder/types/name_test.clj
GuckesRohrkaGbR/address-decoder
1
(ns address-decoder.types.name-test (:require [clojure.test :refer :all]) (:require [address-decoder.types.contact-name :as contact-name])) (deftest contact-name-creation-test (testing "empty name creation" (let [{:keys [given-names surnames organization-name]} (contact-name/make)] (is (= "" given-names)) (is (= "" surnames)) (is (= "" organization-name)))) (testing "person name creation" (is (= "Max" (:given-names (contact-name/make "Max" "Muster")))) (is (= "Max Fritz" (:given-names (contact-name/make "Max Fritz" "Muster")))) (is (= "Muster" (:surnames (contact-name/make "Max" "Muster"))))) (testing "company name creation" (is (= "Guckes Rohrka GbR" (:organization-name (contact-name/make "Guckes Rohrka GbR"))))) (testing "contact person name creation" (let [{:keys [given-names surnames organization-name]} (contact-name/make "Guckes Rohrka GbR" "Max" "Muster")] (is (= "Max" given-names)) (is (= "Muster" surnames)) (is (= "Guckes Rohrka GbR" organization-name))))) (deftest contact-name-parsing (testing "company name parsing" (letfn [(is-organization [org-name] (is (= org-name (:organization-name (contact-name/parse org-name)))))] (is-organization "Guckes Rohrka GbR") (is-organization "Guckes Rohrka GmbH") (is-organization "Guckes Rohrka OHG") (is-organization "Guckes Rohrka KG") (is-organization "Guckes Rohrka KGaA") (is-organization "Guckes Rohrka eG") (is-organization "Guckes Rohrka e.V.") (is-organization "Guckes Rohrka UG") (is-organization "Guckes Rohrka VVaG"))) (testing "person name parsing" (is (= "Max" (:given-names (contact-name/parse "Max Mustermann")))) (is (= "Max Wilhelm" (:given-names (contact-name/parse "Max Wilhelm Mustermann")))) (is (= "Mustermann" (:surnames (contact-name/parse "Max Mustermann")))) (is (= "Mustermann-Meyer" (:surnames (contact-name/parse "Max Mustermann-Meyer"))))))
24408
(ns address-decoder.types.name-test (:require [clojure.test :refer :all]) (:require [address-decoder.types.contact-name :as contact-name])) (deftest contact-name-creation-test (testing "empty name creation" (let [{:keys [given-names surnames organization-name]} (contact-name/make)] (is (= "" given-names)) (is (= "" surnames)) (is (= "" organization-name)))) (testing "person name creation" (is (= "<NAME>" (:given-names (contact-name/make "<NAME>" "<NAME>")))) (is (= "<NAME>" (:given-names (contact-name/make "<NAME>" "<NAME>")))) (is (= "Muster" (:surnames (contact-name/make "<NAME>" "<NAME>"))))) (testing "company name creation" (is (= "Guckes Rohrka GbR" (:organization-name (contact-name/make "Guckes Rohrka GbR"))))) (testing "contact person name creation" (let [{:keys [given-names surnames organization-name]} (contact-name/make "Gu<NAME> GbR" "<NAME>" "<NAME>")] (is (= "Max" given-names)) (is (= "Muster" surnames)) (is (= "Guckes Rohrka GbR" organization-name))))) (deftest contact-name-parsing (testing "company name parsing" (letfn [(is-organization [org-name] (is (= org-name (:organization-name (contact-name/parse org-name)))))] (is-organization "Guckes Rohrka GbR") (is-organization "Guckes Rohrka GmbH") (is-organization "Guckes Rohrka OHG") (is-organization "Guckes Rohrka KG") (is-organization "Guckes Rohrka KGaA") (is-organization "Guckes Rohrka eG") (is-organization "Guckes Rohrka e.V.") (is-organization "Gu<NAME> Rohrka UG") (is-organization "Guckes Rohrka VVaG"))) (testing "person name parsing" (is (= "<NAME>" (:given-names (contact-name/parse "<NAME>")))) (is (= "<NAME>" (:given-names (contact-name/parse "<NAME>")))) (is (= "<NAME>" (:surnames (contact-name/parse "<NAME>")))) (is (= "<NAME>" (:surnames (contact-name/parse "<NAME>"))))))
true
(ns address-decoder.types.name-test (:require [clojure.test :refer :all]) (:require [address-decoder.types.contact-name :as contact-name])) (deftest contact-name-creation-test (testing "empty name creation" (let [{:keys [given-names surnames organization-name]} (contact-name/make)] (is (= "" given-names)) (is (= "" surnames)) (is (= "" organization-name)))) (testing "person name creation" (is (= "PI:NAME:<NAME>END_PI" (:given-names (contact-name/make "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI")))) (is (= "PI:NAME:<NAME>END_PI" (:given-names (contact-name/make "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI")))) (is (= "Muster" (:surnames (contact-name/make "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"))))) (testing "company name creation" (is (= "Guckes Rohrka GbR" (:organization-name (contact-name/make "Guckes Rohrka GbR"))))) (testing "contact person name creation" (let [{:keys [given-names surnames organization-name]} (contact-name/make "GuPI:NAME:<NAME>END_PI GbR" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI")] (is (= "Max" given-names)) (is (= "Muster" surnames)) (is (= "Guckes Rohrka GbR" organization-name))))) (deftest contact-name-parsing (testing "company name parsing" (letfn [(is-organization [org-name] (is (= org-name (:organization-name (contact-name/parse org-name)))))] (is-organization "Guckes Rohrka GbR") (is-organization "Guckes Rohrka GmbH") (is-organization "Guckes Rohrka OHG") (is-organization "Guckes Rohrka KG") (is-organization "Guckes Rohrka KGaA") (is-organization "Guckes Rohrka eG") (is-organization "Guckes Rohrka e.V.") (is-organization "GuPI:NAME:<NAME>END_PI Rohrka UG") (is-organization "Guckes Rohrka VVaG"))) (testing "person name parsing" (is (= "PI:NAME:<NAME>END_PI" (:given-names (contact-name/parse "PI:NAME:<NAME>END_PI")))) (is (= "PI:NAME:<NAME>END_PI" (:given-names (contact-name/parse "PI:NAME:<NAME>END_PI")))) (is (= "PI:NAME:<NAME>END_PI" (:surnames (contact-name/parse "PI:NAME:<NAME>END_PI")))) (is (= "PI:NAME:<NAME>END_PI" (:surnames (contact-name/parse "PI:NAME:<NAME>END_PI"))))))
[ { "context": "input :login-form :passwd {:type :password, :value passwd, :required true}]\n [:> bp/Button {:intent :p", "end": 561, "score": 0.7617628574371338, "start": 555, "tag": "PASSWORD", "value": "passwd" } ]
src/app/view/login_form.cljs
LeXofLeviafan/personal-bookmarks
0
(ns app.view.login-form (:require ["@blueprintjs/core" :as bp] [re-frame.core :as rf] [app.util :refer [force-evt]] [app.view.components :as comp])) (defn login-form [] (let [{:keys [user passwd]} @(rf/subscribe [:login-form]) error @(rf/subscribe [:auth-error])] [:form.login (and error [:> bp/Callout {:intent :danger} error]) [comp/input :login-form :user {:type :email, :value user, :required true}] [comp/input :login-form :passwd {:type :password, :value passwd, :required true}] [:> bp/Button {:intent :primary, :type :submit, :on-click (force-evt [:logon])} "Log in"]]))
98197
(ns app.view.login-form (:require ["@blueprintjs/core" :as bp] [re-frame.core :as rf] [app.util :refer [force-evt]] [app.view.components :as comp])) (defn login-form [] (let [{:keys [user passwd]} @(rf/subscribe [:login-form]) error @(rf/subscribe [:auth-error])] [:form.login (and error [:> bp/Callout {:intent :danger} error]) [comp/input :login-form :user {:type :email, :value user, :required true}] [comp/input :login-form :passwd {:type :password, :value <PASSWORD>, :required true}] [:> bp/Button {:intent :primary, :type :submit, :on-click (force-evt [:logon])} "Log in"]]))
true
(ns app.view.login-form (:require ["@blueprintjs/core" :as bp] [re-frame.core :as rf] [app.util :refer [force-evt]] [app.view.components :as comp])) (defn login-form [] (let [{:keys [user passwd]} @(rf/subscribe [:login-form]) error @(rf/subscribe [:auth-error])] [:form.login (and error [:> bp/Callout {:intent :danger} error]) [comp/input :login-form :user {:type :email, :value user, :required true}] [comp/input :login-form :passwd {:type :password, :value PI:PASSWORD:<PASSWORD>END_PI, :required true}] [:> bp/Button {:intent :primary, :type :submit, :on-click (force-evt [:logon])} "Log in"]]))
[ { "context": ";\n; Copyright © 2021 Peter Monks\n;\n; Licensed under the Apache License, Version 2.", "end": 32, "score": 0.9996545910835266, "start": 21, "tag": "NAME", "value": "Peter Monks" } ]
test/lice_comb/files_test.clj
pmonks/lice-comb
3
; ; Copyright © 2021 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 lice-comb.files-test (:require [clojure.test :refer [deftest testing is use-fixtures]] [clojure.java.io :as io] [lice-comb.test-boilerplate :refer [fixture]] [lice-comb.files :refer [probable-license-file? probable-license-files file->ids dir->ids zip->ids]])) (use-fixtures :once fixture) (def test-data-path "./test/lice_comb/data") (deftest probable-license-file?-tests (testing "Nil, empty or blank names" (is (= false (probable-license-file? nil))) (is (= false (probable-license-file? ""))) (is (= false (probable-license-file? " "))) (is (= false (probable-license-file? "\n"))) (is (= false (probable-license-file? "\t")))) (testing "Filenames that are probable license files" (is (= true (probable-license-file? "pom.xml"))) (is (= true (probable-license-file? "POM.XML"))) (is (= true (probable-license-file? "asf-cat-1.0.12.pom"))) (is (= true (probable-license-file? "license"))) (is (= true (probable-license-file? "LICENSE"))) (is (= true (probable-license-file? "license.txt"))) (is (= true (probable-license-file? "LICENSE.TXT"))) (is (= true (probable-license-file? "copying"))) (is (= true (probable-license-file? "COPYING")))) (testing "Filenames that are not probable license files" (is (= false (probable-license-file? "NOTICES"))) (is (= false (probable-license-file? "notices"))) (is (= false (probable-license-file? "licenses"))) (is (= false (probable-license-file? "LICENSES"))) (is (= false (probable-license-file? "deps.edn"))) (is (= false (probable-license-file? "pm.xml")))) (testing "Filenames including paths" (is (= true (probable-license-file? "/path/to/a/project/containing/a/pom.xml"))) (is (= false (probable-license-file? "/a/different/path/to/some/NOTICES"))))) (deftest probable-license-files-tests (testing "Nil, empty, or blank directory" (is (nil? (probable-license-files nil))) (is (thrown? java.io.FileNotFoundException (probable-license-files ""))) (is (thrown? java.io.FileNotFoundException (probable-license-files " "))) (is (thrown? java.io.FileNotFoundException (probable-license-files "\n"))) (is (thrown? java.io.FileNotFoundException (probable-license-files "\t")))) (testing "Not a directory" (is (thrown? java.nio.file.NotDirectoryException (probable-license-files "deps.edn")))) (testing "A real directory" (is (= #{(io/file (str test-data-path "/asf-cat-1.0.12.pom")) (io/file (str test-data-path "/with-parent.pom")) (io/file (str test-data-path "/no-xml-ns.pom")) (io/file (str test-data-path "/simple.pom")) (io/file (str test-data-path "/CC-BY-4.0/LICENSE")) (io/file (str test-data-path "/MPL-2.0/LICENSE"))} (probable-license-files test-data-path))))) (deftest file->ids-tests (testing "Nil, empty, or blank filename" (is (nil? (file->ids nil))) (is (thrown? java.io.FileNotFoundException (file->ids ""))) (is (thrown? java.io.FileNotFoundException (file->ids " "))) (is (thrown? java.io.FileNotFoundException (file->ids "\n"))) (is (thrown? java.io.FileNotFoundException (file->ids "\t")))) (testing "Non-existent files" (is (thrown? java.io.FileNotFoundException (file->ids "this_file_does_not_exist")))) (testing "License files" ; (is (= #{"Apache-1.0"} (file->ids "https://www.apache.org/licenses/LICENSE-1.0"))) ; Note: this page incorrectly lists itself as Apache 1.1 (is (= #{"CC-BY-4.0"} (file->ids (str test-data-path "/CC-BY-4.0/LICENSE")))) (is (= #{"MPL-2.0"} (file->ids (str test-data-path "/MPL-2.0/LICENSE")))) (is (= #{"Apache-1.1"} (file->ids "https://www.apache.org/licenses/LICENSE-1.1"))) (is (= #{"Apache-2.0"} (file->ids "https://www.apache.org/licenses/LICENSE-2.0.txt"))) (is (= #{"EPL-1.0"} (file->ids "https://www.eclipse.org/org/documents/epl-1.0/EPL-1.0.txt"))) (is (= #{"EPL-2.0"} (file->ids "https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.txt"))) (is (= #{"CDDL-1.0"} (file->ids "https://spdx.org/licenses/CDDL-1.0.txt"))) (is (= #{"CDDL-1.1"} (file->ids "https://spdx.org/licenses/CDDL-1.1.txt"))) (is (= #{"GPL-1.0"} (file->ids "https://www.gnu.org/licenses/gpl-1.0.txt"))) (is (= #{"GPL-2.0"} (file->ids "https://www.gnu.org/licenses/gpl-2.0.txt"))) (is (= #{"GPL-3.0"} (file->ids "https://www.gnu.org/licenses/gpl-3.0.txt"))) (is (= #{"LGPL-2.0"} (file->ids "https://www.gnu.org/licenses/lgpl-2.0.txt"))) (is (= #{"LGPL-2.1"} (file->ids "https://www.gnu.org/licenses/lgpl-2.1.txt"))) (is (= #{"LGPL-3.0"} (file->ids "https://www.gnu.org/licenses/lgpl-3.0.txt"))) (is (= #{"AGPL-3.0"} (file->ids "https://www.gnu.org/licenses/agpl-3.0.txt"))) (is (= #{"Unlicense"} (file->ids "https://unlicense.org/UNLICENSE"))) (is (= #{"WTFPL"} (file->ids "http://www.wtfpl.net/txt/copying/")))) (testing "POM files" (is (= #{"Apache-2.0"} (file->ids (str test-data-path "/simple.pom")))) (is (= #{"BSD-3-Clause"} (file->ids (str test-data-path "/no-xml-ns.pom")))) (is (= #{"Apache-2.0"} (file->ids (str test-data-path "/asf-cat-1.0.12.pom")))) (is (= #{"Apache-2.0"} (file->ids (str test-data-path "/with-parent.pom")))))) (deftest dir->ids-tests (testing "Nil, empty, or blank directory name" (is (nil? (dir->ids nil))) (is (thrown? java.io.FileNotFoundException (dir->ids ""))) (is (thrown? java.io.FileNotFoundException (dir->ids " "))) (is (thrown? java.io.FileNotFoundException (dir->ids "\n"))) (is (thrown? java.io.FileNotFoundException (dir->ids "\t")))) (testing "Non-existent or invalid directory" (is (thrown? java.io.FileNotFoundException (dir->ids "this_directory_does_not_exist"))) (is (thrown? java.nio.file.NotDirectoryException (dir->ids "deps.edn")))) (testing "Valid directory" (is (= #{"Apache-2.0" "BSD-3-Clause" "MPL-2.0" "CC-BY-4.0"} (dir->ids "."))))) (deftest zip->ids-tests (testing "Nil, empty, or blank zip file name" (is (nil? (zip->ids nil))) (is (thrown? java.io.FileNotFoundException (zip->ids ""))) ; Note the hodgepodge of different thrown exception types here - java.util.zip is a mess! (is (thrown? java.nio.file.NoSuchFileException (zip->ids " "))) (is (thrown? java.nio.file.NoSuchFileException (zip->ids "\n"))) (is (thrown? java.nio.file.NoSuchFileException (zip->ids "\t")))) (testing "Non-existent zip file" (is (thrown? java.nio.file.NoSuchFileException (zip->ids "this_zip_file_does_not_exist")))) (testing "Invalid zip file" (is (thrown? java.util.zip.ZipException (zip->ids (str test-data-path "/bad.zip"))))) (testing "Valid zip file" (is (= #{"Apache-2.0"} (zip->ids (str test-data-path "/good.zip"))))))
82209
; ; Copyright © 2021 <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 lice-comb.files-test (:require [clojure.test :refer [deftest testing is use-fixtures]] [clojure.java.io :as io] [lice-comb.test-boilerplate :refer [fixture]] [lice-comb.files :refer [probable-license-file? probable-license-files file->ids dir->ids zip->ids]])) (use-fixtures :once fixture) (def test-data-path "./test/lice_comb/data") (deftest probable-license-file?-tests (testing "Nil, empty or blank names" (is (= false (probable-license-file? nil))) (is (= false (probable-license-file? ""))) (is (= false (probable-license-file? " "))) (is (= false (probable-license-file? "\n"))) (is (= false (probable-license-file? "\t")))) (testing "Filenames that are probable license files" (is (= true (probable-license-file? "pom.xml"))) (is (= true (probable-license-file? "POM.XML"))) (is (= true (probable-license-file? "asf-cat-1.0.12.pom"))) (is (= true (probable-license-file? "license"))) (is (= true (probable-license-file? "LICENSE"))) (is (= true (probable-license-file? "license.txt"))) (is (= true (probable-license-file? "LICENSE.TXT"))) (is (= true (probable-license-file? "copying"))) (is (= true (probable-license-file? "COPYING")))) (testing "Filenames that are not probable license files" (is (= false (probable-license-file? "NOTICES"))) (is (= false (probable-license-file? "notices"))) (is (= false (probable-license-file? "licenses"))) (is (= false (probable-license-file? "LICENSES"))) (is (= false (probable-license-file? "deps.edn"))) (is (= false (probable-license-file? "pm.xml")))) (testing "Filenames including paths" (is (= true (probable-license-file? "/path/to/a/project/containing/a/pom.xml"))) (is (= false (probable-license-file? "/a/different/path/to/some/NOTICES"))))) (deftest probable-license-files-tests (testing "Nil, empty, or blank directory" (is (nil? (probable-license-files nil))) (is (thrown? java.io.FileNotFoundException (probable-license-files ""))) (is (thrown? java.io.FileNotFoundException (probable-license-files " "))) (is (thrown? java.io.FileNotFoundException (probable-license-files "\n"))) (is (thrown? java.io.FileNotFoundException (probable-license-files "\t")))) (testing "Not a directory" (is (thrown? java.nio.file.NotDirectoryException (probable-license-files "deps.edn")))) (testing "A real directory" (is (= #{(io/file (str test-data-path "/asf-cat-1.0.12.pom")) (io/file (str test-data-path "/with-parent.pom")) (io/file (str test-data-path "/no-xml-ns.pom")) (io/file (str test-data-path "/simple.pom")) (io/file (str test-data-path "/CC-BY-4.0/LICENSE")) (io/file (str test-data-path "/MPL-2.0/LICENSE"))} (probable-license-files test-data-path))))) (deftest file->ids-tests (testing "Nil, empty, or blank filename" (is (nil? (file->ids nil))) (is (thrown? java.io.FileNotFoundException (file->ids ""))) (is (thrown? java.io.FileNotFoundException (file->ids " "))) (is (thrown? java.io.FileNotFoundException (file->ids "\n"))) (is (thrown? java.io.FileNotFoundException (file->ids "\t")))) (testing "Non-existent files" (is (thrown? java.io.FileNotFoundException (file->ids "this_file_does_not_exist")))) (testing "License files" ; (is (= #{"Apache-1.0"} (file->ids "https://www.apache.org/licenses/LICENSE-1.0"))) ; Note: this page incorrectly lists itself as Apache 1.1 (is (= #{"CC-BY-4.0"} (file->ids (str test-data-path "/CC-BY-4.0/LICENSE")))) (is (= #{"MPL-2.0"} (file->ids (str test-data-path "/MPL-2.0/LICENSE")))) (is (= #{"Apache-1.1"} (file->ids "https://www.apache.org/licenses/LICENSE-1.1"))) (is (= #{"Apache-2.0"} (file->ids "https://www.apache.org/licenses/LICENSE-2.0.txt"))) (is (= #{"EPL-1.0"} (file->ids "https://www.eclipse.org/org/documents/epl-1.0/EPL-1.0.txt"))) (is (= #{"EPL-2.0"} (file->ids "https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.txt"))) (is (= #{"CDDL-1.0"} (file->ids "https://spdx.org/licenses/CDDL-1.0.txt"))) (is (= #{"CDDL-1.1"} (file->ids "https://spdx.org/licenses/CDDL-1.1.txt"))) (is (= #{"GPL-1.0"} (file->ids "https://www.gnu.org/licenses/gpl-1.0.txt"))) (is (= #{"GPL-2.0"} (file->ids "https://www.gnu.org/licenses/gpl-2.0.txt"))) (is (= #{"GPL-3.0"} (file->ids "https://www.gnu.org/licenses/gpl-3.0.txt"))) (is (= #{"LGPL-2.0"} (file->ids "https://www.gnu.org/licenses/lgpl-2.0.txt"))) (is (= #{"LGPL-2.1"} (file->ids "https://www.gnu.org/licenses/lgpl-2.1.txt"))) (is (= #{"LGPL-3.0"} (file->ids "https://www.gnu.org/licenses/lgpl-3.0.txt"))) (is (= #{"AGPL-3.0"} (file->ids "https://www.gnu.org/licenses/agpl-3.0.txt"))) (is (= #{"Unlicense"} (file->ids "https://unlicense.org/UNLICENSE"))) (is (= #{"WTFPL"} (file->ids "http://www.wtfpl.net/txt/copying/")))) (testing "POM files" (is (= #{"Apache-2.0"} (file->ids (str test-data-path "/simple.pom")))) (is (= #{"BSD-3-Clause"} (file->ids (str test-data-path "/no-xml-ns.pom")))) (is (= #{"Apache-2.0"} (file->ids (str test-data-path "/asf-cat-1.0.12.pom")))) (is (= #{"Apache-2.0"} (file->ids (str test-data-path "/with-parent.pom")))))) (deftest dir->ids-tests (testing "Nil, empty, or blank directory name" (is (nil? (dir->ids nil))) (is (thrown? java.io.FileNotFoundException (dir->ids ""))) (is (thrown? java.io.FileNotFoundException (dir->ids " "))) (is (thrown? java.io.FileNotFoundException (dir->ids "\n"))) (is (thrown? java.io.FileNotFoundException (dir->ids "\t")))) (testing "Non-existent or invalid directory" (is (thrown? java.io.FileNotFoundException (dir->ids "this_directory_does_not_exist"))) (is (thrown? java.nio.file.NotDirectoryException (dir->ids "deps.edn")))) (testing "Valid directory" (is (= #{"Apache-2.0" "BSD-3-Clause" "MPL-2.0" "CC-BY-4.0"} (dir->ids "."))))) (deftest zip->ids-tests (testing "Nil, empty, or blank zip file name" (is (nil? (zip->ids nil))) (is (thrown? java.io.FileNotFoundException (zip->ids ""))) ; Note the hodgepodge of different thrown exception types here - java.util.zip is a mess! (is (thrown? java.nio.file.NoSuchFileException (zip->ids " "))) (is (thrown? java.nio.file.NoSuchFileException (zip->ids "\n"))) (is (thrown? java.nio.file.NoSuchFileException (zip->ids "\t")))) (testing "Non-existent zip file" (is (thrown? java.nio.file.NoSuchFileException (zip->ids "this_zip_file_does_not_exist")))) (testing "Invalid zip file" (is (thrown? java.util.zip.ZipException (zip->ids (str test-data-path "/bad.zip"))))) (testing "Valid zip file" (is (= #{"Apache-2.0"} (zip->ids (str test-data-path "/good.zip"))))))
true
; ; Copyright © 2021 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 lice-comb.files-test (:require [clojure.test :refer [deftest testing is use-fixtures]] [clojure.java.io :as io] [lice-comb.test-boilerplate :refer [fixture]] [lice-comb.files :refer [probable-license-file? probable-license-files file->ids dir->ids zip->ids]])) (use-fixtures :once fixture) (def test-data-path "./test/lice_comb/data") (deftest probable-license-file?-tests (testing "Nil, empty or blank names" (is (= false (probable-license-file? nil))) (is (= false (probable-license-file? ""))) (is (= false (probable-license-file? " "))) (is (= false (probable-license-file? "\n"))) (is (= false (probable-license-file? "\t")))) (testing "Filenames that are probable license files" (is (= true (probable-license-file? "pom.xml"))) (is (= true (probable-license-file? "POM.XML"))) (is (= true (probable-license-file? "asf-cat-1.0.12.pom"))) (is (= true (probable-license-file? "license"))) (is (= true (probable-license-file? "LICENSE"))) (is (= true (probable-license-file? "license.txt"))) (is (= true (probable-license-file? "LICENSE.TXT"))) (is (= true (probable-license-file? "copying"))) (is (= true (probable-license-file? "COPYING")))) (testing "Filenames that are not probable license files" (is (= false (probable-license-file? "NOTICES"))) (is (= false (probable-license-file? "notices"))) (is (= false (probable-license-file? "licenses"))) (is (= false (probable-license-file? "LICENSES"))) (is (= false (probable-license-file? "deps.edn"))) (is (= false (probable-license-file? "pm.xml")))) (testing "Filenames including paths" (is (= true (probable-license-file? "/path/to/a/project/containing/a/pom.xml"))) (is (= false (probable-license-file? "/a/different/path/to/some/NOTICES"))))) (deftest probable-license-files-tests (testing "Nil, empty, or blank directory" (is (nil? (probable-license-files nil))) (is (thrown? java.io.FileNotFoundException (probable-license-files ""))) (is (thrown? java.io.FileNotFoundException (probable-license-files " "))) (is (thrown? java.io.FileNotFoundException (probable-license-files "\n"))) (is (thrown? java.io.FileNotFoundException (probable-license-files "\t")))) (testing "Not a directory" (is (thrown? java.nio.file.NotDirectoryException (probable-license-files "deps.edn")))) (testing "A real directory" (is (= #{(io/file (str test-data-path "/asf-cat-1.0.12.pom")) (io/file (str test-data-path "/with-parent.pom")) (io/file (str test-data-path "/no-xml-ns.pom")) (io/file (str test-data-path "/simple.pom")) (io/file (str test-data-path "/CC-BY-4.0/LICENSE")) (io/file (str test-data-path "/MPL-2.0/LICENSE"))} (probable-license-files test-data-path))))) (deftest file->ids-tests (testing "Nil, empty, or blank filename" (is (nil? (file->ids nil))) (is (thrown? java.io.FileNotFoundException (file->ids ""))) (is (thrown? java.io.FileNotFoundException (file->ids " "))) (is (thrown? java.io.FileNotFoundException (file->ids "\n"))) (is (thrown? java.io.FileNotFoundException (file->ids "\t")))) (testing "Non-existent files" (is (thrown? java.io.FileNotFoundException (file->ids "this_file_does_not_exist")))) (testing "License files" ; (is (= #{"Apache-1.0"} (file->ids "https://www.apache.org/licenses/LICENSE-1.0"))) ; Note: this page incorrectly lists itself as Apache 1.1 (is (= #{"CC-BY-4.0"} (file->ids (str test-data-path "/CC-BY-4.0/LICENSE")))) (is (= #{"MPL-2.0"} (file->ids (str test-data-path "/MPL-2.0/LICENSE")))) (is (= #{"Apache-1.1"} (file->ids "https://www.apache.org/licenses/LICENSE-1.1"))) (is (= #{"Apache-2.0"} (file->ids "https://www.apache.org/licenses/LICENSE-2.0.txt"))) (is (= #{"EPL-1.0"} (file->ids "https://www.eclipse.org/org/documents/epl-1.0/EPL-1.0.txt"))) (is (= #{"EPL-2.0"} (file->ids "https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.txt"))) (is (= #{"CDDL-1.0"} (file->ids "https://spdx.org/licenses/CDDL-1.0.txt"))) (is (= #{"CDDL-1.1"} (file->ids "https://spdx.org/licenses/CDDL-1.1.txt"))) (is (= #{"GPL-1.0"} (file->ids "https://www.gnu.org/licenses/gpl-1.0.txt"))) (is (= #{"GPL-2.0"} (file->ids "https://www.gnu.org/licenses/gpl-2.0.txt"))) (is (= #{"GPL-3.0"} (file->ids "https://www.gnu.org/licenses/gpl-3.0.txt"))) (is (= #{"LGPL-2.0"} (file->ids "https://www.gnu.org/licenses/lgpl-2.0.txt"))) (is (= #{"LGPL-2.1"} (file->ids "https://www.gnu.org/licenses/lgpl-2.1.txt"))) (is (= #{"LGPL-3.0"} (file->ids "https://www.gnu.org/licenses/lgpl-3.0.txt"))) (is (= #{"AGPL-3.0"} (file->ids "https://www.gnu.org/licenses/agpl-3.0.txt"))) (is (= #{"Unlicense"} (file->ids "https://unlicense.org/UNLICENSE"))) (is (= #{"WTFPL"} (file->ids "http://www.wtfpl.net/txt/copying/")))) (testing "POM files" (is (= #{"Apache-2.0"} (file->ids (str test-data-path "/simple.pom")))) (is (= #{"BSD-3-Clause"} (file->ids (str test-data-path "/no-xml-ns.pom")))) (is (= #{"Apache-2.0"} (file->ids (str test-data-path "/asf-cat-1.0.12.pom")))) (is (= #{"Apache-2.0"} (file->ids (str test-data-path "/with-parent.pom")))))) (deftest dir->ids-tests (testing "Nil, empty, or blank directory name" (is (nil? (dir->ids nil))) (is (thrown? java.io.FileNotFoundException (dir->ids ""))) (is (thrown? java.io.FileNotFoundException (dir->ids " "))) (is (thrown? java.io.FileNotFoundException (dir->ids "\n"))) (is (thrown? java.io.FileNotFoundException (dir->ids "\t")))) (testing "Non-existent or invalid directory" (is (thrown? java.io.FileNotFoundException (dir->ids "this_directory_does_not_exist"))) (is (thrown? java.nio.file.NotDirectoryException (dir->ids "deps.edn")))) (testing "Valid directory" (is (= #{"Apache-2.0" "BSD-3-Clause" "MPL-2.0" "CC-BY-4.0"} (dir->ids "."))))) (deftest zip->ids-tests (testing "Nil, empty, or blank zip file name" (is (nil? (zip->ids nil))) (is (thrown? java.io.FileNotFoundException (zip->ids ""))) ; Note the hodgepodge of different thrown exception types here - java.util.zip is a mess! (is (thrown? java.nio.file.NoSuchFileException (zip->ids " "))) (is (thrown? java.nio.file.NoSuchFileException (zip->ids "\n"))) (is (thrown? java.nio.file.NoSuchFileException (zip->ids "\t")))) (testing "Non-existent zip file" (is (thrown? java.nio.file.NoSuchFileException (zip->ids "this_zip_file_does_not_exist")))) (testing "Invalid zip file" (is (thrown? java.util.zip.ZipException (zip->ids (str test-data-path "/bad.zip"))))) (testing "Valid zip file" (is (= #{"Apache-2.0"} (zip->ids (str test-data-path "/good.zip"))))))
[ { "context": "ail Website\"\n :email \"saing.sab@gmail.com\"\n :url \"https://www.s", "end": 810, "score": 0.9999144673347473, "start": 791, "tag": "EMAIL", "value": "saing.sab@gmail.com" } ]
src/stronghand_3e_api/handler.clj
saingsab/stronghand-3e-api
0
(ns stronghand-3e-api.handler (:require [compojure.api.sweet :refer :all] ;;[ring.util.http-response :refer :all] ;; [ring.middleware.cors :refer [wrap-cors]] [jumblerg.middleware.cors :refer [wrap-cors]] [stronghand-3e-api.usr-schema :as usrsc])) ;; [stronghand-3e-api.ops-schema :as opssc] ;; (defn routers [] ;; usrsc/routes ;; opssc/routes ;; ) (def app (api {:swagger {:ui "/" :spec "/swagger.json" :data {:info {:title "STRONGHAND 3E API" :description "Welcome to the STRONGHAND 3E API , This APIs are a set of endpoints created to manage customer order and matching in our platform." :contact {:name "Officail Website" :email "saing.sab@gmail.com" :url "https://www.stronghand3e.com"}}}}} ;; ;; accept everything ;; (wrap-cors routes #".*") ;; (wrap-cors routes identity) ;; ;; accept some things [todo on production] ;; (wrap-cors routes #".*localhost.*" #".*mydomain.org$") ;; (wrap-cors routes #(= (:allowed-origin db) %)) ;; Accept Everthing during dev (wrap-cors usrsc/routes #".*") (wrap-cors usrsc/routes identity) usrsc/routes))
110499
(ns stronghand-3e-api.handler (:require [compojure.api.sweet :refer :all] ;;[ring.util.http-response :refer :all] ;; [ring.middleware.cors :refer [wrap-cors]] [jumblerg.middleware.cors :refer [wrap-cors]] [stronghand-3e-api.usr-schema :as usrsc])) ;; [stronghand-3e-api.ops-schema :as opssc] ;; (defn routers [] ;; usrsc/routes ;; opssc/routes ;; ) (def app (api {:swagger {:ui "/" :spec "/swagger.json" :data {:info {:title "STRONGHAND 3E API" :description "Welcome to the STRONGHAND 3E API , This APIs are a set of endpoints created to manage customer order and matching in our platform." :contact {:name "Officail Website" :email "<EMAIL>" :url "https://www.stronghand3e.com"}}}}} ;; ;; accept everything ;; (wrap-cors routes #".*") ;; (wrap-cors routes identity) ;; ;; accept some things [todo on production] ;; (wrap-cors routes #".*localhost.*" #".*mydomain.org$") ;; (wrap-cors routes #(= (:allowed-origin db) %)) ;; Accept Everthing during dev (wrap-cors usrsc/routes #".*") (wrap-cors usrsc/routes identity) usrsc/routes))
true
(ns stronghand-3e-api.handler (:require [compojure.api.sweet :refer :all] ;;[ring.util.http-response :refer :all] ;; [ring.middleware.cors :refer [wrap-cors]] [jumblerg.middleware.cors :refer [wrap-cors]] [stronghand-3e-api.usr-schema :as usrsc])) ;; [stronghand-3e-api.ops-schema :as opssc] ;; (defn routers [] ;; usrsc/routes ;; opssc/routes ;; ) (def app (api {:swagger {:ui "/" :spec "/swagger.json" :data {:info {:title "STRONGHAND 3E API" :description "Welcome to the STRONGHAND 3E API , This APIs are a set of endpoints created to manage customer order and matching in our platform." :contact {:name "Officail Website" :email "PI:EMAIL:<EMAIL>END_PI" :url "https://www.stronghand3e.com"}}}}} ;; ;; accept everything ;; (wrap-cors routes #".*") ;; (wrap-cors routes identity) ;; ;; accept some things [todo on production] ;; (wrap-cors routes #".*localhost.*" #".*mydomain.org$") ;; (wrap-cors routes #(= (:allowed-origin db) %)) ;; Accept Everthing during dev (wrap-cors usrsc/routes #".*") (wrap-cors usrsc/routes identity) usrsc/routes))
[ { "context": "defrecord Message [sender text])\n\n(user.Message. \"Aaron\" \"Hello\")\n\n(def messages (ref ()))\n\n; bad idea\n(d", "end": 981, "score": 0.9940938949584961, "start": 976, "tag": "NAME", "value": "Aaron" }, { "context": "essage\")\n\n@messages\n\n(add-message (user.Message. \"Aaron\" \"Real Message\"))\n\n; == 5.3 Use Atoms for Uncoord", "end": 1877, "score": 0.9995771646499634, "start": 1872, "tag": "NAME", "value": "Aaron" }, { "context": "g Agents in Transactions\n\n(def output-dir \"/Users/matthewj/git/github/copperlight/programming-clojure-workbo", "end": 2630, "score": 0.8233330845832825, "start": 2622, "tag": "USERNAME", "value": "matthewj" }, { "context": "shot)))\n\n(add-message-with-backup (user.Message. \"John\" \"Message One\"))\n\n(add-message-with-backup (user.", "end": 3042, "score": 0.9997679591178894, "start": 3038, "tag": "NAME", "value": "John" }, { "context": " One\"))\n\n(add-message-with-backup (user.Message. \"Jane\" \"Message Two\"))\n\n; -- The Unified Update Model\n\n", "end": 3106, "score": 0.9987805485725403, "start": 3102, "tag": "NAME", "value": "Jane" } ]
data/train/clojure/521d6ac6d77d7de0585401871fcade6c4b1698fe05_State.clj
harshp8l/deep-learning-lang-detection
84
; refs - manage coordinated, synchronous changes to shared state ; atoms - manage uncoordinated, synchronous changes to shared state ; agents - manage asynchronous changes to shared state ; vars - manage thread-local state ; == 5.1 Concurrency, Parallelism, and Locking ; == 5.2 Refs and Software Transactional Memory (def current-track (ref "Mars, the Bringer of War")) (deref current-track) @current-track ; -- ref-set (ref-set current-track "Venus, the Bringer of Peace") (dosync (ref-set current-track "Venus, the Bringer of Peace")) ; -- Transactional Properties ; guaranteed properties: ; * updates are atomic ; * updates are consistent ; * updates are isolated ; * updates are NOT durable, because they are in-memory (def current-track (ref "Venus, the Bringer of Peace")) (def current-composer (ref "Holst")) (dosync (ref-set current-track "Credo") (ref-set current-composer "Byrd")) ; -- Alter (defrecord Message [sender text]) (user.Message. "Aaron" "Hello") (def messages (ref ())) ; bad idea (defn naive-add-message [msg] (dosync (ref-set messages (cons msg @messages)))) (defn add-message [msg] (dosync (alter messages conj msg))) ; order matters for alter ; (cons item sequence) ; (conj sequence item) (add-message (user.Message. "user 1" "hello")) (add-message (user.Message. "user 2" "howdy")) ; -- How STM Works: MVCC ; Multiversion Concurrency Control ; -- commute (defn add-message-commute [msg] (dosync (commute messages conj msg))) ; -- Prefer alter (def counter (ref 0)) (defn next-counter [] (dosync (alter counter inc))) (next-counter) (next-counter) ; -- Adding Validation to Refs (def validate-message-list (partial every? #(and (:sender %) (:text %)))) (def messages (ref () :validator validate-message-list)) (add-message "not a valid message") @messages (add-message (user.Message. "Aaron" "Real Message")) ; == 5.3 Use Atoms for Uncoordinated, Synchronous Updates (def current-track (atom "Venus, the Bringer of Peace")) (deref current-track) @current-track (reset! current-track "Credo") (def current-track (atom {:title "Credo" :composer "Byrd"})) (reset! current-track {:title "Spem in Alium" :composer "Tallis"}) (swap! current-track assoc :title "Sancte Deus") ; == 5.4 Use Agents for Asynchronous Updates (def counter (agent 0)) (send counter inc) @counter ; -- Validating Agents and Handling Errors (def counter (agent 0 :validator number?)) (send counter (fn [_] "boo")) @counter (agent-errors counter) (clear-agent-errors counter) @counter ; -- Including Agents in Transactions (def output-dir "/Users/matthewj/git/github/copperlight/programming-clojure-workbook/") (def backup-agent (agent (str output-dir "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)) snapshot))) (add-message-with-backup (user.Message. "John" "Message One")) (add-message-with-backup (user.Message. "Jane" "Message Two")) ; -- The Unified Update Model ; function application, ref: alter, atom: swap!, agent: send-off ; function (commutative), ref: commute ; function (non-blocking), agent: send ; simple setter, ref: ref-set, atom: reset! ; vars do not participate in the unified update model ; == 5.5 Managing Per-Thread State with Vars (def ^:dynamic foo 10) (.start (Thread. (fn [] (println foo)))) (binding [foo 42] foo) (defn print-foo [] (println foo)) (let [foo "let foo"] (print-foo)) (binding [foo "bound foo"] (print-foo)) ; -- Acting at a Distance (defn ^:dynamic slow-double [n] (Thread/sleep 100) (* n 2)) (defn calls-slow-double [] (map slow-double [1 2 1 2 1 2])) (time (dorun (calls-slow-double))) (defn demo-memoize [] (time (dorun (binding [slow-double (memoize slow-double)] (calls-slow-double))))) (demo-memoize) ; -- Working with Java Callback APIs ; refs and stm: coordinated, syncrhonous 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 ; == 5.6 A Clojure Snake see reader/snake.clj (use 'examples.snake) (game) ; -- Snakes Without Refs (defn update-positions [{snake :snake, apple :apple, :as game}] (if (eats? snake apple) (merge game {:apple (create-apple) :snake (move snake :grow)}) (merge game {:snake (move snake)}))) (actionPerformed [e] (swap! game update-positions) (when (lose? (@game :snake)) (swap! game reset-game) (JOptionPane/showMessageDialog frame "You lose!")))
13842
; refs - manage coordinated, synchronous changes to shared state ; atoms - manage uncoordinated, synchronous changes to shared state ; agents - manage asynchronous changes to shared state ; vars - manage thread-local state ; == 5.1 Concurrency, Parallelism, and Locking ; == 5.2 Refs and Software Transactional Memory (def current-track (ref "Mars, the Bringer of War")) (deref current-track) @current-track ; -- ref-set (ref-set current-track "Venus, the Bringer of Peace") (dosync (ref-set current-track "Venus, the Bringer of Peace")) ; -- Transactional Properties ; guaranteed properties: ; * updates are atomic ; * updates are consistent ; * updates are isolated ; * updates are NOT durable, because they are in-memory (def current-track (ref "Venus, the Bringer of Peace")) (def current-composer (ref "Holst")) (dosync (ref-set current-track "Credo") (ref-set current-composer "Byrd")) ; -- Alter (defrecord Message [sender text]) (user.Message. "<NAME>" "Hello") (def messages (ref ())) ; bad idea (defn naive-add-message [msg] (dosync (ref-set messages (cons msg @messages)))) (defn add-message [msg] (dosync (alter messages conj msg))) ; order matters for alter ; (cons item sequence) ; (conj sequence item) (add-message (user.Message. "user 1" "hello")) (add-message (user.Message. "user 2" "howdy")) ; -- How STM Works: MVCC ; Multiversion Concurrency Control ; -- commute (defn add-message-commute [msg] (dosync (commute messages conj msg))) ; -- Prefer alter (def counter (ref 0)) (defn next-counter [] (dosync (alter counter inc))) (next-counter) (next-counter) ; -- Adding Validation to Refs (def validate-message-list (partial every? #(and (:sender %) (:text %)))) (def messages (ref () :validator validate-message-list)) (add-message "not a valid message") @messages (add-message (user.Message. "<NAME>" "Real Message")) ; == 5.3 Use Atoms for Uncoordinated, Synchronous Updates (def current-track (atom "Venus, the Bringer of Peace")) (deref current-track) @current-track (reset! current-track "Credo") (def current-track (atom {:title "Credo" :composer "Byrd"})) (reset! current-track {:title "Spem in Alium" :composer "Tallis"}) (swap! current-track assoc :title "Sancte Deus") ; == 5.4 Use Agents for Asynchronous Updates (def counter (agent 0)) (send counter inc) @counter ; -- Validating Agents and Handling Errors (def counter (agent 0 :validator number?)) (send counter (fn [_] "boo")) @counter (agent-errors counter) (clear-agent-errors counter) @counter ; -- Including Agents in Transactions (def output-dir "/Users/matthewj/git/github/copperlight/programming-clojure-workbook/") (def backup-agent (agent (str output-dir "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)) snapshot))) (add-message-with-backup (user.Message. "<NAME>" "Message One")) (add-message-with-backup (user.Message. "<NAME>" "Message Two")) ; -- The Unified Update Model ; function application, ref: alter, atom: swap!, agent: send-off ; function (commutative), ref: commute ; function (non-blocking), agent: send ; simple setter, ref: ref-set, atom: reset! ; vars do not participate in the unified update model ; == 5.5 Managing Per-Thread State with Vars (def ^:dynamic foo 10) (.start (Thread. (fn [] (println foo)))) (binding [foo 42] foo) (defn print-foo [] (println foo)) (let [foo "let foo"] (print-foo)) (binding [foo "bound foo"] (print-foo)) ; -- Acting at a Distance (defn ^:dynamic slow-double [n] (Thread/sleep 100) (* n 2)) (defn calls-slow-double [] (map slow-double [1 2 1 2 1 2])) (time (dorun (calls-slow-double))) (defn demo-memoize [] (time (dorun (binding [slow-double (memoize slow-double)] (calls-slow-double))))) (demo-memoize) ; -- Working with Java Callback APIs ; refs and stm: coordinated, syncrhonous 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 ; == 5.6 A Clojure Snake see reader/snake.clj (use 'examples.snake) (game) ; -- Snakes Without Refs (defn update-positions [{snake :snake, apple :apple, :as game}] (if (eats? snake apple) (merge game {:apple (create-apple) :snake (move snake :grow)}) (merge game {:snake (move snake)}))) (actionPerformed [e] (swap! game update-positions) (when (lose? (@game :snake)) (swap! game reset-game) (JOptionPane/showMessageDialog frame "You lose!")))
true
; refs - manage coordinated, synchronous changes to shared state ; atoms - manage uncoordinated, synchronous changes to shared state ; agents - manage asynchronous changes to shared state ; vars - manage thread-local state ; == 5.1 Concurrency, Parallelism, and Locking ; == 5.2 Refs and Software Transactional Memory (def current-track (ref "Mars, the Bringer of War")) (deref current-track) @current-track ; -- ref-set (ref-set current-track "Venus, the Bringer of Peace") (dosync (ref-set current-track "Venus, the Bringer of Peace")) ; -- Transactional Properties ; guaranteed properties: ; * updates are atomic ; * updates are consistent ; * updates are isolated ; * updates are NOT durable, because they are in-memory (def current-track (ref "Venus, the Bringer of Peace")) (def current-composer (ref "Holst")) (dosync (ref-set current-track "Credo") (ref-set current-composer "Byrd")) ; -- Alter (defrecord Message [sender text]) (user.Message. "PI:NAME:<NAME>END_PI" "Hello") (def messages (ref ())) ; bad idea (defn naive-add-message [msg] (dosync (ref-set messages (cons msg @messages)))) (defn add-message [msg] (dosync (alter messages conj msg))) ; order matters for alter ; (cons item sequence) ; (conj sequence item) (add-message (user.Message. "user 1" "hello")) (add-message (user.Message. "user 2" "howdy")) ; -- How STM Works: MVCC ; Multiversion Concurrency Control ; -- commute (defn add-message-commute [msg] (dosync (commute messages conj msg))) ; -- Prefer alter (def counter (ref 0)) (defn next-counter [] (dosync (alter counter inc))) (next-counter) (next-counter) ; -- Adding Validation to Refs (def validate-message-list (partial every? #(and (:sender %) (:text %)))) (def messages (ref () :validator validate-message-list)) (add-message "not a valid message") @messages (add-message (user.Message. "PI:NAME:<NAME>END_PI" "Real Message")) ; == 5.3 Use Atoms for Uncoordinated, Synchronous Updates (def current-track (atom "Venus, the Bringer of Peace")) (deref current-track) @current-track (reset! current-track "Credo") (def current-track (atom {:title "Credo" :composer "Byrd"})) (reset! current-track {:title "Spem in Alium" :composer "Tallis"}) (swap! current-track assoc :title "Sancte Deus") ; == 5.4 Use Agents for Asynchronous Updates (def counter (agent 0)) (send counter inc) @counter ; -- Validating Agents and Handling Errors (def counter (agent 0 :validator number?)) (send counter (fn [_] "boo")) @counter (agent-errors counter) (clear-agent-errors counter) @counter ; -- Including Agents in Transactions (def output-dir "/Users/matthewj/git/github/copperlight/programming-clojure-workbook/") (def backup-agent (agent (str output-dir "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)) snapshot))) (add-message-with-backup (user.Message. "PI:NAME:<NAME>END_PI" "Message One")) (add-message-with-backup (user.Message. "PI:NAME:<NAME>END_PI" "Message Two")) ; -- The Unified Update Model ; function application, ref: alter, atom: swap!, agent: send-off ; function (commutative), ref: commute ; function (non-blocking), agent: send ; simple setter, ref: ref-set, atom: reset! ; vars do not participate in the unified update model ; == 5.5 Managing Per-Thread State with Vars (def ^:dynamic foo 10) (.start (Thread. (fn [] (println foo)))) (binding [foo 42] foo) (defn print-foo [] (println foo)) (let [foo "let foo"] (print-foo)) (binding [foo "bound foo"] (print-foo)) ; -- Acting at a Distance (defn ^:dynamic slow-double [n] (Thread/sleep 100) (* n 2)) (defn calls-slow-double [] (map slow-double [1 2 1 2 1 2])) (time (dorun (calls-slow-double))) (defn demo-memoize [] (time (dorun (binding [slow-double (memoize slow-double)] (calls-slow-double))))) (demo-memoize) ; -- Working with Java Callback APIs ; refs and stm: coordinated, syncrhonous 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 ; == 5.6 A Clojure Snake see reader/snake.clj (use 'examples.snake) (game) ; -- Snakes Without Refs (defn update-positions [{snake :snake, apple :apple, :as game}] (if (eats? snake apple) (merge game {:apple (create-apple) :snake (move snake :grow)}) (merge game {:snake (move snake)}))) (actionPerformed [e] (swap! game update-positions) (when (lose? (@game :snake)) (swap! game reset-game) (JOptionPane/showMessageDialog frame "You lose!")))
[ { "context": "equired params\"\n (is (= {:errors {:password \"password is too common.\"}}\n (mt/client :post 400 \"util/passw", "end": 296, "score": 0.8924413323402405, "start": 274, "tag": "PASSWORD", "value": "password is too common" }, { "context": "mplexity check\"\n (is (= {:errors {:password \"password is too common.\"}}\n (mt/client :post 400 \"util/passw", "end": 458, "score": 0.7267245054244995, "start": 436, "tag": "PASSWORD", "value": "password is too common" }, { "context": "lient :post 400 \"util/password_check\" {:password \"blah\"}))))\n\n (testing \"Should be a valid password\"\n", "end": 535, "score": 0.9863743782043457, "start": 531, "tag": "PASSWORD", "value": "blah" }, { "context": "lient :post 200 \"util/password_check\" {:password \"something123\"}))))))\n", "end": 692, "score": 0.999537467956543, "start": 680, "tag": "PASSWORD", "value": "something123" } ]
c#-metabase/test/metabase/api/util_test.clj
hanakhry/Crime_Admin
0
(ns metabase.api.util-test "Tests for /api/util" (:require [clojure.test :refer :all] [metabase.test :as mt])) (deftest password-check-test (testing "POST /api/util/password_check" (testing "Test for required params" (is (= {:errors {:password "password is too common."}} (mt/client :post 400 "util/password_check" {})))) (testing "Test complexity check" (is (= {:errors {:password "password is too common."}} (mt/client :post 400 "util/password_check" {:password "blah"})))) (testing "Should be a valid password" (is (= {:valid true} (mt/client :post 200 "util/password_check" {:password "something123"}))))))
45476
(ns metabase.api.util-test "Tests for /api/util" (:require [clojure.test :refer :all] [metabase.test :as mt])) (deftest password-check-test (testing "POST /api/util/password_check" (testing "Test for required params" (is (= {:errors {:password "<PASSWORD>."}} (mt/client :post 400 "util/password_check" {})))) (testing "Test complexity check" (is (= {:errors {:password "<PASSWORD>."}} (mt/client :post 400 "util/password_check" {:password "<PASSWORD>"})))) (testing "Should be a valid password" (is (= {:valid true} (mt/client :post 200 "util/password_check" {:password "<PASSWORD>"}))))))
true
(ns metabase.api.util-test "Tests for /api/util" (:require [clojure.test :refer :all] [metabase.test :as mt])) (deftest password-check-test (testing "POST /api/util/password_check" (testing "Test for required params" (is (= {:errors {:password "PI:PASSWORD:<PASSWORD>END_PI."}} (mt/client :post 400 "util/password_check" {})))) (testing "Test complexity check" (is (= {:errors {:password "PI:PASSWORD:<PASSWORD>END_PI."}} (mt/client :post 400 "util/password_check" {:password "PI:PASSWORD:<PASSWORD>END_PI"})))) (testing "Should be a valid password" (is (= {:valid true} (mt/client :post 200 "util/password_check" {:password "PI:PASSWORD:<PASSWORD>END_PI"}))))))
[ { "context": "#!/usr/bin/env bb\n\n;; Cheers to Bob Herrmann o/\n;; Taken and modified to add request body pars", "end": 44, "score": 0.9998665452003479, "start": 32, "tag": "NAME", "value": "Bob Herrmann" }, { "context": " add request body parsing from https://github.com/bherrmann7/bb-common/blob/master/wee_httpd.bb\n\n(ns wee-httpd", "end": 132, "score": 0.9997082948684692, "start": 122, "tag": "USERNAME", "value": "bherrmann7" } ]
examples/example_bb.clj
pfeodrippe/ummoi
8
#!/usr/bin/env bb ;; Cheers to Bob Herrmann o/ ;; Taken and modified to add request body parsing from https://github.com/bherrmann7/bb-common/blob/master/wee_httpd.bb (ns wee-httpd) (import (java.net ServerSocket)) (require '[clojure.string :as string] '[clojure.java.io :as io] '[cheshire.core :as json]) (defn create-worker-thread [client-socket request-handler] (.start (Thread. (fn [] (with-open [out (io/writer (.getOutputStream client-socket)) in (io/reader (.getInputStream client-socket))] (loop [] (let [[req-line & headers] (loop [headers []] (let [line (.readLine in)] (if (string/blank? line) headers (recur (conj headers line)))))] (when-not (nil? req-line) (let [headers-map (->> headers (map #(update (string/split % #":" 2) 0 string/lower-case)) (into {})) content-length (Integer/parseInt (string/trim (get headers-map "content-length"))) status 200 body (-> (loop [buf "" count 1] (let [c (.read in)] (if (>= count content-length) (str buf (char c)) (recur (str buf (char c)) (inc count))))) json/parse-string request-handler json/generate-string)] (.write out (format "HTTP/1.1 %s OK\r\nContent-Length: %s\r\n\r\n%s" status (count (.getBytes body)) body)) (.flush out) (recur)))))))))) (defn start-web-server [request-handler] (println "Server started \\o/") (.start (Thread. #(with-open [server-socket (new ServerSocket 4444)] (while true (let [client-socket (.accept server-socket)] (create-worker-thread client-socket request-handler ))))))) (def vars-keys [:c1 :c2 :account :sender :receiver :money :pc]) (defn handler [{self "self" vars "vars"}] (let [vars (zipmap vars-keys vars) sender (get-in vars [:sender self]) receiver (get-in vars [:receiver self]) money (get-in vars [:money self])] (-> (:account vars) (update sender - money) (update receiver + money)))) (wee-httpd/start-web-server handler) ;; Keep the shell script from returning. When evaling the whole buffer, comment this out. (while true (Thread/sleep 1000))
30356
#!/usr/bin/env bb ;; Cheers to <NAME> o/ ;; Taken and modified to add request body parsing from https://github.com/bherrmann7/bb-common/blob/master/wee_httpd.bb (ns wee-httpd) (import (java.net ServerSocket)) (require '[clojure.string :as string] '[clojure.java.io :as io] '[cheshire.core :as json]) (defn create-worker-thread [client-socket request-handler] (.start (Thread. (fn [] (with-open [out (io/writer (.getOutputStream client-socket)) in (io/reader (.getInputStream client-socket))] (loop [] (let [[req-line & headers] (loop [headers []] (let [line (.readLine in)] (if (string/blank? line) headers (recur (conj headers line)))))] (when-not (nil? req-line) (let [headers-map (->> headers (map #(update (string/split % #":" 2) 0 string/lower-case)) (into {})) content-length (Integer/parseInt (string/trim (get headers-map "content-length"))) status 200 body (-> (loop [buf "" count 1] (let [c (.read in)] (if (>= count content-length) (str buf (char c)) (recur (str buf (char c)) (inc count))))) json/parse-string request-handler json/generate-string)] (.write out (format "HTTP/1.1 %s OK\r\nContent-Length: %s\r\n\r\n%s" status (count (.getBytes body)) body)) (.flush out) (recur)))))))))) (defn start-web-server [request-handler] (println "Server started \\o/") (.start (Thread. #(with-open [server-socket (new ServerSocket 4444)] (while true (let [client-socket (.accept server-socket)] (create-worker-thread client-socket request-handler ))))))) (def vars-keys [:c1 :c2 :account :sender :receiver :money :pc]) (defn handler [{self "self" vars "vars"}] (let [vars (zipmap vars-keys vars) sender (get-in vars [:sender self]) receiver (get-in vars [:receiver self]) money (get-in vars [:money self])] (-> (:account vars) (update sender - money) (update receiver + money)))) (wee-httpd/start-web-server handler) ;; Keep the shell script from returning. When evaling the whole buffer, comment this out. (while true (Thread/sleep 1000))
true
#!/usr/bin/env bb ;; Cheers to PI:NAME:<NAME>END_PI o/ ;; Taken and modified to add request body parsing from https://github.com/bherrmann7/bb-common/blob/master/wee_httpd.bb (ns wee-httpd) (import (java.net ServerSocket)) (require '[clojure.string :as string] '[clojure.java.io :as io] '[cheshire.core :as json]) (defn create-worker-thread [client-socket request-handler] (.start (Thread. (fn [] (with-open [out (io/writer (.getOutputStream client-socket)) in (io/reader (.getInputStream client-socket))] (loop [] (let [[req-line & headers] (loop [headers []] (let [line (.readLine in)] (if (string/blank? line) headers (recur (conj headers line)))))] (when-not (nil? req-line) (let [headers-map (->> headers (map #(update (string/split % #":" 2) 0 string/lower-case)) (into {})) content-length (Integer/parseInt (string/trim (get headers-map "content-length"))) status 200 body (-> (loop [buf "" count 1] (let [c (.read in)] (if (>= count content-length) (str buf (char c)) (recur (str buf (char c)) (inc count))))) json/parse-string request-handler json/generate-string)] (.write out (format "HTTP/1.1 %s OK\r\nContent-Length: %s\r\n\r\n%s" status (count (.getBytes body)) body)) (.flush out) (recur)))))))))) (defn start-web-server [request-handler] (println "Server started \\o/") (.start (Thread. #(with-open [server-socket (new ServerSocket 4444)] (while true (let [client-socket (.accept server-socket)] (create-worker-thread client-socket request-handler ))))))) (def vars-keys [:c1 :c2 :account :sender :receiver :money :pc]) (defn handler [{self "self" vars "vars"}] (let [vars (zipmap vars-keys vars) sender (get-in vars [:sender self]) receiver (get-in vars [:receiver self]) money (get-in vars [:money self])] (-> (:account vars) (update sender - money) (update receiver + money)))) (wee-httpd/start-web-server handler) ;; Keep the shell script from returning. When evaling the whole buffer, comment this out. (while true (Thread/sleep 1000))
[ { "context": " \"restful-crud\"\n :user \"postgres\"\n :password \"test\"})\n\n(def swagger-config\n {:ui \"/swagger\"\n :spe", "end": 433, "score": 0.9995239973068237, "start": 429, "tag": "PASSWORD", "value": "test" } ]
clojure/restful-crud/src/restful_crud/core.clj
tamizhvendan/BlogSamples
30
(ns restful-crud.core (:require [ring.adapter.jetty :refer [run-jetty]] [toucan.db :as db] [toucan.models :as models] [compojure.api.sweet :refer [api routes]] [restful-crud.user :refer [user-entity-route]] [restful-crud.book :refer [book-entity-route]]) (:gen-class)) (def db-spec {:dbtype "postgres" :dbname "restful-crud" :user "postgres" :password "test"}) (def swagger-config {:ui "/swagger" :spec "/swagger.json" :options {:ui {:validatorUrl nil} :data {:info {:version "1.0.0", :title "Restful CRUD API"}}}}) ; (def app (api {:swagger swagger-config} (apply routes (concat user-routes book-routes)))) (def app (api {:swagger swagger-config} (apply routes book-entity-route user-entity-route))) (defn -main [& args] (db/set-default-db-connection! db-spec) (models/set-root-namespace! 'restful-crud.models) (run-jetty app {:port 3000}))
68664
(ns restful-crud.core (:require [ring.adapter.jetty :refer [run-jetty]] [toucan.db :as db] [toucan.models :as models] [compojure.api.sweet :refer [api routes]] [restful-crud.user :refer [user-entity-route]] [restful-crud.book :refer [book-entity-route]]) (:gen-class)) (def db-spec {:dbtype "postgres" :dbname "restful-crud" :user "postgres" :password "<PASSWORD>"}) (def swagger-config {:ui "/swagger" :spec "/swagger.json" :options {:ui {:validatorUrl nil} :data {:info {:version "1.0.0", :title "Restful CRUD API"}}}}) ; (def app (api {:swagger swagger-config} (apply routes (concat user-routes book-routes)))) (def app (api {:swagger swagger-config} (apply routes book-entity-route user-entity-route))) (defn -main [& args] (db/set-default-db-connection! db-spec) (models/set-root-namespace! 'restful-crud.models) (run-jetty app {:port 3000}))
true
(ns restful-crud.core (:require [ring.adapter.jetty :refer [run-jetty]] [toucan.db :as db] [toucan.models :as models] [compojure.api.sweet :refer [api routes]] [restful-crud.user :refer [user-entity-route]] [restful-crud.book :refer [book-entity-route]]) (:gen-class)) (def db-spec {:dbtype "postgres" :dbname "restful-crud" :user "postgres" :password "PI:PASSWORD:<PASSWORD>END_PI"}) (def swagger-config {:ui "/swagger" :spec "/swagger.json" :options {:ui {:validatorUrl nil} :data {:info {:version "1.0.0", :title "Restful CRUD API"}}}}) ; (def app (api {:swagger swagger-config} (apply routes (concat user-routes book-routes)))) (def app (api {:swagger swagger-config} (apply routes book-entity-route user-entity-route))) (defn -main [& args] (db/set-default-db-connection! db-spec) (models/set-root-namespace! 'restful-crud.models) (run-jetty app {:port 3000}))
[ { "context": " (into {}))}))\n\n\n(def storage-key \"tfsa-app-state\")\n\n(defn save-state [deposits]\n (when-some [stor", "end": 4271, "score": 0.9361293315887451, "start": 4257, "tag": "KEY", "value": "tfsa-app-state" } ]
src/tfsa/app_state.cljs
SneakyPeet/tax-free-savings-tracker
0
(ns tfsa.app-state (:require [citrus.core :as citrus] [cljs-time.core :as time] [cljs-time.format :as time.format] [tfsa.config :as conf] [clojure.string :as string] [tfsa.domain :as domain] [cljsjs.filesaverjs])) ;;;; ADDING PERSON (defmulti adding-person? (fn [event] event)) (defmethod adding-person? :init [] {:state false}) (defmethod adding-person? :adding-person/show [] {:state true}) (defmethod adding-person? :adding-person/hide [] {:state false}) (defmethod adding-person? :person/add [] {:state false}) (defmethod adding-person? :person/remove [_ _ state] {:state state}) (defn show-adding-person? [r] (citrus/subscription r [:adding-person?])) ;;;; Deposit Details (def initial-deposit-details (let [now (time/now)] {:year (time/year now) :month (time/month now) :day (time/day now) :amount 0 :note ""})) (defmulti deposit-details (fn [evt] evt)) (defmethod deposit-details :init [] (let [now (time/now)] {:state {:year (time/year now) :month (time/month now) :day (time/day now) :amount 0 :note ""}})) (defmethod deposit-details :deposit/set-field [_ [f v] state] {:state (assoc state f v)}) (defmethod deposit-details :deposit/clear [_ _ state] {:state (merge initial-deposit-details (select-keys state [:year :month :day]))}) (defmethod deposit-details :person/add [_ _ state] {:state state}) (defmethod deposit-details :person/remove [_ _ state] {:state state}) (defn deposit-form-detail [r] (citrus/subscription r [:deposit-details])) (defn can-deposit? [r] (citrus/subscription r [:deposit-details] (fn [{:keys [amount year month day] :as deposit}] (let [tax-year (domain/calculate-tax-year deposit) current-tax-year (:year (domain/current-tax-year-end-details))] (and (> amount 0) (time/after? (time/date-time year month day) (time/last-day-of-the-month conf/first-tfsa-year 2)) (<= tax-year current-tax-year)))))) ;;;; file (defmulti file (fn [evt] evt)) (defmethod file :default [_] {:state nil}) (defmethod file :save [_] {:state nil :save-file nil}) (defmethod file :load [_ [content]] {:state nil :hydrate-file content}) ;;;; help (defmulti help (fn [evt] evt)) (defmethod help :default [_ _ state] {:state state}) (defmethod help :init [_] {:state {:show? false :options {:store-local? true}}}) (defmethod help :show [_ _ state] {:state (assoc state :show? true)}) (defmethod help :hide [_ _ state] {:state (assoc state :show? false)}) (defn show-help? [r] (citrus/subscription r [:help :show?])) ;;;; SIDE EFFECTS ;;;; storage (defn reset-state ([r] (reset-state r {:person domain/initial-person :people domain/initial-people :deposits domain/initial-deposits})) ([r state] (let [{:keys [person people deposits]} state] (citrus/dispatch! r :deposits :init deposits) (citrus/dispatch! r :people :init people) (citrus/dispatch! r :person :init person)))) (defn deposits->saveable [deposits] (->> deposits vals (map (fn [{:keys [person amount day month year note]}] (->> [person year month day amount note] (map str) (string/join ",")))) (string/join "\r\n"))) (defn saveable->deposits [s] (->> (string/split-lines s) (map #(string/split % ",")) (map (fn [[person year month day amount note]] (domain/calculate-deposit-data {:person person :year (js/parseInt year) :month (js/parseInt month) :day (js/parseInt day) :amount (js/parseFloat amount) :note (or note "") :deposit-id (random-uuid)}))))) (defn saveable->state [s] (let [deposits (saveable->deposits s) people (set (map :person deposits)) person (first people)] {:person person :people people :deposits (->> (map (juxt :deposit-id identity) deposits) (into {}))})) (def storage-key "tfsa-app-state") (defn save-state [deposits] (when-some [storage js/localStorage] (.setItem storage storage-key (deposits->saveable deposits)))) (defn load-state [] (if-some [storage js/localStorage] (let [item (or (.getItem storage storage-key) "")] (if-not (string/blank? item) (saveable->state item) {})) {})) ;; file storage (defn save-file [deposits] (let [file-name (str "TFSA-Tracker-" (time.format/unparse (time.format/formatter "yyyyMMdd") (time/now)) ".csv") content (deposits->saveable deposits) name (clj->js [content]) type (clj->js {:type "text/plain;charset=utf-8"}) blob (js/Blob. name type)] (js/saveAs blob file-name))) (defn hydrate-file [r content] (reset-state r (saveable->state content)))
92722
(ns tfsa.app-state (:require [citrus.core :as citrus] [cljs-time.core :as time] [cljs-time.format :as time.format] [tfsa.config :as conf] [clojure.string :as string] [tfsa.domain :as domain] [cljsjs.filesaverjs])) ;;;; ADDING PERSON (defmulti adding-person? (fn [event] event)) (defmethod adding-person? :init [] {:state false}) (defmethod adding-person? :adding-person/show [] {:state true}) (defmethod adding-person? :adding-person/hide [] {:state false}) (defmethod adding-person? :person/add [] {:state false}) (defmethod adding-person? :person/remove [_ _ state] {:state state}) (defn show-adding-person? [r] (citrus/subscription r [:adding-person?])) ;;;; Deposit Details (def initial-deposit-details (let [now (time/now)] {:year (time/year now) :month (time/month now) :day (time/day now) :amount 0 :note ""})) (defmulti deposit-details (fn [evt] evt)) (defmethod deposit-details :init [] (let [now (time/now)] {:state {:year (time/year now) :month (time/month now) :day (time/day now) :amount 0 :note ""}})) (defmethod deposit-details :deposit/set-field [_ [f v] state] {:state (assoc state f v)}) (defmethod deposit-details :deposit/clear [_ _ state] {:state (merge initial-deposit-details (select-keys state [:year :month :day]))}) (defmethod deposit-details :person/add [_ _ state] {:state state}) (defmethod deposit-details :person/remove [_ _ state] {:state state}) (defn deposit-form-detail [r] (citrus/subscription r [:deposit-details])) (defn can-deposit? [r] (citrus/subscription r [:deposit-details] (fn [{:keys [amount year month day] :as deposit}] (let [tax-year (domain/calculate-tax-year deposit) current-tax-year (:year (domain/current-tax-year-end-details))] (and (> amount 0) (time/after? (time/date-time year month day) (time/last-day-of-the-month conf/first-tfsa-year 2)) (<= tax-year current-tax-year)))))) ;;;; file (defmulti file (fn [evt] evt)) (defmethod file :default [_] {:state nil}) (defmethod file :save [_] {:state nil :save-file nil}) (defmethod file :load [_ [content]] {:state nil :hydrate-file content}) ;;;; help (defmulti help (fn [evt] evt)) (defmethod help :default [_ _ state] {:state state}) (defmethod help :init [_] {:state {:show? false :options {:store-local? true}}}) (defmethod help :show [_ _ state] {:state (assoc state :show? true)}) (defmethod help :hide [_ _ state] {:state (assoc state :show? false)}) (defn show-help? [r] (citrus/subscription r [:help :show?])) ;;;; SIDE EFFECTS ;;;; storage (defn reset-state ([r] (reset-state r {:person domain/initial-person :people domain/initial-people :deposits domain/initial-deposits})) ([r state] (let [{:keys [person people deposits]} state] (citrus/dispatch! r :deposits :init deposits) (citrus/dispatch! r :people :init people) (citrus/dispatch! r :person :init person)))) (defn deposits->saveable [deposits] (->> deposits vals (map (fn [{:keys [person amount day month year note]}] (->> [person year month day amount note] (map str) (string/join ",")))) (string/join "\r\n"))) (defn saveable->deposits [s] (->> (string/split-lines s) (map #(string/split % ",")) (map (fn [[person year month day amount note]] (domain/calculate-deposit-data {:person person :year (js/parseInt year) :month (js/parseInt month) :day (js/parseInt day) :amount (js/parseFloat amount) :note (or note "") :deposit-id (random-uuid)}))))) (defn saveable->state [s] (let [deposits (saveable->deposits s) people (set (map :person deposits)) person (first people)] {:person person :people people :deposits (->> (map (juxt :deposit-id identity) deposits) (into {}))})) (def storage-key "<KEY>") (defn save-state [deposits] (when-some [storage js/localStorage] (.setItem storage storage-key (deposits->saveable deposits)))) (defn load-state [] (if-some [storage js/localStorage] (let [item (or (.getItem storage storage-key) "")] (if-not (string/blank? item) (saveable->state item) {})) {})) ;; file storage (defn save-file [deposits] (let [file-name (str "TFSA-Tracker-" (time.format/unparse (time.format/formatter "yyyyMMdd") (time/now)) ".csv") content (deposits->saveable deposits) name (clj->js [content]) type (clj->js {:type "text/plain;charset=utf-8"}) blob (js/Blob. name type)] (js/saveAs blob file-name))) (defn hydrate-file [r content] (reset-state r (saveable->state content)))
true
(ns tfsa.app-state (:require [citrus.core :as citrus] [cljs-time.core :as time] [cljs-time.format :as time.format] [tfsa.config :as conf] [clojure.string :as string] [tfsa.domain :as domain] [cljsjs.filesaverjs])) ;;;; ADDING PERSON (defmulti adding-person? (fn [event] event)) (defmethod adding-person? :init [] {:state false}) (defmethod adding-person? :adding-person/show [] {:state true}) (defmethod adding-person? :adding-person/hide [] {:state false}) (defmethod adding-person? :person/add [] {:state false}) (defmethod adding-person? :person/remove [_ _ state] {:state state}) (defn show-adding-person? [r] (citrus/subscription r [:adding-person?])) ;;;; Deposit Details (def initial-deposit-details (let [now (time/now)] {:year (time/year now) :month (time/month now) :day (time/day now) :amount 0 :note ""})) (defmulti deposit-details (fn [evt] evt)) (defmethod deposit-details :init [] (let [now (time/now)] {:state {:year (time/year now) :month (time/month now) :day (time/day now) :amount 0 :note ""}})) (defmethod deposit-details :deposit/set-field [_ [f v] state] {:state (assoc state f v)}) (defmethod deposit-details :deposit/clear [_ _ state] {:state (merge initial-deposit-details (select-keys state [:year :month :day]))}) (defmethod deposit-details :person/add [_ _ state] {:state state}) (defmethod deposit-details :person/remove [_ _ state] {:state state}) (defn deposit-form-detail [r] (citrus/subscription r [:deposit-details])) (defn can-deposit? [r] (citrus/subscription r [:deposit-details] (fn [{:keys [amount year month day] :as deposit}] (let [tax-year (domain/calculate-tax-year deposit) current-tax-year (:year (domain/current-tax-year-end-details))] (and (> amount 0) (time/after? (time/date-time year month day) (time/last-day-of-the-month conf/first-tfsa-year 2)) (<= tax-year current-tax-year)))))) ;;;; file (defmulti file (fn [evt] evt)) (defmethod file :default [_] {:state nil}) (defmethod file :save [_] {:state nil :save-file nil}) (defmethod file :load [_ [content]] {:state nil :hydrate-file content}) ;;;; help (defmulti help (fn [evt] evt)) (defmethod help :default [_ _ state] {:state state}) (defmethod help :init [_] {:state {:show? false :options {:store-local? true}}}) (defmethod help :show [_ _ state] {:state (assoc state :show? true)}) (defmethod help :hide [_ _ state] {:state (assoc state :show? false)}) (defn show-help? [r] (citrus/subscription r [:help :show?])) ;;;; SIDE EFFECTS ;;;; storage (defn reset-state ([r] (reset-state r {:person domain/initial-person :people domain/initial-people :deposits domain/initial-deposits})) ([r state] (let [{:keys [person people deposits]} state] (citrus/dispatch! r :deposits :init deposits) (citrus/dispatch! r :people :init people) (citrus/dispatch! r :person :init person)))) (defn deposits->saveable [deposits] (->> deposits vals (map (fn [{:keys [person amount day month year note]}] (->> [person year month day amount note] (map str) (string/join ",")))) (string/join "\r\n"))) (defn saveable->deposits [s] (->> (string/split-lines s) (map #(string/split % ",")) (map (fn [[person year month day amount note]] (domain/calculate-deposit-data {:person person :year (js/parseInt year) :month (js/parseInt month) :day (js/parseInt day) :amount (js/parseFloat amount) :note (or note "") :deposit-id (random-uuid)}))))) (defn saveable->state [s] (let [deposits (saveable->deposits s) people (set (map :person deposits)) person (first people)] {:person person :people people :deposits (->> (map (juxt :deposit-id identity) deposits) (into {}))})) (def storage-key "PI:KEY:<KEY>END_PI") (defn save-state [deposits] (when-some [storage js/localStorage] (.setItem storage storage-key (deposits->saveable deposits)))) (defn load-state [] (if-some [storage js/localStorage] (let [item (or (.getItem storage storage-key) "")] (if-not (string/blank? item) (saveable->state item) {})) {})) ;; file storage (defn save-file [deposits] (let [file-name (str "TFSA-Tracker-" (time.format/unparse (time.format/formatter "yyyyMMdd") (time/now)) ".csv") content (deposits->saveable deposits) name (clj->js [content]) type (clj->js {:type "text/plain;charset=utf-8"}) blob (js/Blob. name type)] (js/saveAs blob file-name))) (defn hydrate-file [r content] (reset-state r (saveable->state content)))
[ { "context": "OTE: This code was forked from\nhttps://github.com/clojure/clojure/blob/master/src/clj/clojure/walk.clj\ncomm", "end": 1038, "score": 0.6848242878913879, "start": 1031, "tag": "USERNAME", "value": "clojure" }, { "context": "OTE: This code was forked from\nhttps://github.com/clojure/clojure/blob/master/src/clj/clojure/walk.clj\ncomm", "end": 1771, "score": 0.997160792350769, "start": 1764, "tag": "USERNAME", "value": "clojure" }, { "context": "OTE: This code was forked from\nhttps://github.com/clojure/clojure/blob/master/src/clj/clojure/walk.clj\ncomm", "end": 2344, "score": 0.9903008937835693, "start": 2337, "tag": "USERNAME", "value": "clojure" }, { "context": "OTE: This code was forked from\nhttps://github.com/clojure/clojure/blob/master/src/clj/clojure/walk.clj\ncomm", "end": 17198, "score": 0.8382207751274109, "start": 17191, "tag": "USERNAME", "value": "clojure" }, { "context": "ure/blob/master/src/clj/clojure/walk.clj\ncommit 2224dba\"}\n prewalkfn3\n [ss sm f]\n (walkfn3 sm (f", "end": 17255, "score": 0.5093809962272644, "start": 17253, "tag": "PASSWORD", "value": "24" } ]
data/train/clojure/03ff0a5b3c904cb66e394d56e9940d9f2697fa25core.clj
harshp8l/deep-learning-lang-detection
84
(ns junior.core) (defmacro ?else [x else] `(if ~x ~x ~else)) (defn !nil? [x] (not (nil? x))) (defmacro !nil?else [x else] `(if (!nil? ~x) ~x ~else)) (defmacro if= [x y then else] `(if (= ~x ~y) ~then ~else)) (defn ^{:doc "Creates a MapEntry"} map-entry ([x y] (map-entry [x y]))([coll] (if= 2 (count coll) (clojure.lang.MapEntry. (first coll) (second coll)) (throw (Exception. "CardinallityException in map-entry: Wrong number of elements in collection, must be of size 2"))))) (defn append [coll x] (if (or (seq? coll) (list? coll)) (apply conj (conj (empty coll) x) (reverse coll)) (conj coll x))) (defn ^{:doc "Like clojure.walk/walk but preserves metadata on lists. Traverses form, an arbitrary data structure. inner and outer are functions. Applies inner to each element of form, building up a data structure of the same type, then applies outer to the result. Recognizes all Clojure data structures. Consumes seqs as with doall. NOTE: This code was forked from https://github.com/clojure/clojure/blob/master/src/clj/clojure/walk.clj commit 2224dba"} walk4pre [inner outer form] (cond (list? form) (with-meta (outer (apply list (map inner form) )) (meta form)) ;(list? form) (outer (apply list (map inner form) )) (instance? clojure.lang.IMapEntry form) (outer (map-entry (map inner form))) (seq? form) (outer (doall (map inner form))) (instance? clojure.lang.IRecord form) (outer (reduce (fn [r x] (conj r (inner x))) form form)) (coll? form) (outer (into (empty form) (map inner form))) :else (outer form))) (defn ^{:doc "Like clojure.walk/prewalk but preserves metadata on lists. Like postwalk, but does pre-order traversal. NOTE: This code was forked from https://github.com/clojure/clojure/blob/master/src/clj/clojure/walk.clj commit 2224dba"} prewalk [f form] (walk4pre (partial prewalk f) identity (f form))) (defn ^{:doc "Like clojure.walk/walk but also takes the map-entry intead of vec in the IMapEntry cond. Traverses form, an arbitrary data structure. inner and outer are functions. Applies inner to each element of form, building up a data structure of the same type, then applies outer to the result. Recognizes all Clojure data structures. Consumes seqs as with doall. NOTE: This code was forked from https://github.com/clojure/clojure/blob/master/src/clj/clojure/walk.clj commit 2224dba"} walk4post [inner outer form] (cond (list? form) (outer (apply list (map inner form) )) (instance? clojure.lang.IMapEntry form) (outer (map-entry (map inner form))) (seq? form) (outer (doall (map inner form))) (instance? clojure.lang.IRecord form) (outer (reduce (fn [r x] (conj r (inner x))) form form)) (coll? form) (outer (into (empty form) (map inner form))) :else (outer form))) (defn postwalk "Performs a depth-first, post-order traversal of form. Calls f on each sub-form, uses f's return value in place of the original. Recognizes all Clojure data structures. Consumes seqs as with doall." {:added "1.1"} [f form] (walk4post (partial postwalk f) f form)) (defn do0 [& c] (last (map #(apply (first %) (next %)) c))) (defn transform0 [m x] (if (coll? x) (walk4pre #(!nil?else (m %) %) identity x) (!nil?else (m x) x)) ) (defn flat0 [m c] (loop [in- c out- (empty c)] (let [f (first in-) tr (transform0 m f)] (if (!nil? tr) (recur (next in-) (apply conj out- (if (list? tr) tr [tr]))) out-)))) (defn ^{:doc " Deprecated. If f is a symbol returns (map- f) if not nil, else f If f is a vector with count > 1, if not nil apply'es (map- f) to (next f), else f. Otherwise returns the map of the first f if not nil, else f. Usage: (abstract {'plus +} ['plus 1 2]) ;=> 3 ((abstract {'plus +} ['plus]) 1 2) ;=> 3 ((abstract {'plus +} 'plus) 1 2) ;=> 3"} abs0- [map- f] (cond (not (coll? f)) (!nil?else (map- f) f) (!nil? (map- (first f))) (if (next f) (if (and (meta (second f)) (:abs-args (meta (second f)))) (apply (map- (first f)) (into (second f) (walk4pre #(!nil?else (map- %) %) identity (next (next f))))) (apply (map- (first f)) (walk4pre #(!nil?else (map- %) %) identity (next f)))) ((map- (first f)))) :else (if (next f) (if (and (meta (second f)) (:abs-args (meta (second f)))) (apply (first f) (into (second f) (walk4pre #(!nil?else (map- %) %) identity (next (next f))))) (apply (first f) (walk4pre #(!nil?else (map- %) %) identity (next f)))) ((first f))))) (defn ^{:doc "basic features: (abs0 {the map} ['(args to flatten) 'arg1 'arg2 '(more args)]) no nested vectors. (abs0 {'s str 'a \"a\" 'b :b 'c 'c 'd '(\"d\" {\"e\" \"f\"})} ['(s a) '(b c) 'd]) ;=> a:bcd{\"e\" \"f\"}"} abs0 [m f] (let [fl (flat0 m f)](apply (first fl) (next fl)))) (defn ^{:doc "postwalks f applying abs0 to each vector"} fabs0 [map- & f] ;(prn f) (last (map #(postwalk (fn [x] (if (and (coll? x) (and (not (map-entry? x)) (not (map? x)))) (abs0 map- x) x)) %) f)) ) (defn resolve1 [sm x] ;(prn (type x) x) (loop [sm sm] (if (first sm) (if (map-entry? x) (if (!nil? ((first sm) (second x))) (map-entry (first x) ((first sm) (second x))) (recur (next sm))) (!nil?else ((first sm) x) (recur (next sm)))) nil))) (defn transform1 [sm x] (if (coll? x) (walk4pre #(!nil?else (resolve1 sm %) %) identity x) (!nil?else (resolve1 sm x) x)) ) (defn flat1 [sm c] (loop [in- c out- []] (let [f (first in-) vec? (vector? f) tr (if vec? nil (transform1 sm f))] (if vec? (recur (rest in-) (apply conj out- [f])) (if (!nil? tr) (do (prn 'tr '_ tr (type tr))(recur (rest in-) (apply conj out- (if (or (list? tr) (instance? clojure.lang.LazySeq tr)) (into [] tr) [tr])))) out-))))) (declare abs1) (defn apply1 [sm f] (prn "sm " sm) (prn "f " f) (apply (if (symbol? (first f)) (resolve (first f)) (first f)) (map #(if (vector? %) (abs1 sm %) %) (rest f))) ) (defn ^{:doc "like abs0 but accepts deep nested vectors. the map can be optionally the first argument. If the first argument points to a map, then its appended to the map chain. There is a map chain, a sequence like ({last map} {older map}...). (abs1 (seq [{:a +}]) [+ 2 [{:a 1 :b 2} + :a :b]]) ;=> 5 (abs1 (seq [{:a {:b + :c '(1 1)} :b +}]) [:a :b :c]) ;=> 2"} abs1 ([f] (abs1 {} f))([sm f] (let [m (if (map? (first f)) (first f)) mr (if m (transform1 sm m)) sm2 (if m (cons mr sm) sm) fl (if m (flat1 sm2 (rest f)) (flat1 sm2 f)) m2 (if (map? (first fl)) (first fl)) mr2 (if m2 (transform1 sm2 m2)) sm3 (if m2 (cons mr2 sm2) sm2) fl2 (if m2 (flat1 sm3 (rest fl)) (flat1 sm3 fl))] ;(prn fl2) (apply1 sm3 fl2)))) (defn literal? [x] (or (instance? clojure.lang.Keyword x) (instance? java.lang.Integer x) (instance? java.lang.Boolean x) (instance? java.lang.String x) (instance? java.lang.Long x) (instance? java.lang.Float x) (instance? java.lang.Character x) (instance? java.lang.Double x) (instance? java.lang.Byte x) (instance? java.lang.Short x) (instance? java.math.BigInteger x) (instance? java.math.BigDecimal x) (instance? clojure.lang.Ratio x))) (defn vector-type2 [v] (let [m (meta v)] (cond (nil? m) :c (:abs m) (if (keyword? (:abs m)) (:abs m) (throw (Exception. (str "NotKeywordException. vector-type: ^" m v " :abs meta key must map to a keyword. Ex. {:abs :some-vector-handler}, in this case you have to have a function like (defn some-vector-handler [sm f]...).")))) (> (count m) 1) (throw (Exception. (str "UndecidableException. vector-type: ^" m v " has more than one meta key."))) :else (key (first m))))) (defn map-type2 [v] (let [m (meta v)] (cond (nil? m) :l (:abs m) (if (keyword? (:abs m)) (:abs m) (throw (Exception. (str "NotKeywordException. map-type: ^" m v " :abs meta key must map to a keyword.")))) (> (count m) 1) (throw (Exception. (str "UndecidableException. map-type: ^" m v " has more than one meta key."))) :else (key (first m))))) (defn ^{:doc "resolves the var in the name of keyword k. Ex :str -> #'clojure.core/str"} resolve-keyword [k] (resolve (symbol (name k)))) (defn single-meta-key-resolve [f] (let [m (meta f) abs (if m (:abs m) nil) m2 (if abs (map-entry abs true) (if (> (count m) 1) nil;(throw (Exception. (str "single-meta-key-resolve " f " has more than one meta key. " m))) (first m))) ;pp (if (> (count m) 1) (throw (Exception. (str "single-meta-key-resolve " f " has more than one meta key. " m)))) ;fi (first (meta f)) ] (if m2 (resolve (symbol (subs (str (key m2)) 1))) nil) )) (declare transform2) (defn m [sm mp] ;(prn mp) (transform2 sm mp) ) (defn v [sm v] (transform2 sm v) ) (declare resolve2) (defn transform2 [sm x] ;(prn 'sm sm) (prn 'transforming x) (if (coll? x) #_(postwalk #(if (coll? %) % (let [res (resolve2 sm %)] (if res (res %) %))) x) (postwalk #(let [res (resolve2 sm %)] (if res (res %) %)) x) (let [res (resolve2 sm x)] (if (!nil? res) (res x) x))) ) (declare abs2) (defn ^{:doc "Named transformlet2."} l [sm m] ;(prn m) (loop [sm sm m m] (let [f (first m) ff (first f) fv (if (vector? ff) (abs2 sm ff) ff)] (if f (let [sec (second f)] (cond (vector? sec) (let [abs (abs2 sm (second f)) sm2 (cons {fv abs} sm)] (recur sm2 (rest m))) (map? sec) (let [sr (single-meta-key-resolve sec)] (if sr (let [sr-res (sr sm sec) sm2 (cons {fv sr-res} sm)] (recur sm2 (rest m))) (let [tr (transform2 sm sec) sm2 (cons {fv tr} sm)] (recur sm2 (rest m))))) (or (keyword? sec) (symbol? sec)) (let [res (resolve2 sm sec) sec-res (if res (sec res) sec) sm2 (cons {fv sec-res} sm)] (recur sm2 (rest m))) :else (let [tr (transform2 sm sec) sm2 (cons {fv tr} sm)] (recur sm2 (rest m))))) sm)))) (defn sm-add2 [sm m] (apply conj [m] sm) ) (defn flat2 [sm c] (loop [in- c out- (empty c)] (if (!nil? (first in-)) (let [f (first in-) tr (if (or (list? f) (instance? clojure.lang.LazySeq f)) (into [] f) [f])] (recur (rest in-) (apply conj out- tr))) out-))) (defn resolve2 [sm x] (loop [sm sm] (if (first sm) (if (map-entry? x) (if (!nil? ((first sm) (second x))) (map-entry (first x) ((first sm) (second x))) (recur (rest sm))) (if (!nil? ((first sm) x)) {x ((first sm) x)} (recur (rest sm)))) nil))) (defn apply2 [sm f] (let [;fapp (resolve2 sm f) tr (transform2 sm f)] ;(prn 'trd (type tr) tr #_(apply (first f) (rest f))) (apply (first tr) (rest tr))) ) #_(defn apply2 [sm f s] (let [fapp (resolve2 sm f) tr (transform2 sm s)] (prn 'trd (type tr) tr (apply fapp tr)) (apply fapp tr)) ) (defn ^{:doc "Named call2"} c [sm f] (loop [sm sm f- f last- nil] (let [fi (first f-)] (if (!nil? fi) (cond (map? fi)(let [sr (single-meta-key-resolve fi) tr (!nil?else sr l) sm2 (tr sm fi)] (recur sm2 (rest f-) (second (ffirst sm2)))) (vector? fi) (if (!nil? (next f-)) (let [app (apply2 sm (cons (second f-) fi))] app) (throw (Exception. (str "No function to apply to " fi ":" f)))) (or (symbol? fi) (keyword? fi)) (apply2 sm f-) :esle (apply2 sm f-)) last-)))) (defn ^{:doc "Main vector handler. Redirects the thread for ^:*[] vectors. Every handler should redirect to abs2 when unknown vector. Vector knowledges: ^:do[] - main thread. [] or ^:c[] - main call. "} abs2 ([f] (abs2 {} f))([sm f] (let [type- (vector-type2 f) ;the-meta (first (meta f)) #_type- #_(if the-meta (if= (key the-meta) :do :thread (single-meta-key-resolve f)) c) ;;pp (println type- 'f f 'sm sm) ] (cond (= :do type-) (let [;fl (flat2 sm f) ;m (if (map? (first fl)) (first fl)) ;sm2 (if m (l sm m) sm) manage-vector (fn [sm f fl] (let [ab (abs2 sm f)] [(rest fl) sm ab])) manage-map (fn [sm f fl] (let [type- (map-type2 f) ;sr (single-meta-key-resolve f) ;tr (!nil?else sr #'littlejr.core/l) ] (cond (= type- :l) (let [sm2 (l sm f) lst (second (ffirst sm2))] [(rest fl) sm2 lst]) :else [(rest fl) sm (transform2 sm f)] #_:else #_(throw (Exception. (str "The handler for :^t[] is not handler for this type of map ^" (meta f) f))))))] (loop [fl f sm sm last- nil] (if (first fl) (let [f (first fl) cond-f (cond (or (symbol? f) (keyword? f)) (let [res (resolve2 sm f) ;fr (f res) #_cond-fr #_(if res (cond (vector? fr) (manage-vector sm fr fl) (map? fr) (manage-map sm fr fl) :else [(rest fl) sm fr]) [(rest fl) sm f]) ]#_cond-fr [(rest fl) sm (f res)]) (vector? f) (manage-vector sm f fl) (map? f) (manage-map sm f fl) :else [(rest fl) sm f]) ](recur (nth cond-f 0) (nth cond-f 1) (nth cond-f 2))) last-))) (= :c type-) (c sm f) :else (let [res (resolve-keyword type-)] (if res (res sm f) (throw (Exception. (str "Don't know what to do with directive " type- ". It must resolve to function " (name type-) ", but couldn't resolve it. Source is ^" (meta f) f "."))))))))) #_(defn fnl3 ([] (fnl3 nil nil nil))([ss sm f] {:let {:l true} :mskip {:fn true}})) #_(defn walkfn3 [sm kp form] (cond (list? form) ;(with-meta (outer (apply list (map inner form))) (meta form)) (with-meta (apply list (map #(walkfn3 sm kp %) form))) (meta form) ;(list? form) (outer (apply list (map inner form) )) (instance? clojure.lang.IMapEntry form) (map-entry (map #(walkfn3 sm kp %) form)) (seq? form) (doall (map #(walkfn3 sm kp %) form)) ;(instance? clojure.lang.IRecord form) ; (reduce (fn [r x] (conj r (f x))) form form) (map? form) (if ((kp :let) (paradigm-type3 form)) (let [ks (keys form) except (kp :except) kp2 (conj kp {:except (apply conj ks except)})] (into (empty form) (map (fn [me] (map-entry (first me) (walkfn3 f (second me) kp2))) form))) (if ((kp :mskip) (paradigm-type3 form)) form (into (empty form) (map #(walkfn3 sm kp %) form)))) (vector? form) (let [para (paradigm-type3 form)] (if ((kp :fn) para) (let [par]) ()) (coll? form) (do (prn 'map) (outer (into (empty form) (map inner form)))) :else (outer form)))) #_(defn ^{:doc "Like clojure.walk/prewalk but preserves metadata on lists. Like postwalk, but does pre-order traversal. NOTE: This code was forked from https://github.com/clojure/clojure/blob/master/src/clj/clojure/walk.clj commit 2224dba"} prewalkfn3 [ss sm f] (walkfn3 sm (fnl3) f)) (defn paradigm-type3 [f] (let [m (meta f)] (cond (nil? m) (if (vector? f) :c (if (map? f) :l :s #_(throw (Exception. (str "paradigm-type3: NoMetaException. ^nil " f " meta is nil. Can't handle empty paradigm"))))) (:jr m) (if (keyword? (:jr m)) (:jr m) (throw (Exception. (str "paradigm-type3: NotKeywordException. :jr meta key must map to a keyword. Ex. {:jr :some-vector-handler}, in this case you have to have a function like (defn some-vector-handler [ss sm f]...). Source is ^" (meta f) f)))) (> (count m) 1) (throw (Exception. (str "paradigm-type3: UndecidableException. More than one meta key. Source is ^" (meta f) f))) :else (key (first m))))) (defn resolve3 ([sm x] ;(prn 'RESOLVE-sm sm) ;(prn 'RESOLVE-x x) (loop [sm sm] (if (first sm) #_(if (map-entry? x) (if (!nil? ((first sm) (second x))) (map-entry (first x) ((first sm) (second x))) (recur (rest sm)))) (if (contains? (first sm) x) {x ((first sm) x)} (recur (rest sm))) nil))) ([sm x s] (if (contains? (into #{} s) x) {x x} (resolve sm x)))) (defn resolve-back3 ([sm x] (resolve3 sm x)) ([level sm x] #_(prn 'resolve-back sm x) (loop [l 0 res x last x] (if (or (nil? res) (> l level)) {x last} (let [r (resolve3 sm res) rs (if (nil? r) nil (r res)) lst (if (nil? r) last (r res))] (recur (inc l) rs lst))))) ([level sm x s](if (contains? (into #{} s) x) {x x} (resolve-back3 level sm x)))) (defn defined? [ss sm x]) (def transform-paradigm3 { ;^:pre:sym-key:0([](fn [sm x] (prewalk #(if (or (symbol? %)(keyword? %)) (let [res (resolve3 sm %)] (if res (res %) %)) %) x))) ;(fn [sm x except] (prewalkfn3 (f :let) #(if (and (or (symbol? %) (keyword? %)) (not (contains? except %))) (let [res (resolve3 sm %)] (if res (res %) %)) %) x)) :pre:sym-key:0:except (fn [sm x except] (prewalk #(if (and (or (symbol? %) (keyword? %)) (not (contains? except %))) (let [res (resolve3 sm %)] (if res (res %) %)) %) x)) :pre:sym-key:0 (fn [sm x] (prewalk #(if (or (symbol? %)(keyword? %)) (let [res (resolve3 sm %)] (if res (res %) %)) %) x)) :pos:sym-key:0 (fn [sm x] (postwalk #(if (or (symbol? %)(keyword? %)) (let [res (resolve3 sm %)] (if res (res %) %)) %) x)) :pre:sym:0 (fn [sm x] (prewalk #(if (symbol? %) (let [res (resolve3 sm %)] (if res (res %) %)) %) x)) :pos:sym:0 (fn [sm x] (postwalk #(if (symbol? %) (let [res (resolve3 sm %)] (if res (res %) %)) %) x)) :pre:key:0 (fn [sm x] (prewalk #(if (keyword? %) (let [res (resolve3 sm %)] (if res (res %) %)) %) x)) :pre:all:0 (fn [sm x] (prewalk #(let [res (resolve3 sm %)] (if res (res %) %)) x)) :pre:all:1 (fn [sm x] (prewalk #(let [res (resolve-back3 1 sm %)] (if res (res %) %)) x)) :pos:all:0 (fn [sm x] (postwalk #(let [res (resolve3 sm %)] (if res (res %) %)) x)) :pos:all:1 (fn [sm x] (postwalk #(let [res (resolve-back3 1 sm %)] (if res (res %) %)) x))}) (declare abs3) (declare f0-3) (defn transform3 ([sm x] (transform3 sm x :pos:sym:0)) ([sm x par] (transform3 sm x par nil)) ([sm x par except] ;#_(prn 'TRANSFORM3-PAR par) ;#_(prn 'TRANSFORM3-X x) (let [para (transform-paradigm3 par)] (if para (if except (para sm x (into #{} except)) (do #_(prn 'TRANSFORM-PARA (para sm x))(para sm x))) (throw (Exception. (str "transform3: UnknownTransformationParadigm " par " for " x))))))) (defn vector3 [ss sm v] (into (empty v) (map (partial abs3 ss sm) v)) ) (defn map3 [ss sm m] (let [ks (keys m) vs (vals m) nks (map (partial abs3 ss sm) ks) nvs (map (partial abs3 ss sm) vs)] (apply assoc {} (interleave nks nvs))) ) (defn midentity3 [v] (if (empty? v) {} (apply assoc {} (interleave v v)))) (defn apply3 [ss sm f] ;(prn 'apply3-IN "^" (meta f) f) (if (map? (first f)) (let [fi (first f) vs (into [] (rest f)) type- (paradigm-type3 fi)] (if (= :x0 type-) (let [ks (fi :args) cntks (count ks) cntvs (count vs) n (- cntks cntvs) zm (if (> n 0) (zipmap ks (apply conj vs (vec (replicate n nil)))) (zipmap ks vs))] #_(prn 'n n 'APPLY3-zm(zipmap ks (apply conj vs (vec (replicate n nil))))) #_(prn 'apply3-OUT ^:do[zm (fi :f)]) (abs3 ss sm ^:do[zm (fi :f)])) (throw (Exception. (str "apply3: UnknownParadigmException. Can't handle this kind of map ^" (meta fi) fi ". Source is ^"(meta f) f))))) (let [;fapp (resolve2 sm f) tr (transform3 sm f) fi (first tr)] ;(prn 'trd (type tr) tr #_(apply (first f) (rest f))) (if (and (or (symbol? fi) (keyword? fi)) (not (map? (second tr)))) (throw (Exception. (str "apply3: NoMapForSymbolAsFunctionException. Source is: ^"(meta f) f))) (apply fi (rest tr))))) ) (defn flat3 [ss sm f] #_(prn 'FLAT3-SM sm) #_(prn 'FLAT3-F f) (loop [ss ss sm sm f f ef (empty f)] (let [fi (first f)] (if (!nil? fi) (cond (map? fi)(let [type- (paradigm-type3 fi) #_pp #_(prn 'FLAT3-PARADIGM type- fi)] (cond ;(= :fn type-) (recur ss sm (rest f) (conj ef fi)) (= :l type-) (let [l ((resolve3 ss :l) :l) sm2 (l ss sm fi) ] (recur ss sm2 (rest f) ef)) ; :else (recur ss sm (rest f) (conj ef fi)))) (vector? fi) (let [abs (abs3 ss sm fi)] (recur ss sm (rest f) (conj ef abs))) :else (let [tr (transform3 sm fi)] (recur ss sm (rest f) (conj ef tr)))) ef)))) (defn ^{:doc "This paradigm is more or less clojure like"} call3 [ss sm f] (let [;pp (prn 'call3-TOFLAT "^" (meta f) f) fl (flat3 ss sm f) fi (first fl) ;pp (prn 'call3-FLATTED "^" (meta fl) fl) ] (if (> (count fl) 1) (if (!nil? fi) (if (or (vector? fi) (seq? fi) (list? fi)) (if (!nil? (next fl)) (let [app (apply3 ss sm (concat (rest fl) fi))] app) (throw (Exception. (str "call3: MalformedStructure. No function to apply to " fi ": " f)))) (apply3 ss sm fl)) (throw (Exception. (str "call3: NilFunctionException. No function to apply. " (first f) " was nil. Source is " f)))) (fi)))) (defn flatf0-3 [ss sm f] ;(prn 'flatf0-3 f) (if (coll? f) (loop [ss ss sm sm f- f ef (empty f)] (let [fi (first f-) #_pp #_(prn 'flatf0-3-f-ef f- ef)] (if (!nil? fi) (cond (map? fi)(let [type- (paradigm-type3 fi)] (cond (= :l type-) (letfn [(lp [sm ks result] (if ks (let [k (first ks) sm2 (cons {k k} sm) fik (fi k) fn- (if (coll? fik) (if (= :f0 (paradigm-type3 fik)) (f0-3 ss sm2 fik) (flatf0-3 ss sm2 fik)) (transform3 sm2 fik))] #_(prn 'lp-fn- fn-) (lp sm2 (next ks) (conj result {k fn-}))) {:sm sm :result result}))] (let [lp- (lp sm (keys fi) (empty fi))] (recur ss (lp- :sm) (rest f-) (append ef (lp- :result))))) :else (recur ss sm (rest f-) (append ef fi)))) (vector? fi) (let [type- (paradigm-type3 fi)] (cond (= :f0 type-) (let [id (midentity3 (first fi)) sm2 (cons id sm) fn- (f0-3 ss sm2 fi) ef- (append ef fn-)] (recur ss sm2 (rest f-) ef-)) :else (let [tr (flatf0-3 ss sm fi) ef- (append ef tr)] (recur ss sm (rest f-) ef-)))) #_(let [fl (flatf0-3 ss sm fi)] (recur ss sm (rest f) (conj ef fl))) :else (let [tr (transform3 sm fi)] ;(prn 'FLATY3-else ef tr) (recur ss sm (rest f-) (append ef tr)))) (do #_(prn 'ef ef) ef)))) f)) (defn x0-3 [ss sm f] f) (defn f0-3 [ss sm v] #_(prn 'f0-3 v) (let [fapp (fn [sm v-] (if (vector? (v- 0)) (let [argl (v- 0) idn (midentity3 argl) sm2 (if (empty? idn) sm (cons idn sm)) tra (into ^:c[] (flatf0-3 ss sm2 (rest v-))) ] ^:x0{:f tra :args (v- 0) :src v} ) (let [tra (into ^:c[] (flatf0-3 ss sm v-))] ^:x0{:f tra :args [] :src v})))] (fapp sm v))) #_(defn f1-3 [ss sm v] #_(prn 'f0-3 v) (let [fapp (fn [sm v-] (if (vector? (v- 0)) (let [argl (v- 0) idn (midentity3 argl) sm2 (if (empty? idn) sm (cons idn sm)) tra (into ^:c[] (flatf1-3 ss sm2 (rest v-))) ] ^:x0{:f tra :args (v- 0) :src v} ) (let [tra (into ^:c[] (flatf1-3 ss sm v-))] ^:x0{:f tra :args [] :src v})))] (fapp sm v))) (defn recur3 [ss sm f] #_(prn 'RECUR-ms sm) #_(prn 'RECUR-f f) (into (empty f) (map (partial abs3 ss sm) f))) (defn loop3 [ss sm f] (let [fi (first f)] (if (map? fi) (let [vec- (into ^:v[] (keys fi)) fndef (apply conj ^:f0[vec-] (rest f)) floop (f0-3 ss sm fndef) init (into ^:v[] (vals fi)) ;pp (prn 'LOOP3-fndef fndef) ;pp (prn 'LOOP3-floop floop) ] (loop [i init] (let [abs (call3 ss sm [i floop]) type- (if (meta abs) (paradigm-type3 abs) nil) ;pp (prn 'LOOP3-abs abs) ] (if (= :rc type-) (do #_(prn 'LOOP3-recur "^" (meta abs) abs)(recur abs)) abs)))) (throw (Exception. (str "loop3: MalformedStructureException. First element must be a map. Source is ^" (meta f) f))))) ) (defn ^{:doc "This paradigm is more or less clojure like"} call3- [ss sm f] (loop [sm sm f- f last- nil] (let [fi (first f-)] (if (!nil? fi) (cond (map? fi)(let [type- (paradigm-type3 fi)] (if= type- :l (let [l ((resolve3 ss :l) :l) sm2 (l ss sm fi)] (recur sm2 (rest f-) (second (ffirst sm2)))) (throw (Exception. (str "call3: UnknownParadigmException. call3 can't handle this paradigm ^" (meta fi) fi))))) (vector? fi) (if (!nil? (next f-)) (let [app (apply3 sm (concat (rest f-) fi))] app) (throw (Exception. (str "call3: MalformedStructure. No function to apply to " fi ": " f)))) ;(or (symbol? fi) (keyword? fi)) (apply3 sm f-) :esle (let [r (resolve3 sm fi)] (if (!nil? r) (if (vector? (r fi)) (if (!nil? (next f-)) (let [app (apply3 sm (concat (rest f-) (r fi)))] app) (throw (Exception. (str "call3: MalformedStructure. No function to apply to " fi ":" f)))) (apply3 sm (cons (r fi) (rest f-)))) (apply3 sm f-)))) last-)))) (defn ^{:doc "Named transformlet2."} let3 [ss sm m] ;(prn m) (loop [sm sm m m] (let [f (first m) ff (first f) fv (if (vector? ff) (abs3 ss sm ff) ff)] (if f (let [sec (second f)] (if (or (map? sec) (vector? sec)) (if (and (map? sec) (= :l (paradigm-type3 sec))) (let [abs (abs3 ss sm ^:do[sec]) sm2 (cons {fv abs} sm)] (recur sm2 (rest m))) (let [abs (abs3 ss sm sec) sm2 (cons {fv abs} sm)] (recur sm2 (rest m)))) (let [res (resolve3 sm sec) sec-res (if res (sec res) sec) sm2 (cons {fv sec-res} sm)] (recur sm2 (rest m))))) sm)))) (defn thread3 [ss sm f] (let [;fl (flat2 sm f) ;m (if (map? (first fl)) (first fl)) ;sm2 (if m (l sm m) sm) manage-vector (fn [ss sm f fl] (let [type- (paradigm-type3 f)] (cond (= type- :us) (let [us ((resolve3 ss :us) :us) sm2 (us ss sm f) lst (second (ffirst sm2))] [(rest fl) ss sm2 lst]) :else (let [ab (abs3 ss sm f)] [(rest fl) ss sm ab])))) manage-map (fn [ss sm f fl] (let [type- (paradigm-type3 f)] (cond (= type- :l) (let [l ((resolve3 ss :l) :l) sm2 (l ss sm f) lst (second (ffirst sm2))] [(rest fl) ss sm2 lst]) (= type- :p) (let [p ((resolve3 ss :p) :p) ss2 (p ss sm f) lst (second (ffirst ss2))] [(rest fl) ss2 sm lst]) :else [(rest fl) ss sm (abs3 ss sm f)] #_:else #_(throw (Exception. (str "The handler for :^t[] is not handler for this type of map ^" (meta f) f))) )))] (loop [fl f ss ss sm sm last- nil] (if (first fl) (let [f (first fl) cond-f (cond (or (symbol? f) (keyword? f)) (let [res (resolve3 sm f) ;fr (f res) #_cond-fr #_(if res (cond (vector? fr) (manage-vector sm fr fl) (map? fr) (manage-map sm fr fl) :else [(rest fl) sm fr]) [(rest fl) sm f]) ]#_cond-fr [(rest fl) ss sm (f res)]) (vector? f) (manage-vector ss sm f fl) (map? f) (manage-map ss sm f fl) :else [(rest fl) ss sm f]) ](recur (nth cond-f 0) (nth cond-f 1) (nth cond-f 2) (nth cond-f 3))) last-)))) (defn if3 [ss sm v] (let [fi (first v) type- (if (map? fi) (paradigm-type3 fi) nil) l (if (= type- :l) ((resolve3 ss :l) :l) nil) sm2 (if l (l ss sm fi) sm) v- (if l (subvec v 1) v) fapp (fn [v- c sm] (if (or (> 2 c) (< 3 c)) (throw (Exception. (str "if3: WrongNumberOfArguments. " c " arguments passed. Source is ^" (meta v) v))) (let [v0 (v- 0) v1 (v- 1)] (if (vector? v0) (if (abs3 ss sm v0) (if (vector? v1) (abs3 ss sm v1) (transform3 sm v1)) (if (= 3 c) (if (vector? (v- 2)) (abs3 ss sm (v- 2)) (transform3 sm (v- 2))) nil)) (if (transform3 sm v0) (if (vector? v1) (abs3 ss sm v1) (transform3 sm v1)) (if (= 3 c) (if (vector? (v- 2)) (abs3 ss sm (v- 2)) (transform3 sm (v- 2))) nil))))))] (fapp v- (count v-) sm2))) (defn sym3 [ss sm s] (prn 'sym s) (let [r (resolve3 sm s)] (if (nil? r) s (r s)))) (defn use3 [ss sm n] (let [nsp (map #(let [nsp (ns-publics %)](into {} (reverse nsp))) (reverse n))] (concat nsp sm))) (def jr-defaults3 (seq [{:do thread3 :l let3 :s sym3 :c call3 :m map3 :v vector3 :f0 f0-3 :x0 x0-3 :fl flat3 :if if3 :a apply3 :ff flatf0-3 :lp loop3 :rc recur3 :us use3 }])) (def fns { 'if '^:f0[[x y z] ^:if[x y z]] 'new (fn [cl & args](clojure.lang.Reflector/invokeConstructor cl (to-array args)))}) (defn abs3 [ss sm f] ;(prn 'ABS3 f) (let [type- (paradigm-type3 f) res (resolve3 ss type-)] (if (nil? res) (throw (Exception. (str "abs3: UnknownParadigmException ^" (meta f) f))) ((res type-) ss sm f)))) (defn jr3 ([f] (let [nsp (ns-publics 'clojure.core) fns- (merge nsp fns)] (jr3 (seq [fns-]) f))) ([sm f] (let [sm2 (if (seq? sm) sm (if (nil? sm) '() (seq [sm])))] (jr3 jr-defaults3 sm2 f))) ([ss sm f] (abs3 ss sm f))) (defn path-from-ns [ns] (clojure.string/join [(clojure.string/replace (clojure.string/replace (str ns) #"\." "/") #"-" "_") ".junior"])) (defn resource-path-of-ns [ns] (clojure.string/replace-first (str (clojure.java.io/resource (path-from-ns ns))) "file:" "") ) (defn ^{:doc "get File .clj corresponding to the symbol ns"} junior-file [ns] (let [ path (path-from-ns ns) ] (clojure.java.io/as-file (clojure.java.io/resource path)) ) ) (defn- read-one [r] (try (binding [*print-meta* true](let [re (read r) p (prn re)] re)) (catch java.lang.RuntimeException e (if (= "EOF while reading" (.getMessage e)) ::EOF (throw e))))) (defn read-seq-from-file "Reads a sequence of top-level objects in file at path." [path] (with-open [r (java.io.PushbackReader. (clojure.java.io/reader path))] (binding [*read-eval* false] (doall (take-while #(not= ::EOF %) (repeatedly #(read-one r))))))) (defn load-junior [ns] (slurp (resource-path-of-ns ns))) (defn read-junior [ns] (read-string (load-junior ns))) (jr3 '^:do[^:us[junior.core]{:b 1 :a :c}])
36891
(ns junior.core) (defmacro ?else [x else] `(if ~x ~x ~else)) (defn !nil? [x] (not (nil? x))) (defmacro !nil?else [x else] `(if (!nil? ~x) ~x ~else)) (defmacro if= [x y then else] `(if (= ~x ~y) ~then ~else)) (defn ^{:doc "Creates a MapEntry"} map-entry ([x y] (map-entry [x y]))([coll] (if= 2 (count coll) (clojure.lang.MapEntry. (first coll) (second coll)) (throw (Exception. "CardinallityException in map-entry: Wrong number of elements in collection, must be of size 2"))))) (defn append [coll x] (if (or (seq? coll) (list? coll)) (apply conj (conj (empty coll) x) (reverse coll)) (conj coll x))) (defn ^{:doc "Like clojure.walk/walk but preserves metadata on lists. Traverses form, an arbitrary data structure. inner and outer are functions. Applies inner to each element of form, building up a data structure of the same type, then applies outer to the result. Recognizes all Clojure data structures. Consumes seqs as with doall. NOTE: This code was forked from https://github.com/clojure/clojure/blob/master/src/clj/clojure/walk.clj commit 2224dba"} walk4pre [inner outer form] (cond (list? form) (with-meta (outer (apply list (map inner form) )) (meta form)) ;(list? form) (outer (apply list (map inner form) )) (instance? clojure.lang.IMapEntry form) (outer (map-entry (map inner form))) (seq? form) (outer (doall (map inner form))) (instance? clojure.lang.IRecord form) (outer (reduce (fn [r x] (conj r (inner x))) form form)) (coll? form) (outer (into (empty form) (map inner form))) :else (outer form))) (defn ^{:doc "Like clojure.walk/prewalk but preserves metadata on lists. Like postwalk, but does pre-order traversal. NOTE: This code was forked from https://github.com/clojure/clojure/blob/master/src/clj/clojure/walk.clj commit 2224dba"} prewalk [f form] (walk4pre (partial prewalk f) identity (f form))) (defn ^{:doc "Like clojure.walk/walk but also takes the map-entry intead of vec in the IMapEntry cond. Traverses form, an arbitrary data structure. inner and outer are functions. Applies inner to each element of form, building up a data structure of the same type, then applies outer to the result. Recognizes all Clojure data structures. Consumes seqs as with doall. NOTE: This code was forked from https://github.com/clojure/clojure/blob/master/src/clj/clojure/walk.clj commit 2224dba"} walk4post [inner outer form] (cond (list? form) (outer (apply list (map inner form) )) (instance? clojure.lang.IMapEntry form) (outer (map-entry (map inner form))) (seq? form) (outer (doall (map inner form))) (instance? clojure.lang.IRecord form) (outer (reduce (fn [r x] (conj r (inner x))) form form)) (coll? form) (outer (into (empty form) (map inner form))) :else (outer form))) (defn postwalk "Performs a depth-first, post-order traversal of form. Calls f on each sub-form, uses f's return value in place of the original. Recognizes all Clojure data structures. Consumes seqs as with doall." {:added "1.1"} [f form] (walk4post (partial postwalk f) f form)) (defn do0 [& c] (last (map #(apply (first %) (next %)) c))) (defn transform0 [m x] (if (coll? x) (walk4pre #(!nil?else (m %) %) identity x) (!nil?else (m x) x)) ) (defn flat0 [m c] (loop [in- c out- (empty c)] (let [f (first in-) tr (transform0 m f)] (if (!nil? tr) (recur (next in-) (apply conj out- (if (list? tr) tr [tr]))) out-)))) (defn ^{:doc " Deprecated. If f is a symbol returns (map- f) if not nil, else f If f is a vector with count > 1, if not nil apply'es (map- f) to (next f), else f. Otherwise returns the map of the first f if not nil, else f. Usage: (abstract {'plus +} ['plus 1 2]) ;=> 3 ((abstract {'plus +} ['plus]) 1 2) ;=> 3 ((abstract {'plus +} 'plus) 1 2) ;=> 3"} abs0- [map- f] (cond (not (coll? f)) (!nil?else (map- f) f) (!nil? (map- (first f))) (if (next f) (if (and (meta (second f)) (:abs-args (meta (second f)))) (apply (map- (first f)) (into (second f) (walk4pre #(!nil?else (map- %) %) identity (next (next f))))) (apply (map- (first f)) (walk4pre #(!nil?else (map- %) %) identity (next f)))) ((map- (first f)))) :else (if (next f) (if (and (meta (second f)) (:abs-args (meta (second f)))) (apply (first f) (into (second f) (walk4pre #(!nil?else (map- %) %) identity (next (next f))))) (apply (first f) (walk4pre #(!nil?else (map- %) %) identity (next f)))) ((first f))))) (defn ^{:doc "basic features: (abs0 {the map} ['(args to flatten) 'arg1 'arg2 '(more args)]) no nested vectors. (abs0 {'s str 'a \"a\" 'b :b 'c 'c 'd '(\"d\" {\"e\" \"f\"})} ['(s a) '(b c) 'd]) ;=> a:bcd{\"e\" \"f\"}"} abs0 [m f] (let [fl (flat0 m f)](apply (first fl) (next fl)))) (defn ^{:doc "postwalks f applying abs0 to each vector"} fabs0 [map- & f] ;(prn f) (last (map #(postwalk (fn [x] (if (and (coll? x) (and (not (map-entry? x)) (not (map? x)))) (abs0 map- x) x)) %) f)) ) (defn resolve1 [sm x] ;(prn (type x) x) (loop [sm sm] (if (first sm) (if (map-entry? x) (if (!nil? ((first sm) (second x))) (map-entry (first x) ((first sm) (second x))) (recur (next sm))) (!nil?else ((first sm) x) (recur (next sm)))) nil))) (defn transform1 [sm x] (if (coll? x) (walk4pre #(!nil?else (resolve1 sm %) %) identity x) (!nil?else (resolve1 sm x) x)) ) (defn flat1 [sm c] (loop [in- c out- []] (let [f (first in-) vec? (vector? f) tr (if vec? nil (transform1 sm f))] (if vec? (recur (rest in-) (apply conj out- [f])) (if (!nil? tr) (do (prn 'tr '_ tr (type tr))(recur (rest in-) (apply conj out- (if (or (list? tr) (instance? clojure.lang.LazySeq tr)) (into [] tr) [tr])))) out-))))) (declare abs1) (defn apply1 [sm f] (prn "sm " sm) (prn "f " f) (apply (if (symbol? (first f)) (resolve (first f)) (first f)) (map #(if (vector? %) (abs1 sm %) %) (rest f))) ) (defn ^{:doc "like abs0 but accepts deep nested vectors. the map can be optionally the first argument. If the first argument points to a map, then its appended to the map chain. There is a map chain, a sequence like ({last map} {older map}...). (abs1 (seq [{:a +}]) [+ 2 [{:a 1 :b 2} + :a :b]]) ;=> 5 (abs1 (seq [{:a {:b + :c '(1 1)} :b +}]) [:a :b :c]) ;=> 2"} abs1 ([f] (abs1 {} f))([sm f] (let [m (if (map? (first f)) (first f)) mr (if m (transform1 sm m)) sm2 (if m (cons mr sm) sm) fl (if m (flat1 sm2 (rest f)) (flat1 sm2 f)) m2 (if (map? (first fl)) (first fl)) mr2 (if m2 (transform1 sm2 m2)) sm3 (if m2 (cons mr2 sm2) sm2) fl2 (if m2 (flat1 sm3 (rest fl)) (flat1 sm3 fl))] ;(prn fl2) (apply1 sm3 fl2)))) (defn literal? [x] (or (instance? clojure.lang.Keyword x) (instance? java.lang.Integer x) (instance? java.lang.Boolean x) (instance? java.lang.String x) (instance? java.lang.Long x) (instance? java.lang.Float x) (instance? java.lang.Character x) (instance? java.lang.Double x) (instance? java.lang.Byte x) (instance? java.lang.Short x) (instance? java.math.BigInteger x) (instance? java.math.BigDecimal x) (instance? clojure.lang.Ratio x))) (defn vector-type2 [v] (let [m (meta v)] (cond (nil? m) :c (:abs m) (if (keyword? (:abs m)) (:abs m) (throw (Exception. (str "NotKeywordException. vector-type: ^" m v " :abs meta key must map to a keyword. Ex. {:abs :some-vector-handler}, in this case you have to have a function like (defn some-vector-handler [sm f]...).")))) (> (count m) 1) (throw (Exception. (str "UndecidableException. vector-type: ^" m v " has more than one meta key."))) :else (key (first m))))) (defn map-type2 [v] (let [m (meta v)] (cond (nil? m) :l (:abs m) (if (keyword? (:abs m)) (:abs m) (throw (Exception. (str "NotKeywordException. map-type: ^" m v " :abs meta key must map to a keyword.")))) (> (count m) 1) (throw (Exception. (str "UndecidableException. map-type: ^" m v " has more than one meta key."))) :else (key (first m))))) (defn ^{:doc "resolves the var in the name of keyword k. Ex :str -> #'clojure.core/str"} resolve-keyword [k] (resolve (symbol (name k)))) (defn single-meta-key-resolve [f] (let [m (meta f) abs (if m (:abs m) nil) m2 (if abs (map-entry abs true) (if (> (count m) 1) nil;(throw (Exception. (str "single-meta-key-resolve " f " has more than one meta key. " m))) (first m))) ;pp (if (> (count m) 1) (throw (Exception. (str "single-meta-key-resolve " f " has more than one meta key. " m)))) ;fi (first (meta f)) ] (if m2 (resolve (symbol (subs (str (key m2)) 1))) nil) )) (declare transform2) (defn m [sm mp] ;(prn mp) (transform2 sm mp) ) (defn v [sm v] (transform2 sm v) ) (declare resolve2) (defn transform2 [sm x] ;(prn 'sm sm) (prn 'transforming x) (if (coll? x) #_(postwalk #(if (coll? %) % (let [res (resolve2 sm %)] (if res (res %) %))) x) (postwalk #(let [res (resolve2 sm %)] (if res (res %) %)) x) (let [res (resolve2 sm x)] (if (!nil? res) (res x) x))) ) (declare abs2) (defn ^{:doc "Named transformlet2."} l [sm m] ;(prn m) (loop [sm sm m m] (let [f (first m) ff (first f) fv (if (vector? ff) (abs2 sm ff) ff)] (if f (let [sec (second f)] (cond (vector? sec) (let [abs (abs2 sm (second f)) sm2 (cons {fv abs} sm)] (recur sm2 (rest m))) (map? sec) (let [sr (single-meta-key-resolve sec)] (if sr (let [sr-res (sr sm sec) sm2 (cons {fv sr-res} sm)] (recur sm2 (rest m))) (let [tr (transform2 sm sec) sm2 (cons {fv tr} sm)] (recur sm2 (rest m))))) (or (keyword? sec) (symbol? sec)) (let [res (resolve2 sm sec) sec-res (if res (sec res) sec) sm2 (cons {fv sec-res} sm)] (recur sm2 (rest m))) :else (let [tr (transform2 sm sec) sm2 (cons {fv tr} sm)] (recur sm2 (rest m))))) sm)))) (defn sm-add2 [sm m] (apply conj [m] sm) ) (defn flat2 [sm c] (loop [in- c out- (empty c)] (if (!nil? (first in-)) (let [f (first in-) tr (if (or (list? f) (instance? clojure.lang.LazySeq f)) (into [] f) [f])] (recur (rest in-) (apply conj out- tr))) out-))) (defn resolve2 [sm x] (loop [sm sm] (if (first sm) (if (map-entry? x) (if (!nil? ((first sm) (second x))) (map-entry (first x) ((first sm) (second x))) (recur (rest sm))) (if (!nil? ((first sm) x)) {x ((first sm) x)} (recur (rest sm)))) nil))) (defn apply2 [sm f] (let [;fapp (resolve2 sm f) tr (transform2 sm f)] ;(prn 'trd (type tr) tr #_(apply (first f) (rest f))) (apply (first tr) (rest tr))) ) #_(defn apply2 [sm f s] (let [fapp (resolve2 sm f) tr (transform2 sm s)] (prn 'trd (type tr) tr (apply fapp tr)) (apply fapp tr)) ) (defn ^{:doc "Named call2"} c [sm f] (loop [sm sm f- f last- nil] (let [fi (first f-)] (if (!nil? fi) (cond (map? fi)(let [sr (single-meta-key-resolve fi) tr (!nil?else sr l) sm2 (tr sm fi)] (recur sm2 (rest f-) (second (ffirst sm2)))) (vector? fi) (if (!nil? (next f-)) (let [app (apply2 sm (cons (second f-) fi))] app) (throw (Exception. (str "No function to apply to " fi ":" f)))) (or (symbol? fi) (keyword? fi)) (apply2 sm f-) :esle (apply2 sm f-)) last-)))) (defn ^{:doc "Main vector handler. Redirects the thread for ^:*[] vectors. Every handler should redirect to abs2 when unknown vector. Vector knowledges: ^:do[] - main thread. [] or ^:c[] - main call. "} abs2 ([f] (abs2 {} f))([sm f] (let [type- (vector-type2 f) ;the-meta (first (meta f)) #_type- #_(if the-meta (if= (key the-meta) :do :thread (single-meta-key-resolve f)) c) ;;pp (println type- 'f f 'sm sm) ] (cond (= :do type-) (let [;fl (flat2 sm f) ;m (if (map? (first fl)) (first fl)) ;sm2 (if m (l sm m) sm) manage-vector (fn [sm f fl] (let [ab (abs2 sm f)] [(rest fl) sm ab])) manage-map (fn [sm f fl] (let [type- (map-type2 f) ;sr (single-meta-key-resolve f) ;tr (!nil?else sr #'littlejr.core/l) ] (cond (= type- :l) (let [sm2 (l sm f) lst (second (ffirst sm2))] [(rest fl) sm2 lst]) :else [(rest fl) sm (transform2 sm f)] #_:else #_(throw (Exception. (str "The handler for :^t[] is not handler for this type of map ^" (meta f) f))))))] (loop [fl f sm sm last- nil] (if (first fl) (let [f (first fl) cond-f (cond (or (symbol? f) (keyword? f)) (let [res (resolve2 sm f) ;fr (f res) #_cond-fr #_(if res (cond (vector? fr) (manage-vector sm fr fl) (map? fr) (manage-map sm fr fl) :else [(rest fl) sm fr]) [(rest fl) sm f]) ]#_cond-fr [(rest fl) sm (f res)]) (vector? f) (manage-vector sm f fl) (map? f) (manage-map sm f fl) :else [(rest fl) sm f]) ](recur (nth cond-f 0) (nth cond-f 1) (nth cond-f 2))) last-))) (= :c type-) (c sm f) :else (let [res (resolve-keyword type-)] (if res (res sm f) (throw (Exception. (str "Don't know what to do with directive " type- ". It must resolve to function " (name type-) ", but couldn't resolve it. Source is ^" (meta f) f "."))))))))) #_(defn fnl3 ([] (fnl3 nil nil nil))([ss sm f] {:let {:l true} :mskip {:fn true}})) #_(defn walkfn3 [sm kp form] (cond (list? form) ;(with-meta (outer (apply list (map inner form))) (meta form)) (with-meta (apply list (map #(walkfn3 sm kp %) form))) (meta form) ;(list? form) (outer (apply list (map inner form) )) (instance? clojure.lang.IMapEntry form) (map-entry (map #(walkfn3 sm kp %) form)) (seq? form) (doall (map #(walkfn3 sm kp %) form)) ;(instance? clojure.lang.IRecord form) ; (reduce (fn [r x] (conj r (f x))) form form) (map? form) (if ((kp :let) (paradigm-type3 form)) (let [ks (keys form) except (kp :except) kp2 (conj kp {:except (apply conj ks except)})] (into (empty form) (map (fn [me] (map-entry (first me) (walkfn3 f (second me) kp2))) form))) (if ((kp :mskip) (paradigm-type3 form)) form (into (empty form) (map #(walkfn3 sm kp %) form)))) (vector? form) (let [para (paradigm-type3 form)] (if ((kp :fn) para) (let [par]) ()) (coll? form) (do (prn 'map) (outer (into (empty form) (map inner form)))) :else (outer form)))) #_(defn ^{:doc "Like clojure.walk/prewalk but preserves metadata on lists. Like postwalk, but does pre-order traversal. NOTE: This code was forked from https://github.com/clojure/clojure/blob/master/src/clj/clojure/walk.clj commit 22<PASSWORD>dba"} prewalkfn3 [ss sm f] (walkfn3 sm (fnl3) f)) (defn paradigm-type3 [f] (let [m (meta f)] (cond (nil? m) (if (vector? f) :c (if (map? f) :l :s #_(throw (Exception. (str "paradigm-type3: NoMetaException. ^nil " f " meta is nil. Can't handle empty paradigm"))))) (:jr m) (if (keyword? (:jr m)) (:jr m) (throw (Exception. (str "paradigm-type3: NotKeywordException. :jr meta key must map to a keyword. Ex. {:jr :some-vector-handler}, in this case you have to have a function like (defn some-vector-handler [ss sm f]...). Source is ^" (meta f) f)))) (> (count m) 1) (throw (Exception. (str "paradigm-type3: UndecidableException. More than one meta key. Source is ^" (meta f) f))) :else (key (first m))))) (defn resolve3 ([sm x] ;(prn 'RESOLVE-sm sm) ;(prn 'RESOLVE-x x) (loop [sm sm] (if (first sm) #_(if (map-entry? x) (if (!nil? ((first sm) (second x))) (map-entry (first x) ((first sm) (second x))) (recur (rest sm)))) (if (contains? (first sm) x) {x ((first sm) x)} (recur (rest sm))) nil))) ([sm x s] (if (contains? (into #{} s) x) {x x} (resolve sm x)))) (defn resolve-back3 ([sm x] (resolve3 sm x)) ([level sm x] #_(prn 'resolve-back sm x) (loop [l 0 res x last x] (if (or (nil? res) (> l level)) {x last} (let [r (resolve3 sm res) rs (if (nil? r) nil (r res)) lst (if (nil? r) last (r res))] (recur (inc l) rs lst))))) ([level sm x s](if (contains? (into #{} s) x) {x x} (resolve-back3 level sm x)))) (defn defined? [ss sm x]) (def transform-paradigm3 { ;^:pre:sym-key:0([](fn [sm x] (prewalk #(if (or (symbol? %)(keyword? %)) (let [res (resolve3 sm %)] (if res (res %) %)) %) x))) ;(fn [sm x except] (prewalkfn3 (f :let) #(if (and (or (symbol? %) (keyword? %)) (not (contains? except %))) (let [res (resolve3 sm %)] (if res (res %) %)) %) x)) :pre:sym-key:0:except (fn [sm x except] (prewalk #(if (and (or (symbol? %) (keyword? %)) (not (contains? except %))) (let [res (resolve3 sm %)] (if res (res %) %)) %) x)) :pre:sym-key:0 (fn [sm x] (prewalk #(if (or (symbol? %)(keyword? %)) (let [res (resolve3 sm %)] (if res (res %) %)) %) x)) :pos:sym-key:0 (fn [sm x] (postwalk #(if (or (symbol? %)(keyword? %)) (let [res (resolve3 sm %)] (if res (res %) %)) %) x)) :pre:sym:0 (fn [sm x] (prewalk #(if (symbol? %) (let [res (resolve3 sm %)] (if res (res %) %)) %) x)) :pos:sym:0 (fn [sm x] (postwalk #(if (symbol? %) (let [res (resolve3 sm %)] (if res (res %) %)) %) x)) :pre:key:0 (fn [sm x] (prewalk #(if (keyword? %) (let [res (resolve3 sm %)] (if res (res %) %)) %) x)) :pre:all:0 (fn [sm x] (prewalk #(let [res (resolve3 sm %)] (if res (res %) %)) x)) :pre:all:1 (fn [sm x] (prewalk #(let [res (resolve-back3 1 sm %)] (if res (res %) %)) x)) :pos:all:0 (fn [sm x] (postwalk #(let [res (resolve3 sm %)] (if res (res %) %)) x)) :pos:all:1 (fn [sm x] (postwalk #(let [res (resolve-back3 1 sm %)] (if res (res %) %)) x))}) (declare abs3) (declare f0-3) (defn transform3 ([sm x] (transform3 sm x :pos:sym:0)) ([sm x par] (transform3 sm x par nil)) ([sm x par except] ;#_(prn 'TRANSFORM3-PAR par) ;#_(prn 'TRANSFORM3-X x) (let [para (transform-paradigm3 par)] (if para (if except (para sm x (into #{} except)) (do #_(prn 'TRANSFORM-PARA (para sm x))(para sm x))) (throw (Exception. (str "transform3: UnknownTransformationParadigm " par " for " x))))))) (defn vector3 [ss sm v] (into (empty v) (map (partial abs3 ss sm) v)) ) (defn map3 [ss sm m] (let [ks (keys m) vs (vals m) nks (map (partial abs3 ss sm) ks) nvs (map (partial abs3 ss sm) vs)] (apply assoc {} (interleave nks nvs))) ) (defn midentity3 [v] (if (empty? v) {} (apply assoc {} (interleave v v)))) (defn apply3 [ss sm f] ;(prn 'apply3-IN "^" (meta f) f) (if (map? (first f)) (let [fi (first f) vs (into [] (rest f)) type- (paradigm-type3 fi)] (if (= :x0 type-) (let [ks (fi :args) cntks (count ks) cntvs (count vs) n (- cntks cntvs) zm (if (> n 0) (zipmap ks (apply conj vs (vec (replicate n nil)))) (zipmap ks vs))] #_(prn 'n n 'APPLY3-zm(zipmap ks (apply conj vs (vec (replicate n nil))))) #_(prn 'apply3-OUT ^:do[zm (fi :f)]) (abs3 ss sm ^:do[zm (fi :f)])) (throw (Exception. (str "apply3: UnknownParadigmException. Can't handle this kind of map ^" (meta fi) fi ". Source is ^"(meta f) f))))) (let [;fapp (resolve2 sm f) tr (transform3 sm f) fi (first tr)] ;(prn 'trd (type tr) tr #_(apply (first f) (rest f))) (if (and (or (symbol? fi) (keyword? fi)) (not (map? (second tr)))) (throw (Exception. (str "apply3: NoMapForSymbolAsFunctionException. Source is: ^"(meta f) f))) (apply fi (rest tr))))) ) (defn flat3 [ss sm f] #_(prn 'FLAT3-SM sm) #_(prn 'FLAT3-F f) (loop [ss ss sm sm f f ef (empty f)] (let [fi (first f)] (if (!nil? fi) (cond (map? fi)(let [type- (paradigm-type3 fi) #_pp #_(prn 'FLAT3-PARADIGM type- fi)] (cond ;(= :fn type-) (recur ss sm (rest f) (conj ef fi)) (= :l type-) (let [l ((resolve3 ss :l) :l) sm2 (l ss sm fi) ] (recur ss sm2 (rest f) ef)) ; :else (recur ss sm (rest f) (conj ef fi)))) (vector? fi) (let [abs (abs3 ss sm fi)] (recur ss sm (rest f) (conj ef abs))) :else (let [tr (transform3 sm fi)] (recur ss sm (rest f) (conj ef tr)))) ef)))) (defn ^{:doc "This paradigm is more or less clojure like"} call3 [ss sm f] (let [;pp (prn 'call3-TOFLAT "^" (meta f) f) fl (flat3 ss sm f) fi (first fl) ;pp (prn 'call3-FLATTED "^" (meta fl) fl) ] (if (> (count fl) 1) (if (!nil? fi) (if (or (vector? fi) (seq? fi) (list? fi)) (if (!nil? (next fl)) (let [app (apply3 ss sm (concat (rest fl) fi))] app) (throw (Exception. (str "call3: MalformedStructure. No function to apply to " fi ": " f)))) (apply3 ss sm fl)) (throw (Exception. (str "call3: NilFunctionException. No function to apply. " (first f) " was nil. Source is " f)))) (fi)))) (defn flatf0-3 [ss sm f] ;(prn 'flatf0-3 f) (if (coll? f) (loop [ss ss sm sm f- f ef (empty f)] (let [fi (first f-) #_pp #_(prn 'flatf0-3-f-ef f- ef)] (if (!nil? fi) (cond (map? fi)(let [type- (paradigm-type3 fi)] (cond (= :l type-) (letfn [(lp [sm ks result] (if ks (let [k (first ks) sm2 (cons {k k} sm) fik (fi k) fn- (if (coll? fik) (if (= :f0 (paradigm-type3 fik)) (f0-3 ss sm2 fik) (flatf0-3 ss sm2 fik)) (transform3 sm2 fik))] #_(prn 'lp-fn- fn-) (lp sm2 (next ks) (conj result {k fn-}))) {:sm sm :result result}))] (let [lp- (lp sm (keys fi) (empty fi))] (recur ss (lp- :sm) (rest f-) (append ef (lp- :result))))) :else (recur ss sm (rest f-) (append ef fi)))) (vector? fi) (let [type- (paradigm-type3 fi)] (cond (= :f0 type-) (let [id (midentity3 (first fi)) sm2 (cons id sm) fn- (f0-3 ss sm2 fi) ef- (append ef fn-)] (recur ss sm2 (rest f-) ef-)) :else (let [tr (flatf0-3 ss sm fi) ef- (append ef tr)] (recur ss sm (rest f-) ef-)))) #_(let [fl (flatf0-3 ss sm fi)] (recur ss sm (rest f) (conj ef fl))) :else (let [tr (transform3 sm fi)] ;(prn 'FLATY3-else ef tr) (recur ss sm (rest f-) (append ef tr)))) (do #_(prn 'ef ef) ef)))) f)) (defn x0-3 [ss sm f] f) (defn f0-3 [ss sm v] #_(prn 'f0-3 v) (let [fapp (fn [sm v-] (if (vector? (v- 0)) (let [argl (v- 0) idn (midentity3 argl) sm2 (if (empty? idn) sm (cons idn sm)) tra (into ^:c[] (flatf0-3 ss sm2 (rest v-))) ] ^:x0{:f tra :args (v- 0) :src v} ) (let [tra (into ^:c[] (flatf0-3 ss sm v-))] ^:x0{:f tra :args [] :src v})))] (fapp sm v))) #_(defn f1-3 [ss sm v] #_(prn 'f0-3 v) (let [fapp (fn [sm v-] (if (vector? (v- 0)) (let [argl (v- 0) idn (midentity3 argl) sm2 (if (empty? idn) sm (cons idn sm)) tra (into ^:c[] (flatf1-3 ss sm2 (rest v-))) ] ^:x0{:f tra :args (v- 0) :src v} ) (let [tra (into ^:c[] (flatf1-3 ss sm v-))] ^:x0{:f tra :args [] :src v})))] (fapp sm v))) (defn recur3 [ss sm f] #_(prn 'RECUR-ms sm) #_(prn 'RECUR-f f) (into (empty f) (map (partial abs3 ss sm) f))) (defn loop3 [ss sm f] (let [fi (first f)] (if (map? fi) (let [vec- (into ^:v[] (keys fi)) fndef (apply conj ^:f0[vec-] (rest f)) floop (f0-3 ss sm fndef) init (into ^:v[] (vals fi)) ;pp (prn 'LOOP3-fndef fndef) ;pp (prn 'LOOP3-floop floop) ] (loop [i init] (let [abs (call3 ss sm [i floop]) type- (if (meta abs) (paradigm-type3 abs) nil) ;pp (prn 'LOOP3-abs abs) ] (if (= :rc type-) (do #_(prn 'LOOP3-recur "^" (meta abs) abs)(recur abs)) abs)))) (throw (Exception. (str "loop3: MalformedStructureException. First element must be a map. Source is ^" (meta f) f))))) ) (defn ^{:doc "This paradigm is more or less clojure like"} call3- [ss sm f] (loop [sm sm f- f last- nil] (let [fi (first f-)] (if (!nil? fi) (cond (map? fi)(let [type- (paradigm-type3 fi)] (if= type- :l (let [l ((resolve3 ss :l) :l) sm2 (l ss sm fi)] (recur sm2 (rest f-) (second (ffirst sm2)))) (throw (Exception. (str "call3: UnknownParadigmException. call3 can't handle this paradigm ^" (meta fi) fi))))) (vector? fi) (if (!nil? (next f-)) (let [app (apply3 sm (concat (rest f-) fi))] app) (throw (Exception. (str "call3: MalformedStructure. No function to apply to " fi ": " f)))) ;(or (symbol? fi) (keyword? fi)) (apply3 sm f-) :esle (let [r (resolve3 sm fi)] (if (!nil? r) (if (vector? (r fi)) (if (!nil? (next f-)) (let [app (apply3 sm (concat (rest f-) (r fi)))] app) (throw (Exception. (str "call3: MalformedStructure. No function to apply to " fi ":" f)))) (apply3 sm (cons (r fi) (rest f-)))) (apply3 sm f-)))) last-)))) (defn ^{:doc "Named transformlet2."} let3 [ss sm m] ;(prn m) (loop [sm sm m m] (let [f (first m) ff (first f) fv (if (vector? ff) (abs3 ss sm ff) ff)] (if f (let [sec (second f)] (if (or (map? sec) (vector? sec)) (if (and (map? sec) (= :l (paradigm-type3 sec))) (let [abs (abs3 ss sm ^:do[sec]) sm2 (cons {fv abs} sm)] (recur sm2 (rest m))) (let [abs (abs3 ss sm sec) sm2 (cons {fv abs} sm)] (recur sm2 (rest m)))) (let [res (resolve3 sm sec) sec-res (if res (sec res) sec) sm2 (cons {fv sec-res} sm)] (recur sm2 (rest m))))) sm)))) (defn thread3 [ss sm f] (let [;fl (flat2 sm f) ;m (if (map? (first fl)) (first fl)) ;sm2 (if m (l sm m) sm) manage-vector (fn [ss sm f fl] (let [type- (paradigm-type3 f)] (cond (= type- :us) (let [us ((resolve3 ss :us) :us) sm2 (us ss sm f) lst (second (ffirst sm2))] [(rest fl) ss sm2 lst]) :else (let [ab (abs3 ss sm f)] [(rest fl) ss sm ab])))) manage-map (fn [ss sm f fl] (let [type- (paradigm-type3 f)] (cond (= type- :l) (let [l ((resolve3 ss :l) :l) sm2 (l ss sm f) lst (second (ffirst sm2))] [(rest fl) ss sm2 lst]) (= type- :p) (let [p ((resolve3 ss :p) :p) ss2 (p ss sm f) lst (second (ffirst ss2))] [(rest fl) ss2 sm lst]) :else [(rest fl) ss sm (abs3 ss sm f)] #_:else #_(throw (Exception. (str "The handler for :^t[] is not handler for this type of map ^" (meta f) f))) )))] (loop [fl f ss ss sm sm last- nil] (if (first fl) (let [f (first fl) cond-f (cond (or (symbol? f) (keyword? f)) (let [res (resolve3 sm f) ;fr (f res) #_cond-fr #_(if res (cond (vector? fr) (manage-vector sm fr fl) (map? fr) (manage-map sm fr fl) :else [(rest fl) sm fr]) [(rest fl) sm f]) ]#_cond-fr [(rest fl) ss sm (f res)]) (vector? f) (manage-vector ss sm f fl) (map? f) (manage-map ss sm f fl) :else [(rest fl) ss sm f]) ](recur (nth cond-f 0) (nth cond-f 1) (nth cond-f 2) (nth cond-f 3))) last-)))) (defn if3 [ss sm v] (let [fi (first v) type- (if (map? fi) (paradigm-type3 fi) nil) l (if (= type- :l) ((resolve3 ss :l) :l) nil) sm2 (if l (l ss sm fi) sm) v- (if l (subvec v 1) v) fapp (fn [v- c sm] (if (or (> 2 c) (< 3 c)) (throw (Exception. (str "if3: WrongNumberOfArguments. " c " arguments passed. Source is ^" (meta v) v))) (let [v0 (v- 0) v1 (v- 1)] (if (vector? v0) (if (abs3 ss sm v0) (if (vector? v1) (abs3 ss sm v1) (transform3 sm v1)) (if (= 3 c) (if (vector? (v- 2)) (abs3 ss sm (v- 2)) (transform3 sm (v- 2))) nil)) (if (transform3 sm v0) (if (vector? v1) (abs3 ss sm v1) (transform3 sm v1)) (if (= 3 c) (if (vector? (v- 2)) (abs3 ss sm (v- 2)) (transform3 sm (v- 2))) nil))))))] (fapp v- (count v-) sm2))) (defn sym3 [ss sm s] (prn 'sym s) (let [r (resolve3 sm s)] (if (nil? r) s (r s)))) (defn use3 [ss sm n] (let [nsp (map #(let [nsp (ns-publics %)](into {} (reverse nsp))) (reverse n))] (concat nsp sm))) (def jr-defaults3 (seq [{:do thread3 :l let3 :s sym3 :c call3 :m map3 :v vector3 :f0 f0-3 :x0 x0-3 :fl flat3 :if if3 :a apply3 :ff flatf0-3 :lp loop3 :rc recur3 :us use3 }])) (def fns { 'if '^:f0[[x y z] ^:if[x y z]] 'new (fn [cl & args](clojure.lang.Reflector/invokeConstructor cl (to-array args)))}) (defn abs3 [ss sm f] ;(prn 'ABS3 f) (let [type- (paradigm-type3 f) res (resolve3 ss type-)] (if (nil? res) (throw (Exception. (str "abs3: UnknownParadigmException ^" (meta f) f))) ((res type-) ss sm f)))) (defn jr3 ([f] (let [nsp (ns-publics 'clojure.core) fns- (merge nsp fns)] (jr3 (seq [fns-]) f))) ([sm f] (let [sm2 (if (seq? sm) sm (if (nil? sm) '() (seq [sm])))] (jr3 jr-defaults3 sm2 f))) ([ss sm f] (abs3 ss sm f))) (defn path-from-ns [ns] (clojure.string/join [(clojure.string/replace (clojure.string/replace (str ns) #"\." "/") #"-" "_") ".junior"])) (defn resource-path-of-ns [ns] (clojure.string/replace-first (str (clojure.java.io/resource (path-from-ns ns))) "file:" "") ) (defn ^{:doc "get File .clj corresponding to the symbol ns"} junior-file [ns] (let [ path (path-from-ns ns) ] (clojure.java.io/as-file (clojure.java.io/resource path)) ) ) (defn- read-one [r] (try (binding [*print-meta* true](let [re (read r) p (prn re)] re)) (catch java.lang.RuntimeException e (if (= "EOF while reading" (.getMessage e)) ::EOF (throw e))))) (defn read-seq-from-file "Reads a sequence of top-level objects in file at path." [path] (with-open [r (java.io.PushbackReader. (clojure.java.io/reader path))] (binding [*read-eval* false] (doall (take-while #(not= ::EOF %) (repeatedly #(read-one r))))))) (defn load-junior [ns] (slurp (resource-path-of-ns ns))) (defn read-junior [ns] (read-string (load-junior ns))) (jr3 '^:do[^:us[junior.core]{:b 1 :a :c}])
true
(ns junior.core) (defmacro ?else [x else] `(if ~x ~x ~else)) (defn !nil? [x] (not (nil? x))) (defmacro !nil?else [x else] `(if (!nil? ~x) ~x ~else)) (defmacro if= [x y then else] `(if (= ~x ~y) ~then ~else)) (defn ^{:doc "Creates a MapEntry"} map-entry ([x y] (map-entry [x y]))([coll] (if= 2 (count coll) (clojure.lang.MapEntry. (first coll) (second coll)) (throw (Exception. "CardinallityException in map-entry: Wrong number of elements in collection, must be of size 2"))))) (defn append [coll x] (if (or (seq? coll) (list? coll)) (apply conj (conj (empty coll) x) (reverse coll)) (conj coll x))) (defn ^{:doc "Like clojure.walk/walk but preserves metadata on lists. Traverses form, an arbitrary data structure. inner and outer are functions. Applies inner to each element of form, building up a data structure of the same type, then applies outer to the result. Recognizes all Clojure data structures. Consumes seqs as with doall. NOTE: This code was forked from https://github.com/clojure/clojure/blob/master/src/clj/clojure/walk.clj commit 2224dba"} walk4pre [inner outer form] (cond (list? form) (with-meta (outer (apply list (map inner form) )) (meta form)) ;(list? form) (outer (apply list (map inner form) )) (instance? clojure.lang.IMapEntry form) (outer (map-entry (map inner form))) (seq? form) (outer (doall (map inner form))) (instance? clojure.lang.IRecord form) (outer (reduce (fn [r x] (conj r (inner x))) form form)) (coll? form) (outer (into (empty form) (map inner form))) :else (outer form))) (defn ^{:doc "Like clojure.walk/prewalk but preserves metadata on lists. Like postwalk, but does pre-order traversal. NOTE: This code was forked from https://github.com/clojure/clojure/blob/master/src/clj/clojure/walk.clj commit 2224dba"} prewalk [f form] (walk4pre (partial prewalk f) identity (f form))) (defn ^{:doc "Like clojure.walk/walk but also takes the map-entry intead of vec in the IMapEntry cond. Traverses form, an arbitrary data structure. inner and outer are functions. Applies inner to each element of form, building up a data structure of the same type, then applies outer to the result. Recognizes all Clojure data structures. Consumes seqs as with doall. NOTE: This code was forked from https://github.com/clojure/clojure/blob/master/src/clj/clojure/walk.clj commit 2224dba"} walk4post [inner outer form] (cond (list? form) (outer (apply list (map inner form) )) (instance? clojure.lang.IMapEntry form) (outer (map-entry (map inner form))) (seq? form) (outer (doall (map inner form))) (instance? clojure.lang.IRecord form) (outer (reduce (fn [r x] (conj r (inner x))) form form)) (coll? form) (outer (into (empty form) (map inner form))) :else (outer form))) (defn postwalk "Performs a depth-first, post-order traversal of form. Calls f on each sub-form, uses f's return value in place of the original. Recognizes all Clojure data structures. Consumes seqs as with doall." {:added "1.1"} [f form] (walk4post (partial postwalk f) f form)) (defn do0 [& c] (last (map #(apply (first %) (next %)) c))) (defn transform0 [m x] (if (coll? x) (walk4pre #(!nil?else (m %) %) identity x) (!nil?else (m x) x)) ) (defn flat0 [m c] (loop [in- c out- (empty c)] (let [f (first in-) tr (transform0 m f)] (if (!nil? tr) (recur (next in-) (apply conj out- (if (list? tr) tr [tr]))) out-)))) (defn ^{:doc " Deprecated. If f is a symbol returns (map- f) if not nil, else f If f is a vector with count > 1, if not nil apply'es (map- f) to (next f), else f. Otherwise returns the map of the first f if not nil, else f. Usage: (abstract {'plus +} ['plus 1 2]) ;=> 3 ((abstract {'plus +} ['plus]) 1 2) ;=> 3 ((abstract {'plus +} 'plus) 1 2) ;=> 3"} abs0- [map- f] (cond (not (coll? f)) (!nil?else (map- f) f) (!nil? (map- (first f))) (if (next f) (if (and (meta (second f)) (:abs-args (meta (second f)))) (apply (map- (first f)) (into (second f) (walk4pre #(!nil?else (map- %) %) identity (next (next f))))) (apply (map- (first f)) (walk4pre #(!nil?else (map- %) %) identity (next f)))) ((map- (first f)))) :else (if (next f) (if (and (meta (second f)) (:abs-args (meta (second f)))) (apply (first f) (into (second f) (walk4pre #(!nil?else (map- %) %) identity (next (next f))))) (apply (first f) (walk4pre #(!nil?else (map- %) %) identity (next f)))) ((first f))))) (defn ^{:doc "basic features: (abs0 {the map} ['(args to flatten) 'arg1 'arg2 '(more args)]) no nested vectors. (abs0 {'s str 'a \"a\" 'b :b 'c 'c 'd '(\"d\" {\"e\" \"f\"})} ['(s a) '(b c) 'd]) ;=> a:bcd{\"e\" \"f\"}"} abs0 [m f] (let [fl (flat0 m f)](apply (first fl) (next fl)))) (defn ^{:doc "postwalks f applying abs0 to each vector"} fabs0 [map- & f] ;(prn f) (last (map #(postwalk (fn [x] (if (and (coll? x) (and (not (map-entry? x)) (not (map? x)))) (abs0 map- x) x)) %) f)) ) (defn resolve1 [sm x] ;(prn (type x) x) (loop [sm sm] (if (first sm) (if (map-entry? x) (if (!nil? ((first sm) (second x))) (map-entry (first x) ((first sm) (second x))) (recur (next sm))) (!nil?else ((first sm) x) (recur (next sm)))) nil))) (defn transform1 [sm x] (if (coll? x) (walk4pre #(!nil?else (resolve1 sm %) %) identity x) (!nil?else (resolve1 sm x) x)) ) (defn flat1 [sm c] (loop [in- c out- []] (let [f (first in-) vec? (vector? f) tr (if vec? nil (transform1 sm f))] (if vec? (recur (rest in-) (apply conj out- [f])) (if (!nil? tr) (do (prn 'tr '_ tr (type tr))(recur (rest in-) (apply conj out- (if (or (list? tr) (instance? clojure.lang.LazySeq tr)) (into [] tr) [tr])))) out-))))) (declare abs1) (defn apply1 [sm f] (prn "sm " sm) (prn "f " f) (apply (if (symbol? (first f)) (resolve (first f)) (first f)) (map #(if (vector? %) (abs1 sm %) %) (rest f))) ) (defn ^{:doc "like abs0 but accepts deep nested vectors. the map can be optionally the first argument. If the first argument points to a map, then its appended to the map chain. There is a map chain, a sequence like ({last map} {older map}...). (abs1 (seq [{:a +}]) [+ 2 [{:a 1 :b 2} + :a :b]]) ;=> 5 (abs1 (seq [{:a {:b + :c '(1 1)} :b +}]) [:a :b :c]) ;=> 2"} abs1 ([f] (abs1 {} f))([sm f] (let [m (if (map? (first f)) (first f)) mr (if m (transform1 sm m)) sm2 (if m (cons mr sm) sm) fl (if m (flat1 sm2 (rest f)) (flat1 sm2 f)) m2 (if (map? (first fl)) (first fl)) mr2 (if m2 (transform1 sm2 m2)) sm3 (if m2 (cons mr2 sm2) sm2) fl2 (if m2 (flat1 sm3 (rest fl)) (flat1 sm3 fl))] ;(prn fl2) (apply1 sm3 fl2)))) (defn literal? [x] (or (instance? clojure.lang.Keyword x) (instance? java.lang.Integer x) (instance? java.lang.Boolean x) (instance? java.lang.String x) (instance? java.lang.Long x) (instance? java.lang.Float x) (instance? java.lang.Character x) (instance? java.lang.Double x) (instance? java.lang.Byte x) (instance? java.lang.Short x) (instance? java.math.BigInteger x) (instance? java.math.BigDecimal x) (instance? clojure.lang.Ratio x))) (defn vector-type2 [v] (let [m (meta v)] (cond (nil? m) :c (:abs m) (if (keyword? (:abs m)) (:abs m) (throw (Exception. (str "NotKeywordException. vector-type: ^" m v " :abs meta key must map to a keyword. Ex. {:abs :some-vector-handler}, in this case you have to have a function like (defn some-vector-handler [sm f]...).")))) (> (count m) 1) (throw (Exception. (str "UndecidableException. vector-type: ^" m v " has more than one meta key."))) :else (key (first m))))) (defn map-type2 [v] (let [m (meta v)] (cond (nil? m) :l (:abs m) (if (keyword? (:abs m)) (:abs m) (throw (Exception. (str "NotKeywordException. map-type: ^" m v " :abs meta key must map to a keyword.")))) (> (count m) 1) (throw (Exception. (str "UndecidableException. map-type: ^" m v " has more than one meta key."))) :else (key (first m))))) (defn ^{:doc "resolves the var in the name of keyword k. Ex :str -> #'clojure.core/str"} resolve-keyword [k] (resolve (symbol (name k)))) (defn single-meta-key-resolve [f] (let [m (meta f) abs (if m (:abs m) nil) m2 (if abs (map-entry abs true) (if (> (count m) 1) nil;(throw (Exception. (str "single-meta-key-resolve " f " has more than one meta key. " m))) (first m))) ;pp (if (> (count m) 1) (throw (Exception. (str "single-meta-key-resolve " f " has more than one meta key. " m)))) ;fi (first (meta f)) ] (if m2 (resolve (symbol (subs (str (key m2)) 1))) nil) )) (declare transform2) (defn m [sm mp] ;(prn mp) (transform2 sm mp) ) (defn v [sm v] (transform2 sm v) ) (declare resolve2) (defn transform2 [sm x] ;(prn 'sm sm) (prn 'transforming x) (if (coll? x) #_(postwalk #(if (coll? %) % (let [res (resolve2 sm %)] (if res (res %) %))) x) (postwalk #(let [res (resolve2 sm %)] (if res (res %) %)) x) (let [res (resolve2 sm x)] (if (!nil? res) (res x) x))) ) (declare abs2) (defn ^{:doc "Named transformlet2."} l [sm m] ;(prn m) (loop [sm sm m m] (let [f (first m) ff (first f) fv (if (vector? ff) (abs2 sm ff) ff)] (if f (let [sec (second f)] (cond (vector? sec) (let [abs (abs2 sm (second f)) sm2 (cons {fv abs} sm)] (recur sm2 (rest m))) (map? sec) (let [sr (single-meta-key-resolve sec)] (if sr (let [sr-res (sr sm sec) sm2 (cons {fv sr-res} sm)] (recur sm2 (rest m))) (let [tr (transform2 sm sec) sm2 (cons {fv tr} sm)] (recur sm2 (rest m))))) (or (keyword? sec) (symbol? sec)) (let [res (resolve2 sm sec) sec-res (if res (sec res) sec) sm2 (cons {fv sec-res} sm)] (recur sm2 (rest m))) :else (let [tr (transform2 sm sec) sm2 (cons {fv tr} sm)] (recur sm2 (rest m))))) sm)))) (defn sm-add2 [sm m] (apply conj [m] sm) ) (defn flat2 [sm c] (loop [in- c out- (empty c)] (if (!nil? (first in-)) (let [f (first in-) tr (if (or (list? f) (instance? clojure.lang.LazySeq f)) (into [] f) [f])] (recur (rest in-) (apply conj out- tr))) out-))) (defn resolve2 [sm x] (loop [sm sm] (if (first sm) (if (map-entry? x) (if (!nil? ((first sm) (second x))) (map-entry (first x) ((first sm) (second x))) (recur (rest sm))) (if (!nil? ((first sm) x)) {x ((first sm) x)} (recur (rest sm)))) nil))) (defn apply2 [sm f] (let [;fapp (resolve2 sm f) tr (transform2 sm f)] ;(prn 'trd (type tr) tr #_(apply (first f) (rest f))) (apply (first tr) (rest tr))) ) #_(defn apply2 [sm f s] (let [fapp (resolve2 sm f) tr (transform2 sm s)] (prn 'trd (type tr) tr (apply fapp tr)) (apply fapp tr)) ) (defn ^{:doc "Named call2"} c [sm f] (loop [sm sm f- f last- nil] (let [fi (first f-)] (if (!nil? fi) (cond (map? fi)(let [sr (single-meta-key-resolve fi) tr (!nil?else sr l) sm2 (tr sm fi)] (recur sm2 (rest f-) (second (ffirst sm2)))) (vector? fi) (if (!nil? (next f-)) (let [app (apply2 sm (cons (second f-) fi))] app) (throw (Exception. (str "No function to apply to " fi ":" f)))) (or (symbol? fi) (keyword? fi)) (apply2 sm f-) :esle (apply2 sm f-)) last-)))) (defn ^{:doc "Main vector handler. Redirects the thread for ^:*[] vectors. Every handler should redirect to abs2 when unknown vector. Vector knowledges: ^:do[] - main thread. [] or ^:c[] - main call. "} abs2 ([f] (abs2 {} f))([sm f] (let [type- (vector-type2 f) ;the-meta (first (meta f)) #_type- #_(if the-meta (if= (key the-meta) :do :thread (single-meta-key-resolve f)) c) ;;pp (println type- 'f f 'sm sm) ] (cond (= :do type-) (let [;fl (flat2 sm f) ;m (if (map? (first fl)) (first fl)) ;sm2 (if m (l sm m) sm) manage-vector (fn [sm f fl] (let [ab (abs2 sm f)] [(rest fl) sm ab])) manage-map (fn [sm f fl] (let [type- (map-type2 f) ;sr (single-meta-key-resolve f) ;tr (!nil?else sr #'littlejr.core/l) ] (cond (= type- :l) (let [sm2 (l sm f) lst (second (ffirst sm2))] [(rest fl) sm2 lst]) :else [(rest fl) sm (transform2 sm f)] #_:else #_(throw (Exception. (str "The handler for :^t[] is not handler for this type of map ^" (meta f) f))))))] (loop [fl f sm sm last- nil] (if (first fl) (let [f (first fl) cond-f (cond (or (symbol? f) (keyword? f)) (let [res (resolve2 sm f) ;fr (f res) #_cond-fr #_(if res (cond (vector? fr) (manage-vector sm fr fl) (map? fr) (manage-map sm fr fl) :else [(rest fl) sm fr]) [(rest fl) sm f]) ]#_cond-fr [(rest fl) sm (f res)]) (vector? f) (manage-vector sm f fl) (map? f) (manage-map sm f fl) :else [(rest fl) sm f]) ](recur (nth cond-f 0) (nth cond-f 1) (nth cond-f 2))) last-))) (= :c type-) (c sm f) :else (let [res (resolve-keyword type-)] (if res (res sm f) (throw (Exception. (str "Don't know what to do with directive " type- ". It must resolve to function " (name type-) ", but couldn't resolve it. Source is ^" (meta f) f "."))))))))) #_(defn fnl3 ([] (fnl3 nil nil nil))([ss sm f] {:let {:l true} :mskip {:fn true}})) #_(defn walkfn3 [sm kp form] (cond (list? form) ;(with-meta (outer (apply list (map inner form))) (meta form)) (with-meta (apply list (map #(walkfn3 sm kp %) form))) (meta form) ;(list? form) (outer (apply list (map inner form) )) (instance? clojure.lang.IMapEntry form) (map-entry (map #(walkfn3 sm kp %) form)) (seq? form) (doall (map #(walkfn3 sm kp %) form)) ;(instance? clojure.lang.IRecord form) ; (reduce (fn [r x] (conj r (f x))) form form) (map? form) (if ((kp :let) (paradigm-type3 form)) (let [ks (keys form) except (kp :except) kp2 (conj kp {:except (apply conj ks except)})] (into (empty form) (map (fn [me] (map-entry (first me) (walkfn3 f (second me) kp2))) form))) (if ((kp :mskip) (paradigm-type3 form)) form (into (empty form) (map #(walkfn3 sm kp %) form)))) (vector? form) (let [para (paradigm-type3 form)] (if ((kp :fn) para) (let [par]) ()) (coll? form) (do (prn 'map) (outer (into (empty form) (map inner form)))) :else (outer form)))) #_(defn ^{:doc "Like clojure.walk/prewalk but preserves metadata on lists. Like postwalk, but does pre-order traversal. NOTE: This code was forked from https://github.com/clojure/clojure/blob/master/src/clj/clojure/walk.clj commit 22PI:PASSWORD:<PASSWORD>END_PIdba"} prewalkfn3 [ss sm f] (walkfn3 sm (fnl3) f)) (defn paradigm-type3 [f] (let [m (meta f)] (cond (nil? m) (if (vector? f) :c (if (map? f) :l :s #_(throw (Exception. (str "paradigm-type3: NoMetaException. ^nil " f " meta is nil. Can't handle empty paradigm"))))) (:jr m) (if (keyword? (:jr m)) (:jr m) (throw (Exception. (str "paradigm-type3: NotKeywordException. :jr meta key must map to a keyword. Ex. {:jr :some-vector-handler}, in this case you have to have a function like (defn some-vector-handler [ss sm f]...). Source is ^" (meta f) f)))) (> (count m) 1) (throw (Exception. (str "paradigm-type3: UndecidableException. More than one meta key. Source is ^" (meta f) f))) :else (key (first m))))) (defn resolve3 ([sm x] ;(prn 'RESOLVE-sm sm) ;(prn 'RESOLVE-x x) (loop [sm sm] (if (first sm) #_(if (map-entry? x) (if (!nil? ((first sm) (second x))) (map-entry (first x) ((first sm) (second x))) (recur (rest sm)))) (if (contains? (first sm) x) {x ((first sm) x)} (recur (rest sm))) nil))) ([sm x s] (if (contains? (into #{} s) x) {x x} (resolve sm x)))) (defn resolve-back3 ([sm x] (resolve3 sm x)) ([level sm x] #_(prn 'resolve-back sm x) (loop [l 0 res x last x] (if (or (nil? res) (> l level)) {x last} (let [r (resolve3 sm res) rs (if (nil? r) nil (r res)) lst (if (nil? r) last (r res))] (recur (inc l) rs lst))))) ([level sm x s](if (contains? (into #{} s) x) {x x} (resolve-back3 level sm x)))) (defn defined? [ss sm x]) (def transform-paradigm3 { ;^:pre:sym-key:0([](fn [sm x] (prewalk #(if (or (symbol? %)(keyword? %)) (let [res (resolve3 sm %)] (if res (res %) %)) %) x))) ;(fn [sm x except] (prewalkfn3 (f :let) #(if (and (or (symbol? %) (keyword? %)) (not (contains? except %))) (let [res (resolve3 sm %)] (if res (res %) %)) %) x)) :pre:sym-key:0:except (fn [sm x except] (prewalk #(if (and (or (symbol? %) (keyword? %)) (not (contains? except %))) (let [res (resolve3 sm %)] (if res (res %) %)) %) x)) :pre:sym-key:0 (fn [sm x] (prewalk #(if (or (symbol? %)(keyword? %)) (let [res (resolve3 sm %)] (if res (res %) %)) %) x)) :pos:sym-key:0 (fn [sm x] (postwalk #(if (or (symbol? %)(keyword? %)) (let [res (resolve3 sm %)] (if res (res %) %)) %) x)) :pre:sym:0 (fn [sm x] (prewalk #(if (symbol? %) (let [res (resolve3 sm %)] (if res (res %) %)) %) x)) :pos:sym:0 (fn [sm x] (postwalk #(if (symbol? %) (let [res (resolve3 sm %)] (if res (res %) %)) %) x)) :pre:key:0 (fn [sm x] (prewalk #(if (keyword? %) (let [res (resolve3 sm %)] (if res (res %) %)) %) x)) :pre:all:0 (fn [sm x] (prewalk #(let [res (resolve3 sm %)] (if res (res %) %)) x)) :pre:all:1 (fn [sm x] (prewalk #(let [res (resolve-back3 1 sm %)] (if res (res %) %)) x)) :pos:all:0 (fn [sm x] (postwalk #(let [res (resolve3 sm %)] (if res (res %) %)) x)) :pos:all:1 (fn [sm x] (postwalk #(let [res (resolve-back3 1 sm %)] (if res (res %) %)) x))}) (declare abs3) (declare f0-3) (defn transform3 ([sm x] (transform3 sm x :pos:sym:0)) ([sm x par] (transform3 sm x par nil)) ([sm x par except] ;#_(prn 'TRANSFORM3-PAR par) ;#_(prn 'TRANSFORM3-X x) (let [para (transform-paradigm3 par)] (if para (if except (para sm x (into #{} except)) (do #_(prn 'TRANSFORM-PARA (para sm x))(para sm x))) (throw (Exception. (str "transform3: UnknownTransformationParadigm " par " for " x))))))) (defn vector3 [ss sm v] (into (empty v) (map (partial abs3 ss sm) v)) ) (defn map3 [ss sm m] (let [ks (keys m) vs (vals m) nks (map (partial abs3 ss sm) ks) nvs (map (partial abs3 ss sm) vs)] (apply assoc {} (interleave nks nvs))) ) (defn midentity3 [v] (if (empty? v) {} (apply assoc {} (interleave v v)))) (defn apply3 [ss sm f] ;(prn 'apply3-IN "^" (meta f) f) (if (map? (first f)) (let [fi (first f) vs (into [] (rest f)) type- (paradigm-type3 fi)] (if (= :x0 type-) (let [ks (fi :args) cntks (count ks) cntvs (count vs) n (- cntks cntvs) zm (if (> n 0) (zipmap ks (apply conj vs (vec (replicate n nil)))) (zipmap ks vs))] #_(prn 'n n 'APPLY3-zm(zipmap ks (apply conj vs (vec (replicate n nil))))) #_(prn 'apply3-OUT ^:do[zm (fi :f)]) (abs3 ss sm ^:do[zm (fi :f)])) (throw (Exception. (str "apply3: UnknownParadigmException. Can't handle this kind of map ^" (meta fi) fi ". Source is ^"(meta f) f))))) (let [;fapp (resolve2 sm f) tr (transform3 sm f) fi (first tr)] ;(prn 'trd (type tr) tr #_(apply (first f) (rest f))) (if (and (or (symbol? fi) (keyword? fi)) (not (map? (second tr)))) (throw (Exception. (str "apply3: NoMapForSymbolAsFunctionException. Source is: ^"(meta f) f))) (apply fi (rest tr))))) ) (defn flat3 [ss sm f] #_(prn 'FLAT3-SM sm) #_(prn 'FLAT3-F f) (loop [ss ss sm sm f f ef (empty f)] (let [fi (first f)] (if (!nil? fi) (cond (map? fi)(let [type- (paradigm-type3 fi) #_pp #_(prn 'FLAT3-PARADIGM type- fi)] (cond ;(= :fn type-) (recur ss sm (rest f) (conj ef fi)) (= :l type-) (let [l ((resolve3 ss :l) :l) sm2 (l ss sm fi) ] (recur ss sm2 (rest f) ef)) ; :else (recur ss sm (rest f) (conj ef fi)))) (vector? fi) (let [abs (abs3 ss sm fi)] (recur ss sm (rest f) (conj ef abs))) :else (let [tr (transform3 sm fi)] (recur ss sm (rest f) (conj ef tr)))) ef)))) (defn ^{:doc "This paradigm is more or less clojure like"} call3 [ss sm f] (let [;pp (prn 'call3-TOFLAT "^" (meta f) f) fl (flat3 ss sm f) fi (first fl) ;pp (prn 'call3-FLATTED "^" (meta fl) fl) ] (if (> (count fl) 1) (if (!nil? fi) (if (or (vector? fi) (seq? fi) (list? fi)) (if (!nil? (next fl)) (let [app (apply3 ss sm (concat (rest fl) fi))] app) (throw (Exception. (str "call3: MalformedStructure. No function to apply to " fi ": " f)))) (apply3 ss sm fl)) (throw (Exception. (str "call3: NilFunctionException. No function to apply. " (first f) " was nil. Source is " f)))) (fi)))) (defn flatf0-3 [ss sm f] ;(prn 'flatf0-3 f) (if (coll? f) (loop [ss ss sm sm f- f ef (empty f)] (let [fi (first f-) #_pp #_(prn 'flatf0-3-f-ef f- ef)] (if (!nil? fi) (cond (map? fi)(let [type- (paradigm-type3 fi)] (cond (= :l type-) (letfn [(lp [sm ks result] (if ks (let [k (first ks) sm2 (cons {k k} sm) fik (fi k) fn- (if (coll? fik) (if (= :f0 (paradigm-type3 fik)) (f0-3 ss sm2 fik) (flatf0-3 ss sm2 fik)) (transform3 sm2 fik))] #_(prn 'lp-fn- fn-) (lp sm2 (next ks) (conj result {k fn-}))) {:sm sm :result result}))] (let [lp- (lp sm (keys fi) (empty fi))] (recur ss (lp- :sm) (rest f-) (append ef (lp- :result))))) :else (recur ss sm (rest f-) (append ef fi)))) (vector? fi) (let [type- (paradigm-type3 fi)] (cond (= :f0 type-) (let [id (midentity3 (first fi)) sm2 (cons id sm) fn- (f0-3 ss sm2 fi) ef- (append ef fn-)] (recur ss sm2 (rest f-) ef-)) :else (let [tr (flatf0-3 ss sm fi) ef- (append ef tr)] (recur ss sm (rest f-) ef-)))) #_(let [fl (flatf0-3 ss sm fi)] (recur ss sm (rest f) (conj ef fl))) :else (let [tr (transform3 sm fi)] ;(prn 'FLATY3-else ef tr) (recur ss sm (rest f-) (append ef tr)))) (do #_(prn 'ef ef) ef)))) f)) (defn x0-3 [ss sm f] f) (defn f0-3 [ss sm v] #_(prn 'f0-3 v) (let [fapp (fn [sm v-] (if (vector? (v- 0)) (let [argl (v- 0) idn (midentity3 argl) sm2 (if (empty? idn) sm (cons idn sm)) tra (into ^:c[] (flatf0-3 ss sm2 (rest v-))) ] ^:x0{:f tra :args (v- 0) :src v} ) (let [tra (into ^:c[] (flatf0-3 ss sm v-))] ^:x0{:f tra :args [] :src v})))] (fapp sm v))) #_(defn f1-3 [ss sm v] #_(prn 'f0-3 v) (let [fapp (fn [sm v-] (if (vector? (v- 0)) (let [argl (v- 0) idn (midentity3 argl) sm2 (if (empty? idn) sm (cons idn sm)) tra (into ^:c[] (flatf1-3 ss sm2 (rest v-))) ] ^:x0{:f tra :args (v- 0) :src v} ) (let [tra (into ^:c[] (flatf1-3 ss sm v-))] ^:x0{:f tra :args [] :src v})))] (fapp sm v))) (defn recur3 [ss sm f] #_(prn 'RECUR-ms sm) #_(prn 'RECUR-f f) (into (empty f) (map (partial abs3 ss sm) f))) (defn loop3 [ss sm f] (let [fi (first f)] (if (map? fi) (let [vec- (into ^:v[] (keys fi)) fndef (apply conj ^:f0[vec-] (rest f)) floop (f0-3 ss sm fndef) init (into ^:v[] (vals fi)) ;pp (prn 'LOOP3-fndef fndef) ;pp (prn 'LOOP3-floop floop) ] (loop [i init] (let [abs (call3 ss sm [i floop]) type- (if (meta abs) (paradigm-type3 abs) nil) ;pp (prn 'LOOP3-abs abs) ] (if (= :rc type-) (do #_(prn 'LOOP3-recur "^" (meta abs) abs)(recur abs)) abs)))) (throw (Exception. (str "loop3: MalformedStructureException. First element must be a map. Source is ^" (meta f) f))))) ) (defn ^{:doc "This paradigm is more or less clojure like"} call3- [ss sm f] (loop [sm sm f- f last- nil] (let [fi (first f-)] (if (!nil? fi) (cond (map? fi)(let [type- (paradigm-type3 fi)] (if= type- :l (let [l ((resolve3 ss :l) :l) sm2 (l ss sm fi)] (recur sm2 (rest f-) (second (ffirst sm2)))) (throw (Exception. (str "call3: UnknownParadigmException. call3 can't handle this paradigm ^" (meta fi) fi))))) (vector? fi) (if (!nil? (next f-)) (let [app (apply3 sm (concat (rest f-) fi))] app) (throw (Exception. (str "call3: MalformedStructure. No function to apply to " fi ": " f)))) ;(or (symbol? fi) (keyword? fi)) (apply3 sm f-) :esle (let [r (resolve3 sm fi)] (if (!nil? r) (if (vector? (r fi)) (if (!nil? (next f-)) (let [app (apply3 sm (concat (rest f-) (r fi)))] app) (throw (Exception. (str "call3: MalformedStructure. No function to apply to " fi ":" f)))) (apply3 sm (cons (r fi) (rest f-)))) (apply3 sm f-)))) last-)))) (defn ^{:doc "Named transformlet2."} let3 [ss sm m] ;(prn m) (loop [sm sm m m] (let [f (first m) ff (first f) fv (if (vector? ff) (abs3 ss sm ff) ff)] (if f (let [sec (second f)] (if (or (map? sec) (vector? sec)) (if (and (map? sec) (= :l (paradigm-type3 sec))) (let [abs (abs3 ss sm ^:do[sec]) sm2 (cons {fv abs} sm)] (recur sm2 (rest m))) (let [abs (abs3 ss sm sec) sm2 (cons {fv abs} sm)] (recur sm2 (rest m)))) (let [res (resolve3 sm sec) sec-res (if res (sec res) sec) sm2 (cons {fv sec-res} sm)] (recur sm2 (rest m))))) sm)))) (defn thread3 [ss sm f] (let [;fl (flat2 sm f) ;m (if (map? (first fl)) (first fl)) ;sm2 (if m (l sm m) sm) manage-vector (fn [ss sm f fl] (let [type- (paradigm-type3 f)] (cond (= type- :us) (let [us ((resolve3 ss :us) :us) sm2 (us ss sm f) lst (second (ffirst sm2))] [(rest fl) ss sm2 lst]) :else (let [ab (abs3 ss sm f)] [(rest fl) ss sm ab])))) manage-map (fn [ss sm f fl] (let [type- (paradigm-type3 f)] (cond (= type- :l) (let [l ((resolve3 ss :l) :l) sm2 (l ss sm f) lst (second (ffirst sm2))] [(rest fl) ss sm2 lst]) (= type- :p) (let [p ((resolve3 ss :p) :p) ss2 (p ss sm f) lst (second (ffirst ss2))] [(rest fl) ss2 sm lst]) :else [(rest fl) ss sm (abs3 ss sm f)] #_:else #_(throw (Exception. (str "The handler for :^t[] is not handler for this type of map ^" (meta f) f))) )))] (loop [fl f ss ss sm sm last- nil] (if (first fl) (let [f (first fl) cond-f (cond (or (symbol? f) (keyword? f)) (let [res (resolve3 sm f) ;fr (f res) #_cond-fr #_(if res (cond (vector? fr) (manage-vector sm fr fl) (map? fr) (manage-map sm fr fl) :else [(rest fl) sm fr]) [(rest fl) sm f]) ]#_cond-fr [(rest fl) ss sm (f res)]) (vector? f) (manage-vector ss sm f fl) (map? f) (manage-map ss sm f fl) :else [(rest fl) ss sm f]) ](recur (nth cond-f 0) (nth cond-f 1) (nth cond-f 2) (nth cond-f 3))) last-)))) (defn if3 [ss sm v] (let [fi (first v) type- (if (map? fi) (paradigm-type3 fi) nil) l (if (= type- :l) ((resolve3 ss :l) :l) nil) sm2 (if l (l ss sm fi) sm) v- (if l (subvec v 1) v) fapp (fn [v- c sm] (if (or (> 2 c) (< 3 c)) (throw (Exception. (str "if3: WrongNumberOfArguments. " c " arguments passed. Source is ^" (meta v) v))) (let [v0 (v- 0) v1 (v- 1)] (if (vector? v0) (if (abs3 ss sm v0) (if (vector? v1) (abs3 ss sm v1) (transform3 sm v1)) (if (= 3 c) (if (vector? (v- 2)) (abs3 ss sm (v- 2)) (transform3 sm (v- 2))) nil)) (if (transform3 sm v0) (if (vector? v1) (abs3 ss sm v1) (transform3 sm v1)) (if (= 3 c) (if (vector? (v- 2)) (abs3 ss sm (v- 2)) (transform3 sm (v- 2))) nil))))))] (fapp v- (count v-) sm2))) (defn sym3 [ss sm s] (prn 'sym s) (let [r (resolve3 sm s)] (if (nil? r) s (r s)))) (defn use3 [ss sm n] (let [nsp (map #(let [nsp (ns-publics %)](into {} (reverse nsp))) (reverse n))] (concat nsp sm))) (def jr-defaults3 (seq [{:do thread3 :l let3 :s sym3 :c call3 :m map3 :v vector3 :f0 f0-3 :x0 x0-3 :fl flat3 :if if3 :a apply3 :ff flatf0-3 :lp loop3 :rc recur3 :us use3 }])) (def fns { 'if '^:f0[[x y z] ^:if[x y z]] 'new (fn [cl & args](clojure.lang.Reflector/invokeConstructor cl (to-array args)))}) (defn abs3 [ss sm f] ;(prn 'ABS3 f) (let [type- (paradigm-type3 f) res (resolve3 ss type-)] (if (nil? res) (throw (Exception. (str "abs3: UnknownParadigmException ^" (meta f) f))) ((res type-) ss sm f)))) (defn jr3 ([f] (let [nsp (ns-publics 'clojure.core) fns- (merge nsp fns)] (jr3 (seq [fns-]) f))) ([sm f] (let [sm2 (if (seq? sm) sm (if (nil? sm) '() (seq [sm])))] (jr3 jr-defaults3 sm2 f))) ([ss sm f] (abs3 ss sm f))) (defn path-from-ns [ns] (clojure.string/join [(clojure.string/replace (clojure.string/replace (str ns) #"\." "/") #"-" "_") ".junior"])) (defn resource-path-of-ns [ns] (clojure.string/replace-first (str (clojure.java.io/resource (path-from-ns ns))) "file:" "") ) (defn ^{:doc "get File .clj corresponding to the symbol ns"} junior-file [ns] (let [ path (path-from-ns ns) ] (clojure.java.io/as-file (clojure.java.io/resource path)) ) ) (defn- read-one [r] (try (binding [*print-meta* true](let [re (read r) p (prn re)] re)) (catch java.lang.RuntimeException e (if (= "EOF while reading" (.getMessage e)) ::EOF (throw e))))) (defn read-seq-from-file "Reads a sequence of top-level objects in file at path." [path] (with-open [r (java.io.PushbackReader. (clojure.java.io/reader path))] (binding [*read-eval* false] (doall (take-while #(not= ::EOF %) (repeatedly #(read-one r))))))) (defn load-junior [ns] (slurp (resource-path-of-ns ns))) (defn read-junior [ns] (read-string (load-junior ns))) (jr3 '^:do[^:us[junior.core]{:b 1 :a :c}])
[ { "context": "\"grant_type\" \"authorization_code\"\n \"code\" \"MGMxMTIxOGMtODllNi00Y2IxLTgzMmUtNWRiOTlkN2JjNTFiuCB9pfAg6EonMv-7e_aCGitFnndOIe5gNT71hH4Ix1ImrqHk2EHrPCBNMV-l1crDC4RtS2shyDamk9myheKPkQ\"\n \"redirect_uri\" \"http://localhost:3002/on", "end": 2799, "score": 0.9931158423423767, "start": 2665, "tag": "KEY", "value": "MGMxMTIxOGMtODllNi00Y2IxLTgzMmUtNWRiOTlkN2JjNTFiuCB9pfAg6EonMv-7e_aCGitFnndOIe5gNT71hH4Ix1ImrqHk2EHrPCBNMV-l1crDC4RtS2shyDamk9myheKPkQ" }, { "context": "df57-0a163e67b84c140139\"\n \"client_secret\" \"dc8347cda5fc1bc5667d12f832c5f03bcb2134e59ec16586f247b25a5295209f\"}))})\n\n (exceptionally\n (reify java.util.fun", "end": 3020, "score": 0.9997372627258301, "start": 2956, "tag": "KEY", "value": "dc8347cda5fc1bc5667d12f832c5f03bcb2134e59ec16586f247b25a5295209f" } ]
modules/oauth2/src/juxt/apex/alpha/oauth2/http_client.clj
SevereOverfl0w/apex
123
;; Copyright © 2020, JUXT LTD. (ns juxt.apex.alpha.oauth2.http-client (:require [ring.util.codec :as codec]) (:import [java.net URI] [java.net.http HttpClient HttpClient$Version HttpRequest HttpResponse$BodyHandlers HttpRequest$BodyPublishers])) (defn new-client ([] (new-client {})) ([{:keys [connect-timeout] :or {connect-timeout (java.time.Duration/ofSeconds 20)} :as opts}] (.. (HttpClient/newBuilder) (version HttpClient$Version/HTTP_1_1) (connectTimeout connect-timeout) (build)))) (defn new-request ([method url] (new-request method url {})) ([method url {:keys [request-body-publisher headers] :as opts}] (.build (cond-> (HttpRequest/newBuilder) (= method :get) (.GET) (= method :delete) (.DELETE) headers ((fn [builder] (doseq [[k v] headers] (.setHeader builder k v)) builder)) request-body-publisher (.method (.toUpperCase (name method)) request-body-publisher) true (.uri (URI/create url)))))) (defn request ([client method url] (request client method url {})) ([client method url {:keys [response-body-handler async on-success on-error] :or {response-body-handler (HttpResponse$BodyHandlers/ofString)} :as opts}] (let [request (new-request method url opts)] (if async (cond-> (.sendAsync client request response-body-handler) on-error (. (exceptionally (reify java.util.function.Function (apply [_ error] (println "Error:" error) (on-error error))))) on-success (. (thenAccept (reify java.util.function.Consumer (accept [_ result] (on-success result)))))) (try (let [result (.send client request response-body-handler)] (if on-success (on-success result) result)) (catch Exception e (if on-error (on-error e) (throw e)))))))) (defn ->www-form-urlencoded [m] (apply str (interpose "&" (for [[k v] m] (if (sequential? v) (apply str (interpose "&" (for [v v] (str k "=" v)))) (str k "=" v)))))) ;; Try https://developers.onelogin.com/openid-connect/inspector #_(let [client (new-client)] (.. (request client :get "https://juxt-dev.onelogin.com/oidc/token" {:async true :request-body-publisher (HttpRequest$BodyPublishers/ofString (->www-form-urlencoded {"grant_type" "authorization_code" "code" "MGMxMTIxOGMtODllNi00Y2IxLTgzMmUtNWRiOTlkN2JjNTFiuCB9pfAg6EonMv-7e_aCGitFnndOIe5gNT71hH4Ix1ImrqHk2EHrPCBNMV-l1crDC4RtS2shyDamk9myheKPkQ" "redirect_uri" "http://localhost:3002/onelogin/callback" "client_id" "ed6dd790-ee2b-0136-df57-0a163e67b84c140139" "client_secret" "dc8347cda5fc1bc5667d12f832c5f03bcb2134e59ec16586f247b25a5295209f"}))}) (exceptionally (reify java.util.function.Function (apply [_ error] (println "Error:" error) ))) (thenAccept (reify java.util.function.Consumer (accept [_ result] (println "Result:" result) (println "Headers:" (.headers result)) (println "Body:" (.body result)) )) )) )
121858
;; Copyright © 2020, JUXT LTD. (ns juxt.apex.alpha.oauth2.http-client (:require [ring.util.codec :as codec]) (:import [java.net URI] [java.net.http HttpClient HttpClient$Version HttpRequest HttpResponse$BodyHandlers HttpRequest$BodyPublishers])) (defn new-client ([] (new-client {})) ([{:keys [connect-timeout] :or {connect-timeout (java.time.Duration/ofSeconds 20)} :as opts}] (.. (HttpClient/newBuilder) (version HttpClient$Version/HTTP_1_1) (connectTimeout connect-timeout) (build)))) (defn new-request ([method url] (new-request method url {})) ([method url {:keys [request-body-publisher headers] :as opts}] (.build (cond-> (HttpRequest/newBuilder) (= method :get) (.GET) (= method :delete) (.DELETE) headers ((fn [builder] (doseq [[k v] headers] (.setHeader builder k v)) builder)) request-body-publisher (.method (.toUpperCase (name method)) request-body-publisher) true (.uri (URI/create url)))))) (defn request ([client method url] (request client method url {})) ([client method url {:keys [response-body-handler async on-success on-error] :or {response-body-handler (HttpResponse$BodyHandlers/ofString)} :as opts}] (let [request (new-request method url opts)] (if async (cond-> (.sendAsync client request response-body-handler) on-error (. (exceptionally (reify java.util.function.Function (apply [_ error] (println "Error:" error) (on-error error))))) on-success (. (thenAccept (reify java.util.function.Consumer (accept [_ result] (on-success result)))))) (try (let [result (.send client request response-body-handler)] (if on-success (on-success result) result)) (catch Exception e (if on-error (on-error e) (throw e)))))))) (defn ->www-form-urlencoded [m] (apply str (interpose "&" (for [[k v] m] (if (sequential? v) (apply str (interpose "&" (for [v v] (str k "=" v)))) (str k "=" v)))))) ;; Try https://developers.onelogin.com/openid-connect/inspector #_(let [client (new-client)] (.. (request client :get "https://juxt-dev.onelogin.com/oidc/token" {:async true :request-body-publisher (HttpRequest$BodyPublishers/ofString (->www-form-urlencoded {"grant_type" "authorization_code" "code" "<KEY>" "redirect_uri" "http://localhost:3002/onelogin/callback" "client_id" "ed6dd790-ee2b-0136-df57-0a163e67b84c140139" "client_secret" "<KEY>"}))}) (exceptionally (reify java.util.function.Function (apply [_ error] (println "Error:" error) ))) (thenAccept (reify java.util.function.Consumer (accept [_ result] (println "Result:" result) (println "Headers:" (.headers result)) (println "Body:" (.body result)) )) )) )
true
;; Copyright © 2020, JUXT LTD. (ns juxt.apex.alpha.oauth2.http-client (:require [ring.util.codec :as codec]) (:import [java.net URI] [java.net.http HttpClient HttpClient$Version HttpRequest HttpResponse$BodyHandlers HttpRequest$BodyPublishers])) (defn new-client ([] (new-client {})) ([{:keys [connect-timeout] :or {connect-timeout (java.time.Duration/ofSeconds 20)} :as opts}] (.. (HttpClient/newBuilder) (version HttpClient$Version/HTTP_1_1) (connectTimeout connect-timeout) (build)))) (defn new-request ([method url] (new-request method url {})) ([method url {:keys [request-body-publisher headers] :as opts}] (.build (cond-> (HttpRequest/newBuilder) (= method :get) (.GET) (= method :delete) (.DELETE) headers ((fn [builder] (doseq [[k v] headers] (.setHeader builder k v)) builder)) request-body-publisher (.method (.toUpperCase (name method)) request-body-publisher) true (.uri (URI/create url)))))) (defn request ([client method url] (request client method url {})) ([client method url {:keys [response-body-handler async on-success on-error] :or {response-body-handler (HttpResponse$BodyHandlers/ofString)} :as opts}] (let [request (new-request method url opts)] (if async (cond-> (.sendAsync client request response-body-handler) on-error (. (exceptionally (reify java.util.function.Function (apply [_ error] (println "Error:" error) (on-error error))))) on-success (. (thenAccept (reify java.util.function.Consumer (accept [_ result] (on-success result)))))) (try (let [result (.send client request response-body-handler)] (if on-success (on-success result) result)) (catch Exception e (if on-error (on-error e) (throw e)))))))) (defn ->www-form-urlencoded [m] (apply str (interpose "&" (for [[k v] m] (if (sequential? v) (apply str (interpose "&" (for [v v] (str k "=" v)))) (str k "=" v)))))) ;; Try https://developers.onelogin.com/openid-connect/inspector #_(let [client (new-client)] (.. (request client :get "https://juxt-dev.onelogin.com/oidc/token" {:async true :request-body-publisher (HttpRequest$BodyPublishers/ofString (->www-form-urlencoded {"grant_type" "authorization_code" "code" "PI:KEY:<KEY>END_PI" "redirect_uri" "http://localhost:3002/onelogin/callback" "client_id" "ed6dd790-ee2b-0136-df57-0a163e67b84c140139" "client_secret" "PI:KEY:<KEY>END_PI"}))}) (exceptionally (reify java.util.function.Function (apply [_ error] (println "Error:" error) ))) (thenAccept (reify java.util.function.Consumer (accept [_ result] (println "Result:" result) (println "Headers:" (.headers result)) (println "Body:" (.body result)) )) )) )
[ { "context": ";;;; Tests for the utiity code.\n;;;;\n;;;; Ron Ferguson\n;;;; Created: 2014-04-22\n;;;; Updated: 2014-04-30", "end": 54, "score": 0.9998576045036316, "start": 42, "tag": "NAME", "value": "Ron Ferguson" } ]
test/dray/util_test.clj
visthink/dray2
1
;;;; Tests for the utiity code. ;;;; ;;;; Ron Ferguson ;;;; Created: 2014-04-22 ;;;; Updated: 2014-04-30 ;;;; (ns dray.util-test (:import (java.io File) (java.nio.file Path) ) (:require [clojure.test :refer :all] [dray.util :refer :all] [dray.util.map :refer [contains-key-vals?]] [clojure.repl :refer :all] [clojure.inspector :refer :all] [clojure.java.io :refer [file]] #_[clojure.data.xml :refer [Element]] [dray.test-data :refer [+prxml-sample-data+]] [dray.corpus :refer [corpus]] )) (defn const? [x] (:const (meta x))) (deftest defconst-tests (let [[n1 n2 n3] (repeatedly gensym) ; Gen const names and values. [v1 v2 v3] (repeatedly #(rand 100))] (testing "Single constant definition test" (is (const? (eval `(defconst ~n1 ~v1)))) (is (eval `(= ~n1 ~v1))) ) (testing "Multiple constants definition test" (eval `(defconst ~n2 ~v2 ~n3 ~v3)) (is (const? (eval `(var ,~n2)))) (is (const? (eval `(var ,~n3)))) (is (eval `(= ~n2 ~v2))) (is (eval `(= ~n3 ~v3))) ))) (deftest map-selector-fn-test (testing "Map selector fn test" (let [ff1 (file "./foo/bar.bat") ff2 (file "test.txt") sel-fn (map-selector-fn :name getName :parent getParent :dir? isDirectory)] (is (contains-key-vals? (sel-fn ff1) :name "bar.bat" :parent "./foo" :dir? false)) (is (contains-key-vals? (sel-fn ff2) :name "test.txt" :parent nil :dir? false)) ))) (deftest hyphenate-classname-test (testing "Hyphenate classnames" (is (= "text-fragment" (hyphenate-camelcase "TextFragment"))) (is (= "text-box" (hyphenate-camelcase "TextBox"))) (is (= "long" (hyphenate-classname (class 1)))) (is (= "persistent-array-map" (hyphenate-classname (class {})))) )) (deftest test-keyword (testing "Test de-keywording" (is (= 'foo (de-keyword :foo))) (is (= 'foo (de-keyword 'foo))) )) (deftest test-find-classname (testing "Test of full-classname-for-symbol" (is (= "java.lang.Integer" (full-classname-for-symbol 'Integer))) (is (= "clojure.data.xml.Element" (full-classname-for-symbol 'Element 'clojure.data.xml))) (is (thrown-with-msg? Exception #"Could not find full classname for symbol .+" (full-classname-for-symbol 'not-a-known-class))) )) (deftest test-cache-dir (testing "Test the cache-directory functions." (let [pdf (corpus :core-test 0) cdir (cache-directory pdf) p1 (file "test/myfile.txt") p2 (file ".dray-cache/test/myfile.txt") p3 (file "resource/corpus/test-core/.dray-cache/test/myfile.txt") p4 (file (.getCanonicalPath p3)) good-result (file cdir "test" "myfile.txt") ] (is (= good-result (resolve-cache-file-for pdf p1))) ; Test straight add. (is (= good-result (resolve-cache-file-for pdf p2))) ; Test one-level overlap. (is (= good-result (resolve-cache-file-for pdf p3))) ; Test higher amount of overlap. ; (is (= (file (.getCanonicalPath good-result)) (resolve-cache-file-for pdf p4))) ))) (deftest test-uerr-and-uerror (testing "Testing the uerr and uerror macros." (is (thrown-with-msg? Exception #"Foobar!" (uerror "Foobar!"))) (is (thrown-with-msg? Exception #"Foobar!" (uerr "Foobar!"))) (is (thrown-with-msg? ArithmeticException #"Div 4 by zero." (uerr ArithmeticException "Div %d by zero." 4))) )) (deftest test-filetype? (testing "Test the file-type? predicate." (let [f (file "myfile.txt")] (is (true? (file-type? f ".txt"))) (is (false? (file-type? f ".pdf"))) (is (false? (file-type? f ".txttxt"))) ))) (deftest test-every-other (testing "Test every other utility function." (is (= (every-other (range 10)) '(0 2 4 6 8))) (is (= (every-other (range 11)) '(0 2 4 6 8 10))) (is (= (every-other '()) '())) (is (= (every-other '(1)) '(1))) )) (deftest test-pairwise-group-by (testing "Test the pairwise-group-by function." (let [s1 '(1 2 3 6 7 9 10 11 15 18 20 21 22) ; typical. s2 '(1 3 5 7) ; none s3 '(1 2 3 4) ; all s4 '(0 3 5 6 7 9 10 13) ; starting with non-group. plus-one? (fn [a b] (= 1 (- b a)))] (is (= (pairwise-group-by s1 plus-one?) '((1 2 3) (6 7) (9 10 11) (20 21 22)))) (is (= (pairwise-group-by s2 plus-one?) '())) (is (= (pairwise-group-by s3 plus-one?) '((1 2 3 4)))) (is (= (pairwise-group-by s4 plus-one?) '((5 6 7) (9 10)))) ))) (deftest test-pairwise-replace (testing "Test the pairwise-replace function." (let [s1 '(1 2 2 3 4 5 5 10 11) s2 '(1 1 2 3 4 5 1 1) ; merge at start. s3 '(1 2 3 3 6) ; merge at end. ] (is (= (pairwise-replace s1 = +) '(1 4 3 4 20 11))) (is (= (pairwise-replace s2 = +) '(4 3 4 5 2))) (is (= (pairwise-replace s3 = +) '(1 2 12))) (is (= (pairwise-replace '(1 1) = +) '(2))) (is (= (pairwise-replace '(1) = +) '(1))) (is (= (pairwise-replace '() = +) '())) ))) (deftest test-decode-url (testing "Test the decode-url function." (is (= (decode-url "p2x-3_Ogura%20et%20al%202009.xml_data/image-2.vec") "p2x-3_Ogura et al 2009.xml_data/image-2.vec")) (is (= (decode-url "http%3A%2F%2Ffoo%20bar%2F") ;; from rosettacode.org. "http://foo bar/"))))
92299
;;;; Tests for the utiity code. ;;;; ;;;; <NAME> ;;;; Created: 2014-04-22 ;;;; Updated: 2014-04-30 ;;;; (ns dray.util-test (:import (java.io File) (java.nio.file Path) ) (:require [clojure.test :refer :all] [dray.util :refer :all] [dray.util.map :refer [contains-key-vals?]] [clojure.repl :refer :all] [clojure.inspector :refer :all] [clojure.java.io :refer [file]] #_[clojure.data.xml :refer [Element]] [dray.test-data :refer [+prxml-sample-data+]] [dray.corpus :refer [corpus]] )) (defn const? [x] (:const (meta x))) (deftest defconst-tests (let [[n1 n2 n3] (repeatedly gensym) ; Gen const names and values. [v1 v2 v3] (repeatedly #(rand 100))] (testing "Single constant definition test" (is (const? (eval `(defconst ~n1 ~v1)))) (is (eval `(= ~n1 ~v1))) ) (testing "Multiple constants definition test" (eval `(defconst ~n2 ~v2 ~n3 ~v3)) (is (const? (eval `(var ,~n2)))) (is (const? (eval `(var ,~n3)))) (is (eval `(= ~n2 ~v2))) (is (eval `(= ~n3 ~v3))) ))) (deftest map-selector-fn-test (testing "Map selector fn test" (let [ff1 (file "./foo/bar.bat") ff2 (file "test.txt") sel-fn (map-selector-fn :name getName :parent getParent :dir? isDirectory)] (is (contains-key-vals? (sel-fn ff1) :name "bar.bat" :parent "./foo" :dir? false)) (is (contains-key-vals? (sel-fn ff2) :name "test.txt" :parent nil :dir? false)) ))) (deftest hyphenate-classname-test (testing "Hyphenate classnames" (is (= "text-fragment" (hyphenate-camelcase "TextFragment"))) (is (= "text-box" (hyphenate-camelcase "TextBox"))) (is (= "long" (hyphenate-classname (class 1)))) (is (= "persistent-array-map" (hyphenate-classname (class {})))) )) (deftest test-keyword (testing "Test de-keywording" (is (= 'foo (de-keyword :foo))) (is (= 'foo (de-keyword 'foo))) )) (deftest test-find-classname (testing "Test of full-classname-for-symbol" (is (= "java.lang.Integer" (full-classname-for-symbol 'Integer))) (is (= "clojure.data.xml.Element" (full-classname-for-symbol 'Element 'clojure.data.xml))) (is (thrown-with-msg? Exception #"Could not find full classname for symbol .+" (full-classname-for-symbol 'not-a-known-class))) )) (deftest test-cache-dir (testing "Test the cache-directory functions." (let [pdf (corpus :core-test 0) cdir (cache-directory pdf) p1 (file "test/myfile.txt") p2 (file ".dray-cache/test/myfile.txt") p3 (file "resource/corpus/test-core/.dray-cache/test/myfile.txt") p4 (file (.getCanonicalPath p3)) good-result (file cdir "test" "myfile.txt") ] (is (= good-result (resolve-cache-file-for pdf p1))) ; Test straight add. (is (= good-result (resolve-cache-file-for pdf p2))) ; Test one-level overlap. (is (= good-result (resolve-cache-file-for pdf p3))) ; Test higher amount of overlap. ; (is (= (file (.getCanonicalPath good-result)) (resolve-cache-file-for pdf p4))) ))) (deftest test-uerr-and-uerror (testing "Testing the uerr and uerror macros." (is (thrown-with-msg? Exception #"Foobar!" (uerror "Foobar!"))) (is (thrown-with-msg? Exception #"Foobar!" (uerr "Foobar!"))) (is (thrown-with-msg? ArithmeticException #"Div 4 by zero." (uerr ArithmeticException "Div %d by zero." 4))) )) (deftest test-filetype? (testing "Test the file-type? predicate." (let [f (file "myfile.txt")] (is (true? (file-type? f ".txt"))) (is (false? (file-type? f ".pdf"))) (is (false? (file-type? f ".txttxt"))) ))) (deftest test-every-other (testing "Test every other utility function." (is (= (every-other (range 10)) '(0 2 4 6 8))) (is (= (every-other (range 11)) '(0 2 4 6 8 10))) (is (= (every-other '()) '())) (is (= (every-other '(1)) '(1))) )) (deftest test-pairwise-group-by (testing "Test the pairwise-group-by function." (let [s1 '(1 2 3 6 7 9 10 11 15 18 20 21 22) ; typical. s2 '(1 3 5 7) ; none s3 '(1 2 3 4) ; all s4 '(0 3 5 6 7 9 10 13) ; starting with non-group. plus-one? (fn [a b] (= 1 (- b a)))] (is (= (pairwise-group-by s1 plus-one?) '((1 2 3) (6 7) (9 10 11) (20 21 22)))) (is (= (pairwise-group-by s2 plus-one?) '())) (is (= (pairwise-group-by s3 plus-one?) '((1 2 3 4)))) (is (= (pairwise-group-by s4 plus-one?) '((5 6 7) (9 10)))) ))) (deftest test-pairwise-replace (testing "Test the pairwise-replace function." (let [s1 '(1 2 2 3 4 5 5 10 11) s2 '(1 1 2 3 4 5 1 1) ; merge at start. s3 '(1 2 3 3 6) ; merge at end. ] (is (= (pairwise-replace s1 = +) '(1 4 3 4 20 11))) (is (= (pairwise-replace s2 = +) '(4 3 4 5 2))) (is (= (pairwise-replace s3 = +) '(1 2 12))) (is (= (pairwise-replace '(1 1) = +) '(2))) (is (= (pairwise-replace '(1) = +) '(1))) (is (= (pairwise-replace '() = +) '())) ))) (deftest test-decode-url (testing "Test the decode-url function." (is (= (decode-url "p2x-3_Ogura%20et%20al%202009.xml_data/image-2.vec") "p2x-3_Ogura et al 2009.xml_data/image-2.vec")) (is (= (decode-url "http%3A%2F%2Ffoo%20bar%2F") ;; from rosettacode.org. "http://foo bar/"))))
true
;;;; Tests for the utiity code. ;;;; ;;;; PI:NAME:<NAME>END_PI ;;;; Created: 2014-04-22 ;;;; Updated: 2014-04-30 ;;;; (ns dray.util-test (:import (java.io File) (java.nio.file Path) ) (:require [clojure.test :refer :all] [dray.util :refer :all] [dray.util.map :refer [contains-key-vals?]] [clojure.repl :refer :all] [clojure.inspector :refer :all] [clojure.java.io :refer [file]] #_[clojure.data.xml :refer [Element]] [dray.test-data :refer [+prxml-sample-data+]] [dray.corpus :refer [corpus]] )) (defn const? [x] (:const (meta x))) (deftest defconst-tests (let [[n1 n2 n3] (repeatedly gensym) ; Gen const names and values. [v1 v2 v3] (repeatedly #(rand 100))] (testing "Single constant definition test" (is (const? (eval `(defconst ~n1 ~v1)))) (is (eval `(= ~n1 ~v1))) ) (testing "Multiple constants definition test" (eval `(defconst ~n2 ~v2 ~n3 ~v3)) (is (const? (eval `(var ,~n2)))) (is (const? (eval `(var ,~n3)))) (is (eval `(= ~n2 ~v2))) (is (eval `(= ~n3 ~v3))) ))) (deftest map-selector-fn-test (testing "Map selector fn test" (let [ff1 (file "./foo/bar.bat") ff2 (file "test.txt") sel-fn (map-selector-fn :name getName :parent getParent :dir? isDirectory)] (is (contains-key-vals? (sel-fn ff1) :name "bar.bat" :parent "./foo" :dir? false)) (is (contains-key-vals? (sel-fn ff2) :name "test.txt" :parent nil :dir? false)) ))) (deftest hyphenate-classname-test (testing "Hyphenate classnames" (is (= "text-fragment" (hyphenate-camelcase "TextFragment"))) (is (= "text-box" (hyphenate-camelcase "TextBox"))) (is (= "long" (hyphenate-classname (class 1)))) (is (= "persistent-array-map" (hyphenate-classname (class {})))) )) (deftest test-keyword (testing "Test de-keywording" (is (= 'foo (de-keyword :foo))) (is (= 'foo (de-keyword 'foo))) )) (deftest test-find-classname (testing "Test of full-classname-for-symbol" (is (= "java.lang.Integer" (full-classname-for-symbol 'Integer))) (is (= "clojure.data.xml.Element" (full-classname-for-symbol 'Element 'clojure.data.xml))) (is (thrown-with-msg? Exception #"Could not find full classname for symbol .+" (full-classname-for-symbol 'not-a-known-class))) )) (deftest test-cache-dir (testing "Test the cache-directory functions." (let [pdf (corpus :core-test 0) cdir (cache-directory pdf) p1 (file "test/myfile.txt") p2 (file ".dray-cache/test/myfile.txt") p3 (file "resource/corpus/test-core/.dray-cache/test/myfile.txt") p4 (file (.getCanonicalPath p3)) good-result (file cdir "test" "myfile.txt") ] (is (= good-result (resolve-cache-file-for pdf p1))) ; Test straight add. (is (= good-result (resolve-cache-file-for pdf p2))) ; Test one-level overlap. (is (= good-result (resolve-cache-file-for pdf p3))) ; Test higher amount of overlap. ; (is (= (file (.getCanonicalPath good-result)) (resolve-cache-file-for pdf p4))) ))) (deftest test-uerr-and-uerror (testing "Testing the uerr and uerror macros." (is (thrown-with-msg? Exception #"Foobar!" (uerror "Foobar!"))) (is (thrown-with-msg? Exception #"Foobar!" (uerr "Foobar!"))) (is (thrown-with-msg? ArithmeticException #"Div 4 by zero." (uerr ArithmeticException "Div %d by zero." 4))) )) (deftest test-filetype? (testing "Test the file-type? predicate." (let [f (file "myfile.txt")] (is (true? (file-type? f ".txt"))) (is (false? (file-type? f ".pdf"))) (is (false? (file-type? f ".txttxt"))) ))) (deftest test-every-other (testing "Test every other utility function." (is (= (every-other (range 10)) '(0 2 4 6 8))) (is (= (every-other (range 11)) '(0 2 4 6 8 10))) (is (= (every-other '()) '())) (is (= (every-other '(1)) '(1))) )) (deftest test-pairwise-group-by (testing "Test the pairwise-group-by function." (let [s1 '(1 2 3 6 7 9 10 11 15 18 20 21 22) ; typical. s2 '(1 3 5 7) ; none s3 '(1 2 3 4) ; all s4 '(0 3 5 6 7 9 10 13) ; starting with non-group. plus-one? (fn [a b] (= 1 (- b a)))] (is (= (pairwise-group-by s1 plus-one?) '((1 2 3) (6 7) (9 10 11) (20 21 22)))) (is (= (pairwise-group-by s2 plus-one?) '())) (is (= (pairwise-group-by s3 plus-one?) '((1 2 3 4)))) (is (= (pairwise-group-by s4 plus-one?) '((5 6 7) (9 10)))) ))) (deftest test-pairwise-replace (testing "Test the pairwise-replace function." (let [s1 '(1 2 2 3 4 5 5 10 11) s2 '(1 1 2 3 4 5 1 1) ; merge at start. s3 '(1 2 3 3 6) ; merge at end. ] (is (= (pairwise-replace s1 = +) '(1 4 3 4 20 11))) (is (= (pairwise-replace s2 = +) '(4 3 4 5 2))) (is (= (pairwise-replace s3 = +) '(1 2 12))) (is (= (pairwise-replace '(1 1) = +) '(2))) (is (= (pairwise-replace '(1) = +) '(1))) (is (= (pairwise-replace '() = +) '())) ))) (deftest test-decode-url (testing "Test the decode-url function." (is (= (decode-url "p2x-3_Ogura%20et%20al%202009.xml_data/image-2.vec") "p2x-3_Ogura et al 2009.xml_data/image-2.vec")) (is (= (decode-url "http%3A%2F%2Ffoo%20bar%2F") ;; from rosettacode.org. "http://foo bar/"))))
[ { "context": ";; ClojureScript by Mathieu Legrand <mathieu@legrand.im>\n(ns potato.emoji\n (:require", "end": 35, "score": 0.9998874068260193, "start": 20, "tag": "NAME", "value": "Mathieu Legrand" }, { "context": ";; ClojureScript by Mathieu Legrand <mathieu@legrand.im>\n(ns potato.emoji\n (:require [om.dom :include-ma", "end": 55, "score": 0.9999250173568726, "start": 37, "tag": "EMAIL", "value": "mathieu@legrand.im" }, { "context": " \"construction worker\"\n \"\\uD83D\\uDC82\" \"guardsman\"\n \"\\uD83D\\uDC76\" \"baby\"\n \"\\uD83D", "end": 2771, "score": 0.6637458205223083, "start": 2769, "tag": "NAME", "value": "gu" }, { "context": " [\"runner\" \"running\"]\n \"\\uD83D\\uDC83\" \"dancer\"\n \"\\uD83D\\uDC6B\" \"couple\"\n \"\\uD83D\\uDC6", "end": 5039, "score": 0.7710940837860107, "start": 5033, "tag": "NAME", "value": "dancer" }, { "context": " \"couple with heart\"\n \"\\uD83D\\uDC6F\" \"dancers\"\n \"\\uD83D\\uDE46\" \"ok woman\"\n \"\\uD83D\\uD", "end": 5318, "score": 0.7287378311157227, "start": 5311, "tag": "NAME", "value": "dancers" }, { "context": "4B\" \"cancer\"\n \"\\u264C\" \"leo\"\n \"\\u264D\" \"virgo\"\n \"\\u264E\" ", "end": 27966, "score": 0.9436357021331787, "start": 27963, "tag": "NAME", "value": "leo" }, { "context": "u264C\" \"leo\"\n \"\\u264D\" \"virgo\"\n \"\\u264E\" \"libra\"\n \"\\u264F\" ", "end": 27998, "score": 0.9354180097579956, "start": 27993, "tag": "NAME", "value": "virgo" }, { "context": "64D\" \"virgo\"\n \"\\u264E\" \"libra\"\n \"\\u264F\" \"scorpius\"\n \"\\u2650\" ", "end": 28030, "score": 0.7390984296798706, "start": 28025, "tag": "NAME", "value": "libra" }, { "context": "64E\" \"libra\"\n \"\\u264F\" \"scorpius\"\n \"\\u2650\" \"sagittarius\"\n \"", "end": 28059, "score": 0.5146053433418274, "start": 28057, "tag": "NAME", "value": "sc" }, { "context": "\" \"scorpius\"\n \"\\u2650\" \"sagittarius\"\n \"\\u2651\" \"capricorn\"\n \"\\u2652\" ", "end": 28103, "score": 0.9451120495796204, "start": 28092, "tag": "NAME", "value": "sagittarius" }, { "context": " \"sagittarius\"\n \"\\u2651\" \"capricorn\"\n \"\\u2652\" \"aquarius\"\n \"\\u2653\" ", "end": 28139, "score": 0.975461483001709, "start": 28130, "tag": "NAME", "value": "capricorn" }, { "context": " \"capricorn\"\n \"\\u2652\" \"aquarius\"\n \"\\u2653\" \"pisces\"\n \"\\u26CE\" ", "end": 28174, "score": 0.9684873223304749, "start": 28166, "tag": "NAME", "value": "aquarius" }, { "context": "\" \"aquarius\"\n \"\\u2653\" \"pisces\"\n \"\\u26CE\" \"ophiuchus\"\n \"\\uD83D\\u", "end": 28207, "score": 0.8055455088615417, "start": 28201, "tag": "NAME", "value": "pisces" } ]
web-app/src/cljs/potato/emoji.cljs
cicakhq/potato
188
;; ClojureScript by Mathieu Legrand <mathieu@legrand.im> (ns potato.emoji (:require [om.dom :include-macros true])) (declare unicode-to-aliases) (defn get-name [alias] (condp = (type alias) js/String alias cljs.core/PersistentVector (first alias) "")) (defn span [item] (om.dom/span nil (om.dom/span #js {:className "emoji"} (:text item)) (get-name (:id item)))) (def unicode-to-aliases {"\uD83D\uDE04" ["smile" ")" "-)"] "\uD83D\uDE03" "smiley" "\uD83D\uDE00" "grinning" "\uD83D\uDE0A" "blush" "\u263A\uFE0F" "relaxed" "\uD83D\uDE09" "wink" "\uD83D\uDE0D" "heart eyes" "\uD83D\uDE18" "kissing heart" "\uD83D\uDE1A" "kissing closed eyes" "\uD83D\uDE17" "kissing" "\uD83D\uDE19" "kissing smiling eyes" "\uD83D\uDE1C" ["stuck out tongue winking eye" "p" "-p"] "\uD83D\uDE1D" "stuck out tongue closed eyes" "\uD83D\uDE1B" "stuck out tongue" "\uD83D\uDE33" "flushed" "\uD83D\uDE01" "grin" "\uD83D\uDE14" "pensive" "\uD83D\uDE0C" "relieved" "\uD83D\uDE12" "unamused" "\uD83D\uDE1E" ["disappointed" "("] "\uD83D\uDE23" "persevere" "\uD83D\uDE22" "cry" "\uD83D\uDE02" "joy" "\uD83D\uDE2D" "sob" "\uD83D\uDE2A" "sleepy" "\uD83D\uDE25" "disappointed relieved" "\uD83D\uDE30" "cold sweat" "\uD83D\uDE05" "sweat smile" "\uD83D\uDE13" "sweat" "\uD83D\uDE29" "weary" "\uD83D\uDE2B" "tired face" "\uD83D\uDE28" "fearful" "\uD83D\uDE31" "scream" "\uD83D\uDE20" "angry" "\uD83D\uDE21" "rage" "\uD83D\uDE24" "triumph" "\uD83D\uDE16" "confounded" "\uD83D\uDE06" ["laughing" "satisfied"] "\uD83D\uDE0B" "yum" "\uD83D\uDE37" "mask" "\uD83D\uDE0E" ["sunglasses" "cool"] "\uD83D\uDE34" "sleeping" "\uD83D\uDE35" "dizzy face" "\uD83D\uDE32" "astonished" "\uD83D\uDE1F" "worried" "\uD83D\uDE26" "frowning" "\uD83D\uDE27" "anguished" "\uD83D\uDE08" "smiling imp" "\uD83D\uDC7F" "imp" "\uD83D\uDE2E" "open mouth" "\uD83D\uDE2C" "grimacing" "\uD83D\uDE10" "neutral face" "\uD83D\uDE15" ["confused" "/"] "\uD83D\uDE2F" "hushed" "\uD83D\uDE36" "no mouth" "\uD83D\uDE07" "innocent" "\uD83D\uDE0F" "smirk" "\uD83D\uDE11" "expressionless" "\uD83D\uDC72" "man with gua pi mao" "\uD83D\uDC73" "man with turban" "\uD83D\uDC6E" "cop" "\uD83D\uDC77" "construction worker" "\uD83D\uDC82" "guardsman" "\uD83D\uDC76" "baby" "\uD83D\uDC66" "boy" "\uD83D\uDC67" "girl" "\uD83D\uDC68" "man" "\uD83D\uDC69" "woman" "\uD83D\uDC74" "older man" "\uD83D\uDC75" "older woman" "\uD83D\uDC71" "person with blond hair" "\uD83D\uDC7C" "angel" "\uD83D\uDC78" "princess" "\uD83D\uDE3A" "smiley cat" "\uD83D\uDE38" "smile cat" "\uD83D\uDE3B" "heart eyes cat" "\uD83D\uDE3D" "kissing cat" "\uD83D\uDE3C" "smirk cat" "\uD83D\uDE40" "scream cat" "\uD83D\uDE3F" "crying cat face" "\uD83D\uDE39" "joy cat" "\uD83D\uDE3E" "pouting cat" "\uD83D\uDC79" "japanese ogre" "\uD83D\uDC7A" "japanese goblin" "\uD83D\uDE48" "see no evil" "\uD83D\uDE49" "hear no evil" "\uD83D\uDE4A" "speak no evil" "\uD83D\uDC80" "skull" "\uD83D\uDC7D" "alien" "\uD83D\uDCA9" ["hankey" "poop" "shit"] "\uD83D\uDD25" "fire" "\u2728" "sparkles" "\uD83C\uDF1F" "star2" "\uD83D\uDCAB" "dizzy" "\uD83D\uDCA5" ["boom" "collision"] "\uD83D\uDCA2" "anger" "\uD83D\uDCA6" "sweat drops" "\uD83D\uDCA7" "droplet" "\uD83D\uDCA4" "zzz" "\uD83D\uDCA8" "dash" "\uD83D\uDC42" "ear" "\uD83D\uDC40" "eyes" "\uD83D\uDC43" "nose" "\uD83D\uDC45" "tongue" "\uD83D\uDC44" "lips" "\uD83D\uDC4D" ["+1" "thumbsup"] "\uD83D\uDC4E" ["-1" "thumbsdown"] "\uD83D\uDC4C" "ok hand" "\uD83D\uDC4A" ["facepunch" "punch"] "\u270A" "fist" "\u270C\uFE0F" "v" "\uD83D\uDC4B" "wave" "\u270B" ["hand" "raised hand"] "\uD83D\uDC50" "open hands" "\uD83D\uDC46" "point up 2" "\uD83D\uDC47" "point down" "\uD83D\uDC49" "point right" "\uD83D\uDC48" "point left" "\uD83D\uDE4C" "raised hands" "\uD83D\uDE4F" "pray" "\u261D\uFE0F" "point up" "\uD83D\uDC4F" "clap" "\uD83D\uDCAA" "muscle" "\uD83D\uDEB6" "walking" "\uD83C\uDFC3" ["runner" "running"] "\uD83D\uDC83" "dancer" "\uD83D\uDC6B" "couple" "\uD83D\uDC6A" "family" "\uD83D\uDC6C" "two men holding hands" "\uD83D\uDC6D" "two women holding hands" "\uD83D\uDC8F" "couplekiss" "\uD83D\uDC91" "couple with heart" "\uD83D\uDC6F" "dancers" "\uD83D\uDE46" "ok woman" "\uD83D\uDE45" "no good" "\uD83D\uDC81" "information desk person" "\uD83D\uDE4B" "raising hand" "\uD83D\uDC86" "massage" "\uD83D\uDC87" "haircut" "\uD83D\uDC85" "nail care" "\uD83D\uDC70" "bride with veil" "\uD83D\uDE4E" "person with pouting face" "\uD83D\uDE4D" "person frowning" "\uD83D\uDE47" "bow" "\uD83C\uDFA9" "tophat" "\uD83D\uDC51" "crown" "\uD83D\uDC52" "womans hat" "\uD83D\uDC5F" "athletic shoe" "\uD83D\uDC5E" ["man's shoe" "shoe"] "\uD83D\uDC61" "sandal" "\uD83D\uDC60" "high heel" "\uD83D\uDC62" "boot" "\uD83D\uDC55" ["shirt" "t-shirt"] "\uD83D\uDC54" "necktie" "\uD83D\uDC5A" "woman's clothes" "\uD83D\uDC57" "dress" "\uD83C\uDFBD" "running shirt with sash" "\uD83D\uDC56" "jeans" "\uD83D\uDC58" "kimono" "\uD83D\uDC59" "bikini" "\uD83D\uDCBC" "briefcase" "\uD83D\uDC5C" "handbag" "\uD83D\uDC5D" "pouch" "\uD83D\uDC5B" "purse" "\uD83D\uDC53" "eyeglasses" "\uD83C\uDF80" "ribbon" "\uD83C\uDF02" "closed umbrella" "\uD83D\uDC84" "lipstick" "\uD83D\uDC9B" "yellow heart" "\uD83D\uDC99" "blue heart" "\uD83D\uDC9C" "purple heart" "\uD83D\uDC9A" "green heart" "\u2764\uFE0F" "heart" "\uD83D\uDC94" "broken heart" "\uD83D\uDC97" "heartpulse" "\uD83D\uDC93" "heartbeat" "\uD83D\uDC95" "two hearts" "\uD83D\uDC96" "sparkling heart" "\uD83D\uDC9E" "revolving hearts" "\uD83D\uDC98" "cupid" "\uD83D\uDC8C" "love letter" "\uD83D\uDC8B" ["kiss" "*"] "\uD83D\uDC8D" "ring" "\uD83D\uDC8E" "gem" "\uD83D\uDC64" "bust in silhouette" "\uD83D\uDC65" "busts in silhouette" "\uD83D\uDCAC" "speech balloon" "\uD83D\uDC63" "footprints" "\uD83D\uDCAD" "thought balloon" "\uD83D\uDC36" "dog" "\uD83D\uDC3A" "wolf" "\uD83D\uDC31" "cat" "\uD83D\uDC2D" "mouse" "\uD83D\uDC39" "hamster" "\uD83D\uDC30" "rabbit" "\uD83D\uDC38" "frog" "\uD83D\uDC2F" "tiger" "\uD83D\uDC28" "koala" "\uD83D\uDC3B" "bear" "\uD83D\uDC37" "pig" "\uD83D\uDC3D" "pig nose" "\uD83D\uDC2E" "cow" "\uD83D\uDC17" "boar" "\uD83D\uDC35" "monkey face" "\uD83D\uDC12" "monkey" "\uD83D\uDC34" "horse" "\uD83D\uDC11" "sheep" "\uD83D\uDC18" "elephant" "\uD83D\uDC3C" "panda face" "\uD83D\uDC27" "penguin" "\uD83D\uDC26" "bird" "\uD83D\uDC24" "baby chick" "\uD83D\uDC25" "hatched chick" "\uD83D\uDC23" "hatching chick" "\uD83D\uDC14" "chicken" "\uD83D\uDC0D" "snake" "\uD83D\uDC22" "turtle" "\uD83D\uDC1B" "bug" "\uD83D\uDC1D" ["bee" "honeybee"] "\uD83D\uDC1C" "ant" "\uD83D\uDC1E" "beetle" "\uD83D\uDC0C" "snail" "\uD83D\uDC19" "octopus" "\uD83D\uDC1A" "shell" "\uD83D\uDC20" "tropical fish" "\uD83D\uDC1F" "fish" "\uD83D\uDC2C" ["dolphin" "flipper"] "\uD83D\uDC33" "whale" "\uD83D\uDC0B" "whale2" "\uD83D\uDC04" "cow2" "\uD83D\uDC0F" "ram" "\uD83D\uDC00" "rat" "\uD83D\uDC03" "water buffalo" "\uD83D\uDC05" "tiger2" "\uD83D\uDC07" "rabbit2" "\uD83D\uDC09" "dragon" "\uD83D\uDC0E" "racehorse" "\uD83D\uDC10" "goat" "\uD83D\uDC13" "rooster" "\uD83D\uDC15" "dog2" "\uD83D\uDC16" "pig2" "\uD83D\uDC01" "mouse2" "\uD83D\uDC02" "ox" "\uD83D\uDC32" "dragon face" "\uD83D\uDC21" "blowfish" "\uD83D\uDC0A" "crocodile" "\uD83D\uDC2B" "camel" "\uD83D\uDC2A" "dromedary camel" "\uD83D\uDC06" "leopard" "\uD83D\uDC08" "cat2" "\uD83D\uDC29" "poodle" "\uD83D\uDC3E" ["feet" "paw prints"] "\uD83D\uDC90" "bouquet" "\uD83C\uDF38" "cherry blossom" "\uD83C\uDF37" "tulip" "\uD83C\uDF40" "four leaf clover" "\uD83C\uDF39" "rose" "\uD83C\uDF3B" "sunflower" "\uD83C\uDF3A" "hibiscus" "\uD83C\uDF41" "mapleleaf" "\uD83C\uDF43" "leaves" "\uD83C\uDF42" "fallen leaf" "\uD83C\uDF3F" "herb" "\uD83C\uDF3E" "ear of rice" "\uD83C\uDF44" "mushroom" "\uD83C\uDF35" "cactus" "\uD83C\uDF34" "palm tree" "\uD83C\uDF32" "evergreen tree" "\uD83C\uDF33" "deciduous tree" "\uD83C\uDF30" "chestnut" "\uD83C\uDF31" "seedling" "\uD83C\uDF3C" "blossom" "\uD83C\uDF10" "globe with meridians" "\uD83C\uDF1E" "sun with face" "\uD83C\uDF1D" "full moon with face" "\uD83C\uDF1A" "new moon with face" "\uD83C\uDF11" "new moon" "\uD83C\uDF12" "waxing crescent moon" "\uD83C\uDF13" "first quarter moon" "\uD83C\uDF14" ["moon" "waxing gibbous moon"] "\uD83C\uDF15" "full moon" "\uD83C\uDF16" "waning gibbous moon" "\uD83C\uDF17" "last quarter moon" "\uD83C\uDF18" "waning crescent moon" "\uD83C\uDF1C" "last quarter moon with face" "\uD83C\uDF1B" "first quarter moon with face" "\uD83C\uDF19" "crescent moon" "\uD83C\uDF0D" "earth africa" "\uD83C\uDF0E" "earth americas" "\uD83C\uDF0F" "earth asia" "\uD83C\uDF0B" "volcano" "\uD83C\uDF0C" "milky way" "\uD83C\uDF20" "stars" "\u2B50" "star" "\u2600\uFE0F" "sunny" "\u26C5" "partly sunny" "\u2601\uFE0F" "cloud" "\u26A1" "zap" "\u2614" "umbrella" "\u2744\uFE0F" "snowflake" "\u26C4" "snowman" "\uD83C\uDF00" "cyclone" "\uD83C\uDF01" "foggy" "\uD83C\uDF08" "rainbow" "\uD83C\uDF0A" "ocean" "\uD83C\uDF8D" "bamboo" "\uD83D\uDC9D" "gift heart" "\uD83C\uDF8E" "dolls" "\uD83C\uDF92" "school satchel" "\uD83C\uDF93" "mortar board" "\uD83C\uDF8F" "flags" "\uD83C\uDF86" "fireworks" "\uD83C\uDF87" "sparkler" "\uD83C\uDF90" "wind chime" "\uD83C\uDF91" "rice scene" "\uD83C\uDF83" "jack-o-lantern" "\uD83D\uDC7B" "ghost" "\uD83C\uDF85" "santa" "\uD83C\uDF84" "christmas tree" "\uD83C\uDF81" "gift" "\uD83C\uDF8B" "tanabata tree" "\uD83C\uDF89" "tada" "\uD83C\uDF8A" "confetti ball" "\uD83C\uDF88" "balloon" "\uD83C\uDF8C" "crossed flags" "\uD83D\uDD2E" "crystal ball" "\uD83C\uDFA5" "movie camera" "\uD83D\uDCF7" "camera" "\uD83D\uDCF9" "video camera" "\uD83D\uDCFC" "vhs" "\uD83D\uDCBF" "cd" "\uD83D\uDCC0" "dvd" "\uD83D\uDCBD" "minidisc" "\uD83D\uDCBE" "floppy disk" "\uD83D\uDCBB" "computer" "\uD83D\uDCF1" "iphone" "\u260E\uFE0F" ["phone" "telephone"] "\uD83D\uDCDE" "telephone receiver" "\uD83D\uDCDF" "pager" "\uD83D\uDCE0" "fax" "\uD83D\uDCE1" "satellite" "\uD83D\uDCFA" "tv" "\uD83D\uDCFB" "radio" "\uD83D\uDD0A" "loud sound" "\uD83D\uDD09" "sound" "\uD83D\uDD08" "speaker" "\uD83D\uDD07" "mute" "\uD83D\uDD14" "bell" "\uD83D\uDD15" "no bell" "\uD83D\uDCE2" "loudspeaker" "\uD83D\uDCE3" "mega" "\u23F3" "hourglass flowing sand" "\u231B" "hourglass" "\u23F0" "alarm clock" "\u231A" "watch" "\uD83D\uDD13" "unlock" "\uD83D\uDD12" "lock" "\uD83D\uDD0F" "lock with ink pen" "\uD83D\uDD10" "closed lock with key" "\uD83D\uDD11" "key" "\uD83D\uDD0E" "mag right" "\uD83D\uDCA1" "bulb" "\uD83D\uDD26" "flashlight" "\uD83D\uDD06" "high brightness" "\uD83D\uDD05" "low brightness" "\uD83D\uDD0C" "electric plug" "\uD83D\uDD0B" "battery" "\uD83D\uDD0D" "mag" "\uD83D\uDEC1" "bathtub" "\uD83D\uDEC0" "bath" "\uD83D\uDEBF" "shower" "\uD83D\uDEBD" "toilet" "\uD83D\uDD27" "wrench" "\uD83D\uDD29" "nut and bolt" "\uD83D\uDD28" "hammer" "\uD83D\uDEAA" "door" "\uD83D\uDEAC" "smoking" "\uD83D\uDCA3" "bomb" "\uD83D\uDD2B" "gun" "\uD83D\uDD2A" ["hocho" "knife"] "\uD83D\uDC8A" "pill" "\uD83D\uDC89" "syringe" "\uD83D\uDCB0" "moneybag" "\uD83D\uDCB4" "yen" "\uD83D\uDCB5" "dollar" "\uD83D\uDCB7" "pound" "\uD83D\uDCB6" "euro" "\uD83D\uDCB3" "credit card" "\uD83D\uDCB8" "money with wings" "\uD83D\uDCF2" "calling" "\uD83D\uDCE7" "e-mail" "\uD83D\uDCE5" "inbox tray" "\uD83D\uDCE4" "outbox tray" "\u2709\uFE0F" ["email" "envelope"] "\uD83D\uDCE9" "envelope with arrow" "\uD83D\uDCE8" "incoming envelope" "\uD83D\uDCEF" "postal horn" "\uD83D\uDCEB" "mailbox" "\uD83D\uDCEA" "mailbox closed" "\uD83D\uDCEC" "mailbox with mail" "\uD83D\uDCED" "mailbox with no mail" "\uD83D\uDCEE" "postbox" "\uD83D\uDCE6" "package" "\uD83D\uDCDD" ["memo" "pencil"] "\uD83D\uDCC4" "page facing up" "\uD83D\uDCC3" "page with curl" "\uD83D\uDCD1" "bookmark tabs" "\uD83D\uDCCA" "bar chart" "\uD83D\uDCC8" "chart with upwards trend" "\uD83D\uDCC9" "chart with downwards trend" "\uD83D\uDCDC" "scroll" "\uD83D\uDCCB" "clipboard" "\uD83D\uDCC5" "date" "\uD83D\uDCC6" "calendar" "\uD83D\uDCC7" "card index" "\uD83D\uDCC1" "file folder" "\uD83D\uDCC2" "open file folder" "\u2702\uFE0F" "scissors" "\uD83D\uDCCC" "pushpin" "\uD83D\uDCCE" "paperclip" "\u2712\uFE0F" "black nib" "\u270F\uFE0F" "pencil2" "\uD83D\uDCCF" "straight ruler" "\uD83D\uDCD0" "triangular ruler" "\uD83D\uDCD5" "closed book" "\uD83D\uDCD7" "green book" "\uD83D\uDCD8" "blue book" "\uD83D\uDCD9" "orange book" "\uD83D\uDCD3" "notebook" "\uD83D\uDCD4" "notebook with decorative cover" "\uD83D\uDCD2" "ledger" "\uD83D\uDCDA" "books" "\uD83D\uDCD6" ["book" "open book"] "\uD83D\uDD16" "bookmark" "\uD83D\uDCDB" "name badge" "\uD83D\uDD2C" "microscope" "\uD83D\uDD2D" "telescope" "\uD83D\uDCF0" "newspaper" "\uD83C\uDFA8" "art" "\uD83C\uDFAC" "clapper" "\uD83C\uDFA4" "microphone" "\uD83C\uDFA7" "headphones" "\uD83C\uDFBC" "musical score" "\uD83C\uDFB5" "musical note" "\uD83C\uDFB6" "notes" "\uD83C\uDFB9" "musical keyboard" "\uD83C\uDFBB" "violin" "\uD83C\uDFBA" "trumpet" "\uD83C\uDFB7" "saxophone" "\uD83C\uDFB8" "guitar" "\uD83D\uDC7E" "space invader" "\uD83C\uDFAE" "video game" "\uD83C\uDCCF" "black joker" "\uD83C\uDFB4" "flower playing cards" "\uD83C\uDC04" "mahjong" "\uD83C\uDFB2" "game die" "\uD83C\uDFAF" "dart" "\uD83C\uDFC8" "football" "\uD83C\uDFC0" "basketball" "\u26BD" "soccer" "\u26BE\uFE0F" "baseball" "\uD83C\uDFBE" "tennis" "\uD83C\uDFB1" "8ball" "\uD83C\uDFC9" "rugby football" "\uD83C\uDFB3" "bowling" "\u26F3" "golf" "\uD83D\uDEB5" "mountain bicyclist" "\uD83D\uDEB4" "bicyclist" "\uD83C\uDFC1" "checkered flag" "\uD83C\uDFC7" "horse racing" "\uD83C\uDFC6" "trophy" "\uD83C\uDFBF" "ski" "\uD83C\uDFC2" "snowboarder" "\uD83C\uDFCA" "swimmer" "\uD83C\uDFC4" "surfer" "\uD83C\uDFA3" "fishing pole and fish" "\u2615" "coffee" "\uD83C\uDF75" "tea" "\uD83C\uDF76" "sake" "\uD83C\uDF7C" "baby bottle" "\uD83C\uDF7A" "beer" "\uD83C\uDF7B" "beers" "\uD83C\uDF78" "cocktail" "\uD83C\uDF79" "tropical drink" "\uD83C\uDF77" "wine glass" "\uD83C\uDF74" "fork and knife" "\uD83C\uDF55" "pizza" "\uD83C\uDF54" "hamburger" "\uD83C\uDF5F" "fries" "\uD83C\uDF57" "poultry leg" "\uD83C\uDF56" "meat on bone" "\uD83C\uDF5D" "spaghetti" "\uD83C\uDF5B" "curry" "\uD83C\uDF64" "fried shrimp" "\uD83C\uDF71" "bento" "\uD83C\uDF63" "sushi" "\uD83C\uDF65" "fish cake" "\uD83C\uDF59" "rice ball" "\uD83C\uDF58" "rice cracker" "\uD83C\uDF5A" "rice" "\uD83C\uDF5C" "ramen" "\uD83C\uDF72" "stew" "\uD83C\uDF62" "oden" "\uD83C\uDF61" "dango" "\uD83C\uDF73" "egg" "\uD83C\uDF5E" "bread" "\uD83C\uDF69" "doughnut" "\uD83C\uDF6E" "custard" "\uD83C\uDF66" "icecream" "\uD83C\uDF68" "ice cream" "\uD83C\uDF67" "shaved ice" "\uD83C\uDF82" "birthday" "\uD83C\uDF70" "cake" "\uD83C\uDF6A" "cookie" "\uD83C\uDF6B" "chocolate bar" "\uD83C\uDF6C" "candy" "\uD83C\uDF6D" "lollipop" "\uD83C\uDF6F" "honey pot" "\uD83C\uDF4E" "apple" "\uD83C\uDF4F" "green apple" "\uD83C\uDF4A" "tangerine" "\uD83C\uDF4B" "lemon" "\uD83C\uDF52" "cherries" "\uD83C\uDF47" "grapes" "\uD83C\uDF49" "watermelon" "\uD83C\uDF53" "strawberry" "\uD83C\uDF51" "peach" "\uD83C\uDF48" "melon" "\uD83C\uDF4C" "banana" "\uD83C\uDF50" "pear" "\uD83C\uDF4D" "pineapple" "\uD83C\uDF60" "sweet potato" "\uD83C\uDF46" "eggplant" "\uD83C\uDF45" "tomato" "\uD83C\uDF3D" "corn" "\uD83C\uDFE0" "house" "\uD83C\uDFE1" "house with garden" "\uD83C\uDFEB" "school" "\uD83C\uDFE2" "office" "\uD83C\uDFE3" "post office" "\uD83C\uDFE5" "hospital" "\uD83C\uDFE6" "bank" "\uD83C\uDFEA" "convenience store" "\uD83C\uDFE9" "love hotel" "\uD83C\uDFE8" "hotel" "\uD83D\uDC92" "wedding" "\u26EA" "church" "\uD83C\uDFEC" "department store" "\uD83C\uDFE4" "european post office" "\uD83C\uDF07" "city sunrise" "\uD83C\uDF06" "city sunset" "\uD83C\uDFEF" "japanese castle" "\uD83C\uDFF0" "european castle" "\u26FA" "tent" "\uD83C\uDFED" "factory" "\uD83D\uDDFC" "tokyo tower" "\uD83D\uDDFE" "japan" "\uD83D\uDDFB" "mount fuji" "\uD83C\uDF04" "sunrise over mountains" "\uD83C\uDF05" "sunrise" "\uD83C\uDF03" "night with stars" "\uD83D\uDDFD" "statue of liberty" "\uD83C\uDF09" "bridge at night" "\uD83C\uDFA0" "carousel horse" "\uD83C\uDFA1" "ferris wheel" "\u26F2" "fountain" "\uD83C\uDFA2" "roller coaster" "\uD83D\uDEA2" "ship" "\u26F5" ["boat" "sailboat"] "\uD83D\uDEA4" "speedboat" "\uD83D\uDEA3" "rowboat" "\u2693" "anchor" "\uD83D\uDE80" "rocket" "\u2708\uFE0F" "airplane" "\uD83D\uDCBA" "seat" "\uD83D\uDE81" "helicopter" "\uD83D\uDE82" "steam locomotive" "\uD83D\uDE8A" "tram" "\uD83D\uDE89" "station" "\uD83D\uDE9E" "mountain railway" "\uD83D\uDE86" "train2" "\uD83D\uDE84" "bullettrain side" "\uD83D\uDE85" "bullettrain front" "\uD83D\uDE88" "light rail" "\uD83D\uDE87" "metro" "\uD83D\uDE9D" "monorail" "\uD83D\uDE8B" "train" "\uD83D\uDE83" "railway car" "\uD83D\uDE8E" "trolleybus" "\uD83D\uDE8C" "bus" "\uD83D\uDE8D" "oncoming bus" "\uD83D\uDE99" "blue car" "\uD83D\uDE98" "oncoming automobile" "\uD83D\uDE97" ["car" "red car"] "\uD83D\uDE95" "taxi" "\uD83D\uDE96" "oncoming taxi" "\uD83D\uDE9B" "articulated lorry" "\uD83D\uDE9A" "truck" "\uD83D\uDEA8" "rotating light" "\uD83D\uDE93" "police car" "\uD83D\uDE94" "oncoming police car" "\uD83D\uDE92" "fire engine" "\uD83D\uDE91" "ambulance" "\uD83D\uDE90" "minibus" "\uD83D\uDEB2" "bike" "\uD83D\uDEA1" "aerial tramway" "\uD83D\uDE9F" "suspension railway" "\uD83D\uDEA0" "mountain cableway" "\uD83D\uDE9C" "tractor" "\uD83D\uDC88" "barber" "\uD83D\uDE8F" "busstop" "\uD83C\uDFAB" "ticket" "\uD83D\uDEA6" "vertical traffic light" "\uD83D\uDEA5" "traffic light" "\u26A0\uFE0F" "warning" "\uD83D\uDEA7" "construction" "\uD83D\uDD30" "beginner" "\u26FD" "fuelpump" "\uD83C\uDFEE" ["izakaya lantern" "lantern"] "\uD83C\uDFB0" "slot machine" "\u2668\uFE0F" "hotsprings" "\uD83D\uDDFF" "moyai" "\uD83C\uDFAA" "circus tent" "\uD83C\uDFAD" "performing arts" "\uD83D\uDCCD" "round pushpin" "\uD83D\uDEA9" "triangular flag on post" "\uD83C\uDDEF\uD83C\uDDF5" "jp" "\uD83C\uDDF0\uD83C\uDDF7" "kr" "\uD83C\uDDE9\uD83C\uDDEA" "de" "\uD83C\uDDE8\uD83C\uDDF3" "cn" "\uD83C\uDDFA\uD83C\uDDF8" "us" "\uD83C\uDDEB\uD83C\uDDF7" "fr" "\uD83C\uDDEA\uD83C\uDDF8" "es" "\uD83C\uDDEE\uD83C\uDDF9" "it" "\uD83C\uDDF7\uD83C\uDDFA" "ru" "\uD83C\uDDEC\uD83C\uDDE7" ["gb" "uk"] "1\uFE0F\u20E3" "one" "2\uFE0F\u20E3" "two" "3\uFE0F\u20E3" "three" "4\uFE0F\u20E3" "four" "5\uFE0F\u20E3" "five" "6\uFE0F\u20E3" "six" "7\uFE0F\u20E3" "seven" "8\uFE0F\u20E3" "eight" "9\uFE0F\u20E3" "nine" "0\uFE0F\u20E3" "zero" "\uD83D\uDD1F" "keycap ten" "\uD83D\uDD22" "1234" "#\uFE0F\u20E3" "hash" "\uD83D\uDD23" "symbols" "\u2B06\uFE0F" "arrow up" "\u2B07\uFE0F" "arrow down" "\u2B05\uFE0F" "arrow left" "\u27A1\uFE0F" "arrow right" "\uD83D\uDD20" "capital abcd" "\uD83D\uDD21" "abcd" "\uD83D\uDD24" "abc" "\u2197\uFE0F" "arrow upper right" "\u2196\uFE0F" "arrow upper left" "\u2198\uFE0F" "arrow lower right" "\u2199\uFE0F" "arrow lower left" "\u2194\uFE0F" "left right arrow" "\u2195\uFE0F" "arrow up down" "\uD83D\uDD04" "arrows counterclockwise" "\u25C0\uFE0F" "arrow backward" "\u25B6\uFE0F" "arrow forward" "\uD83D\uDD3C" "arrow up small" "\uD83D\uDD3D" "arrow down small" "\u21A9\uFE0F" "leftwards arrow with hook" "\u21AA\uFE0F" "arrow right hook" "\u2139\uFE0F" "information source" "\u23EA" "rewind" "\u23E9" "fast forward" "\u23EB" "arrow double up" "\u23EC" "arrow double down" "\u2935\uFE0F" "arrow heading down" "\u2934\uFE0F" "arrow heading up" "\uD83C\uDD97" "ok" "\uD83D\uDD00" "twisted rightwards arrows" "\uD83D\uDD01" "repeat" "\uD83D\uDD02" "repeat one" "\uD83C\uDD95" "new" "\uD83C\uDD99" "up" "\uD83C\uDD92" "cool" "\uD83C\uDD93" "free" "\uD83C\uDD96" "ng" "\uD83D\uDCF6" "signal strength" "\uD83C\uDFA6" "cinema" "\uD83C\uDE01" "koko" "\uD83C\uDE2F" ["u6307" "finger"] "\uD83C\uDE33" ["u7a7a" "empty"] "\uD83C\uDE35" "u6e80" "\uD83C\uDE34" ["u5408" "close"] "\uD83C\uDE32" ["u7981" "ban"] "\uD83C\uDE50" "ideograph advantage" "\uD83C\uDE39" ["u5272" "assignment"] "\uD83C\uDE3A" "u55b6" "\uD83C\uDE36" ["u6709" "have"] "\uD83C\uDE1A" ["u7121" "no"] "\uD83D\uDEBB" "restroom" "\uD83D\uDEB9" "mens" "\uD83D\uDEBA" "womens" "\uD83D\uDEBC" "baby symbol" "\uD83D\uDEBE" "wc" "\uD83D\uDEB0" "potable water" "\uD83D\uDEAE" "put litter in its place" "\uD83C\uDD7F\uFE0F" "parking" "\u267F" "wheelchair" "\uD83D\uDEAD" "no smoking" "\uD83C\uDE37\uFE0F" "u6708" "\uD83C\uDE38" "u7533" "\uD83C\uDE02\uFE0F" "sa" "\u24C2\uFE0F" "m" "\uD83D\uDEC2" "passport control" "\uD83D\uDEC4" "baggage claim" "\uD83D\uDEC5" "left luggage" "\uD83D\uDEC3" "customs" "\uD83C\uDE51" "accept" "\u3299\uFE0F" "secret" "\u3297\uFE0F" "congratulations" "\uD83C\uDD91" "cl" "\uD83C\uDD98" "sos" "\uD83C\uDD94" "id" "\uD83D\uDEAB" "no entry sign" "\uD83D\uDD1E" "underage" "\uD83D\uDCF5" "no mobile phones" "\uD83D\uDEAF" "do not litter" "\uD83D\uDEB1" "non-potable water" "\uD83D\uDEB3" "no bicycles" "\uD83D\uDEB7" "no pedestrians" "\uD83D\uDEB8" "children crossing" "\u26D4" "no entry" "\u2733\uFE0F" "eight spoked asterisk" "\u2747\uFE0F" "sparkle" "\u274E" "negative squared cross mark" "\u2705" "white check mark" "\u2734\uFE0F" "eight pointed black star" "\uD83D\uDC9F" "heart decoration" "\uD83C\uDD9A" "vs" "\uD83D\uDCF3" "vibration mode" "\uD83D\uDCF4" "mobile phone off" "\uD83C\uDD70\uFE0F" "a" "\uD83C\uDD71\uFE0F" "b" "\uD83C\uDD8E" "ab" "\uD83C\uDD7E\uFE0F" "o2" "\uD83D\uDCA0" "diamond shape with a dot inside" "\u27BF" "loop" "\u267B\uFE0F" "recycle" "\u2648" "aries" "\u2649" "taurus" "\u264A" "gemini" "\u264B" "cancer" "\u264C" "leo" "\u264D" "virgo" "\u264E" "libra" "\u264F" "scorpius" "\u2650" "sagittarius" "\u2651" "capricorn" "\u2652" "aquarius" "\u2653" "pisces" "\u26CE" "ophiuchus" "\uD83D\uDD2F" "six pointed star" "\uD83C\uDFE7" "atm" "\uD83D\uDCB9" "chart" "\uD83D\uDCB2" "heavy dollar sign" "\uD83D\uDCB1" "currency exchange" "\u00A9\uFE0F" "copyright" "\u00AE\uFE0F" "registered" "\u2122\uFE0F" "tm" "\u274C" "x" "\u203C\uFE0F" "bangbang" "\u2049\uFE0F" "interrobang" "\u2757" ["exclamation" "heavy exclamation mark"] "\u2753" "question" "\u2755" "grey exclamation" "\u2754" "grey question" "\u2B55" "o" "\uD83D\uDD1D" "top" "\uD83D\uDD1A" "end" "\uD83D\uDD19" "back" "\uD83D\uDD1B" "on" "\uD83D\uDD1C" "soon" "\uD83D\uDD03" "arrows clockwise" "\uD83D\uDD5B" "clock 12" "\uD83D\uDD67" "clock 12:30" "\uD83D\uDD50" "clock 1" "\uD83D\uDD5C" "clock 1:30" "\uD83D\uDD51" "clock 2" "\uD83D\uDD5D" "clock 2:30" "\uD83D\uDD52" "clock 3" "\uD83D\uDD5E" "clock 3:30" "\uD83D\uDD53" "clock 4" "\uD83D\uDD5F" "clock 4:30" "\uD83D\uDD54" "clock 5" "\uD83D\uDD60" "clock 5:30" "\uD83D\uDD55" "clock 6" "\uD83D\uDD56" "clock 7" "\uD83D\uDD57" "clock 8" "\uD83D\uDD58" "clock 9" "\uD83D\uDD59" "clock 10" "\uD83D\uDD5A" "clock 11" "\uD83D\uDD61" "clock 6:30" "\uD83D\uDD62" "clock 7:30" "\uD83D\uDD63" "clock 8:30" "\uD83D\uDD64" "clock 9:30" "\uD83D\uDD65" "clock 10:30" "\uD83D\uDD66" "clock 11:30" "\u2716\uFE0F" "heavy multiplication x" "\u2795" "heavy plus sign" "\u2796" "heavy minus sign" "\u2797" "heavy division sign" "\u2660\uFE0F" "spades" "\u2665\uFE0F" "hearts" "\u2663\uFE0F" "clubs" "\u2666\uFE0F" "diamonds" "\uD83D\uDCAE" "white flower" "\uD83D\uDCAF" "100" "\u2714\uFE0F" "heavy check mark" "\u2611\uFE0F" "ballot box with check" "\uD83D\uDD18" "radio button" "\uD83D\uDD17" "link" "\u27B0" "curly loop" "\u3030\uFE0F" "wavy dash" "\u303D\uFE0F" "part alternation mark" "\uD83D\uDD31" "trident" "\u25FC\uFE0F" "black medium square" "\u25FB\uFE0F" "white medium square" "\u25FE" "black medium small square" "\u25FD" "white medium small square" "\u25AA\uFE0F" "black small square" "\u25AB\uFE0F" "white small square" "\uD83D\uDD3A" "small red triangle" "\uD83D\uDD32" "black square button" "\uD83D\uDD33" "white square button" "\u26AB" "black circle" "\u26AA" "white circle" "\uD83D\uDD34" "red circle" "\uD83D\uDD35" "large blue circle" "\uD83D\uDD3B" "small red triangle down" "\u2B1C" "white large square" "\u2B1B" "black large square" "\uD83D\uDD36" "large orange diamond" "\uD83D\uDD37" "large blue diamond" "\uD83D\uDD38" "small orange diamond" "\uD83D\uDD39" "small blue diamond"})
110623
;; ClojureScript by <NAME> <<EMAIL>> (ns potato.emoji (:require [om.dom :include-macros true])) (declare unicode-to-aliases) (defn get-name [alias] (condp = (type alias) js/String alias cljs.core/PersistentVector (first alias) "")) (defn span [item] (om.dom/span nil (om.dom/span #js {:className "emoji"} (:text item)) (get-name (:id item)))) (def unicode-to-aliases {"\uD83D\uDE04" ["smile" ")" "-)"] "\uD83D\uDE03" "smiley" "\uD83D\uDE00" "grinning" "\uD83D\uDE0A" "blush" "\u263A\uFE0F" "relaxed" "\uD83D\uDE09" "wink" "\uD83D\uDE0D" "heart eyes" "\uD83D\uDE18" "kissing heart" "\uD83D\uDE1A" "kissing closed eyes" "\uD83D\uDE17" "kissing" "\uD83D\uDE19" "kissing smiling eyes" "\uD83D\uDE1C" ["stuck out tongue winking eye" "p" "-p"] "\uD83D\uDE1D" "stuck out tongue closed eyes" "\uD83D\uDE1B" "stuck out tongue" "\uD83D\uDE33" "flushed" "\uD83D\uDE01" "grin" "\uD83D\uDE14" "pensive" "\uD83D\uDE0C" "relieved" "\uD83D\uDE12" "unamused" "\uD83D\uDE1E" ["disappointed" "("] "\uD83D\uDE23" "persevere" "\uD83D\uDE22" "cry" "\uD83D\uDE02" "joy" "\uD83D\uDE2D" "sob" "\uD83D\uDE2A" "sleepy" "\uD83D\uDE25" "disappointed relieved" "\uD83D\uDE30" "cold sweat" "\uD83D\uDE05" "sweat smile" "\uD83D\uDE13" "sweat" "\uD83D\uDE29" "weary" "\uD83D\uDE2B" "tired face" "\uD83D\uDE28" "fearful" "\uD83D\uDE31" "scream" "\uD83D\uDE20" "angry" "\uD83D\uDE21" "rage" "\uD83D\uDE24" "triumph" "\uD83D\uDE16" "confounded" "\uD83D\uDE06" ["laughing" "satisfied"] "\uD83D\uDE0B" "yum" "\uD83D\uDE37" "mask" "\uD83D\uDE0E" ["sunglasses" "cool"] "\uD83D\uDE34" "sleeping" "\uD83D\uDE35" "dizzy face" "\uD83D\uDE32" "astonished" "\uD83D\uDE1F" "worried" "\uD83D\uDE26" "frowning" "\uD83D\uDE27" "anguished" "\uD83D\uDE08" "smiling imp" "\uD83D\uDC7F" "imp" "\uD83D\uDE2E" "open mouth" "\uD83D\uDE2C" "grimacing" "\uD83D\uDE10" "neutral face" "\uD83D\uDE15" ["confused" "/"] "\uD83D\uDE2F" "hushed" "\uD83D\uDE36" "no mouth" "\uD83D\uDE07" "innocent" "\uD83D\uDE0F" "smirk" "\uD83D\uDE11" "expressionless" "\uD83D\uDC72" "man with gua pi mao" "\uD83D\uDC73" "man with turban" "\uD83D\uDC6E" "cop" "\uD83D\uDC77" "construction worker" "\uD83D\uDC82" "<NAME>ardsman" "\uD83D\uDC76" "baby" "\uD83D\uDC66" "boy" "\uD83D\uDC67" "girl" "\uD83D\uDC68" "man" "\uD83D\uDC69" "woman" "\uD83D\uDC74" "older man" "\uD83D\uDC75" "older woman" "\uD83D\uDC71" "person with blond hair" "\uD83D\uDC7C" "angel" "\uD83D\uDC78" "princess" "\uD83D\uDE3A" "smiley cat" "\uD83D\uDE38" "smile cat" "\uD83D\uDE3B" "heart eyes cat" "\uD83D\uDE3D" "kissing cat" "\uD83D\uDE3C" "smirk cat" "\uD83D\uDE40" "scream cat" "\uD83D\uDE3F" "crying cat face" "\uD83D\uDE39" "joy cat" "\uD83D\uDE3E" "pouting cat" "\uD83D\uDC79" "japanese ogre" "\uD83D\uDC7A" "japanese goblin" "\uD83D\uDE48" "see no evil" "\uD83D\uDE49" "hear no evil" "\uD83D\uDE4A" "speak no evil" "\uD83D\uDC80" "skull" "\uD83D\uDC7D" "alien" "\uD83D\uDCA9" ["hankey" "poop" "shit"] "\uD83D\uDD25" "fire" "\u2728" "sparkles" "\uD83C\uDF1F" "star2" "\uD83D\uDCAB" "dizzy" "\uD83D\uDCA5" ["boom" "collision"] "\uD83D\uDCA2" "anger" "\uD83D\uDCA6" "sweat drops" "\uD83D\uDCA7" "droplet" "\uD83D\uDCA4" "zzz" "\uD83D\uDCA8" "dash" "\uD83D\uDC42" "ear" "\uD83D\uDC40" "eyes" "\uD83D\uDC43" "nose" "\uD83D\uDC45" "tongue" "\uD83D\uDC44" "lips" "\uD83D\uDC4D" ["+1" "thumbsup"] "\uD83D\uDC4E" ["-1" "thumbsdown"] "\uD83D\uDC4C" "ok hand" "\uD83D\uDC4A" ["facepunch" "punch"] "\u270A" "fist" "\u270C\uFE0F" "v" "\uD83D\uDC4B" "wave" "\u270B" ["hand" "raised hand"] "\uD83D\uDC50" "open hands" "\uD83D\uDC46" "point up 2" "\uD83D\uDC47" "point down" "\uD83D\uDC49" "point right" "\uD83D\uDC48" "point left" "\uD83D\uDE4C" "raised hands" "\uD83D\uDE4F" "pray" "\u261D\uFE0F" "point up" "\uD83D\uDC4F" "clap" "\uD83D\uDCAA" "muscle" "\uD83D\uDEB6" "walking" "\uD83C\uDFC3" ["runner" "running"] "\uD83D\uDC83" "<NAME>" "\uD83D\uDC6B" "couple" "\uD83D\uDC6A" "family" "\uD83D\uDC6C" "two men holding hands" "\uD83D\uDC6D" "two women holding hands" "\uD83D\uDC8F" "couplekiss" "\uD83D\uDC91" "couple with heart" "\uD83D\uDC6F" "<NAME>" "\uD83D\uDE46" "ok woman" "\uD83D\uDE45" "no good" "\uD83D\uDC81" "information desk person" "\uD83D\uDE4B" "raising hand" "\uD83D\uDC86" "massage" "\uD83D\uDC87" "haircut" "\uD83D\uDC85" "nail care" "\uD83D\uDC70" "bride with veil" "\uD83D\uDE4E" "person with pouting face" "\uD83D\uDE4D" "person frowning" "\uD83D\uDE47" "bow" "\uD83C\uDFA9" "tophat" "\uD83D\uDC51" "crown" "\uD83D\uDC52" "womans hat" "\uD83D\uDC5F" "athletic shoe" "\uD83D\uDC5E" ["man's shoe" "shoe"] "\uD83D\uDC61" "sandal" "\uD83D\uDC60" "high heel" "\uD83D\uDC62" "boot" "\uD83D\uDC55" ["shirt" "t-shirt"] "\uD83D\uDC54" "necktie" "\uD83D\uDC5A" "woman's clothes" "\uD83D\uDC57" "dress" "\uD83C\uDFBD" "running shirt with sash" "\uD83D\uDC56" "jeans" "\uD83D\uDC58" "kimono" "\uD83D\uDC59" "bikini" "\uD83D\uDCBC" "briefcase" "\uD83D\uDC5C" "handbag" "\uD83D\uDC5D" "pouch" "\uD83D\uDC5B" "purse" "\uD83D\uDC53" "eyeglasses" "\uD83C\uDF80" "ribbon" "\uD83C\uDF02" "closed umbrella" "\uD83D\uDC84" "lipstick" "\uD83D\uDC9B" "yellow heart" "\uD83D\uDC99" "blue heart" "\uD83D\uDC9C" "purple heart" "\uD83D\uDC9A" "green heart" "\u2764\uFE0F" "heart" "\uD83D\uDC94" "broken heart" "\uD83D\uDC97" "heartpulse" "\uD83D\uDC93" "heartbeat" "\uD83D\uDC95" "two hearts" "\uD83D\uDC96" "sparkling heart" "\uD83D\uDC9E" "revolving hearts" "\uD83D\uDC98" "cupid" "\uD83D\uDC8C" "love letter" "\uD83D\uDC8B" ["kiss" "*"] "\uD83D\uDC8D" "ring" "\uD83D\uDC8E" "gem" "\uD83D\uDC64" "bust in silhouette" "\uD83D\uDC65" "busts in silhouette" "\uD83D\uDCAC" "speech balloon" "\uD83D\uDC63" "footprints" "\uD83D\uDCAD" "thought balloon" "\uD83D\uDC36" "dog" "\uD83D\uDC3A" "wolf" "\uD83D\uDC31" "cat" "\uD83D\uDC2D" "mouse" "\uD83D\uDC39" "hamster" "\uD83D\uDC30" "rabbit" "\uD83D\uDC38" "frog" "\uD83D\uDC2F" "tiger" "\uD83D\uDC28" "koala" "\uD83D\uDC3B" "bear" "\uD83D\uDC37" "pig" "\uD83D\uDC3D" "pig nose" "\uD83D\uDC2E" "cow" "\uD83D\uDC17" "boar" "\uD83D\uDC35" "monkey face" "\uD83D\uDC12" "monkey" "\uD83D\uDC34" "horse" "\uD83D\uDC11" "sheep" "\uD83D\uDC18" "elephant" "\uD83D\uDC3C" "panda face" "\uD83D\uDC27" "penguin" "\uD83D\uDC26" "bird" "\uD83D\uDC24" "baby chick" "\uD83D\uDC25" "hatched chick" "\uD83D\uDC23" "hatching chick" "\uD83D\uDC14" "chicken" "\uD83D\uDC0D" "snake" "\uD83D\uDC22" "turtle" "\uD83D\uDC1B" "bug" "\uD83D\uDC1D" ["bee" "honeybee"] "\uD83D\uDC1C" "ant" "\uD83D\uDC1E" "beetle" "\uD83D\uDC0C" "snail" "\uD83D\uDC19" "octopus" "\uD83D\uDC1A" "shell" "\uD83D\uDC20" "tropical fish" "\uD83D\uDC1F" "fish" "\uD83D\uDC2C" ["dolphin" "flipper"] "\uD83D\uDC33" "whale" "\uD83D\uDC0B" "whale2" "\uD83D\uDC04" "cow2" "\uD83D\uDC0F" "ram" "\uD83D\uDC00" "rat" "\uD83D\uDC03" "water buffalo" "\uD83D\uDC05" "tiger2" "\uD83D\uDC07" "rabbit2" "\uD83D\uDC09" "dragon" "\uD83D\uDC0E" "racehorse" "\uD83D\uDC10" "goat" "\uD83D\uDC13" "rooster" "\uD83D\uDC15" "dog2" "\uD83D\uDC16" "pig2" "\uD83D\uDC01" "mouse2" "\uD83D\uDC02" "ox" "\uD83D\uDC32" "dragon face" "\uD83D\uDC21" "blowfish" "\uD83D\uDC0A" "crocodile" "\uD83D\uDC2B" "camel" "\uD83D\uDC2A" "dromedary camel" "\uD83D\uDC06" "leopard" "\uD83D\uDC08" "cat2" "\uD83D\uDC29" "poodle" "\uD83D\uDC3E" ["feet" "paw prints"] "\uD83D\uDC90" "bouquet" "\uD83C\uDF38" "cherry blossom" "\uD83C\uDF37" "tulip" "\uD83C\uDF40" "four leaf clover" "\uD83C\uDF39" "rose" "\uD83C\uDF3B" "sunflower" "\uD83C\uDF3A" "hibiscus" "\uD83C\uDF41" "mapleleaf" "\uD83C\uDF43" "leaves" "\uD83C\uDF42" "fallen leaf" "\uD83C\uDF3F" "herb" "\uD83C\uDF3E" "ear of rice" "\uD83C\uDF44" "mushroom" "\uD83C\uDF35" "cactus" "\uD83C\uDF34" "palm tree" "\uD83C\uDF32" "evergreen tree" "\uD83C\uDF33" "deciduous tree" "\uD83C\uDF30" "chestnut" "\uD83C\uDF31" "seedling" "\uD83C\uDF3C" "blossom" "\uD83C\uDF10" "globe with meridians" "\uD83C\uDF1E" "sun with face" "\uD83C\uDF1D" "full moon with face" "\uD83C\uDF1A" "new moon with face" "\uD83C\uDF11" "new moon" "\uD83C\uDF12" "waxing crescent moon" "\uD83C\uDF13" "first quarter moon" "\uD83C\uDF14" ["moon" "waxing gibbous moon"] "\uD83C\uDF15" "full moon" "\uD83C\uDF16" "waning gibbous moon" "\uD83C\uDF17" "last quarter moon" "\uD83C\uDF18" "waning crescent moon" "\uD83C\uDF1C" "last quarter moon with face" "\uD83C\uDF1B" "first quarter moon with face" "\uD83C\uDF19" "crescent moon" "\uD83C\uDF0D" "earth africa" "\uD83C\uDF0E" "earth americas" "\uD83C\uDF0F" "earth asia" "\uD83C\uDF0B" "volcano" "\uD83C\uDF0C" "milky way" "\uD83C\uDF20" "stars" "\u2B50" "star" "\u2600\uFE0F" "sunny" "\u26C5" "partly sunny" "\u2601\uFE0F" "cloud" "\u26A1" "zap" "\u2614" "umbrella" "\u2744\uFE0F" "snowflake" "\u26C4" "snowman" "\uD83C\uDF00" "cyclone" "\uD83C\uDF01" "foggy" "\uD83C\uDF08" "rainbow" "\uD83C\uDF0A" "ocean" "\uD83C\uDF8D" "bamboo" "\uD83D\uDC9D" "gift heart" "\uD83C\uDF8E" "dolls" "\uD83C\uDF92" "school satchel" "\uD83C\uDF93" "mortar board" "\uD83C\uDF8F" "flags" "\uD83C\uDF86" "fireworks" "\uD83C\uDF87" "sparkler" "\uD83C\uDF90" "wind chime" "\uD83C\uDF91" "rice scene" "\uD83C\uDF83" "jack-o-lantern" "\uD83D\uDC7B" "ghost" "\uD83C\uDF85" "santa" "\uD83C\uDF84" "christmas tree" "\uD83C\uDF81" "gift" "\uD83C\uDF8B" "tanabata tree" "\uD83C\uDF89" "tada" "\uD83C\uDF8A" "confetti ball" "\uD83C\uDF88" "balloon" "\uD83C\uDF8C" "crossed flags" "\uD83D\uDD2E" "crystal ball" "\uD83C\uDFA5" "movie camera" "\uD83D\uDCF7" "camera" "\uD83D\uDCF9" "video camera" "\uD83D\uDCFC" "vhs" "\uD83D\uDCBF" "cd" "\uD83D\uDCC0" "dvd" "\uD83D\uDCBD" "minidisc" "\uD83D\uDCBE" "floppy disk" "\uD83D\uDCBB" "computer" "\uD83D\uDCF1" "iphone" "\u260E\uFE0F" ["phone" "telephone"] "\uD83D\uDCDE" "telephone receiver" "\uD83D\uDCDF" "pager" "\uD83D\uDCE0" "fax" "\uD83D\uDCE1" "satellite" "\uD83D\uDCFA" "tv" "\uD83D\uDCFB" "radio" "\uD83D\uDD0A" "loud sound" "\uD83D\uDD09" "sound" "\uD83D\uDD08" "speaker" "\uD83D\uDD07" "mute" "\uD83D\uDD14" "bell" "\uD83D\uDD15" "no bell" "\uD83D\uDCE2" "loudspeaker" "\uD83D\uDCE3" "mega" "\u23F3" "hourglass flowing sand" "\u231B" "hourglass" "\u23F0" "alarm clock" "\u231A" "watch" "\uD83D\uDD13" "unlock" "\uD83D\uDD12" "lock" "\uD83D\uDD0F" "lock with ink pen" "\uD83D\uDD10" "closed lock with key" "\uD83D\uDD11" "key" "\uD83D\uDD0E" "mag right" "\uD83D\uDCA1" "bulb" "\uD83D\uDD26" "flashlight" "\uD83D\uDD06" "high brightness" "\uD83D\uDD05" "low brightness" "\uD83D\uDD0C" "electric plug" "\uD83D\uDD0B" "battery" "\uD83D\uDD0D" "mag" "\uD83D\uDEC1" "bathtub" "\uD83D\uDEC0" "bath" "\uD83D\uDEBF" "shower" "\uD83D\uDEBD" "toilet" "\uD83D\uDD27" "wrench" "\uD83D\uDD29" "nut and bolt" "\uD83D\uDD28" "hammer" "\uD83D\uDEAA" "door" "\uD83D\uDEAC" "smoking" "\uD83D\uDCA3" "bomb" "\uD83D\uDD2B" "gun" "\uD83D\uDD2A" ["hocho" "knife"] "\uD83D\uDC8A" "pill" "\uD83D\uDC89" "syringe" "\uD83D\uDCB0" "moneybag" "\uD83D\uDCB4" "yen" "\uD83D\uDCB5" "dollar" "\uD83D\uDCB7" "pound" "\uD83D\uDCB6" "euro" "\uD83D\uDCB3" "credit card" "\uD83D\uDCB8" "money with wings" "\uD83D\uDCF2" "calling" "\uD83D\uDCE7" "e-mail" "\uD83D\uDCE5" "inbox tray" "\uD83D\uDCE4" "outbox tray" "\u2709\uFE0F" ["email" "envelope"] "\uD83D\uDCE9" "envelope with arrow" "\uD83D\uDCE8" "incoming envelope" "\uD83D\uDCEF" "postal horn" "\uD83D\uDCEB" "mailbox" "\uD83D\uDCEA" "mailbox closed" "\uD83D\uDCEC" "mailbox with mail" "\uD83D\uDCED" "mailbox with no mail" "\uD83D\uDCEE" "postbox" "\uD83D\uDCE6" "package" "\uD83D\uDCDD" ["memo" "pencil"] "\uD83D\uDCC4" "page facing up" "\uD83D\uDCC3" "page with curl" "\uD83D\uDCD1" "bookmark tabs" "\uD83D\uDCCA" "bar chart" "\uD83D\uDCC8" "chart with upwards trend" "\uD83D\uDCC9" "chart with downwards trend" "\uD83D\uDCDC" "scroll" "\uD83D\uDCCB" "clipboard" "\uD83D\uDCC5" "date" "\uD83D\uDCC6" "calendar" "\uD83D\uDCC7" "card index" "\uD83D\uDCC1" "file folder" "\uD83D\uDCC2" "open file folder" "\u2702\uFE0F" "scissors" "\uD83D\uDCCC" "pushpin" "\uD83D\uDCCE" "paperclip" "\u2712\uFE0F" "black nib" "\u270F\uFE0F" "pencil2" "\uD83D\uDCCF" "straight ruler" "\uD83D\uDCD0" "triangular ruler" "\uD83D\uDCD5" "closed book" "\uD83D\uDCD7" "green book" "\uD83D\uDCD8" "blue book" "\uD83D\uDCD9" "orange book" "\uD83D\uDCD3" "notebook" "\uD83D\uDCD4" "notebook with decorative cover" "\uD83D\uDCD2" "ledger" "\uD83D\uDCDA" "books" "\uD83D\uDCD6" ["book" "open book"] "\uD83D\uDD16" "bookmark" "\uD83D\uDCDB" "name badge" "\uD83D\uDD2C" "microscope" "\uD83D\uDD2D" "telescope" "\uD83D\uDCF0" "newspaper" "\uD83C\uDFA8" "art" "\uD83C\uDFAC" "clapper" "\uD83C\uDFA4" "microphone" "\uD83C\uDFA7" "headphones" "\uD83C\uDFBC" "musical score" "\uD83C\uDFB5" "musical note" "\uD83C\uDFB6" "notes" "\uD83C\uDFB9" "musical keyboard" "\uD83C\uDFBB" "violin" "\uD83C\uDFBA" "trumpet" "\uD83C\uDFB7" "saxophone" "\uD83C\uDFB8" "guitar" "\uD83D\uDC7E" "space invader" "\uD83C\uDFAE" "video game" "\uD83C\uDCCF" "black joker" "\uD83C\uDFB4" "flower playing cards" "\uD83C\uDC04" "mahjong" "\uD83C\uDFB2" "game die" "\uD83C\uDFAF" "dart" "\uD83C\uDFC8" "football" "\uD83C\uDFC0" "basketball" "\u26BD" "soccer" "\u26BE\uFE0F" "baseball" "\uD83C\uDFBE" "tennis" "\uD83C\uDFB1" "8ball" "\uD83C\uDFC9" "rugby football" "\uD83C\uDFB3" "bowling" "\u26F3" "golf" "\uD83D\uDEB5" "mountain bicyclist" "\uD83D\uDEB4" "bicyclist" "\uD83C\uDFC1" "checkered flag" "\uD83C\uDFC7" "horse racing" "\uD83C\uDFC6" "trophy" "\uD83C\uDFBF" "ski" "\uD83C\uDFC2" "snowboarder" "\uD83C\uDFCA" "swimmer" "\uD83C\uDFC4" "surfer" "\uD83C\uDFA3" "fishing pole and fish" "\u2615" "coffee" "\uD83C\uDF75" "tea" "\uD83C\uDF76" "sake" "\uD83C\uDF7C" "baby bottle" "\uD83C\uDF7A" "beer" "\uD83C\uDF7B" "beers" "\uD83C\uDF78" "cocktail" "\uD83C\uDF79" "tropical drink" "\uD83C\uDF77" "wine glass" "\uD83C\uDF74" "fork and knife" "\uD83C\uDF55" "pizza" "\uD83C\uDF54" "hamburger" "\uD83C\uDF5F" "fries" "\uD83C\uDF57" "poultry leg" "\uD83C\uDF56" "meat on bone" "\uD83C\uDF5D" "spaghetti" "\uD83C\uDF5B" "curry" "\uD83C\uDF64" "fried shrimp" "\uD83C\uDF71" "bento" "\uD83C\uDF63" "sushi" "\uD83C\uDF65" "fish cake" "\uD83C\uDF59" "rice ball" "\uD83C\uDF58" "rice cracker" "\uD83C\uDF5A" "rice" "\uD83C\uDF5C" "ramen" "\uD83C\uDF72" "stew" "\uD83C\uDF62" "oden" "\uD83C\uDF61" "dango" "\uD83C\uDF73" "egg" "\uD83C\uDF5E" "bread" "\uD83C\uDF69" "doughnut" "\uD83C\uDF6E" "custard" "\uD83C\uDF66" "icecream" "\uD83C\uDF68" "ice cream" "\uD83C\uDF67" "shaved ice" "\uD83C\uDF82" "birthday" "\uD83C\uDF70" "cake" "\uD83C\uDF6A" "cookie" "\uD83C\uDF6B" "chocolate bar" "\uD83C\uDF6C" "candy" "\uD83C\uDF6D" "lollipop" "\uD83C\uDF6F" "honey pot" "\uD83C\uDF4E" "apple" "\uD83C\uDF4F" "green apple" "\uD83C\uDF4A" "tangerine" "\uD83C\uDF4B" "lemon" "\uD83C\uDF52" "cherries" "\uD83C\uDF47" "grapes" "\uD83C\uDF49" "watermelon" "\uD83C\uDF53" "strawberry" "\uD83C\uDF51" "peach" "\uD83C\uDF48" "melon" "\uD83C\uDF4C" "banana" "\uD83C\uDF50" "pear" "\uD83C\uDF4D" "pineapple" "\uD83C\uDF60" "sweet potato" "\uD83C\uDF46" "eggplant" "\uD83C\uDF45" "tomato" "\uD83C\uDF3D" "corn" "\uD83C\uDFE0" "house" "\uD83C\uDFE1" "house with garden" "\uD83C\uDFEB" "school" "\uD83C\uDFE2" "office" "\uD83C\uDFE3" "post office" "\uD83C\uDFE5" "hospital" "\uD83C\uDFE6" "bank" "\uD83C\uDFEA" "convenience store" "\uD83C\uDFE9" "love hotel" "\uD83C\uDFE8" "hotel" "\uD83D\uDC92" "wedding" "\u26EA" "church" "\uD83C\uDFEC" "department store" "\uD83C\uDFE4" "european post office" "\uD83C\uDF07" "city sunrise" "\uD83C\uDF06" "city sunset" "\uD83C\uDFEF" "japanese castle" "\uD83C\uDFF0" "european castle" "\u26FA" "tent" "\uD83C\uDFED" "factory" "\uD83D\uDDFC" "tokyo tower" "\uD83D\uDDFE" "japan" "\uD83D\uDDFB" "mount fuji" "\uD83C\uDF04" "sunrise over mountains" "\uD83C\uDF05" "sunrise" "\uD83C\uDF03" "night with stars" "\uD83D\uDDFD" "statue of liberty" "\uD83C\uDF09" "bridge at night" "\uD83C\uDFA0" "carousel horse" "\uD83C\uDFA1" "ferris wheel" "\u26F2" "fountain" "\uD83C\uDFA2" "roller coaster" "\uD83D\uDEA2" "ship" "\u26F5" ["boat" "sailboat"] "\uD83D\uDEA4" "speedboat" "\uD83D\uDEA3" "rowboat" "\u2693" "anchor" "\uD83D\uDE80" "rocket" "\u2708\uFE0F" "airplane" "\uD83D\uDCBA" "seat" "\uD83D\uDE81" "helicopter" "\uD83D\uDE82" "steam locomotive" "\uD83D\uDE8A" "tram" "\uD83D\uDE89" "station" "\uD83D\uDE9E" "mountain railway" "\uD83D\uDE86" "train2" "\uD83D\uDE84" "bullettrain side" "\uD83D\uDE85" "bullettrain front" "\uD83D\uDE88" "light rail" "\uD83D\uDE87" "metro" "\uD83D\uDE9D" "monorail" "\uD83D\uDE8B" "train" "\uD83D\uDE83" "railway car" "\uD83D\uDE8E" "trolleybus" "\uD83D\uDE8C" "bus" "\uD83D\uDE8D" "oncoming bus" "\uD83D\uDE99" "blue car" "\uD83D\uDE98" "oncoming automobile" "\uD83D\uDE97" ["car" "red car"] "\uD83D\uDE95" "taxi" "\uD83D\uDE96" "oncoming taxi" "\uD83D\uDE9B" "articulated lorry" "\uD83D\uDE9A" "truck" "\uD83D\uDEA8" "rotating light" "\uD83D\uDE93" "police car" "\uD83D\uDE94" "oncoming police car" "\uD83D\uDE92" "fire engine" "\uD83D\uDE91" "ambulance" "\uD83D\uDE90" "minibus" "\uD83D\uDEB2" "bike" "\uD83D\uDEA1" "aerial tramway" "\uD83D\uDE9F" "suspension railway" "\uD83D\uDEA0" "mountain cableway" "\uD83D\uDE9C" "tractor" "\uD83D\uDC88" "barber" "\uD83D\uDE8F" "busstop" "\uD83C\uDFAB" "ticket" "\uD83D\uDEA6" "vertical traffic light" "\uD83D\uDEA5" "traffic light" "\u26A0\uFE0F" "warning" "\uD83D\uDEA7" "construction" "\uD83D\uDD30" "beginner" "\u26FD" "fuelpump" "\uD83C\uDFEE" ["izakaya lantern" "lantern"] "\uD83C\uDFB0" "slot machine" "\u2668\uFE0F" "hotsprings" "\uD83D\uDDFF" "moyai" "\uD83C\uDFAA" "circus tent" "\uD83C\uDFAD" "performing arts" "\uD83D\uDCCD" "round pushpin" "\uD83D\uDEA9" "triangular flag on post" "\uD83C\uDDEF\uD83C\uDDF5" "jp" "\uD83C\uDDF0\uD83C\uDDF7" "kr" "\uD83C\uDDE9\uD83C\uDDEA" "de" "\uD83C\uDDE8\uD83C\uDDF3" "cn" "\uD83C\uDDFA\uD83C\uDDF8" "us" "\uD83C\uDDEB\uD83C\uDDF7" "fr" "\uD83C\uDDEA\uD83C\uDDF8" "es" "\uD83C\uDDEE\uD83C\uDDF9" "it" "\uD83C\uDDF7\uD83C\uDDFA" "ru" "\uD83C\uDDEC\uD83C\uDDE7" ["gb" "uk"] "1\uFE0F\u20E3" "one" "2\uFE0F\u20E3" "two" "3\uFE0F\u20E3" "three" "4\uFE0F\u20E3" "four" "5\uFE0F\u20E3" "five" "6\uFE0F\u20E3" "six" "7\uFE0F\u20E3" "seven" "8\uFE0F\u20E3" "eight" "9\uFE0F\u20E3" "nine" "0\uFE0F\u20E3" "zero" "\uD83D\uDD1F" "keycap ten" "\uD83D\uDD22" "1234" "#\uFE0F\u20E3" "hash" "\uD83D\uDD23" "symbols" "\u2B06\uFE0F" "arrow up" "\u2B07\uFE0F" "arrow down" "\u2B05\uFE0F" "arrow left" "\u27A1\uFE0F" "arrow right" "\uD83D\uDD20" "capital abcd" "\uD83D\uDD21" "abcd" "\uD83D\uDD24" "abc" "\u2197\uFE0F" "arrow upper right" "\u2196\uFE0F" "arrow upper left" "\u2198\uFE0F" "arrow lower right" "\u2199\uFE0F" "arrow lower left" "\u2194\uFE0F" "left right arrow" "\u2195\uFE0F" "arrow up down" "\uD83D\uDD04" "arrows counterclockwise" "\u25C0\uFE0F" "arrow backward" "\u25B6\uFE0F" "arrow forward" "\uD83D\uDD3C" "arrow up small" "\uD83D\uDD3D" "arrow down small" "\u21A9\uFE0F" "leftwards arrow with hook" "\u21AA\uFE0F" "arrow right hook" "\u2139\uFE0F" "information source" "\u23EA" "rewind" "\u23E9" "fast forward" "\u23EB" "arrow double up" "\u23EC" "arrow double down" "\u2935\uFE0F" "arrow heading down" "\u2934\uFE0F" "arrow heading up" "\uD83C\uDD97" "ok" "\uD83D\uDD00" "twisted rightwards arrows" "\uD83D\uDD01" "repeat" "\uD83D\uDD02" "repeat one" "\uD83C\uDD95" "new" "\uD83C\uDD99" "up" "\uD83C\uDD92" "cool" "\uD83C\uDD93" "free" "\uD83C\uDD96" "ng" "\uD83D\uDCF6" "signal strength" "\uD83C\uDFA6" "cinema" "\uD83C\uDE01" "koko" "\uD83C\uDE2F" ["u6307" "finger"] "\uD83C\uDE33" ["u7a7a" "empty"] "\uD83C\uDE35" "u6e80" "\uD83C\uDE34" ["u5408" "close"] "\uD83C\uDE32" ["u7981" "ban"] "\uD83C\uDE50" "ideograph advantage" "\uD83C\uDE39" ["u5272" "assignment"] "\uD83C\uDE3A" "u55b6" "\uD83C\uDE36" ["u6709" "have"] "\uD83C\uDE1A" ["u7121" "no"] "\uD83D\uDEBB" "restroom" "\uD83D\uDEB9" "mens" "\uD83D\uDEBA" "womens" "\uD83D\uDEBC" "baby symbol" "\uD83D\uDEBE" "wc" "\uD83D\uDEB0" "potable water" "\uD83D\uDEAE" "put litter in its place" "\uD83C\uDD7F\uFE0F" "parking" "\u267F" "wheelchair" "\uD83D\uDEAD" "no smoking" "\uD83C\uDE37\uFE0F" "u6708" "\uD83C\uDE38" "u7533" "\uD83C\uDE02\uFE0F" "sa" "\u24C2\uFE0F" "m" "\uD83D\uDEC2" "passport control" "\uD83D\uDEC4" "baggage claim" "\uD83D\uDEC5" "left luggage" "\uD83D\uDEC3" "customs" "\uD83C\uDE51" "accept" "\u3299\uFE0F" "secret" "\u3297\uFE0F" "congratulations" "\uD83C\uDD91" "cl" "\uD83C\uDD98" "sos" "\uD83C\uDD94" "id" "\uD83D\uDEAB" "no entry sign" "\uD83D\uDD1E" "underage" "\uD83D\uDCF5" "no mobile phones" "\uD83D\uDEAF" "do not litter" "\uD83D\uDEB1" "non-potable water" "\uD83D\uDEB3" "no bicycles" "\uD83D\uDEB7" "no pedestrians" "\uD83D\uDEB8" "children crossing" "\u26D4" "no entry" "\u2733\uFE0F" "eight spoked asterisk" "\u2747\uFE0F" "sparkle" "\u274E" "negative squared cross mark" "\u2705" "white check mark" "\u2734\uFE0F" "eight pointed black star" "\uD83D\uDC9F" "heart decoration" "\uD83C\uDD9A" "vs" "\uD83D\uDCF3" "vibration mode" "\uD83D\uDCF4" "mobile phone off" "\uD83C\uDD70\uFE0F" "a" "\uD83C\uDD71\uFE0F" "b" "\uD83C\uDD8E" "ab" "\uD83C\uDD7E\uFE0F" "o2" "\uD83D\uDCA0" "diamond shape with a dot inside" "\u27BF" "loop" "\u267B\uFE0F" "recycle" "\u2648" "aries" "\u2649" "taurus" "\u264A" "gemini" "\u264B" "cancer" "\u264C" "<NAME>" "\u264D" "<NAME>" "\u264E" "<NAME>" "\u264F" "<NAME>orpius" "\u2650" "<NAME>" "\u2651" "<NAME>" "\u2652" "<NAME>" "\u2653" "<NAME>" "\u26CE" "ophiuchus" "\uD83D\uDD2F" "six pointed star" "\uD83C\uDFE7" "atm" "\uD83D\uDCB9" "chart" "\uD83D\uDCB2" "heavy dollar sign" "\uD83D\uDCB1" "currency exchange" "\u00A9\uFE0F" "copyright" "\u00AE\uFE0F" "registered" "\u2122\uFE0F" "tm" "\u274C" "x" "\u203C\uFE0F" "bangbang" "\u2049\uFE0F" "interrobang" "\u2757" ["exclamation" "heavy exclamation mark"] "\u2753" "question" "\u2755" "grey exclamation" "\u2754" "grey question" "\u2B55" "o" "\uD83D\uDD1D" "top" "\uD83D\uDD1A" "end" "\uD83D\uDD19" "back" "\uD83D\uDD1B" "on" "\uD83D\uDD1C" "soon" "\uD83D\uDD03" "arrows clockwise" "\uD83D\uDD5B" "clock 12" "\uD83D\uDD67" "clock 12:30" "\uD83D\uDD50" "clock 1" "\uD83D\uDD5C" "clock 1:30" "\uD83D\uDD51" "clock 2" "\uD83D\uDD5D" "clock 2:30" "\uD83D\uDD52" "clock 3" "\uD83D\uDD5E" "clock 3:30" "\uD83D\uDD53" "clock 4" "\uD83D\uDD5F" "clock 4:30" "\uD83D\uDD54" "clock 5" "\uD83D\uDD60" "clock 5:30" "\uD83D\uDD55" "clock 6" "\uD83D\uDD56" "clock 7" "\uD83D\uDD57" "clock 8" "\uD83D\uDD58" "clock 9" "\uD83D\uDD59" "clock 10" "\uD83D\uDD5A" "clock 11" "\uD83D\uDD61" "clock 6:30" "\uD83D\uDD62" "clock 7:30" "\uD83D\uDD63" "clock 8:30" "\uD83D\uDD64" "clock 9:30" "\uD83D\uDD65" "clock 10:30" "\uD83D\uDD66" "clock 11:30" "\u2716\uFE0F" "heavy multiplication x" "\u2795" "heavy plus sign" "\u2796" "heavy minus sign" "\u2797" "heavy division sign" "\u2660\uFE0F" "spades" "\u2665\uFE0F" "hearts" "\u2663\uFE0F" "clubs" "\u2666\uFE0F" "diamonds" "\uD83D\uDCAE" "white flower" "\uD83D\uDCAF" "100" "\u2714\uFE0F" "heavy check mark" "\u2611\uFE0F" "ballot box with check" "\uD83D\uDD18" "radio button" "\uD83D\uDD17" "link" "\u27B0" "curly loop" "\u3030\uFE0F" "wavy dash" "\u303D\uFE0F" "part alternation mark" "\uD83D\uDD31" "trident" "\u25FC\uFE0F" "black medium square" "\u25FB\uFE0F" "white medium square" "\u25FE" "black medium small square" "\u25FD" "white medium small square" "\u25AA\uFE0F" "black small square" "\u25AB\uFE0F" "white small square" "\uD83D\uDD3A" "small red triangle" "\uD83D\uDD32" "black square button" "\uD83D\uDD33" "white square button" "\u26AB" "black circle" "\u26AA" "white circle" "\uD83D\uDD34" "red circle" "\uD83D\uDD35" "large blue circle" "\uD83D\uDD3B" "small red triangle down" "\u2B1C" "white large square" "\u2B1B" "black large square" "\uD83D\uDD36" "large orange diamond" "\uD83D\uDD37" "large blue diamond" "\uD83D\uDD38" "small orange diamond" "\uD83D\uDD39" "small blue diamond"})
true
;; ClojureScript by PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> (ns potato.emoji (:require [om.dom :include-macros true])) (declare unicode-to-aliases) (defn get-name [alias] (condp = (type alias) js/String alias cljs.core/PersistentVector (first alias) "")) (defn span [item] (om.dom/span nil (om.dom/span #js {:className "emoji"} (:text item)) (get-name (:id item)))) (def unicode-to-aliases {"\uD83D\uDE04" ["smile" ")" "-)"] "\uD83D\uDE03" "smiley" "\uD83D\uDE00" "grinning" "\uD83D\uDE0A" "blush" "\u263A\uFE0F" "relaxed" "\uD83D\uDE09" "wink" "\uD83D\uDE0D" "heart eyes" "\uD83D\uDE18" "kissing heart" "\uD83D\uDE1A" "kissing closed eyes" "\uD83D\uDE17" "kissing" "\uD83D\uDE19" "kissing smiling eyes" "\uD83D\uDE1C" ["stuck out tongue winking eye" "p" "-p"] "\uD83D\uDE1D" "stuck out tongue closed eyes" "\uD83D\uDE1B" "stuck out tongue" "\uD83D\uDE33" "flushed" "\uD83D\uDE01" "grin" "\uD83D\uDE14" "pensive" "\uD83D\uDE0C" "relieved" "\uD83D\uDE12" "unamused" "\uD83D\uDE1E" ["disappointed" "("] "\uD83D\uDE23" "persevere" "\uD83D\uDE22" "cry" "\uD83D\uDE02" "joy" "\uD83D\uDE2D" "sob" "\uD83D\uDE2A" "sleepy" "\uD83D\uDE25" "disappointed relieved" "\uD83D\uDE30" "cold sweat" "\uD83D\uDE05" "sweat smile" "\uD83D\uDE13" "sweat" "\uD83D\uDE29" "weary" "\uD83D\uDE2B" "tired face" "\uD83D\uDE28" "fearful" "\uD83D\uDE31" "scream" "\uD83D\uDE20" "angry" "\uD83D\uDE21" "rage" "\uD83D\uDE24" "triumph" "\uD83D\uDE16" "confounded" "\uD83D\uDE06" ["laughing" "satisfied"] "\uD83D\uDE0B" "yum" "\uD83D\uDE37" "mask" "\uD83D\uDE0E" ["sunglasses" "cool"] "\uD83D\uDE34" "sleeping" "\uD83D\uDE35" "dizzy face" "\uD83D\uDE32" "astonished" "\uD83D\uDE1F" "worried" "\uD83D\uDE26" "frowning" "\uD83D\uDE27" "anguished" "\uD83D\uDE08" "smiling imp" "\uD83D\uDC7F" "imp" "\uD83D\uDE2E" "open mouth" "\uD83D\uDE2C" "grimacing" "\uD83D\uDE10" "neutral face" "\uD83D\uDE15" ["confused" "/"] "\uD83D\uDE2F" "hushed" "\uD83D\uDE36" "no mouth" "\uD83D\uDE07" "innocent" "\uD83D\uDE0F" "smirk" "\uD83D\uDE11" "expressionless" "\uD83D\uDC72" "man with gua pi mao" "\uD83D\uDC73" "man with turban" "\uD83D\uDC6E" "cop" "\uD83D\uDC77" "construction worker" "\uD83D\uDC82" "PI:NAME:<NAME>END_PIardsman" "\uD83D\uDC76" "baby" "\uD83D\uDC66" "boy" "\uD83D\uDC67" "girl" "\uD83D\uDC68" "man" "\uD83D\uDC69" "woman" "\uD83D\uDC74" "older man" "\uD83D\uDC75" "older woman" "\uD83D\uDC71" "person with blond hair" "\uD83D\uDC7C" "angel" "\uD83D\uDC78" "princess" "\uD83D\uDE3A" "smiley cat" "\uD83D\uDE38" "smile cat" "\uD83D\uDE3B" "heart eyes cat" "\uD83D\uDE3D" "kissing cat" "\uD83D\uDE3C" "smirk cat" "\uD83D\uDE40" "scream cat" "\uD83D\uDE3F" "crying cat face" "\uD83D\uDE39" "joy cat" "\uD83D\uDE3E" "pouting cat" "\uD83D\uDC79" "japanese ogre" "\uD83D\uDC7A" "japanese goblin" "\uD83D\uDE48" "see no evil" "\uD83D\uDE49" "hear no evil" "\uD83D\uDE4A" "speak no evil" "\uD83D\uDC80" "skull" "\uD83D\uDC7D" "alien" "\uD83D\uDCA9" ["hankey" "poop" "shit"] "\uD83D\uDD25" "fire" "\u2728" "sparkles" "\uD83C\uDF1F" "star2" "\uD83D\uDCAB" "dizzy" "\uD83D\uDCA5" ["boom" "collision"] "\uD83D\uDCA2" "anger" "\uD83D\uDCA6" "sweat drops" "\uD83D\uDCA7" "droplet" "\uD83D\uDCA4" "zzz" "\uD83D\uDCA8" "dash" "\uD83D\uDC42" "ear" "\uD83D\uDC40" "eyes" "\uD83D\uDC43" "nose" "\uD83D\uDC45" "tongue" "\uD83D\uDC44" "lips" "\uD83D\uDC4D" ["+1" "thumbsup"] "\uD83D\uDC4E" ["-1" "thumbsdown"] "\uD83D\uDC4C" "ok hand" "\uD83D\uDC4A" ["facepunch" "punch"] "\u270A" "fist" "\u270C\uFE0F" "v" "\uD83D\uDC4B" "wave" "\u270B" ["hand" "raised hand"] "\uD83D\uDC50" "open hands" "\uD83D\uDC46" "point up 2" "\uD83D\uDC47" "point down" "\uD83D\uDC49" "point right" "\uD83D\uDC48" "point left" "\uD83D\uDE4C" "raised hands" "\uD83D\uDE4F" "pray" "\u261D\uFE0F" "point up" "\uD83D\uDC4F" "clap" "\uD83D\uDCAA" "muscle" "\uD83D\uDEB6" "walking" "\uD83C\uDFC3" ["runner" "running"] "\uD83D\uDC83" "PI:NAME:<NAME>END_PI" "\uD83D\uDC6B" "couple" "\uD83D\uDC6A" "family" "\uD83D\uDC6C" "two men holding hands" "\uD83D\uDC6D" "two women holding hands" "\uD83D\uDC8F" "couplekiss" "\uD83D\uDC91" "couple with heart" "\uD83D\uDC6F" "PI:NAME:<NAME>END_PI" "\uD83D\uDE46" "ok woman" "\uD83D\uDE45" "no good" "\uD83D\uDC81" "information desk person" "\uD83D\uDE4B" "raising hand" "\uD83D\uDC86" "massage" "\uD83D\uDC87" "haircut" "\uD83D\uDC85" "nail care" "\uD83D\uDC70" "bride with veil" "\uD83D\uDE4E" "person with pouting face" "\uD83D\uDE4D" "person frowning" "\uD83D\uDE47" "bow" "\uD83C\uDFA9" "tophat" "\uD83D\uDC51" "crown" "\uD83D\uDC52" "womans hat" "\uD83D\uDC5F" "athletic shoe" "\uD83D\uDC5E" ["man's shoe" "shoe"] "\uD83D\uDC61" "sandal" "\uD83D\uDC60" "high heel" "\uD83D\uDC62" "boot" "\uD83D\uDC55" ["shirt" "t-shirt"] "\uD83D\uDC54" "necktie" "\uD83D\uDC5A" "woman's clothes" "\uD83D\uDC57" "dress" "\uD83C\uDFBD" "running shirt with sash" "\uD83D\uDC56" "jeans" "\uD83D\uDC58" "kimono" "\uD83D\uDC59" "bikini" "\uD83D\uDCBC" "briefcase" "\uD83D\uDC5C" "handbag" "\uD83D\uDC5D" "pouch" "\uD83D\uDC5B" "purse" "\uD83D\uDC53" "eyeglasses" "\uD83C\uDF80" "ribbon" "\uD83C\uDF02" "closed umbrella" "\uD83D\uDC84" "lipstick" "\uD83D\uDC9B" "yellow heart" "\uD83D\uDC99" "blue heart" "\uD83D\uDC9C" "purple heart" "\uD83D\uDC9A" "green heart" "\u2764\uFE0F" "heart" "\uD83D\uDC94" "broken heart" "\uD83D\uDC97" "heartpulse" "\uD83D\uDC93" "heartbeat" "\uD83D\uDC95" "two hearts" "\uD83D\uDC96" "sparkling heart" "\uD83D\uDC9E" "revolving hearts" "\uD83D\uDC98" "cupid" "\uD83D\uDC8C" "love letter" "\uD83D\uDC8B" ["kiss" "*"] "\uD83D\uDC8D" "ring" "\uD83D\uDC8E" "gem" "\uD83D\uDC64" "bust in silhouette" "\uD83D\uDC65" "busts in silhouette" "\uD83D\uDCAC" "speech balloon" "\uD83D\uDC63" "footprints" "\uD83D\uDCAD" "thought balloon" "\uD83D\uDC36" "dog" "\uD83D\uDC3A" "wolf" "\uD83D\uDC31" "cat" "\uD83D\uDC2D" "mouse" "\uD83D\uDC39" "hamster" "\uD83D\uDC30" "rabbit" "\uD83D\uDC38" "frog" "\uD83D\uDC2F" "tiger" "\uD83D\uDC28" "koala" "\uD83D\uDC3B" "bear" "\uD83D\uDC37" "pig" "\uD83D\uDC3D" "pig nose" "\uD83D\uDC2E" "cow" "\uD83D\uDC17" "boar" "\uD83D\uDC35" "monkey face" "\uD83D\uDC12" "monkey" "\uD83D\uDC34" "horse" "\uD83D\uDC11" "sheep" "\uD83D\uDC18" "elephant" "\uD83D\uDC3C" "panda face" "\uD83D\uDC27" "penguin" "\uD83D\uDC26" "bird" "\uD83D\uDC24" "baby chick" "\uD83D\uDC25" "hatched chick" "\uD83D\uDC23" "hatching chick" "\uD83D\uDC14" "chicken" "\uD83D\uDC0D" "snake" "\uD83D\uDC22" "turtle" "\uD83D\uDC1B" "bug" "\uD83D\uDC1D" ["bee" "honeybee"] "\uD83D\uDC1C" "ant" "\uD83D\uDC1E" "beetle" "\uD83D\uDC0C" "snail" "\uD83D\uDC19" "octopus" "\uD83D\uDC1A" "shell" "\uD83D\uDC20" "tropical fish" "\uD83D\uDC1F" "fish" "\uD83D\uDC2C" ["dolphin" "flipper"] "\uD83D\uDC33" "whale" "\uD83D\uDC0B" "whale2" "\uD83D\uDC04" "cow2" "\uD83D\uDC0F" "ram" "\uD83D\uDC00" "rat" "\uD83D\uDC03" "water buffalo" "\uD83D\uDC05" "tiger2" "\uD83D\uDC07" "rabbit2" "\uD83D\uDC09" "dragon" "\uD83D\uDC0E" "racehorse" "\uD83D\uDC10" "goat" "\uD83D\uDC13" "rooster" "\uD83D\uDC15" "dog2" "\uD83D\uDC16" "pig2" "\uD83D\uDC01" "mouse2" "\uD83D\uDC02" "ox" "\uD83D\uDC32" "dragon face" "\uD83D\uDC21" "blowfish" "\uD83D\uDC0A" "crocodile" "\uD83D\uDC2B" "camel" "\uD83D\uDC2A" "dromedary camel" "\uD83D\uDC06" "leopard" "\uD83D\uDC08" "cat2" "\uD83D\uDC29" "poodle" "\uD83D\uDC3E" ["feet" "paw prints"] "\uD83D\uDC90" "bouquet" "\uD83C\uDF38" "cherry blossom" "\uD83C\uDF37" "tulip" "\uD83C\uDF40" "four leaf clover" "\uD83C\uDF39" "rose" "\uD83C\uDF3B" "sunflower" "\uD83C\uDF3A" "hibiscus" "\uD83C\uDF41" "mapleleaf" "\uD83C\uDF43" "leaves" "\uD83C\uDF42" "fallen leaf" "\uD83C\uDF3F" "herb" "\uD83C\uDF3E" "ear of rice" "\uD83C\uDF44" "mushroom" "\uD83C\uDF35" "cactus" "\uD83C\uDF34" "palm tree" "\uD83C\uDF32" "evergreen tree" "\uD83C\uDF33" "deciduous tree" "\uD83C\uDF30" "chestnut" "\uD83C\uDF31" "seedling" "\uD83C\uDF3C" "blossom" "\uD83C\uDF10" "globe with meridians" "\uD83C\uDF1E" "sun with face" "\uD83C\uDF1D" "full moon with face" "\uD83C\uDF1A" "new moon with face" "\uD83C\uDF11" "new moon" "\uD83C\uDF12" "waxing crescent moon" "\uD83C\uDF13" "first quarter moon" "\uD83C\uDF14" ["moon" "waxing gibbous moon"] "\uD83C\uDF15" "full moon" "\uD83C\uDF16" "waning gibbous moon" "\uD83C\uDF17" "last quarter moon" "\uD83C\uDF18" "waning crescent moon" "\uD83C\uDF1C" "last quarter moon with face" "\uD83C\uDF1B" "first quarter moon with face" "\uD83C\uDF19" "crescent moon" "\uD83C\uDF0D" "earth africa" "\uD83C\uDF0E" "earth americas" "\uD83C\uDF0F" "earth asia" "\uD83C\uDF0B" "volcano" "\uD83C\uDF0C" "milky way" "\uD83C\uDF20" "stars" "\u2B50" "star" "\u2600\uFE0F" "sunny" "\u26C5" "partly sunny" "\u2601\uFE0F" "cloud" "\u26A1" "zap" "\u2614" "umbrella" "\u2744\uFE0F" "snowflake" "\u26C4" "snowman" "\uD83C\uDF00" "cyclone" "\uD83C\uDF01" "foggy" "\uD83C\uDF08" "rainbow" "\uD83C\uDF0A" "ocean" "\uD83C\uDF8D" "bamboo" "\uD83D\uDC9D" "gift heart" "\uD83C\uDF8E" "dolls" "\uD83C\uDF92" "school satchel" "\uD83C\uDF93" "mortar board" "\uD83C\uDF8F" "flags" "\uD83C\uDF86" "fireworks" "\uD83C\uDF87" "sparkler" "\uD83C\uDF90" "wind chime" "\uD83C\uDF91" "rice scene" "\uD83C\uDF83" "jack-o-lantern" "\uD83D\uDC7B" "ghost" "\uD83C\uDF85" "santa" "\uD83C\uDF84" "christmas tree" "\uD83C\uDF81" "gift" "\uD83C\uDF8B" "tanabata tree" "\uD83C\uDF89" "tada" "\uD83C\uDF8A" "confetti ball" "\uD83C\uDF88" "balloon" "\uD83C\uDF8C" "crossed flags" "\uD83D\uDD2E" "crystal ball" "\uD83C\uDFA5" "movie camera" "\uD83D\uDCF7" "camera" "\uD83D\uDCF9" "video camera" "\uD83D\uDCFC" "vhs" "\uD83D\uDCBF" "cd" "\uD83D\uDCC0" "dvd" "\uD83D\uDCBD" "minidisc" "\uD83D\uDCBE" "floppy disk" "\uD83D\uDCBB" "computer" "\uD83D\uDCF1" "iphone" "\u260E\uFE0F" ["phone" "telephone"] "\uD83D\uDCDE" "telephone receiver" "\uD83D\uDCDF" "pager" "\uD83D\uDCE0" "fax" "\uD83D\uDCE1" "satellite" "\uD83D\uDCFA" "tv" "\uD83D\uDCFB" "radio" "\uD83D\uDD0A" "loud sound" "\uD83D\uDD09" "sound" "\uD83D\uDD08" "speaker" "\uD83D\uDD07" "mute" "\uD83D\uDD14" "bell" "\uD83D\uDD15" "no bell" "\uD83D\uDCE2" "loudspeaker" "\uD83D\uDCE3" "mega" "\u23F3" "hourglass flowing sand" "\u231B" "hourglass" "\u23F0" "alarm clock" "\u231A" "watch" "\uD83D\uDD13" "unlock" "\uD83D\uDD12" "lock" "\uD83D\uDD0F" "lock with ink pen" "\uD83D\uDD10" "closed lock with key" "\uD83D\uDD11" "key" "\uD83D\uDD0E" "mag right" "\uD83D\uDCA1" "bulb" "\uD83D\uDD26" "flashlight" "\uD83D\uDD06" "high brightness" "\uD83D\uDD05" "low brightness" "\uD83D\uDD0C" "electric plug" "\uD83D\uDD0B" "battery" "\uD83D\uDD0D" "mag" "\uD83D\uDEC1" "bathtub" "\uD83D\uDEC0" "bath" "\uD83D\uDEBF" "shower" "\uD83D\uDEBD" "toilet" "\uD83D\uDD27" "wrench" "\uD83D\uDD29" "nut and bolt" "\uD83D\uDD28" "hammer" "\uD83D\uDEAA" "door" "\uD83D\uDEAC" "smoking" "\uD83D\uDCA3" "bomb" "\uD83D\uDD2B" "gun" "\uD83D\uDD2A" ["hocho" "knife"] "\uD83D\uDC8A" "pill" "\uD83D\uDC89" "syringe" "\uD83D\uDCB0" "moneybag" "\uD83D\uDCB4" "yen" "\uD83D\uDCB5" "dollar" "\uD83D\uDCB7" "pound" "\uD83D\uDCB6" "euro" "\uD83D\uDCB3" "credit card" "\uD83D\uDCB8" "money with wings" "\uD83D\uDCF2" "calling" "\uD83D\uDCE7" "e-mail" "\uD83D\uDCE5" "inbox tray" "\uD83D\uDCE4" "outbox tray" "\u2709\uFE0F" ["email" "envelope"] "\uD83D\uDCE9" "envelope with arrow" "\uD83D\uDCE8" "incoming envelope" "\uD83D\uDCEF" "postal horn" "\uD83D\uDCEB" "mailbox" "\uD83D\uDCEA" "mailbox closed" "\uD83D\uDCEC" "mailbox with mail" "\uD83D\uDCED" "mailbox with no mail" "\uD83D\uDCEE" "postbox" "\uD83D\uDCE6" "package" "\uD83D\uDCDD" ["memo" "pencil"] "\uD83D\uDCC4" "page facing up" "\uD83D\uDCC3" "page with curl" "\uD83D\uDCD1" "bookmark tabs" "\uD83D\uDCCA" "bar chart" "\uD83D\uDCC8" "chart with upwards trend" "\uD83D\uDCC9" "chart with downwards trend" "\uD83D\uDCDC" "scroll" "\uD83D\uDCCB" "clipboard" "\uD83D\uDCC5" "date" "\uD83D\uDCC6" "calendar" "\uD83D\uDCC7" "card index" "\uD83D\uDCC1" "file folder" "\uD83D\uDCC2" "open file folder" "\u2702\uFE0F" "scissors" "\uD83D\uDCCC" "pushpin" "\uD83D\uDCCE" "paperclip" "\u2712\uFE0F" "black nib" "\u270F\uFE0F" "pencil2" "\uD83D\uDCCF" "straight ruler" "\uD83D\uDCD0" "triangular ruler" "\uD83D\uDCD5" "closed book" "\uD83D\uDCD7" "green book" "\uD83D\uDCD8" "blue book" "\uD83D\uDCD9" "orange book" "\uD83D\uDCD3" "notebook" "\uD83D\uDCD4" "notebook with decorative cover" "\uD83D\uDCD2" "ledger" "\uD83D\uDCDA" "books" "\uD83D\uDCD6" ["book" "open book"] "\uD83D\uDD16" "bookmark" "\uD83D\uDCDB" "name badge" "\uD83D\uDD2C" "microscope" "\uD83D\uDD2D" "telescope" "\uD83D\uDCF0" "newspaper" "\uD83C\uDFA8" "art" "\uD83C\uDFAC" "clapper" "\uD83C\uDFA4" "microphone" "\uD83C\uDFA7" "headphones" "\uD83C\uDFBC" "musical score" "\uD83C\uDFB5" "musical note" "\uD83C\uDFB6" "notes" "\uD83C\uDFB9" "musical keyboard" "\uD83C\uDFBB" "violin" "\uD83C\uDFBA" "trumpet" "\uD83C\uDFB7" "saxophone" "\uD83C\uDFB8" "guitar" "\uD83D\uDC7E" "space invader" "\uD83C\uDFAE" "video game" "\uD83C\uDCCF" "black joker" "\uD83C\uDFB4" "flower playing cards" "\uD83C\uDC04" "mahjong" "\uD83C\uDFB2" "game die" "\uD83C\uDFAF" "dart" "\uD83C\uDFC8" "football" "\uD83C\uDFC0" "basketball" "\u26BD" "soccer" "\u26BE\uFE0F" "baseball" "\uD83C\uDFBE" "tennis" "\uD83C\uDFB1" "8ball" "\uD83C\uDFC9" "rugby football" "\uD83C\uDFB3" "bowling" "\u26F3" "golf" "\uD83D\uDEB5" "mountain bicyclist" "\uD83D\uDEB4" "bicyclist" "\uD83C\uDFC1" "checkered flag" "\uD83C\uDFC7" "horse racing" "\uD83C\uDFC6" "trophy" "\uD83C\uDFBF" "ski" "\uD83C\uDFC2" "snowboarder" "\uD83C\uDFCA" "swimmer" "\uD83C\uDFC4" "surfer" "\uD83C\uDFA3" "fishing pole and fish" "\u2615" "coffee" "\uD83C\uDF75" "tea" "\uD83C\uDF76" "sake" "\uD83C\uDF7C" "baby bottle" "\uD83C\uDF7A" "beer" "\uD83C\uDF7B" "beers" "\uD83C\uDF78" "cocktail" "\uD83C\uDF79" "tropical drink" "\uD83C\uDF77" "wine glass" "\uD83C\uDF74" "fork and knife" "\uD83C\uDF55" "pizza" "\uD83C\uDF54" "hamburger" "\uD83C\uDF5F" "fries" "\uD83C\uDF57" "poultry leg" "\uD83C\uDF56" "meat on bone" "\uD83C\uDF5D" "spaghetti" "\uD83C\uDF5B" "curry" "\uD83C\uDF64" "fried shrimp" "\uD83C\uDF71" "bento" "\uD83C\uDF63" "sushi" "\uD83C\uDF65" "fish cake" "\uD83C\uDF59" "rice ball" "\uD83C\uDF58" "rice cracker" "\uD83C\uDF5A" "rice" "\uD83C\uDF5C" "ramen" "\uD83C\uDF72" "stew" "\uD83C\uDF62" "oden" "\uD83C\uDF61" "dango" "\uD83C\uDF73" "egg" "\uD83C\uDF5E" "bread" "\uD83C\uDF69" "doughnut" "\uD83C\uDF6E" "custard" "\uD83C\uDF66" "icecream" "\uD83C\uDF68" "ice cream" "\uD83C\uDF67" "shaved ice" "\uD83C\uDF82" "birthday" "\uD83C\uDF70" "cake" "\uD83C\uDF6A" "cookie" "\uD83C\uDF6B" "chocolate bar" "\uD83C\uDF6C" "candy" "\uD83C\uDF6D" "lollipop" "\uD83C\uDF6F" "honey pot" "\uD83C\uDF4E" "apple" "\uD83C\uDF4F" "green apple" "\uD83C\uDF4A" "tangerine" "\uD83C\uDF4B" "lemon" "\uD83C\uDF52" "cherries" "\uD83C\uDF47" "grapes" "\uD83C\uDF49" "watermelon" "\uD83C\uDF53" "strawberry" "\uD83C\uDF51" "peach" "\uD83C\uDF48" "melon" "\uD83C\uDF4C" "banana" "\uD83C\uDF50" "pear" "\uD83C\uDF4D" "pineapple" "\uD83C\uDF60" "sweet potato" "\uD83C\uDF46" "eggplant" "\uD83C\uDF45" "tomato" "\uD83C\uDF3D" "corn" "\uD83C\uDFE0" "house" "\uD83C\uDFE1" "house with garden" "\uD83C\uDFEB" "school" "\uD83C\uDFE2" "office" "\uD83C\uDFE3" "post office" "\uD83C\uDFE5" "hospital" "\uD83C\uDFE6" "bank" "\uD83C\uDFEA" "convenience store" "\uD83C\uDFE9" "love hotel" "\uD83C\uDFE8" "hotel" "\uD83D\uDC92" "wedding" "\u26EA" "church" "\uD83C\uDFEC" "department store" "\uD83C\uDFE4" "european post office" "\uD83C\uDF07" "city sunrise" "\uD83C\uDF06" "city sunset" "\uD83C\uDFEF" "japanese castle" "\uD83C\uDFF0" "european castle" "\u26FA" "tent" "\uD83C\uDFED" "factory" "\uD83D\uDDFC" "tokyo tower" "\uD83D\uDDFE" "japan" "\uD83D\uDDFB" "mount fuji" "\uD83C\uDF04" "sunrise over mountains" "\uD83C\uDF05" "sunrise" "\uD83C\uDF03" "night with stars" "\uD83D\uDDFD" "statue of liberty" "\uD83C\uDF09" "bridge at night" "\uD83C\uDFA0" "carousel horse" "\uD83C\uDFA1" "ferris wheel" "\u26F2" "fountain" "\uD83C\uDFA2" "roller coaster" "\uD83D\uDEA2" "ship" "\u26F5" ["boat" "sailboat"] "\uD83D\uDEA4" "speedboat" "\uD83D\uDEA3" "rowboat" "\u2693" "anchor" "\uD83D\uDE80" "rocket" "\u2708\uFE0F" "airplane" "\uD83D\uDCBA" "seat" "\uD83D\uDE81" "helicopter" "\uD83D\uDE82" "steam locomotive" "\uD83D\uDE8A" "tram" "\uD83D\uDE89" "station" "\uD83D\uDE9E" "mountain railway" "\uD83D\uDE86" "train2" "\uD83D\uDE84" "bullettrain side" "\uD83D\uDE85" "bullettrain front" "\uD83D\uDE88" "light rail" "\uD83D\uDE87" "metro" "\uD83D\uDE9D" "monorail" "\uD83D\uDE8B" "train" "\uD83D\uDE83" "railway car" "\uD83D\uDE8E" "trolleybus" "\uD83D\uDE8C" "bus" "\uD83D\uDE8D" "oncoming bus" "\uD83D\uDE99" "blue car" "\uD83D\uDE98" "oncoming automobile" "\uD83D\uDE97" ["car" "red car"] "\uD83D\uDE95" "taxi" "\uD83D\uDE96" "oncoming taxi" "\uD83D\uDE9B" "articulated lorry" "\uD83D\uDE9A" "truck" "\uD83D\uDEA8" "rotating light" "\uD83D\uDE93" "police car" "\uD83D\uDE94" "oncoming police car" "\uD83D\uDE92" "fire engine" "\uD83D\uDE91" "ambulance" "\uD83D\uDE90" "minibus" "\uD83D\uDEB2" "bike" "\uD83D\uDEA1" "aerial tramway" "\uD83D\uDE9F" "suspension railway" "\uD83D\uDEA0" "mountain cableway" "\uD83D\uDE9C" "tractor" "\uD83D\uDC88" "barber" "\uD83D\uDE8F" "busstop" "\uD83C\uDFAB" "ticket" "\uD83D\uDEA6" "vertical traffic light" "\uD83D\uDEA5" "traffic light" "\u26A0\uFE0F" "warning" "\uD83D\uDEA7" "construction" "\uD83D\uDD30" "beginner" "\u26FD" "fuelpump" "\uD83C\uDFEE" ["izakaya lantern" "lantern"] "\uD83C\uDFB0" "slot machine" "\u2668\uFE0F" "hotsprings" "\uD83D\uDDFF" "moyai" "\uD83C\uDFAA" "circus tent" "\uD83C\uDFAD" "performing arts" "\uD83D\uDCCD" "round pushpin" "\uD83D\uDEA9" "triangular flag on post" "\uD83C\uDDEF\uD83C\uDDF5" "jp" "\uD83C\uDDF0\uD83C\uDDF7" "kr" "\uD83C\uDDE9\uD83C\uDDEA" "de" "\uD83C\uDDE8\uD83C\uDDF3" "cn" "\uD83C\uDDFA\uD83C\uDDF8" "us" "\uD83C\uDDEB\uD83C\uDDF7" "fr" "\uD83C\uDDEA\uD83C\uDDF8" "es" "\uD83C\uDDEE\uD83C\uDDF9" "it" "\uD83C\uDDF7\uD83C\uDDFA" "ru" "\uD83C\uDDEC\uD83C\uDDE7" ["gb" "uk"] "1\uFE0F\u20E3" "one" "2\uFE0F\u20E3" "two" "3\uFE0F\u20E3" "three" "4\uFE0F\u20E3" "four" "5\uFE0F\u20E3" "five" "6\uFE0F\u20E3" "six" "7\uFE0F\u20E3" "seven" "8\uFE0F\u20E3" "eight" "9\uFE0F\u20E3" "nine" "0\uFE0F\u20E3" "zero" "\uD83D\uDD1F" "keycap ten" "\uD83D\uDD22" "1234" "#\uFE0F\u20E3" "hash" "\uD83D\uDD23" "symbols" "\u2B06\uFE0F" "arrow up" "\u2B07\uFE0F" "arrow down" "\u2B05\uFE0F" "arrow left" "\u27A1\uFE0F" "arrow right" "\uD83D\uDD20" "capital abcd" "\uD83D\uDD21" "abcd" "\uD83D\uDD24" "abc" "\u2197\uFE0F" "arrow upper right" "\u2196\uFE0F" "arrow upper left" "\u2198\uFE0F" "arrow lower right" "\u2199\uFE0F" "arrow lower left" "\u2194\uFE0F" "left right arrow" "\u2195\uFE0F" "arrow up down" "\uD83D\uDD04" "arrows counterclockwise" "\u25C0\uFE0F" "arrow backward" "\u25B6\uFE0F" "arrow forward" "\uD83D\uDD3C" "arrow up small" "\uD83D\uDD3D" "arrow down small" "\u21A9\uFE0F" "leftwards arrow with hook" "\u21AA\uFE0F" "arrow right hook" "\u2139\uFE0F" "information source" "\u23EA" "rewind" "\u23E9" "fast forward" "\u23EB" "arrow double up" "\u23EC" "arrow double down" "\u2935\uFE0F" "arrow heading down" "\u2934\uFE0F" "arrow heading up" "\uD83C\uDD97" "ok" "\uD83D\uDD00" "twisted rightwards arrows" "\uD83D\uDD01" "repeat" "\uD83D\uDD02" "repeat one" "\uD83C\uDD95" "new" "\uD83C\uDD99" "up" "\uD83C\uDD92" "cool" "\uD83C\uDD93" "free" "\uD83C\uDD96" "ng" "\uD83D\uDCF6" "signal strength" "\uD83C\uDFA6" "cinema" "\uD83C\uDE01" "koko" "\uD83C\uDE2F" ["u6307" "finger"] "\uD83C\uDE33" ["u7a7a" "empty"] "\uD83C\uDE35" "u6e80" "\uD83C\uDE34" ["u5408" "close"] "\uD83C\uDE32" ["u7981" "ban"] "\uD83C\uDE50" "ideograph advantage" "\uD83C\uDE39" ["u5272" "assignment"] "\uD83C\uDE3A" "u55b6" "\uD83C\uDE36" ["u6709" "have"] "\uD83C\uDE1A" ["u7121" "no"] "\uD83D\uDEBB" "restroom" "\uD83D\uDEB9" "mens" "\uD83D\uDEBA" "womens" "\uD83D\uDEBC" "baby symbol" "\uD83D\uDEBE" "wc" "\uD83D\uDEB0" "potable water" "\uD83D\uDEAE" "put litter in its place" "\uD83C\uDD7F\uFE0F" "parking" "\u267F" "wheelchair" "\uD83D\uDEAD" "no smoking" "\uD83C\uDE37\uFE0F" "u6708" "\uD83C\uDE38" "u7533" "\uD83C\uDE02\uFE0F" "sa" "\u24C2\uFE0F" "m" "\uD83D\uDEC2" "passport control" "\uD83D\uDEC4" "baggage claim" "\uD83D\uDEC5" "left luggage" "\uD83D\uDEC3" "customs" "\uD83C\uDE51" "accept" "\u3299\uFE0F" "secret" "\u3297\uFE0F" "congratulations" "\uD83C\uDD91" "cl" "\uD83C\uDD98" "sos" "\uD83C\uDD94" "id" "\uD83D\uDEAB" "no entry sign" "\uD83D\uDD1E" "underage" "\uD83D\uDCF5" "no mobile phones" "\uD83D\uDEAF" "do not litter" "\uD83D\uDEB1" "non-potable water" "\uD83D\uDEB3" "no bicycles" "\uD83D\uDEB7" "no pedestrians" "\uD83D\uDEB8" "children crossing" "\u26D4" "no entry" "\u2733\uFE0F" "eight spoked asterisk" "\u2747\uFE0F" "sparkle" "\u274E" "negative squared cross mark" "\u2705" "white check mark" "\u2734\uFE0F" "eight pointed black star" "\uD83D\uDC9F" "heart decoration" "\uD83C\uDD9A" "vs" "\uD83D\uDCF3" "vibration mode" "\uD83D\uDCF4" "mobile phone off" "\uD83C\uDD70\uFE0F" "a" "\uD83C\uDD71\uFE0F" "b" "\uD83C\uDD8E" "ab" "\uD83C\uDD7E\uFE0F" "o2" "\uD83D\uDCA0" "diamond shape with a dot inside" "\u27BF" "loop" "\u267B\uFE0F" "recycle" "\u2648" "aries" "\u2649" "taurus" "\u264A" "gemini" "\u264B" "cancer" "\u264C" "PI:NAME:<NAME>END_PI" "\u264D" "PI:NAME:<NAME>END_PI" "\u264E" "PI:NAME:<NAME>END_PI" "\u264F" "PI:NAME:<NAME>END_PIorpius" "\u2650" "PI:NAME:<NAME>END_PI" "\u2651" "PI:NAME:<NAME>END_PI" "\u2652" "PI:NAME:<NAME>END_PI" "\u2653" "PI:NAME:<NAME>END_PI" "\u26CE" "ophiuchus" "\uD83D\uDD2F" "six pointed star" "\uD83C\uDFE7" "atm" "\uD83D\uDCB9" "chart" "\uD83D\uDCB2" "heavy dollar sign" "\uD83D\uDCB1" "currency exchange" "\u00A9\uFE0F" "copyright" "\u00AE\uFE0F" "registered" "\u2122\uFE0F" "tm" "\u274C" "x" "\u203C\uFE0F" "bangbang" "\u2049\uFE0F" "interrobang" "\u2757" ["exclamation" "heavy exclamation mark"] "\u2753" "question" "\u2755" "grey exclamation" "\u2754" "grey question" "\u2B55" "o" "\uD83D\uDD1D" "top" "\uD83D\uDD1A" "end" "\uD83D\uDD19" "back" "\uD83D\uDD1B" "on" "\uD83D\uDD1C" "soon" "\uD83D\uDD03" "arrows clockwise" "\uD83D\uDD5B" "clock 12" "\uD83D\uDD67" "clock 12:30" "\uD83D\uDD50" "clock 1" "\uD83D\uDD5C" "clock 1:30" "\uD83D\uDD51" "clock 2" "\uD83D\uDD5D" "clock 2:30" "\uD83D\uDD52" "clock 3" "\uD83D\uDD5E" "clock 3:30" "\uD83D\uDD53" "clock 4" "\uD83D\uDD5F" "clock 4:30" "\uD83D\uDD54" "clock 5" "\uD83D\uDD60" "clock 5:30" "\uD83D\uDD55" "clock 6" "\uD83D\uDD56" "clock 7" "\uD83D\uDD57" "clock 8" "\uD83D\uDD58" "clock 9" "\uD83D\uDD59" "clock 10" "\uD83D\uDD5A" "clock 11" "\uD83D\uDD61" "clock 6:30" "\uD83D\uDD62" "clock 7:30" "\uD83D\uDD63" "clock 8:30" "\uD83D\uDD64" "clock 9:30" "\uD83D\uDD65" "clock 10:30" "\uD83D\uDD66" "clock 11:30" "\u2716\uFE0F" "heavy multiplication x" "\u2795" "heavy plus sign" "\u2796" "heavy minus sign" "\u2797" "heavy division sign" "\u2660\uFE0F" "spades" "\u2665\uFE0F" "hearts" "\u2663\uFE0F" "clubs" "\u2666\uFE0F" "diamonds" "\uD83D\uDCAE" "white flower" "\uD83D\uDCAF" "100" "\u2714\uFE0F" "heavy check mark" "\u2611\uFE0F" "ballot box with check" "\uD83D\uDD18" "radio button" "\uD83D\uDD17" "link" "\u27B0" "curly loop" "\u3030\uFE0F" "wavy dash" "\u303D\uFE0F" "part alternation mark" "\uD83D\uDD31" "trident" "\u25FC\uFE0F" "black medium square" "\u25FB\uFE0F" "white medium square" "\u25FE" "black medium small square" "\u25FD" "white medium small square" "\u25AA\uFE0F" "black small square" "\u25AB\uFE0F" "white small square" "\uD83D\uDD3A" "small red triangle" "\uD83D\uDD32" "black square button" "\uD83D\uDD33" "white square button" "\u26AB" "black circle" "\u26AA" "white circle" "\uD83D\uDD34" "red circle" "\uD83D\uDD35" "large blue circle" "\uD83D\uDD3B" "small red triangle down" "\u2B1C" "white large square" "\u2B1B" "black large square" "\uD83D\uDD36" "large orange diamond" "\uD83D\uDD37" "large blue diamond" "\uD83D\uDD38" "small orange diamond" "\uD83D\uDD39" "small blue diamond"})
[ { "context": "nstant} (<? (d/<transact! conn [[:db/add 1 :name \"Ivan\"]]))\n {tx2 :tx txInstant2 :txInstant} (<? ", "end": 4111, "score": 0.954752504825592, "start": 4107, "tag": "NAME", "value": "Ivan" }, { "context": "nstant} (<? (d/<transact! conn [[:db/add 1 :name \"Petr\"]]))\n {tx3 :tx txInstant3 :txInstant} (<? ", "end": 4203, "score": 0.9208117127418518, "start": 4199, "tag": "NAME", "value": "Petr" }, { "context": "ms-after (d/db conn) tx0))\n #{[1 :name \"Petr\"]\n [1 :aka \"Tupen\"]\n [1 ", "end": 4469, "score": 0.946546196937561, "start": 4465, "tag": "NAME", "value": "Petr" }, { "context": "ons-after (d/db conn) tx0))\n [[1 :name \"Ivan\" tx1 1] ;; TODO: true, not 1.\n [tx1 :d", "end": 4618, "score": 0.9800233840942383, "start": 4614, "tag": "NAME", "value": "Ivan" }, { "context": "txInstant txInstant1 tx1 1]\n [1 :name \"Ivan\" tx2 0]\n [1 :name \"Petr\" tx2 1]\n ", "end": 4724, "score": 0.9996057748794556, "start": 4720, "tag": "NAME", "value": "Ivan" }, { "context": " [1 :name \"Ivan\" tx2 0]\n [1 :name \"Petr\" tx2 1]\n [tx2 :db/txInstant txInstant2", "end": 4759, "score": 0.9995754957199097, "start": 4755, "tag": "NAME", "value": "Petr" }, { "context": "/txInstant txInstant2 tx2 1]\n [1 :aka \"Tupen\" tx3 1]\n [tx3 :db/txInstant txInstant3", "end": 4843, "score": 0.9994838237762451, "start": 4838, "tag": "NAME", "value": "Tupen" }, { "context": "/txInstant txInstant3 tx3 1]\n [1 :aka \"Devil\" tx4 1]\n [tx4 :db/txInstant txInstant4", "end": 4927, "score": 0.9992983341217041, "start": 4922, "tag": "NAME", "value": "Devil" }, { "context": "0 (:tx (<? (d/<transact! conn [{:db/id 101 :name \"Ivan\" :email \"@1\"}\n ", "end": 8951, "score": 0.9988806843757629, "start": 8947, "tag": "NAME", "value": "Ivan" }, { "context": " {:db/id 102 :name \"Petr\" :email \"@2\"}])))]\n\n (testing \"upsert with tem", "end": 9030, "score": 0.999426007270813, "start": 9026, "tag": "NAME", "value": "Petr" }, { "context": " [[:db/add (d/id-literal :db.part/user -1) :name \"Ivan\"]\n [:db", "end": 9180, "score": 0.9989675879478455, "start": 9176, "tag": "NAME", "value": "Ivan" }, { "context": "w-entity (d/db conn) 101))\n {:name \"Ivan\" :age 12 :email \"@1\"}))\n (is (= (tempids r", "end": 9361, "score": 0.9997744560241699, "start": 9357, "tag": "NAME", "value": "Ivan" }, { "context": " 101))\n {:name \"Ivan\" :age 12 :email \"@1\"}))\n (is (= (tempids report)\n ", "end": 9377, "score": 0.7149226069450378, "start": 9377, "tag": "USERNAME", "value": "" }, { "context": " [:db/add (d/id-literal :db.part/user -1) :name \"Petr\"]]))]\n (is (= (<? (<shallow-entity (d/db c", "end": 9692, "score": 0.9996864795684814, "start": 9688, "tag": "NAME", "value": "Petr" }, { "context": "w-entity (d/db conn) 102))\n {:name \"Petr\" :age 13 :email \"@2\"}))\n (is (= (tempids r", "end": 9780, "score": 0.9997571110725403, "start": 9776, "tag": "NAME", "value": "Petr" }, { "context": " [[:db/add (d/id-literal :db.part/user -1) :name \"Ivan\"]\n ", "end": 10070, "score": 0.9995030760765076, "start": 10066, "tag": "NAME", "value": "Ivan" }, { "context": " [:db/add (d/id-literal :db.part/user -1) :name \"Petr\"]\n ", "end": 10279, "score": 0.9996516704559326, "start": 10275, "tag": "NAME", "value": "Petr" }, { "context": "n [{:db/id (d/id-literal :db.part/user -1) :name \"Ivan\" :email \"@1\"}\n ", "end": 10654, "score": 0.9996812343597412, "start": 10650, "tag": "NAME", "value": "Ivan" }, { "context": " {:db/id (d/id-literal :db.part/user -2) :name \"Petr\" :friends (d/id-literal :db.part/user -1)}]))]\n\n ", "end": 10756, "score": 0.9997067451477051, "start": 10752, "tag": "NAME", "value": "Petr" }, { "context": "n [{:db/id (d/id-literal :db.part/user -1) :name \"Ivan\" :email \"@1\"}\n ", "end": 11138, "score": 0.9994040727615356, "start": 11134, "tag": "NAME", "value": "Ivan" }, { "context": " {:db/id (d/id-literal :db.part/user -2) :name \"Petr\" :friends (d/id-literal :db.part/user -1)}]))]\n\n ", "end": 11242, "score": 0.9995403289794922, "start": 11238, "tag": "NAME", "value": "Petr" }, { "context": "0 (:tx (<? (d/<transact! conn [{:db/id 101 :name \"Ivan\" :email \"@1\"}\n ", "end": 11721, "score": 0.9992959499359131, "start": 11717, "tag": "NAME", "value": "Ivan" }, { "context": " {:db/id 102 :name \"Petr\" :email \"@2\"}])))]\n\n (testing \"upsert with tem", "end": 11800, "score": 0.9994989633560181, "start": 11796, "tag": "NAME", "value": "Petr" }, { "context": "n [{:db/id (d/id-literal :db.part/user -1) :name \"Ivan\" :age 35}]))]\n (is (= (<? (<shallow-entity", "end": 11945, "score": 0.9989346861839294, "start": 11941, "tag": "NAME", "value": "Ivan" }, { "context": "w-entity (d/db conn) 101))\n {:name \"Ivan\" :email \"@1\" :age 35}))\n (is (= (tempids t", "end": 12041, "score": 0.9994346499443054, "start": 12037, "tag": "NAME", "value": "Ivan" }, { "context": "n [{:db/id (d/id-literal :db.part/user -1) :name \"Ivan\" :email \"@1\" :age 35}]))]\n (is (= (<? (<sh", "end": 12258, "score": 0.9993523359298706, "start": 12254, "tag": "NAME", "value": "Ivan" }, { "context": "w-entity (d/db conn) 101))\n {:name \"Ivan\" :email \"@1\" :age 35}))\n (is (= (tempids t", "end": 12366, "score": 0.9994028806686401, "start": 12362, "tag": "NAME", "value": "Ivan" }, { "context": "et [tx (<? (d/<transact! conn [{:db/id 101 :name \"Ivan\" :age 36}]))]\n (is (= (<? (<shallow-entity", "end": 12549, "score": 0.9994442462921143, "start": 12545, "tag": "NAME", "value": "Ivan" }, { "context": "w-entity (d/db conn) 101))\n {:name \"Ivan\" :email \"@1\" :age 36}))\n (is (= (tempids t", "end": 12645, "score": 0.999660849571228, "start": 12641, "tag": "NAME", "value": "Ivan" }, { "context": "db conn) 101))\n {:name \"Ivan\" :email \"@1\" :age 36}))\n (is (= (tempids tx)\n ", "end": 12653, "score": 0.8525393605232239, "start": 12653, "tag": "USERNAME", "value": "" }, { "context": "et [tx (<? (d/<transact! conn [{:db/id 101 :name \"Ivan\" :email \"@1\" :age 37}]))]\n (is (= (<? (<sh", "end": 12833, "score": 0.9995300769805908, "start": 12829, "tag": "NAME", "value": "Ivan" }, { "context": "d/<transact! conn [{:db/id 101 :name \"Ivan\" :email \"@1\" :age 37}]))]\n (is (= (<? (<shallow-entit", "end": 12841, "score": 0.5301751494407654, "start": 12841, "tag": "USERNAME", "value": "" }, { "context": "w-entity (d/db conn) 101))\n {:name \"Ivan\" :email \"@1\" :age 37}))\n (is (= (tempids t", "end": 12941, "score": 0.999640703201294, "start": 12937, "tag": "NAME", "value": "Ivan" }, { "context": "db conn) 101))\n {:name \"Ivan\" :email \"@1\" :age 37}))\n (is (= (tempids tx)\n ", "end": 12949, "score": 0.4960481822490692, "start": 12949, "tag": "USERNAME", "value": "" }, { "context": "n [{:db/id (d/id-literal :db.part/user -1) :name \"Ivan\" :age 35}\n ", "end": 13279, "score": 0.9992309808731079, "start": 13275, "tag": "NAME", "value": "Ivan" }, { "context": " {:db/id (d/id-literal :db.part/user -1) :name \"Ivan\" :age 36}])))))\n\n (testing \"upsert to two enti", "end": 13393, "score": 0.9993652701377869, "start": 13389, "tag": "NAME", "value": "Ivan" }, { "context": "n [{:db/id (d/id-literal :db.part/user -1) :name \"Ivan\" :age 35}\n ", "end": 13662, "score": 0.9993122816085815, "start": 13658, "tag": "NAME", "value": "Ivan" }, { "context": " {:db/id (d/id-literal :db.part/user -2) :name \"Ivan\" :age 36}])))))))\n\n(deftest-db test-map-upsert-co", "end": 13776, "score": 0.9994646310806274, "start": 13772, "tag": "NAME", "value": "Ivan" }, { "context": "0 (:tx (<? (d/<transact! conn [{:db/id 101 :name \"Ivan\" :email \"@1\"}\n ", "end": 14113, "score": 0.9995405077934265, "start": 14109, "tag": "NAME", "value": "Ivan" }, { "context": " {:db/id 102 :name \"Petr\" :email \"@2\"}])))]\n\n ;; TODO: improve error me", "end": 14192, "score": 0.9996458292007446, "start": 14188, "tag": "NAME", "value": "Petr" }, { "context": " (<? (d/<transact! conn [{:db/id 102 :name \"Ivan\" :age 36}])))))\n\n ;; TODO: improve error messa", "end": 14457, "score": 0.9995172023773193, "start": 14453, "tag": "NAME", "value": "Ivan" }, { "context": " (<? (d/<transact! conn [{:db/id 103 :name \"Ivan\" :age 36}])))))\n\n ;; TODO: improve error messa", "end": 14723, "score": 0.9995409250259399, "start": 14719, "tag": "NAME", "value": "Ivan" }, { "context": "n [{:db/id (d/id-literal :db.part/user -1) :name \"Ivan\" :email \"@2\" :age 35}])))))\n\n (testing \"upsert", "end": 15012, "score": 0.999415397644043, "start": 15008, "tag": "NAME", "value": "Ivan" }, { "context": "n [{:db/id (d/id-literal :db.part/user -1) :name \"Ivan\" :email \"@3\" :age 35}]))]\n (is (= (<? (<sh", "end": 15199, "score": 0.9993884563446045, "start": 15195, "tag": "NAME", "value": "Ivan" }, { "context": "w-entity (d/db conn) 101))\n {:name \"Ivan\" :email \"@3\" :age 35}))\n (is (= (tempids r", "end": 15307, "score": 0.9995454549789429, "start": 15303, "tag": "NAME", "value": "Ivan" }, { "context": " (d/<transact! conn [{:db/id 101 :friends {:name \"Petr\"}}]))\n ;; TODO: this works only because we h", "end": 24265, "score": 0.9995856881141663, "start": 24261, "tag": "NAME", "value": "Petr" }, { "context": "[101 :friends petr]\n [petr :name \"Petr\"]}))))\n\n (testing \"recursively nested maps are", "end": 24527, "score": 0.9991217255592346, "start": 24523, "tag": "NAME", "value": "Petr" }, { "context": " (d/<transact! conn [{:db/id 102 :friends {:name \"Ivan\" :friends {:name \"Petr\"}}}]))\n ;; This would", "end": 24651, "score": 0.9996509552001953, "start": 24647, "tag": "NAME", "value": "Ivan" }, { "context": "db/id 102 :friends {:name \"Ivan\" :friends {:name \"Petr\"}}}]))\n ;; This would be much easier with `e", "end": 24674, "score": 0.9997081160545349, "start": 24670, "tag": "NAME", "value": "Petr" }, { "context": "[101 :friends petr]\n [petr :name \"Petr\"]\n [102 :friends ivan]\n ", "end": 25007, "score": 0.9995578527450562, "start": 25003, "tag": "NAME", "value": "Petr" }, { "context": "[102 :friends ivan]\n [ivan :name \"Ivan\"]\n [ivan :friends petr]}))))\n\n ", "end": 25081, "score": 0.9995375871658325, "start": 25077, "tag": "NAME", "value": "Ivan" }, { "context": " (<? (d/<transact! conn [{:db/id 101 :aka {:name \"Petr\"}}])))))))\n\n(deftest-db test-explode-maps-with-db", "end": 25334, "score": 0.9667356014251709, "start": 25330, "tag": "NAME", "value": "Petr" }, { "context": "\n (<? (d/<transact! conn [{:db/id 101 :name \"Oleg\"}]))\n\n (<? (d/<transact! conn [{:db/id 101 :", "end": 25576, "score": 0.7011436223983765, "start": 25572, "tag": "NAME", "value": "Oleg" }, { "context": "ct! conn [{:db/id 101 :friends {:db/id 201 :name \"Ivan\" :friends {:db/id 301 :name \"Petr\"}}}]))\n (i", "end": 25657, "score": 0.9996930360794067, "start": 25653, "tag": "NAME", "value": "Ivan" }, { "context": "b/id 201 :name \"Ivan\" :friends {:db/id 301 :name \"Petr\"}}}]))\n (is (= (<? (<datoms-after (d/db conn", "end": 25691, "score": 0.999793291091919, "start": 25687, "tag": "NAME", "value": "Petr" }, { "context": "fter (d/db conn) tx0))\n #{[101 :name \"Oleg\"]\n [101 :friends 201]\n ", "end": 25780, "score": 0.9996855854988098, "start": 25776, "tag": "NAME", "value": "Oleg" }, { "context": " [101 :friends 201]\n [201 :name \"Ivan\"]\n [201 :friends 301 ]\n ", "end": 25848, "score": 0.9997583031654358, "start": 25844, "tag": "NAME", "value": "Ivan" }, { "context": " [201 :friends 301 ]\n [301 :name \"Petr\"]})))))\n\n(deftest-db test-explode-reverse-refs co", "end": 25917, "score": 0.9998135566711426, "start": 25913, "tag": "NAME", "value": "Petr" }, { "context": "\n (<? (d/<transact! conn [{:db/id 101 :name \"Igor\"}]))\n (<? (d/<transact! conn [{:db/id 102 :n", "end": 26120, "score": 0.997988224029541, "start": 26116, "tag": "NAME", "value": "Igor" }, { "context": "\n (<? (d/<transact! conn [{:db/id 102 :name \"Oleg\" :_friends 101}]))\n (is (= (<? (<datoms-afte", "end": 26179, "score": 0.9992179870605469, "start": 26175, "tag": "NAME", "value": "Oleg" }, { "context": "fter (d/db conn) tx0))\n #{[101 :name \"Igor\"]\n [102 :name \"Oleg\"]\n ", "end": 26280, "score": 0.9988484978675842, "start": 26276, "tag": "NAME", "value": "Igor" }, { "context": " #{[101 :name \"Igor\"]\n [102 :name \"Oleg\"]\n [101 :friends 102]})))\n\n (tes", "end": 26314, "score": 0.9994314312934875, "start": 26310, "tag": "NAME", "value": "Oleg" }, { "context": "n [{:db/id (d/id-literal :db.part/user -1) :name \"Igor\"}]))\n r2 (<? (d/<transact! conn [{:d", "end": 26964, "score": 0.9966701865196228, "start": 26960, "tag": "NAME", "value": "Igor" }, { "context": "n [{:db/id (d/id-literal :db.part/user -2) :name \"Oleg\"}]))\n e1 (get (tempids r1) -1)\n ", "end": 27062, "score": 0.999687671661377, "start": 27058, "tag": "NAME", "value": "Oleg" }, { "context": "n [{:db/id (d/id-literal :db.part/user -3) :name \"Petr\"}]))\n e3 (get (tempids r3) -", "end": 27572, "score": 0.9996001720428467, "start": 27568, "tag": "NAME", "value": "Petr" }, { "context": "est-db test-simple-schema conn\n (let [in {:name \"mystuff\"\n :attributes [{:name \"foo/age\"\n ", "end": 41970, "score": 0.9985201358795166, "start": 41963, "tag": "USERNAME", "value": "mystuff" }, { "context": "x1 :tx} (<? (d/<transact! conn [[:db/add 1 :name \"Ivan\"]\n [:db/", "end": 43474, "score": 0.9991452693939209, "start": 43470, "tag": "NAME", "value": "Ivan" }, { "context": " [:db/add 2 :name \"Phil\"]\n [:db/", "end": 43541, "score": 0.9997982382774353, "start": 43537, "tag": "NAME", "value": "Phil" }, { "context": " [:db/add 3 :name \"Petr\"]]))]\n (testing \"Looks up entity refs\"\n (", "end": 43608, "score": 0.99961256980896, "start": 43604, "tag": "NAME", "value": "Petr" }, { "context": "(d/<transact! conn [[:db/add (d/lookup-ref :name \"Ivan\") :aka \"Devil\"]\n ", "end": 43730, "score": 0.9991215467453003, "start": 43726, "tag": "NAME", "value": "Ivan" }, { "context": " conn [[:db/add (d/lookup-ref :name \"Ivan\") :aka \"Devil\"]\n [:", "end": 43744, "score": 0.9982929229736328, "start": 43739, "tag": "NAME", "value": "Devil" }, { "context": " [:db/add (d/lookup-ref :name \"Phil\") :email \"@1\"]]))]\n (is (= #{[1 :name \"Iva", "end": 43826, "score": 0.9996559619903564, "start": 43822, "tag": "NAME", "value": "Phil" }, { "context": "hil\") :email \"@1\"]]))]\n (is (= #{[1 :name \"Ivan\"]\n [2 :name \"Phil\"]\n ", "end": 43877, "score": 0.9994216561317444, "start": 43873, "tag": "NAME", "value": "Ivan" }, { "context": " (= #{[1 :name \"Ivan\"]\n [2 :name \"Phil\"]\n [3 :name \"Petr\"]\n ", "end": 43911, "score": 0.9997930526733398, "start": 43907, "tag": "NAME", "value": "Phil" }, { "context": " [2 :name \"Phil\"]\n [3 :name \"Petr\"]\n [1 :aka \"Devil\"]\n ", "end": 43945, "score": 0.9996978044509888, "start": 43941, "tag": "NAME", "value": "Petr" }, { "context": " [3 :name \"Petr\"]\n [1 :aka \"Devil\"]\n [2 :email \"@1\"]}\n ", "end": 43979, "score": 0.9995329976081848, "start": 43974, "tag": "NAME", "value": "Devil" }, { "context": "t! conn [[:db/add 1 :friends (d/lookup-ref :name \"Petr\")]\n [", "end": 44194, "score": 0.9995099902153015, "start": 44190, "tag": "NAME", "value": "Petr" }, { "context": " [:db/add 3 :friends (d/lookup-ref :name \"Ivan\")]]))]\n (is (= #{[1 :friends 3]\n ", "end": 44288, "score": 0.9995582103729248, "start": 44284, "tag": "NAME", "value": "Ivan" }, { "context": " (d/<transact! conn [{:db/id (d/lookup-ref :name \"Phil\") :friends 1}]))]\n (is (= #{[2 :friends 1]", "end": 44535, "score": 0.9996567964553833, "start": 44531, "tag": "NAME", "value": "Phil" }, { "context": "ct! conn [{:db/id 2 :friends (d/lookup-ref :name \"Petr\")}]))]\n (is (= #{[2 :friends 3]}\n ", "end": 44771, "score": 0.9994426965713501, "start": 44767, "tag": "NAME", "value": "Petr" }, { "context": "t! conn [{:db/id 1 :friends [(d/lookup-ref :name \"Ivan\") (d/lookup-ref :name \"Phil\")]}]))]\n (is (", "end": 45012, "score": 0.9994392991065979, "start": 45008, "tag": "NAME", "value": "Ivan" }, { "context": "[(d/lookup-ref :name \"Ivan\") (d/lookup-ref :name \"Phil\")]}]))]\n (is (= #{[1 :friends 1]\n ", "end": 45040, "score": 0.9997734427452087, "start": 45036, "tag": "NAME", "value": "Phil" }, { "context": " make-add #(vector :db/add (+ 1000 %) :name (str \"Ivan-\" %))\n make-ref #(-> {:db/id (d/lookup-", "end": 45345, "score": 0.9991880655288696, "start": 45341, "tag": "NAME", "value": "Ivan" }, { "context": " make-ref #(-> {:db/id (d/lookup-ref :name (str \"Ivan-\" %)) :email (str \"Ivan-\" % \"@\" %)})\n {", "end": 45415, "score": 0.9333492517471313, "start": 45411, "tag": "NAME", "value": "Ivan" }, { "context": "(d/<transact! conn [[:db/add (d/lookup-ref :name \"Mysterioso\") :aka \"The Magician\"]]))))\n (is (thrown-wit", "end": 46046, "score": 0.7087975740432739, "start": 46036, "tag": "NAME", "value": "Mysterioso" }, { "context": "t! conn [[:db/add 1 :friends (d/lookup-ref :name \"Mysterioso\")]])))))\n\n (testing \"Fails for non-identity at", "end": 46250, "score": 0.6847609281539917, "start": 46240, "tag": "NAME", "value": "Mysterioso" } ]
test/datomish/db_test.cljc
joewalker/mentat
0
;; Copyright 2016 Mozilla ;; ;; 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 datomish.db-test #?(:cljs (:require-macros [datomish.pair-chan :refer [go-pair <?]] [datomish.node-tempfile-macros :refer [with-tempfile]] [cljs.core.async.macros :as a :refer [go]])) (:require [datomish.api :as d] [datomish.db.debug :refer [<datoms-after <datoms>= <transactions-after <shallow-entity <fulltext-values]] [datomish.util :as util #?(:cljs :refer-macros :clj :refer) [raise cond-let]] [datomish.schema :as ds] [datomish.simple-schema] [datomish.sqlite :as s] [datomish.sqlite-schema] [datomish.datom] #?@(:clj [[datomish.jdbc-sqlite] [datomish.pair-chan :refer [go-pair <?]] [tempfile.core :refer [tempfile with-tempfile]] [datomish.test-macros :refer [deftest-async deftest-db]] [clojure.test :as t :refer [is are deftest testing]] [clojure.core.async :refer [go <! >!]]]) #?@(:cljs [[datomish.js-sqlite] [datomish.pair-chan] [datomish.test-macros :refer-macros [deftest-async deftest-db]] [datomish.node-tempfile :refer [tempfile]] [cljs.test :as t :refer-macros [is are deftest testing async]] [cljs.core.async :as a :refer [<! >!]]])) #?(:clj (:import [clojure.lang ExceptionInfo])) #?(:clj (:import [datascript.db DB]))) #?(:cljs (def Throwable js/Error)) (defn- tempids [tx] (into {} (map (juxt (comp :idx first) second) (:tempids tx)))) (def test-schema [{:db/id (d/id-literal :db.part/user) :db/ident :x :db/unique :db.unique/identity :db/valueType :db.type/long :db.install/_attribute :db.part/db} {:db/id (d/id-literal :db.part/user) :db/ident :name :db/unique :db.unique/identity :db/valueType :db.type/string :db.install/_attribute :db.part/db} {:db/id (d/id-literal :db.part/user) :db/ident :y :db/cardinality :db.cardinality/many :db/valueType :db.type/long :db.install/_attribute :db.part/db} {:db/id (d/id-literal :db.part/user) :db/ident :aka :db/cardinality :db.cardinality/many :db/valueType :db.type/string :db.install/_attribute :db.part/db} {:db/id (d/id-literal :db.part/user) :db/ident :age :db/valueType :db.type/long :db.install/_attribute :db.part/db} {:db/id (d/id-literal :db.part/user) :db/ident :email :db/unique :db.unique/identity :db/valueType :db.type/string :db.install/_attribute :db.part/db} {:db/id (d/id-literal :db.part/user) :db/ident :spouse :db/unique :db.unique/value :db/valueType :db.type/string :db.install/_attribute :db.part/db} {:db/id (d/id-literal :db.part/user) :db/ident :friends :db/cardinality :db.cardinality/many :db/valueType :db.type/ref :db.install/_attribute :db.part/db} ]) (deftest-db test-add-one conn (let [{tx0 :tx} (<? (d/<transact! conn test-schema))] (let [{:keys [tx txInstant]} (<? (d/<transact! conn [[:db/add 0 :name "valuex"]]))] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[0 :name "valuex"]})) (is (= (<? (<transactions-after (d/db conn) tx0)) [[0 :name "valuex" tx 1] ;; TODO: true, not 1. [tx :db/txInstant txInstant tx 1]]))))) (deftest-db test-add-two conn (let [{tx0 :tx} (<? (d/<transact! conn test-schema)) {tx1 :tx txInstant1 :txInstant} (<? (d/<transact! conn [[:db/add 1 :name "Ivan"]])) {tx2 :tx txInstant2 :txInstant} (<? (d/<transact! conn [[:db/add 1 :name "Petr"]])) {tx3 :tx txInstant3 :txInstant} (<? (d/<transact! conn [[:db/add 1 :aka "Tupen"]])) {tx4 :tx txInstant4 :txInstant} (<? (d/<transact! conn [[:db/add 1 :aka "Devil"]]))] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[1 :name "Petr"] [1 :aka "Tupen"] [1 :aka "Devil"]})) (is (= (<? (<transactions-after (d/db conn) tx0)) [[1 :name "Ivan" tx1 1] ;; TODO: true, not 1. [tx1 :db/txInstant txInstant1 tx1 1] [1 :name "Ivan" tx2 0] [1 :name "Petr" tx2 1] [tx2 :db/txInstant txInstant2 tx2 1] [1 :aka "Tupen" tx3 1] [tx3 :db/txInstant txInstant3 tx3 1] [1 :aka "Devil" tx4 1] [tx4 :db/txInstant txInstant4 tx4 1]])))) (deftest-db test-retract conn (let [{tx0 :tx} (<? (d/<transact! conn test-schema)) {tx1 :tx txInstant1 :txInstant} (<? (d/<transact! conn [[:db/add 0 :x 123]])) {tx2 :tx txInstant2 :txInstant} (<? (d/<transact! conn [[:db/retract 0 :x 123]]))] (is (= (<? (<datoms-after (d/db conn) tx0)) #{})) (is (= (<? (<transactions-after (d/db conn) tx0)) [[0 :x 123 tx1 1] [tx1 :db/txInstant txInstant1 tx1 1] [0 :x 123 tx2 0] [tx2 :db/txInstant txInstant2 tx2 1]])))) (deftest-db test-id-literal-1 conn (let [tx0 (:tx (<? (d/<transact! conn test-schema))) report (<? (d/<transact! conn [[:db/add (d/id-literal :db.part/user -1) :x 0] [:db/add (d/id-literal :db.part/user -1) :y 1] [:db/add (d/id-literal :db.part/user -2) :y 2] [:db/add (d/id-literal :db.part/user -2) :y 3]]))] (is (= (keys (:tempids report)) ;; TODO: include values. [(d/id-literal :db.part/user -1) (d/id-literal :db.part/user -2)])) (let [eid1 (get-in report [:tempids (d/id-literal :db.part/user -1)]) eid2 (get-in report [:tempids (d/id-literal :db.part/user -2)])] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :x 0] [eid1 :y 1] [eid2 :y 2] [eid2 :y 3]}))))) (deftest-db test-unique conn (let [tx0 (:tx (<? (d/<transact! conn test-schema)))] (testing "Multiple :db/unique values in tx-data violate unique constraint, no tempid" (is (thrown-with-msg? ExceptionInfo #"unique constraint" (<? (d/<transact! conn [[:db/add 1 :x 0] [:db/add 2 :x 0]]))))) (testing "Multiple :db/unique values in tx-data violate unique constraint, tempid" (is (thrown-with-msg? ExceptionInfo #"unique constraint" (<? (d/<transact! conn [[:db/add (d/id-literal :db.part/user -1) :spouse "Dana"] [:db/add (d/id-literal :db.part/user -2) :spouse "Dana"]]))))))) (deftest-db test-valueType-keyword conn (let [tx0 (:tx (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :db/ident :test/kw :db/unique :db.unique/identity :db/valueType :db.type/keyword} {:db/id :db.part/db :db.install/attribute (d/id-literal :db.part/user -1)}])))] (let [report (<? (d/<transact! conn [[:db/add (d/id-literal :db.part/user -1) :test/kw :test/kw1]])) eid (get-in report [:tempids (d/id-literal :db.part/user -1)])] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid :test/kw ":test/kw1"]})) ;; Value is raw. (testing "Adding the same value compares existing values correctly." (<? (d/<transact! conn [[:db/add eid :test/kw :test/kw1]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid :test/kw ":test/kw1"]}))) ;; Value is raw. (testing "Upserting retracts existing value correctly." (<? (d/<transact! conn [[:db/add eid :test/kw :test/kw2]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid :test/kw ":test/kw2"]}))) ;; Value is raw. (testing "Retracting compares values correctly." (<? (d/<transact! conn [[:db/retract eid :test/kw :test/kw2]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{})))))) (deftest-db test-vector-upsert conn ;; Not having DB-as-value really hurts us here. This test only works because all upserts ;; succeed on top of each other, so we never need to reset the underlying store. (<? (d/<transact! conn test-schema)) (let [tx0 (:tx (<? (d/<transact! conn [{:db/id 101 :name "Ivan" :email "@1"} {:db/id 102 :name "Petr" :email "@2"}])))] (testing "upsert with tempid" (let [report (<? (d/<transact! conn [[:db/add (d/id-literal :db.part/user -1) :name "Ivan"] [:db/add (d/id-literal :db.part/user -1) :age 12]]))] (is (= (<? (<shallow-entity (d/db conn) 101)) {:name "Ivan" :age 12 :email "@1"})) (is (= (tempids report) {-1 101})))) (testing "upsert with tempid, order does not matter" (let [report (<? (d/<transact! conn [[:db/add (d/id-literal :db.part/user -1) :age 13] [:db/add (d/id-literal :db.part/user -1) :name "Petr"]]))] (is (= (<? (<shallow-entity (d/db conn) 102)) {:name "Petr" :age 13 :email "@2"})) (is (= (tempids report) {-1 102})))) (testing "Conflicting upserts fail" (is (thrown-with-msg? Throwable #"Conflicting upsert" (<? (d/<transact! conn [[:db/add (d/id-literal :db.part/user -1) :name "Ivan"] [:db/add (d/id-literal :db.part/user -1) :age 35] [:db/add (d/id-literal :db.part/user -1) :name "Petr"] [:db/add (d/id-literal :db.part/user -1) :age 36]]))))))) (deftest-db test-multistep-upsert conn (<? (d/<transact! conn test-schema)) ;; The upsert algorithm will first try to resolve -1, fail, and then allocate both -1 and -2. (let [tx0 (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :name "Ivan" :email "@1"} {:db/id (d/id-literal :db.part/user -2) :name "Petr" :friends (d/id-literal :db.part/user -1)}]))] ;; Sanity checks that these are freshly allocated, not resolved. (is (> (get (tempids tx0) -1) 1000)) (is (> (get (tempids tx0) -1) 1000)) ;; This time, we can resolve both, but we have to try -1, succeed, and then resolve -2. (let [tx1 (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :name "Ivan" :email "@1"} {:db/id (d/id-literal :db.part/user -2) :name "Petr" :friends (d/id-literal :db.part/user -1)}]))] ;; Ensure these are resolved, not freshly allocated. (is (= (tempids tx0) (tempids tx1)))))) (deftest-db test-map-upsert conn ;; Not having DB-as-value really hurts us here. This test only works because all upserts ;; succeed on top of each other, so we never need to reset the underlying store. (<? (d/<transact! conn test-schema)) (let [tx0 (:tx (<? (d/<transact! conn [{:db/id 101 :name "Ivan" :email "@1"} {:db/id 102 :name "Petr" :email "@2"}])))] (testing "upsert with tempid" (let [tx (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :name "Ivan" :age 35}]))] (is (= (<? (<shallow-entity (d/db conn) 101)) {:name "Ivan" :email "@1" :age 35})) (is (= (tempids tx) {-1 101})))) (testing "upsert by 2 attrs with tempid" (let [tx (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :name "Ivan" :email "@1" :age 35}]))] (is (= (<? (<shallow-entity (d/db conn) 101)) {:name "Ivan" :email "@1" :age 35})) (is (= (tempids tx) {-1 101})))) (testing "upsert with existing id" (let [tx (<? (d/<transact! conn [{:db/id 101 :name "Ivan" :age 36}]))] (is (= (<? (<shallow-entity (d/db conn) 101)) {:name "Ivan" :email "@1" :age 36})) (is (= (tempids tx) {})))) (testing "upsert by 2 attrs with existing id" (let [tx (<? (d/<transact! conn [{:db/id 101 :name "Ivan" :email "@1" :age 37}]))] (is (= (<? (<shallow-entity (d/db conn) 101)) {:name "Ivan" :email "@1" :age 37})) (is (= (tempids tx) {})))) (testing "upsert to two entities, resolve to same tempid, fails due to overlapping writes" (is (thrown-with-msg? Throwable #"cardinality constraint" (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :name "Ivan" :age 35} {:db/id (d/id-literal :db.part/user -1) :name "Ivan" :age 36}]))))) (testing "upsert to two entities, two tempids, fails due to overlapping writes" (is (thrown-with-msg? Throwable #"cardinality constraint" (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :name "Ivan" :age 35} {:db/id (d/id-literal :db.part/user -2) :name "Ivan" :age 36}]))))))) (deftest-db test-map-upsert-conflicts conn ;; Not having DB-as-value really hurts us here. This test only works because all upserts ;; fail until the final one, so we never need to reset the underlying store. (<? (d/<transact! conn test-schema)) (let [tx0 (:tx (<? (d/<transact! conn [{:db/id 101 :name "Ivan" :email "@1"} {:db/id 102 :name "Petr" :email "@2"}])))] ;; TODO: improve error message to refer to upsert inputs. (testing "upsert conficts with existing id" (is (thrown-with-msg? Throwable #"unique constraint" (<? (d/<transact! conn [{:db/id 102 :name "Ivan" :age 36}]))))) ;; TODO: improve error message to refer to upsert inputs. (testing "upsert conficts with non-existing id" (is (thrown-with-msg? Throwable #"unique constraint" (<? (d/<transact! conn [{:db/id 103 :name "Ivan" :age 36}]))))) ;; TODO: improve error message to refer to upsert inputs. (testing "upsert by 2 conflicting fields" (is (thrown-with-msg? Throwable #"Conflicting upsert" (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :name "Ivan" :email "@2" :age 35}]))))) (testing "upsert by non-existing value resolves as update" (let [report (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :name "Ivan" :email "@3" :age 35}]))] (is (= (<? (<shallow-entity (d/db conn) 101)) {:name "Ivan" :email "@3" :age 35})) (is (= (tempids report) {-1 101})))))) (deftest-db test-add-schema conn (let [es [[:db/add :db.part/db :db.install/attribute (d/id-literal :db.part/db -1)] {:db/id (d/id-literal :db.part/db -1) :db/ident :test/attr :db/valueType :db.type/string :db/cardinality :db.cardinality/one}] report (<? (d/<transact! conn es)) db-after (:db-after report) tx (:tx db-after)] (testing "New ident is allocated" (is (some? (d/entid db-after :test/attr)))) (testing "Schema is modified" (is (= (get-in db-after [:symbolic-schema :test/attr]) {:db/valueType :db.type/string, :db/cardinality :db.cardinality/one}))) (testing "Schema is used in subsequent transaction" (<? (d/<transact! conn [{:db/id 100 :test/attr "value 1"}])) (<? (d/<transact! conn [{:db/id 100 :test/attr "value 2"}])) (is (= (<? (<shallow-entity (d/db conn) 100)) {:test/attr "value 2"}))))) (deftest-db test-fulltext conn (let [schema [{:db/id (d/id-literal :db.part/db -1) :db/ident :test/fulltext :db/valueType :db.type/string :db/fulltext true :db/unique :db.unique/identity} {:db/id :db.part/db :db.install/attribute (d/id-literal :db.part/db -1)} {:db/id (d/id-literal :db.part/db -2) :db/ident :test/other :db/valueType :db.type/string :db/fulltext true :db/cardinality :db.cardinality/one} {:db/id :db.part/db :db.install/attribute (d/id-literal :db.part/db -2)} ] tx0 (:tx (<? (d/<transact! conn schema)))] (testing "Schema checks" (is (ds/fulltext? (d/schema (d/db conn)) (d/entid (d/db conn) :test/fulltext)))) (testing "Can add fulltext indexed datoms" (let [{tx1 :tx txInstant1 :txInstant} (<? (d/<transact! conn [[:db/add 101 :test/fulltext "test this"]]))] (is (= (<? (<fulltext-values (d/db conn))) [[1 "test this"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :test/fulltext 1]})) ;; Values are raw; 1 is the rowid into fulltext_values. (is (= (<? (<transactions-after (d/db conn) tx0)) [[101 :test/fulltext 1 tx1 1] ;; Values are raw; 1 is the rowid into fulltext_values. [tx1 :db/txInstant txInstant1 tx1 1]])) (testing "Can replace fulltext indexed datoms" (let [{tx2 :tx txInstant2 :txInstant} (<? (d/<transact! conn [[:db/add 101 :test/fulltext "alternate thing"]]))] (is (= (<? (<fulltext-values (d/db conn))) [[1 "test this"] [2 "alternate thing"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :test/fulltext 2]})) ;; Values are raw; 2 is the rowid into fulltext_values. (is (= (<? (<transactions-after (d/db conn) tx0)) [[101 :test/fulltext 1 tx1 1] ;; Values are raw; 1 is the rowid into fulltext_values. [tx1 :db/txInstant txInstant1 tx1 1] [101 :test/fulltext 1 tx2 0] ;; Values are raw; 1 is the rowid into fulltext_values. [101 :test/fulltext 2 tx2 1] ;; Values are raw; 2 is the rowid into fulltext_values. [tx2 :db/txInstant txInstant2 tx2 1]])) (testing "Can upsert keyed by fulltext indexed datoms" (let [{tx3 :tx txInstant3 :txInstant} (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user) :test/fulltext "alternate thing" :test/other "other"}]))] (is (= (<? (<fulltext-values (d/db conn))) [[1 "test this"] [2 "alternate thing"] [3 "other"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :test/fulltext 2] ;; Values are raw; 2, 3 are the rowids into fulltext_values. [101 :test/other 3]})) (is (= (<? (<transactions-after (d/db conn) tx0)) [[101 :test/fulltext 1 tx1 1] ;; Values are raw; 1 is the rowid into fulltext_values. [tx1 :db/txInstant txInstant1 tx1 1] [101 :test/fulltext 1 tx2 0] ;; Values are raw; 1 is the rowid into fulltext_values. [101 :test/fulltext 2 tx2 1] ;; Values are raw; 2 is the rowid into fulltext_values. [tx2 :db/txInstant txInstant2 tx2 1] [101 :test/other 3 tx3 1] ;; Values are raw; 3 is the rowid into fulltext_values. [tx3 :db/txInstant txInstant3 tx3 1]])) )))))) (testing "Can re-use fulltext indexed datoms" (let [r (<? (d/<transact! conn [[:db/add 102 :test/other "test this"]]))] (is (= (<? (<fulltext-values (d/db conn))) [[1 "test this"] [2 "alternate thing"] [3 "other"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :test/fulltext 2] [101 :test/other 3] [102 :test/other 1]})) ;; Values are raw; 1, 2, 3 are the rowids into fulltext_values. )) (testing "Can retract fulltext indexed datoms" (let [r (<? (d/<transact! conn [[:db/retract 101 :test/fulltext "alternate thing"]]))] (is (= (<? (<fulltext-values (d/db conn))) [[1 "test this"] [2 "alternate thing"] [3 "other"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :test/other 3] [102 :test/other 1]})) ;; Values are raw; 1, 3 are the rowids into fulltext_values. )))) (deftest-db test-txInstant conn (let [{tx0 :tx} (<? (d/<transact! conn test-schema)) {txa :tx txInstantA :txInstant} (<? (d/<transact! conn []))] (testing ":db/txInstant is set by default" (is (= (<? (<transactions-after (d/db conn) tx0)) [[txa :db/txInstant txInstantA txa 1]]))) ;; TODO: range check txInstant values against DB clock. (testing ":db/txInstant can be set explicitly" (let [{txb :tx txInstantB :txInstant} (<? (d/<transact! conn [[:db/add :db/tx :db/txInstant (+ txInstantA 1)]]))] (is (= txInstantB (+ txInstantA 1))) (is (= (<? (<transactions-after (d/db conn) txa)) [[txb :db/txInstant txInstantB txb 1]])) (testing ":db/txInstant can be set explicitly, with additional datoms" (let [{txc :tx txInstantC :txInstant} (<? (d/<transact! conn [[:db/add :db/tx :db/txInstant (+ txInstantB 2)] [:db/add :db/tx :x 123]]))] (is (= txInstantC (+ txInstantB 2))) (is (= (<? (<transactions-after (d/db conn) txb)) [[txc :db/txInstant txInstantC txc 1] [txc :x 123 txc 1]])) (testing "additional datoms can be added, without :db/txInstant explicitly" (let [{txd :tx txInstantD :txInstant} (<? (d/<transact! conn [[:db/add :db/tx :x 456]]))] (is (= (<? (<transactions-after (d/db conn) txc)) [[txd :db/txInstant txInstantD txd 1] [txd :x 456 txd 1]])))))))))) (deftest-db test-no-tx conn (let [{tx0 :tx} (<? (d/<transact! conn test-schema))] (testing "Cannot specificy an explicit tx" (is (thrown-with-msg? ExceptionInfo #"Bad entity: too long" (<? (d/<transact! conn [[:db/add (d/id-literal :db.part/user) :x 0 10101]]))))))) (deftest-db test-explode-sequences conn (let [{tx0 :tx} (<? (d/<transact! conn test-schema))] (testing ":db.cardinality/many sequences are accepted" (<? (d/<transact! conn [{:db/id 101 :aka ["first" "second"]}])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :aka "first"] [101 :aka "second"]}))) (testing ":db.cardinality/many sequences are recursively applied, allowing unexpected sequence nesting" (<? (d/<transact! conn [{:db/id 102 :aka [[["first"]] ["second"]]}])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :aka "first"] [101 :aka "second"] [102 :aka "first"] [102 :aka "second"]}))) (testing ":db.cardinality/one sequences fail" (is (thrown-with-msg? ExceptionInfo #"Sequential values" (<? (d/<transact! conn [{:db/id 101 :email ["@1" "@2"]}]))))))) (deftest-db test-explode-maps conn (let [{tx0 :tx} (<? (d/<transact! conn test-schema))] (testing "nested maps are accepted" (<? (d/<transact! conn [{:db/id 101 :friends {:name "Petr"}}])) ;; TODO: this works only because we have a single friend. (let [{petr :friends} (<? (<shallow-entity (d/db conn) 101))] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :friends petr] [petr :name "Petr"]})))) (testing "recursively nested maps are accepted" (<? (d/<transact! conn [{:db/id 102 :friends {:name "Ivan" :friends {:name "Petr"}}}])) ;; This would be much easier with `entity` and lookup refs. (let [{ivan :friends} (<? (<shallow-entity (d/db conn) 102)) {petr :friends} (<? (<shallow-entity (d/db conn) ivan))] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :friends petr] [petr :name "Petr"] [102 :friends ivan] [ivan :name "Ivan"] [ivan :friends petr]})))) (testing "nested maps without :db.type/ref fail" (is (thrown-with-msg? ExceptionInfo #"\{:db/valueType :db.type/ref\}" (<? (d/<transact! conn [{:db/id 101 :aka {:name "Petr"}}]))))))) (deftest-db test-explode-maps-with-db-id conn (let [{tx0 :tx} (<? (d/<transact! conn test-schema))] (testing "recursively nested maps with specified :db/id are accepted" (<? (d/<transact! conn [{:db/id 101 :name "Oleg"}])) (<? (d/<transact! conn [{:db/id 101 :friends {:db/id 201 :name "Ivan" :friends {:db/id 301 :name "Petr"}}}])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :name "Oleg"] [101 :friends 201] [201 :name "Ivan"] [201 :friends 301 ] [301 :name "Petr"]}))))) (deftest-db test-explode-reverse-refs conn (let [{tx0 :tx} (<? (d/<transact! conn test-schema))] (testing "reverse refs are accepted" (<? (d/<transact! conn [{:db/id 101 :name "Igor"}])) (<? (d/<transact! conn [{:db/id 102 :name "Oleg" :_friends 101}])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :name "Igor"] [102 :name "Oleg"] [101 :friends 102]}))) (testing "reverse refs without :db.type/ref fail" (is (thrown-with-msg? ExceptionInfo #"\{:db/valueType :db.type/ref\}" (<? (d/<transact! conn [{:db/id 101 :_aka 102}]))))))) ;; We don't use deftest-db in order to be able to re-open an on disk file. (deftest-async test-next-eid (with-tempfile [t (tempfile)] (let [conn (<? (d/<connect t)) {tx0 :tx} (<? (d/<transact! conn test-schema))] (testing "entids are increasing, tx ids are larger than user ids" (let [r1 (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :name "Igor"}])) r2 (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -2) :name "Oleg"}])) e1 (get (tempids r1) -1) e2 (get (tempids r2) -2)] (is (< e1 (:tx r1))) (is (< e2 (:tx r2))) (is (< e1 e2)) (is (< (:tx r1) (:tx r2))) ;; Close and re-open same DB. (<? (d/<close conn)) (let [conn (<? (d/<connect t))] (try (testing "entid counters are persisted across re-opens" (let [r3 (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -3) :name "Petr"}])) e3 (get (tempids r3) -3)] (is (< e3 (:tx r3))) (is (< e2 e3)) (is (< (:tx r2) (:tx r3))))) (finally (<? (d/<close conn)))))))))) (deftest-db test-unique-value conn (let [tx0 (:tx (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :db/ident :test/x :db/unique :db.unique/value :db/valueType :db.type/long :db.install/_attribute :db.part/db} {:db/id (d/id-literal :db.part/user -2) :db/ident :test/y :db/unique :db.unique/value :db/valueType :db.type/long :db.install/_attribute :db.part/db}])))] (testing "can insert different :db.unique/value attributes with the same value" (let [report1 (<? (d/<transact! conn [[:db/add (d/id-literal :db.part/user -1) :test/x 12345]])) eid1 (get-in report1 [:tempids (d/id-literal :db.part/user -1)]) report2 (<? (d/<transact! conn [[:db/add (d/id-literal :db.part/user -2) :test/y 12345]])) eid2 (get-in report2 [:tempids (d/id-literal :db.part/user -2)])] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/x 12345] [eid2 :test/y 12345]})))) (testing "can't upsert a :db.unique/value field" (is (thrown-with-msg? ExceptionInfo #"unique constraint" (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :test/x 12345 :test/y 99999}]))))))) (def retract-schema [{:db/id (d/id-literal :db.part/user -1) :db/ident :test/long :db/cardinality :db.cardinality/many :db/valueType :db.type/long :db.install/_attribute :db.part/db} {:db/id (d/id-literal :db.part/user -2) :db/ident :test/fulltext :db/cardinality :db.cardinality/many :db/valueType :db.type/string :db/fulltext true :db.install/_attribute :db.part/db} {:db/id (d/id-literal :db.part/user -3) :db/ident :test/ref :db/valueType :db.type/ref :db.install/_attribute :db.part/db}]) (deftest-db test-retract-attribute conn (let [tx0 (:tx (<? (d/<transact! conn retract-schema)))] (testing "retractAttribute" (let [report (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :test/long [12345 123456]} {:db/id (d/id-literal :db.part/user -2) :test/ref (d/id-literal :db.part/user -1)}])) eid1 (get-in report [:tempids (d/id-literal :db.part/user -1)]) eid2 (get-in report [:tempids (d/id-literal :db.part/user -2)])] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/long 12345] [eid1 :test/long 123456] [eid2 :test/ref eid1]})) (testing "retractAttribute with no matching datoms succeeds" (<? (d/<transact! conn [[:db.fn/retractAttribute eid1 :test/ref]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/long 12345] [eid1 :test/long 123456] [eid2 :test/ref eid1]}))) (testing "retractAttribute retracts datoms" (let [{tx1 :tx} (<? (d/<transact! conn [[:db.fn/retractAttribute eid2 :test/ref]]))] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/long 12345] [eid1 :test/long 123456]}))) (let [{tx2 :tx} (<? (d/<transact! conn [[:db.fn/retractAttribute eid1 :test/long]]))] (is (= (<? (<datoms-after (d/db conn) tx0)) #{})))))))) (deftest-db test-retract-attribute-multiple conn (let [tx0 (:tx (<? (d/<transact! conn retract-schema)))] (let [report (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :test/long [12345 123456]} {:db/id (d/id-literal :db.part/user -1) :test/fulltext ["1 fulltext value" "2 fulltext value"]}])) eid1 (get-in report [:tempids (d/id-literal :db.part/user -1)])] (is (= (<? (<fulltext-values (d/db conn))) [[1 "1 fulltext value"] [2 "2 fulltext value"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/fulltext 1] [eid1 :test/fulltext 2] [eid1 :test/long 12345] [eid1 :test/long 123456]})) (testing "multiple retractAttribute in one transaction" (let [{tx1 :tx} (<? (d/<transact! conn [[:db.fn/retractAttribute eid1 :test/long] [:db.fn/retractAttribute eid1 :test/fulltext]]))] (is (= (<? (<datoms-after (d/db conn) tx0)) #{}))))))) (deftest-db test-retract-attribute-fulltext conn (let [tx0 (:tx (<? (d/<transact! conn retract-schema)))] (testing "retractAttribute, fulltext" (let [report (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :test/fulltext ["1 fulltext value" "2 fulltext value"]} {:db/id (d/id-literal :db.part/user -2) :test/ref (d/id-literal :db.part/user -1)}])) eid1 (get-in report [:tempids (d/id-literal :db.part/user -1)]) eid2 (get-in report [:tempids (d/id-literal :db.part/user -2)])] (is (= (<? (<fulltext-values (d/db conn))) [[1 "1 fulltext value"] [2 "2 fulltext value"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/fulltext 1] [eid1 :test/fulltext 2] [eid2 :test/ref eid1]})) (testing "retractAttribute retracts datoms, fulltext" (let [{tx1 :tx} (<? (d/<transact! conn [[:db.fn/retractAttribute eid2 :test/ref]]))] ;; fulltext values are not purged. (is (= (<? (<fulltext-values (d/db conn))) [[1 "1 fulltext value"] [2 "2 fulltext value"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/fulltext 1] [eid1 :test/fulltext 2]}))) (let [{tx2 :tx} (<? (d/<transact! conn [[:db.fn/retractAttribute eid1 :test/fulltext]]))] ;; fulltext values are not purged. (is (= (<? (<fulltext-values (d/db conn))) [[1 "1 fulltext value"] [2 "2 fulltext value"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{})))))))) (deftest-db test-retract-entity conn (let [tx0 (:tx (<? (d/<transact! conn retract-schema)))] (testing "retractEntity" (let [report (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :test/long [12345 123456]} {:db/id (d/id-literal :db.part/user -2) :test/ref (d/id-literal :db.part/user -1)} {:db/id (d/id-literal :db.part/user -3) :test/long 0xdeadbeef}])) eid1 (get-in report [:tempids (d/id-literal :db.part/user -1)]) eid2 (get-in report [:tempids (d/id-literal :db.part/user -2)]) eid3 (get-in report [:tempids (d/id-literal :db.part/user -3)])] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/long 12345] [eid1 :test/long 123456] [eid2 :test/ref eid1] [eid3 :test/long 0xdeadbeef]})) (testing "retractEntity with no matching datoms succeeds" (<? (d/<transact! conn [[:db.fn/retractEntity 0xdeadbeef]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/long 12345] [eid1 :test/long 123456] [eid2 :test/ref eid1] [eid3 :test/long 0xdeadbeef]}))) (testing "retractEntity retracts datoms" (let [{tx1 :tx} (<? (d/<transact! conn [[:db.fn/retractEntity eid3]]))] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/long 12345] [eid1 :test/long 123456] [eid2 :test/ref eid1]})))) (testing "retractEntity retracts datoms and references" (let [{tx2 :tx} (<? (d/<transact! conn [[:db.fn/retractEntity eid1]]))] (is (= (<? (<datoms-after (d/db conn) tx0)) ;; [eid2 :test/ref eid1] is gone, since the ref eid1 is gone. #{})))))))) (deftest-db test-retract-entity-multiple conn (let [tx0 (:tx (<? (d/<transact! conn retract-schema)))] (let [report (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :test/long [12345 123456]} {:db/id (d/id-literal :db.part/user -2) :test/fulltext ["1 fulltext value" "2 fulltext value"]}])) eid1 (get-in report [:tempids (d/id-literal :db.part/user -1)]) eid2 (get-in report [:tempids (d/id-literal :db.part/user -2)])] (is (= (<? (<fulltext-values (d/db conn))) [[1 "1 fulltext value"] [2 "2 fulltext value"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid2 :test/fulltext 1] [eid2 :test/fulltext 2] [eid1 :test/long 12345] [eid1 :test/long 123456]})) (testing "multiple retractEntity in one transaction" (let [{tx1 :tx} (<? (d/<transact! conn [[:db.fn/retractEntity eid1] [:db.fn/retractEntity eid2]]))] (is (= (<? (<datoms-after (d/db conn) tx0)) #{}))))))) (deftest-db test-retract-entity-fulltext conn (let [tx0 (:tx (<? (d/<transact! conn retract-schema)))] (testing "retractEntity, fulltext" (let [report (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :test/fulltext ["1 fulltext value" "2 fulltext value"]} {:db/id (d/id-literal :db.part/user -2) :test/ref (d/id-literal :db.part/user -1)} {:db/id (d/id-literal :db.part/user -3) :test/fulltext "3 fulltext value"}])) eid1 (get-in report [:tempids (d/id-literal :db.part/user -1)]) eid2 (get-in report [:tempids (d/id-literal :db.part/user -2)]) eid3 (get-in report [:tempids (d/id-literal :db.part/user -3)])] (is (= (<? (<fulltext-values (d/db conn))) [[1 "1 fulltext value"] [2 "2 fulltext value"] [3 "3 fulltext value"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/fulltext 1] [eid1 :test/fulltext 2] [eid2 :test/ref eid1] [eid3 :test/fulltext 3]})) (testing "retractEntity with no matching datoms succeeds, fulltext" (<? (d/<transact! conn [[:db.fn/retractEntity 0xdeadbeef]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/fulltext 1] [eid1 :test/fulltext 2] [eid2 :test/ref eid1] [eid3 :test/fulltext 3]}))) (testing "retractEntity retracts datoms, fulltext" (let [{tx1 :tx} (<? (d/<transact! conn [[:db.fn/retractEntity eid3]]))] ;; fulltext values are not purged. (is (= (<? (<fulltext-values (d/db conn))) [[1 "1 fulltext value"] [2 "2 fulltext value"] [3 "3 fulltext value"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/fulltext 1] [eid1 :test/fulltext 2] [eid2 :test/ref eid1]})))) (testing "retractEntity retracts datoms and references, fulltext" (let [{tx2 :tx} (<? (d/<transact! conn [[:db.fn/retractEntity eid1]]))] (is (= (<? (<datoms-after (d/db conn) tx0)) ;; [eid2 :test/ref eid1] is gone, since the ref eid1 is gone. #{})))))))) ;; We don't use deftest-db in order to be able to re-open an on disk file. (deftest-async test-reopen-schema (with-tempfile [t (tempfile)] (let [conn (<? (d/<connect t)) test-schema [{:db/id (d/id-literal :db.part/user -1) :db/ident :test/fulltext :db/cardinality :db.cardinality/many :db/valueType :db.type/string :db/fulltext true :db/doc "Documentation string" :db.install/_attribute :db.part/db}] {tx0 :tx} (<? (d/<transact! conn test-schema))] (testing "Values in schema are correct initially" (let [db (d/db conn) schema (d/schema db)] (is (= true (ds/indexing? schema (d/entid db :db/txInstant)))) (is (= true (ds/fulltext? schema (d/entid db :test/fulltext)))) (is (= "Documentation string" (ds/doc schema (d/entid db :test/fulltext)))) (is (= :db.type/string (ds/valueType schema (d/entid db :test/fulltext)))))) ;; Close and re-open same DB. (<? (d/<close conn)) (let [conn (<? (d/<connect t))] (try (testing "Boolean values in schema are correct after re-opening" (let [db (d/db conn) schema (d/schema db)] (is (= true (ds/indexing? schema (d/entid db :db/txInstant)))) (is (= true (ds/fulltext? schema (d/entid db :test/fulltext)))) (is (= "Documentation string" (ds/doc schema (d/entid db :test/fulltext)))) (is (= :db.type/string (ds/valueType schema (d/entid db :test/fulltext)))))) (finally (<? (d/<close conn)))))))) (deftest-db test-simple-schema conn (let [in {:name "mystuff" :attributes [{:name "foo/age" :type "long" :cardinality "one"} {:name "foo/name" :type "string" :cardinality "many" :doc "People can have many names."} {:name "foo/id" :type "string" :cardinality "one" :unique "value"}]} expected [{:db/ident :foo/age :db/valueType :db.type/long :db/cardinality :db.cardinality/one :db.install/_attribute :db.part/db} {:db/ident :foo/name :db/valueType :db.type/string :db/cardinality :db.cardinality/many :db/doc "People can have many names." :db.install/_attribute :db.part/db} {:db/ident :foo/id :db/valueType :db.type/string :db/cardinality :db.cardinality/one :db/unique :db.unique/value :db.install/_attribute :db.part/db}]] (testing "Simple schemas are expanded." (is (= (map #(dissoc %1 :db/id) (datomish.simple-schema/simple-schema->schema in)) expected))))) (deftest-db test-lookup-refs conn (let [{tx0 :tx} (<? (d/<transact! conn test-schema)) {tx1 :tx} (<? (d/<transact! conn [[:db/add 1 :name "Ivan"] [:db/add 2 :name "Phil"] [:db/add 3 :name "Petr"]]))] (testing "Looks up entity refs" (let [{tx :tx} (<? (d/<transact! conn [[:db/add (d/lookup-ref :name "Ivan") :aka "Devil"] [:db/add (d/lookup-ref :name "Phil") :email "@1"]]))] (is (= #{[1 :name "Ivan"] [2 :name "Phil"] [3 :name "Petr"] [1 :aka "Devil"] [2 :email "@1"]} (<? (<datoms>= (d/db conn) tx1)))))) (testing "Looks up value refs" (let [{tx :tx} (<? (d/<transact! conn [[:db/add 1 :friends (d/lookup-ref :name "Petr")] [:db/add 3 :friends (d/lookup-ref :name "Ivan")]]))] (is (= #{[1 :friends 3] [3 :friends 1]} (<? (<datoms>= (d/db conn) tx)))))) (testing "Looks up entity refs in maps" (let [{tx :tx} (<? (d/<transact! conn [{:db/id (d/lookup-ref :name "Phil") :friends 1}]))] (is (= #{[2 :friends 1]} (<? (<datoms>= (d/db conn) tx)))))) (testing "Looks up value refs in maps" (let [{tx :tx} (<? (d/<transact! conn [{:db/id 2 :friends (d/lookup-ref :name "Petr")}]))] (is (= #{[2 :friends 3]} (<? (<datoms>= (d/db conn) tx)))))) (testing "Looks up value refs in sequences in maps" (let [{tx :tx} (<? (d/<transact! conn [{:db/id 1 :friends [(d/lookup-ref :name "Ivan") (d/lookup-ref :name "Phil")]}]))] (is (= #{[1 :friends 1] [1 :friends 2]} (<? (<datoms>= (d/db conn) tx)))))) (testing "Looks up refs when there are more than 999 refs (all present)" (let [bound (* 999 2) make-add #(vector :db/add (+ 1000 %) :name (str "Ivan-" %)) make-ref #(-> {:db/id (d/lookup-ref :name (str "Ivan-" %)) :email (str "Ivan-" % "@" %)}) {tx-data1 :tx-data} (<? (d/<transact! conn (map make-add (range bound)))) {tx-data2 :tx-data} (<? (d/<transact! conn (map make-ref (range bound))))] (is (= bound (dec (count tx-data1)))) ;; Each :name is new; dec to account for :db/tx. (is (= bound (dec (count tx-data2)))) ;; Each lookup-ref exists, each :email is new; dec for :db/tx. )) (testing "Fails for missing entities" (is (thrown-with-msg? ExceptionInfo #"No entity found for lookup-ref" (<? (d/<transact! conn [[:db/add (d/lookup-ref :name "Mysterioso") :aka "The Magician"]])))) (is (thrown-with-msg? ExceptionInfo #"No entity found for lookup-ref" (<? (d/<transact! conn [[:db/add 1 :friends (d/lookup-ref :name "Mysterioso")]]))))) (testing "Fails for non-identity attributes" (is (thrown-with-msg? ExceptionInfo #"Lookup-ref found with non-unique-identity attribute" (<? (d/<transact! conn [[:db/add (d/lookup-ref :aka "The Magician") :email "@2"]])))) (is (thrown-with-msg? ExceptionInfo #"Lookup-ref found with non-unique-identity attribute" (<? (d/<transact! conn [[:db/add 1 :friends (d/lookup-ref :aka "The Magician")]]))))))) (deftest-db test-fulltext-lookup-refs conn (let [schema [{:db/id (d/id-literal :db.part/db -1) :db/ident :test/fulltext :db/valueType :db.type/string :db/fulltext true :db/unique :db.unique/identity} {:db/id :db.part/db :db.install/attribute (d/id-literal :db.part/db -1)} {:db/id (d/id-literal :db.part/db -2) :db/ident :test/other :db/valueType :db.type/string :db/fulltext true :db/cardinality :db.cardinality/one} {:db/id :db.part/db :db.install/attribute (d/id-literal :db.part/db -2)} ] tx0 (:tx (<? (d/<transact! conn schema)))] (testing "Can look up fulltext refs" (<? (d/<transact! conn [[:db/add 101 :test/fulltext "test this"]])) (let [{tx :tx} (<? (d/<transact! conn [{:db/id (d/lookup-ref :test/fulltext "test this") :test/other "test other"}]))] (is (= (<? (<fulltext-values (d/db conn))) [[1 "test this"] [2 "test other"]])) (is (= #{[101 :test/other 2]} ;; Values are raw; 2 is the rowid into fulltext_values. (<? (<datoms>= (d/db conn) tx)))))) (testing "Fails for missing fulltext entities" (is (thrown-with-msg? ExceptionInfo #"No entity found for lookup-ref" (<? (d/<transact! conn [[:db/add (d/lookup-ref :test/fulltext "not found") :test/other "test random"]]))))))) #_ (time (t/run-tests)) #_ (time (clojure.test/test-vars [#'test-lookup-refs]))
104160
;; Copyright 2016 Mozilla ;; ;; 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 datomish.db-test #?(:cljs (:require-macros [datomish.pair-chan :refer [go-pair <?]] [datomish.node-tempfile-macros :refer [with-tempfile]] [cljs.core.async.macros :as a :refer [go]])) (:require [datomish.api :as d] [datomish.db.debug :refer [<datoms-after <datoms>= <transactions-after <shallow-entity <fulltext-values]] [datomish.util :as util #?(:cljs :refer-macros :clj :refer) [raise cond-let]] [datomish.schema :as ds] [datomish.simple-schema] [datomish.sqlite :as s] [datomish.sqlite-schema] [datomish.datom] #?@(:clj [[datomish.jdbc-sqlite] [datomish.pair-chan :refer [go-pair <?]] [tempfile.core :refer [tempfile with-tempfile]] [datomish.test-macros :refer [deftest-async deftest-db]] [clojure.test :as t :refer [is are deftest testing]] [clojure.core.async :refer [go <! >!]]]) #?@(:cljs [[datomish.js-sqlite] [datomish.pair-chan] [datomish.test-macros :refer-macros [deftest-async deftest-db]] [datomish.node-tempfile :refer [tempfile]] [cljs.test :as t :refer-macros [is are deftest testing async]] [cljs.core.async :as a :refer [<! >!]]])) #?(:clj (:import [clojure.lang ExceptionInfo])) #?(:clj (:import [datascript.db DB]))) #?(:cljs (def Throwable js/Error)) (defn- tempids [tx] (into {} (map (juxt (comp :idx first) second) (:tempids tx)))) (def test-schema [{:db/id (d/id-literal :db.part/user) :db/ident :x :db/unique :db.unique/identity :db/valueType :db.type/long :db.install/_attribute :db.part/db} {:db/id (d/id-literal :db.part/user) :db/ident :name :db/unique :db.unique/identity :db/valueType :db.type/string :db.install/_attribute :db.part/db} {:db/id (d/id-literal :db.part/user) :db/ident :y :db/cardinality :db.cardinality/many :db/valueType :db.type/long :db.install/_attribute :db.part/db} {:db/id (d/id-literal :db.part/user) :db/ident :aka :db/cardinality :db.cardinality/many :db/valueType :db.type/string :db.install/_attribute :db.part/db} {:db/id (d/id-literal :db.part/user) :db/ident :age :db/valueType :db.type/long :db.install/_attribute :db.part/db} {:db/id (d/id-literal :db.part/user) :db/ident :email :db/unique :db.unique/identity :db/valueType :db.type/string :db.install/_attribute :db.part/db} {:db/id (d/id-literal :db.part/user) :db/ident :spouse :db/unique :db.unique/value :db/valueType :db.type/string :db.install/_attribute :db.part/db} {:db/id (d/id-literal :db.part/user) :db/ident :friends :db/cardinality :db.cardinality/many :db/valueType :db.type/ref :db.install/_attribute :db.part/db} ]) (deftest-db test-add-one conn (let [{tx0 :tx} (<? (d/<transact! conn test-schema))] (let [{:keys [tx txInstant]} (<? (d/<transact! conn [[:db/add 0 :name "valuex"]]))] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[0 :name "valuex"]})) (is (= (<? (<transactions-after (d/db conn) tx0)) [[0 :name "valuex" tx 1] ;; TODO: true, not 1. [tx :db/txInstant txInstant tx 1]]))))) (deftest-db test-add-two conn (let [{tx0 :tx} (<? (d/<transact! conn test-schema)) {tx1 :tx txInstant1 :txInstant} (<? (d/<transact! conn [[:db/add 1 :name "<NAME>"]])) {tx2 :tx txInstant2 :txInstant} (<? (d/<transact! conn [[:db/add 1 :name "<NAME>"]])) {tx3 :tx txInstant3 :txInstant} (<? (d/<transact! conn [[:db/add 1 :aka "Tupen"]])) {tx4 :tx txInstant4 :txInstant} (<? (d/<transact! conn [[:db/add 1 :aka "Devil"]]))] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[1 :name "<NAME>"] [1 :aka "Tupen"] [1 :aka "Devil"]})) (is (= (<? (<transactions-after (d/db conn) tx0)) [[1 :name "<NAME>" tx1 1] ;; TODO: true, not 1. [tx1 :db/txInstant txInstant1 tx1 1] [1 :name "<NAME>" tx2 0] [1 :name "<NAME>" tx2 1] [tx2 :db/txInstant txInstant2 tx2 1] [1 :aka "<NAME>" tx3 1] [tx3 :db/txInstant txInstant3 tx3 1] [1 :aka "<NAME>" tx4 1] [tx4 :db/txInstant txInstant4 tx4 1]])))) (deftest-db test-retract conn (let [{tx0 :tx} (<? (d/<transact! conn test-schema)) {tx1 :tx txInstant1 :txInstant} (<? (d/<transact! conn [[:db/add 0 :x 123]])) {tx2 :tx txInstant2 :txInstant} (<? (d/<transact! conn [[:db/retract 0 :x 123]]))] (is (= (<? (<datoms-after (d/db conn) tx0)) #{})) (is (= (<? (<transactions-after (d/db conn) tx0)) [[0 :x 123 tx1 1] [tx1 :db/txInstant txInstant1 tx1 1] [0 :x 123 tx2 0] [tx2 :db/txInstant txInstant2 tx2 1]])))) (deftest-db test-id-literal-1 conn (let [tx0 (:tx (<? (d/<transact! conn test-schema))) report (<? (d/<transact! conn [[:db/add (d/id-literal :db.part/user -1) :x 0] [:db/add (d/id-literal :db.part/user -1) :y 1] [:db/add (d/id-literal :db.part/user -2) :y 2] [:db/add (d/id-literal :db.part/user -2) :y 3]]))] (is (= (keys (:tempids report)) ;; TODO: include values. [(d/id-literal :db.part/user -1) (d/id-literal :db.part/user -2)])) (let [eid1 (get-in report [:tempids (d/id-literal :db.part/user -1)]) eid2 (get-in report [:tempids (d/id-literal :db.part/user -2)])] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :x 0] [eid1 :y 1] [eid2 :y 2] [eid2 :y 3]}))))) (deftest-db test-unique conn (let [tx0 (:tx (<? (d/<transact! conn test-schema)))] (testing "Multiple :db/unique values in tx-data violate unique constraint, no tempid" (is (thrown-with-msg? ExceptionInfo #"unique constraint" (<? (d/<transact! conn [[:db/add 1 :x 0] [:db/add 2 :x 0]]))))) (testing "Multiple :db/unique values in tx-data violate unique constraint, tempid" (is (thrown-with-msg? ExceptionInfo #"unique constraint" (<? (d/<transact! conn [[:db/add (d/id-literal :db.part/user -1) :spouse "Dana"] [:db/add (d/id-literal :db.part/user -2) :spouse "Dana"]]))))))) (deftest-db test-valueType-keyword conn (let [tx0 (:tx (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :db/ident :test/kw :db/unique :db.unique/identity :db/valueType :db.type/keyword} {:db/id :db.part/db :db.install/attribute (d/id-literal :db.part/user -1)}])))] (let [report (<? (d/<transact! conn [[:db/add (d/id-literal :db.part/user -1) :test/kw :test/kw1]])) eid (get-in report [:tempids (d/id-literal :db.part/user -1)])] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid :test/kw ":test/kw1"]})) ;; Value is raw. (testing "Adding the same value compares existing values correctly." (<? (d/<transact! conn [[:db/add eid :test/kw :test/kw1]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid :test/kw ":test/kw1"]}))) ;; Value is raw. (testing "Upserting retracts existing value correctly." (<? (d/<transact! conn [[:db/add eid :test/kw :test/kw2]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid :test/kw ":test/kw2"]}))) ;; Value is raw. (testing "Retracting compares values correctly." (<? (d/<transact! conn [[:db/retract eid :test/kw :test/kw2]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{})))))) (deftest-db test-vector-upsert conn ;; Not having DB-as-value really hurts us here. This test only works because all upserts ;; succeed on top of each other, so we never need to reset the underlying store. (<? (d/<transact! conn test-schema)) (let [tx0 (:tx (<? (d/<transact! conn [{:db/id 101 :name "<NAME>" :email "@1"} {:db/id 102 :name "<NAME>" :email "@2"}])))] (testing "upsert with tempid" (let [report (<? (d/<transact! conn [[:db/add (d/id-literal :db.part/user -1) :name "<NAME>"] [:db/add (d/id-literal :db.part/user -1) :age 12]]))] (is (= (<? (<shallow-entity (d/db conn) 101)) {:name "<NAME>" :age 12 :email "@1"})) (is (= (tempids report) {-1 101})))) (testing "upsert with tempid, order does not matter" (let [report (<? (d/<transact! conn [[:db/add (d/id-literal :db.part/user -1) :age 13] [:db/add (d/id-literal :db.part/user -1) :name "<NAME>"]]))] (is (= (<? (<shallow-entity (d/db conn) 102)) {:name "<NAME>" :age 13 :email "@2"})) (is (= (tempids report) {-1 102})))) (testing "Conflicting upserts fail" (is (thrown-with-msg? Throwable #"Conflicting upsert" (<? (d/<transact! conn [[:db/add (d/id-literal :db.part/user -1) :name "<NAME>"] [:db/add (d/id-literal :db.part/user -1) :age 35] [:db/add (d/id-literal :db.part/user -1) :name "<NAME>"] [:db/add (d/id-literal :db.part/user -1) :age 36]]))))))) (deftest-db test-multistep-upsert conn (<? (d/<transact! conn test-schema)) ;; The upsert algorithm will first try to resolve -1, fail, and then allocate both -1 and -2. (let [tx0 (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :name "<NAME>" :email "@1"} {:db/id (d/id-literal :db.part/user -2) :name "<NAME>" :friends (d/id-literal :db.part/user -1)}]))] ;; Sanity checks that these are freshly allocated, not resolved. (is (> (get (tempids tx0) -1) 1000)) (is (> (get (tempids tx0) -1) 1000)) ;; This time, we can resolve both, but we have to try -1, succeed, and then resolve -2. (let [tx1 (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :name "<NAME>" :email "@1"} {:db/id (d/id-literal :db.part/user -2) :name "<NAME>" :friends (d/id-literal :db.part/user -1)}]))] ;; Ensure these are resolved, not freshly allocated. (is (= (tempids tx0) (tempids tx1)))))) (deftest-db test-map-upsert conn ;; Not having DB-as-value really hurts us here. This test only works because all upserts ;; succeed on top of each other, so we never need to reset the underlying store. (<? (d/<transact! conn test-schema)) (let [tx0 (:tx (<? (d/<transact! conn [{:db/id 101 :name "<NAME>" :email "@1"} {:db/id 102 :name "<NAME>" :email "@2"}])))] (testing "upsert with tempid" (let [tx (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :name "<NAME>" :age 35}]))] (is (= (<? (<shallow-entity (d/db conn) 101)) {:name "<NAME>" :email "@1" :age 35})) (is (= (tempids tx) {-1 101})))) (testing "upsert by 2 attrs with tempid" (let [tx (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :name "<NAME>" :email "@1" :age 35}]))] (is (= (<? (<shallow-entity (d/db conn) 101)) {:name "<NAME>" :email "@1" :age 35})) (is (= (tempids tx) {-1 101})))) (testing "upsert with existing id" (let [tx (<? (d/<transact! conn [{:db/id 101 :name "<NAME>" :age 36}]))] (is (= (<? (<shallow-entity (d/db conn) 101)) {:name "<NAME>" :email "@1" :age 36})) (is (= (tempids tx) {})))) (testing "upsert by 2 attrs with existing id" (let [tx (<? (d/<transact! conn [{:db/id 101 :name "<NAME>" :email "@1" :age 37}]))] (is (= (<? (<shallow-entity (d/db conn) 101)) {:name "<NAME>" :email "@1" :age 37})) (is (= (tempids tx) {})))) (testing "upsert to two entities, resolve to same tempid, fails due to overlapping writes" (is (thrown-with-msg? Throwable #"cardinality constraint" (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :name "<NAME>" :age 35} {:db/id (d/id-literal :db.part/user -1) :name "<NAME>" :age 36}]))))) (testing "upsert to two entities, two tempids, fails due to overlapping writes" (is (thrown-with-msg? Throwable #"cardinality constraint" (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :name "<NAME>" :age 35} {:db/id (d/id-literal :db.part/user -2) :name "<NAME>" :age 36}]))))))) (deftest-db test-map-upsert-conflicts conn ;; Not having DB-as-value really hurts us here. This test only works because all upserts ;; fail until the final one, so we never need to reset the underlying store. (<? (d/<transact! conn test-schema)) (let [tx0 (:tx (<? (d/<transact! conn [{:db/id 101 :name "<NAME>" :email "@1"} {:db/id 102 :name "<NAME>" :email "@2"}])))] ;; TODO: improve error message to refer to upsert inputs. (testing "upsert conficts with existing id" (is (thrown-with-msg? Throwable #"unique constraint" (<? (d/<transact! conn [{:db/id 102 :name "<NAME>" :age 36}]))))) ;; TODO: improve error message to refer to upsert inputs. (testing "upsert conficts with non-existing id" (is (thrown-with-msg? Throwable #"unique constraint" (<? (d/<transact! conn [{:db/id 103 :name "<NAME>" :age 36}]))))) ;; TODO: improve error message to refer to upsert inputs. (testing "upsert by 2 conflicting fields" (is (thrown-with-msg? Throwable #"Conflicting upsert" (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :name "<NAME>" :email "@2" :age 35}]))))) (testing "upsert by non-existing value resolves as update" (let [report (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :name "<NAME>" :email "@3" :age 35}]))] (is (= (<? (<shallow-entity (d/db conn) 101)) {:name "<NAME>" :email "@3" :age 35})) (is (= (tempids report) {-1 101})))))) (deftest-db test-add-schema conn (let [es [[:db/add :db.part/db :db.install/attribute (d/id-literal :db.part/db -1)] {:db/id (d/id-literal :db.part/db -1) :db/ident :test/attr :db/valueType :db.type/string :db/cardinality :db.cardinality/one}] report (<? (d/<transact! conn es)) db-after (:db-after report) tx (:tx db-after)] (testing "New ident is allocated" (is (some? (d/entid db-after :test/attr)))) (testing "Schema is modified" (is (= (get-in db-after [:symbolic-schema :test/attr]) {:db/valueType :db.type/string, :db/cardinality :db.cardinality/one}))) (testing "Schema is used in subsequent transaction" (<? (d/<transact! conn [{:db/id 100 :test/attr "value 1"}])) (<? (d/<transact! conn [{:db/id 100 :test/attr "value 2"}])) (is (= (<? (<shallow-entity (d/db conn) 100)) {:test/attr "value 2"}))))) (deftest-db test-fulltext conn (let [schema [{:db/id (d/id-literal :db.part/db -1) :db/ident :test/fulltext :db/valueType :db.type/string :db/fulltext true :db/unique :db.unique/identity} {:db/id :db.part/db :db.install/attribute (d/id-literal :db.part/db -1)} {:db/id (d/id-literal :db.part/db -2) :db/ident :test/other :db/valueType :db.type/string :db/fulltext true :db/cardinality :db.cardinality/one} {:db/id :db.part/db :db.install/attribute (d/id-literal :db.part/db -2)} ] tx0 (:tx (<? (d/<transact! conn schema)))] (testing "Schema checks" (is (ds/fulltext? (d/schema (d/db conn)) (d/entid (d/db conn) :test/fulltext)))) (testing "Can add fulltext indexed datoms" (let [{tx1 :tx txInstant1 :txInstant} (<? (d/<transact! conn [[:db/add 101 :test/fulltext "test this"]]))] (is (= (<? (<fulltext-values (d/db conn))) [[1 "test this"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :test/fulltext 1]})) ;; Values are raw; 1 is the rowid into fulltext_values. (is (= (<? (<transactions-after (d/db conn) tx0)) [[101 :test/fulltext 1 tx1 1] ;; Values are raw; 1 is the rowid into fulltext_values. [tx1 :db/txInstant txInstant1 tx1 1]])) (testing "Can replace fulltext indexed datoms" (let [{tx2 :tx txInstant2 :txInstant} (<? (d/<transact! conn [[:db/add 101 :test/fulltext "alternate thing"]]))] (is (= (<? (<fulltext-values (d/db conn))) [[1 "test this"] [2 "alternate thing"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :test/fulltext 2]})) ;; Values are raw; 2 is the rowid into fulltext_values. (is (= (<? (<transactions-after (d/db conn) tx0)) [[101 :test/fulltext 1 tx1 1] ;; Values are raw; 1 is the rowid into fulltext_values. [tx1 :db/txInstant txInstant1 tx1 1] [101 :test/fulltext 1 tx2 0] ;; Values are raw; 1 is the rowid into fulltext_values. [101 :test/fulltext 2 tx2 1] ;; Values are raw; 2 is the rowid into fulltext_values. [tx2 :db/txInstant txInstant2 tx2 1]])) (testing "Can upsert keyed by fulltext indexed datoms" (let [{tx3 :tx txInstant3 :txInstant} (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user) :test/fulltext "alternate thing" :test/other "other"}]))] (is (= (<? (<fulltext-values (d/db conn))) [[1 "test this"] [2 "alternate thing"] [3 "other"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :test/fulltext 2] ;; Values are raw; 2, 3 are the rowids into fulltext_values. [101 :test/other 3]})) (is (= (<? (<transactions-after (d/db conn) tx0)) [[101 :test/fulltext 1 tx1 1] ;; Values are raw; 1 is the rowid into fulltext_values. [tx1 :db/txInstant txInstant1 tx1 1] [101 :test/fulltext 1 tx2 0] ;; Values are raw; 1 is the rowid into fulltext_values. [101 :test/fulltext 2 tx2 1] ;; Values are raw; 2 is the rowid into fulltext_values. [tx2 :db/txInstant txInstant2 tx2 1] [101 :test/other 3 tx3 1] ;; Values are raw; 3 is the rowid into fulltext_values. [tx3 :db/txInstant txInstant3 tx3 1]])) )))))) (testing "Can re-use fulltext indexed datoms" (let [r (<? (d/<transact! conn [[:db/add 102 :test/other "test this"]]))] (is (= (<? (<fulltext-values (d/db conn))) [[1 "test this"] [2 "alternate thing"] [3 "other"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :test/fulltext 2] [101 :test/other 3] [102 :test/other 1]})) ;; Values are raw; 1, 2, 3 are the rowids into fulltext_values. )) (testing "Can retract fulltext indexed datoms" (let [r (<? (d/<transact! conn [[:db/retract 101 :test/fulltext "alternate thing"]]))] (is (= (<? (<fulltext-values (d/db conn))) [[1 "test this"] [2 "alternate thing"] [3 "other"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :test/other 3] [102 :test/other 1]})) ;; Values are raw; 1, 3 are the rowids into fulltext_values. )))) (deftest-db test-txInstant conn (let [{tx0 :tx} (<? (d/<transact! conn test-schema)) {txa :tx txInstantA :txInstant} (<? (d/<transact! conn []))] (testing ":db/txInstant is set by default" (is (= (<? (<transactions-after (d/db conn) tx0)) [[txa :db/txInstant txInstantA txa 1]]))) ;; TODO: range check txInstant values against DB clock. (testing ":db/txInstant can be set explicitly" (let [{txb :tx txInstantB :txInstant} (<? (d/<transact! conn [[:db/add :db/tx :db/txInstant (+ txInstantA 1)]]))] (is (= txInstantB (+ txInstantA 1))) (is (= (<? (<transactions-after (d/db conn) txa)) [[txb :db/txInstant txInstantB txb 1]])) (testing ":db/txInstant can be set explicitly, with additional datoms" (let [{txc :tx txInstantC :txInstant} (<? (d/<transact! conn [[:db/add :db/tx :db/txInstant (+ txInstantB 2)] [:db/add :db/tx :x 123]]))] (is (= txInstantC (+ txInstantB 2))) (is (= (<? (<transactions-after (d/db conn) txb)) [[txc :db/txInstant txInstantC txc 1] [txc :x 123 txc 1]])) (testing "additional datoms can be added, without :db/txInstant explicitly" (let [{txd :tx txInstantD :txInstant} (<? (d/<transact! conn [[:db/add :db/tx :x 456]]))] (is (= (<? (<transactions-after (d/db conn) txc)) [[txd :db/txInstant txInstantD txd 1] [txd :x 456 txd 1]])))))))))) (deftest-db test-no-tx conn (let [{tx0 :tx} (<? (d/<transact! conn test-schema))] (testing "Cannot specificy an explicit tx" (is (thrown-with-msg? ExceptionInfo #"Bad entity: too long" (<? (d/<transact! conn [[:db/add (d/id-literal :db.part/user) :x 0 10101]]))))))) (deftest-db test-explode-sequences conn (let [{tx0 :tx} (<? (d/<transact! conn test-schema))] (testing ":db.cardinality/many sequences are accepted" (<? (d/<transact! conn [{:db/id 101 :aka ["first" "second"]}])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :aka "first"] [101 :aka "second"]}))) (testing ":db.cardinality/many sequences are recursively applied, allowing unexpected sequence nesting" (<? (d/<transact! conn [{:db/id 102 :aka [[["first"]] ["second"]]}])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :aka "first"] [101 :aka "second"] [102 :aka "first"] [102 :aka "second"]}))) (testing ":db.cardinality/one sequences fail" (is (thrown-with-msg? ExceptionInfo #"Sequential values" (<? (d/<transact! conn [{:db/id 101 :email ["@1" "@2"]}]))))))) (deftest-db test-explode-maps conn (let [{tx0 :tx} (<? (d/<transact! conn test-schema))] (testing "nested maps are accepted" (<? (d/<transact! conn [{:db/id 101 :friends {:name "<NAME>"}}])) ;; TODO: this works only because we have a single friend. (let [{petr :friends} (<? (<shallow-entity (d/db conn) 101))] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :friends petr] [petr :name "<NAME>"]})))) (testing "recursively nested maps are accepted" (<? (d/<transact! conn [{:db/id 102 :friends {:name "<NAME>" :friends {:name "<NAME>"}}}])) ;; This would be much easier with `entity` and lookup refs. (let [{ivan :friends} (<? (<shallow-entity (d/db conn) 102)) {petr :friends} (<? (<shallow-entity (d/db conn) ivan))] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :friends petr] [petr :name "<NAME>"] [102 :friends ivan] [ivan :name "<NAME>"] [ivan :friends petr]})))) (testing "nested maps without :db.type/ref fail" (is (thrown-with-msg? ExceptionInfo #"\{:db/valueType :db.type/ref\}" (<? (d/<transact! conn [{:db/id 101 :aka {:name "<NAME>"}}]))))))) (deftest-db test-explode-maps-with-db-id conn (let [{tx0 :tx} (<? (d/<transact! conn test-schema))] (testing "recursively nested maps with specified :db/id are accepted" (<? (d/<transact! conn [{:db/id 101 :name "<NAME>"}])) (<? (d/<transact! conn [{:db/id 101 :friends {:db/id 201 :name "<NAME>" :friends {:db/id 301 :name "<NAME>"}}}])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :name "<NAME>"] [101 :friends 201] [201 :name "<NAME>"] [201 :friends 301 ] [301 :name "<NAME>"]}))))) (deftest-db test-explode-reverse-refs conn (let [{tx0 :tx} (<? (d/<transact! conn test-schema))] (testing "reverse refs are accepted" (<? (d/<transact! conn [{:db/id 101 :name "<NAME>"}])) (<? (d/<transact! conn [{:db/id 102 :name "<NAME>" :_friends 101}])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :name "<NAME>"] [102 :name "<NAME>"] [101 :friends 102]}))) (testing "reverse refs without :db.type/ref fail" (is (thrown-with-msg? ExceptionInfo #"\{:db/valueType :db.type/ref\}" (<? (d/<transact! conn [{:db/id 101 :_aka 102}]))))))) ;; We don't use deftest-db in order to be able to re-open an on disk file. (deftest-async test-next-eid (with-tempfile [t (tempfile)] (let [conn (<? (d/<connect t)) {tx0 :tx} (<? (d/<transact! conn test-schema))] (testing "entids are increasing, tx ids are larger than user ids" (let [r1 (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :name "<NAME>"}])) r2 (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -2) :name "<NAME>"}])) e1 (get (tempids r1) -1) e2 (get (tempids r2) -2)] (is (< e1 (:tx r1))) (is (< e2 (:tx r2))) (is (< e1 e2)) (is (< (:tx r1) (:tx r2))) ;; Close and re-open same DB. (<? (d/<close conn)) (let [conn (<? (d/<connect t))] (try (testing "entid counters are persisted across re-opens" (let [r3 (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -3) :name "<NAME>"}])) e3 (get (tempids r3) -3)] (is (< e3 (:tx r3))) (is (< e2 e3)) (is (< (:tx r2) (:tx r3))))) (finally (<? (d/<close conn)))))))))) (deftest-db test-unique-value conn (let [tx0 (:tx (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :db/ident :test/x :db/unique :db.unique/value :db/valueType :db.type/long :db.install/_attribute :db.part/db} {:db/id (d/id-literal :db.part/user -2) :db/ident :test/y :db/unique :db.unique/value :db/valueType :db.type/long :db.install/_attribute :db.part/db}])))] (testing "can insert different :db.unique/value attributes with the same value" (let [report1 (<? (d/<transact! conn [[:db/add (d/id-literal :db.part/user -1) :test/x 12345]])) eid1 (get-in report1 [:tempids (d/id-literal :db.part/user -1)]) report2 (<? (d/<transact! conn [[:db/add (d/id-literal :db.part/user -2) :test/y 12345]])) eid2 (get-in report2 [:tempids (d/id-literal :db.part/user -2)])] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/x 12345] [eid2 :test/y 12345]})))) (testing "can't upsert a :db.unique/value field" (is (thrown-with-msg? ExceptionInfo #"unique constraint" (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :test/x 12345 :test/y 99999}]))))))) (def retract-schema [{:db/id (d/id-literal :db.part/user -1) :db/ident :test/long :db/cardinality :db.cardinality/many :db/valueType :db.type/long :db.install/_attribute :db.part/db} {:db/id (d/id-literal :db.part/user -2) :db/ident :test/fulltext :db/cardinality :db.cardinality/many :db/valueType :db.type/string :db/fulltext true :db.install/_attribute :db.part/db} {:db/id (d/id-literal :db.part/user -3) :db/ident :test/ref :db/valueType :db.type/ref :db.install/_attribute :db.part/db}]) (deftest-db test-retract-attribute conn (let [tx0 (:tx (<? (d/<transact! conn retract-schema)))] (testing "retractAttribute" (let [report (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :test/long [12345 123456]} {:db/id (d/id-literal :db.part/user -2) :test/ref (d/id-literal :db.part/user -1)}])) eid1 (get-in report [:tempids (d/id-literal :db.part/user -1)]) eid2 (get-in report [:tempids (d/id-literal :db.part/user -2)])] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/long 12345] [eid1 :test/long 123456] [eid2 :test/ref eid1]})) (testing "retractAttribute with no matching datoms succeeds" (<? (d/<transact! conn [[:db.fn/retractAttribute eid1 :test/ref]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/long 12345] [eid1 :test/long 123456] [eid2 :test/ref eid1]}))) (testing "retractAttribute retracts datoms" (let [{tx1 :tx} (<? (d/<transact! conn [[:db.fn/retractAttribute eid2 :test/ref]]))] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/long 12345] [eid1 :test/long 123456]}))) (let [{tx2 :tx} (<? (d/<transact! conn [[:db.fn/retractAttribute eid1 :test/long]]))] (is (= (<? (<datoms-after (d/db conn) tx0)) #{})))))))) (deftest-db test-retract-attribute-multiple conn (let [tx0 (:tx (<? (d/<transact! conn retract-schema)))] (let [report (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :test/long [12345 123456]} {:db/id (d/id-literal :db.part/user -1) :test/fulltext ["1 fulltext value" "2 fulltext value"]}])) eid1 (get-in report [:tempids (d/id-literal :db.part/user -1)])] (is (= (<? (<fulltext-values (d/db conn))) [[1 "1 fulltext value"] [2 "2 fulltext value"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/fulltext 1] [eid1 :test/fulltext 2] [eid1 :test/long 12345] [eid1 :test/long 123456]})) (testing "multiple retractAttribute in one transaction" (let [{tx1 :tx} (<? (d/<transact! conn [[:db.fn/retractAttribute eid1 :test/long] [:db.fn/retractAttribute eid1 :test/fulltext]]))] (is (= (<? (<datoms-after (d/db conn) tx0)) #{}))))))) (deftest-db test-retract-attribute-fulltext conn (let [tx0 (:tx (<? (d/<transact! conn retract-schema)))] (testing "retractAttribute, fulltext" (let [report (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :test/fulltext ["1 fulltext value" "2 fulltext value"]} {:db/id (d/id-literal :db.part/user -2) :test/ref (d/id-literal :db.part/user -1)}])) eid1 (get-in report [:tempids (d/id-literal :db.part/user -1)]) eid2 (get-in report [:tempids (d/id-literal :db.part/user -2)])] (is (= (<? (<fulltext-values (d/db conn))) [[1 "1 fulltext value"] [2 "2 fulltext value"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/fulltext 1] [eid1 :test/fulltext 2] [eid2 :test/ref eid1]})) (testing "retractAttribute retracts datoms, fulltext" (let [{tx1 :tx} (<? (d/<transact! conn [[:db.fn/retractAttribute eid2 :test/ref]]))] ;; fulltext values are not purged. (is (= (<? (<fulltext-values (d/db conn))) [[1 "1 fulltext value"] [2 "2 fulltext value"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/fulltext 1] [eid1 :test/fulltext 2]}))) (let [{tx2 :tx} (<? (d/<transact! conn [[:db.fn/retractAttribute eid1 :test/fulltext]]))] ;; fulltext values are not purged. (is (= (<? (<fulltext-values (d/db conn))) [[1 "1 fulltext value"] [2 "2 fulltext value"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{})))))))) (deftest-db test-retract-entity conn (let [tx0 (:tx (<? (d/<transact! conn retract-schema)))] (testing "retractEntity" (let [report (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :test/long [12345 123456]} {:db/id (d/id-literal :db.part/user -2) :test/ref (d/id-literal :db.part/user -1)} {:db/id (d/id-literal :db.part/user -3) :test/long 0xdeadbeef}])) eid1 (get-in report [:tempids (d/id-literal :db.part/user -1)]) eid2 (get-in report [:tempids (d/id-literal :db.part/user -2)]) eid3 (get-in report [:tempids (d/id-literal :db.part/user -3)])] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/long 12345] [eid1 :test/long 123456] [eid2 :test/ref eid1] [eid3 :test/long 0xdeadbeef]})) (testing "retractEntity with no matching datoms succeeds" (<? (d/<transact! conn [[:db.fn/retractEntity 0xdeadbeef]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/long 12345] [eid1 :test/long 123456] [eid2 :test/ref eid1] [eid3 :test/long 0xdeadbeef]}))) (testing "retractEntity retracts datoms" (let [{tx1 :tx} (<? (d/<transact! conn [[:db.fn/retractEntity eid3]]))] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/long 12345] [eid1 :test/long 123456] [eid2 :test/ref eid1]})))) (testing "retractEntity retracts datoms and references" (let [{tx2 :tx} (<? (d/<transact! conn [[:db.fn/retractEntity eid1]]))] (is (= (<? (<datoms-after (d/db conn) tx0)) ;; [eid2 :test/ref eid1] is gone, since the ref eid1 is gone. #{})))))))) (deftest-db test-retract-entity-multiple conn (let [tx0 (:tx (<? (d/<transact! conn retract-schema)))] (let [report (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :test/long [12345 123456]} {:db/id (d/id-literal :db.part/user -2) :test/fulltext ["1 fulltext value" "2 fulltext value"]}])) eid1 (get-in report [:tempids (d/id-literal :db.part/user -1)]) eid2 (get-in report [:tempids (d/id-literal :db.part/user -2)])] (is (= (<? (<fulltext-values (d/db conn))) [[1 "1 fulltext value"] [2 "2 fulltext value"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid2 :test/fulltext 1] [eid2 :test/fulltext 2] [eid1 :test/long 12345] [eid1 :test/long 123456]})) (testing "multiple retractEntity in one transaction" (let [{tx1 :tx} (<? (d/<transact! conn [[:db.fn/retractEntity eid1] [:db.fn/retractEntity eid2]]))] (is (= (<? (<datoms-after (d/db conn) tx0)) #{}))))))) (deftest-db test-retract-entity-fulltext conn (let [tx0 (:tx (<? (d/<transact! conn retract-schema)))] (testing "retractEntity, fulltext" (let [report (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :test/fulltext ["1 fulltext value" "2 fulltext value"]} {:db/id (d/id-literal :db.part/user -2) :test/ref (d/id-literal :db.part/user -1)} {:db/id (d/id-literal :db.part/user -3) :test/fulltext "3 fulltext value"}])) eid1 (get-in report [:tempids (d/id-literal :db.part/user -1)]) eid2 (get-in report [:tempids (d/id-literal :db.part/user -2)]) eid3 (get-in report [:tempids (d/id-literal :db.part/user -3)])] (is (= (<? (<fulltext-values (d/db conn))) [[1 "1 fulltext value"] [2 "2 fulltext value"] [3 "3 fulltext value"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/fulltext 1] [eid1 :test/fulltext 2] [eid2 :test/ref eid1] [eid3 :test/fulltext 3]})) (testing "retractEntity with no matching datoms succeeds, fulltext" (<? (d/<transact! conn [[:db.fn/retractEntity 0xdeadbeef]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/fulltext 1] [eid1 :test/fulltext 2] [eid2 :test/ref eid1] [eid3 :test/fulltext 3]}))) (testing "retractEntity retracts datoms, fulltext" (let [{tx1 :tx} (<? (d/<transact! conn [[:db.fn/retractEntity eid3]]))] ;; fulltext values are not purged. (is (= (<? (<fulltext-values (d/db conn))) [[1 "1 fulltext value"] [2 "2 fulltext value"] [3 "3 fulltext value"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/fulltext 1] [eid1 :test/fulltext 2] [eid2 :test/ref eid1]})))) (testing "retractEntity retracts datoms and references, fulltext" (let [{tx2 :tx} (<? (d/<transact! conn [[:db.fn/retractEntity eid1]]))] (is (= (<? (<datoms-after (d/db conn) tx0)) ;; [eid2 :test/ref eid1] is gone, since the ref eid1 is gone. #{})))))))) ;; We don't use deftest-db in order to be able to re-open an on disk file. (deftest-async test-reopen-schema (with-tempfile [t (tempfile)] (let [conn (<? (d/<connect t)) test-schema [{:db/id (d/id-literal :db.part/user -1) :db/ident :test/fulltext :db/cardinality :db.cardinality/many :db/valueType :db.type/string :db/fulltext true :db/doc "Documentation string" :db.install/_attribute :db.part/db}] {tx0 :tx} (<? (d/<transact! conn test-schema))] (testing "Values in schema are correct initially" (let [db (d/db conn) schema (d/schema db)] (is (= true (ds/indexing? schema (d/entid db :db/txInstant)))) (is (= true (ds/fulltext? schema (d/entid db :test/fulltext)))) (is (= "Documentation string" (ds/doc schema (d/entid db :test/fulltext)))) (is (= :db.type/string (ds/valueType schema (d/entid db :test/fulltext)))))) ;; Close and re-open same DB. (<? (d/<close conn)) (let [conn (<? (d/<connect t))] (try (testing "Boolean values in schema are correct after re-opening" (let [db (d/db conn) schema (d/schema db)] (is (= true (ds/indexing? schema (d/entid db :db/txInstant)))) (is (= true (ds/fulltext? schema (d/entid db :test/fulltext)))) (is (= "Documentation string" (ds/doc schema (d/entid db :test/fulltext)))) (is (= :db.type/string (ds/valueType schema (d/entid db :test/fulltext)))))) (finally (<? (d/<close conn)))))))) (deftest-db test-simple-schema conn (let [in {:name "mystuff" :attributes [{:name "foo/age" :type "long" :cardinality "one"} {:name "foo/name" :type "string" :cardinality "many" :doc "People can have many names."} {:name "foo/id" :type "string" :cardinality "one" :unique "value"}]} expected [{:db/ident :foo/age :db/valueType :db.type/long :db/cardinality :db.cardinality/one :db.install/_attribute :db.part/db} {:db/ident :foo/name :db/valueType :db.type/string :db/cardinality :db.cardinality/many :db/doc "People can have many names." :db.install/_attribute :db.part/db} {:db/ident :foo/id :db/valueType :db.type/string :db/cardinality :db.cardinality/one :db/unique :db.unique/value :db.install/_attribute :db.part/db}]] (testing "Simple schemas are expanded." (is (= (map #(dissoc %1 :db/id) (datomish.simple-schema/simple-schema->schema in)) expected))))) (deftest-db test-lookup-refs conn (let [{tx0 :tx} (<? (d/<transact! conn test-schema)) {tx1 :tx} (<? (d/<transact! conn [[:db/add 1 :name "<NAME>"] [:db/add 2 :name "<NAME>"] [:db/add 3 :name "<NAME>"]]))] (testing "Looks up entity refs" (let [{tx :tx} (<? (d/<transact! conn [[:db/add (d/lookup-ref :name "<NAME>") :aka "<NAME>"] [:db/add (d/lookup-ref :name "<NAME>") :email "@1"]]))] (is (= #{[1 :name "<NAME>"] [2 :name "<NAME>"] [3 :name "<NAME>"] [1 :aka "<NAME>"] [2 :email "@1"]} (<? (<datoms>= (d/db conn) tx1)))))) (testing "Looks up value refs" (let [{tx :tx} (<? (d/<transact! conn [[:db/add 1 :friends (d/lookup-ref :name "<NAME>")] [:db/add 3 :friends (d/lookup-ref :name "<NAME>")]]))] (is (= #{[1 :friends 3] [3 :friends 1]} (<? (<datoms>= (d/db conn) tx)))))) (testing "Looks up entity refs in maps" (let [{tx :tx} (<? (d/<transact! conn [{:db/id (d/lookup-ref :name "<NAME>") :friends 1}]))] (is (= #{[2 :friends 1]} (<? (<datoms>= (d/db conn) tx)))))) (testing "Looks up value refs in maps" (let [{tx :tx} (<? (d/<transact! conn [{:db/id 2 :friends (d/lookup-ref :name "<NAME>")}]))] (is (= #{[2 :friends 3]} (<? (<datoms>= (d/db conn) tx)))))) (testing "Looks up value refs in sequences in maps" (let [{tx :tx} (<? (d/<transact! conn [{:db/id 1 :friends [(d/lookup-ref :name "<NAME>") (d/lookup-ref :name "<NAME>")]}]))] (is (= #{[1 :friends 1] [1 :friends 2]} (<? (<datoms>= (d/db conn) tx)))))) (testing "Looks up refs when there are more than 999 refs (all present)" (let [bound (* 999 2) make-add #(vector :db/add (+ 1000 %) :name (str "<NAME>-" %)) make-ref #(-> {:db/id (d/lookup-ref :name (str "<NAME>-" %)) :email (str "Ivan-" % "@" %)}) {tx-data1 :tx-data} (<? (d/<transact! conn (map make-add (range bound)))) {tx-data2 :tx-data} (<? (d/<transact! conn (map make-ref (range bound))))] (is (= bound (dec (count tx-data1)))) ;; Each :name is new; dec to account for :db/tx. (is (= bound (dec (count tx-data2)))) ;; Each lookup-ref exists, each :email is new; dec for :db/tx. )) (testing "Fails for missing entities" (is (thrown-with-msg? ExceptionInfo #"No entity found for lookup-ref" (<? (d/<transact! conn [[:db/add (d/lookup-ref :name "<NAME>") :aka "The Magician"]])))) (is (thrown-with-msg? ExceptionInfo #"No entity found for lookup-ref" (<? (d/<transact! conn [[:db/add 1 :friends (d/lookup-ref :name "<NAME>")]]))))) (testing "Fails for non-identity attributes" (is (thrown-with-msg? ExceptionInfo #"Lookup-ref found with non-unique-identity attribute" (<? (d/<transact! conn [[:db/add (d/lookup-ref :aka "The Magician") :email "@2"]])))) (is (thrown-with-msg? ExceptionInfo #"Lookup-ref found with non-unique-identity attribute" (<? (d/<transact! conn [[:db/add 1 :friends (d/lookup-ref :aka "The Magician")]]))))))) (deftest-db test-fulltext-lookup-refs conn (let [schema [{:db/id (d/id-literal :db.part/db -1) :db/ident :test/fulltext :db/valueType :db.type/string :db/fulltext true :db/unique :db.unique/identity} {:db/id :db.part/db :db.install/attribute (d/id-literal :db.part/db -1)} {:db/id (d/id-literal :db.part/db -2) :db/ident :test/other :db/valueType :db.type/string :db/fulltext true :db/cardinality :db.cardinality/one} {:db/id :db.part/db :db.install/attribute (d/id-literal :db.part/db -2)} ] tx0 (:tx (<? (d/<transact! conn schema)))] (testing "Can look up fulltext refs" (<? (d/<transact! conn [[:db/add 101 :test/fulltext "test this"]])) (let [{tx :tx} (<? (d/<transact! conn [{:db/id (d/lookup-ref :test/fulltext "test this") :test/other "test other"}]))] (is (= (<? (<fulltext-values (d/db conn))) [[1 "test this"] [2 "test other"]])) (is (= #{[101 :test/other 2]} ;; Values are raw; 2 is the rowid into fulltext_values. (<? (<datoms>= (d/db conn) tx)))))) (testing "Fails for missing fulltext entities" (is (thrown-with-msg? ExceptionInfo #"No entity found for lookup-ref" (<? (d/<transact! conn [[:db/add (d/lookup-ref :test/fulltext "not found") :test/other "test random"]]))))))) #_ (time (t/run-tests)) #_ (time (clojure.test/test-vars [#'test-lookup-refs]))
true
;; Copyright 2016 Mozilla ;; ;; 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 datomish.db-test #?(:cljs (:require-macros [datomish.pair-chan :refer [go-pair <?]] [datomish.node-tempfile-macros :refer [with-tempfile]] [cljs.core.async.macros :as a :refer [go]])) (:require [datomish.api :as d] [datomish.db.debug :refer [<datoms-after <datoms>= <transactions-after <shallow-entity <fulltext-values]] [datomish.util :as util #?(:cljs :refer-macros :clj :refer) [raise cond-let]] [datomish.schema :as ds] [datomish.simple-schema] [datomish.sqlite :as s] [datomish.sqlite-schema] [datomish.datom] #?@(:clj [[datomish.jdbc-sqlite] [datomish.pair-chan :refer [go-pair <?]] [tempfile.core :refer [tempfile with-tempfile]] [datomish.test-macros :refer [deftest-async deftest-db]] [clojure.test :as t :refer [is are deftest testing]] [clojure.core.async :refer [go <! >!]]]) #?@(:cljs [[datomish.js-sqlite] [datomish.pair-chan] [datomish.test-macros :refer-macros [deftest-async deftest-db]] [datomish.node-tempfile :refer [tempfile]] [cljs.test :as t :refer-macros [is are deftest testing async]] [cljs.core.async :as a :refer [<! >!]]])) #?(:clj (:import [clojure.lang ExceptionInfo])) #?(:clj (:import [datascript.db DB]))) #?(:cljs (def Throwable js/Error)) (defn- tempids [tx] (into {} (map (juxt (comp :idx first) second) (:tempids tx)))) (def test-schema [{:db/id (d/id-literal :db.part/user) :db/ident :x :db/unique :db.unique/identity :db/valueType :db.type/long :db.install/_attribute :db.part/db} {:db/id (d/id-literal :db.part/user) :db/ident :name :db/unique :db.unique/identity :db/valueType :db.type/string :db.install/_attribute :db.part/db} {:db/id (d/id-literal :db.part/user) :db/ident :y :db/cardinality :db.cardinality/many :db/valueType :db.type/long :db.install/_attribute :db.part/db} {:db/id (d/id-literal :db.part/user) :db/ident :aka :db/cardinality :db.cardinality/many :db/valueType :db.type/string :db.install/_attribute :db.part/db} {:db/id (d/id-literal :db.part/user) :db/ident :age :db/valueType :db.type/long :db.install/_attribute :db.part/db} {:db/id (d/id-literal :db.part/user) :db/ident :email :db/unique :db.unique/identity :db/valueType :db.type/string :db.install/_attribute :db.part/db} {:db/id (d/id-literal :db.part/user) :db/ident :spouse :db/unique :db.unique/value :db/valueType :db.type/string :db.install/_attribute :db.part/db} {:db/id (d/id-literal :db.part/user) :db/ident :friends :db/cardinality :db.cardinality/many :db/valueType :db.type/ref :db.install/_attribute :db.part/db} ]) (deftest-db test-add-one conn (let [{tx0 :tx} (<? (d/<transact! conn test-schema))] (let [{:keys [tx txInstant]} (<? (d/<transact! conn [[:db/add 0 :name "valuex"]]))] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[0 :name "valuex"]})) (is (= (<? (<transactions-after (d/db conn) tx0)) [[0 :name "valuex" tx 1] ;; TODO: true, not 1. [tx :db/txInstant txInstant tx 1]]))))) (deftest-db test-add-two conn (let [{tx0 :tx} (<? (d/<transact! conn test-schema)) {tx1 :tx txInstant1 :txInstant} (<? (d/<transact! conn [[:db/add 1 :name "PI:NAME:<NAME>END_PI"]])) {tx2 :tx txInstant2 :txInstant} (<? (d/<transact! conn [[:db/add 1 :name "PI:NAME:<NAME>END_PI"]])) {tx3 :tx txInstant3 :txInstant} (<? (d/<transact! conn [[:db/add 1 :aka "Tupen"]])) {tx4 :tx txInstant4 :txInstant} (<? (d/<transact! conn [[:db/add 1 :aka "Devil"]]))] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[1 :name "PI:NAME:<NAME>END_PI"] [1 :aka "Tupen"] [1 :aka "Devil"]})) (is (= (<? (<transactions-after (d/db conn) tx0)) [[1 :name "PI:NAME:<NAME>END_PI" tx1 1] ;; TODO: true, not 1. [tx1 :db/txInstant txInstant1 tx1 1] [1 :name "PI:NAME:<NAME>END_PI" tx2 0] [1 :name "PI:NAME:<NAME>END_PI" tx2 1] [tx2 :db/txInstant txInstant2 tx2 1] [1 :aka "PI:NAME:<NAME>END_PI" tx3 1] [tx3 :db/txInstant txInstant3 tx3 1] [1 :aka "PI:NAME:<NAME>END_PI" tx4 1] [tx4 :db/txInstant txInstant4 tx4 1]])))) (deftest-db test-retract conn (let [{tx0 :tx} (<? (d/<transact! conn test-schema)) {tx1 :tx txInstant1 :txInstant} (<? (d/<transact! conn [[:db/add 0 :x 123]])) {tx2 :tx txInstant2 :txInstant} (<? (d/<transact! conn [[:db/retract 0 :x 123]]))] (is (= (<? (<datoms-after (d/db conn) tx0)) #{})) (is (= (<? (<transactions-after (d/db conn) tx0)) [[0 :x 123 tx1 1] [tx1 :db/txInstant txInstant1 tx1 1] [0 :x 123 tx2 0] [tx2 :db/txInstant txInstant2 tx2 1]])))) (deftest-db test-id-literal-1 conn (let [tx0 (:tx (<? (d/<transact! conn test-schema))) report (<? (d/<transact! conn [[:db/add (d/id-literal :db.part/user -1) :x 0] [:db/add (d/id-literal :db.part/user -1) :y 1] [:db/add (d/id-literal :db.part/user -2) :y 2] [:db/add (d/id-literal :db.part/user -2) :y 3]]))] (is (= (keys (:tempids report)) ;; TODO: include values. [(d/id-literal :db.part/user -1) (d/id-literal :db.part/user -2)])) (let [eid1 (get-in report [:tempids (d/id-literal :db.part/user -1)]) eid2 (get-in report [:tempids (d/id-literal :db.part/user -2)])] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :x 0] [eid1 :y 1] [eid2 :y 2] [eid2 :y 3]}))))) (deftest-db test-unique conn (let [tx0 (:tx (<? (d/<transact! conn test-schema)))] (testing "Multiple :db/unique values in tx-data violate unique constraint, no tempid" (is (thrown-with-msg? ExceptionInfo #"unique constraint" (<? (d/<transact! conn [[:db/add 1 :x 0] [:db/add 2 :x 0]]))))) (testing "Multiple :db/unique values in tx-data violate unique constraint, tempid" (is (thrown-with-msg? ExceptionInfo #"unique constraint" (<? (d/<transact! conn [[:db/add (d/id-literal :db.part/user -1) :spouse "Dana"] [:db/add (d/id-literal :db.part/user -2) :spouse "Dana"]]))))))) (deftest-db test-valueType-keyword conn (let [tx0 (:tx (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :db/ident :test/kw :db/unique :db.unique/identity :db/valueType :db.type/keyword} {:db/id :db.part/db :db.install/attribute (d/id-literal :db.part/user -1)}])))] (let [report (<? (d/<transact! conn [[:db/add (d/id-literal :db.part/user -1) :test/kw :test/kw1]])) eid (get-in report [:tempids (d/id-literal :db.part/user -1)])] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid :test/kw ":test/kw1"]})) ;; Value is raw. (testing "Adding the same value compares existing values correctly." (<? (d/<transact! conn [[:db/add eid :test/kw :test/kw1]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid :test/kw ":test/kw1"]}))) ;; Value is raw. (testing "Upserting retracts existing value correctly." (<? (d/<transact! conn [[:db/add eid :test/kw :test/kw2]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid :test/kw ":test/kw2"]}))) ;; Value is raw. (testing "Retracting compares values correctly." (<? (d/<transact! conn [[:db/retract eid :test/kw :test/kw2]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{})))))) (deftest-db test-vector-upsert conn ;; Not having DB-as-value really hurts us here. This test only works because all upserts ;; succeed on top of each other, so we never need to reset the underlying store. (<? (d/<transact! conn test-schema)) (let [tx0 (:tx (<? (d/<transact! conn [{:db/id 101 :name "PI:NAME:<NAME>END_PI" :email "@1"} {:db/id 102 :name "PI:NAME:<NAME>END_PI" :email "@2"}])))] (testing "upsert with tempid" (let [report (<? (d/<transact! conn [[:db/add (d/id-literal :db.part/user -1) :name "PI:NAME:<NAME>END_PI"] [:db/add (d/id-literal :db.part/user -1) :age 12]]))] (is (= (<? (<shallow-entity (d/db conn) 101)) {:name "PI:NAME:<NAME>END_PI" :age 12 :email "@1"})) (is (= (tempids report) {-1 101})))) (testing "upsert with tempid, order does not matter" (let [report (<? (d/<transact! conn [[:db/add (d/id-literal :db.part/user -1) :age 13] [:db/add (d/id-literal :db.part/user -1) :name "PI:NAME:<NAME>END_PI"]]))] (is (= (<? (<shallow-entity (d/db conn) 102)) {:name "PI:NAME:<NAME>END_PI" :age 13 :email "@2"})) (is (= (tempids report) {-1 102})))) (testing "Conflicting upserts fail" (is (thrown-with-msg? Throwable #"Conflicting upsert" (<? (d/<transact! conn [[:db/add (d/id-literal :db.part/user -1) :name "PI:NAME:<NAME>END_PI"] [:db/add (d/id-literal :db.part/user -1) :age 35] [:db/add (d/id-literal :db.part/user -1) :name "PI:NAME:<NAME>END_PI"] [:db/add (d/id-literal :db.part/user -1) :age 36]]))))))) (deftest-db test-multistep-upsert conn (<? (d/<transact! conn test-schema)) ;; The upsert algorithm will first try to resolve -1, fail, and then allocate both -1 and -2. (let [tx0 (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :name "PI:NAME:<NAME>END_PI" :email "@1"} {:db/id (d/id-literal :db.part/user -2) :name "PI:NAME:<NAME>END_PI" :friends (d/id-literal :db.part/user -1)}]))] ;; Sanity checks that these are freshly allocated, not resolved. (is (> (get (tempids tx0) -1) 1000)) (is (> (get (tempids tx0) -1) 1000)) ;; This time, we can resolve both, but we have to try -1, succeed, and then resolve -2. (let [tx1 (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :name "PI:NAME:<NAME>END_PI" :email "@1"} {:db/id (d/id-literal :db.part/user -2) :name "PI:NAME:<NAME>END_PI" :friends (d/id-literal :db.part/user -1)}]))] ;; Ensure these are resolved, not freshly allocated. (is (= (tempids tx0) (tempids tx1)))))) (deftest-db test-map-upsert conn ;; Not having DB-as-value really hurts us here. This test only works because all upserts ;; succeed on top of each other, so we never need to reset the underlying store. (<? (d/<transact! conn test-schema)) (let [tx0 (:tx (<? (d/<transact! conn [{:db/id 101 :name "PI:NAME:<NAME>END_PI" :email "@1"} {:db/id 102 :name "PI:NAME:<NAME>END_PI" :email "@2"}])))] (testing "upsert with tempid" (let [tx (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :name "PI:NAME:<NAME>END_PI" :age 35}]))] (is (= (<? (<shallow-entity (d/db conn) 101)) {:name "PI:NAME:<NAME>END_PI" :email "@1" :age 35})) (is (= (tempids tx) {-1 101})))) (testing "upsert by 2 attrs with tempid" (let [tx (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :name "PI:NAME:<NAME>END_PI" :email "@1" :age 35}]))] (is (= (<? (<shallow-entity (d/db conn) 101)) {:name "PI:NAME:<NAME>END_PI" :email "@1" :age 35})) (is (= (tempids tx) {-1 101})))) (testing "upsert with existing id" (let [tx (<? (d/<transact! conn [{:db/id 101 :name "PI:NAME:<NAME>END_PI" :age 36}]))] (is (= (<? (<shallow-entity (d/db conn) 101)) {:name "PI:NAME:<NAME>END_PI" :email "@1" :age 36})) (is (= (tempids tx) {})))) (testing "upsert by 2 attrs with existing id" (let [tx (<? (d/<transact! conn [{:db/id 101 :name "PI:NAME:<NAME>END_PI" :email "@1" :age 37}]))] (is (= (<? (<shallow-entity (d/db conn) 101)) {:name "PI:NAME:<NAME>END_PI" :email "@1" :age 37})) (is (= (tempids tx) {})))) (testing "upsert to two entities, resolve to same tempid, fails due to overlapping writes" (is (thrown-with-msg? Throwable #"cardinality constraint" (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :name "PI:NAME:<NAME>END_PI" :age 35} {:db/id (d/id-literal :db.part/user -1) :name "PI:NAME:<NAME>END_PI" :age 36}]))))) (testing "upsert to two entities, two tempids, fails due to overlapping writes" (is (thrown-with-msg? Throwable #"cardinality constraint" (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :name "PI:NAME:<NAME>END_PI" :age 35} {:db/id (d/id-literal :db.part/user -2) :name "PI:NAME:<NAME>END_PI" :age 36}]))))))) (deftest-db test-map-upsert-conflicts conn ;; Not having DB-as-value really hurts us here. This test only works because all upserts ;; fail until the final one, so we never need to reset the underlying store. (<? (d/<transact! conn test-schema)) (let [tx0 (:tx (<? (d/<transact! conn [{:db/id 101 :name "PI:NAME:<NAME>END_PI" :email "@1"} {:db/id 102 :name "PI:NAME:<NAME>END_PI" :email "@2"}])))] ;; TODO: improve error message to refer to upsert inputs. (testing "upsert conficts with existing id" (is (thrown-with-msg? Throwable #"unique constraint" (<? (d/<transact! conn [{:db/id 102 :name "PI:NAME:<NAME>END_PI" :age 36}]))))) ;; TODO: improve error message to refer to upsert inputs. (testing "upsert conficts with non-existing id" (is (thrown-with-msg? Throwable #"unique constraint" (<? (d/<transact! conn [{:db/id 103 :name "PI:NAME:<NAME>END_PI" :age 36}]))))) ;; TODO: improve error message to refer to upsert inputs. (testing "upsert by 2 conflicting fields" (is (thrown-with-msg? Throwable #"Conflicting upsert" (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :name "PI:NAME:<NAME>END_PI" :email "@2" :age 35}]))))) (testing "upsert by non-existing value resolves as update" (let [report (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :name "PI:NAME:<NAME>END_PI" :email "@3" :age 35}]))] (is (= (<? (<shallow-entity (d/db conn) 101)) {:name "PI:NAME:<NAME>END_PI" :email "@3" :age 35})) (is (= (tempids report) {-1 101})))))) (deftest-db test-add-schema conn (let [es [[:db/add :db.part/db :db.install/attribute (d/id-literal :db.part/db -1)] {:db/id (d/id-literal :db.part/db -1) :db/ident :test/attr :db/valueType :db.type/string :db/cardinality :db.cardinality/one}] report (<? (d/<transact! conn es)) db-after (:db-after report) tx (:tx db-after)] (testing "New ident is allocated" (is (some? (d/entid db-after :test/attr)))) (testing "Schema is modified" (is (= (get-in db-after [:symbolic-schema :test/attr]) {:db/valueType :db.type/string, :db/cardinality :db.cardinality/one}))) (testing "Schema is used in subsequent transaction" (<? (d/<transact! conn [{:db/id 100 :test/attr "value 1"}])) (<? (d/<transact! conn [{:db/id 100 :test/attr "value 2"}])) (is (= (<? (<shallow-entity (d/db conn) 100)) {:test/attr "value 2"}))))) (deftest-db test-fulltext conn (let [schema [{:db/id (d/id-literal :db.part/db -1) :db/ident :test/fulltext :db/valueType :db.type/string :db/fulltext true :db/unique :db.unique/identity} {:db/id :db.part/db :db.install/attribute (d/id-literal :db.part/db -1)} {:db/id (d/id-literal :db.part/db -2) :db/ident :test/other :db/valueType :db.type/string :db/fulltext true :db/cardinality :db.cardinality/one} {:db/id :db.part/db :db.install/attribute (d/id-literal :db.part/db -2)} ] tx0 (:tx (<? (d/<transact! conn schema)))] (testing "Schema checks" (is (ds/fulltext? (d/schema (d/db conn)) (d/entid (d/db conn) :test/fulltext)))) (testing "Can add fulltext indexed datoms" (let [{tx1 :tx txInstant1 :txInstant} (<? (d/<transact! conn [[:db/add 101 :test/fulltext "test this"]]))] (is (= (<? (<fulltext-values (d/db conn))) [[1 "test this"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :test/fulltext 1]})) ;; Values are raw; 1 is the rowid into fulltext_values. (is (= (<? (<transactions-after (d/db conn) tx0)) [[101 :test/fulltext 1 tx1 1] ;; Values are raw; 1 is the rowid into fulltext_values. [tx1 :db/txInstant txInstant1 tx1 1]])) (testing "Can replace fulltext indexed datoms" (let [{tx2 :tx txInstant2 :txInstant} (<? (d/<transact! conn [[:db/add 101 :test/fulltext "alternate thing"]]))] (is (= (<? (<fulltext-values (d/db conn))) [[1 "test this"] [2 "alternate thing"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :test/fulltext 2]})) ;; Values are raw; 2 is the rowid into fulltext_values. (is (= (<? (<transactions-after (d/db conn) tx0)) [[101 :test/fulltext 1 tx1 1] ;; Values are raw; 1 is the rowid into fulltext_values. [tx1 :db/txInstant txInstant1 tx1 1] [101 :test/fulltext 1 tx2 0] ;; Values are raw; 1 is the rowid into fulltext_values. [101 :test/fulltext 2 tx2 1] ;; Values are raw; 2 is the rowid into fulltext_values. [tx2 :db/txInstant txInstant2 tx2 1]])) (testing "Can upsert keyed by fulltext indexed datoms" (let [{tx3 :tx txInstant3 :txInstant} (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user) :test/fulltext "alternate thing" :test/other "other"}]))] (is (= (<? (<fulltext-values (d/db conn))) [[1 "test this"] [2 "alternate thing"] [3 "other"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :test/fulltext 2] ;; Values are raw; 2, 3 are the rowids into fulltext_values. [101 :test/other 3]})) (is (= (<? (<transactions-after (d/db conn) tx0)) [[101 :test/fulltext 1 tx1 1] ;; Values are raw; 1 is the rowid into fulltext_values. [tx1 :db/txInstant txInstant1 tx1 1] [101 :test/fulltext 1 tx2 0] ;; Values are raw; 1 is the rowid into fulltext_values. [101 :test/fulltext 2 tx2 1] ;; Values are raw; 2 is the rowid into fulltext_values. [tx2 :db/txInstant txInstant2 tx2 1] [101 :test/other 3 tx3 1] ;; Values are raw; 3 is the rowid into fulltext_values. [tx3 :db/txInstant txInstant3 tx3 1]])) )))))) (testing "Can re-use fulltext indexed datoms" (let [r (<? (d/<transact! conn [[:db/add 102 :test/other "test this"]]))] (is (= (<? (<fulltext-values (d/db conn))) [[1 "test this"] [2 "alternate thing"] [3 "other"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :test/fulltext 2] [101 :test/other 3] [102 :test/other 1]})) ;; Values are raw; 1, 2, 3 are the rowids into fulltext_values. )) (testing "Can retract fulltext indexed datoms" (let [r (<? (d/<transact! conn [[:db/retract 101 :test/fulltext "alternate thing"]]))] (is (= (<? (<fulltext-values (d/db conn))) [[1 "test this"] [2 "alternate thing"] [3 "other"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :test/other 3] [102 :test/other 1]})) ;; Values are raw; 1, 3 are the rowids into fulltext_values. )))) (deftest-db test-txInstant conn (let [{tx0 :tx} (<? (d/<transact! conn test-schema)) {txa :tx txInstantA :txInstant} (<? (d/<transact! conn []))] (testing ":db/txInstant is set by default" (is (= (<? (<transactions-after (d/db conn) tx0)) [[txa :db/txInstant txInstantA txa 1]]))) ;; TODO: range check txInstant values against DB clock. (testing ":db/txInstant can be set explicitly" (let [{txb :tx txInstantB :txInstant} (<? (d/<transact! conn [[:db/add :db/tx :db/txInstant (+ txInstantA 1)]]))] (is (= txInstantB (+ txInstantA 1))) (is (= (<? (<transactions-after (d/db conn) txa)) [[txb :db/txInstant txInstantB txb 1]])) (testing ":db/txInstant can be set explicitly, with additional datoms" (let [{txc :tx txInstantC :txInstant} (<? (d/<transact! conn [[:db/add :db/tx :db/txInstant (+ txInstantB 2)] [:db/add :db/tx :x 123]]))] (is (= txInstantC (+ txInstantB 2))) (is (= (<? (<transactions-after (d/db conn) txb)) [[txc :db/txInstant txInstantC txc 1] [txc :x 123 txc 1]])) (testing "additional datoms can be added, without :db/txInstant explicitly" (let [{txd :tx txInstantD :txInstant} (<? (d/<transact! conn [[:db/add :db/tx :x 456]]))] (is (= (<? (<transactions-after (d/db conn) txc)) [[txd :db/txInstant txInstantD txd 1] [txd :x 456 txd 1]])))))))))) (deftest-db test-no-tx conn (let [{tx0 :tx} (<? (d/<transact! conn test-schema))] (testing "Cannot specificy an explicit tx" (is (thrown-with-msg? ExceptionInfo #"Bad entity: too long" (<? (d/<transact! conn [[:db/add (d/id-literal :db.part/user) :x 0 10101]]))))))) (deftest-db test-explode-sequences conn (let [{tx0 :tx} (<? (d/<transact! conn test-schema))] (testing ":db.cardinality/many sequences are accepted" (<? (d/<transact! conn [{:db/id 101 :aka ["first" "second"]}])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :aka "first"] [101 :aka "second"]}))) (testing ":db.cardinality/many sequences are recursively applied, allowing unexpected sequence nesting" (<? (d/<transact! conn [{:db/id 102 :aka [[["first"]] ["second"]]}])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :aka "first"] [101 :aka "second"] [102 :aka "first"] [102 :aka "second"]}))) (testing ":db.cardinality/one sequences fail" (is (thrown-with-msg? ExceptionInfo #"Sequential values" (<? (d/<transact! conn [{:db/id 101 :email ["@1" "@2"]}]))))))) (deftest-db test-explode-maps conn (let [{tx0 :tx} (<? (d/<transact! conn test-schema))] (testing "nested maps are accepted" (<? (d/<transact! conn [{:db/id 101 :friends {:name "PI:NAME:<NAME>END_PI"}}])) ;; TODO: this works only because we have a single friend. (let [{petr :friends} (<? (<shallow-entity (d/db conn) 101))] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :friends petr] [petr :name "PI:NAME:<NAME>END_PI"]})))) (testing "recursively nested maps are accepted" (<? (d/<transact! conn [{:db/id 102 :friends {:name "PI:NAME:<NAME>END_PI" :friends {:name "PI:NAME:<NAME>END_PI"}}}])) ;; This would be much easier with `entity` and lookup refs. (let [{ivan :friends} (<? (<shallow-entity (d/db conn) 102)) {petr :friends} (<? (<shallow-entity (d/db conn) ivan))] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :friends petr] [petr :name "PI:NAME:<NAME>END_PI"] [102 :friends ivan] [ivan :name "PI:NAME:<NAME>END_PI"] [ivan :friends petr]})))) (testing "nested maps without :db.type/ref fail" (is (thrown-with-msg? ExceptionInfo #"\{:db/valueType :db.type/ref\}" (<? (d/<transact! conn [{:db/id 101 :aka {:name "PI:NAME:<NAME>END_PI"}}]))))))) (deftest-db test-explode-maps-with-db-id conn (let [{tx0 :tx} (<? (d/<transact! conn test-schema))] (testing "recursively nested maps with specified :db/id are accepted" (<? (d/<transact! conn [{:db/id 101 :name "PI:NAME:<NAME>END_PI"}])) (<? (d/<transact! conn [{:db/id 101 :friends {:db/id 201 :name "PI:NAME:<NAME>END_PI" :friends {:db/id 301 :name "PI:NAME:<NAME>END_PI"}}}])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :name "PI:NAME:<NAME>END_PI"] [101 :friends 201] [201 :name "PI:NAME:<NAME>END_PI"] [201 :friends 301 ] [301 :name "PI:NAME:<NAME>END_PI"]}))))) (deftest-db test-explode-reverse-refs conn (let [{tx0 :tx} (<? (d/<transact! conn test-schema))] (testing "reverse refs are accepted" (<? (d/<transact! conn [{:db/id 101 :name "PI:NAME:<NAME>END_PI"}])) (<? (d/<transact! conn [{:db/id 102 :name "PI:NAME:<NAME>END_PI" :_friends 101}])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[101 :name "PI:NAME:<NAME>END_PI"] [102 :name "PI:NAME:<NAME>END_PI"] [101 :friends 102]}))) (testing "reverse refs without :db.type/ref fail" (is (thrown-with-msg? ExceptionInfo #"\{:db/valueType :db.type/ref\}" (<? (d/<transact! conn [{:db/id 101 :_aka 102}]))))))) ;; We don't use deftest-db in order to be able to re-open an on disk file. (deftest-async test-next-eid (with-tempfile [t (tempfile)] (let [conn (<? (d/<connect t)) {tx0 :tx} (<? (d/<transact! conn test-schema))] (testing "entids are increasing, tx ids are larger than user ids" (let [r1 (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :name "PI:NAME:<NAME>END_PI"}])) r2 (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -2) :name "PI:NAME:<NAME>END_PI"}])) e1 (get (tempids r1) -1) e2 (get (tempids r2) -2)] (is (< e1 (:tx r1))) (is (< e2 (:tx r2))) (is (< e1 e2)) (is (< (:tx r1) (:tx r2))) ;; Close and re-open same DB. (<? (d/<close conn)) (let [conn (<? (d/<connect t))] (try (testing "entid counters are persisted across re-opens" (let [r3 (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -3) :name "PI:NAME:<NAME>END_PI"}])) e3 (get (tempids r3) -3)] (is (< e3 (:tx r3))) (is (< e2 e3)) (is (< (:tx r2) (:tx r3))))) (finally (<? (d/<close conn)))))))))) (deftest-db test-unique-value conn (let [tx0 (:tx (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :db/ident :test/x :db/unique :db.unique/value :db/valueType :db.type/long :db.install/_attribute :db.part/db} {:db/id (d/id-literal :db.part/user -2) :db/ident :test/y :db/unique :db.unique/value :db/valueType :db.type/long :db.install/_attribute :db.part/db}])))] (testing "can insert different :db.unique/value attributes with the same value" (let [report1 (<? (d/<transact! conn [[:db/add (d/id-literal :db.part/user -1) :test/x 12345]])) eid1 (get-in report1 [:tempids (d/id-literal :db.part/user -1)]) report2 (<? (d/<transact! conn [[:db/add (d/id-literal :db.part/user -2) :test/y 12345]])) eid2 (get-in report2 [:tempids (d/id-literal :db.part/user -2)])] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/x 12345] [eid2 :test/y 12345]})))) (testing "can't upsert a :db.unique/value field" (is (thrown-with-msg? ExceptionInfo #"unique constraint" (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :test/x 12345 :test/y 99999}]))))))) (def retract-schema [{:db/id (d/id-literal :db.part/user -1) :db/ident :test/long :db/cardinality :db.cardinality/many :db/valueType :db.type/long :db.install/_attribute :db.part/db} {:db/id (d/id-literal :db.part/user -2) :db/ident :test/fulltext :db/cardinality :db.cardinality/many :db/valueType :db.type/string :db/fulltext true :db.install/_attribute :db.part/db} {:db/id (d/id-literal :db.part/user -3) :db/ident :test/ref :db/valueType :db.type/ref :db.install/_attribute :db.part/db}]) (deftest-db test-retract-attribute conn (let [tx0 (:tx (<? (d/<transact! conn retract-schema)))] (testing "retractAttribute" (let [report (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :test/long [12345 123456]} {:db/id (d/id-literal :db.part/user -2) :test/ref (d/id-literal :db.part/user -1)}])) eid1 (get-in report [:tempids (d/id-literal :db.part/user -1)]) eid2 (get-in report [:tempids (d/id-literal :db.part/user -2)])] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/long 12345] [eid1 :test/long 123456] [eid2 :test/ref eid1]})) (testing "retractAttribute with no matching datoms succeeds" (<? (d/<transact! conn [[:db.fn/retractAttribute eid1 :test/ref]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/long 12345] [eid1 :test/long 123456] [eid2 :test/ref eid1]}))) (testing "retractAttribute retracts datoms" (let [{tx1 :tx} (<? (d/<transact! conn [[:db.fn/retractAttribute eid2 :test/ref]]))] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/long 12345] [eid1 :test/long 123456]}))) (let [{tx2 :tx} (<? (d/<transact! conn [[:db.fn/retractAttribute eid1 :test/long]]))] (is (= (<? (<datoms-after (d/db conn) tx0)) #{})))))))) (deftest-db test-retract-attribute-multiple conn (let [tx0 (:tx (<? (d/<transact! conn retract-schema)))] (let [report (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :test/long [12345 123456]} {:db/id (d/id-literal :db.part/user -1) :test/fulltext ["1 fulltext value" "2 fulltext value"]}])) eid1 (get-in report [:tempids (d/id-literal :db.part/user -1)])] (is (= (<? (<fulltext-values (d/db conn))) [[1 "1 fulltext value"] [2 "2 fulltext value"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/fulltext 1] [eid1 :test/fulltext 2] [eid1 :test/long 12345] [eid1 :test/long 123456]})) (testing "multiple retractAttribute in one transaction" (let [{tx1 :tx} (<? (d/<transact! conn [[:db.fn/retractAttribute eid1 :test/long] [:db.fn/retractAttribute eid1 :test/fulltext]]))] (is (= (<? (<datoms-after (d/db conn) tx0)) #{}))))))) (deftest-db test-retract-attribute-fulltext conn (let [tx0 (:tx (<? (d/<transact! conn retract-schema)))] (testing "retractAttribute, fulltext" (let [report (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :test/fulltext ["1 fulltext value" "2 fulltext value"]} {:db/id (d/id-literal :db.part/user -2) :test/ref (d/id-literal :db.part/user -1)}])) eid1 (get-in report [:tempids (d/id-literal :db.part/user -1)]) eid2 (get-in report [:tempids (d/id-literal :db.part/user -2)])] (is (= (<? (<fulltext-values (d/db conn))) [[1 "1 fulltext value"] [2 "2 fulltext value"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/fulltext 1] [eid1 :test/fulltext 2] [eid2 :test/ref eid1]})) (testing "retractAttribute retracts datoms, fulltext" (let [{tx1 :tx} (<? (d/<transact! conn [[:db.fn/retractAttribute eid2 :test/ref]]))] ;; fulltext values are not purged. (is (= (<? (<fulltext-values (d/db conn))) [[1 "1 fulltext value"] [2 "2 fulltext value"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/fulltext 1] [eid1 :test/fulltext 2]}))) (let [{tx2 :tx} (<? (d/<transact! conn [[:db.fn/retractAttribute eid1 :test/fulltext]]))] ;; fulltext values are not purged. (is (= (<? (<fulltext-values (d/db conn))) [[1 "1 fulltext value"] [2 "2 fulltext value"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{})))))))) (deftest-db test-retract-entity conn (let [tx0 (:tx (<? (d/<transact! conn retract-schema)))] (testing "retractEntity" (let [report (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :test/long [12345 123456]} {:db/id (d/id-literal :db.part/user -2) :test/ref (d/id-literal :db.part/user -1)} {:db/id (d/id-literal :db.part/user -3) :test/long 0xdeadbeef}])) eid1 (get-in report [:tempids (d/id-literal :db.part/user -1)]) eid2 (get-in report [:tempids (d/id-literal :db.part/user -2)]) eid3 (get-in report [:tempids (d/id-literal :db.part/user -3)])] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/long 12345] [eid1 :test/long 123456] [eid2 :test/ref eid1] [eid3 :test/long 0xdeadbeef]})) (testing "retractEntity with no matching datoms succeeds" (<? (d/<transact! conn [[:db.fn/retractEntity 0xdeadbeef]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/long 12345] [eid1 :test/long 123456] [eid2 :test/ref eid1] [eid3 :test/long 0xdeadbeef]}))) (testing "retractEntity retracts datoms" (let [{tx1 :tx} (<? (d/<transact! conn [[:db.fn/retractEntity eid3]]))] (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/long 12345] [eid1 :test/long 123456] [eid2 :test/ref eid1]})))) (testing "retractEntity retracts datoms and references" (let [{tx2 :tx} (<? (d/<transact! conn [[:db.fn/retractEntity eid1]]))] (is (= (<? (<datoms-after (d/db conn) tx0)) ;; [eid2 :test/ref eid1] is gone, since the ref eid1 is gone. #{})))))))) (deftest-db test-retract-entity-multiple conn (let [tx0 (:tx (<? (d/<transact! conn retract-schema)))] (let [report (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :test/long [12345 123456]} {:db/id (d/id-literal :db.part/user -2) :test/fulltext ["1 fulltext value" "2 fulltext value"]}])) eid1 (get-in report [:tempids (d/id-literal :db.part/user -1)]) eid2 (get-in report [:tempids (d/id-literal :db.part/user -2)])] (is (= (<? (<fulltext-values (d/db conn))) [[1 "1 fulltext value"] [2 "2 fulltext value"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid2 :test/fulltext 1] [eid2 :test/fulltext 2] [eid1 :test/long 12345] [eid1 :test/long 123456]})) (testing "multiple retractEntity in one transaction" (let [{tx1 :tx} (<? (d/<transact! conn [[:db.fn/retractEntity eid1] [:db.fn/retractEntity eid2]]))] (is (= (<? (<datoms-after (d/db conn) tx0)) #{}))))))) (deftest-db test-retract-entity-fulltext conn (let [tx0 (:tx (<? (d/<transact! conn retract-schema)))] (testing "retractEntity, fulltext" (let [report (<? (d/<transact! conn [{:db/id (d/id-literal :db.part/user -1) :test/fulltext ["1 fulltext value" "2 fulltext value"]} {:db/id (d/id-literal :db.part/user -2) :test/ref (d/id-literal :db.part/user -1)} {:db/id (d/id-literal :db.part/user -3) :test/fulltext "3 fulltext value"}])) eid1 (get-in report [:tempids (d/id-literal :db.part/user -1)]) eid2 (get-in report [:tempids (d/id-literal :db.part/user -2)]) eid3 (get-in report [:tempids (d/id-literal :db.part/user -3)])] (is (= (<? (<fulltext-values (d/db conn))) [[1 "1 fulltext value"] [2 "2 fulltext value"] [3 "3 fulltext value"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/fulltext 1] [eid1 :test/fulltext 2] [eid2 :test/ref eid1] [eid3 :test/fulltext 3]})) (testing "retractEntity with no matching datoms succeeds, fulltext" (<? (d/<transact! conn [[:db.fn/retractEntity 0xdeadbeef]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/fulltext 1] [eid1 :test/fulltext 2] [eid2 :test/ref eid1] [eid3 :test/fulltext 3]}))) (testing "retractEntity retracts datoms, fulltext" (let [{tx1 :tx} (<? (d/<transact! conn [[:db.fn/retractEntity eid3]]))] ;; fulltext values are not purged. (is (= (<? (<fulltext-values (d/db conn))) [[1 "1 fulltext value"] [2 "2 fulltext value"] [3 "3 fulltext value"]])) (is (= (<? (<datoms-after (d/db conn) tx0)) #{[eid1 :test/fulltext 1] [eid1 :test/fulltext 2] [eid2 :test/ref eid1]})))) (testing "retractEntity retracts datoms and references, fulltext" (let [{tx2 :tx} (<? (d/<transact! conn [[:db.fn/retractEntity eid1]]))] (is (= (<? (<datoms-after (d/db conn) tx0)) ;; [eid2 :test/ref eid1] is gone, since the ref eid1 is gone. #{})))))))) ;; We don't use deftest-db in order to be able to re-open an on disk file. (deftest-async test-reopen-schema (with-tempfile [t (tempfile)] (let [conn (<? (d/<connect t)) test-schema [{:db/id (d/id-literal :db.part/user -1) :db/ident :test/fulltext :db/cardinality :db.cardinality/many :db/valueType :db.type/string :db/fulltext true :db/doc "Documentation string" :db.install/_attribute :db.part/db}] {tx0 :tx} (<? (d/<transact! conn test-schema))] (testing "Values in schema are correct initially" (let [db (d/db conn) schema (d/schema db)] (is (= true (ds/indexing? schema (d/entid db :db/txInstant)))) (is (= true (ds/fulltext? schema (d/entid db :test/fulltext)))) (is (= "Documentation string" (ds/doc schema (d/entid db :test/fulltext)))) (is (= :db.type/string (ds/valueType schema (d/entid db :test/fulltext)))))) ;; Close and re-open same DB. (<? (d/<close conn)) (let [conn (<? (d/<connect t))] (try (testing "Boolean values in schema are correct after re-opening" (let [db (d/db conn) schema (d/schema db)] (is (= true (ds/indexing? schema (d/entid db :db/txInstant)))) (is (= true (ds/fulltext? schema (d/entid db :test/fulltext)))) (is (= "Documentation string" (ds/doc schema (d/entid db :test/fulltext)))) (is (= :db.type/string (ds/valueType schema (d/entid db :test/fulltext)))))) (finally (<? (d/<close conn)))))))) (deftest-db test-simple-schema conn (let [in {:name "mystuff" :attributes [{:name "foo/age" :type "long" :cardinality "one"} {:name "foo/name" :type "string" :cardinality "many" :doc "People can have many names."} {:name "foo/id" :type "string" :cardinality "one" :unique "value"}]} expected [{:db/ident :foo/age :db/valueType :db.type/long :db/cardinality :db.cardinality/one :db.install/_attribute :db.part/db} {:db/ident :foo/name :db/valueType :db.type/string :db/cardinality :db.cardinality/many :db/doc "People can have many names." :db.install/_attribute :db.part/db} {:db/ident :foo/id :db/valueType :db.type/string :db/cardinality :db.cardinality/one :db/unique :db.unique/value :db.install/_attribute :db.part/db}]] (testing "Simple schemas are expanded." (is (= (map #(dissoc %1 :db/id) (datomish.simple-schema/simple-schema->schema in)) expected))))) (deftest-db test-lookup-refs conn (let [{tx0 :tx} (<? (d/<transact! conn test-schema)) {tx1 :tx} (<? (d/<transact! conn [[:db/add 1 :name "PI:NAME:<NAME>END_PI"] [:db/add 2 :name "PI:NAME:<NAME>END_PI"] [:db/add 3 :name "PI:NAME:<NAME>END_PI"]]))] (testing "Looks up entity refs" (let [{tx :tx} (<? (d/<transact! conn [[:db/add (d/lookup-ref :name "PI:NAME:<NAME>END_PI") :aka "PI:NAME:<NAME>END_PI"] [:db/add (d/lookup-ref :name "PI:NAME:<NAME>END_PI") :email "@1"]]))] (is (= #{[1 :name "PI:NAME:<NAME>END_PI"] [2 :name "PI:NAME:<NAME>END_PI"] [3 :name "PI:NAME:<NAME>END_PI"] [1 :aka "PI:NAME:<NAME>END_PI"] [2 :email "@1"]} (<? (<datoms>= (d/db conn) tx1)))))) (testing "Looks up value refs" (let [{tx :tx} (<? (d/<transact! conn [[:db/add 1 :friends (d/lookup-ref :name "PI:NAME:<NAME>END_PI")] [:db/add 3 :friends (d/lookup-ref :name "PI:NAME:<NAME>END_PI")]]))] (is (= #{[1 :friends 3] [3 :friends 1]} (<? (<datoms>= (d/db conn) tx)))))) (testing "Looks up entity refs in maps" (let [{tx :tx} (<? (d/<transact! conn [{:db/id (d/lookup-ref :name "PI:NAME:<NAME>END_PI") :friends 1}]))] (is (= #{[2 :friends 1]} (<? (<datoms>= (d/db conn) tx)))))) (testing "Looks up value refs in maps" (let [{tx :tx} (<? (d/<transact! conn [{:db/id 2 :friends (d/lookup-ref :name "PI:NAME:<NAME>END_PI")}]))] (is (= #{[2 :friends 3]} (<? (<datoms>= (d/db conn) tx)))))) (testing "Looks up value refs in sequences in maps" (let [{tx :tx} (<? (d/<transact! conn [{:db/id 1 :friends [(d/lookup-ref :name "PI:NAME:<NAME>END_PI") (d/lookup-ref :name "PI:NAME:<NAME>END_PI")]}]))] (is (= #{[1 :friends 1] [1 :friends 2]} (<? (<datoms>= (d/db conn) tx)))))) (testing "Looks up refs when there are more than 999 refs (all present)" (let [bound (* 999 2) make-add #(vector :db/add (+ 1000 %) :name (str "PI:NAME:<NAME>END_PI-" %)) make-ref #(-> {:db/id (d/lookup-ref :name (str "PI:NAME:<NAME>END_PI-" %)) :email (str "Ivan-" % "@" %)}) {tx-data1 :tx-data} (<? (d/<transact! conn (map make-add (range bound)))) {tx-data2 :tx-data} (<? (d/<transact! conn (map make-ref (range bound))))] (is (= bound (dec (count tx-data1)))) ;; Each :name is new; dec to account for :db/tx. (is (= bound (dec (count tx-data2)))) ;; Each lookup-ref exists, each :email is new; dec for :db/tx. )) (testing "Fails for missing entities" (is (thrown-with-msg? ExceptionInfo #"No entity found for lookup-ref" (<? (d/<transact! conn [[:db/add (d/lookup-ref :name "PI:NAME:<NAME>END_PI") :aka "The Magician"]])))) (is (thrown-with-msg? ExceptionInfo #"No entity found for lookup-ref" (<? (d/<transact! conn [[:db/add 1 :friends (d/lookup-ref :name "PI:NAME:<NAME>END_PI")]]))))) (testing "Fails for non-identity attributes" (is (thrown-with-msg? ExceptionInfo #"Lookup-ref found with non-unique-identity attribute" (<? (d/<transact! conn [[:db/add (d/lookup-ref :aka "The Magician") :email "@2"]])))) (is (thrown-with-msg? ExceptionInfo #"Lookup-ref found with non-unique-identity attribute" (<? (d/<transact! conn [[:db/add 1 :friends (d/lookup-ref :aka "The Magician")]]))))))) (deftest-db test-fulltext-lookup-refs conn (let [schema [{:db/id (d/id-literal :db.part/db -1) :db/ident :test/fulltext :db/valueType :db.type/string :db/fulltext true :db/unique :db.unique/identity} {:db/id :db.part/db :db.install/attribute (d/id-literal :db.part/db -1)} {:db/id (d/id-literal :db.part/db -2) :db/ident :test/other :db/valueType :db.type/string :db/fulltext true :db/cardinality :db.cardinality/one} {:db/id :db.part/db :db.install/attribute (d/id-literal :db.part/db -2)} ] tx0 (:tx (<? (d/<transact! conn schema)))] (testing "Can look up fulltext refs" (<? (d/<transact! conn [[:db/add 101 :test/fulltext "test this"]])) (let [{tx :tx} (<? (d/<transact! conn [{:db/id (d/lookup-ref :test/fulltext "test this") :test/other "test other"}]))] (is (= (<? (<fulltext-values (d/db conn))) [[1 "test this"] [2 "test other"]])) (is (= #{[101 :test/other 2]} ;; Values are raw; 2 is the rowid into fulltext_values. (<? (<datoms>= (d/db conn) tx)))))) (testing "Fails for missing fulltext entities" (is (thrown-with-msg? ExceptionInfo #"No entity found for lookup-ref" (<? (d/<transact! conn [[:db/add (d/lookup-ref :test/fulltext "not found") :test/other "test random"]]))))))) #_ (time (t/run-tests)) #_ (time (clojure.test/test-vars [#'test-lookup-refs]))
[ { "context": " private-keyset-handle (keyset/generate-new :ecies-p256-hkdf-hmac-sha256-aes128-gcm)\n public-keyset-handle (keyset/get-publi", "end": 569, "score": 0.8161426186561584, "start": 533, "tag": "KEY", "value": "ies-p256-hkdf-hmac-sha256-aes128-gcm" } ]
test/tinklj/acceptance/hybrid_encryption_test.clj
lamp/tinklj
22
(ns tinklj.acceptance.hybrid-encryption-test (:require [clojure.test :refer [deftest is testing]] [tinklj.config :refer [register]] [tinklj.keys.keyset-handle :as keyset] [tinklj.primitives :as primitives] [tinklj.encryption.aead :refer [encrypt decrypt]])) (register) (deftest hybrid-encryption-test (testing "Hybrid Encryption using Public and Private Key" (let [aad (.getBytes "salt") plain-text "Secret" private-keyset-handle (keyset/generate-new :ecies-p256-hkdf-hmac-sha256-aes128-gcm) public-keyset-handle (keyset/get-public-keyset-handle private-keyset-handle) hybrid-encrypt (primitives/hybrid-encryption public-keyset-handle) hybrid-decrypt (primitives/hybrid-decryption private-keyset-handle) encrypted-data (encrypt hybrid-encrypt (.getBytes plain-text) aad) decrypted-data (decrypt hybrid-decrypt encrypted-data aad)] (is (= plain-text (String. decrypted-data))))))
4484
(ns tinklj.acceptance.hybrid-encryption-test (:require [clojure.test :refer [deftest is testing]] [tinklj.config :refer [register]] [tinklj.keys.keyset-handle :as keyset] [tinklj.primitives :as primitives] [tinklj.encryption.aead :refer [encrypt decrypt]])) (register) (deftest hybrid-encryption-test (testing "Hybrid Encryption using Public and Private Key" (let [aad (.getBytes "salt") plain-text "Secret" private-keyset-handle (keyset/generate-new :ec<KEY>) public-keyset-handle (keyset/get-public-keyset-handle private-keyset-handle) hybrid-encrypt (primitives/hybrid-encryption public-keyset-handle) hybrid-decrypt (primitives/hybrid-decryption private-keyset-handle) encrypted-data (encrypt hybrid-encrypt (.getBytes plain-text) aad) decrypted-data (decrypt hybrid-decrypt encrypted-data aad)] (is (= plain-text (String. decrypted-data))))))
true
(ns tinklj.acceptance.hybrid-encryption-test (:require [clojure.test :refer [deftest is testing]] [tinklj.config :refer [register]] [tinklj.keys.keyset-handle :as keyset] [tinklj.primitives :as primitives] [tinklj.encryption.aead :refer [encrypt decrypt]])) (register) (deftest hybrid-encryption-test (testing "Hybrid Encryption using Public and Private Key" (let [aad (.getBytes "salt") plain-text "Secret" private-keyset-handle (keyset/generate-new :ecPI:KEY:<KEY>END_PI) public-keyset-handle (keyset/get-public-keyset-handle private-keyset-handle) hybrid-encrypt (primitives/hybrid-encryption public-keyset-handle) hybrid-decrypt (primitives/hybrid-decryption private-keyset-handle) encrypted-data (encrypt hybrid-encrypt (.getBytes plain-text) aad) decrypted-data (decrypt hybrid-decrypt encrypted-data aad)] (is (= plain-text (String. decrypted-data))))))
[ { "context": "Functions for unit conversions\n References:\n [1] Meeus, Jean. _Astronomical Algorithms_ 2nd Ed. Willman-Bell, ", "end": 104, "score": 0.9991084933280945, "start": 93, "tag": "NAME", "value": "Meeus, Jean" } ]
src/com/climate/astro_algo/conversions.clj
TheClimateCorporation/astro-algo
8
(ns com.climate.astro-algo.conversions "Functions for unit conversions References: [1] Meeus, Jean. _Astronomical Algorithms_ 2nd Ed. Willman-Bell, Inc. 1998.") (defn deg->rad "Convert degrees to radians" [deg] ; based on [1] Ch.1 (* deg (/ (Math/PI) 180))) (defn rad->deg "Convert radians to degrees" [rad] ; based on [1] Ch.1 (* rad (/ 180 (Math/PI)))) (defn instant->deg "Convert hours, minutes, seconds to degrees" ; based on [1] Ch.1 [hours minutes seconds] (let [total-hours (-> (/ seconds 60) (+ minutes) (/ 60) (+ hours))] (* total-hours 15))) (defn angle->deg "Convert degrees, arcminutes, arcseconds to degrees" ; based on [1] Ch.1 [degrees arcminutes arcseconds] (-> (/ arcseconds 60) (+ arcminutes) (/ 60) (+ degrees)))
72069
(ns com.climate.astro-algo.conversions "Functions for unit conversions References: [1] <NAME>. _Astronomical Algorithms_ 2nd Ed. Willman-Bell, Inc. 1998.") (defn deg->rad "Convert degrees to radians" [deg] ; based on [1] Ch.1 (* deg (/ (Math/PI) 180))) (defn rad->deg "Convert radians to degrees" [rad] ; based on [1] Ch.1 (* rad (/ 180 (Math/PI)))) (defn instant->deg "Convert hours, minutes, seconds to degrees" ; based on [1] Ch.1 [hours minutes seconds] (let [total-hours (-> (/ seconds 60) (+ minutes) (/ 60) (+ hours))] (* total-hours 15))) (defn angle->deg "Convert degrees, arcminutes, arcseconds to degrees" ; based on [1] Ch.1 [degrees arcminutes arcseconds] (-> (/ arcseconds 60) (+ arcminutes) (/ 60) (+ degrees)))
true
(ns com.climate.astro-algo.conversions "Functions for unit conversions References: [1] PI:NAME:<NAME>END_PI. _Astronomical Algorithms_ 2nd Ed. Willman-Bell, Inc. 1998.") (defn deg->rad "Convert degrees to radians" [deg] ; based on [1] Ch.1 (* deg (/ (Math/PI) 180))) (defn rad->deg "Convert radians to degrees" [rad] ; based on [1] Ch.1 (* rad (/ 180 (Math/PI)))) (defn instant->deg "Convert hours, minutes, seconds to degrees" ; based on [1] Ch.1 [hours minutes seconds] (let [total-hours (-> (/ seconds 60) (+ minutes) (/ 60) (+ hours))] (* total-hours 15))) (defn angle->deg "Convert degrees, arcminutes, arcseconds to degrees" ; based on [1] Ch.1 [degrees arcminutes arcseconds] (-> (/ arcseconds 60) (+ arcminutes) (/ 60) (+ degrees)))
[ { "context": ".4.4\"\n :sha256-hash \"b4dc37877a0fd00fc72ebda98977c2133be9ba6b26bcdd13b1b14a369e508948\"}\n :docker {:bip \"192.168.1.1", "end": 5327, "score": 0.989876389503479, "start": 5263, "tag": "KEY", "value": "b4dc37877a0fd00fc72ebda98977c2133be9ba6b26bcdd13b1b14a369e508948" }, { "context": "a369e508948\"}\n :docker {:bip \"192.168.1.1/24\"}\n :aws {}}\n :i", "end": 5377, "score": 0.9995784163475037, "start": 5366, "tag": "IP_ADDRESS", "value": "192.168.1.1" } ]
main/src/dda/pallet/dda_managed_ide/domain.clj
DomainDrivenArchitecture/dda-managed-ide
10
; Licensed to the Apache Software Foundation (ASF) under one ; or more contributor license agreements. See the NOTICE file ; distributed with this work for additional information ; regarding copyright ownership. The ASF licenses this file ; to you under the Apache License, Version 2.0 (the ; "License"); you may not use this file except in compliance ; with the License. You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns dda.pallet.dda-managed-ide.domain (:require [schema.core :as s] [dda.pallet.commons.secret :as secret] [dda.config.commons.map-utils :as mu] [dda.pallet.dda-managed-vm.domain :as vm-domain] [dda.pallet.dda-git-crate.domain :as git-domain] [dda.pallet.dda-managed-ide.domain.git :as git] [dda.pallet.dda-managed-ide.domain.atom :as atom] [dda.pallet.dda-managed-ide.domain.idea :as idea] [dda.pallet.dda-managed-ide.domain.serverspec :as serverspec] [dda.pallet.dda-managed-ide.infra :as infra])) (def InfraResult {infra/facility infra/DdaIdeConfig}) (def RepoAuth {:repo s/Str :username secret/Secret :password secret/Secret}) (def DdaIdeDomainConfig (merge vm-domain/DdaVmUser vm-domain/DdaVmDomainBookmarks vm-domain/DdaVmTargetType {:target-type (s/enum :virtualbox :remote-aws :plain)} {:ide-platform (hash-set (s/enum :atom :idea :pycharm)) (s/optional-key :git) git-domain/GitDomain (s/optional-key :clojure) {(s/optional-key :lein-auth) [RepoAuth]} (s/optional-key :java) {} (s/optional-key :java-script) {:nodejs-use s/Str} (s/optional-key :bigdata) {} (s/optional-key :devops) {(s/optional-key :aws) {(s/optional-key :simple) {:id secret/Secret :secret secret/Secret}} (s/optional-key :docker) {:bip s/Str}}})) (def RepoAuthResolved (secret/create-resolved-schema RepoAuth)) (def DdaIdeDomainResolvedConfig (secret/create-resolved-schema DdaIdeDomainConfig)) ;TODO: backup-crate integration (s/defn ^:always-validate ide-git-config [ide-config :- DdaIdeDomainResolvedConfig] (let [{:keys [user git]} ide-config {:keys [name email git-credentials desktop-wiki credential-store]} user ide-git-config (git/ide-git-config name email git-credentials desktop-wiki credential-store)] (mu/deep-merge {} git ide-git-config))) (s/defn ^:always-validate ide-serverspec-config [domain-config :- DdaIdeDomainResolvedConfig] (serverspec/serverspec-prerequisits)) (s/defn ^:always-validate dda-vm-domain-configuration [ide-config :- DdaIdeDomainResolvedConfig] (let [{:keys [user bookmarks target-type]} ide-config] (merge {:user user :target-type target-type :usage-type :desktop-ide} (when (contains? ide-config :bookmarks) {:bookmarks bookmarks})))) (s/defn ^:always-validate infra-configuration :- InfraResult [domain-config :- DdaIdeDomainResolvedConfig] (let [{:keys [user vm-type ide-platform clojure devops java-script]} domain-config user-name (:name user) contains-clojure? (contains? domain-config :clojure) contains-java? (contains? domain-config :java) contains-java-script? (contains? domain-config :java-script) contains-devops? (contains? domain-config :devops) contains-bigdata? (contains? domain-config :bigdata)] {infra/facility (mu/deep-merge {:ide-user (keyword (:name user)) :ide-settings #{:install-basics :install-tmate :install-asciinema :install-pgtools} :basics {:argo-uml {:version "0.34"} :yed {:download-url "https://www.yworks.com/resources/yed/demo/yEd-3.20.zip"}} :db {:dbvis {:version "10.0.25"}}} (when (contains? ide-platform :atom) {:atom (atom/atom-config vm-type contains-clojure? contains-devops?)}) (when (contains? ide-platform :idea) {:idea (idea/idea-config vm-type contains-clojure? contains-devops?) :ide-settings #{:install-idea-inodes}}) (when (contains? ide-platform :pycharm) {:pycharm (idea/pycharm-config)}) (when contains-clojure? {:clojure clojure :java {:java-default-to "/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java"}}) (when contains-java? {:java {:gradle {:version "4.9"}}}) (if contains-java-script? {:java-script java-script :ide-settings #{:install-nvm :install-asciinema}} {:ide-settings #{:install-npm :install-asciinema}}) (when contains-devops? (mu/deep-merge {:devops {:terraform {:version "0.12.11" :sha256-hash "d61f8758a25bc079bb0833b81f998fbc4cf03bb0f41b995e08204cf5978f700e"} :packer {:version "1.4.4" :sha256-hash "b4dc37877a0fd00fc72ebda98977c2133be9ba6b26bcdd13b1b14a369e508948"} :docker {:bip "192.168.1.1/24"} :aws {}} :ide-settings #{:install-pip3 :install-pybuilder :install-mfa :install-ami-cleaner}} {:devops devops})) (when contains-bigdata? {:ide-settings #{:install-pip3 :install-jupyterlab}}))}))
1646
; Licensed to the Apache Software Foundation (ASF) under one ; or more contributor license agreements. See the NOTICE file ; distributed with this work for additional information ; regarding copyright ownership. The ASF licenses this file ; to you under the Apache License, Version 2.0 (the ; "License"); you may not use this file except in compliance ; with the License. You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns dda.pallet.dda-managed-ide.domain (:require [schema.core :as s] [dda.pallet.commons.secret :as secret] [dda.config.commons.map-utils :as mu] [dda.pallet.dda-managed-vm.domain :as vm-domain] [dda.pallet.dda-git-crate.domain :as git-domain] [dda.pallet.dda-managed-ide.domain.git :as git] [dda.pallet.dda-managed-ide.domain.atom :as atom] [dda.pallet.dda-managed-ide.domain.idea :as idea] [dda.pallet.dda-managed-ide.domain.serverspec :as serverspec] [dda.pallet.dda-managed-ide.infra :as infra])) (def InfraResult {infra/facility infra/DdaIdeConfig}) (def RepoAuth {:repo s/Str :username secret/Secret :password secret/Secret}) (def DdaIdeDomainConfig (merge vm-domain/DdaVmUser vm-domain/DdaVmDomainBookmarks vm-domain/DdaVmTargetType {:target-type (s/enum :virtualbox :remote-aws :plain)} {:ide-platform (hash-set (s/enum :atom :idea :pycharm)) (s/optional-key :git) git-domain/GitDomain (s/optional-key :clojure) {(s/optional-key :lein-auth) [RepoAuth]} (s/optional-key :java) {} (s/optional-key :java-script) {:nodejs-use s/Str} (s/optional-key :bigdata) {} (s/optional-key :devops) {(s/optional-key :aws) {(s/optional-key :simple) {:id secret/Secret :secret secret/Secret}} (s/optional-key :docker) {:bip s/Str}}})) (def RepoAuthResolved (secret/create-resolved-schema RepoAuth)) (def DdaIdeDomainResolvedConfig (secret/create-resolved-schema DdaIdeDomainConfig)) ;TODO: backup-crate integration (s/defn ^:always-validate ide-git-config [ide-config :- DdaIdeDomainResolvedConfig] (let [{:keys [user git]} ide-config {:keys [name email git-credentials desktop-wiki credential-store]} user ide-git-config (git/ide-git-config name email git-credentials desktop-wiki credential-store)] (mu/deep-merge {} git ide-git-config))) (s/defn ^:always-validate ide-serverspec-config [domain-config :- DdaIdeDomainResolvedConfig] (serverspec/serverspec-prerequisits)) (s/defn ^:always-validate dda-vm-domain-configuration [ide-config :- DdaIdeDomainResolvedConfig] (let [{:keys [user bookmarks target-type]} ide-config] (merge {:user user :target-type target-type :usage-type :desktop-ide} (when (contains? ide-config :bookmarks) {:bookmarks bookmarks})))) (s/defn ^:always-validate infra-configuration :- InfraResult [domain-config :- DdaIdeDomainResolvedConfig] (let [{:keys [user vm-type ide-platform clojure devops java-script]} domain-config user-name (:name user) contains-clojure? (contains? domain-config :clojure) contains-java? (contains? domain-config :java) contains-java-script? (contains? domain-config :java-script) contains-devops? (contains? domain-config :devops) contains-bigdata? (contains? domain-config :bigdata)] {infra/facility (mu/deep-merge {:ide-user (keyword (:name user)) :ide-settings #{:install-basics :install-tmate :install-asciinema :install-pgtools} :basics {:argo-uml {:version "0.34"} :yed {:download-url "https://www.yworks.com/resources/yed/demo/yEd-3.20.zip"}} :db {:dbvis {:version "10.0.25"}}} (when (contains? ide-platform :atom) {:atom (atom/atom-config vm-type contains-clojure? contains-devops?)}) (when (contains? ide-platform :idea) {:idea (idea/idea-config vm-type contains-clojure? contains-devops?) :ide-settings #{:install-idea-inodes}}) (when (contains? ide-platform :pycharm) {:pycharm (idea/pycharm-config)}) (when contains-clojure? {:clojure clojure :java {:java-default-to "/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java"}}) (when contains-java? {:java {:gradle {:version "4.9"}}}) (if contains-java-script? {:java-script java-script :ide-settings #{:install-nvm :install-asciinema}} {:ide-settings #{:install-npm :install-asciinema}}) (when contains-devops? (mu/deep-merge {:devops {:terraform {:version "0.12.11" :sha256-hash "d61f8758a25bc079bb0833b81f998fbc4cf03bb0f41b995e08204cf5978f700e"} :packer {:version "1.4.4" :sha256-hash "<KEY>"} :docker {:bip "192.168.1.1/24"} :aws {}} :ide-settings #{:install-pip3 :install-pybuilder :install-mfa :install-ami-cleaner}} {:devops devops})) (when contains-bigdata? {:ide-settings #{:install-pip3 :install-jupyterlab}}))}))
true
; Licensed to the Apache Software Foundation (ASF) under one ; or more contributor license agreements. See the NOTICE file ; distributed with this work for additional information ; regarding copyright ownership. The ASF licenses this file ; to you under the Apache License, Version 2.0 (the ; "License"); you may not use this file except in compliance ; with the License. You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns dda.pallet.dda-managed-ide.domain (:require [schema.core :as s] [dda.pallet.commons.secret :as secret] [dda.config.commons.map-utils :as mu] [dda.pallet.dda-managed-vm.domain :as vm-domain] [dda.pallet.dda-git-crate.domain :as git-domain] [dda.pallet.dda-managed-ide.domain.git :as git] [dda.pallet.dda-managed-ide.domain.atom :as atom] [dda.pallet.dda-managed-ide.domain.idea :as idea] [dda.pallet.dda-managed-ide.domain.serverspec :as serverspec] [dda.pallet.dda-managed-ide.infra :as infra])) (def InfraResult {infra/facility infra/DdaIdeConfig}) (def RepoAuth {:repo s/Str :username secret/Secret :password secret/Secret}) (def DdaIdeDomainConfig (merge vm-domain/DdaVmUser vm-domain/DdaVmDomainBookmarks vm-domain/DdaVmTargetType {:target-type (s/enum :virtualbox :remote-aws :plain)} {:ide-platform (hash-set (s/enum :atom :idea :pycharm)) (s/optional-key :git) git-domain/GitDomain (s/optional-key :clojure) {(s/optional-key :lein-auth) [RepoAuth]} (s/optional-key :java) {} (s/optional-key :java-script) {:nodejs-use s/Str} (s/optional-key :bigdata) {} (s/optional-key :devops) {(s/optional-key :aws) {(s/optional-key :simple) {:id secret/Secret :secret secret/Secret}} (s/optional-key :docker) {:bip s/Str}}})) (def RepoAuthResolved (secret/create-resolved-schema RepoAuth)) (def DdaIdeDomainResolvedConfig (secret/create-resolved-schema DdaIdeDomainConfig)) ;TODO: backup-crate integration (s/defn ^:always-validate ide-git-config [ide-config :- DdaIdeDomainResolvedConfig] (let [{:keys [user git]} ide-config {:keys [name email git-credentials desktop-wiki credential-store]} user ide-git-config (git/ide-git-config name email git-credentials desktop-wiki credential-store)] (mu/deep-merge {} git ide-git-config))) (s/defn ^:always-validate ide-serverspec-config [domain-config :- DdaIdeDomainResolvedConfig] (serverspec/serverspec-prerequisits)) (s/defn ^:always-validate dda-vm-domain-configuration [ide-config :- DdaIdeDomainResolvedConfig] (let [{:keys [user bookmarks target-type]} ide-config] (merge {:user user :target-type target-type :usage-type :desktop-ide} (when (contains? ide-config :bookmarks) {:bookmarks bookmarks})))) (s/defn ^:always-validate infra-configuration :- InfraResult [domain-config :- DdaIdeDomainResolvedConfig] (let [{:keys [user vm-type ide-platform clojure devops java-script]} domain-config user-name (:name user) contains-clojure? (contains? domain-config :clojure) contains-java? (contains? domain-config :java) contains-java-script? (contains? domain-config :java-script) contains-devops? (contains? domain-config :devops) contains-bigdata? (contains? domain-config :bigdata)] {infra/facility (mu/deep-merge {:ide-user (keyword (:name user)) :ide-settings #{:install-basics :install-tmate :install-asciinema :install-pgtools} :basics {:argo-uml {:version "0.34"} :yed {:download-url "https://www.yworks.com/resources/yed/demo/yEd-3.20.zip"}} :db {:dbvis {:version "10.0.25"}}} (when (contains? ide-platform :atom) {:atom (atom/atom-config vm-type contains-clojure? contains-devops?)}) (when (contains? ide-platform :idea) {:idea (idea/idea-config vm-type contains-clojure? contains-devops?) :ide-settings #{:install-idea-inodes}}) (when (contains? ide-platform :pycharm) {:pycharm (idea/pycharm-config)}) (when contains-clojure? {:clojure clojure :java {:java-default-to "/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java"}}) (when contains-java? {:java {:gradle {:version "4.9"}}}) (if contains-java-script? {:java-script java-script :ide-settings #{:install-nvm :install-asciinema}} {:ide-settings #{:install-npm :install-asciinema}}) (when contains-devops? (mu/deep-merge {:devops {:terraform {:version "0.12.11" :sha256-hash "d61f8758a25bc079bb0833b81f998fbc4cf03bb0f41b995e08204cf5978f700e"} :packer {:version "1.4.4" :sha256-hash "PI:KEY:<KEY>END_PI"} :docker {:bip "192.168.1.1/24"} :aws {}} :ide-settings #{:install-pip3 :install-pybuilder :install-mfa :install-ami-cleaner}} {:devops devops})) (when contains-bigdata? {:ide-settings #{:install-pip3 :install-jupyterlab}}))}))
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 29, "score": 0.9998094439506531, "start": 18, "tag": "NAME", "value": "Rich Hickey" } ]
vendor/bundle/ruby/2.1.0/gems/charlock_holmes-0.6.9.4/test/fixtures/repl2.cljs
suhongrui/gitlab
535
; Copyright (c) Rich Hickey. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns clojure.browser.repl2 (:require [clojure.browser.net :as net] [clojure.browser.event :as event] [goog.json :as gjson])) ;; Notes ;; ===== ;; ;; Using keywords for the service names does not work in Chrome or ;; FireFox. ;; ;; -- (defn log-obj [obj] (.log js/console obj)) ;; Outer/Parent Peer ;; ================= ;; ;; The code in this section will be run in the parent page which ;; exists in the application's domain. This is where code will be ;; evaluated. (def parent-channel (atom nil)) (defn- ensure-string [val] (if (string? val) val (str val))) (defn evaluate-javascript "Given a block of JavaScript, evaluate it and transmit the result to the inner peer of the cross domain channel." [block] (log-obj (str "evaluating: " block)) (let [result (pr-str (try {:status :success :value (ensure-string (js* "eval(~{block})"))} (catch js/Error e {:status :exception :value (pr-str e)})))] (log-obj (str "result: " result)) (net/transmit @parent-channel "return-value" result))) (defn create-cross-domain-channel "Create a cross domain channel with an iframe which can communicate with the REPL server." [url] (let [chnl (doto (net/xpc-connection {:peer_uri (str url "/repl")}) (net/register-service "evaluate-javascript" evaluate-javascript) (net/connect document.body (fn [] (log-obj "Parent channel connected.")) (fn [iframe] (set! iframe.style.display "none"))))] (reset! parent-channel chnl))) (defn connect "Connect to a ClojureScript REPL server located at the passed url." [url] (goog.events/listen js/window "load" #(create-cross-domain-channel url))) ;; Inner peer ;; ========= ;; ;; The code in this section will be run in the child iframe and can ;; communicate with REPL server. (def state (atom {:connection nil :url nil})) (def child-channel (atom nil)) (defn transmit-post [connection url data] (net/transmit connection url "POST" data nil 0)) (defn start-repl-connection "Start the REPL loop" [url] (let [connection (net/xhr-connection)] (reset! state {:connection connection :url url}) (event/listen connection :success (fn [e] (net/transmit @child-channel "evaluate-javascript" (.getResponseText e/currentTarget ())))) ;; The server is expecting to see the string "ready" for the ;; initial connection. (transmit-post connection url "ready"))) (defn return-value [val] (log-obj (str "sending: " val)) (transmit-post (:connection @state) (:url @state) val)) ;; I can't get this to work using the clojure.browser.net api. (defn inner-peer-channel "This function will be called from a script in the child iframe." [repl-url] (let [cfg (gjson/parse (.getParameterValue (goog.Uri. window.location.href) "xpc")) chnl (doto (goog.net.xpc.CrossPageChannel. cfg) (net/register-service "return-value" return-value) (.connect #(log-obj "Child channel connected.")))] (do (reset! child-channel chnl) (js/setTimeout #(start-repl-connection repl-url) 500))))
25060
; Copyright (c) <NAME>. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns clojure.browser.repl2 (:require [clojure.browser.net :as net] [clojure.browser.event :as event] [goog.json :as gjson])) ;; Notes ;; ===== ;; ;; Using keywords for the service names does not work in Chrome or ;; FireFox. ;; ;; -- (defn log-obj [obj] (.log js/console obj)) ;; Outer/Parent Peer ;; ================= ;; ;; The code in this section will be run in the parent page which ;; exists in the application's domain. This is where code will be ;; evaluated. (def parent-channel (atom nil)) (defn- ensure-string [val] (if (string? val) val (str val))) (defn evaluate-javascript "Given a block of JavaScript, evaluate it and transmit the result to the inner peer of the cross domain channel." [block] (log-obj (str "evaluating: " block)) (let [result (pr-str (try {:status :success :value (ensure-string (js* "eval(~{block})"))} (catch js/Error e {:status :exception :value (pr-str e)})))] (log-obj (str "result: " result)) (net/transmit @parent-channel "return-value" result))) (defn create-cross-domain-channel "Create a cross domain channel with an iframe which can communicate with the REPL server." [url] (let [chnl (doto (net/xpc-connection {:peer_uri (str url "/repl")}) (net/register-service "evaluate-javascript" evaluate-javascript) (net/connect document.body (fn [] (log-obj "Parent channel connected.")) (fn [iframe] (set! iframe.style.display "none"))))] (reset! parent-channel chnl))) (defn connect "Connect to a ClojureScript REPL server located at the passed url." [url] (goog.events/listen js/window "load" #(create-cross-domain-channel url))) ;; Inner peer ;; ========= ;; ;; The code in this section will be run in the child iframe and can ;; communicate with REPL server. (def state (atom {:connection nil :url nil})) (def child-channel (atom nil)) (defn transmit-post [connection url data] (net/transmit connection url "POST" data nil 0)) (defn start-repl-connection "Start the REPL loop" [url] (let [connection (net/xhr-connection)] (reset! state {:connection connection :url url}) (event/listen connection :success (fn [e] (net/transmit @child-channel "evaluate-javascript" (.getResponseText e/currentTarget ())))) ;; The server is expecting to see the string "ready" for the ;; initial connection. (transmit-post connection url "ready"))) (defn return-value [val] (log-obj (str "sending: " val)) (transmit-post (:connection @state) (:url @state) val)) ;; I can't get this to work using the clojure.browser.net api. (defn inner-peer-channel "This function will be called from a script in the child iframe." [repl-url] (let [cfg (gjson/parse (.getParameterValue (goog.Uri. window.location.href) "xpc")) chnl (doto (goog.net.xpc.CrossPageChannel. cfg) (net/register-service "return-value" return-value) (.connect #(log-obj "Child channel connected.")))] (do (reset! child-channel chnl) (js/setTimeout #(start-repl-connection repl-url) 500))))
true
; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns clojure.browser.repl2 (:require [clojure.browser.net :as net] [clojure.browser.event :as event] [goog.json :as gjson])) ;; Notes ;; ===== ;; ;; Using keywords for the service names does not work in Chrome or ;; FireFox. ;; ;; -- (defn log-obj [obj] (.log js/console obj)) ;; Outer/Parent Peer ;; ================= ;; ;; The code in this section will be run in the parent page which ;; exists in the application's domain. This is where code will be ;; evaluated. (def parent-channel (atom nil)) (defn- ensure-string [val] (if (string? val) val (str val))) (defn evaluate-javascript "Given a block of JavaScript, evaluate it and transmit the result to the inner peer of the cross domain channel." [block] (log-obj (str "evaluating: " block)) (let [result (pr-str (try {:status :success :value (ensure-string (js* "eval(~{block})"))} (catch js/Error e {:status :exception :value (pr-str e)})))] (log-obj (str "result: " result)) (net/transmit @parent-channel "return-value" result))) (defn create-cross-domain-channel "Create a cross domain channel with an iframe which can communicate with the REPL server." [url] (let [chnl (doto (net/xpc-connection {:peer_uri (str url "/repl")}) (net/register-service "evaluate-javascript" evaluate-javascript) (net/connect document.body (fn [] (log-obj "Parent channel connected.")) (fn [iframe] (set! iframe.style.display "none"))))] (reset! parent-channel chnl))) (defn connect "Connect to a ClojureScript REPL server located at the passed url." [url] (goog.events/listen js/window "load" #(create-cross-domain-channel url))) ;; Inner peer ;; ========= ;; ;; The code in this section will be run in the child iframe and can ;; communicate with REPL server. (def state (atom {:connection nil :url nil})) (def child-channel (atom nil)) (defn transmit-post [connection url data] (net/transmit connection url "POST" data nil 0)) (defn start-repl-connection "Start the REPL loop" [url] (let [connection (net/xhr-connection)] (reset! state {:connection connection :url url}) (event/listen connection :success (fn [e] (net/transmit @child-channel "evaluate-javascript" (.getResponseText e/currentTarget ())))) ;; The server is expecting to see the string "ready" for the ;; initial connection. (transmit-post connection url "ready"))) (defn return-value [val] (log-obj (str "sending: " val)) (transmit-post (:connection @state) (:url @state) val)) ;; I can't get this to work using the clojure.browser.net api. (defn inner-peer-channel "This function will be called from a script in the child iframe." [repl-url] (let [cfg (gjson/parse (.getParameterValue (goog.Uri. window.location.href) "xpc")) chnl (doto (goog.net.xpc.CrossPageChannel. cfg) (net/register-service "return-value" return-value) (.connect #(log-obj "Child channel connected.")))] (do (reset! child-channel chnl) (js/setTimeout #(start-repl-connection repl-url) 500))))
[ { "context": ";; Copyright (c) Michal Kurťák\n;; All rights reserved.\n(ns salt.test-utils)\n\n(de", "end": 30, "score": 0.9998072385787964, "start": 17, "tag": "NAME", "value": "Michal Kurťák" } ]
test/src/salt/test_utils.clj
mkurtak/clj-salt-api
9
;; Copyright (c) Michal Kurťák ;; All rights reserved. (ns salt.test-utils) (defn- expand-let-flow [name forms] (let [prev (gensym)] (loop [x '() frms (reverse (partition 2 forms))] (if frms (let [form (first frms) expr (second form) test-expr (first form) threaded `(let [~prev ~name ~name (~(first expr) ~prev ~@(next expr))] ~test-expr ~@x)] (recur (list threaded) (next frms))) x)))) (defmacro test-flow-> [expr name & forms] `(let [~name ~expr] ~@(expand-let-flow name forms))) (defn submap? "Is m1 a subset of m2?" [m1 m2] (if (and (map? m1) (map? m2)) (every? (fn [[k v]] (and (contains? m2 k) (submap? v (get m2 k)))) m1) (if (and (coll? m1) (coll? m2)) (every? (fn [v] (some #(submap? v %) m2)) m1) (= m1 m2)) )) (comment (submap? {:command :send :conf {:val1 "val1"} :body [{:minion "m1" :success false}]} {:command :send :test "test1" :conf {:val1 "val1" :val2 "val2"} :body [{:minion "m1" :more "Test" :success false}] }) )
28266
;; Copyright (c) <NAME> ;; All rights reserved. (ns salt.test-utils) (defn- expand-let-flow [name forms] (let [prev (gensym)] (loop [x '() frms (reverse (partition 2 forms))] (if frms (let [form (first frms) expr (second form) test-expr (first form) threaded `(let [~prev ~name ~name (~(first expr) ~prev ~@(next expr))] ~test-expr ~@x)] (recur (list threaded) (next frms))) x)))) (defmacro test-flow-> [expr name & forms] `(let [~name ~expr] ~@(expand-let-flow name forms))) (defn submap? "Is m1 a subset of m2?" [m1 m2] (if (and (map? m1) (map? m2)) (every? (fn [[k v]] (and (contains? m2 k) (submap? v (get m2 k)))) m1) (if (and (coll? m1) (coll? m2)) (every? (fn [v] (some #(submap? v %) m2)) m1) (= m1 m2)) )) (comment (submap? {:command :send :conf {:val1 "val1"} :body [{:minion "m1" :success false}]} {:command :send :test "test1" :conf {:val1 "val1" :val2 "val2"} :body [{:minion "m1" :more "Test" :success false}] }) )
true
;; Copyright (c) PI:NAME:<NAME>END_PI ;; All rights reserved. (ns salt.test-utils) (defn- expand-let-flow [name forms] (let [prev (gensym)] (loop [x '() frms (reverse (partition 2 forms))] (if frms (let [form (first frms) expr (second form) test-expr (first form) threaded `(let [~prev ~name ~name (~(first expr) ~prev ~@(next expr))] ~test-expr ~@x)] (recur (list threaded) (next frms))) x)))) (defmacro test-flow-> [expr name & forms] `(let [~name ~expr] ~@(expand-let-flow name forms))) (defn submap? "Is m1 a subset of m2?" [m1 m2] (if (and (map? m1) (map? m2)) (every? (fn [[k v]] (and (contains? m2 k) (submap? v (get m2 k)))) m1) (if (and (coll? m1) (coll? m2)) (every? (fn [v] (some #(submap? v %) m2)) m1) (= m1 m2)) )) (comment (submap? {:command :send :conf {:val1 "val1"} :body [{:minion "m1" :success false}]} {:command :send :test "test1" :conf {:val1 "val1" :val2 "val2"} :body [{:minion "m1" :more "Test" :success false}] }) )
[ { "context": "\n\n(def db {})\n\n(deftest add-student\n (is (= {2 [\"Aimee\"]} (school/add db \"Aimee\" 2))))\n\n(deftest add-mor", "end": 140, "score": 0.9993776679039001, "start": 135, "tag": "NAME", "value": "Aimee" }, { "context": "dd-student\n (is (= {2 [\"Aimee\"]} (school/add db \"Aimee\" 2))))\n\n(deftest add-more-students-in-same-class\n", "end": 165, "score": 0.9992576241493225, "start": 160, "tag": "NAME", "value": "Aimee" }, { "context": "est add-more-students-in-same-class\n (is (= {2 [\"James\", \"Blair\", \"Paul\"]}\n (-> db\n ", "end": 234, "score": 0.9997453093528748, "start": 229, "tag": "NAME", "value": "James" }, { "context": "ore-students-in-same-class\n (is (= {2 [\"James\", \"Blair\", \"Paul\"]}\n (-> db\n (school/a", "end": 243, "score": 0.9996207356452942, "start": 238, "tag": "NAME", "value": "Blair" }, { "context": "nts-in-same-class\n (is (= {2 [\"James\", \"Blair\", \"Paul\"]}\n (-> db\n (school/add \"Jame", "end": 251, "score": 0.9994392395019531, "start": 247, "tag": "NAME", "value": "Paul" }, { "context": "Paul\"]}\n (-> db\n (school/add \"James\" 2)\n (school/add \"Blair\" 2)\n ", "end": 302, "score": 0.9986947774887085, "start": 297, "tag": "NAME", "value": "James" }, { "context": " (school/add \"James\" 2)\n (school/add \"Blair\" 2)\n (school/add \"Paul\" 2)))))\n\n(deft", "end": 338, "score": 0.9982813596725464, "start": 333, "tag": "NAME", "value": "Blair" }, { "context": " (school/add \"Blair\" 2)\n (school/add \"Paul\" 2)))))\n\n(deftest add-students-to-different-grade", "end": 373, "score": 0.9939496517181396, "start": 369, "tag": "NAME", "value": "Paul" }, { "context": "st add-students-to-different-grades\n (is (= {3 [\"Chelsea\"] 7 [\"Logan\"]}\n (-> db\n (scho", "end": 446, "score": 0.928473949432373, "start": 439, "tag": "NAME", "value": "Chelsea" }, { "context": "s-to-different-grades\n (is (= {3 [\"Chelsea\"] 7 [\"Logan\"]}\n (-> db\n (school/add \"Chel", "end": 458, "score": 0.9984639883041382, "start": 453, "tag": "NAME", "value": "Logan" }, { "context": "gan\"]}\n (-> db\n (school/add \"Chelsea\" 3)\n (school/add \"Logan\" 7)))))\n\n(def", "end": 511, "score": 0.9279987215995789, "start": 505, "tag": "NAME", "value": "helsea" }, { "context": "school/add \"Chelsea\" 3)\n (school/add \"Logan\" 7)))))\n\n(deftest get-students-in-a-grade\n (is (", "end": 547, "score": 0.9706794619560242, "start": 542, "tag": "NAME", "value": "Logan" }, { "context": "))))\n\n(deftest get-students-in-a-grade\n (is (= [\"Franklin\", \"Bradley\"]\n (-> db\n (school", "end": 609, "score": 0.9995970129966736, "start": 601, "tag": "NAME", "value": "Franklin" }, { "context": "st get-students-in-a-grade\n (is (= [\"Franklin\", \"Bradley\"]\n (-> db\n (school/add \"Frank", "end": 620, "score": 0.9995858073234558, "start": 613, "tag": "NAME", "value": "Bradley" }, { "context": "adley\"]\n (-> db\n (school/add \"Franklin\" 5)\n (school/add \"Bradley\" 5)\n ", "end": 673, "score": 0.9977732300758362, "start": 665, "tag": "NAME", "value": "Franklin" }, { "context": "chool/add \"Franklin\" 5)\n (school/add \"Bradley\" 5)\n (school/add \"Jeff\" 1)\n ", "end": 711, "score": 0.9993922114372253, "start": 704, "tag": "NAME", "value": "Bradley" }, { "context": "school/add \"Bradley\" 5)\n (school/add \"Jeff\" 1)\n (school/grade 5)))))\n\n(deftest g", "end": 746, "score": 0.9993473291397095, "start": 742, "tag": "NAME", "value": "Jeff" }, { "context": "e db 1))))\n\n(deftest sorted-school\n (is (= { 3 [\"Kyle\"]\n 4 [\"Christopher\" \"Jennifer\"]\n ", "end": 910, "score": 0.999381422996521, "start": 906, "tag": "NAME", "value": "Kyle" }, { "context": "orted-school\n (is (= { 3 [\"Kyle\"]\n 4 [\"Christopher\" \"Jennifer\"]\n 6 [\"Kareem\"] }\n (", "end": 939, "score": 0.9997526407241821, "start": 928, "tag": "NAME", "value": "Christopher" }, { "context": " (is (= { 3 [\"Kyle\"]\n 4 [\"Christopher\" \"Jennifer\"]\n 6 [\"Kareem\"] }\n (-> db\n ", "end": 950, "score": 0.9997153878211975, "start": 942, "tag": "NAME", "value": "Jennifer" }, { "context": " 4 [\"Christopher\" \"Jennifer\"]\n 6 [\"Kareem\"] }\n (-> db\n (school/add \"Jen", "end": 974, "score": 0.9996728897094727, "start": 968, "tag": "NAME", "value": "Kareem" }, { "context": "eem\"] }\n (-> db\n (school/add \"Jennifer\" 4)\n (school/add \"Kareem\" 6)\n ", "end": 1029, "score": 0.9982364177703857, "start": 1021, "tag": "NAME", "value": "Jennifer" }, { "context": "chool/add \"Jennifer\" 4)\n (school/add \"Kareem\" 6)\n (school/add \"Christopher\" 4)\n ", "end": 1066, "score": 0.9967651963233948, "start": 1060, "tag": "NAME", "value": "Kareem" }, { "context": "(school/add \"Kareem\" 6)\n (school/add \"Christopher\" 4)\n (school/add \"Kyle\" 3)\n ", "end": 1108, "score": 0.9990787506103516, "start": 1097, "tag": "NAME", "value": "Christopher" }, { "context": "ol/add \"Christopher\" 4)\n (school/add \"Kyle\" 3)\n (school/sorted)))))\n\n(deftest ad", "end": 1143, "score": 0.999176561832428, "start": 1139, "tag": "NAME", "value": "Kyle" }, { "context": "d-students-avoids-external-mutation\n (is (= {3 [\"Chelsea\"] 7 [\"Logan\"]}\n (-> db\n (asso", "end": 1250, "score": 0.9991586804389954, "start": 1243, "tag": "NAME", "value": "Chelsea" }, { "context": "ids-external-mutation\n (is (= {3 [\"Chelsea\"] 7 [\"Logan\"]}\n (-> db\n (assoc 2 [\"John\"]", "end": 1262, "score": 0.9996777772903442, "start": 1257, "tag": "NAME", "value": "Logan" }, { "context": "\"Logan\"]}\n (-> db\n (assoc 2 [\"John\"])\n (school/add \"Chelsea\" 3)\n ", "end": 1310, "score": 0.9997888207435608, "start": 1306, "tag": "NAME", "value": "John" }, { "context": " (assoc 2 [\"John\"])\n (school/add \"Chelsea\" 3)\n (assoc 4 [\"Judie\"])\n ", "end": 1347, "score": 0.993238091468811, "start": 1341, "tag": "NAME", "value": "helsea" }, { "context": " (school/add \"Chelsea\" 3)\n (assoc 4 [\"Judie\"])\n (school/add \"Logan\" 7)))))\n\n(run-", "end": 1381, "score": 0.9997712969779968, "start": 1376, "tag": "NAME", "value": "Judie" }, { "context": " (assoc 4 [\"Judie\"])\n (school/add \"Logan\" 7)))))\n\n(run-tests)\n", "end": 1416, "score": 0.9847303628921509, "start": 1411, "tag": "NAME", "value": "Logan" } ]
clojure/grade-school/grade_school_test.clj
arnab/exercism
1
(ns grade-school.test (:require [clojure.test :refer :all])) (load-file "school.clj") (def db {}) (deftest add-student (is (= {2 ["Aimee"]} (school/add db "Aimee" 2)))) (deftest add-more-students-in-same-class (is (= {2 ["James", "Blair", "Paul"]} (-> db (school/add "James" 2) (school/add "Blair" 2) (school/add "Paul" 2))))) (deftest add-students-to-different-grades (is (= {3 ["Chelsea"] 7 ["Logan"]} (-> db (school/add "Chelsea" 3) (school/add "Logan" 7))))) (deftest get-students-in-a-grade (is (= ["Franklin", "Bradley"] (-> db (school/add "Franklin" 5) (school/add "Bradley" 5) (school/add "Jeff" 1) (school/grade 5))))) (deftest get-students-in-a-non-existant-grade (is (= [] (school/grade db 1)))) (deftest sorted-school (is (= { 3 ["Kyle"] 4 ["Christopher" "Jennifer"] 6 ["Kareem"] } (-> db (school/add "Jennifer" 4) (school/add "Kareem" 6) (school/add "Christopher" 4) (school/add "Kyle" 3) (school/sorted))))) (deftest add-students-avoids-external-mutation (is (= {3 ["Chelsea"] 7 ["Logan"]} (-> db (assoc 2 ["John"]) (school/add "Chelsea" 3) (assoc 4 ["Judie"]) (school/add "Logan" 7))))) (run-tests)
61676
(ns grade-school.test (:require [clojure.test :refer :all])) (load-file "school.clj") (def db {}) (deftest add-student (is (= {2 ["<NAME>"]} (school/add db "<NAME>" 2)))) (deftest add-more-students-in-same-class (is (= {2 ["<NAME>", "<NAME>", "<NAME>"]} (-> db (school/add "<NAME>" 2) (school/add "<NAME>" 2) (school/add "<NAME>" 2))))) (deftest add-students-to-different-grades (is (= {3 ["<NAME>"] 7 ["<NAME>"]} (-> db (school/add "C<NAME>" 3) (school/add "<NAME>" 7))))) (deftest get-students-in-a-grade (is (= ["<NAME>", "<NAME>"] (-> db (school/add "<NAME>" 5) (school/add "<NAME>" 5) (school/add "<NAME>" 1) (school/grade 5))))) (deftest get-students-in-a-non-existant-grade (is (= [] (school/grade db 1)))) (deftest sorted-school (is (= { 3 ["<NAME>"] 4 ["<NAME>" "<NAME>"] 6 ["<NAME>"] } (-> db (school/add "<NAME>" 4) (school/add "<NAME>" 6) (school/add "<NAME>" 4) (school/add "<NAME>" 3) (school/sorted))))) (deftest add-students-avoids-external-mutation (is (= {3 ["<NAME>"] 7 ["<NAME>"]} (-> db (assoc 2 ["<NAME>"]) (school/add "C<NAME>" 3) (assoc 4 ["<NAME>"]) (school/add "<NAME>" 7))))) (run-tests)
true
(ns grade-school.test (:require [clojure.test :refer :all])) (load-file "school.clj") (def db {}) (deftest add-student (is (= {2 ["PI:NAME:<NAME>END_PI"]} (school/add db "PI:NAME:<NAME>END_PI" 2)))) (deftest add-more-students-in-same-class (is (= {2 ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"]} (-> db (school/add "PI:NAME:<NAME>END_PI" 2) (school/add "PI:NAME:<NAME>END_PI" 2) (school/add "PI:NAME:<NAME>END_PI" 2))))) (deftest add-students-to-different-grades (is (= {3 ["PI:NAME:<NAME>END_PI"] 7 ["PI:NAME:<NAME>END_PI"]} (-> db (school/add "CPI:NAME:<NAME>END_PI" 3) (school/add "PI:NAME:<NAME>END_PI" 7))))) (deftest get-students-in-a-grade (is (= ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"] (-> db (school/add "PI:NAME:<NAME>END_PI" 5) (school/add "PI:NAME:<NAME>END_PI" 5) (school/add "PI:NAME:<NAME>END_PI" 1) (school/grade 5))))) (deftest get-students-in-a-non-existant-grade (is (= [] (school/grade db 1)))) (deftest sorted-school (is (= { 3 ["PI:NAME:<NAME>END_PI"] 4 ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"] 6 ["PI:NAME:<NAME>END_PI"] } (-> db (school/add "PI:NAME:<NAME>END_PI" 4) (school/add "PI:NAME:<NAME>END_PI" 6) (school/add "PI:NAME:<NAME>END_PI" 4) (school/add "PI:NAME:<NAME>END_PI" 3) (school/sorted))))) (deftest add-students-avoids-external-mutation (is (= {3 ["PI:NAME:<NAME>END_PI"] 7 ["PI:NAME:<NAME>END_PI"]} (-> db (assoc 2 ["PI:NAME:<NAME>END_PI"]) (school/add "CPI:NAME:<NAME>END_PI" 3) (assoc 4 ["PI:NAME:<NAME>END_PI"]) (school/add "PI:NAME:<NAME>END_PI" 7))))) (run-tests)
[ { "context": " :password (docker/connection-properties \"MYSQL_PASSWORD\")}\n ;when\n session (ta", "end": 1401, "score": 0.9750658869743347, "start": 1396, "tag": "PASSWORD", "value": "MYSQL" }, { "context": " :password (docker/connection-properties \"MYSQL_PASSWORD\")}\n ;when\n session (target/open", "end": 1410, "score": 0.8972662091255188, "start": 1402, "tag": "PASSWORD", "value": "PASSWORD" }, { "context": " :password (docker/connection-properties \"MYSQL_PASSWORD\")}\n session (target/open-session connect", "end": 2020, "score": 0.9688641428947449, "start": 2006, "tag": "PASSWORD", "value": "MYSQL_PASSWORD" }, { "context": " \"root\"\n :password \"root\"}\n session (target/open-session connecti", "end": 2550, "score": 0.9991594552993774, "start": 2546, "tag": "PASSWORD", "value": "root" }, { "context": " :password (docker/connection-properties \"MYSQL_PASSWORD\")}\n session (target/open-sessio", "end": 3178, "score": 0.8002917170524597, "start": 3173, "tag": "PASSWORD", "value": "MYSQL" }, { "context": " :password (docker/connection-properties \"MYSQL_PASSWORD\")}\n session (target/open-session connect", "end": 3187, "score": 0.5752069354057312, "start": 3179, "tag": "PASSWORD", "value": "PASSWORD" }, { "context": " \"root\"\n :password \"root\"}\n session (target/open-session connecti", "end": 3714, "score": 0.9992407560348511, "start": 3710, "tag": "PASSWORD", "value": "root" }, { "context": " \"root\"\n :password \"root\"}\n session (target/open-session connec", "end": 4370, "score": 0.9994288086891174, "start": 4366, "tag": "PASSWORD", "value": "root" }, { "context": " \"root\"\n :password \"root\"}\n session (target/open-session connec", "end": 5258, "score": 0.9993287324905396, "start": 5254, "tag": "PASSWORD", "value": "root" } ]
test/com/chicoalmeida/mysqlx_clj/core_test.clj
chicoalmeida/mysqlx-clj
4
(ns com.chicoalmeida.mysqlx-clj.core-test (:require [clojure.test :refer :all] [clojure.string :refer [split]] [bond.james :as bond :refer [with-spy]] [com.chicoalmeida.mysqlx-clj.core :as target] [com.chicoalmeida.mysqlx-clj.config.docker-lifecycle :as docker]) (:import (clojure.lang ExceptionInfo) (java.util UUID))) (def container (atom nil)) (defn random-string [] (first (shuffle (split (.toString (UUID/randomUUID)) #"-")))) (use-fixtures :once (fn [f] (if (= (System/getenv "RUNNING_LOCAL") "true") (do (println "you must have docker-compose up and running when this flag is enabled") (f)) (do (reset! container (docker/initialize)) (f) (docker/destroy @container))))) (deftest connection-validations (testing "given valid credentials should start a valid session" (let [;given connection-props {:host (docker/host-address @container) :port (docker/host-port @container) :dbname (docker/connection-properties "MYSQL_DATABASE") :user (docker/connection-properties "MYSQL_USER") :password (docker/connection-properties "MYSQL_PASSWORD")} ;when session (target/open-session connection-props)] ;then (is (= true (target/open? session))))) (testing "given open session ensure it gets closed" (let [;given connection-props {:host (docker/host-address @container) :port (docker/host-port @container) :dbname (docker/connection-properties "MYSQL_DATABASE") :user (docker/connection-properties "MYSQL_USER") :password (docker/connection-properties "MYSQL_PASSWORD")} session (target/open-session connection-props) ;when _ (target/close-session session)] ;then (is (= false (target/open? session)))))) (deftest schema-validations (testing "given a valid session create schema should succeed" (let [;given connection-props {:host (docker/host-address @container) :port (docker/host-port @container) :user "root" :password "root"} session (target/open-session connection-props) schema-name-fxt (random-string) ;when result (target/create-schema session schema-name-fxt)] (is (= (.getName result) schema-name-fxt)))) (testing "attempt to create schema without permission must fail" (let [;given connection-props {:host (docker/host-address @container) :port (docker/host-port @container) :user (docker/connection-properties "MYSQL_USER") :password (docker/connection-properties "MYSQL_PASSWORD")} session (target/open-session connection-props) schema-name-fxt (random-string)] (is (thrown-with-msg? ExceptionInfo #"Access denied for user" (target/create-schema session schema-name-fxt))))) (testing "attempt to create duplicated schema must fail" (let [;given connection-props {:host (docker/host-address @container) :port (docker/host-port @container) :user "root" :password "root"} session (target/open-session connection-props) schema-name-fxt (random-string) _ (target/create-schema session schema-name-fxt)] (is (thrown-with-msg? ExceptionInfo #"^.*database exists*$" (target/create-schema session schema-name-fxt))))) (testing "given a valid schema name to drop should succeed" (with-spy [target/get-schema-names target/drop-schema] (let [;given connection-props {:host (docker/host-address @container) :port (docker/host-port @container) :user "root" :password "root"} session (target/open-session connection-props) schema-name-fxt (random-string) _ (target/create-schema session schema-name-fxt)] ;when (target/drop-schema session schema-name-fxt) ;then (is (= 1 (-> target/get-schema-names bond/calls count))) (is (= 1 (-> target/drop-schema bond/calls count))) (is (not (contains? (target/get-schema-names session) schema-name-fxt)))))) (testing "given a schema that doesn't exists should not call drop" (with-spy [target/get-schema-names target/drop-schema] (let [;given connection-props {:host (docker/host-address @container) :port (docker/host-port @container) :user "root" :password "root"} session (target/open-session connection-props)] ;when (target/drop-schema session (random-string)) ;then (is (= 1 (-> target/get-schema-names bond/calls count))) (is (= 1 (-> target/drop-schema bond/calls count)))))))
81786
(ns com.chicoalmeida.mysqlx-clj.core-test (:require [clojure.test :refer :all] [clojure.string :refer [split]] [bond.james :as bond :refer [with-spy]] [com.chicoalmeida.mysqlx-clj.core :as target] [com.chicoalmeida.mysqlx-clj.config.docker-lifecycle :as docker]) (:import (clojure.lang ExceptionInfo) (java.util UUID))) (def container (atom nil)) (defn random-string [] (first (shuffle (split (.toString (UUID/randomUUID)) #"-")))) (use-fixtures :once (fn [f] (if (= (System/getenv "RUNNING_LOCAL") "true") (do (println "you must have docker-compose up and running when this flag is enabled") (f)) (do (reset! container (docker/initialize)) (f) (docker/destroy @container))))) (deftest connection-validations (testing "given valid credentials should start a valid session" (let [;given connection-props {:host (docker/host-address @container) :port (docker/host-port @container) :dbname (docker/connection-properties "MYSQL_DATABASE") :user (docker/connection-properties "MYSQL_USER") :password (docker/connection-properties "<PASSWORD>_<PASSWORD>")} ;when session (target/open-session connection-props)] ;then (is (= true (target/open? session))))) (testing "given open session ensure it gets closed" (let [;given connection-props {:host (docker/host-address @container) :port (docker/host-port @container) :dbname (docker/connection-properties "MYSQL_DATABASE") :user (docker/connection-properties "MYSQL_USER") :password (docker/connection-properties "<PASSWORD>")} session (target/open-session connection-props) ;when _ (target/close-session session)] ;then (is (= false (target/open? session)))))) (deftest schema-validations (testing "given a valid session create schema should succeed" (let [;given connection-props {:host (docker/host-address @container) :port (docker/host-port @container) :user "root" :password "<PASSWORD>"} session (target/open-session connection-props) schema-name-fxt (random-string) ;when result (target/create-schema session schema-name-fxt)] (is (= (.getName result) schema-name-fxt)))) (testing "attempt to create schema without permission must fail" (let [;given connection-props {:host (docker/host-address @container) :port (docker/host-port @container) :user (docker/connection-properties "MYSQL_USER") :password (docker/connection-properties "<PASSWORD>_<PASSWORD>")} session (target/open-session connection-props) schema-name-fxt (random-string)] (is (thrown-with-msg? ExceptionInfo #"Access denied for user" (target/create-schema session schema-name-fxt))))) (testing "attempt to create duplicated schema must fail" (let [;given connection-props {:host (docker/host-address @container) :port (docker/host-port @container) :user "root" :password "<PASSWORD>"} session (target/open-session connection-props) schema-name-fxt (random-string) _ (target/create-schema session schema-name-fxt)] (is (thrown-with-msg? ExceptionInfo #"^.*database exists*$" (target/create-schema session schema-name-fxt))))) (testing "given a valid schema name to drop should succeed" (with-spy [target/get-schema-names target/drop-schema] (let [;given connection-props {:host (docker/host-address @container) :port (docker/host-port @container) :user "root" :password "<PASSWORD>"} session (target/open-session connection-props) schema-name-fxt (random-string) _ (target/create-schema session schema-name-fxt)] ;when (target/drop-schema session schema-name-fxt) ;then (is (= 1 (-> target/get-schema-names bond/calls count))) (is (= 1 (-> target/drop-schema bond/calls count))) (is (not (contains? (target/get-schema-names session) schema-name-fxt)))))) (testing "given a schema that doesn't exists should not call drop" (with-spy [target/get-schema-names target/drop-schema] (let [;given connection-props {:host (docker/host-address @container) :port (docker/host-port @container) :user "root" :password "<PASSWORD>"} session (target/open-session connection-props)] ;when (target/drop-schema session (random-string)) ;then (is (= 1 (-> target/get-schema-names bond/calls count))) (is (= 1 (-> target/drop-schema bond/calls count)))))))
true
(ns com.chicoalmeida.mysqlx-clj.core-test (:require [clojure.test :refer :all] [clojure.string :refer [split]] [bond.james :as bond :refer [with-spy]] [com.chicoalmeida.mysqlx-clj.core :as target] [com.chicoalmeida.mysqlx-clj.config.docker-lifecycle :as docker]) (:import (clojure.lang ExceptionInfo) (java.util UUID))) (def container (atom nil)) (defn random-string [] (first (shuffle (split (.toString (UUID/randomUUID)) #"-")))) (use-fixtures :once (fn [f] (if (= (System/getenv "RUNNING_LOCAL") "true") (do (println "you must have docker-compose up and running when this flag is enabled") (f)) (do (reset! container (docker/initialize)) (f) (docker/destroy @container))))) (deftest connection-validations (testing "given valid credentials should start a valid session" (let [;given connection-props {:host (docker/host-address @container) :port (docker/host-port @container) :dbname (docker/connection-properties "MYSQL_DATABASE") :user (docker/connection-properties "MYSQL_USER") :password (docker/connection-properties "PI:PASSWORD:<PASSWORD>END_PI_PI:PASSWORD:<PASSWORD>END_PI")} ;when session (target/open-session connection-props)] ;then (is (= true (target/open? session))))) (testing "given open session ensure it gets closed" (let [;given connection-props {:host (docker/host-address @container) :port (docker/host-port @container) :dbname (docker/connection-properties "MYSQL_DATABASE") :user (docker/connection-properties "MYSQL_USER") :password (docker/connection-properties "PI:PASSWORD:<PASSWORD>END_PI")} session (target/open-session connection-props) ;when _ (target/close-session session)] ;then (is (= false (target/open? session)))))) (deftest schema-validations (testing "given a valid session create schema should succeed" (let [;given connection-props {:host (docker/host-address @container) :port (docker/host-port @container) :user "root" :password "PI:PASSWORD:<PASSWORD>END_PI"} session (target/open-session connection-props) schema-name-fxt (random-string) ;when result (target/create-schema session schema-name-fxt)] (is (= (.getName result) schema-name-fxt)))) (testing "attempt to create schema without permission must fail" (let [;given connection-props {:host (docker/host-address @container) :port (docker/host-port @container) :user (docker/connection-properties "MYSQL_USER") :password (docker/connection-properties "PI:PASSWORD:<PASSWORD>END_PI_PI:PASSWORD:<PASSWORD>END_PI")} session (target/open-session connection-props) schema-name-fxt (random-string)] (is (thrown-with-msg? ExceptionInfo #"Access denied for user" (target/create-schema session schema-name-fxt))))) (testing "attempt to create duplicated schema must fail" (let [;given connection-props {:host (docker/host-address @container) :port (docker/host-port @container) :user "root" :password "PI:PASSWORD:<PASSWORD>END_PI"} session (target/open-session connection-props) schema-name-fxt (random-string) _ (target/create-schema session schema-name-fxt)] (is (thrown-with-msg? ExceptionInfo #"^.*database exists*$" (target/create-schema session schema-name-fxt))))) (testing "given a valid schema name to drop should succeed" (with-spy [target/get-schema-names target/drop-schema] (let [;given connection-props {:host (docker/host-address @container) :port (docker/host-port @container) :user "root" :password "PI:PASSWORD:<PASSWORD>END_PI"} session (target/open-session connection-props) schema-name-fxt (random-string) _ (target/create-schema session schema-name-fxt)] ;when (target/drop-schema session schema-name-fxt) ;then (is (= 1 (-> target/get-schema-names bond/calls count))) (is (= 1 (-> target/drop-schema bond/calls count))) (is (not (contains? (target/get-schema-names session) schema-name-fxt)))))) (testing "given a schema that doesn't exists should not call drop" (with-spy [target/get-schema-names target/drop-schema] (let [;given connection-props {:host (docker/host-address @container) :port (docker/host-port @container) :user "root" :password "PI:PASSWORD:<PASSWORD>END_PI"} session (target/open-session connection-props)] ;when (target/drop-schema session (random-string)) ;then (is (= 1 (-> target/get-schema-names bond/calls count))) (is (= 1 (-> target/drop-schema bond/calls count)))))))
[ { "context": " ^{:doc \"DICE-like generic model.\"\n :author \"Anna Shchiptsova\"}\n dice-simulator.compute.generic-structure\n (:r", "end": 547, "score": 0.9998790621757507, "start": 531, "tag": "NAME", "value": "Anna Shchiptsova" } ]
src/dice_simulator/compute/generic_structure.clj
shchipts/dice-simulator
0
; Copyright (c) 2021 International Institute for Applied Systems Analysis. ; All rights reserved. The use and distribution terms for this software ; are covered by the MIT License (http://opensource.org/licenses/MIT) ; which can be found in the file LICENSE at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns ^{:doc "DICE-like generic model." :author "Anna Shchiptsova"} dice-simulator.compute.generic-structure (:require [clojure.math.numeric-tower :as math])) (defn output "Output gross of abatement cost and climate damage." [{{labor :labor tfp :tfp a :capital-elasticity} :cobb-douglas} capital-stock_t t] (* (nth tfp t) (math/expt (nth labor t) (- 1 a)) (math/expt capital-stock_t a))) (defn capital-stock "The law of motion of the capital stock." [{d :depreciation-rate h :time-step} capital-stock investment] (+ (* (math/expt (- 1 d) h) capital-stock) (* h investment))) (defn investment "The total amount of final goods in the closed economy must be either consumed or invested." [{{labor :labor} :cobb-douglas} gdp_t consumption-per-capita_t t] (- gdp_t (* consumption-per-capita_t (nth labor t)))) (defn emissions "Industrial CO2 emissions from the produced output after abatement." [{s :carbon-intensity :as model-instance} rate_t capital-stock_t t] (* (nth s t) (- 1 rate_t) (output model-instance capital-stock_t t)))
45486
; Copyright (c) 2021 International Institute for Applied Systems Analysis. ; All rights reserved. The use and distribution terms for this software ; are covered by the MIT License (http://opensource.org/licenses/MIT) ; which can be found in the file LICENSE at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns ^{:doc "DICE-like generic model." :author "<NAME>"} dice-simulator.compute.generic-structure (:require [clojure.math.numeric-tower :as math])) (defn output "Output gross of abatement cost and climate damage." [{{labor :labor tfp :tfp a :capital-elasticity} :cobb-douglas} capital-stock_t t] (* (nth tfp t) (math/expt (nth labor t) (- 1 a)) (math/expt capital-stock_t a))) (defn capital-stock "The law of motion of the capital stock." [{d :depreciation-rate h :time-step} capital-stock investment] (+ (* (math/expt (- 1 d) h) capital-stock) (* h investment))) (defn investment "The total amount of final goods in the closed economy must be either consumed or invested." [{{labor :labor} :cobb-douglas} gdp_t consumption-per-capita_t t] (- gdp_t (* consumption-per-capita_t (nth labor t)))) (defn emissions "Industrial CO2 emissions from the produced output after abatement." [{s :carbon-intensity :as model-instance} rate_t capital-stock_t t] (* (nth s t) (- 1 rate_t) (output model-instance capital-stock_t t)))
true
; Copyright (c) 2021 International Institute for Applied Systems Analysis. ; All rights reserved. The use and distribution terms for this software ; are covered by the MIT License (http://opensource.org/licenses/MIT) ; which can be found in the file LICENSE at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns ^{:doc "DICE-like generic model." :author "PI:NAME:<NAME>END_PI"} dice-simulator.compute.generic-structure (:require [clojure.math.numeric-tower :as math])) (defn output "Output gross of abatement cost and climate damage." [{{labor :labor tfp :tfp a :capital-elasticity} :cobb-douglas} capital-stock_t t] (* (nth tfp t) (math/expt (nth labor t) (- 1 a)) (math/expt capital-stock_t a))) (defn capital-stock "The law of motion of the capital stock." [{d :depreciation-rate h :time-step} capital-stock investment] (+ (* (math/expt (- 1 d) h) capital-stock) (* h investment))) (defn investment "The total amount of final goods in the closed economy must be either consumed or invested." [{{labor :labor} :cobb-douglas} gdp_t consumption-per-capita_t t] (- gdp_t (* consumption-per-capita_t (nth labor t)))) (defn emissions "Industrial CO2 emissions from the produced output after abatement." [{s :carbon-intensity :as model-instance} rate_t capital-stock_t t] (* (nth s t) (- 1 rate_t) (output model-instance capital-stock_t t)))
[ { "context": "(ns ^{:author \"Leeor Engel\"}\n chapter-3.chapter-3-q4-test\n (:require [cloj", "end": 26, "score": 0.9998853802680969, "start": 15, "tag": "NAME", "value": "Leeor Engel" } ]
Clojure/test/chapter_3/chapter_3_q4_test.clj
Kiandr/crackingcodinginterview
0
(ns ^{:author "Leeor Engel"} chapter-3.chapter-3-q4-test (:require [clojure.test :refer :all] [data-structures.persistent-stack :refer :all] [chapter-3.chapter-3-q4 :refer :all])) (deftest my-queue-test (testing "all pushes, then pops" (let [q (create-my-queue 1)] (is (not (queue-empty? q))) (let [q2 (enqueue q 2) q3 (enqueue q2 3)] (is (= 3 (queue-size q3))) (is (= 1 (queue-peek q3))) (is (= (->MyQueue (create-stack) (create-stack '(2 3))) (dequeue q3))) (is (= (->MyQueue (create-stack) (create-stack '(3))) (dequeue (dequeue q3)))) (is (queue-empty? (dequeue (dequeue (dequeue q3)))))))) (testing "irregular pushes/pops" (let [q (create-my-queue 1) q2 (enqueue q 2) q3 (enqueue q2 3) q4 (enqueue q3 4) q5 (dequeue q4) q6 (enqueue q5 5) q7 (enqueue q6 6) q8 (enqueue q7 7) q9 (dequeue q8) q10 (enqueue q9 8) q11 (enqueue q10 9) q12 (enqueue q11 10) q13 (dequeue q12) q14 (dequeue q13) q15 (dequeue q14)] (is (= (->MyQueue (create-stack '()) (create-stack '(2 3 4))) q5)) (is (= (->MyQueue (create-stack '(7 6 5)) (create-stack '(2 3 4))) q8)) (is (= (->MyQueue (create-stack '(7 6 5)) (create-stack '(3 4))) q9)) (is (= (->MyQueue (create-stack '(10 9 8 7 6 5)) (create-stack '(3 4))) q12)) (is (= (->MyQueue (create-stack '()) (create-stack '(6 7 8 9 10))) q15)))))
60372
(ns ^{:author "<NAME>"} chapter-3.chapter-3-q4-test (:require [clojure.test :refer :all] [data-structures.persistent-stack :refer :all] [chapter-3.chapter-3-q4 :refer :all])) (deftest my-queue-test (testing "all pushes, then pops" (let [q (create-my-queue 1)] (is (not (queue-empty? q))) (let [q2 (enqueue q 2) q3 (enqueue q2 3)] (is (= 3 (queue-size q3))) (is (= 1 (queue-peek q3))) (is (= (->MyQueue (create-stack) (create-stack '(2 3))) (dequeue q3))) (is (= (->MyQueue (create-stack) (create-stack '(3))) (dequeue (dequeue q3)))) (is (queue-empty? (dequeue (dequeue (dequeue q3)))))))) (testing "irregular pushes/pops" (let [q (create-my-queue 1) q2 (enqueue q 2) q3 (enqueue q2 3) q4 (enqueue q3 4) q5 (dequeue q4) q6 (enqueue q5 5) q7 (enqueue q6 6) q8 (enqueue q7 7) q9 (dequeue q8) q10 (enqueue q9 8) q11 (enqueue q10 9) q12 (enqueue q11 10) q13 (dequeue q12) q14 (dequeue q13) q15 (dequeue q14)] (is (= (->MyQueue (create-stack '()) (create-stack '(2 3 4))) q5)) (is (= (->MyQueue (create-stack '(7 6 5)) (create-stack '(2 3 4))) q8)) (is (= (->MyQueue (create-stack '(7 6 5)) (create-stack '(3 4))) q9)) (is (= (->MyQueue (create-stack '(10 9 8 7 6 5)) (create-stack '(3 4))) q12)) (is (= (->MyQueue (create-stack '()) (create-stack '(6 7 8 9 10))) q15)))))
true
(ns ^{:author "PI:NAME:<NAME>END_PI"} chapter-3.chapter-3-q4-test (:require [clojure.test :refer :all] [data-structures.persistent-stack :refer :all] [chapter-3.chapter-3-q4 :refer :all])) (deftest my-queue-test (testing "all pushes, then pops" (let [q (create-my-queue 1)] (is (not (queue-empty? q))) (let [q2 (enqueue q 2) q3 (enqueue q2 3)] (is (= 3 (queue-size q3))) (is (= 1 (queue-peek q3))) (is (= (->MyQueue (create-stack) (create-stack '(2 3))) (dequeue q3))) (is (= (->MyQueue (create-stack) (create-stack '(3))) (dequeue (dequeue q3)))) (is (queue-empty? (dequeue (dequeue (dequeue q3)))))))) (testing "irregular pushes/pops" (let [q (create-my-queue 1) q2 (enqueue q 2) q3 (enqueue q2 3) q4 (enqueue q3 4) q5 (dequeue q4) q6 (enqueue q5 5) q7 (enqueue q6 6) q8 (enqueue q7 7) q9 (dequeue q8) q10 (enqueue q9 8) q11 (enqueue q10 9) q12 (enqueue q11 10) q13 (dequeue q12) q14 (dequeue q13) q15 (dequeue q14)] (is (= (->MyQueue (create-stack '()) (create-stack '(2 3 4))) q5)) (is (= (->MyQueue (create-stack '(7 6 5)) (create-stack '(2 3 4))) q8)) (is (= (->MyQueue (create-stack '(7 6 5)) (create-stack '(3 4))) q9)) (is (= (->MyQueue (create-stack '(10 9 8 7 6 5)) (create-stack '(3 4))) q12)) (is (= (->MyQueue (create-stack '()) (create-stack '(6 7 8 9 10))) q15)))))
[ { "context": ";; Copyright 2020, Di Sera Luca\n;; Contacts: disera.luca@gmail.com\n;; ", "end": 31, "score": 0.9998758435249329, "start": 19, "tag": "NAME", "value": "Di Sera Luca" }, { "context": " Copyright 2020, Di Sera Luca\n;; Contacts: disera.luca@gmail.com\n;; https://github.com/diseraluc", "end": 74, "score": 0.9999315738677979, "start": 53, "tag": "EMAIL", "value": "disera.luca@gmail.com" }, { "context": "gmail.com\n;; https://github.com/diseraluca\n;; https://www.linkedin.com/in/", "end": 125, "score": 0.9997035264968872, "start": 115, "tag": "USERNAME", "value": "diseraluca" }, { "context": "\n;; https://www.linkedin.com/in/luca-di-sera-200023167\n;;\n;; This code is licensed under the MIT License", "end": 197, "score": 0.9995365142822266, "start": 175, "tag": "USERNAME", "value": "luca-di-sera-200023167" } ]
pmal/test/pmal/backend/packages/packagemanagers/dpkg_test.clj
diseraluca/pmal
0
;; Copyright 2020, Di Sera Luca ;; Contacts: disera.luca@gmail.com ;; https://github.com/diseraluca ;; https://www.linkedin.com/in/luca-di-sera-200023167 ;; ;; This code is licensed under the MIT License. ;; More information can be found in the LICENSE file in the root of this repository (ns pmal.backend.packages.packagemanagers.dpkg-test (:require [clojure.test :refer :all] [clojure.string :refer [split-lines join]] [pmal.backend.packages.packagemanagers.dpkg :refer :all] [pmal.backend.packages.types :refer [PackageManager]]) (:import (pmal.backend.packages.packagemanagers.dpkg dpkg))) (def package-details "testpackage\nA Package that is used for testing\nThis is the description of this package.") ;; TODO: Remember to add tests for query-details as soon as the behavior regarding error checking is laid out. ;; TODO: Remember to add tests to show the form of the details string as soon as the format is more complete. (deftest test-parse-details (let [parsed (parse-details package-details)] (is (map? parsed) "Given a correctly formed details string, parse-details returns a mapped structure.") (testing "The mapped structure returned by parse-details provides information about the described package." (is (contains? parsed :name) "The mapped structure contains the 'name' key.") (is (= (first (split-lines package-details)) (:name parsed)) "The 'name' key contains the content of the first line of the details string.") (is (contains? parsed :description) "The mapped structure contains the 'description' key.") (is (= (join "\n" (rest (split-lines package-details))) (:description parsed)) "The 'description' key contains the newline-separated concatenation of the lines in the details string excluding the first.")))) (deftest test-dpkg (is (satisfies? PackageManager (dpkg.)) "The dpkg type satisfies the PackageManager protocol.")) (deftest test-package-manager (is (instance? dpkg package-manager) "package-manager returns an instance of the dpkg PackageManager."))
29555
;; Copyright 2020, <NAME> ;; Contacts: <EMAIL> ;; https://github.com/diseraluca ;; https://www.linkedin.com/in/luca-di-sera-200023167 ;; ;; This code is licensed under the MIT License. ;; More information can be found in the LICENSE file in the root of this repository (ns pmal.backend.packages.packagemanagers.dpkg-test (:require [clojure.test :refer :all] [clojure.string :refer [split-lines join]] [pmal.backend.packages.packagemanagers.dpkg :refer :all] [pmal.backend.packages.types :refer [PackageManager]]) (:import (pmal.backend.packages.packagemanagers.dpkg dpkg))) (def package-details "testpackage\nA Package that is used for testing\nThis is the description of this package.") ;; TODO: Remember to add tests for query-details as soon as the behavior regarding error checking is laid out. ;; TODO: Remember to add tests to show the form of the details string as soon as the format is more complete. (deftest test-parse-details (let [parsed (parse-details package-details)] (is (map? parsed) "Given a correctly formed details string, parse-details returns a mapped structure.") (testing "The mapped structure returned by parse-details provides information about the described package." (is (contains? parsed :name) "The mapped structure contains the 'name' key.") (is (= (first (split-lines package-details)) (:name parsed)) "The 'name' key contains the content of the first line of the details string.") (is (contains? parsed :description) "The mapped structure contains the 'description' key.") (is (= (join "\n" (rest (split-lines package-details))) (:description parsed)) "The 'description' key contains the newline-separated concatenation of the lines in the details string excluding the first.")))) (deftest test-dpkg (is (satisfies? PackageManager (dpkg.)) "The dpkg type satisfies the PackageManager protocol.")) (deftest test-package-manager (is (instance? dpkg package-manager) "package-manager returns an instance of the dpkg PackageManager."))
true
;; Copyright 2020, PI:NAME:<NAME>END_PI ;; Contacts: PI:EMAIL:<EMAIL>END_PI ;; https://github.com/diseraluca ;; https://www.linkedin.com/in/luca-di-sera-200023167 ;; ;; This code is licensed under the MIT License. ;; More information can be found in the LICENSE file in the root of this repository (ns pmal.backend.packages.packagemanagers.dpkg-test (:require [clojure.test :refer :all] [clojure.string :refer [split-lines join]] [pmal.backend.packages.packagemanagers.dpkg :refer :all] [pmal.backend.packages.types :refer [PackageManager]]) (:import (pmal.backend.packages.packagemanagers.dpkg dpkg))) (def package-details "testpackage\nA Package that is used for testing\nThis is the description of this package.") ;; TODO: Remember to add tests for query-details as soon as the behavior regarding error checking is laid out. ;; TODO: Remember to add tests to show the form of the details string as soon as the format is more complete. (deftest test-parse-details (let [parsed (parse-details package-details)] (is (map? parsed) "Given a correctly formed details string, parse-details returns a mapped structure.") (testing "The mapped structure returned by parse-details provides information about the described package." (is (contains? parsed :name) "The mapped structure contains the 'name' key.") (is (= (first (split-lines package-details)) (:name parsed)) "The 'name' key contains the content of the first line of the details string.") (is (contains? parsed :description) "The mapped structure contains the 'description' key.") (is (= (join "\n" (rest (split-lines package-details))) (:description parsed)) "The 'description' key contains the newline-separated concatenation of the lines in the details string excluding the first.")))) (deftest test-dpkg (is (satisfies? PackageManager (dpkg.)) "The dpkg type satisfies the PackageManager protocol.")) (deftest test-package-manager (is (instance? dpkg package-manager) "package-manager returns an instance of the dpkg PackageManager."))
[ { "context": ":as ifs]))\n\n(ifs/defroom ::study\n \"The Study\"\n \"Max's study, where he spends all his free time.\"\n {:", "end": 90, "score": 0.9899559020996094, "start": 87, "tag": "NAME", "value": "Max" } ]
src/if/house.clj
m-r-hunt/improved-fortnight
0
(ns if.house (:require [if.systems :as ifs])) (ifs/defroom ::study "The Study" "Max's study, where he spends all his free time." {:east ["door" ::hallway] :north ["window" ::outside]}) (ifs/defobject ::computer "Computer" "Max's gaming PC. It's a bit noisy when first switched on." ::study) (ifs/defobject ::bass "Bass Guitar" "A creamy orange Fender Jazz Bass." ::study) (ifs/defobject ::breastplate "Breast Plate" "A breast plate from a suit of medival armour. On closer inspection it's made of foam." ::boiler-cupboard) (ifs/defroom ::hallway "Ground Floor Hallway" "A small hallway." {:north ["arch" ::kitchen] :south ["arch" ::living-room]}) (ifs/defroom ::living-room "The Living Room" "The main living room." {:north ["arch" ::hallway] :south ["front door" ::outside]}) (ifs/defobject ::key "The Front Door Key" "The key to the front door." ::living-room) (ifs/defflag ::front-door-locked true) (ifs/defscript [:use ::key ::front-door] [true (ifs/set-flag state ::front-door-locked false) "You unlock the door."]) (ifs/defscript [:go ::living-room :south] (if (ifs/flag? state ::front-door-locked) [false state "You can't go out because the door is locked."] [true state "You go out the unlocked door."]))
34039
(ns if.house (:require [if.systems :as ifs])) (ifs/defroom ::study "The Study" "<NAME>'s study, where he spends all his free time." {:east ["door" ::hallway] :north ["window" ::outside]}) (ifs/defobject ::computer "Computer" "Max's gaming PC. It's a bit noisy when first switched on." ::study) (ifs/defobject ::bass "Bass Guitar" "A creamy orange Fender Jazz Bass." ::study) (ifs/defobject ::breastplate "Breast Plate" "A breast plate from a suit of medival armour. On closer inspection it's made of foam." ::boiler-cupboard) (ifs/defroom ::hallway "Ground Floor Hallway" "A small hallway." {:north ["arch" ::kitchen] :south ["arch" ::living-room]}) (ifs/defroom ::living-room "The Living Room" "The main living room." {:north ["arch" ::hallway] :south ["front door" ::outside]}) (ifs/defobject ::key "The Front Door Key" "The key to the front door." ::living-room) (ifs/defflag ::front-door-locked true) (ifs/defscript [:use ::key ::front-door] [true (ifs/set-flag state ::front-door-locked false) "You unlock the door."]) (ifs/defscript [:go ::living-room :south] (if (ifs/flag? state ::front-door-locked) [false state "You can't go out because the door is locked."] [true state "You go out the unlocked door."]))
true
(ns if.house (:require [if.systems :as ifs])) (ifs/defroom ::study "The Study" "PI:NAME:<NAME>END_PI's study, where he spends all his free time." {:east ["door" ::hallway] :north ["window" ::outside]}) (ifs/defobject ::computer "Computer" "Max's gaming PC. It's a bit noisy when first switched on." ::study) (ifs/defobject ::bass "Bass Guitar" "A creamy orange Fender Jazz Bass." ::study) (ifs/defobject ::breastplate "Breast Plate" "A breast plate from a suit of medival armour. On closer inspection it's made of foam." ::boiler-cupboard) (ifs/defroom ::hallway "Ground Floor Hallway" "A small hallway." {:north ["arch" ::kitchen] :south ["arch" ::living-room]}) (ifs/defroom ::living-room "The Living Room" "The main living room." {:north ["arch" ::hallway] :south ["front door" ::outside]}) (ifs/defobject ::key "The Front Door Key" "The key to the front door." ::living-room) (ifs/defflag ::front-door-locked true) (ifs/defscript [:use ::key ::front-door] [true (ifs/set-flag state ::front-door-locked false) "You unlock the door."]) (ifs/defscript [:go ::living-room :south] (if (ifs/flag? state ::front-door-locked) [false state "You can't go out because the door is locked."] [true state "You go out the unlocked door."]))
[ { "context": " :as books]))\n\n(def ^:private authors [\n {:name \"Fernando Aramburu\" :books [\"Patria\"]}\n {:name \"Federico Moccia\" :b", "end": 218, "score": 0.9998723864555359, "start": 201, "tag": "NAME", "value": "Fernando Aramburu" }, { "context": "e authors [\n {:name \"Fernando Aramburu\" :books [\"Patria\"]}\n {:name \"Federico Moccia\" :books [\"Tres veces", "end": 235, "score": 0.9823203682899475, "start": 229, "tag": "NAME", "value": "Patria" }, { "context": " \"Fernando Aramburu\" :books [\"Patria\"]}\n {:name \"Federico Moccia\" :books [\"Tres veces tú\"]}\n {:name \"Dolores Redo", "end": 264, "score": 0.9998581409454346, "start": 249, "tag": "NAME", "value": "Federico Moccia" }, { "context": "erico Moccia\" :books [\"Tres veces tú\"]}\n {:name \"Dolores Redondo\" :books [\"Todo esto te daré\"]}\n {:name \"Carlos R", "end": 317, "score": 0.9998722076416016, "start": 302, "tag": "NAME", "value": "Dolores Redondo" }, { "context": " Redondo\" :books [\"Todo esto te daré\"]}\n {:name \"Carlos Ruiz Zafón\" :books [\"El Laberinto de los Espíritus\"]}\n {:na", "end": 376, "score": 0.9998682737350464, "start": 359, "tag": "NAME", "value": "Carlos Ruiz Zafón" }, { "context": "ooks [\"El Laberinto de los Espíritus\"]}\n {:name \"Luz Gabás\" :books [\"Como fuego en el hielo\"]}\n {:name \"Món", "end": 439, "score": 0.9998671412467957, "start": 430, "tag": "NAME", "value": "Luz Gabás" }, { "context": "bás\" :books [\"Como fuego en el hielo\"]}\n {:name \"Mónica Carrillo\" :books [\"El tiempo. Todo. Locura\"]}\n {:name \"La", "end": 501, "score": 0.9998550415039062, "start": 486, "tag": "NAME", "value": "Mónica Carrillo" }, { "context": "lo\" :books [\"El tiempo. Todo. Locura\"]}\n {:name \"Laura Norton\" :books [\"Ante todo, mucho karma\"]}\n {:name \"Lui", "end": 561, "score": 0.9998571276664734, "start": 549, "tag": "NAME", "value": "Laura Norton" }, { "context": "ton\" :books [\"Ante todo, mucho karma\"]}\n {:name \"Luis Landero Duran\" :books [\"La vida negociable\"]}\n {:name \"Marcos ", "end": 626, "score": 0.9998533129692078, "start": 608, "tag": "NAME", "value": "Luis Landero Duran" }, { "context": "o Duran\" :books [\"La vida negociable\"]}\n {:name \"Marcos Chicot\" :books [\"El asesinato de Sócrates\"]}\n {:name \"P", "end": 682, "score": 0.9998329877853394, "start": 669, "tag": "NAME", "value": "Marcos Chicot" }, { "context": "t\" :books [\"El asesinato de Sócrates\"]}\n {:name \"Paula Hawkins\" :books [\"La chica del tren\"]}])\n\n(defn- create-b", "end": 744, "score": 0.999849796295166, "start": 731, "tag": "NAME", "value": "Paula Hawkins" } ]
src/compojure_api_setup/migrations/bookstore.clj
jorgesuja/compojure-api-setup
2
(ns compojure-api-setup.migrations.bookstore (:require [compojure-api-setup.models.authors :as authors] [compojure-api-setup.models.books :as books])) (def ^:private authors [ {:name "Fernando Aramburu" :books ["Patria"]} {:name "Federico Moccia" :books ["Tres veces tú"]} {:name "Dolores Redondo" :books ["Todo esto te daré"]} {:name "Carlos Ruiz Zafón" :books ["El Laberinto de los Espíritus"]} {:name "Luz Gabás" :books ["Como fuego en el hielo"]} {:name "Mónica Carrillo" :books ["El tiempo. Todo. Locura"]} {:name "Laura Norton" :books ["Ante todo, mucho karma"]} {:name "Luis Landero Duran" :books ["La vida negociable"]} {:name "Marcos Chicot" :books ["El asesinato de Sócrates"]} {:name "Paula Hawkins" :books ["La chica del tren"]}]) (defn- create-books "Inserts books from vector of names and author id" [author-id book-names connection] (doseq [book-name book-names] (books/create connection {:name book-name :author-id author-id}))) (defn migrate-up "Populates authors and books tables with test data" [{connection :conn}] (doseq [author-data authors] (-> (authors/create connection author-data) :generated_key (create-books (:books author-data) connection)))) (defn migrate-down "Truncates authors and books (by cascading)" [{connection :conn}] (authors/truncate connection))
17775
(ns compojure-api-setup.migrations.bookstore (:require [compojure-api-setup.models.authors :as authors] [compojure-api-setup.models.books :as books])) (def ^:private authors [ {:name "<NAME>" :books ["<NAME>"]} {:name "<NAME>" :books ["Tres veces tú"]} {:name "<NAME>" :books ["Todo esto te daré"]} {:name "<NAME>" :books ["El Laberinto de los Espíritus"]} {:name "<NAME>" :books ["Como fuego en el hielo"]} {:name "<NAME>" :books ["El tiempo. Todo. Locura"]} {:name "<NAME>" :books ["Ante todo, mucho karma"]} {:name "<NAME>" :books ["La vida negociable"]} {:name "<NAME>" :books ["El asesinato de Sócrates"]} {:name "<NAME>" :books ["La chica del tren"]}]) (defn- create-books "Inserts books from vector of names and author id" [author-id book-names connection] (doseq [book-name book-names] (books/create connection {:name book-name :author-id author-id}))) (defn migrate-up "Populates authors and books tables with test data" [{connection :conn}] (doseq [author-data authors] (-> (authors/create connection author-data) :generated_key (create-books (:books author-data) connection)))) (defn migrate-down "Truncates authors and books (by cascading)" [{connection :conn}] (authors/truncate connection))
true
(ns compojure-api-setup.migrations.bookstore (:require [compojure-api-setup.models.authors :as authors] [compojure-api-setup.models.books :as books])) (def ^:private authors [ {:name "PI:NAME:<NAME>END_PI" :books ["PI:NAME:<NAME>END_PI"]} {:name "PI:NAME:<NAME>END_PI" :books ["Tres veces tú"]} {:name "PI:NAME:<NAME>END_PI" :books ["Todo esto te daré"]} {:name "PI:NAME:<NAME>END_PI" :books ["El Laberinto de los Espíritus"]} {:name "PI:NAME:<NAME>END_PI" :books ["Como fuego en el hielo"]} {:name "PI:NAME:<NAME>END_PI" :books ["El tiempo. Todo. Locura"]} {:name "PI:NAME:<NAME>END_PI" :books ["Ante todo, mucho karma"]} {:name "PI:NAME:<NAME>END_PI" :books ["La vida negociable"]} {:name "PI:NAME:<NAME>END_PI" :books ["El asesinato de Sócrates"]} {:name "PI:NAME:<NAME>END_PI" :books ["La chica del tren"]}]) (defn- create-books "Inserts books from vector of names and author id" [author-id book-names connection] (doseq [book-name book-names] (books/create connection {:name book-name :author-id author-id}))) (defn migrate-up "Populates authors and books tables with test data" [{connection :conn}] (doseq [author-data authors] (-> (authors/create connection author-data) :generated_key (create-books (:books author-data) connection)))) (defn migrate-down "Truncates authors and books (by cascading)" [{connection :conn}] (authors/truncate connection))
[ { "context": "; Copyright (c) 2021 Mikołaj Kuranowski\n; SPDX-License-Identifier: WTFPL\n(ns day2b\n (:re", "end": 39, "score": 0.9996575713157654, "start": 21, "tag": "NAME", "value": "Mikołaj Kuranowski" } ]
src/day02b.clj
MKuranowski/AdventOfCode2020
0
; Copyright (c) 2021 Mikołaj Kuranowski ; SPDX-License-Identifier: WTFPL (ns day2b (:require [core])) (defn either [a b] (and (or a b) (not (and a b)))) (defn is-valid? [line] (let [[_ i1-str i2-str letter-str password] (re-matches #"(\d+)-(\d+) (\w): (\w+)" line) i1 (dec (core/parse-int i1-str)) i2 (dec (core/parse-int i2-str)) letter (first letter-str)] (either (= letter (nth password i1)) (= letter (nth password i2))))) (defn -main [filename] (->> filename (core/lines-from-file) (map is-valid?) (filter true?) (count) prn))
46129
; Copyright (c) 2021 <NAME> ; SPDX-License-Identifier: WTFPL (ns day2b (:require [core])) (defn either [a b] (and (or a b) (not (and a b)))) (defn is-valid? [line] (let [[_ i1-str i2-str letter-str password] (re-matches #"(\d+)-(\d+) (\w): (\w+)" line) i1 (dec (core/parse-int i1-str)) i2 (dec (core/parse-int i2-str)) letter (first letter-str)] (either (= letter (nth password i1)) (= letter (nth password i2))))) (defn -main [filename] (->> filename (core/lines-from-file) (map is-valid?) (filter true?) (count) prn))
true
; Copyright (c) 2021 PI:NAME:<NAME>END_PI ; SPDX-License-Identifier: WTFPL (ns day2b (:require [core])) (defn either [a b] (and (or a b) (not (and a b)))) (defn is-valid? [line] (let [[_ i1-str i2-str letter-str password] (re-matches #"(\d+)-(\d+) (\w): (\w+)" line) i1 (dec (core/parse-int i1-str)) i2 (dec (core/parse-int i2-str)) letter (first letter-str)] (either (= letter (nth password i1)) (= letter (nth password i2))))) (defn -main [filename] (->> filename (core/lines-from-file) (map is-valid?) (filter true?) (count) prn))
[ { "context": "nd the community whose names includes the string \"Wallingford\"\n(pprint (q '[:find ?n .\n :where\n ", "end": 6120, "score": 0.9991900324821472, "start": 6109, "tag": "NAME", "value": "Wallingford" }, { "context": ":where\n [(fulltext $ :community/name \"Wallingford\") [[?e ?n]]]]\n (db conn)))\n\n;; find all", "end": 6220, "score": 0.9992339015007019, "start": 6209, "tag": "NAME", "value": "Wallingford" } ]
dotfiles/bin/datomic-pro-0.9.5394/samples/seattle/getting-started.clj
patbrown/dev
7
;; This file contains code examples for getting-started.html. They are ;; written in clojure, for use with Datomic's interactive repl. You can ;; start the repl by running 'bin/repl' from the datomic directory. ;; Once the repl is running, you can copy code into it or, if invoke it ;; directory from your editor, based on your configuration. (use '[datomic.api :only [q db] :as d]) (use 'clojure.pprint) ;; store database uri (def uri "datomic:mem://seattle") ;; create database (d/create-database uri) ;; connect to database (def conn (d/connect uri)) ;; parse schema edn file (def schema-tx (read-string (slurp "samples/seattle/seattle-schema.edn"))) ;; display first statement (first schema-tx) ;; submit schema transaction @(d/transact conn schema-tx) ;; parse seed data edn file (def data-tx (read-string (slurp "samples/seattle/seattle-data0.edn"))) ;; display first three statements in seed data transaction (first data-tx) (second data-tx) (nth data-tx 2) ;; submit seed data transaction @(d/transact conn data-tx) ;; find all communities, return entity ids (def results (q '[:find ?c :where [?c :community/name]] (db conn))) (count results) ;; get first entity id in results and make an entity map (def id (ffirst results)) (def entity (-> conn db (d/entity id))) ;; display the entity map's keys (keys entity) ;; display the value of the entity's community name (:community/name entity) ;; Use a pull expression to get entities' attributes and values. (def pull-results (q '[:find (pull ?c [*]) :where [?c :community/name]] (db conn))) (pprint (first pull-results)) ;; for each community, display its name (let [db (db conn)] (pprint (map #(:community/name (d/entity db (first %))) results))) ;; for each community, get its neighborhood and display ;; both names (let [db (db conn)] (pprint (map #(let [entity (d/entity db (first %))] [(:community/name entity) (-> entity :community/neighborhood :neighborhood/name)]) results))) ;; for the first community, get its neighborhood, then for ;; that neighborhood, get all its communities, and ;; print out their names (def community (d/entity (db conn) (ffirst results))) (def neighborhood (:community/neighborhood community)) (def communities (:community/_neighborhood neighborhood)) (pprint (map :community/name communities)) ;; find all communities and specify returning their names into a collection (def results (q '[:find [?n ...] :where [_ :community/name ?n]] (db conn))) (pprint results) ;; find all community names and pull their urls (pprint (seq (q '[:find ?n (pull ?c [:community/url]) :where [?c :community/name ?n]] (db conn)))) ;; find all categories for community named "belltown" (pprint (q '[:find [?c ...] :where [?e :community/name "belltown"] [?e :community/category ?c]] (db conn))) ;; find names of all communities that are twitter feeds (pprint (q '[:find [?n ...] :where [?c :community/name ?n] [?c :community/type :community.type/twitter]] (db conn))) ;; find names of all communities that are in the NE region (pprint (q '[:find [?c_name ...] :where [?c :community/name ?c_name] [?c :community/neighborhood ?n] [?n :neighborhood/district ?d] [?d :district/region :region/ne]] (db conn))) ;; find names and regions of all communities (pprint (seq (q '[:find ?c_name ?r_name :where [?c :community/name ?c_name] [?c :community/neighborhood ?n] [?n :neighborhood/district ?d] [?d :district/region ?r] [?r :db/ident ?r_name]] (db conn)))) ;; find all communities that are twitter feeds and facebook pages ;; using the same query and passing in type as a parameter (def query-by-type '[:find [?n ...] :in $ ?t :where [?c :community/name ?n] [?c :community/type ?t]]) (def query-by-type-with-pull '[:find (pull ?c [:community/name]) :in $ ?t :where [?c :community/type ?t]]) ;; using first query (pprint (q query-by-type (db conn) :community.type/twitter)) (pprint (q query-by-type (db conn) :community.type/facebook-page)) ;; using second query with pull (pprint (seq (q query-by-type-with-pull (db conn) :community.type/twitter))) (pprint (seq (q query-by-type-with-pull (db conn) :community.type/facebook-page))) ;; find all communities that are twitter feeds or facebook pages using ;; one query and a list of individual parameters (pprint (seq (q '[:find ?n ?t :in $ [?t ...] :where [?c :community/name ?n] [?c :community/type ?t]] (db conn) [:community.type/facebook-page :community.type/twitter]))) ;; find all communities that are non-commercial email-lists or commercial ;; web-sites using a list of tuple parameters (pprint (seq (q '[:find ?n ?t ?ot :in $ [[?t ?ot]] :where [?c :community/name ?n] [?c :community/type ?t] [?c :community/orgtype ?ot]] (db conn) [[:community.type/email-list :community.orgtype/community] [:community.type/website :community.orgtype/commercial]]))) ;; find all community names coming before "C" in alphabetical order (pprint (q '[:find [?n ...] :where [?c :community/name ?n] [(.compareTo ?n "C") ?res] [(< ?res 0)]] (db conn))) ;; find the community whose names includes the string "Wallingford" (pprint (q '[:find ?n . :where [(fulltext $ :community/name "Wallingford") [[?e ?n]]]] (db conn))) ;; find all communities that are websites and that are about ;; food, passing in type and search string as parameters (pprint (seq (q '[:find ?name ?cat :in $ ?type ?search :where [?c :community/name ?name] [?c :community/type ?type] [(fulltext $ :community/category ?search) [[?c ?cat]]]] (db conn) :community.type/website "food"))) ;; find all names of all communities that are twitter feeds, using rules (let [rules '[[[twitter ?c] [?c :community/type :community.type/twitter]]]] (pprint (q '[:find [?n ...] :in $ % :where [?c :community/name ?n] (twitter ?c)] (db conn) rules))) ;; find names of all communities in NE and SW regions, using rules ;; to avoid repeating logic (let [rules '[[[region ?c ?r] [?c :community/neighborhood ?n] [?n :neighborhood/district ?d] [?d :district/region ?re] [?re :db/ident ?r]]]] (pprint (q '[:find [?n ...] :in $ % :where [?c :community/name ?n] [region ?c :region/ne]] (db conn) rules)) (pprint (q '[:find [?n ...] :in $ % :where [?c :community/name ?n] [region ?c :region/sw]] (db conn) rules))) ;; find names of all communities that are in any of the northern ;; regions and are social-media, using rules for OR logic (let [rules '[[[region ?c ?r] [?c :community/neighborhood ?n] [?n :neighborhood/district ?d] [?d :district/region ?re] [?re :db/ident ?r]] [[social-media ?c] [?c :community/type :community.type/twitter]] [[social-media ?c] [?c :community/type :community.type/facebook-page]] [[northern ?c] (region ?c :region/ne)] [[northern ?c] (region ?c :region/n)] [[northern ?c] (region ?c :region/nw)] [[southern ?c] (region ?c :region/sw)] [[southern ?c] (region ?c :region/s)] [[southern ?c] (region ?c :region/se)]]] (pprint (q '[:find [?n ...] :in $ % :where [?c :community/name ?n] (southern ?c) (social-media ?c)] (db conn) rules))) ;; Find all transaction times, sort them in reverse order (def tx-instants (reverse (sort (q '[:find [?when ...] :where [_ :db/txInstant ?when]] (db conn))))) ;; pull out two most recent transactions, most recent loaded ;; seed data, second most recent loaded schema (def data-tx-date (first tx-instants)) (def schema-tx-date (second tx-instants)) ;; make query to find all communities (def communities-query '[:find [?c ...] :where [?c :community/name]]) ;; find all communities as of schema transaction (let [db-asof-schema (-> conn db (d/as-of schema-tx-date))] (println (count (q communities-query db-asof-schema)))) ;; find all communities as of seed data transaction (let [db-asof-data (-> conn db (d/as-of data-tx-date))] (println (count (q communities-query db-asof-data)))) ;; find all communities since schema transaction (let [db-since-data (-> conn db (d/since schema-tx-date))] (println (count (q communities-query db-since-data)))) ;; find all communities since seed data transaction (let [db-since-data (-> conn db (d/since data-tx-date))] (println (count (q communities-query db-since-data)))) ;; parse additional seed data file (def new-data-tx (read-string (slurp "samples/seattle/seattle-data1.edn"))) ;; find all communities if new data is loaded (let [db-if-new-data (-> conn db (d/with new-data-tx) :db-after)] (println (count (q communities-query db-if-new-data)))) ;; find all communities currently in database (println (count (q communities-query (db conn)))) ;; submit new data transaction @(d/transact conn new-data-tx) ;; find all communities currently in database (println (count (q communities-query (db conn)))) ;; find all communities since original seed data load transaction (let [db-since-data (-> conn db (d/since data-tx-date))] (println (count (q communities-query db-since-data)))) ;; make a new partition @(d/transact conn [{:db/id (d/tempid :db.part/db) :db/ident :communities :db.install/_partition :db.part/db}]) ;; make a new community @(d/transact conn [{:db/id (d/tempid :communities) :community/name "Easton"}]) ;; get id for a community, use to transact data (def belltown-id (q '[:find ?id . :where [?id :community/name "belltown"]] (db conn))) @(d/transact conn [{:db/id belltown-id :community/category "free stuff"}]) ;; retract data for a community @(d/transact conn [[:db/retract belltown-id :community/category "free stuff"]]) ;; retract a community entity (def easton-id (q '[:find ?id . :where [?id :community/name "Easton"]] (db conn))) @(d/transact conn [[:db.fn/retractEntity easton-id]]) ;; get transaction report queue, add new community again (def queue (d/tx-report-queue conn)) @(d/transact conn [{:db/id (d/tempid :communities) :community/name "Easton"}]) (when-let [report (.poll queue)] (pprint (seq (q '[:find ?e ?aname ?v ?added :in $ [[?e ?a ?v _ ?added]] :where [?e ?a ?v _ ?added] [?a :db/ident ?aname]] (:db-after report) (:tx-data report)))))
115063
;; This file contains code examples for getting-started.html. They are ;; written in clojure, for use with Datomic's interactive repl. You can ;; start the repl by running 'bin/repl' from the datomic directory. ;; Once the repl is running, you can copy code into it or, if invoke it ;; directory from your editor, based on your configuration. (use '[datomic.api :only [q db] :as d]) (use 'clojure.pprint) ;; store database uri (def uri "datomic:mem://seattle") ;; create database (d/create-database uri) ;; connect to database (def conn (d/connect uri)) ;; parse schema edn file (def schema-tx (read-string (slurp "samples/seattle/seattle-schema.edn"))) ;; display first statement (first schema-tx) ;; submit schema transaction @(d/transact conn schema-tx) ;; parse seed data edn file (def data-tx (read-string (slurp "samples/seattle/seattle-data0.edn"))) ;; display first three statements in seed data transaction (first data-tx) (second data-tx) (nth data-tx 2) ;; submit seed data transaction @(d/transact conn data-tx) ;; find all communities, return entity ids (def results (q '[:find ?c :where [?c :community/name]] (db conn))) (count results) ;; get first entity id in results and make an entity map (def id (ffirst results)) (def entity (-> conn db (d/entity id))) ;; display the entity map's keys (keys entity) ;; display the value of the entity's community name (:community/name entity) ;; Use a pull expression to get entities' attributes and values. (def pull-results (q '[:find (pull ?c [*]) :where [?c :community/name]] (db conn))) (pprint (first pull-results)) ;; for each community, display its name (let [db (db conn)] (pprint (map #(:community/name (d/entity db (first %))) results))) ;; for each community, get its neighborhood and display ;; both names (let [db (db conn)] (pprint (map #(let [entity (d/entity db (first %))] [(:community/name entity) (-> entity :community/neighborhood :neighborhood/name)]) results))) ;; for the first community, get its neighborhood, then for ;; that neighborhood, get all its communities, and ;; print out their names (def community (d/entity (db conn) (ffirst results))) (def neighborhood (:community/neighborhood community)) (def communities (:community/_neighborhood neighborhood)) (pprint (map :community/name communities)) ;; find all communities and specify returning their names into a collection (def results (q '[:find [?n ...] :where [_ :community/name ?n]] (db conn))) (pprint results) ;; find all community names and pull their urls (pprint (seq (q '[:find ?n (pull ?c [:community/url]) :where [?c :community/name ?n]] (db conn)))) ;; find all categories for community named "belltown" (pprint (q '[:find [?c ...] :where [?e :community/name "belltown"] [?e :community/category ?c]] (db conn))) ;; find names of all communities that are twitter feeds (pprint (q '[:find [?n ...] :where [?c :community/name ?n] [?c :community/type :community.type/twitter]] (db conn))) ;; find names of all communities that are in the NE region (pprint (q '[:find [?c_name ...] :where [?c :community/name ?c_name] [?c :community/neighborhood ?n] [?n :neighborhood/district ?d] [?d :district/region :region/ne]] (db conn))) ;; find names and regions of all communities (pprint (seq (q '[:find ?c_name ?r_name :where [?c :community/name ?c_name] [?c :community/neighborhood ?n] [?n :neighborhood/district ?d] [?d :district/region ?r] [?r :db/ident ?r_name]] (db conn)))) ;; find all communities that are twitter feeds and facebook pages ;; using the same query and passing in type as a parameter (def query-by-type '[:find [?n ...] :in $ ?t :where [?c :community/name ?n] [?c :community/type ?t]]) (def query-by-type-with-pull '[:find (pull ?c [:community/name]) :in $ ?t :where [?c :community/type ?t]]) ;; using first query (pprint (q query-by-type (db conn) :community.type/twitter)) (pprint (q query-by-type (db conn) :community.type/facebook-page)) ;; using second query with pull (pprint (seq (q query-by-type-with-pull (db conn) :community.type/twitter))) (pprint (seq (q query-by-type-with-pull (db conn) :community.type/facebook-page))) ;; find all communities that are twitter feeds or facebook pages using ;; one query and a list of individual parameters (pprint (seq (q '[:find ?n ?t :in $ [?t ...] :where [?c :community/name ?n] [?c :community/type ?t]] (db conn) [:community.type/facebook-page :community.type/twitter]))) ;; find all communities that are non-commercial email-lists or commercial ;; web-sites using a list of tuple parameters (pprint (seq (q '[:find ?n ?t ?ot :in $ [[?t ?ot]] :where [?c :community/name ?n] [?c :community/type ?t] [?c :community/orgtype ?ot]] (db conn) [[:community.type/email-list :community.orgtype/community] [:community.type/website :community.orgtype/commercial]]))) ;; find all community names coming before "C" in alphabetical order (pprint (q '[:find [?n ...] :where [?c :community/name ?n] [(.compareTo ?n "C") ?res] [(< ?res 0)]] (db conn))) ;; find the community whose names includes the string "<NAME>" (pprint (q '[:find ?n . :where [(fulltext $ :community/name "<NAME>") [[?e ?n]]]] (db conn))) ;; find all communities that are websites and that are about ;; food, passing in type and search string as parameters (pprint (seq (q '[:find ?name ?cat :in $ ?type ?search :where [?c :community/name ?name] [?c :community/type ?type] [(fulltext $ :community/category ?search) [[?c ?cat]]]] (db conn) :community.type/website "food"))) ;; find all names of all communities that are twitter feeds, using rules (let [rules '[[[twitter ?c] [?c :community/type :community.type/twitter]]]] (pprint (q '[:find [?n ...] :in $ % :where [?c :community/name ?n] (twitter ?c)] (db conn) rules))) ;; find names of all communities in NE and SW regions, using rules ;; to avoid repeating logic (let [rules '[[[region ?c ?r] [?c :community/neighborhood ?n] [?n :neighborhood/district ?d] [?d :district/region ?re] [?re :db/ident ?r]]]] (pprint (q '[:find [?n ...] :in $ % :where [?c :community/name ?n] [region ?c :region/ne]] (db conn) rules)) (pprint (q '[:find [?n ...] :in $ % :where [?c :community/name ?n] [region ?c :region/sw]] (db conn) rules))) ;; find names of all communities that are in any of the northern ;; regions and are social-media, using rules for OR logic (let [rules '[[[region ?c ?r] [?c :community/neighborhood ?n] [?n :neighborhood/district ?d] [?d :district/region ?re] [?re :db/ident ?r]] [[social-media ?c] [?c :community/type :community.type/twitter]] [[social-media ?c] [?c :community/type :community.type/facebook-page]] [[northern ?c] (region ?c :region/ne)] [[northern ?c] (region ?c :region/n)] [[northern ?c] (region ?c :region/nw)] [[southern ?c] (region ?c :region/sw)] [[southern ?c] (region ?c :region/s)] [[southern ?c] (region ?c :region/se)]]] (pprint (q '[:find [?n ...] :in $ % :where [?c :community/name ?n] (southern ?c) (social-media ?c)] (db conn) rules))) ;; Find all transaction times, sort them in reverse order (def tx-instants (reverse (sort (q '[:find [?when ...] :where [_ :db/txInstant ?when]] (db conn))))) ;; pull out two most recent transactions, most recent loaded ;; seed data, second most recent loaded schema (def data-tx-date (first tx-instants)) (def schema-tx-date (second tx-instants)) ;; make query to find all communities (def communities-query '[:find [?c ...] :where [?c :community/name]]) ;; find all communities as of schema transaction (let [db-asof-schema (-> conn db (d/as-of schema-tx-date))] (println (count (q communities-query db-asof-schema)))) ;; find all communities as of seed data transaction (let [db-asof-data (-> conn db (d/as-of data-tx-date))] (println (count (q communities-query db-asof-data)))) ;; find all communities since schema transaction (let [db-since-data (-> conn db (d/since schema-tx-date))] (println (count (q communities-query db-since-data)))) ;; find all communities since seed data transaction (let [db-since-data (-> conn db (d/since data-tx-date))] (println (count (q communities-query db-since-data)))) ;; parse additional seed data file (def new-data-tx (read-string (slurp "samples/seattle/seattle-data1.edn"))) ;; find all communities if new data is loaded (let [db-if-new-data (-> conn db (d/with new-data-tx) :db-after)] (println (count (q communities-query db-if-new-data)))) ;; find all communities currently in database (println (count (q communities-query (db conn)))) ;; submit new data transaction @(d/transact conn new-data-tx) ;; find all communities currently in database (println (count (q communities-query (db conn)))) ;; find all communities since original seed data load transaction (let [db-since-data (-> conn db (d/since data-tx-date))] (println (count (q communities-query db-since-data)))) ;; make a new partition @(d/transact conn [{:db/id (d/tempid :db.part/db) :db/ident :communities :db.install/_partition :db.part/db}]) ;; make a new community @(d/transact conn [{:db/id (d/tempid :communities) :community/name "Easton"}]) ;; get id for a community, use to transact data (def belltown-id (q '[:find ?id . :where [?id :community/name "belltown"]] (db conn))) @(d/transact conn [{:db/id belltown-id :community/category "free stuff"}]) ;; retract data for a community @(d/transact conn [[:db/retract belltown-id :community/category "free stuff"]]) ;; retract a community entity (def easton-id (q '[:find ?id . :where [?id :community/name "Easton"]] (db conn))) @(d/transact conn [[:db.fn/retractEntity easton-id]]) ;; get transaction report queue, add new community again (def queue (d/tx-report-queue conn)) @(d/transact conn [{:db/id (d/tempid :communities) :community/name "Easton"}]) (when-let [report (.poll queue)] (pprint (seq (q '[:find ?e ?aname ?v ?added :in $ [[?e ?a ?v _ ?added]] :where [?e ?a ?v _ ?added] [?a :db/ident ?aname]] (:db-after report) (:tx-data report)))))
true
;; This file contains code examples for getting-started.html. They are ;; written in clojure, for use with Datomic's interactive repl. You can ;; start the repl by running 'bin/repl' from the datomic directory. ;; Once the repl is running, you can copy code into it or, if invoke it ;; directory from your editor, based on your configuration. (use '[datomic.api :only [q db] :as d]) (use 'clojure.pprint) ;; store database uri (def uri "datomic:mem://seattle") ;; create database (d/create-database uri) ;; connect to database (def conn (d/connect uri)) ;; parse schema edn file (def schema-tx (read-string (slurp "samples/seattle/seattle-schema.edn"))) ;; display first statement (first schema-tx) ;; submit schema transaction @(d/transact conn schema-tx) ;; parse seed data edn file (def data-tx (read-string (slurp "samples/seattle/seattle-data0.edn"))) ;; display first three statements in seed data transaction (first data-tx) (second data-tx) (nth data-tx 2) ;; submit seed data transaction @(d/transact conn data-tx) ;; find all communities, return entity ids (def results (q '[:find ?c :where [?c :community/name]] (db conn))) (count results) ;; get first entity id in results and make an entity map (def id (ffirst results)) (def entity (-> conn db (d/entity id))) ;; display the entity map's keys (keys entity) ;; display the value of the entity's community name (:community/name entity) ;; Use a pull expression to get entities' attributes and values. (def pull-results (q '[:find (pull ?c [*]) :where [?c :community/name]] (db conn))) (pprint (first pull-results)) ;; for each community, display its name (let [db (db conn)] (pprint (map #(:community/name (d/entity db (first %))) results))) ;; for each community, get its neighborhood and display ;; both names (let [db (db conn)] (pprint (map #(let [entity (d/entity db (first %))] [(:community/name entity) (-> entity :community/neighborhood :neighborhood/name)]) results))) ;; for the first community, get its neighborhood, then for ;; that neighborhood, get all its communities, and ;; print out their names (def community (d/entity (db conn) (ffirst results))) (def neighborhood (:community/neighborhood community)) (def communities (:community/_neighborhood neighborhood)) (pprint (map :community/name communities)) ;; find all communities and specify returning their names into a collection (def results (q '[:find [?n ...] :where [_ :community/name ?n]] (db conn))) (pprint results) ;; find all community names and pull their urls (pprint (seq (q '[:find ?n (pull ?c [:community/url]) :where [?c :community/name ?n]] (db conn)))) ;; find all categories for community named "belltown" (pprint (q '[:find [?c ...] :where [?e :community/name "belltown"] [?e :community/category ?c]] (db conn))) ;; find names of all communities that are twitter feeds (pprint (q '[:find [?n ...] :where [?c :community/name ?n] [?c :community/type :community.type/twitter]] (db conn))) ;; find names of all communities that are in the NE region (pprint (q '[:find [?c_name ...] :where [?c :community/name ?c_name] [?c :community/neighborhood ?n] [?n :neighborhood/district ?d] [?d :district/region :region/ne]] (db conn))) ;; find names and regions of all communities (pprint (seq (q '[:find ?c_name ?r_name :where [?c :community/name ?c_name] [?c :community/neighborhood ?n] [?n :neighborhood/district ?d] [?d :district/region ?r] [?r :db/ident ?r_name]] (db conn)))) ;; find all communities that are twitter feeds and facebook pages ;; using the same query and passing in type as a parameter (def query-by-type '[:find [?n ...] :in $ ?t :where [?c :community/name ?n] [?c :community/type ?t]]) (def query-by-type-with-pull '[:find (pull ?c [:community/name]) :in $ ?t :where [?c :community/type ?t]]) ;; using first query (pprint (q query-by-type (db conn) :community.type/twitter)) (pprint (q query-by-type (db conn) :community.type/facebook-page)) ;; using second query with pull (pprint (seq (q query-by-type-with-pull (db conn) :community.type/twitter))) (pprint (seq (q query-by-type-with-pull (db conn) :community.type/facebook-page))) ;; find all communities that are twitter feeds or facebook pages using ;; one query and a list of individual parameters (pprint (seq (q '[:find ?n ?t :in $ [?t ...] :where [?c :community/name ?n] [?c :community/type ?t]] (db conn) [:community.type/facebook-page :community.type/twitter]))) ;; find all communities that are non-commercial email-lists or commercial ;; web-sites using a list of tuple parameters (pprint (seq (q '[:find ?n ?t ?ot :in $ [[?t ?ot]] :where [?c :community/name ?n] [?c :community/type ?t] [?c :community/orgtype ?ot]] (db conn) [[:community.type/email-list :community.orgtype/community] [:community.type/website :community.orgtype/commercial]]))) ;; find all community names coming before "C" in alphabetical order (pprint (q '[:find [?n ...] :where [?c :community/name ?n] [(.compareTo ?n "C") ?res] [(< ?res 0)]] (db conn))) ;; find the community whose names includes the string "PI:NAME:<NAME>END_PI" (pprint (q '[:find ?n . :where [(fulltext $ :community/name "PI:NAME:<NAME>END_PI") [[?e ?n]]]] (db conn))) ;; find all communities that are websites and that are about ;; food, passing in type and search string as parameters (pprint (seq (q '[:find ?name ?cat :in $ ?type ?search :where [?c :community/name ?name] [?c :community/type ?type] [(fulltext $ :community/category ?search) [[?c ?cat]]]] (db conn) :community.type/website "food"))) ;; find all names of all communities that are twitter feeds, using rules (let [rules '[[[twitter ?c] [?c :community/type :community.type/twitter]]]] (pprint (q '[:find [?n ...] :in $ % :where [?c :community/name ?n] (twitter ?c)] (db conn) rules))) ;; find names of all communities in NE and SW regions, using rules ;; to avoid repeating logic (let [rules '[[[region ?c ?r] [?c :community/neighborhood ?n] [?n :neighborhood/district ?d] [?d :district/region ?re] [?re :db/ident ?r]]]] (pprint (q '[:find [?n ...] :in $ % :where [?c :community/name ?n] [region ?c :region/ne]] (db conn) rules)) (pprint (q '[:find [?n ...] :in $ % :where [?c :community/name ?n] [region ?c :region/sw]] (db conn) rules))) ;; find names of all communities that are in any of the northern ;; regions and are social-media, using rules for OR logic (let [rules '[[[region ?c ?r] [?c :community/neighborhood ?n] [?n :neighborhood/district ?d] [?d :district/region ?re] [?re :db/ident ?r]] [[social-media ?c] [?c :community/type :community.type/twitter]] [[social-media ?c] [?c :community/type :community.type/facebook-page]] [[northern ?c] (region ?c :region/ne)] [[northern ?c] (region ?c :region/n)] [[northern ?c] (region ?c :region/nw)] [[southern ?c] (region ?c :region/sw)] [[southern ?c] (region ?c :region/s)] [[southern ?c] (region ?c :region/se)]]] (pprint (q '[:find [?n ...] :in $ % :where [?c :community/name ?n] (southern ?c) (social-media ?c)] (db conn) rules))) ;; Find all transaction times, sort them in reverse order (def tx-instants (reverse (sort (q '[:find [?when ...] :where [_ :db/txInstant ?when]] (db conn))))) ;; pull out two most recent transactions, most recent loaded ;; seed data, second most recent loaded schema (def data-tx-date (first tx-instants)) (def schema-tx-date (second tx-instants)) ;; make query to find all communities (def communities-query '[:find [?c ...] :where [?c :community/name]]) ;; find all communities as of schema transaction (let [db-asof-schema (-> conn db (d/as-of schema-tx-date))] (println (count (q communities-query db-asof-schema)))) ;; find all communities as of seed data transaction (let [db-asof-data (-> conn db (d/as-of data-tx-date))] (println (count (q communities-query db-asof-data)))) ;; find all communities since schema transaction (let [db-since-data (-> conn db (d/since schema-tx-date))] (println (count (q communities-query db-since-data)))) ;; find all communities since seed data transaction (let [db-since-data (-> conn db (d/since data-tx-date))] (println (count (q communities-query db-since-data)))) ;; parse additional seed data file (def new-data-tx (read-string (slurp "samples/seattle/seattle-data1.edn"))) ;; find all communities if new data is loaded (let [db-if-new-data (-> conn db (d/with new-data-tx) :db-after)] (println (count (q communities-query db-if-new-data)))) ;; find all communities currently in database (println (count (q communities-query (db conn)))) ;; submit new data transaction @(d/transact conn new-data-tx) ;; find all communities currently in database (println (count (q communities-query (db conn)))) ;; find all communities since original seed data load transaction (let [db-since-data (-> conn db (d/since data-tx-date))] (println (count (q communities-query db-since-data)))) ;; make a new partition @(d/transact conn [{:db/id (d/tempid :db.part/db) :db/ident :communities :db.install/_partition :db.part/db}]) ;; make a new community @(d/transact conn [{:db/id (d/tempid :communities) :community/name "Easton"}]) ;; get id for a community, use to transact data (def belltown-id (q '[:find ?id . :where [?id :community/name "belltown"]] (db conn))) @(d/transact conn [{:db/id belltown-id :community/category "free stuff"}]) ;; retract data for a community @(d/transact conn [[:db/retract belltown-id :community/category "free stuff"]]) ;; retract a community entity (def easton-id (q '[:find ?id . :where [?id :community/name "Easton"]] (db conn))) @(d/transact conn [[:db.fn/retractEntity easton-id]]) ;; get transaction report queue, add new community again (def queue (d/tx-report-queue conn)) @(d/transact conn [{:db/id (d/tempid :communities) :community/name "Easton"}]) (when-let [report (.poll queue)] (pprint (seq (q '[:find ?e ?aname ?v ?added :in $ [[?e ?a ?v _ ?added]] :where [?e ?a ?v _ ?added] [?a :db/ident ?aname]] (:db-after report) (:tx-data report)))))
[ { "context": "eaking-company}}\n {:k1 \"ipsum\" :k2 \"5abc\" :attrs {:type :breaking-company}}\n ", "end": 22965, "score": 0.7019852995872498, "start": 22962, "tag": "KEY", "value": "abc" } ]
test/edd/search_it.clj
raiffeisenbankinternational/edd-core
4
(ns edd.search-it (:require [clojure.test :refer :all] [clojure.tools.logging :as log] [lambda.util :as util] [edd.memory.view-store :as memory-view-store] [edd.elastic.view-store :as elastic-view-store] [edd.search :as search] [lambda.test.fixture.state :as state] [edd.search :as search] [lambda.elastic :as el] [lambda.uuid :as uuid] [clojure.string :as str])) (def ctx {:elastic-search {:url (util/get-env "IndexDomainEndpoint")} :meta {:realm :test} :aws {:region (util/get-env "AWS_DEFAULT_REGION") :aws-access-key-id (util/get-env "AWS_ACCESS_KEY_ID") :aws-secret-access-key (util/get-env "AWS_SECRET_ACCESS_KEY") :aws-session-token (util/get-env "AWS_SESSION_TOKEN")}}) (defn load-data [ctx] (doseq [i (:aggregate-store @state/*dal-state*)] (log/info (el/query (assoc ctx :method "POST" :path (str "/" (elastic-view-store/realm ctx) "_" (:service-name ctx) "/_doc") :body (util/to-json i)))))) (defn test-query [data q] (binding [state/*dal-state* (atom {:aggregate-store data})] (let [service-name (str/replace (str (uuid/gen)) "-" "_") local-ctx (assoc ctx :service-name service-name) body {:settings {:index {:number_of_shards 1 :number_of_replicas 0}} :mappings {:dynamic_templates [{:integers {:match_mapping_type "long", :mapping {:type "integer", :fields {:number {:type "long"}, :keyword {:type "keyword", :ignore_above 256}}}}}]}}] (log/info "Index name" service-name) (el/query (assoc local-ctx :method "PUT" :path (str "/" (elastic-view-store/realm ctx) "_" service-name) :body (util/to-json body))) (load-data local-ctx) (Thread/sleep 2000) (let [el-result (search/advanced-search (-> local-ctx (elastic-view-store/register) (assoc :query q))) mock-result (search/advanced-search (-> local-ctx (memory-view-store/register) (assoc :query q)))] (log/info el-result) (log/info mock-result) (el/query (assoc local-ctx :method "DELETE" :path (str "/" service-name))) [el-result mock-result])))) (deftest test-elastic-mock-parity-1 (let [data [{:k1 "121" :k2 "be" :k3 {:k31 "c"}} {:k1 "758" :k2 "be"} {:k1 "121" :k2 "be" :k3 {:k31 "d"}}] query {:filter [:and [:and [:eq :k1 "121"] [:eq :k2 "be"]] [:eq "k3.k31" "c"]]} expected {:total 1 :from 0 :size 50 :hits [{:k1 "121" :k2 "be" :k3 {:k31 "c"}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-2 (let [data [{:k1 "121" :k2 "be" :k3 {:k31 "c"}} {:k1 "758" :k2 "be"} {:k1 "751" :k2 "be"} {:k1 "751" :k2 "bb"} {:k1 "121" :k2 "be" :k3 {:k31 "d"}}] query {:filter [:and [:eq :k2 "be"] [:in :k1 ["751" "758"]]]} expected {:total 2 :from 0 :size 50 :hits [{:k1 "758" :k2 "be"} {:k1 "751" :k2 "be"}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-keyword-in-2 (let [data [{:k1 :v0 :k2 "be" :k3 {:k31 "c"}} {:k1 :v1 :k2 "bi"} {:k1 :v1 :k2 "be"} {:k1 :v2 :k2 "be"} {:k1 :v1 :k2 "bb"} {:k1 :v3 :k2 "be" :k3 {:k31 "d"}}] query {:filter [:and [:eq :k2 "be"] [:in :k1 [:v1 :v2]]]} expected {:total 2 :from 0 :size 50 :hits [{:k1 :v1 :k2 "be"} {:k1 :v2 :k2 "be"}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-3 (let [data [{:k1 "121" :k2 "be" :k3 {:k31 "c"}} {:k1 "758" :k2 "be"} {:k1 "751" :k2 "be"} {:k1 "751" :k2 "bb"} {:k1 "121" :k2 "be" :k3 {:k31 "d"}}] query {:filter [:and [:eq :k2 "be"] [:not [:in :k1 ["751" "758"]]]]} expected {:total 2 :from 0 :size 50 :hits [{:k1 "121" :k2 "be" :k3 {:k31 "c"}} {:k1 "121" :k2 "be" :k3 {:k31 "d"}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-4 (let [data [{:k1 "121" :attrs {:type :booking-company}} {:k1 "122" :attrs {:type :breaking-company}} {:k1 "123" :attrs {:type :booking-company}}] query {:filter [:not [:eq "attrs.type" :booking-company]]} expected {:total 1 :from 0 :size 50 :hits [{:k1 "122" :attrs {:type :breaking-company}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-test-search-1 (let [data [{:k1 "consectetur" :attrs {:type :booking-company}} {:k1 "lorem" :k2 "1adc" :attrs {:type :breaking-company}} {:k1 "ipsum" :k2 "2abc" :attrs {:type :breaking-company}} {:k1 "dolor" :k2 "3abc" :attrs {:type :breaking-company}} {:k1 "lem" :k2 "4adcor" :attrs {:type :breaking-company}} {:k1 "ipsum" :k2 "5abc" :attrs {:type :breaking-company}} {:k1 "dol" :k2 "6abc" :attrs {:type :breaking-company}} {:k1 "amet" :k2 "7abc" :attrs {:type :booking-company}}] query {:search [:fields [:k1 :k2] :value "or"] :filter [:not [:eq "attrs.type" :booking-company]]} expected {:total 3 :from 0 :size 50 :hits [{:k1 "lorem" :k2 "1adc" :attrs {:type :breaking-company}} {:k1 "dolor" :k2 "3abc" :attrs {:type :breaking-company}} {:k1 "lem" :k2 "4adcor" :attrs {:type :breaking-company}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-test-search-only-1 (let [data [{:k1 "consectetur" :attrs {:type :booking-company}} {:k1 "lorem" :k2 "1adc" :attrs {:type :breaking-company}} {:k1 "ipsum" :k2 "2abc" :attrs {:type :breaking-company}} {:k1 "dolor" :k2 "3abc" :attrs {:type :breaking-company}} {:k1 "lem" :k2 "4adcor" :attrs {:type :breaking-company}} {:k1 "ipsum" :k2 "5abc" :attrs {:type :breaking-company}} {:k1 "dol" :k2 "6abc" :attrs {:type :breaking-company}} {:k1 "amet" :k2 "7aor" :attrs {:type :booking-company}}] query {:search [:fields [:k1 :k2] :value "or"]} expected {:total 4 :from 0 :size 50 :hits [{:k1 "lorem" :k2 "1adc" :attrs {:type :breaking-company}} {:k1 "dolor" :k2 "3abc" :attrs {:type :breaking-company}} {:k1 "lem" :k2 "4adcor" :attrs {:type :breaking-company}} {:k1 "amet" :k2 "7aor" :attrs {:type :booking-company}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-test-search-only-2 (let [data [{:k1 "consectetur" :attrs {:type :booking-company}} {:k1 "lorem" :k2 "1adc" :attrs {:type :breaking-company}} {:k1 "ipsum" :k2 "2abc" :attrs {:type :breaking-company}} {:k1 "dolor" :k2 "3abc" :attrs {:type :breaking-company}} {:k1 "lem" :k2 "4adcor" :attrs {:type :breaking-company}} {:k1 "ipsum" :k2 "5abc" :attrs {:type :breaking-company}} {:k1 "dol" :k2 "6abc" :attrs {:type :breaking-company}} {:k1 "amet" :k2 "7aor" :attrs {:type :booking-company}} {:k1 "ame5" :k2 "7aor" :attrs {:type :booking-company}}] query {:search [:fields [:k1 :k2] :value "or"] :from 2 :size 2} expected {:total 5 :from 2 :size 2 :hits [{:k1 "lem" :k2 "4adcor" :attrs {:type :breaking-company}} {:k1 "amet" :k2 "7aor" :attrs {:type :booking-company}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-test-search-only-3 (let [data [{:attrs {:top-parent-id #uuid "1111a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}} {:attrs {:top-parent-id #uuid "3333a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "4444a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}} {:attrs {:top-parent-id #uuid "5555a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}} {:attrs {:top-parent-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "8888a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}}] query {:filter [:or [:eq :attrs.top-parent-id #uuid "1111a4b3-1c40-48ec-b6c9-b9cceeea6bb8"] [:eq :attrs.top-gcc-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8"]]} expected {:total 2 :from 0 :size 50 :hits [{:attrs {:top-parent-id #uuid "1111a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}} {:attrs {:top-parent-id #uuid "5555a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-test-search-4 (let [data [{:k1 "consectetur" :attrs {:type :booking-company}} {:k1 "lorem" :k2 "1adc" :attrs {:type :breaking-company}} {:k1 "ipsum" :k2 "2abc" :attrs {:type :breaking-company}} {:k1 "dolor" :k2 "3abc" :attrs {:type :breaking-company}} {:k1 "lem" :k2 "4adcor" :attrs {:type :breaking-company}} {:k1 "ipsum" :k2 "5abc" :attrs {:type :breaking-company}} {:k1 "dol" :k2 "6abc" :attrs {:type :breaking-company}} {:k1 "amet" :k2 "7abc" :attrs {:type :booking-company}}] query {:search [:fields [:k1 :k2] :value "or"] :filter [:not [:eq "attrs.type" :booking-company]]} expected {:total 3 :from 0 :size 50 :hits [{:k1 "lorem" :k2 "1adc" :attrs {:type :breaking-company}} {:k1 "dolor" :k2 "3abc" :attrs {:type :breaking-company}} {:k1 "lem" :k2 "4adcor" :attrs {:type :breaking-company}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-select-filter-2 (let [data [{:k1 "121" :k2 {:k21 "a" :k22 "1"}} {:k1 "758" :k2 {:k21 "c" :k22 "2"}} {:k1 "751" :k2 {:k21 "c" :k22 "2"}} {:k1 "751" :k2 {:k21 "d" :k22 "2"}} {:k1 "121" :k2 {:k21 "e" :k22 "3"}}] query {:select ["k1" "k2.k21"] :size 50 :filter [:eq "k2.k22" "2"]} expected {:total 3 :from 0 :size 50 :hits [{:k1 "758" :k2 {:k21 "c"}} {:k1 "751" :k2 {:k21 "c"}} {:k1 "751" :k2 {:k21 "d"}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-select-filter-keywords (let [data [{:k1 "121" :k2 {:k21 "a" :k22 "1"}} {:k1 "758" :k2 {:k21 "c" :k22 "2"}} {:k1 "751" :k2 {:k21 "c" :k22 "2"}} {:k1 "751" :k2 {:k21 "d" :k22 "2"}} {:k1 "121" :k2 {:k21 "e" :k22 "3"}}] query {:select [:k1 :k2.k21] :size 50 :filter [:eq "k2.k22" "2"]} expected {:total 3 :from 0 :size 50 :hits [{:k1 "758" :k2 {:k21 "c"}} {:k1 "751" :k2 {:k21 "c"}} {:k1 "751" :k2 {:k21 "d"}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-sort-asc (let [data [{:k1 "121" :k2 {:k21 "a" :k22 "1"}} {:k1 "758" :k2 {:k21 "c" :k22 "2"}} {:k1 "752" :k2 {:k21 "d" :k22 "2"}} {:k1 "751" :k2 {:k21 "c" :k22 "2"}} {:k1 "121" :k2 {:k21 "e" :k22 "3"}}] query {:select [:k1 :k2.k21] :size 50 :filter [:eq "k2.k22" "2"] :sort [:k1 "asc"]} expected {:total 3 :from 0 :size 50 :hits [{:k1 "751" :k2 {:k21 "c"}} {:k1 "752" :k2 {:k21 "d"}} {:k1 "758" :k2 {:k21 "c"}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-sort-desc (let [data [{:k1 "121" :k2 {:k21 "a" :k22 "1"}} {:k1 "758" :k2 {:k21 "c" :k22 "2"}} {:k1 "752" :k2 {:k21 "d" :k22 "2"}} {:k1 "751" :k2 {:k21 "c" :k22 "2"}} {:k1 "121" :k2 {:k21 "e" :k22 "3"}}] query {:select [:k1 :k2.k21] :size 50 :filter [:eq "k2.k22" "2"] :sort [:k1 "desc"]} expected {:total 3 :from 0 :size 50 :hits [{:k1 "758" :k2 {:k21 "c"}} {:k1 "752" :k2 {:k21 "d"}} {:k1 "751" :k2 {:k21 "c"}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-sort-desc-1 (let [data [{:k1 "121" :k2 {:k21 "a" :k22 "1"}} {:k1 "758" :k2 {:k21 "1" :k22 "2"}} {:k1 "758" :k2 {:k21 "2" :k22 "2"}} {:k1 "250" :k2 {:k21 "3" :k22 "2"}} {:k1 "121" :k2 {:k21 "4" :k22 "2"}}] query {:select [:k1 :k2.k21] :size 50 :filter [:eq "k2.k22" "2"] :sort [:k1 "desc" :k2.k21 "asc"]} expected {:total 4 :from 0 :size 50 :hits [{:k1 "758" :k2 {:k21 "1"}} {:k1 "758" :k2 {:k21 "2"}} {:k1 "250" :k2 {:k21 "3"}} {:k1 "121" :k2 {:k21 "4"}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-sort-desc-2 (let [data [{:k1 "121" :k2 {:k21 "a" :k22 "1"}} {:k1 "758" :k2 {:k21 "1" :k22 "2"}} {:k1 "758" :k2 {:k21 "2" :k22 "2"}} {:k1 "250" :k2 {:k21 "3" :k22 "2"}} {:k1 "121" :k2 {:k21 "4" :k22 "2"}}] query {:select [:k1 :k2.k21] :size 50 :filter [:eq "k2.k22" "2"] :sort [:k1 "desc" :k2.k21 "desc"]} expected {:total 4 :from 0 :size 50 :hits [{:k1 "758" :k2 {:k21 "2"}} {:k1 "758" :k2 {:k21 "1"}} {:k1 "250" :k2 {:k21 "3"}} {:k1 "121" :k2 {:k21 "4"}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-sort-asc-1 (let [data [{:k1 "121" :k2 {:k21 "a" :k22 "1"}} {:k1 "758" :k2 {:k21 "1" :k22 "2"}} {:k1 "758" :k2 {:k21 "2" :k22 "2"}} {:k1 "250" :k2 {:k21 "3" :k22 "2"}} {:k1 "121" :k2 {:k21 "4" :k22 "2"}}] query {:select [:k1 :k2.k21] :size 50 :filter [:eq "k2.k22" "2"] :sort [:k1 "asc" :k2.k21 "desc"]} expected {:total 4 :from 0 :size 50 :hits [{:k1 "121" :k2 {:k21 "4"}} {:k1 "250" :k2 {:k21 "3"}} {:k1 "758" :k2 {:k21 "2"}} {:k1 "758" :k2 {:k21 "1"}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-sort-asc-2 (let [data [{:k1 1} {:k1 20} {:k1 3} {:k1 400} {:k1 5}] query {:size 50 :sort [:k1 "asc-number"]} expected {:total 5 :from 0 :size 50 :hits [{:k1 1} {:k1 3} {:k1 5} {:k1 20} {:k1 400}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-sort-desc-2 (let [data [{:k1 1} {:k1 20} {:k1 3} {:k1 400} {:k1 5}] query {:size 50 :sort [:k1 :desc-number]} expected {:total 5 :from 0 :size 50 :hits [{:k1 400} {:k1 20} {:k1 5} {:k1 3} {:k1 1}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-test-exists-field-1 (let [data [{:attrs {:top-parent-id #uuid "1111a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}} {:attrs {:top-parent-id #uuid "3333a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "4444a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}} {:attrs {:top-parent-id #uuid "5555a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}} {:attrs {:top-parent-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "8888a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}}] query {:filter [:exists :attrs.top-parent-id]} expected {:total 4 :from 0 :size 50 :hits data} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-test-exists-field-2 (let [data [{:attrs {:top-parent-id #uuid "1111a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}} {:attrs {:top-parent-id #uuid "3333a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "4444a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}} {:attrs {:top-parent-id #uuid "5555a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}} {:attrs {:top-parent-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "8888a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}}] query {:filter [:not [:exists :attrs.top-parent-id]]} expected {:total 0 :from 0 :size 50 :hits []} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-test-order-of-exact-match (let [data [{:k1 "120" :attrs {:type :booking-company}} {:k1 "10" :k2 "1adc" :attrs {:type :breaking-company}} {:k1 "100" :k2 "10" :attrs {:type :breaking-company}} {:k1 "1011" :k2 "1011" :attrs {:type :breaking-company}} {:k1 "lem" :k2 "4adcor" :attrs {:type :breaking-company}} {:k1 "ipsum" :k2 "5abc" :attrs {:type :breaking-company}} {:k1 "dol" :k2 "6abc" :attrs {:type :breaking-company}} {:k1 "10" :k2 "zeko" :attrs {:type :breaking-company}} {:k1 "amet" :k2 "7abc" :attrs {:type :booking-company}}] query {:search [:fields [:k1 :k2] :value "10"]} expected {:from 0 :hits [{:attrs {:type :breaking-company} :k1 "100" :k2 "10"} {:attrs {:type :breaking-company} :k1 "10" :k2 "1adc"} {:attrs {:type :breaking-company} :k1 "10" :k2 "zeko"} {:attrs {:type :breaking-company} :k1 "1011" :k2 "1011"}] :size 50 :total 4} [el-result mock-result] (test-query data query)] (is (= expected el-result))))
6726
(ns edd.search-it (:require [clojure.test :refer :all] [clojure.tools.logging :as log] [lambda.util :as util] [edd.memory.view-store :as memory-view-store] [edd.elastic.view-store :as elastic-view-store] [edd.search :as search] [lambda.test.fixture.state :as state] [edd.search :as search] [lambda.elastic :as el] [lambda.uuid :as uuid] [clojure.string :as str])) (def ctx {:elastic-search {:url (util/get-env "IndexDomainEndpoint")} :meta {:realm :test} :aws {:region (util/get-env "AWS_DEFAULT_REGION") :aws-access-key-id (util/get-env "AWS_ACCESS_KEY_ID") :aws-secret-access-key (util/get-env "AWS_SECRET_ACCESS_KEY") :aws-session-token (util/get-env "AWS_SESSION_TOKEN")}}) (defn load-data [ctx] (doseq [i (:aggregate-store @state/*dal-state*)] (log/info (el/query (assoc ctx :method "POST" :path (str "/" (elastic-view-store/realm ctx) "_" (:service-name ctx) "/_doc") :body (util/to-json i)))))) (defn test-query [data q] (binding [state/*dal-state* (atom {:aggregate-store data})] (let [service-name (str/replace (str (uuid/gen)) "-" "_") local-ctx (assoc ctx :service-name service-name) body {:settings {:index {:number_of_shards 1 :number_of_replicas 0}} :mappings {:dynamic_templates [{:integers {:match_mapping_type "long", :mapping {:type "integer", :fields {:number {:type "long"}, :keyword {:type "keyword", :ignore_above 256}}}}}]}}] (log/info "Index name" service-name) (el/query (assoc local-ctx :method "PUT" :path (str "/" (elastic-view-store/realm ctx) "_" service-name) :body (util/to-json body))) (load-data local-ctx) (Thread/sleep 2000) (let [el-result (search/advanced-search (-> local-ctx (elastic-view-store/register) (assoc :query q))) mock-result (search/advanced-search (-> local-ctx (memory-view-store/register) (assoc :query q)))] (log/info el-result) (log/info mock-result) (el/query (assoc local-ctx :method "DELETE" :path (str "/" service-name))) [el-result mock-result])))) (deftest test-elastic-mock-parity-1 (let [data [{:k1 "121" :k2 "be" :k3 {:k31 "c"}} {:k1 "758" :k2 "be"} {:k1 "121" :k2 "be" :k3 {:k31 "d"}}] query {:filter [:and [:and [:eq :k1 "121"] [:eq :k2 "be"]] [:eq "k3.k31" "c"]]} expected {:total 1 :from 0 :size 50 :hits [{:k1 "121" :k2 "be" :k3 {:k31 "c"}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-2 (let [data [{:k1 "121" :k2 "be" :k3 {:k31 "c"}} {:k1 "758" :k2 "be"} {:k1 "751" :k2 "be"} {:k1 "751" :k2 "bb"} {:k1 "121" :k2 "be" :k3 {:k31 "d"}}] query {:filter [:and [:eq :k2 "be"] [:in :k1 ["751" "758"]]]} expected {:total 2 :from 0 :size 50 :hits [{:k1 "758" :k2 "be"} {:k1 "751" :k2 "be"}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-keyword-in-2 (let [data [{:k1 :v0 :k2 "be" :k3 {:k31 "c"}} {:k1 :v1 :k2 "bi"} {:k1 :v1 :k2 "be"} {:k1 :v2 :k2 "be"} {:k1 :v1 :k2 "bb"} {:k1 :v3 :k2 "be" :k3 {:k31 "d"}}] query {:filter [:and [:eq :k2 "be"] [:in :k1 [:v1 :v2]]]} expected {:total 2 :from 0 :size 50 :hits [{:k1 :v1 :k2 "be"} {:k1 :v2 :k2 "be"}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-3 (let [data [{:k1 "121" :k2 "be" :k3 {:k31 "c"}} {:k1 "758" :k2 "be"} {:k1 "751" :k2 "be"} {:k1 "751" :k2 "bb"} {:k1 "121" :k2 "be" :k3 {:k31 "d"}}] query {:filter [:and [:eq :k2 "be"] [:not [:in :k1 ["751" "758"]]]]} expected {:total 2 :from 0 :size 50 :hits [{:k1 "121" :k2 "be" :k3 {:k31 "c"}} {:k1 "121" :k2 "be" :k3 {:k31 "d"}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-4 (let [data [{:k1 "121" :attrs {:type :booking-company}} {:k1 "122" :attrs {:type :breaking-company}} {:k1 "123" :attrs {:type :booking-company}}] query {:filter [:not [:eq "attrs.type" :booking-company]]} expected {:total 1 :from 0 :size 50 :hits [{:k1 "122" :attrs {:type :breaking-company}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-test-search-1 (let [data [{:k1 "consectetur" :attrs {:type :booking-company}} {:k1 "lorem" :k2 "1adc" :attrs {:type :breaking-company}} {:k1 "ipsum" :k2 "2abc" :attrs {:type :breaking-company}} {:k1 "dolor" :k2 "3abc" :attrs {:type :breaking-company}} {:k1 "lem" :k2 "4adcor" :attrs {:type :breaking-company}} {:k1 "ipsum" :k2 "5abc" :attrs {:type :breaking-company}} {:k1 "dol" :k2 "6abc" :attrs {:type :breaking-company}} {:k1 "amet" :k2 "7abc" :attrs {:type :booking-company}}] query {:search [:fields [:k1 :k2] :value "or"] :filter [:not [:eq "attrs.type" :booking-company]]} expected {:total 3 :from 0 :size 50 :hits [{:k1 "lorem" :k2 "1adc" :attrs {:type :breaking-company}} {:k1 "dolor" :k2 "3abc" :attrs {:type :breaking-company}} {:k1 "lem" :k2 "4adcor" :attrs {:type :breaking-company}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-test-search-only-1 (let [data [{:k1 "consectetur" :attrs {:type :booking-company}} {:k1 "lorem" :k2 "1adc" :attrs {:type :breaking-company}} {:k1 "ipsum" :k2 "2abc" :attrs {:type :breaking-company}} {:k1 "dolor" :k2 "3abc" :attrs {:type :breaking-company}} {:k1 "lem" :k2 "4adcor" :attrs {:type :breaking-company}} {:k1 "ipsum" :k2 "5abc" :attrs {:type :breaking-company}} {:k1 "dol" :k2 "6abc" :attrs {:type :breaking-company}} {:k1 "amet" :k2 "7aor" :attrs {:type :booking-company}}] query {:search [:fields [:k1 :k2] :value "or"]} expected {:total 4 :from 0 :size 50 :hits [{:k1 "lorem" :k2 "1adc" :attrs {:type :breaking-company}} {:k1 "dolor" :k2 "3abc" :attrs {:type :breaking-company}} {:k1 "lem" :k2 "4adcor" :attrs {:type :breaking-company}} {:k1 "amet" :k2 "7aor" :attrs {:type :booking-company}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-test-search-only-2 (let [data [{:k1 "consectetur" :attrs {:type :booking-company}} {:k1 "lorem" :k2 "1adc" :attrs {:type :breaking-company}} {:k1 "ipsum" :k2 "2abc" :attrs {:type :breaking-company}} {:k1 "dolor" :k2 "3abc" :attrs {:type :breaking-company}} {:k1 "lem" :k2 "4adcor" :attrs {:type :breaking-company}} {:k1 "ipsum" :k2 "5abc" :attrs {:type :breaking-company}} {:k1 "dol" :k2 "6abc" :attrs {:type :breaking-company}} {:k1 "amet" :k2 "7aor" :attrs {:type :booking-company}} {:k1 "ame5" :k2 "7aor" :attrs {:type :booking-company}}] query {:search [:fields [:k1 :k2] :value "or"] :from 2 :size 2} expected {:total 5 :from 2 :size 2 :hits [{:k1 "lem" :k2 "4adcor" :attrs {:type :breaking-company}} {:k1 "amet" :k2 "7aor" :attrs {:type :booking-company}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-test-search-only-3 (let [data [{:attrs {:top-parent-id #uuid "1111a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}} {:attrs {:top-parent-id #uuid "3333a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "4444a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}} {:attrs {:top-parent-id #uuid "5555a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}} {:attrs {:top-parent-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "8888a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}}] query {:filter [:or [:eq :attrs.top-parent-id #uuid "1111a4b3-1c40-48ec-b6c9-b9cceeea6bb8"] [:eq :attrs.top-gcc-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8"]]} expected {:total 2 :from 0 :size 50 :hits [{:attrs {:top-parent-id #uuid "1111a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}} {:attrs {:top-parent-id #uuid "5555a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-test-search-4 (let [data [{:k1 "consectetur" :attrs {:type :booking-company}} {:k1 "lorem" :k2 "1adc" :attrs {:type :breaking-company}} {:k1 "ipsum" :k2 "2abc" :attrs {:type :breaking-company}} {:k1 "dolor" :k2 "3abc" :attrs {:type :breaking-company}} {:k1 "lem" :k2 "4adcor" :attrs {:type :breaking-company}} {:k1 "ipsum" :k2 "5abc" :attrs {:type :breaking-company}} {:k1 "dol" :k2 "6abc" :attrs {:type :breaking-company}} {:k1 "amet" :k2 "7abc" :attrs {:type :booking-company}}] query {:search [:fields [:k1 :k2] :value "or"] :filter [:not [:eq "attrs.type" :booking-company]]} expected {:total 3 :from 0 :size 50 :hits [{:k1 "lorem" :k2 "1adc" :attrs {:type :breaking-company}} {:k1 "dolor" :k2 "3abc" :attrs {:type :breaking-company}} {:k1 "lem" :k2 "4adcor" :attrs {:type :breaking-company}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-select-filter-2 (let [data [{:k1 "121" :k2 {:k21 "a" :k22 "1"}} {:k1 "758" :k2 {:k21 "c" :k22 "2"}} {:k1 "751" :k2 {:k21 "c" :k22 "2"}} {:k1 "751" :k2 {:k21 "d" :k22 "2"}} {:k1 "121" :k2 {:k21 "e" :k22 "3"}}] query {:select ["k1" "k2.k21"] :size 50 :filter [:eq "k2.k22" "2"]} expected {:total 3 :from 0 :size 50 :hits [{:k1 "758" :k2 {:k21 "c"}} {:k1 "751" :k2 {:k21 "c"}} {:k1 "751" :k2 {:k21 "d"}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-select-filter-keywords (let [data [{:k1 "121" :k2 {:k21 "a" :k22 "1"}} {:k1 "758" :k2 {:k21 "c" :k22 "2"}} {:k1 "751" :k2 {:k21 "c" :k22 "2"}} {:k1 "751" :k2 {:k21 "d" :k22 "2"}} {:k1 "121" :k2 {:k21 "e" :k22 "3"}}] query {:select [:k1 :k2.k21] :size 50 :filter [:eq "k2.k22" "2"]} expected {:total 3 :from 0 :size 50 :hits [{:k1 "758" :k2 {:k21 "c"}} {:k1 "751" :k2 {:k21 "c"}} {:k1 "751" :k2 {:k21 "d"}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-sort-asc (let [data [{:k1 "121" :k2 {:k21 "a" :k22 "1"}} {:k1 "758" :k2 {:k21 "c" :k22 "2"}} {:k1 "752" :k2 {:k21 "d" :k22 "2"}} {:k1 "751" :k2 {:k21 "c" :k22 "2"}} {:k1 "121" :k2 {:k21 "e" :k22 "3"}}] query {:select [:k1 :k2.k21] :size 50 :filter [:eq "k2.k22" "2"] :sort [:k1 "asc"]} expected {:total 3 :from 0 :size 50 :hits [{:k1 "751" :k2 {:k21 "c"}} {:k1 "752" :k2 {:k21 "d"}} {:k1 "758" :k2 {:k21 "c"}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-sort-desc (let [data [{:k1 "121" :k2 {:k21 "a" :k22 "1"}} {:k1 "758" :k2 {:k21 "c" :k22 "2"}} {:k1 "752" :k2 {:k21 "d" :k22 "2"}} {:k1 "751" :k2 {:k21 "c" :k22 "2"}} {:k1 "121" :k2 {:k21 "e" :k22 "3"}}] query {:select [:k1 :k2.k21] :size 50 :filter [:eq "k2.k22" "2"] :sort [:k1 "desc"]} expected {:total 3 :from 0 :size 50 :hits [{:k1 "758" :k2 {:k21 "c"}} {:k1 "752" :k2 {:k21 "d"}} {:k1 "751" :k2 {:k21 "c"}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-sort-desc-1 (let [data [{:k1 "121" :k2 {:k21 "a" :k22 "1"}} {:k1 "758" :k2 {:k21 "1" :k22 "2"}} {:k1 "758" :k2 {:k21 "2" :k22 "2"}} {:k1 "250" :k2 {:k21 "3" :k22 "2"}} {:k1 "121" :k2 {:k21 "4" :k22 "2"}}] query {:select [:k1 :k2.k21] :size 50 :filter [:eq "k2.k22" "2"] :sort [:k1 "desc" :k2.k21 "asc"]} expected {:total 4 :from 0 :size 50 :hits [{:k1 "758" :k2 {:k21 "1"}} {:k1 "758" :k2 {:k21 "2"}} {:k1 "250" :k2 {:k21 "3"}} {:k1 "121" :k2 {:k21 "4"}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-sort-desc-2 (let [data [{:k1 "121" :k2 {:k21 "a" :k22 "1"}} {:k1 "758" :k2 {:k21 "1" :k22 "2"}} {:k1 "758" :k2 {:k21 "2" :k22 "2"}} {:k1 "250" :k2 {:k21 "3" :k22 "2"}} {:k1 "121" :k2 {:k21 "4" :k22 "2"}}] query {:select [:k1 :k2.k21] :size 50 :filter [:eq "k2.k22" "2"] :sort [:k1 "desc" :k2.k21 "desc"]} expected {:total 4 :from 0 :size 50 :hits [{:k1 "758" :k2 {:k21 "2"}} {:k1 "758" :k2 {:k21 "1"}} {:k1 "250" :k2 {:k21 "3"}} {:k1 "121" :k2 {:k21 "4"}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-sort-asc-1 (let [data [{:k1 "121" :k2 {:k21 "a" :k22 "1"}} {:k1 "758" :k2 {:k21 "1" :k22 "2"}} {:k1 "758" :k2 {:k21 "2" :k22 "2"}} {:k1 "250" :k2 {:k21 "3" :k22 "2"}} {:k1 "121" :k2 {:k21 "4" :k22 "2"}}] query {:select [:k1 :k2.k21] :size 50 :filter [:eq "k2.k22" "2"] :sort [:k1 "asc" :k2.k21 "desc"]} expected {:total 4 :from 0 :size 50 :hits [{:k1 "121" :k2 {:k21 "4"}} {:k1 "250" :k2 {:k21 "3"}} {:k1 "758" :k2 {:k21 "2"}} {:k1 "758" :k2 {:k21 "1"}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-sort-asc-2 (let [data [{:k1 1} {:k1 20} {:k1 3} {:k1 400} {:k1 5}] query {:size 50 :sort [:k1 "asc-number"]} expected {:total 5 :from 0 :size 50 :hits [{:k1 1} {:k1 3} {:k1 5} {:k1 20} {:k1 400}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-sort-desc-2 (let [data [{:k1 1} {:k1 20} {:k1 3} {:k1 400} {:k1 5}] query {:size 50 :sort [:k1 :desc-number]} expected {:total 5 :from 0 :size 50 :hits [{:k1 400} {:k1 20} {:k1 5} {:k1 3} {:k1 1}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-test-exists-field-1 (let [data [{:attrs {:top-parent-id #uuid "1111a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}} {:attrs {:top-parent-id #uuid "3333a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "4444a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}} {:attrs {:top-parent-id #uuid "5555a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}} {:attrs {:top-parent-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "8888a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}}] query {:filter [:exists :attrs.top-parent-id]} expected {:total 4 :from 0 :size 50 :hits data} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-test-exists-field-2 (let [data [{:attrs {:top-parent-id #uuid "1111a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}} {:attrs {:top-parent-id #uuid "3333a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "4444a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}} {:attrs {:top-parent-id #uuid "5555a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}} {:attrs {:top-parent-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "8888a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}}] query {:filter [:not [:exists :attrs.top-parent-id]]} expected {:total 0 :from 0 :size 50 :hits []} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-test-order-of-exact-match (let [data [{:k1 "120" :attrs {:type :booking-company}} {:k1 "10" :k2 "1adc" :attrs {:type :breaking-company}} {:k1 "100" :k2 "10" :attrs {:type :breaking-company}} {:k1 "1011" :k2 "1011" :attrs {:type :breaking-company}} {:k1 "lem" :k2 "4adcor" :attrs {:type :breaking-company}} {:k1 "ipsum" :k2 "5<KEY>" :attrs {:type :breaking-company}} {:k1 "dol" :k2 "6abc" :attrs {:type :breaking-company}} {:k1 "10" :k2 "zeko" :attrs {:type :breaking-company}} {:k1 "amet" :k2 "7abc" :attrs {:type :booking-company}}] query {:search [:fields [:k1 :k2] :value "10"]} expected {:from 0 :hits [{:attrs {:type :breaking-company} :k1 "100" :k2 "10"} {:attrs {:type :breaking-company} :k1 "10" :k2 "1adc"} {:attrs {:type :breaking-company} :k1 "10" :k2 "zeko"} {:attrs {:type :breaking-company} :k1 "1011" :k2 "1011"}] :size 50 :total 4} [el-result mock-result] (test-query data query)] (is (= expected el-result))))
true
(ns edd.search-it (:require [clojure.test :refer :all] [clojure.tools.logging :as log] [lambda.util :as util] [edd.memory.view-store :as memory-view-store] [edd.elastic.view-store :as elastic-view-store] [edd.search :as search] [lambda.test.fixture.state :as state] [edd.search :as search] [lambda.elastic :as el] [lambda.uuid :as uuid] [clojure.string :as str])) (def ctx {:elastic-search {:url (util/get-env "IndexDomainEndpoint")} :meta {:realm :test} :aws {:region (util/get-env "AWS_DEFAULT_REGION") :aws-access-key-id (util/get-env "AWS_ACCESS_KEY_ID") :aws-secret-access-key (util/get-env "AWS_SECRET_ACCESS_KEY") :aws-session-token (util/get-env "AWS_SESSION_TOKEN")}}) (defn load-data [ctx] (doseq [i (:aggregate-store @state/*dal-state*)] (log/info (el/query (assoc ctx :method "POST" :path (str "/" (elastic-view-store/realm ctx) "_" (:service-name ctx) "/_doc") :body (util/to-json i)))))) (defn test-query [data q] (binding [state/*dal-state* (atom {:aggregate-store data})] (let [service-name (str/replace (str (uuid/gen)) "-" "_") local-ctx (assoc ctx :service-name service-name) body {:settings {:index {:number_of_shards 1 :number_of_replicas 0}} :mappings {:dynamic_templates [{:integers {:match_mapping_type "long", :mapping {:type "integer", :fields {:number {:type "long"}, :keyword {:type "keyword", :ignore_above 256}}}}}]}}] (log/info "Index name" service-name) (el/query (assoc local-ctx :method "PUT" :path (str "/" (elastic-view-store/realm ctx) "_" service-name) :body (util/to-json body))) (load-data local-ctx) (Thread/sleep 2000) (let [el-result (search/advanced-search (-> local-ctx (elastic-view-store/register) (assoc :query q))) mock-result (search/advanced-search (-> local-ctx (memory-view-store/register) (assoc :query q)))] (log/info el-result) (log/info mock-result) (el/query (assoc local-ctx :method "DELETE" :path (str "/" service-name))) [el-result mock-result])))) (deftest test-elastic-mock-parity-1 (let [data [{:k1 "121" :k2 "be" :k3 {:k31 "c"}} {:k1 "758" :k2 "be"} {:k1 "121" :k2 "be" :k3 {:k31 "d"}}] query {:filter [:and [:and [:eq :k1 "121"] [:eq :k2 "be"]] [:eq "k3.k31" "c"]]} expected {:total 1 :from 0 :size 50 :hits [{:k1 "121" :k2 "be" :k3 {:k31 "c"}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-2 (let [data [{:k1 "121" :k2 "be" :k3 {:k31 "c"}} {:k1 "758" :k2 "be"} {:k1 "751" :k2 "be"} {:k1 "751" :k2 "bb"} {:k1 "121" :k2 "be" :k3 {:k31 "d"}}] query {:filter [:and [:eq :k2 "be"] [:in :k1 ["751" "758"]]]} expected {:total 2 :from 0 :size 50 :hits [{:k1 "758" :k2 "be"} {:k1 "751" :k2 "be"}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-keyword-in-2 (let [data [{:k1 :v0 :k2 "be" :k3 {:k31 "c"}} {:k1 :v1 :k2 "bi"} {:k1 :v1 :k2 "be"} {:k1 :v2 :k2 "be"} {:k1 :v1 :k2 "bb"} {:k1 :v3 :k2 "be" :k3 {:k31 "d"}}] query {:filter [:and [:eq :k2 "be"] [:in :k1 [:v1 :v2]]]} expected {:total 2 :from 0 :size 50 :hits [{:k1 :v1 :k2 "be"} {:k1 :v2 :k2 "be"}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-3 (let [data [{:k1 "121" :k2 "be" :k3 {:k31 "c"}} {:k1 "758" :k2 "be"} {:k1 "751" :k2 "be"} {:k1 "751" :k2 "bb"} {:k1 "121" :k2 "be" :k3 {:k31 "d"}}] query {:filter [:and [:eq :k2 "be"] [:not [:in :k1 ["751" "758"]]]]} expected {:total 2 :from 0 :size 50 :hits [{:k1 "121" :k2 "be" :k3 {:k31 "c"}} {:k1 "121" :k2 "be" :k3 {:k31 "d"}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-4 (let [data [{:k1 "121" :attrs {:type :booking-company}} {:k1 "122" :attrs {:type :breaking-company}} {:k1 "123" :attrs {:type :booking-company}}] query {:filter [:not [:eq "attrs.type" :booking-company]]} expected {:total 1 :from 0 :size 50 :hits [{:k1 "122" :attrs {:type :breaking-company}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-test-search-1 (let [data [{:k1 "consectetur" :attrs {:type :booking-company}} {:k1 "lorem" :k2 "1adc" :attrs {:type :breaking-company}} {:k1 "ipsum" :k2 "2abc" :attrs {:type :breaking-company}} {:k1 "dolor" :k2 "3abc" :attrs {:type :breaking-company}} {:k1 "lem" :k2 "4adcor" :attrs {:type :breaking-company}} {:k1 "ipsum" :k2 "5abc" :attrs {:type :breaking-company}} {:k1 "dol" :k2 "6abc" :attrs {:type :breaking-company}} {:k1 "amet" :k2 "7abc" :attrs {:type :booking-company}}] query {:search [:fields [:k1 :k2] :value "or"] :filter [:not [:eq "attrs.type" :booking-company]]} expected {:total 3 :from 0 :size 50 :hits [{:k1 "lorem" :k2 "1adc" :attrs {:type :breaking-company}} {:k1 "dolor" :k2 "3abc" :attrs {:type :breaking-company}} {:k1 "lem" :k2 "4adcor" :attrs {:type :breaking-company}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-test-search-only-1 (let [data [{:k1 "consectetur" :attrs {:type :booking-company}} {:k1 "lorem" :k2 "1adc" :attrs {:type :breaking-company}} {:k1 "ipsum" :k2 "2abc" :attrs {:type :breaking-company}} {:k1 "dolor" :k2 "3abc" :attrs {:type :breaking-company}} {:k1 "lem" :k2 "4adcor" :attrs {:type :breaking-company}} {:k1 "ipsum" :k2 "5abc" :attrs {:type :breaking-company}} {:k1 "dol" :k2 "6abc" :attrs {:type :breaking-company}} {:k1 "amet" :k2 "7aor" :attrs {:type :booking-company}}] query {:search [:fields [:k1 :k2] :value "or"]} expected {:total 4 :from 0 :size 50 :hits [{:k1 "lorem" :k2 "1adc" :attrs {:type :breaking-company}} {:k1 "dolor" :k2 "3abc" :attrs {:type :breaking-company}} {:k1 "lem" :k2 "4adcor" :attrs {:type :breaking-company}} {:k1 "amet" :k2 "7aor" :attrs {:type :booking-company}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-test-search-only-2 (let [data [{:k1 "consectetur" :attrs {:type :booking-company}} {:k1 "lorem" :k2 "1adc" :attrs {:type :breaking-company}} {:k1 "ipsum" :k2 "2abc" :attrs {:type :breaking-company}} {:k1 "dolor" :k2 "3abc" :attrs {:type :breaking-company}} {:k1 "lem" :k2 "4adcor" :attrs {:type :breaking-company}} {:k1 "ipsum" :k2 "5abc" :attrs {:type :breaking-company}} {:k1 "dol" :k2 "6abc" :attrs {:type :breaking-company}} {:k1 "amet" :k2 "7aor" :attrs {:type :booking-company}} {:k1 "ame5" :k2 "7aor" :attrs {:type :booking-company}}] query {:search [:fields [:k1 :k2] :value "or"] :from 2 :size 2} expected {:total 5 :from 2 :size 2 :hits [{:k1 "lem" :k2 "4adcor" :attrs {:type :breaking-company}} {:k1 "amet" :k2 "7aor" :attrs {:type :booking-company}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-test-search-only-3 (let [data [{:attrs {:top-parent-id #uuid "1111a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}} {:attrs {:top-parent-id #uuid "3333a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "4444a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}} {:attrs {:top-parent-id #uuid "5555a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}} {:attrs {:top-parent-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "8888a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}}] query {:filter [:or [:eq :attrs.top-parent-id #uuid "1111a4b3-1c40-48ec-b6c9-b9cceeea6bb8"] [:eq :attrs.top-gcc-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8"]]} expected {:total 2 :from 0 :size 50 :hits [{:attrs {:top-parent-id #uuid "1111a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}} {:attrs {:top-parent-id #uuid "5555a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-test-search-4 (let [data [{:k1 "consectetur" :attrs {:type :booking-company}} {:k1 "lorem" :k2 "1adc" :attrs {:type :breaking-company}} {:k1 "ipsum" :k2 "2abc" :attrs {:type :breaking-company}} {:k1 "dolor" :k2 "3abc" :attrs {:type :breaking-company}} {:k1 "lem" :k2 "4adcor" :attrs {:type :breaking-company}} {:k1 "ipsum" :k2 "5abc" :attrs {:type :breaking-company}} {:k1 "dol" :k2 "6abc" :attrs {:type :breaking-company}} {:k1 "amet" :k2 "7abc" :attrs {:type :booking-company}}] query {:search [:fields [:k1 :k2] :value "or"] :filter [:not [:eq "attrs.type" :booking-company]]} expected {:total 3 :from 0 :size 50 :hits [{:k1 "lorem" :k2 "1adc" :attrs {:type :breaking-company}} {:k1 "dolor" :k2 "3abc" :attrs {:type :breaking-company}} {:k1 "lem" :k2 "4adcor" :attrs {:type :breaking-company}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-select-filter-2 (let [data [{:k1 "121" :k2 {:k21 "a" :k22 "1"}} {:k1 "758" :k2 {:k21 "c" :k22 "2"}} {:k1 "751" :k2 {:k21 "c" :k22 "2"}} {:k1 "751" :k2 {:k21 "d" :k22 "2"}} {:k1 "121" :k2 {:k21 "e" :k22 "3"}}] query {:select ["k1" "k2.k21"] :size 50 :filter [:eq "k2.k22" "2"]} expected {:total 3 :from 0 :size 50 :hits [{:k1 "758" :k2 {:k21 "c"}} {:k1 "751" :k2 {:k21 "c"}} {:k1 "751" :k2 {:k21 "d"}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-select-filter-keywords (let [data [{:k1 "121" :k2 {:k21 "a" :k22 "1"}} {:k1 "758" :k2 {:k21 "c" :k22 "2"}} {:k1 "751" :k2 {:k21 "c" :k22 "2"}} {:k1 "751" :k2 {:k21 "d" :k22 "2"}} {:k1 "121" :k2 {:k21 "e" :k22 "3"}}] query {:select [:k1 :k2.k21] :size 50 :filter [:eq "k2.k22" "2"]} expected {:total 3 :from 0 :size 50 :hits [{:k1 "758" :k2 {:k21 "c"}} {:k1 "751" :k2 {:k21 "c"}} {:k1 "751" :k2 {:k21 "d"}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-sort-asc (let [data [{:k1 "121" :k2 {:k21 "a" :k22 "1"}} {:k1 "758" :k2 {:k21 "c" :k22 "2"}} {:k1 "752" :k2 {:k21 "d" :k22 "2"}} {:k1 "751" :k2 {:k21 "c" :k22 "2"}} {:k1 "121" :k2 {:k21 "e" :k22 "3"}}] query {:select [:k1 :k2.k21] :size 50 :filter [:eq "k2.k22" "2"] :sort [:k1 "asc"]} expected {:total 3 :from 0 :size 50 :hits [{:k1 "751" :k2 {:k21 "c"}} {:k1 "752" :k2 {:k21 "d"}} {:k1 "758" :k2 {:k21 "c"}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-sort-desc (let [data [{:k1 "121" :k2 {:k21 "a" :k22 "1"}} {:k1 "758" :k2 {:k21 "c" :k22 "2"}} {:k1 "752" :k2 {:k21 "d" :k22 "2"}} {:k1 "751" :k2 {:k21 "c" :k22 "2"}} {:k1 "121" :k2 {:k21 "e" :k22 "3"}}] query {:select [:k1 :k2.k21] :size 50 :filter [:eq "k2.k22" "2"] :sort [:k1 "desc"]} expected {:total 3 :from 0 :size 50 :hits [{:k1 "758" :k2 {:k21 "c"}} {:k1 "752" :k2 {:k21 "d"}} {:k1 "751" :k2 {:k21 "c"}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-sort-desc-1 (let [data [{:k1 "121" :k2 {:k21 "a" :k22 "1"}} {:k1 "758" :k2 {:k21 "1" :k22 "2"}} {:k1 "758" :k2 {:k21 "2" :k22 "2"}} {:k1 "250" :k2 {:k21 "3" :k22 "2"}} {:k1 "121" :k2 {:k21 "4" :k22 "2"}}] query {:select [:k1 :k2.k21] :size 50 :filter [:eq "k2.k22" "2"] :sort [:k1 "desc" :k2.k21 "asc"]} expected {:total 4 :from 0 :size 50 :hits [{:k1 "758" :k2 {:k21 "1"}} {:k1 "758" :k2 {:k21 "2"}} {:k1 "250" :k2 {:k21 "3"}} {:k1 "121" :k2 {:k21 "4"}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-sort-desc-2 (let [data [{:k1 "121" :k2 {:k21 "a" :k22 "1"}} {:k1 "758" :k2 {:k21 "1" :k22 "2"}} {:k1 "758" :k2 {:k21 "2" :k22 "2"}} {:k1 "250" :k2 {:k21 "3" :k22 "2"}} {:k1 "121" :k2 {:k21 "4" :k22 "2"}}] query {:select [:k1 :k2.k21] :size 50 :filter [:eq "k2.k22" "2"] :sort [:k1 "desc" :k2.k21 "desc"]} expected {:total 4 :from 0 :size 50 :hits [{:k1 "758" :k2 {:k21 "2"}} {:k1 "758" :k2 {:k21 "1"}} {:k1 "250" :k2 {:k21 "3"}} {:k1 "121" :k2 {:k21 "4"}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-sort-asc-1 (let [data [{:k1 "121" :k2 {:k21 "a" :k22 "1"}} {:k1 "758" :k2 {:k21 "1" :k22 "2"}} {:k1 "758" :k2 {:k21 "2" :k22 "2"}} {:k1 "250" :k2 {:k21 "3" :k22 "2"}} {:k1 "121" :k2 {:k21 "4" :k22 "2"}}] query {:select [:k1 :k2.k21] :size 50 :filter [:eq "k2.k22" "2"] :sort [:k1 "asc" :k2.k21 "desc"]} expected {:total 4 :from 0 :size 50 :hits [{:k1 "121" :k2 {:k21 "4"}} {:k1 "250" :k2 {:k21 "3"}} {:k1 "758" :k2 {:k21 "2"}} {:k1 "758" :k2 {:k21 "1"}}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-sort-asc-2 (let [data [{:k1 1} {:k1 20} {:k1 3} {:k1 400} {:k1 5}] query {:size 50 :sort [:k1 "asc-number"]} expected {:total 5 :from 0 :size 50 :hits [{:k1 1} {:k1 3} {:k1 5} {:k1 20} {:k1 400}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-sort-desc-2 (let [data [{:k1 1} {:k1 20} {:k1 3} {:k1 400} {:k1 5}] query {:size 50 :sort [:k1 :desc-number]} expected {:total 5 :from 0 :size 50 :hits [{:k1 400} {:k1 20} {:k1 5} {:k1 3} {:k1 1}]} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-test-exists-field-1 (let [data [{:attrs {:top-parent-id #uuid "1111a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}} {:attrs {:top-parent-id #uuid "3333a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "4444a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}} {:attrs {:top-parent-id #uuid "5555a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}} {:attrs {:top-parent-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "8888a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}}] query {:filter [:exists :attrs.top-parent-id]} expected {:total 4 :from 0 :size 50 :hits data} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-test-exists-field-2 (let [data [{:attrs {:top-parent-id #uuid "1111a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}} {:attrs {:top-parent-id #uuid "3333a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "4444a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}} {:attrs {:top-parent-id #uuid "5555a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}} {:attrs {:top-parent-id #uuid "2222a4b3-1c40-48ec-b6c9-b9cceeea6bb8" :top-gcc-id #uuid "8888a4b3-1c40-48ec-b6c9-b9cceeea6bb8"}}] query {:filter [:not [:exists :attrs.top-parent-id]]} expected {:total 0 :from 0 :size 50 :hits []} [el-result mock-result] (test-query data query)] (is (= expected el-result)) (is (= expected mock-result)))) (deftest test-elastic-mock-parity-test-order-of-exact-match (let [data [{:k1 "120" :attrs {:type :booking-company}} {:k1 "10" :k2 "1adc" :attrs {:type :breaking-company}} {:k1 "100" :k2 "10" :attrs {:type :breaking-company}} {:k1 "1011" :k2 "1011" :attrs {:type :breaking-company}} {:k1 "lem" :k2 "4adcor" :attrs {:type :breaking-company}} {:k1 "ipsum" :k2 "5PI:KEY:<KEY>END_PI" :attrs {:type :breaking-company}} {:k1 "dol" :k2 "6abc" :attrs {:type :breaking-company}} {:k1 "10" :k2 "zeko" :attrs {:type :breaking-company}} {:k1 "amet" :k2 "7abc" :attrs {:type :booking-company}}] query {:search [:fields [:k1 :k2] :value "10"]} expected {:from 0 :hits [{:attrs {:type :breaking-company} :k1 "100" :k2 "10"} {:attrs {:type :breaking-company} :k1 "10" :k2 "1adc"} {:attrs {:type :breaking-company} :k1 "10" :k2 "zeko"} {:attrs {:type :breaking-company} :k1 "1011" :k2 "1011"}] :size 50 :total 4} [el-result mock-result] (test-query data query)] (is (= expected el-result))))
[ { "context": " \"Reach us at \"\n [:a {:href \"mailto:support+shotbot@oursky.com\"} \"support+shotbot@oursky.com\"]]]]]]]])})))\n", "end": 2511, "score": 0.9999166131019592, "start": 2485, "tag": "EMAIL", "value": "support+shotbot@oursky.com" }, { "context": " [:a {:href \"mailto:support+shotbot@oursky.com\"} \"support+shotbot@oursky.com\"]]]]]]]])})))\n", "end": 2541, "score": 0.9999141693115234, "start": 2515, "tag": "EMAIL", "value": "support+shotbot@oursky.com" } ]
src/cljs/shotbot/re_frame/settings/views.cljs
skygear-demo/shotbot3
2
(ns shotbot.re-frame.settings.views (:require [re-frame.core :refer [dispatch subscribe]] [reagent.core :as r])) (defn modal [] (let [message (subscribe [:settings/message]) user-email (subscribe [:settings/user-email]) key-down (fn [event] (when (= event.key "Escape") (dispatch [:shotbot/modal-pop])))] (r/create-class {:component-will-mount (fn [_] (js/addEventListener "keydown" key-down)) :component-will-unmount (fn [_] (js/removeEventListener "keydown" key-down)) :reagent-render (fn modal-reaction [] [:div.overlay [:div.container [:div.row [:div.col-sm-6.col-sm-offset-3.settings-modal [:div [:header.settings [:div.right-aligner [:img {:src "img/icon-close.svg" :on-click #(dispatch [:shotbot/modal-pop])}]] [:h1 "Settings"] [:p.user-email @user-email]] [:form.settings {:on-submit (fn [evt] (.preventDefault evt) (dispatch [:settings/change-password]))} [:p.form-header "Change my Password"] [:input {:type "password" :placeholder "Old Password" :required true :on-change (fn [evt] (dispatch [:settings/old-password (-> evt .-target .-value)]))}] [:br] [:input {:type "password" :placeholder "New Password" :required true :on-change (fn [evt] (dispatch [:settings/new-password (-> evt .-target .-value)]))}] [:br] [:input {:type "password" :placeholder "New Password (Confirm)" :required true :on-change (fn [evt] (dispatch [:settings/new-password-confirm (-> evt .-target .-value)]))}] [:br] [:p.message @message] [:input {:type "submit" :value "Save Changes"}]] [:footer.settings [:p "Comments? Any Advice? Looking for Help?"] [:p "Reach us at " [:a {:href "mailto:support+shotbot@oursky.com"} "support+shotbot@oursky.com"]]]]]]]])})))
37860
(ns shotbot.re-frame.settings.views (:require [re-frame.core :refer [dispatch subscribe]] [reagent.core :as r])) (defn modal [] (let [message (subscribe [:settings/message]) user-email (subscribe [:settings/user-email]) key-down (fn [event] (when (= event.key "Escape") (dispatch [:shotbot/modal-pop])))] (r/create-class {:component-will-mount (fn [_] (js/addEventListener "keydown" key-down)) :component-will-unmount (fn [_] (js/removeEventListener "keydown" key-down)) :reagent-render (fn modal-reaction [] [:div.overlay [:div.container [:div.row [:div.col-sm-6.col-sm-offset-3.settings-modal [:div [:header.settings [:div.right-aligner [:img {:src "img/icon-close.svg" :on-click #(dispatch [:shotbot/modal-pop])}]] [:h1 "Settings"] [:p.user-email @user-email]] [:form.settings {:on-submit (fn [evt] (.preventDefault evt) (dispatch [:settings/change-password]))} [:p.form-header "Change my Password"] [:input {:type "password" :placeholder "Old Password" :required true :on-change (fn [evt] (dispatch [:settings/old-password (-> evt .-target .-value)]))}] [:br] [:input {:type "password" :placeholder "New Password" :required true :on-change (fn [evt] (dispatch [:settings/new-password (-> evt .-target .-value)]))}] [:br] [:input {:type "password" :placeholder "New Password (Confirm)" :required true :on-change (fn [evt] (dispatch [:settings/new-password-confirm (-> evt .-target .-value)]))}] [:br] [:p.message @message] [:input {:type "submit" :value "Save Changes"}]] [:footer.settings [:p "Comments? Any Advice? Looking for Help?"] [:p "Reach us at " [:a {:href "mailto:<EMAIL>"} "<EMAIL>"]]]]]]]])})))
true
(ns shotbot.re-frame.settings.views (:require [re-frame.core :refer [dispatch subscribe]] [reagent.core :as r])) (defn modal [] (let [message (subscribe [:settings/message]) user-email (subscribe [:settings/user-email]) key-down (fn [event] (when (= event.key "Escape") (dispatch [:shotbot/modal-pop])))] (r/create-class {:component-will-mount (fn [_] (js/addEventListener "keydown" key-down)) :component-will-unmount (fn [_] (js/removeEventListener "keydown" key-down)) :reagent-render (fn modal-reaction [] [:div.overlay [:div.container [:div.row [:div.col-sm-6.col-sm-offset-3.settings-modal [:div [:header.settings [:div.right-aligner [:img {:src "img/icon-close.svg" :on-click #(dispatch [:shotbot/modal-pop])}]] [:h1 "Settings"] [:p.user-email @user-email]] [:form.settings {:on-submit (fn [evt] (.preventDefault evt) (dispatch [:settings/change-password]))} [:p.form-header "Change my Password"] [:input {:type "password" :placeholder "Old Password" :required true :on-change (fn [evt] (dispatch [:settings/old-password (-> evt .-target .-value)]))}] [:br] [:input {:type "password" :placeholder "New Password" :required true :on-change (fn [evt] (dispatch [:settings/new-password (-> evt .-target .-value)]))}] [:br] [:input {:type "password" :placeholder "New Password (Confirm)" :required true :on-change (fn [evt] (dispatch [:settings/new-password-confirm (-> evt .-target .-value)]))}] [:br] [:p.message @message] [:input {:type "submit" :value "Save Changes"}]] [:footer.settings [:p "Comments? Any Advice? Looking for Help?"] [:p "Reach us at " [:a {:href "mailto:PI:EMAIL:<EMAIL>END_PI"} "PI:EMAIL:<EMAIL>END_PI"]]]]]]]])})))
[ { "context": "est\"\n :user \"everest\", :password \"everest\"})\n\n(def +hikari-config\n {:datasource-classname ", "end": 1091, "score": 0.9993419051170349, "start": 1084, "tag": "PASSWORD", "value": "everest" }, { "context": "g.postgresql.ds.PGSimpleDataSource\"\n :username \"everest\"\n :password \"everest\"\n :database-name \"everes", "end": 1201, "score": 0.9981030225753784, "start": 1194, "tag": "USERNAME", "value": "everest" }, { "context": "eDataSource\"\n :username \"everest\"\n :password \"everest\"\n :database-name \"everest\"\n :server-name \"loc", "end": 1224, "score": 0.9993363618850708, "start": 1217, "tag": "PASSWORD", "value": "everest" }, { "context": "\n :everest.event/metadata {:user \"test-user\"}})\n (store/append-events! store+ \"t", "end": 5591, "score": 0.9993001818656921, "start": 5582, "tag": "USERNAME", "value": "test-user" } ]
examples/pg/src/app.clj
dm3/everest
4
(ns app (:require [everest.json.handler.middleware :as json.handler.middleware] [everest.json.store.middleware :as json.store.middleware] [everest.pg.store :as pg.store] [everest.pg.schema :as pg.schema] [everest.pg.handler.store :as pg.handler.store] [everest.pg.handler.middleware :as pg.handler.middleware] [everest.pg.notification.poll-notify :as pg.poll-notify] [everest.handler.middleware :as handler.middleware] [everest.handler :as handler] [everest.store :as store] [everest.store.middleware :as store.middleware] [everest.store.subscription :as subscriptions] [clojure.tools.logging :as log] [clojure.pprint :as pprint :refer [pprint]] [embedded-pg :as pg] [hikari-cp.core :as hikari] [manifold.stream :as m.s] [mount.core :as mount :refer [defstate]])) (def +pg-config {:host "localhost", :port 3334, :db-name "everest" :user "everest", :password "everest"}) (def +hikari-config {:datasource-classname "org.postgresql.ds.PGSimpleDataSource" :username "everest" :password "everest" :database-name "everest" :server-name "localhost" :port-number 3334 :pool-name "everest"}) (defstate pg+ :start (doto (pg/make {:version "9.5.7-1"}) (pg/start! +pg-config)) :stop (pg/stop! pg+)) (defstate pool+ :start (hikari/make-datasource +hikari-config) :stop (hikari/close-datasource pool+)) (defstate pg-schema+ :start (pg.schema/migrate! pool+ {:type "bytea"}) :stop (pg.schema/drop! pool+)) (defn- wrap-edn-utf8-bytes [store] (let [generate-fn #(-> % pr-str (.getBytes "UTF-8")) parse-fn #(if (zero? (alength %)) {} (-> % (String.) read-string))] (store.middleware/wrap-store store (fn [e] (-> e (update :everest.event/data generate-fn) (update :everest.event/metadata generate-fn))) (fn [e] (-> e (update :everest.event/data parse-fn) (update :everest.event/metadata parse-fn)))))) (defstate store+ :start (-> (pg.store/create-store pool+ {:everest.pg.store/event-data-type :bytea}) (wrap-edn-utf8-bytes) #_(json.store.middleware/wrap-cheshire-json {}))) (defstate notifications+ :start (pg.poll-notify/create-notification-source pool+ {}) :stop (.close notifications+)) (defstate subscriptions+ :start (subscriptions/create-subscription-source store+ (pg.poll-notify/notifications notifications+) {}) :stop (.close subscriptions+)) (defn- event-handler [handler-name handler-fn] (-> handler-fn (handler.middleware/wrap-state-atom {}) (json.handler.middleware/wrap-cheshire-json {}) (pg.handler.middleware/wrap-json-state {}) (pg.handler.middleware/wrap-state {:handler.middleware/catch-up-upsert-batch-size 500 :handler.middleware/handler-type (name handler-name) :handler.middleware/handler-id (name handler-name)}) (pg.handler.middleware/wrap-tx {:handler.middleware/tx-during-catch-up? false}) (pg.handler.middleware/wrap-connection {:handler.middleware/db pool+}))) (defn- init-handler! [id pos] (pg.handler.store/update! pool+ {:pg.handler/type id :pg.handler/id (name id) :pg.handler/position pos})) (defstate catch-up-executor+ :start (java.util.concurrent.Executors/newFixedThreadPool 2) :stop (.shutdownNow catch-up-executor+)) (defn- run-with [sub handler] (.execute ^java.util.concurrent.Executor catch-up-executor+ #(m.s/consume handler sub))) (defn- init-and-subscribe-handler! [f stream type pos] (let [type (name type) _ (init-handler! type pos) sub (pg.handler.store/subscribe subscriptions+ pool+ stream type {})] (run-with sub (event-handler type f)) sub)) (defstate handler-all+ :start (-> (fn [{:everest.event/keys [stream type position] :as event}] (let [{:handler/keys [id state]} event] (log/info id stream "->" type "@" position ">" @state) (swap! state (fnil inc 0)))) (init-and-subscribe-handler! :all 'TestHandlerAll 0)) :stop (m.s/close! handler-all+)) (defstate handler-stream+ :start (-> (fn [{:everest.event/keys [stream type position] :as event}] (let [{:handler/keys [id state]} event] (log/info id stream "->" type "@" position ">" @state) (swap! state (fnil inc 0)))) (init-and-subscribe-handler! "test-stream" 'TestHandlerStream 5)) :stop (m.s/close! handler-stream+)) (defn- read-all-events [] (log/info "EVENTS IN STORE>>\n" (with-out-str (-> (store/read-stream-forward store+ :all nil 10) (pprint))))) (defn main [] (try (mount/start) (let [all-sub (store/subscribe subscriptions+ :all :everest.subscription.events/all {})] (m.s/consume (fn [e] (log/info "GOT EVENT>>" (with-out-str (pprint e)))) all-sub) (read-all-events) (->> (for [i (range 1)] {:everest.event/type 'TestEvent :everest.event/data {:string "string" :int i :double 1.0 :boolean true :date (java.util.Date.)} :everest.event/metadata {:user "test-user"}}) (store/append-events! store+ "test-stream" :everest.stream.version/any)) ;; allow the notifications to propagate (Thread/sleep 1000) (read-all-events)) (finally (mount/stop))))
82013
(ns app (:require [everest.json.handler.middleware :as json.handler.middleware] [everest.json.store.middleware :as json.store.middleware] [everest.pg.store :as pg.store] [everest.pg.schema :as pg.schema] [everest.pg.handler.store :as pg.handler.store] [everest.pg.handler.middleware :as pg.handler.middleware] [everest.pg.notification.poll-notify :as pg.poll-notify] [everest.handler.middleware :as handler.middleware] [everest.handler :as handler] [everest.store :as store] [everest.store.middleware :as store.middleware] [everest.store.subscription :as subscriptions] [clojure.tools.logging :as log] [clojure.pprint :as pprint :refer [pprint]] [embedded-pg :as pg] [hikari-cp.core :as hikari] [manifold.stream :as m.s] [mount.core :as mount :refer [defstate]])) (def +pg-config {:host "localhost", :port 3334, :db-name "everest" :user "everest", :password "<PASSWORD>"}) (def +hikari-config {:datasource-classname "org.postgresql.ds.PGSimpleDataSource" :username "everest" :password "<PASSWORD>" :database-name "everest" :server-name "localhost" :port-number 3334 :pool-name "everest"}) (defstate pg+ :start (doto (pg/make {:version "9.5.7-1"}) (pg/start! +pg-config)) :stop (pg/stop! pg+)) (defstate pool+ :start (hikari/make-datasource +hikari-config) :stop (hikari/close-datasource pool+)) (defstate pg-schema+ :start (pg.schema/migrate! pool+ {:type "bytea"}) :stop (pg.schema/drop! pool+)) (defn- wrap-edn-utf8-bytes [store] (let [generate-fn #(-> % pr-str (.getBytes "UTF-8")) parse-fn #(if (zero? (alength %)) {} (-> % (String.) read-string))] (store.middleware/wrap-store store (fn [e] (-> e (update :everest.event/data generate-fn) (update :everest.event/metadata generate-fn))) (fn [e] (-> e (update :everest.event/data parse-fn) (update :everest.event/metadata parse-fn)))))) (defstate store+ :start (-> (pg.store/create-store pool+ {:everest.pg.store/event-data-type :bytea}) (wrap-edn-utf8-bytes) #_(json.store.middleware/wrap-cheshire-json {}))) (defstate notifications+ :start (pg.poll-notify/create-notification-source pool+ {}) :stop (.close notifications+)) (defstate subscriptions+ :start (subscriptions/create-subscription-source store+ (pg.poll-notify/notifications notifications+) {}) :stop (.close subscriptions+)) (defn- event-handler [handler-name handler-fn] (-> handler-fn (handler.middleware/wrap-state-atom {}) (json.handler.middleware/wrap-cheshire-json {}) (pg.handler.middleware/wrap-json-state {}) (pg.handler.middleware/wrap-state {:handler.middleware/catch-up-upsert-batch-size 500 :handler.middleware/handler-type (name handler-name) :handler.middleware/handler-id (name handler-name)}) (pg.handler.middleware/wrap-tx {:handler.middleware/tx-during-catch-up? false}) (pg.handler.middleware/wrap-connection {:handler.middleware/db pool+}))) (defn- init-handler! [id pos] (pg.handler.store/update! pool+ {:pg.handler/type id :pg.handler/id (name id) :pg.handler/position pos})) (defstate catch-up-executor+ :start (java.util.concurrent.Executors/newFixedThreadPool 2) :stop (.shutdownNow catch-up-executor+)) (defn- run-with [sub handler] (.execute ^java.util.concurrent.Executor catch-up-executor+ #(m.s/consume handler sub))) (defn- init-and-subscribe-handler! [f stream type pos] (let [type (name type) _ (init-handler! type pos) sub (pg.handler.store/subscribe subscriptions+ pool+ stream type {})] (run-with sub (event-handler type f)) sub)) (defstate handler-all+ :start (-> (fn [{:everest.event/keys [stream type position] :as event}] (let [{:handler/keys [id state]} event] (log/info id stream "->" type "@" position ">" @state) (swap! state (fnil inc 0)))) (init-and-subscribe-handler! :all 'TestHandlerAll 0)) :stop (m.s/close! handler-all+)) (defstate handler-stream+ :start (-> (fn [{:everest.event/keys [stream type position] :as event}] (let [{:handler/keys [id state]} event] (log/info id stream "->" type "@" position ">" @state) (swap! state (fnil inc 0)))) (init-and-subscribe-handler! "test-stream" 'TestHandlerStream 5)) :stop (m.s/close! handler-stream+)) (defn- read-all-events [] (log/info "EVENTS IN STORE>>\n" (with-out-str (-> (store/read-stream-forward store+ :all nil 10) (pprint))))) (defn main [] (try (mount/start) (let [all-sub (store/subscribe subscriptions+ :all :everest.subscription.events/all {})] (m.s/consume (fn [e] (log/info "GOT EVENT>>" (with-out-str (pprint e)))) all-sub) (read-all-events) (->> (for [i (range 1)] {:everest.event/type 'TestEvent :everest.event/data {:string "string" :int i :double 1.0 :boolean true :date (java.util.Date.)} :everest.event/metadata {:user "test-user"}}) (store/append-events! store+ "test-stream" :everest.stream.version/any)) ;; allow the notifications to propagate (Thread/sleep 1000) (read-all-events)) (finally (mount/stop))))
true
(ns app (:require [everest.json.handler.middleware :as json.handler.middleware] [everest.json.store.middleware :as json.store.middleware] [everest.pg.store :as pg.store] [everest.pg.schema :as pg.schema] [everest.pg.handler.store :as pg.handler.store] [everest.pg.handler.middleware :as pg.handler.middleware] [everest.pg.notification.poll-notify :as pg.poll-notify] [everest.handler.middleware :as handler.middleware] [everest.handler :as handler] [everest.store :as store] [everest.store.middleware :as store.middleware] [everest.store.subscription :as subscriptions] [clojure.tools.logging :as log] [clojure.pprint :as pprint :refer [pprint]] [embedded-pg :as pg] [hikari-cp.core :as hikari] [manifold.stream :as m.s] [mount.core :as mount :refer [defstate]])) (def +pg-config {:host "localhost", :port 3334, :db-name "everest" :user "everest", :password "PI:PASSWORD:<PASSWORD>END_PI"}) (def +hikari-config {:datasource-classname "org.postgresql.ds.PGSimpleDataSource" :username "everest" :password "PI:PASSWORD:<PASSWORD>END_PI" :database-name "everest" :server-name "localhost" :port-number 3334 :pool-name "everest"}) (defstate pg+ :start (doto (pg/make {:version "9.5.7-1"}) (pg/start! +pg-config)) :stop (pg/stop! pg+)) (defstate pool+ :start (hikari/make-datasource +hikari-config) :stop (hikari/close-datasource pool+)) (defstate pg-schema+ :start (pg.schema/migrate! pool+ {:type "bytea"}) :stop (pg.schema/drop! pool+)) (defn- wrap-edn-utf8-bytes [store] (let [generate-fn #(-> % pr-str (.getBytes "UTF-8")) parse-fn #(if (zero? (alength %)) {} (-> % (String.) read-string))] (store.middleware/wrap-store store (fn [e] (-> e (update :everest.event/data generate-fn) (update :everest.event/metadata generate-fn))) (fn [e] (-> e (update :everest.event/data parse-fn) (update :everest.event/metadata parse-fn)))))) (defstate store+ :start (-> (pg.store/create-store pool+ {:everest.pg.store/event-data-type :bytea}) (wrap-edn-utf8-bytes) #_(json.store.middleware/wrap-cheshire-json {}))) (defstate notifications+ :start (pg.poll-notify/create-notification-source pool+ {}) :stop (.close notifications+)) (defstate subscriptions+ :start (subscriptions/create-subscription-source store+ (pg.poll-notify/notifications notifications+) {}) :stop (.close subscriptions+)) (defn- event-handler [handler-name handler-fn] (-> handler-fn (handler.middleware/wrap-state-atom {}) (json.handler.middleware/wrap-cheshire-json {}) (pg.handler.middleware/wrap-json-state {}) (pg.handler.middleware/wrap-state {:handler.middleware/catch-up-upsert-batch-size 500 :handler.middleware/handler-type (name handler-name) :handler.middleware/handler-id (name handler-name)}) (pg.handler.middleware/wrap-tx {:handler.middleware/tx-during-catch-up? false}) (pg.handler.middleware/wrap-connection {:handler.middleware/db pool+}))) (defn- init-handler! [id pos] (pg.handler.store/update! pool+ {:pg.handler/type id :pg.handler/id (name id) :pg.handler/position pos})) (defstate catch-up-executor+ :start (java.util.concurrent.Executors/newFixedThreadPool 2) :stop (.shutdownNow catch-up-executor+)) (defn- run-with [sub handler] (.execute ^java.util.concurrent.Executor catch-up-executor+ #(m.s/consume handler sub))) (defn- init-and-subscribe-handler! [f stream type pos] (let [type (name type) _ (init-handler! type pos) sub (pg.handler.store/subscribe subscriptions+ pool+ stream type {})] (run-with sub (event-handler type f)) sub)) (defstate handler-all+ :start (-> (fn [{:everest.event/keys [stream type position] :as event}] (let [{:handler/keys [id state]} event] (log/info id stream "->" type "@" position ">" @state) (swap! state (fnil inc 0)))) (init-and-subscribe-handler! :all 'TestHandlerAll 0)) :stop (m.s/close! handler-all+)) (defstate handler-stream+ :start (-> (fn [{:everest.event/keys [stream type position] :as event}] (let [{:handler/keys [id state]} event] (log/info id stream "->" type "@" position ">" @state) (swap! state (fnil inc 0)))) (init-and-subscribe-handler! "test-stream" 'TestHandlerStream 5)) :stop (m.s/close! handler-stream+)) (defn- read-all-events [] (log/info "EVENTS IN STORE>>\n" (with-out-str (-> (store/read-stream-forward store+ :all nil 10) (pprint))))) (defn main [] (try (mount/start) (let [all-sub (store/subscribe subscriptions+ :all :everest.subscription.events/all {})] (m.s/consume (fn [e] (log/info "GOT EVENT>>" (with-out-str (pprint e)))) all-sub) (read-all-events) (->> (for [i (range 1)] {:everest.event/type 'TestEvent :everest.event/data {:string "string" :int i :double 1.0 :boolean true :date (java.util.Date.)} :everest.event/metadata {:user "test-user"}}) (store/append-events! store+ "test-stream" :everest.stream.version/any)) ;; allow the notifications to propagate (Thread/sleep 1000) (read-all-events)) (finally (mount/stop))))
[ { "context": "NPJPfvnRweFmC4-OxvYhzao/edit?resourcekey#gid=1308791289\")\n\n(defn configure-survey-results\n [google-co", "end": 597, "score": 0.5490709543228149, "start": 595, "tag": "KEY", "value": "91" } ]
src/main/clojure/edmondson/google_forms.clj
krukow/edmondson
3
(ns edmondson.google-forms (:require [edmondson.config :as cfg] [edmondson.google-api :as api] [edmondson.survey-analysis :as analysis] [edmondson.survey-model :as model])) (defn normalize-responses [survey-questions responses] (map-indexed (fn [n response] {:responseId n :meta-data {} :answers (zipmap survey-questions response)}) responses)) (def default-results-url "https://docs.google.com/spreadsheets/d/1S_p5d9YrPg1_sawbhhTRNPJPfvnRweFmC4-OxvYhzao/edit?resourcekey#gid=1308791289") (defn configure-survey-results [google-config survey-model] (binding [cfg/*credentials-json-path-override* (or (:credentials google-config) (cfg/environment-config cfg/credentials-json-path-env "credentials.json"))] (let [total-team-size (Integer/parseInt (cfg/environment-config "NUM_PARTICIPANTS" "25") 10) team-name (cfg/environment-config "TEAM_NAME" "Spidercats") spreadsheetUrl (cfg/environment-config "RESULTS_URL" default-results-url) spreadsheetId (let [url-path (.getPath (java.net.URL. spreadsheetUrl)) id-action-segment (last (clojure.string/split url-path #"/spreadsheets/d/"))] ;; "1QkBeMNGfsHHga85c-UsLAwnpmz7QyhvFK_n31CzDe7c/edit" (first (clojure.string/split id-action-segment #"/"))) tab-name (cfg/environment-config "TAB_NAME" "Form Responses 1") spreadsheet-range (cfg/environment-config "SPREADSHEET_RANGE" (str tab-name "!B:Z")) ;; where the answers are survey-results (api/eval-range google-config spreadsheetId spreadsheet-range) questions (first survey-results) answers (rest survey-results) num-responses (count answers) scored-responses (analysis/score-responses survey-model (normalize-responses questions answers)) model-index (model/index-questions survey-model) ] {:scored-responses scored-responses :aggregate-results (analysis/aggregate-scores survey-model scored-responses) :model-index model-index :num-responses num-responses :participation-rate (/ num-responses (float total-team-size)) :team-name team-name :team-size total-team-size})))
88386
(ns edmondson.google-forms (:require [edmondson.config :as cfg] [edmondson.google-api :as api] [edmondson.survey-analysis :as analysis] [edmondson.survey-model :as model])) (defn normalize-responses [survey-questions responses] (map-indexed (fn [n response] {:responseId n :meta-data {} :answers (zipmap survey-questions response)}) responses)) (def default-results-url "https://docs.google.com/spreadsheets/d/1S_p5d9YrPg1_sawbhhTRNPJPfvnRweFmC4-OxvYhzao/edit?resourcekey#gid=13087<KEY>289") (defn configure-survey-results [google-config survey-model] (binding [cfg/*credentials-json-path-override* (or (:credentials google-config) (cfg/environment-config cfg/credentials-json-path-env "credentials.json"))] (let [total-team-size (Integer/parseInt (cfg/environment-config "NUM_PARTICIPANTS" "25") 10) team-name (cfg/environment-config "TEAM_NAME" "Spidercats") spreadsheetUrl (cfg/environment-config "RESULTS_URL" default-results-url) spreadsheetId (let [url-path (.getPath (java.net.URL. spreadsheetUrl)) id-action-segment (last (clojure.string/split url-path #"/spreadsheets/d/"))] ;; "1QkBeMNGfsHHga85c-UsLAwnpmz7QyhvFK_n31CzDe7c/edit" (first (clojure.string/split id-action-segment #"/"))) tab-name (cfg/environment-config "TAB_NAME" "Form Responses 1") spreadsheet-range (cfg/environment-config "SPREADSHEET_RANGE" (str tab-name "!B:Z")) ;; where the answers are survey-results (api/eval-range google-config spreadsheetId spreadsheet-range) questions (first survey-results) answers (rest survey-results) num-responses (count answers) scored-responses (analysis/score-responses survey-model (normalize-responses questions answers)) model-index (model/index-questions survey-model) ] {:scored-responses scored-responses :aggregate-results (analysis/aggregate-scores survey-model scored-responses) :model-index model-index :num-responses num-responses :participation-rate (/ num-responses (float total-team-size)) :team-name team-name :team-size total-team-size})))
true
(ns edmondson.google-forms (:require [edmondson.config :as cfg] [edmondson.google-api :as api] [edmondson.survey-analysis :as analysis] [edmondson.survey-model :as model])) (defn normalize-responses [survey-questions responses] (map-indexed (fn [n response] {:responseId n :meta-data {} :answers (zipmap survey-questions response)}) responses)) (def default-results-url "https://docs.google.com/spreadsheets/d/1S_p5d9YrPg1_sawbhhTRNPJPfvnRweFmC4-OxvYhzao/edit?resourcekey#gid=13087PI:KEY:<KEY>END_PI289") (defn configure-survey-results [google-config survey-model] (binding [cfg/*credentials-json-path-override* (or (:credentials google-config) (cfg/environment-config cfg/credentials-json-path-env "credentials.json"))] (let [total-team-size (Integer/parseInt (cfg/environment-config "NUM_PARTICIPANTS" "25") 10) team-name (cfg/environment-config "TEAM_NAME" "Spidercats") spreadsheetUrl (cfg/environment-config "RESULTS_URL" default-results-url) spreadsheetId (let [url-path (.getPath (java.net.URL. spreadsheetUrl)) id-action-segment (last (clojure.string/split url-path #"/spreadsheets/d/"))] ;; "1QkBeMNGfsHHga85c-UsLAwnpmz7QyhvFK_n31CzDe7c/edit" (first (clojure.string/split id-action-segment #"/"))) tab-name (cfg/environment-config "TAB_NAME" "Form Responses 1") spreadsheet-range (cfg/environment-config "SPREADSHEET_RANGE" (str tab-name "!B:Z")) ;; where the answers are survey-results (api/eval-range google-config spreadsheetId spreadsheet-range) questions (first survey-results) answers (rest survey-results) num-responses (count answers) scored-responses (analysis/score-responses survey-model (normalize-responses questions answers)) model-index (model/index-questions survey-model) ] {:scored-responses scored-responses :aggregate-results (analysis/aggregate-scores survey-model scored-responses) :model-index model-index :num-responses num-responses :participation-rate (/ num-responses (float total-team-size)) :team-name team-name :team-size total-team-size})))
[ { "context": "pport for encoding FQL data as JSON.\"\n {:author \"Michael McClintock\"}\n (:require\n [clojure.data.json :as json]\n ", "end": 95, "score": 0.9998238682746887, "start": 77, "tag": "NAME", "value": "Michael McClintock" } ]
src/mrmcc3/fauna/json.clj
mrmcc3/faunadb-clj
0
(ns mrmcc3.fauna.json "Support for encoding FQL data as JSON." {:author "Michael McClintock"} (:require [clojure.data.json :as json] [clojure.walk :as walk] [mrmcc3.fauna.query :as q]) (:import (java.util Date Base64) (java.time Instant LocalDate) (java.time.format DateTimeFormatter))) ;; FQL fundamentally deals with richer information then JSON provides. ;; This is a flaw in JSON and means that we have to overload JSON types ;; (the canonical FQL impl. chooses to overload JSON objects). ;; The overloading is needed to support ;; 1. Additional primitives. That is FQL special types: ;; Byte (byte[]) -> {"@bytes" "base64 url encoded string"} ;; Date (LocalDate) -> {"@date" "1970-01-01"} ;; Timestamp (Instant) -> {"@ts" "1970-01-01T00:00:00Z"} ;; 2. FQL function calls. These are represented as plain objects ;; where the keys act as reserved words when decoded by Fauna. ;; (new-id) -> {"new_id" null} ;; 3. Actual data. Encoding maps as plain objects is a problem as it runs the ;; risk of being interpreted as a FQL function call unintentionally. They're ;; handled by nesting. ;; {"new_id" "oops"} -> {"object" {"new_id" "oops"}} ;; clojure.data.json only supports custom types in objects. so it won't work ;; cheshire/jsonista/jackson can handle it and performance is very good ;; but it's low level. We can choose this route later for now let's ;; introduce a postwalk step on both encoding and decoding (defn encode-fql [v] (cond (bytes? v) {"@bytes" (.encodeToString (Base64/getUrlEncoder) v)} (instance? Instant v) {"@ts" (.toString v)} (instance? LocalDate v) {"@date" (.toString v)} (-> v meta :op) v (map? v) {:object (with-meta v {:op true})} :else v)) (defn write-str [data] (json/write-str (walk/postwalk encode-fql data))) (defn decode-ref [{{:keys [collection id database]} "@ref" :as v}] (cond (= collection {"@ref" {:id "databases"}}) (q/database id database) (= collection {"@ref" {:id "collections"}}) (q/collection id database) (= collection {"@ref" {:id "functions"}}) (q/function id database) (= collection {"@ref" {:id "indexes"}}) (q/index id database) (= collection {"@ref" {:id "roles"}}) (q/role id database) collection (q/ref collection id) :else v)) (defn decode-fql [v] (cond (not (map? v)) v (contains? v "@bytes") (.decode (Base64/getUrlDecoder) ^String (get v "@bytes")) (contains? v "@ts") (Instant/from (.parse (DateTimeFormatter/ISO_OFFSET_DATE_TIME) (get v "@ts"))) (contains? v "@date") (LocalDate/parse (get v "@date")) (contains? v "@ref") (decode-ref v) :else v)) (defn key-fn [k] (if (.startsWith k "@") k (keyword k))) (defn read-str [s] (walk/postwalk decode-fql (json/read-str s :key-fn key-fn)))
28738
(ns mrmcc3.fauna.json "Support for encoding FQL data as JSON." {:author "<NAME>"} (:require [clojure.data.json :as json] [clojure.walk :as walk] [mrmcc3.fauna.query :as q]) (:import (java.util Date Base64) (java.time Instant LocalDate) (java.time.format DateTimeFormatter))) ;; FQL fundamentally deals with richer information then JSON provides. ;; This is a flaw in JSON and means that we have to overload JSON types ;; (the canonical FQL impl. chooses to overload JSON objects). ;; The overloading is needed to support ;; 1. Additional primitives. That is FQL special types: ;; Byte (byte[]) -> {"@bytes" "base64 url encoded string"} ;; Date (LocalDate) -> {"@date" "1970-01-01"} ;; Timestamp (Instant) -> {"@ts" "1970-01-01T00:00:00Z"} ;; 2. FQL function calls. These are represented as plain objects ;; where the keys act as reserved words when decoded by Fauna. ;; (new-id) -> {"new_id" null} ;; 3. Actual data. Encoding maps as plain objects is a problem as it runs the ;; risk of being interpreted as a FQL function call unintentionally. They're ;; handled by nesting. ;; {"new_id" "oops"} -> {"object" {"new_id" "oops"}} ;; clojure.data.json only supports custom types in objects. so it won't work ;; cheshire/jsonista/jackson can handle it and performance is very good ;; but it's low level. We can choose this route later for now let's ;; introduce a postwalk step on both encoding and decoding (defn encode-fql [v] (cond (bytes? v) {"@bytes" (.encodeToString (Base64/getUrlEncoder) v)} (instance? Instant v) {"@ts" (.toString v)} (instance? LocalDate v) {"@date" (.toString v)} (-> v meta :op) v (map? v) {:object (with-meta v {:op true})} :else v)) (defn write-str [data] (json/write-str (walk/postwalk encode-fql data))) (defn decode-ref [{{:keys [collection id database]} "@ref" :as v}] (cond (= collection {"@ref" {:id "databases"}}) (q/database id database) (= collection {"@ref" {:id "collections"}}) (q/collection id database) (= collection {"@ref" {:id "functions"}}) (q/function id database) (= collection {"@ref" {:id "indexes"}}) (q/index id database) (= collection {"@ref" {:id "roles"}}) (q/role id database) collection (q/ref collection id) :else v)) (defn decode-fql [v] (cond (not (map? v)) v (contains? v "@bytes") (.decode (Base64/getUrlDecoder) ^String (get v "@bytes")) (contains? v "@ts") (Instant/from (.parse (DateTimeFormatter/ISO_OFFSET_DATE_TIME) (get v "@ts"))) (contains? v "@date") (LocalDate/parse (get v "@date")) (contains? v "@ref") (decode-ref v) :else v)) (defn key-fn [k] (if (.startsWith k "@") k (keyword k))) (defn read-str [s] (walk/postwalk decode-fql (json/read-str s :key-fn key-fn)))
true
(ns mrmcc3.fauna.json "Support for encoding FQL data as JSON." {:author "PI:NAME:<NAME>END_PI"} (:require [clojure.data.json :as json] [clojure.walk :as walk] [mrmcc3.fauna.query :as q]) (:import (java.util Date Base64) (java.time Instant LocalDate) (java.time.format DateTimeFormatter))) ;; FQL fundamentally deals with richer information then JSON provides. ;; This is a flaw in JSON and means that we have to overload JSON types ;; (the canonical FQL impl. chooses to overload JSON objects). ;; The overloading is needed to support ;; 1. Additional primitives. That is FQL special types: ;; Byte (byte[]) -> {"@bytes" "base64 url encoded string"} ;; Date (LocalDate) -> {"@date" "1970-01-01"} ;; Timestamp (Instant) -> {"@ts" "1970-01-01T00:00:00Z"} ;; 2. FQL function calls. These are represented as plain objects ;; where the keys act as reserved words when decoded by Fauna. ;; (new-id) -> {"new_id" null} ;; 3. Actual data. Encoding maps as plain objects is a problem as it runs the ;; risk of being interpreted as a FQL function call unintentionally. They're ;; handled by nesting. ;; {"new_id" "oops"} -> {"object" {"new_id" "oops"}} ;; clojure.data.json only supports custom types in objects. so it won't work ;; cheshire/jsonista/jackson can handle it and performance is very good ;; but it's low level. We can choose this route later for now let's ;; introduce a postwalk step on both encoding and decoding (defn encode-fql [v] (cond (bytes? v) {"@bytes" (.encodeToString (Base64/getUrlEncoder) v)} (instance? Instant v) {"@ts" (.toString v)} (instance? LocalDate v) {"@date" (.toString v)} (-> v meta :op) v (map? v) {:object (with-meta v {:op true})} :else v)) (defn write-str [data] (json/write-str (walk/postwalk encode-fql data))) (defn decode-ref [{{:keys [collection id database]} "@ref" :as v}] (cond (= collection {"@ref" {:id "databases"}}) (q/database id database) (= collection {"@ref" {:id "collections"}}) (q/collection id database) (= collection {"@ref" {:id "functions"}}) (q/function id database) (= collection {"@ref" {:id "indexes"}}) (q/index id database) (= collection {"@ref" {:id "roles"}}) (q/role id database) collection (q/ref collection id) :else v)) (defn decode-fql [v] (cond (not (map? v)) v (contains? v "@bytes") (.decode (Base64/getUrlDecoder) ^String (get v "@bytes")) (contains? v "@ts") (Instant/from (.parse (DateTimeFormatter/ISO_OFFSET_DATE_TIME) (get v "@ts"))) (contains? v "@date") (LocalDate/parse (get v "@date")) (contains? v "@ref") (decode-ref v) :else v)) (defn key-fn [k] (if (.startsWith k "@") k (keyword k))) (defn read-str [s] (walk/postwalk decode-fql (json/read-str s :key-fn key-fn)))
[ { "context": " \"Denebola Shippers\"\n \"Eridani Expediters\"\n \"Fomalhaut Freight", "end": 235, "score": 0.5917873382568359, "start": 232, "tag": "NAME", "value": "rid" }, { "context": " \"Eridani Expediters\"\n \"Fomalhaut Freighters\"\n \"Gamma Corvi Cartel\"\n ", "end": 288, "score": 0.9538068771362305, "start": 268, "tag": "NAME", "value": "Fomalhaut Freighters" }, { "context": " \"Fomalhaut Freighters\"\n \"Gamma Corvi Cartel\"\n \"Horologii Holdings\"\n ", "end": 325, "score": 0.9943548440933228, "start": 307, "tag": "NAME", "value": "Gamma Corvi Cartel" }, { "context": " \"Jabbah Journeyers\"\n \"Kapteyn's Outfitters\"\n \"Luyten, Ltd.\"])\n", "end": 457, "score": 0.729702353477478, "start": 453, "tag": "NAME", "value": "apte" }, { "context": " \"Jabbah Journeyers\"\n \"Kapteyn's Outfitters\"\n \"Luyten, Ltd.\"])\n\n(de", "end": 461, "score": 0.6917610168457031, "start": 460, "tag": "NAME", "value": "s" }, { "context": " work for ticket #36:\n;; https://github.com/clojusc/clj-starlanes/issues/36\n\n(def xgrid-start-name \"a", "end": 942, "score": 0.9996435642242432, "start": 935, "tag": "USERNAME", "value": "clojusc" } ]
src/starlanes/const.clj
oubiwann/clj-starlanes
1
(ns starlanes.const) (def debug true) (def game-title "Star Traders") (def companies ["Altair Starways" "Betelgeuse, Ltd." "Capella Cargo Co." "Denebola Shippers" "Eridani Expediters" "Fomalhaut Freighters" "Gamma Corvi Cartel" "Horologii Holdings" "Innes Industries" "Jabbah Journeyers" "Kapteyn's Outfitters" "Luyten, Ltd."]) (def max-companies 5) (def items {:star "*" :empty "." :outpost "+"}) (def item-colors {:star :yellow :empty :dark-grey :outpost :light-green :company :light-cyan}) (def outpost-char "+") (def grid-spaces 3) ;; XXX it might make sense to move this into the layout namespace as part of ;; the work for ticket #36: ;; https://github.com/clojusc/clj-starlanes/issues/36 (def xgrid-start-name "a") (def xgrid-end-name "e") (def xgrid-start (int (.charAt xgrid-start-name 0))) (def xgrid-end (inc (int (.charAt xgrid-end-name 0)))) (def xgrid-size (- xgrid-end xgrid-start)) (def xgrid (map (comp str char) (range xgrid-start xgrid-end))) (def ygrid-start-name "1") (def ygrid-end-name "5") (def ygrid-start (Integer. ygrid-start-name)) (def ygrid-end-prime (Integer. ygrid-end-name)) (def ygrid-pad (count (str ygrid-end-prime))) (defn make-y-coord [y] (format (str "%0" ygrid-pad "d") (Integer. y))) (def ygrid-end (+ ygrid-start ygrid-end-prime)) (def ygrid (map str (range ygrid-start ygrid-end))) (def horiz-title-heading-char "=") (def horiz-divider-char "-") (def horiz-divider-init (str "+" horiz-divider-char)) (def horiz-divider-term (str horiz-divider-char "+")) (def vert-divider-char "|") (def row-heading-init (str \space vert-divider-char \space)) (def row-heading-term (str \space vert-divider-char)) (def win-by-turns? false) (def max-turns 2) (def seed 314) ;; max-moves-choices is the maximum allowed number of randomly-generated moves ;; that will be offered to the player as options during a turn. By default, ;; users are presented with 5 choices from which they can select their move. (def max-moves-choices 5) (def star-rate 0.05) (def share-modifier-star 500) (def share-modifier-base 100) (def founding-shares 5) (def dividend-percentage 0.1) (def dividend-multiplier (/ dividend-percentage 100)) (def max-stock-value 3000) (def currency-name "credit") (def continue-prompt "Press <RETURN> to continue ...") (def confirm-prompt "Are you sure? [N/y] ") ;; terminal color components (def open-color "\33[") (def close-color "m") (def start-color "\33[") (def end-color "\33[m") (def color-info {:dark "0" :light "1" :foreground "3" :background "4" :black "0" :red "1" :green "2" :yellow "3" :blue "4" :magenta "5" :cyan "6" :white "7"}) (def color-map {:black [:black :dark] :white [:white :light] :dark-grey [:black :light] :light-grey [:white :dark] :red [:red :dark] :dark-red [:red :dark] :green [:green :dark] :dark-green [:green :dark] :yellow [:yellow :dark] :dark-yellow [:yellow :dark] :blue [:blue :dark] :dark-blue [:blue :dark] :magenta [:magenta :dark] :cyan [:cyan :dark] :light-red [:red :light] :light-green [:green :light] :light-yellow [:yellow :light] :light-blue [:blue :light] :light-magenta [:magenta :light] :light-cyan [:cyan :light]})
69607
(ns starlanes.const) (def debug true) (def game-title "Star Traders") (def companies ["Altair Starways" "Betelgeuse, Ltd." "Capella Cargo Co." "Denebola Shippers" "E<NAME>ani Expediters" "<NAME>" "<NAME>" "Horologii Holdings" "Innes Industries" "Jabbah Journeyers" "K<NAME>yn'<NAME> Outfitters" "Luyten, Ltd."]) (def max-companies 5) (def items {:star "*" :empty "." :outpost "+"}) (def item-colors {:star :yellow :empty :dark-grey :outpost :light-green :company :light-cyan}) (def outpost-char "+") (def grid-spaces 3) ;; XXX it might make sense to move this into the layout namespace as part of ;; the work for ticket #36: ;; https://github.com/clojusc/clj-starlanes/issues/36 (def xgrid-start-name "a") (def xgrid-end-name "e") (def xgrid-start (int (.charAt xgrid-start-name 0))) (def xgrid-end (inc (int (.charAt xgrid-end-name 0)))) (def xgrid-size (- xgrid-end xgrid-start)) (def xgrid (map (comp str char) (range xgrid-start xgrid-end))) (def ygrid-start-name "1") (def ygrid-end-name "5") (def ygrid-start (Integer. ygrid-start-name)) (def ygrid-end-prime (Integer. ygrid-end-name)) (def ygrid-pad (count (str ygrid-end-prime))) (defn make-y-coord [y] (format (str "%0" ygrid-pad "d") (Integer. y))) (def ygrid-end (+ ygrid-start ygrid-end-prime)) (def ygrid (map str (range ygrid-start ygrid-end))) (def horiz-title-heading-char "=") (def horiz-divider-char "-") (def horiz-divider-init (str "+" horiz-divider-char)) (def horiz-divider-term (str horiz-divider-char "+")) (def vert-divider-char "|") (def row-heading-init (str \space vert-divider-char \space)) (def row-heading-term (str \space vert-divider-char)) (def win-by-turns? false) (def max-turns 2) (def seed 314) ;; max-moves-choices is the maximum allowed number of randomly-generated moves ;; that will be offered to the player as options during a turn. By default, ;; users are presented with 5 choices from which they can select their move. (def max-moves-choices 5) (def star-rate 0.05) (def share-modifier-star 500) (def share-modifier-base 100) (def founding-shares 5) (def dividend-percentage 0.1) (def dividend-multiplier (/ dividend-percentage 100)) (def max-stock-value 3000) (def currency-name "credit") (def continue-prompt "Press <RETURN> to continue ...") (def confirm-prompt "Are you sure? [N/y] ") ;; terminal color components (def open-color "\33[") (def close-color "m") (def start-color "\33[") (def end-color "\33[m") (def color-info {:dark "0" :light "1" :foreground "3" :background "4" :black "0" :red "1" :green "2" :yellow "3" :blue "4" :magenta "5" :cyan "6" :white "7"}) (def color-map {:black [:black :dark] :white [:white :light] :dark-grey [:black :light] :light-grey [:white :dark] :red [:red :dark] :dark-red [:red :dark] :green [:green :dark] :dark-green [:green :dark] :yellow [:yellow :dark] :dark-yellow [:yellow :dark] :blue [:blue :dark] :dark-blue [:blue :dark] :magenta [:magenta :dark] :cyan [:cyan :dark] :light-red [:red :light] :light-green [:green :light] :light-yellow [:yellow :light] :light-blue [:blue :light] :light-magenta [:magenta :light] :light-cyan [:cyan :light]})
true
(ns starlanes.const) (def debug true) (def game-title "Star Traders") (def companies ["Altair Starways" "Betelgeuse, Ltd." "Capella Cargo Co." "Denebola Shippers" "EPI:NAME:<NAME>END_PIani Expediters" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "Horologii Holdings" "Innes Industries" "Jabbah Journeyers" "KPI:NAME:<NAME>END_PIyn'PI:NAME:<NAME>END_PI Outfitters" "Luyten, Ltd."]) (def max-companies 5) (def items {:star "*" :empty "." :outpost "+"}) (def item-colors {:star :yellow :empty :dark-grey :outpost :light-green :company :light-cyan}) (def outpost-char "+") (def grid-spaces 3) ;; XXX it might make sense to move this into the layout namespace as part of ;; the work for ticket #36: ;; https://github.com/clojusc/clj-starlanes/issues/36 (def xgrid-start-name "a") (def xgrid-end-name "e") (def xgrid-start (int (.charAt xgrid-start-name 0))) (def xgrid-end (inc (int (.charAt xgrid-end-name 0)))) (def xgrid-size (- xgrid-end xgrid-start)) (def xgrid (map (comp str char) (range xgrid-start xgrid-end))) (def ygrid-start-name "1") (def ygrid-end-name "5") (def ygrid-start (Integer. ygrid-start-name)) (def ygrid-end-prime (Integer. ygrid-end-name)) (def ygrid-pad (count (str ygrid-end-prime))) (defn make-y-coord [y] (format (str "%0" ygrid-pad "d") (Integer. y))) (def ygrid-end (+ ygrid-start ygrid-end-prime)) (def ygrid (map str (range ygrid-start ygrid-end))) (def horiz-title-heading-char "=") (def horiz-divider-char "-") (def horiz-divider-init (str "+" horiz-divider-char)) (def horiz-divider-term (str horiz-divider-char "+")) (def vert-divider-char "|") (def row-heading-init (str \space vert-divider-char \space)) (def row-heading-term (str \space vert-divider-char)) (def win-by-turns? false) (def max-turns 2) (def seed 314) ;; max-moves-choices is the maximum allowed number of randomly-generated moves ;; that will be offered to the player as options during a turn. By default, ;; users are presented with 5 choices from which they can select their move. (def max-moves-choices 5) (def star-rate 0.05) (def share-modifier-star 500) (def share-modifier-base 100) (def founding-shares 5) (def dividend-percentage 0.1) (def dividend-multiplier (/ dividend-percentage 100)) (def max-stock-value 3000) (def currency-name "credit") (def continue-prompt "Press <RETURN> to continue ...") (def confirm-prompt "Are you sure? [N/y] ") ;; terminal color components (def open-color "\33[") (def close-color "m") (def start-color "\33[") (def end-color "\33[m") (def color-info {:dark "0" :light "1" :foreground "3" :background "4" :black "0" :red "1" :green "2" :yellow "3" :blue "4" :magenta "5" :cyan "6" :white "7"}) (def color-map {:black [:black :dark] :white [:white :light] :dark-grey [:black :light] :light-grey [:white :dark] :red [:red :dark] :dark-red [:red :dark] :green [:green :dark] :dark-green [:green :dark] :yellow [:yellow :dark] :dark-yellow [:yellow :dark] :blue [:blue :dark] :dark-blue [:blue :dark] :magenta [:magenta :dark] :cyan [:cyan :dark] :light-red [:red :light] :light-green [:green :light] :light-yellow [:yellow :light] :light-blue [:blue :light] :light-magenta [:magenta :light] :light-cyan [:cyan :light]})
[ { "context": "]\n\n :users\n [{:id \"100\"\n :name \"Burt\"\n :age 23\n :projects #{\"1\" \"2\"}}\n\n ", "end": 782, "score": 0.9997771978378296, "start": 778, "tag": "NAME", "value": "Burt" }, { "context": "#{\"1\" \"2\"}}\n\n {:id \"200\"\n :name \"Earnie\"\n :age 32\n :projects #{\"2\"}}]})\n\n(de", "end": 873, "score": 0.9997771382331848, "start": 867, "tag": "NAME", "value": "Earnie" } ]
GraphQL/graphql-toy/src/clj/graphql_toy/routes/services/graphql.clj
zclj/replication-packages
8
(ns graphql-toy.routes.services.graphql (:require [com.walmartlabs.lacinia.util :refer [attach-resolvers]] [com.walmartlabs.lacinia.schema :as schema] [com.walmartlabs.lacinia :as lacinia] [clojure.data.json :as json] [clojure.edn :as edn] [clojure.java.io :as io] [ring.util.http-response :refer :all] [mount.core :refer [defstate]])) (def db {:projects [{:id "1" :name "Project 1" :description "Awesome project!" :owner "100" :members #{"100" "200"}} {:id "2" ;; DB error vector instead of scalar :name "Project 2" :description "Not an awesome project!" :owner "200" :members #{"200"}}] :users [{:id "100" :name "Burt" :age 23 :projects #{"1" "2"}} {:id "200" :name "Earnie" :age 32 :projects #{"2"}}]}) (defn resolve-project-by-id [projects context args value] (let [{:keys [id]} args] ;; Example bug 1 - Syntax misstake ;; (first (filter #(= (:id %) id)) projects) ;; Example bug 2 - Give "foo", input validation ;; (nth projects (Integer/parseInt id)) ;; Example bug 3 - Input type validation bug ;; (nth projects id) ;; Example bug 4 - Using the wrong field ;; (first (filter #(= (:name %) id) projects)) ;; Example bug 5 - wrong type "error" ;; (assoc (first (filter #(= (:id %) id) projects)) :name [:a :b]) ;; Example bug 6 - IndexOutOfBounds ;;(nth projects (Integer/parseInt id)) ;; Correct implementation (first (filter #(= (:id %) id) projects)) )) (defn resolve-project-owner [users context args project] (let [owner (:owner project)] ;; Example bug 1 - Syntax misstake ;;(first (filter #(= (:id %) owner)) users) ;; Example bug 2 - Using the wrong field ;; (first (filter #(= (:name %) owner) project)) ;; Example bug 3 - wrong type "error" ;;(assoc (first (filter #(= (:id %) owner) project)) :name [:a :b]) ;; Correct implementation (first (filter #(= (:id %) owner) users)) )) (defn resolve-project-members [users context args project] (let [members (:members project)] ;; Example bug 1 - logic error ;; (filter #(contains? members) users) ;; Example bug 2 - Using the wrong field ;; (filter #(contains? members (:name %)) users) ;; Example bug 3 - wrong type "errors" ;;(filter #(contains? members (:id %))) ;; Correct implementation (filter #(contains? members (:id %)) users) )) (defn resolve-user-projects [projects context args user] (let [user-projects (:projects user)] ;; Example bug 1 - Syntax Error ;; (filter #(contains? user-projects) projects) ;; Example bug 2 - Using the wrong field ;; (filter #(contains? user-projects (:name %)) projects) ;; Example bug 3 - wrong type "errors" ;; (filter #(contains? user-projects (:id %))) ;; Correct implementation (filter #(contains? user-projects (:id %)) projects) )) (defstate compiled-schema :start (-> "graphql/schema.edn" io/resource slurp edn/read-string (attach-resolvers {:query/project (partial resolve-project-by-id (:projects db)) :user/projects (partial resolve-user-projects (:projects db)) :project/members (partial resolve-project-members (:users db)) :project/owner (partial resolve-project-owner (:users db))}) schema/compile)) (defn format-params [query] (let [parsed (json/read-str query)] ;;-> placeholder - need to ensure query meets graphql syntax (str "query { hero(id: \"1000\") { name appears_in }}"))) (defn execute-request [query] (let [vars nil context nil] (-> (lacinia/execute compiled-schema query vars context) (json/write-str))))
10661
(ns graphql-toy.routes.services.graphql (:require [com.walmartlabs.lacinia.util :refer [attach-resolvers]] [com.walmartlabs.lacinia.schema :as schema] [com.walmartlabs.lacinia :as lacinia] [clojure.data.json :as json] [clojure.edn :as edn] [clojure.java.io :as io] [ring.util.http-response :refer :all] [mount.core :refer [defstate]])) (def db {:projects [{:id "1" :name "Project 1" :description "Awesome project!" :owner "100" :members #{"100" "200"}} {:id "2" ;; DB error vector instead of scalar :name "Project 2" :description "Not an awesome project!" :owner "200" :members #{"200"}}] :users [{:id "100" :name "<NAME>" :age 23 :projects #{"1" "2"}} {:id "200" :name "<NAME>" :age 32 :projects #{"2"}}]}) (defn resolve-project-by-id [projects context args value] (let [{:keys [id]} args] ;; Example bug 1 - Syntax misstake ;; (first (filter #(= (:id %) id)) projects) ;; Example bug 2 - Give "foo", input validation ;; (nth projects (Integer/parseInt id)) ;; Example bug 3 - Input type validation bug ;; (nth projects id) ;; Example bug 4 - Using the wrong field ;; (first (filter #(= (:name %) id) projects)) ;; Example bug 5 - wrong type "error" ;; (assoc (first (filter #(= (:id %) id) projects)) :name [:a :b]) ;; Example bug 6 - IndexOutOfBounds ;;(nth projects (Integer/parseInt id)) ;; Correct implementation (first (filter #(= (:id %) id) projects)) )) (defn resolve-project-owner [users context args project] (let [owner (:owner project)] ;; Example bug 1 - Syntax misstake ;;(first (filter #(= (:id %) owner)) users) ;; Example bug 2 - Using the wrong field ;; (first (filter #(= (:name %) owner) project)) ;; Example bug 3 - wrong type "error" ;;(assoc (first (filter #(= (:id %) owner) project)) :name [:a :b]) ;; Correct implementation (first (filter #(= (:id %) owner) users)) )) (defn resolve-project-members [users context args project] (let [members (:members project)] ;; Example bug 1 - logic error ;; (filter #(contains? members) users) ;; Example bug 2 - Using the wrong field ;; (filter #(contains? members (:name %)) users) ;; Example bug 3 - wrong type "errors" ;;(filter #(contains? members (:id %))) ;; Correct implementation (filter #(contains? members (:id %)) users) )) (defn resolve-user-projects [projects context args user] (let [user-projects (:projects user)] ;; Example bug 1 - Syntax Error ;; (filter #(contains? user-projects) projects) ;; Example bug 2 - Using the wrong field ;; (filter #(contains? user-projects (:name %)) projects) ;; Example bug 3 - wrong type "errors" ;; (filter #(contains? user-projects (:id %))) ;; Correct implementation (filter #(contains? user-projects (:id %)) projects) )) (defstate compiled-schema :start (-> "graphql/schema.edn" io/resource slurp edn/read-string (attach-resolvers {:query/project (partial resolve-project-by-id (:projects db)) :user/projects (partial resolve-user-projects (:projects db)) :project/members (partial resolve-project-members (:users db)) :project/owner (partial resolve-project-owner (:users db))}) schema/compile)) (defn format-params [query] (let [parsed (json/read-str query)] ;;-> placeholder - need to ensure query meets graphql syntax (str "query { hero(id: \"1000\") { name appears_in }}"))) (defn execute-request [query] (let [vars nil context nil] (-> (lacinia/execute compiled-schema query vars context) (json/write-str))))
true
(ns graphql-toy.routes.services.graphql (:require [com.walmartlabs.lacinia.util :refer [attach-resolvers]] [com.walmartlabs.lacinia.schema :as schema] [com.walmartlabs.lacinia :as lacinia] [clojure.data.json :as json] [clojure.edn :as edn] [clojure.java.io :as io] [ring.util.http-response :refer :all] [mount.core :refer [defstate]])) (def db {:projects [{:id "1" :name "Project 1" :description "Awesome project!" :owner "100" :members #{"100" "200"}} {:id "2" ;; DB error vector instead of scalar :name "Project 2" :description "Not an awesome project!" :owner "200" :members #{"200"}}] :users [{:id "100" :name "PI:NAME:<NAME>END_PI" :age 23 :projects #{"1" "2"}} {:id "200" :name "PI:NAME:<NAME>END_PI" :age 32 :projects #{"2"}}]}) (defn resolve-project-by-id [projects context args value] (let [{:keys [id]} args] ;; Example bug 1 - Syntax misstake ;; (first (filter #(= (:id %) id)) projects) ;; Example bug 2 - Give "foo", input validation ;; (nth projects (Integer/parseInt id)) ;; Example bug 3 - Input type validation bug ;; (nth projects id) ;; Example bug 4 - Using the wrong field ;; (first (filter #(= (:name %) id) projects)) ;; Example bug 5 - wrong type "error" ;; (assoc (first (filter #(= (:id %) id) projects)) :name [:a :b]) ;; Example bug 6 - IndexOutOfBounds ;;(nth projects (Integer/parseInt id)) ;; Correct implementation (first (filter #(= (:id %) id) projects)) )) (defn resolve-project-owner [users context args project] (let [owner (:owner project)] ;; Example bug 1 - Syntax misstake ;;(first (filter #(= (:id %) owner)) users) ;; Example bug 2 - Using the wrong field ;; (first (filter #(= (:name %) owner) project)) ;; Example bug 3 - wrong type "error" ;;(assoc (first (filter #(= (:id %) owner) project)) :name [:a :b]) ;; Correct implementation (first (filter #(= (:id %) owner) users)) )) (defn resolve-project-members [users context args project] (let [members (:members project)] ;; Example bug 1 - logic error ;; (filter #(contains? members) users) ;; Example bug 2 - Using the wrong field ;; (filter #(contains? members (:name %)) users) ;; Example bug 3 - wrong type "errors" ;;(filter #(contains? members (:id %))) ;; Correct implementation (filter #(contains? members (:id %)) users) )) (defn resolve-user-projects [projects context args user] (let [user-projects (:projects user)] ;; Example bug 1 - Syntax Error ;; (filter #(contains? user-projects) projects) ;; Example bug 2 - Using the wrong field ;; (filter #(contains? user-projects (:name %)) projects) ;; Example bug 3 - wrong type "errors" ;; (filter #(contains? user-projects (:id %))) ;; Correct implementation (filter #(contains? user-projects (:id %)) projects) )) (defstate compiled-schema :start (-> "graphql/schema.edn" io/resource slurp edn/read-string (attach-resolvers {:query/project (partial resolve-project-by-id (:projects db)) :user/projects (partial resolve-user-projects (:projects db)) :project/members (partial resolve-project-members (:users db)) :project/owner (partial resolve-project-owner (:users db))}) schema/compile)) (defn format-params [query] (let [parsed (json/read-str query)] ;;-> placeholder - need to ensure query meets graphql syntax (str "query { hero(id: \"1000\") { name appears_in }}"))) (defn execute-request [query] (let [vars nil context nil] (-> (lacinia/execute compiled-schema query vars context) (json/write-str))))
[ { "context": "5q6uZfIpm0qZbb6Brcfw8S3/wejWolU0Bl1n1Dz/yqvLGxf/XXV6/uOBB75WhFE9V98pIw5Qm18VY6+rlzUnuaTfPvPbiJbh3D9w=", "end": 23154, "score": 0.522358775138855, "start": 23153, "tag": "KEY", "value": "V" }, { "context": "uZfIpm0qZbb6Brcfw8S3/wejWolU0Bl1n1Dz/yqvLGxf/XXV6/uOBB75WhFE9V98pIw5Qm18VY6+rlzUnuaTfPvPbiJbh3D9w=\"})", "end": 23157, "score": 0.5301764607429504, "start": 23156, "tag": "KEY", "value": "u" }, { "context": "Zbb6Brcfw8S3/wejWolU0Bl1n1Dz/yqvLGxf/XXV6/uOBB75WhFE9V98pIw5Qm18VY6+rlzUnuaTfPvPbiJbh3D9w=\"})\n ", "end": 23166, "score": 0.5065925717353821, "start": 23164, "tag": "KEY", "value": "FE" }, { "context": "6Brcfw8S3/wejWolU0Bl1n1Dz/yqvLGxf/XXV6/uOBB75WhFE9V98pIw5Qm18VY6+rlzUnuaTfPvPbiJbh3D9w=\"})\n ", "end": 23169, "score": 0.5454421043395996, "start": 23167, "tag": "KEY", "value": "V9" }, { "context": "8S3/wejWolU0Bl1n1Dz/yqvLGxf/XXV6/uOBB75WhFE9V98pIw5Qm18VY6+rlzUnuaTfPvPbiJbh3D9w=\"})\n ;; ju", "end": 23182, "score": 0.5356324315071106, "start": 23173, "tag": "KEY", "value": "5Qm18VY6+" }, { "context": "0Bl1n1Dz/yqvLGxf/XXV6/uOBB75WhFE9V98pIw5Qm18VY6+rlzUnuaTfPvPbiJbh3D9w=\"})\n ;; just make sure the AP", "end": 23201, "score": 0.5753315091133118, "start": 23184, "tag": "KEY", "value": "zUnuaTfPvPbiJbh3D" } ]
c#-metabase/modules/drivers/googleanalytics/test/metabase/driver/googleanalytics_test.clj
hanakhry/Crime_Admin
0
(ns metabase.driver.googleanalytics-test "Tests for the Google Analytics driver and query processor." (:require [clojure.test :refer :all] [java-time :as t] [medley.core :as m] [metabase.driver :as driver] metabase.driver.googleanalytics [metabase.driver.googleanalytics.execute :as ga.execute] [metabase.driver.googleanalytics.query-processor :as ga.qp] [metabase.models :refer [Card Database Field Table]] [metabase.query-processor :as qp] [metabase.query-processor.context :as qp.context] [metabase.query-processor.store :as qp.store] [metabase.test :as mt] [metabase.test.fixtures :as fixtures] [metabase.test.util :as tu] [metabase.util :as u] [toucan.db :as db])) (comment metabase.driver.googleanalytics/keep-me) (use-fixtures :once (fixtures/initialize :db)) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | MBQL->NATIVE (QUERY -> GA QUERY) | ;;; +----------------------------------------------------------------------------------------------------------------+ (defn- ga-query [inner-query] {:query (merge {:ids "ga:0123456" :dimensions "" :start-date "2005-01-01" :end-date "today" :max-results 10000 :include-empty-rows false} inner-query) :mbql? true}) (defn- mbql->native [query] (binding [qp.store/*store* (atom {:tables {1 #metabase.models.table.TableInstance{:name "0123456" :schema nil :id 1}}})] (driver/mbql->native :googleanalytics (update query :query (partial merge {:source-table 1}))))) (deftest basic-compilation-test (testing "just check that a basic almost-empty MBQL query can be compiled" (is (= (ga-query {}) (mbql->native {})))) (testing "try a basic query with a metric (aggregation)" (is (= (ga-query {:metrics "ga:users"}) (mbql->native {:query {:aggregation [[:metric "ga:users"]]}})))) (testing "query with metric (aggregation) + breakout" (is (= (ga-query {:metrics "ga:users" :dimensions "ga:browser"}) (mbql->native {:query {:aggregation [[:metric "ga:users"]] :breakout [[:field "ga:browser" nil]]}})))) (testing "query w/ segment (filter)" (is (= (ga-query {:segment "gaid::-4"}) (mbql->native {:query {:filter [:segment "gaid::-4"]}})))) (testing "query w/ non-segment filter" (is (= (ga-query {:filters "ga:continent==North America"}) (mbql->native {:query {:filter [:= [:field "ga:continent" nil] [:value "North America"]]}})))) (testing "query w/ segment & non-segment filter" (is (= (ga-query {:filters "ga:continent==North America" :segment "gaid::-4"}) (mbql->native {:query {:filter [:and [:segment "gaid::-4"] [:= [:field "ga:continent" nil] [:value "North America"]]]}}))))) (defn- ga-date-field [unit] [:field "ga:date" {:temporal-unit unit}]) (deftest filter-by-absolute-datetime-test (is (= (ga-query {:start-date "2016-11-08", :end-date "2016-11-08"}) (mbql->native {:query {:filter [:= (ga-date-field :day) [:absolute-datetime (t/local-date "2016-11-08") :day]]}}))) (testing "tests off by one day correction for gt/lt operators (GA doesn't support exclusive ranges)" (is (= (ga-query {:start-date "2016-11-09", :end-date "today"}) (mbql->native {:query {:filter [:> (ga-date-field :day) [:absolute-datetime (t/local-date "2016-11-08") :day]]}}))) (is (= (ga-query {:start-date "2005-01-01", :end-date "2016-10-01"}) (mbql->native {:query {:filter [:< (ga-date-field :day) [:absolute-datetime (t/local-date "2016-10-02") :day]]}}))) (is (= (ga-query {:start-date "2005-01-01", :end-date "2016-10-02"}) (mbql->native {:query {:filter [:<= (ga-date-field :day) [:absolute-datetime (t/local-date "2016-10-02") :day]]}}))) (is (= (ga-query {:start-date "2016-09-10", :end-date "2016-10-01"}) (mbql->native {:query {:filter [:and [:< (ga-date-field :day) [:absolute-datetime (t/local-date "2016-10-02") :day]] [:> (ga-date-field :day) [:absolute-datetime (t/local-date "2016-09-09") :day]]]}}))) (is (= (ga-query {:start-date "2016-09-10", :end-date "2016-10-02"}) (mbql->native {:query {:filter [:and [:<= (ga-date-field :day) [:absolute-datetime (t/local-date "2016-10-02") :day]] [:> (ga-date-field :day) [:absolute-datetime (t/local-date "2016-09-09") :day]]]}}))))) (deftest filter-by-relative-date-test (mt/with-database-timezone-id nil (testing "\nsystem timezone should not affect the queries that get generated" (doseq [system-timezone-id ["UTC" "US/Pacific"]] (mt/with-system-timezone-id system-timezone-id (mt/with-clock (t/mock-clock (t/instant (t/zoned-date-time (t/local-date "2019-11-18") (t/local-time 0) (t/zone-id system-timezone-id))) (t/zone-id system-timezone-id)) (testing "last month" (is (= (ga-query {:start-date "2019-10-01" :end-date "2019-10-31"}) (mbql->native {:query {:filter [:= (ga-date-field :month) [:relative-datetime -1 :month]]}})))) (testing "this month" (is (= (ga-query {:start-date "2019-11-01" :end-date "2019-11-30"}) (mbql->native {:query {:filter [:= (ga-date-field :month) [:relative-datetime 0 :month]]}})))) (testing "next month" (is (= (ga-query {:start-date "2019-12-01" :end-date "2019-12-31"}) (mbql->native {:query {:filter [:= (ga-date-field :month) [:relative-datetime 1 :month]]}})))) (testing "month is 2 months from current month" (is (= (ga-query {:start-date "2020-01-01" :end-date "2020-01-31"}) (mbql->native {:query {:filter [:= (ga-date-field :month) [:relative-datetime 2 :month]]}})))) (testing "last year" (is (= (ga-query {:start-date "2018-01-01" :end-date "2018-12-31"}) (mbql->native {:query {:filter [:= (ga-date-field :year) [:relative-datetime -1 :year]]}})))) (testing "day is > yesterday (start-date should be today)" (is (= (ga-query {:start-date "today", :end-date "today"}) (mbql->native {:query {:filter [:> (ga-date-field :day) [:relative-datetime -1 :day]]}})))) (testing "day is > 30 days ago (start-date should be 29 days ago)" (is (= (ga-query {:start-date "29daysAgo" :end-date "today"}) (mbql->native {:query {:filter [:> (ga-date-field :day) [:relative-datetime -30 :day]]}})))) (testing "day is >= 30 days ago (start-date should be 30 days ago)" (is (= (ga-query {:start-date "30daysAgo" :end-date "today"}) (mbql->native {:query {:filter [:>= (ga-date-field :day) [:relative-datetime -30 :day]]}})))) (testing "day > last year" ;; [:relative-datetime -1 :year] => 2018 ;; day > 2018 => day >= 2018-01-02 (GA filters are inclusive) ;; (This query doesn't really make a ton of sense, but this matches the behavior of the SQL drivers) (is (= (ga-query {:start-date "2018-01-02" :end-date "today"}) (mbql->native {:query {:filter [:> (ga-date-field :day) [:relative-datetime -1 :year]]}})))) (testing "year > last year" ;; [:relative-datetime -1 :year] => 2018 ;; year > 2018 => year >= 2019 => year >= 2019 (is (= (ga-query {:start-date "2019-01-01" :end-date "today"}) (mbql->native {:query {:filter [:> (ga-date-field :year) [:relative-datetime -1 :year]]}})))) (testing "month is between 4 months ago and 1 month ago (:between is inclusive) (i.e., July, August, September, or Octover)" (is (= (ga-query {:start-date "2019-07-01", :end-date "2019-10-31"}) (mbql->native {:query {:filter [:between (ga-date-field :month) [:relative-datetime -4 :month] [:relative-datetime -1 :month]]}})))))))))) (deftest limit-test (is (= (ga-query {:max-results 25}) (mbql->native {:query {:limit 25}})))) ;;; ----------------------------------------------- (Almost) E2E tests ----------------------------------------------- (defn do-with-some-fields [thunk] (mt/with-temp* [Database [db {:engine "googleanalytics"}] Table [table {:name "98765432", :db_id (u/the-id db)}] Field [event-action-field {:name "ga:eventAction", :base_type "type/Text", :table_id (u/the-id table)}] Field [event-label-field {:name "ga:eventLabel", :base_type "type/Text", :table_id (u/the-id table)}] Field [date-field {:name "ga:date", :base_type "type/Date", :table_id (u/the-id table)}]] (mt/with-db db (thunk {:db db :table table :event-action-field event-action-field :event-label-field event-label-field :date-field date-field})))) (defmacro with-some-fields [fields-binding & body] `(do-with-some-fields (fn [~(or (first fields-binding) '_)] ~@body))) ;; let's try a real-life GA query and see how it looks when it's all put together. This one has already been ;; preprocessed, so we're just checking it gets converted to the correct native query (def ^:private expected-ga-query {:query {:ids "ga:98765432" :dimensions "ga:eventLabel" :metrics "ga:totalEvents" :segment "gaid::-4" :start-date "30daysAgo" :end-date "yesterday" :filters "ga:eventAction==Run Query;ga:eventLabel!=(not set);ga:eventLabel!=url" :sort "ga:eventLabel" :max-results 10000 :include-empty-rows false} :mbql? true}) (defn- preprocessed-query-with-some-fields [{:keys [db table event-action-field event-label-field date-field]}] {:database (u/the-id db) :type :query :query {:source-table (u/the-id table) :aggregation [[:metric "ga:totalEvents"]] :breakout [[:field (u/the-id event-label-field) nil]] :filter [:and [:segment "gaid::-4"] [:= [:field (u/the-id event-action-field) nil] [:value "Run Query" {:base_type :type/Text, :semantic_type nil, :database_type "VARCHAR"}]] [:between [:field (u/the-id date-field) {:temporal-unit :day}] [:relative-datetime -30 :day] [:relative-datetime -1 :day]] [:!= [:field (u/the-id event-label-field) nil] [:value "(not set)" {:base_type :type/Text, :semantic_type nil, :database_type "VARCHAR"}]] [:!= [:field (u/the-id event-label-field) nil] [:value "url" {:base_type :type/Text, :semantic_type nil, :database_type "VARCHAR"}]]] :order-by [[:asc [:field (u/the-id event-label-field) nil]]]}}) (deftest almost-e2e-test-1 ;; system timezone ID shouldn't affect generated query (doseq [system-timezone-id ["UTC" "US/Pacific"]] (mt/with-system-timezone-id system-timezone-id (mt/with-clock (t/mock-clock (t/instant (t/zoned-date-time (t/local-date "2019-11-18") (t/local-time 0) (t/zone-id system-timezone-id))) (t/zone-id system-timezone-id)) (is (= expected-ga-query (do-with-some-fields (fn [{:keys [db table event-action-field event-label-field date-field], :as objects}] (qp.store/with-store (qp.store/fetch-and-store-database! (u/the-id db)) (qp.store/fetch-and-store-tables! [(u/the-id table)]) (qp.store/fetch-and-store-fields! (map u/the-id [event-action-field event-label-field date-field])) (ga.qp/mbql->native (preprocessed-query-with-some-fields objects))))))))))) ;; this was the above query before it was preprocessed. Make sure we actually handle everything correctly end-to-end ;; for the entire preprocessing process (defn- query-with-some-fields [{:keys [db table event-action-field event-label-field date-field]}] {:database (u/the-id db) :type :query :query {:source-table (u/the-id table) :aggregation [[:metric "ga:totalEvents"]] :filter [:and [:segment "gaid::-4"] [:= [:field (u/the-id event-action-field) nil] "Run Query"] [:time-interval [:field (u/the-id date-field) nil] -30 :day] [:!= [:field (u/the-id event-label-field) nil] "(not set)" "url"]] :breakout [[:field (u/the-id event-label-field) nil]]}}) (deftest almost-e2e-test-2 (doseq [system-timezone-id ["UTC" "US/Pacific"]] (mt/with-system-timezone-id system-timezone-id (mt/with-clock (t/mock-clock (t/instant (t/zoned-date-time (t/local-date "2019-11-18") (t/local-time 0) (t/zone-id system-timezone-id))) (t/zone-id system-timezone-id)) (is (= expected-ga-query (do-with-some-fields (comp qp/query->native query-with-some-fields)))))))) ;; ok, now do the same query again, but run the entire QP pipeline, swapping out a few things so nothing is actually ;; run externally. (deftest almost-e2e-test-3 (testing "system timezone ID shouldn't affect generated query" (doseq [system-timezone-id ["UTC" "US/Pacific"]] (mt/with-system-timezone-id system-timezone-id (mt/with-clock (t/mock-clock (t/instant (t/zoned-date-time (t/local-date "2019-11-18") (t/local-time 0) (t/zone-id system-timezone-id))) (t/zone-id system-timezone-id)) (with-redefs [ga.execute/memoized-column-metadata (fn [_ column-name] {:display_name column-name :description (str "This is " column-name) :base_type :type/Text})] (do-with-some-fields (fn [objects] (let [query (query-with-some-fields objects) cols (for [col [{:name "ga:eventLabel"} {:name "ga:totalEvents", :base_type :type/Text}]] (#'ga.execute/add-col-metadata query col)) rows [["Toucan Sighting" 1000]] context {:timeout 500 :runf (fn [query rff context] (let [metadata {:cols cols}] (qp.context/reducef rff context metadata rows)))} qp (fn [query] (qp/process-query query context))] (is (= {:row_count 1 :status :completed :data {:rows [["Toucan Sighting" 1000]] :native_form expected-ga-query :cols [{:description "This is ga:eventLabel" :semantic_type nil :name "ga:eventLabel" :settings nil :source :breakout :parent_id nil :visibility_type :normal :display_name "ga:eventLabel" :fingerprint nil :base_type :type/Text :effective_type :type/Text :coercion_strategy nil} {:name "metric" :display_name "ga:totalEvents" :source :aggregation :description "This is ga:totalEvents" :base_type :type/Text :effective_type :type/Text}] :results_timezone system-timezone-id}} (-> (tu/doall-recursive (qp query)) (update-in [:data :cols] #(for [col %] (dissoc col :table_id :id :field_ref))) (m/dissoc-in [:data :results_metadata]) (m/dissoc-in [:data :insights]))))))))))))) (deftest almost-e2e-time-interval-test (testing "Make sure filtering by the previous 4 months actually filters against the right months (#10701)" (doseq [system-timezone-id ["UTC" "US/Pacific"]] (mt/with-system-timezone-id system-timezone-id (mt/with-clock (t/mock-clock (t/instant (t/zoned-date-time (t/local-date "2019-11-18") (t/local-time 0) (t/zone-id system-timezone-id))) (t/zone-id system-timezone-id)) (do-with-some-fields (fn [{:keys [db table date-field]}] (is (= {:metrics "ga:users" :dimensions "ga:date" :start-date "2019-07-01" :end-date "2019-10-31" :sort "ga:date"} (-> {:query {:source-table (:id table) :filter [:time-interval [:field (:id date-field) nil] -4 :month] :aggregation [[:metric "ga:users"]] :breakout [[:field (:id date-field) {:temporal-unit :day}]]} :type :query :database (:id db)} qp/query->native :query (select-keys [:start-date :end-date :dimensions :metrics :sort]))) "Last 4 months should includy July, August, September, and October (July 1st - October 31st)")))))))) ;;; ------------------------------------------------ Saving GA Cards ------------------------------------------------- ;; Can we *save* a GA query that has two aggregations? (deftest save-ga-query-test (mt/with-temp* [Database [db {:engine :googleanalytics}] Table [table {:db_id (u/the-id db)}] Field [field {:table_id (u/the-id table)}]] (let [cnt (->> (mt/user-http-request :crowberto :post 202 "card" {:name "Metabase Websites, Sessions and 1 Day Active Users, Grouped by Date (day)" :display :table :visualization_settings {} :dataset_query {:database (u/the-id db) :type :query :query {:source-table (u/the-id table) :aggregation [[:METRIC "ga:sessions"] [:METRIC "ga:1dayUsers"]] :breakout [[:field (u/the-id field) {:temporal-unit :day}]]}} :result_metadata [{:base_type :type/Date :display_name "Date" :name "ga:date" :description "The date of the session formatted as YYYYMMDD." :unit :day} {:base_type :type/Integer :display_name "Ga:1day Users" :name "ga:1dayUsers"} {:base_type :type/Integer :display_name "Ga:sessions" :name "ga:sessions"}] :metadata_checksum "i3uR1PM5q6uZfIpm0qZbb6Brcfw8S3/wejWolU0Bl1n1Dz/yqvLGxf/XXV6/uOBB75WhFE9V98pIw5Qm18VY6+rlzUnuaTfPvPbiJbh3D9w="}) ;; just make sure the API call actually worked by checking that the created Card is actually ;; successfully saved in the DB u/the-id (db/count Card :id))] (is (= 1 cnt)))))
41697
(ns metabase.driver.googleanalytics-test "Tests for the Google Analytics driver and query processor." (:require [clojure.test :refer :all] [java-time :as t] [medley.core :as m] [metabase.driver :as driver] metabase.driver.googleanalytics [metabase.driver.googleanalytics.execute :as ga.execute] [metabase.driver.googleanalytics.query-processor :as ga.qp] [metabase.models :refer [Card Database Field Table]] [metabase.query-processor :as qp] [metabase.query-processor.context :as qp.context] [metabase.query-processor.store :as qp.store] [metabase.test :as mt] [metabase.test.fixtures :as fixtures] [metabase.test.util :as tu] [metabase.util :as u] [toucan.db :as db])) (comment metabase.driver.googleanalytics/keep-me) (use-fixtures :once (fixtures/initialize :db)) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | MBQL->NATIVE (QUERY -> GA QUERY) | ;;; +----------------------------------------------------------------------------------------------------------------+ (defn- ga-query [inner-query] {:query (merge {:ids "ga:0123456" :dimensions "" :start-date "2005-01-01" :end-date "today" :max-results 10000 :include-empty-rows false} inner-query) :mbql? true}) (defn- mbql->native [query] (binding [qp.store/*store* (atom {:tables {1 #metabase.models.table.TableInstance{:name "0123456" :schema nil :id 1}}})] (driver/mbql->native :googleanalytics (update query :query (partial merge {:source-table 1}))))) (deftest basic-compilation-test (testing "just check that a basic almost-empty MBQL query can be compiled" (is (= (ga-query {}) (mbql->native {})))) (testing "try a basic query with a metric (aggregation)" (is (= (ga-query {:metrics "ga:users"}) (mbql->native {:query {:aggregation [[:metric "ga:users"]]}})))) (testing "query with metric (aggregation) + breakout" (is (= (ga-query {:metrics "ga:users" :dimensions "ga:browser"}) (mbql->native {:query {:aggregation [[:metric "ga:users"]] :breakout [[:field "ga:browser" nil]]}})))) (testing "query w/ segment (filter)" (is (= (ga-query {:segment "gaid::-4"}) (mbql->native {:query {:filter [:segment "gaid::-4"]}})))) (testing "query w/ non-segment filter" (is (= (ga-query {:filters "ga:continent==North America"}) (mbql->native {:query {:filter [:= [:field "ga:continent" nil] [:value "North America"]]}})))) (testing "query w/ segment & non-segment filter" (is (= (ga-query {:filters "ga:continent==North America" :segment "gaid::-4"}) (mbql->native {:query {:filter [:and [:segment "gaid::-4"] [:= [:field "ga:continent" nil] [:value "North America"]]]}}))))) (defn- ga-date-field [unit] [:field "ga:date" {:temporal-unit unit}]) (deftest filter-by-absolute-datetime-test (is (= (ga-query {:start-date "2016-11-08", :end-date "2016-11-08"}) (mbql->native {:query {:filter [:= (ga-date-field :day) [:absolute-datetime (t/local-date "2016-11-08") :day]]}}))) (testing "tests off by one day correction for gt/lt operators (GA doesn't support exclusive ranges)" (is (= (ga-query {:start-date "2016-11-09", :end-date "today"}) (mbql->native {:query {:filter [:> (ga-date-field :day) [:absolute-datetime (t/local-date "2016-11-08") :day]]}}))) (is (= (ga-query {:start-date "2005-01-01", :end-date "2016-10-01"}) (mbql->native {:query {:filter [:< (ga-date-field :day) [:absolute-datetime (t/local-date "2016-10-02") :day]]}}))) (is (= (ga-query {:start-date "2005-01-01", :end-date "2016-10-02"}) (mbql->native {:query {:filter [:<= (ga-date-field :day) [:absolute-datetime (t/local-date "2016-10-02") :day]]}}))) (is (= (ga-query {:start-date "2016-09-10", :end-date "2016-10-01"}) (mbql->native {:query {:filter [:and [:< (ga-date-field :day) [:absolute-datetime (t/local-date "2016-10-02") :day]] [:> (ga-date-field :day) [:absolute-datetime (t/local-date "2016-09-09") :day]]]}}))) (is (= (ga-query {:start-date "2016-09-10", :end-date "2016-10-02"}) (mbql->native {:query {:filter [:and [:<= (ga-date-field :day) [:absolute-datetime (t/local-date "2016-10-02") :day]] [:> (ga-date-field :day) [:absolute-datetime (t/local-date "2016-09-09") :day]]]}}))))) (deftest filter-by-relative-date-test (mt/with-database-timezone-id nil (testing "\nsystem timezone should not affect the queries that get generated" (doseq [system-timezone-id ["UTC" "US/Pacific"]] (mt/with-system-timezone-id system-timezone-id (mt/with-clock (t/mock-clock (t/instant (t/zoned-date-time (t/local-date "2019-11-18") (t/local-time 0) (t/zone-id system-timezone-id))) (t/zone-id system-timezone-id)) (testing "last month" (is (= (ga-query {:start-date "2019-10-01" :end-date "2019-10-31"}) (mbql->native {:query {:filter [:= (ga-date-field :month) [:relative-datetime -1 :month]]}})))) (testing "this month" (is (= (ga-query {:start-date "2019-11-01" :end-date "2019-11-30"}) (mbql->native {:query {:filter [:= (ga-date-field :month) [:relative-datetime 0 :month]]}})))) (testing "next month" (is (= (ga-query {:start-date "2019-12-01" :end-date "2019-12-31"}) (mbql->native {:query {:filter [:= (ga-date-field :month) [:relative-datetime 1 :month]]}})))) (testing "month is 2 months from current month" (is (= (ga-query {:start-date "2020-01-01" :end-date "2020-01-31"}) (mbql->native {:query {:filter [:= (ga-date-field :month) [:relative-datetime 2 :month]]}})))) (testing "last year" (is (= (ga-query {:start-date "2018-01-01" :end-date "2018-12-31"}) (mbql->native {:query {:filter [:= (ga-date-field :year) [:relative-datetime -1 :year]]}})))) (testing "day is > yesterday (start-date should be today)" (is (= (ga-query {:start-date "today", :end-date "today"}) (mbql->native {:query {:filter [:> (ga-date-field :day) [:relative-datetime -1 :day]]}})))) (testing "day is > 30 days ago (start-date should be 29 days ago)" (is (= (ga-query {:start-date "29daysAgo" :end-date "today"}) (mbql->native {:query {:filter [:> (ga-date-field :day) [:relative-datetime -30 :day]]}})))) (testing "day is >= 30 days ago (start-date should be 30 days ago)" (is (= (ga-query {:start-date "30daysAgo" :end-date "today"}) (mbql->native {:query {:filter [:>= (ga-date-field :day) [:relative-datetime -30 :day]]}})))) (testing "day > last year" ;; [:relative-datetime -1 :year] => 2018 ;; day > 2018 => day >= 2018-01-02 (GA filters are inclusive) ;; (This query doesn't really make a ton of sense, but this matches the behavior of the SQL drivers) (is (= (ga-query {:start-date "2018-01-02" :end-date "today"}) (mbql->native {:query {:filter [:> (ga-date-field :day) [:relative-datetime -1 :year]]}})))) (testing "year > last year" ;; [:relative-datetime -1 :year] => 2018 ;; year > 2018 => year >= 2019 => year >= 2019 (is (= (ga-query {:start-date "2019-01-01" :end-date "today"}) (mbql->native {:query {:filter [:> (ga-date-field :year) [:relative-datetime -1 :year]]}})))) (testing "month is between 4 months ago and 1 month ago (:between is inclusive) (i.e., July, August, September, or Octover)" (is (= (ga-query {:start-date "2019-07-01", :end-date "2019-10-31"}) (mbql->native {:query {:filter [:between (ga-date-field :month) [:relative-datetime -4 :month] [:relative-datetime -1 :month]]}})))))))))) (deftest limit-test (is (= (ga-query {:max-results 25}) (mbql->native {:query {:limit 25}})))) ;;; ----------------------------------------------- (Almost) E2E tests ----------------------------------------------- (defn do-with-some-fields [thunk] (mt/with-temp* [Database [db {:engine "googleanalytics"}] Table [table {:name "98765432", :db_id (u/the-id db)}] Field [event-action-field {:name "ga:eventAction", :base_type "type/Text", :table_id (u/the-id table)}] Field [event-label-field {:name "ga:eventLabel", :base_type "type/Text", :table_id (u/the-id table)}] Field [date-field {:name "ga:date", :base_type "type/Date", :table_id (u/the-id table)}]] (mt/with-db db (thunk {:db db :table table :event-action-field event-action-field :event-label-field event-label-field :date-field date-field})))) (defmacro with-some-fields [fields-binding & body] `(do-with-some-fields (fn [~(or (first fields-binding) '_)] ~@body))) ;; let's try a real-life GA query and see how it looks when it's all put together. This one has already been ;; preprocessed, so we're just checking it gets converted to the correct native query (def ^:private expected-ga-query {:query {:ids "ga:98765432" :dimensions "ga:eventLabel" :metrics "ga:totalEvents" :segment "gaid::-4" :start-date "30daysAgo" :end-date "yesterday" :filters "ga:eventAction==Run Query;ga:eventLabel!=(not set);ga:eventLabel!=url" :sort "ga:eventLabel" :max-results 10000 :include-empty-rows false} :mbql? true}) (defn- preprocessed-query-with-some-fields [{:keys [db table event-action-field event-label-field date-field]}] {:database (u/the-id db) :type :query :query {:source-table (u/the-id table) :aggregation [[:metric "ga:totalEvents"]] :breakout [[:field (u/the-id event-label-field) nil]] :filter [:and [:segment "gaid::-4"] [:= [:field (u/the-id event-action-field) nil] [:value "Run Query" {:base_type :type/Text, :semantic_type nil, :database_type "VARCHAR"}]] [:between [:field (u/the-id date-field) {:temporal-unit :day}] [:relative-datetime -30 :day] [:relative-datetime -1 :day]] [:!= [:field (u/the-id event-label-field) nil] [:value "(not set)" {:base_type :type/Text, :semantic_type nil, :database_type "VARCHAR"}]] [:!= [:field (u/the-id event-label-field) nil] [:value "url" {:base_type :type/Text, :semantic_type nil, :database_type "VARCHAR"}]]] :order-by [[:asc [:field (u/the-id event-label-field) nil]]]}}) (deftest almost-e2e-test-1 ;; system timezone ID shouldn't affect generated query (doseq [system-timezone-id ["UTC" "US/Pacific"]] (mt/with-system-timezone-id system-timezone-id (mt/with-clock (t/mock-clock (t/instant (t/zoned-date-time (t/local-date "2019-11-18") (t/local-time 0) (t/zone-id system-timezone-id))) (t/zone-id system-timezone-id)) (is (= expected-ga-query (do-with-some-fields (fn [{:keys [db table event-action-field event-label-field date-field], :as objects}] (qp.store/with-store (qp.store/fetch-and-store-database! (u/the-id db)) (qp.store/fetch-and-store-tables! [(u/the-id table)]) (qp.store/fetch-and-store-fields! (map u/the-id [event-action-field event-label-field date-field])) (ga.qp/mbql->native (preprocessed-query-with-some-fields objects))))))))))) ;; this was the above query before it was preprocessed. Make sure we actually handle everything correctly end-to-end ;; for the entire preprocessing process (defn- query-with-some-fields [{:keys [db table event-action-field event-label-field date-field]}] {:database (u/the-id db) :type :query :query {:source-table (u/the-id table) :aggregation [[:metric "ga:totalEvents"]] :filter [:and [:segment "gaid::-4"] [:= [:field (u/the-id event-action-field) nil] "Run Query"] [:time-interval [:field (u/the-id date-field) nil] -30 :day] [:!= [:field (u/the-id event-label-field) nil] "(not set)" "url"]] :breakout [[:field (u/the-id event-label-field) nil]]}}) (deftest almost-e2e-test-2 (doseq [system-timezone-id ["UTC" "US/Pacific"]] (mt/with-system-timezone-id system-timezone-id (mt/with-clock (t/mock-clock (t/instant (t/zoned-date-time (t/local-date "2019-11-18") (t/local-time 0) (t/zone-id system-timezone-id))) (t/zone-id system-timezone-id)) (is (= expected-ga-query (do-with-some-fields (comp qp/query->native query-with-some-fields)))))))) ;; ok, now do the same query again, but run the entire QP pipeline, swapping out a few things so nothing is actually ;; run externally. (deftest almost-e2e-test-3 (testing "system timezone ID shouldn't affect generated query" (doseq [system-timezone-id ["UTC" "US/Pacific"]] (mt/with-system-timezone-id system-timezone-id (mt/with-clock (t/mock-clock (t/instant (t/zoned-date-time (t/local-date "2019-11-18") (t/local-time 0) (t/zone-id system-timezone-id))) (t/zone-id system-timezone-id)) (with-redefs [ga.execute/memoized-column-metadata (fn [_ column-name] {:display_name column-name :description (str "This is " column-name) :base_type :type/Text})] (do-with-some-fields (fn [objects] (let [query (query-with-some-fields objects) cols (for [col [{:name "ga:eventLabel"} {:name "ga:totalEvents", :base_type :type/Text}]] (#'ga.execute/add-col-metadata query col)) rows [["Toucan Sighting" 1000]] context {:timeout 500 :runf (fn [query rff context] (let [metadata {:cols cols}] (qp.context/reducef rff context metadata rows)))} qp (fn [query] (qp/process-query query context))] (is (= {:row_count 1 :status :completed :data {:rows [["Toucan Sighting" 1000]] :native_form expected-ga-query :cols [{:description "This is ga:eventLabel" :semantic_type nil :name "ga:eventLabel" :settings nil :source :breakout :parent_id nil :visibility_type :normal :display_name "ga:eventLabel" :fingerprint nil :base_type :type/Text :effective_type :type/Text :coercion_strategy nil} {:name "metric" :display_name "ga:totalEvents" :source :aggregation :description "This is ga:totalEvents" :base_type :type/Text :effective_type :type/Text}] :results_timezone system-timezone-id}} (-> (tu/doall-recursive (qp query)) (update-in [:data :cols] #(for [col %] (dissoc col :table_id :id :field_ref))) (m/dissoc-in [:data :results_metadata]) (m/dissoc-in [:data :insights]))))))))))))) (deftest almost-e2e-time-interval-test (testing "Make sure filtering by the previous 4 months actually filters against the right months (#10701)" (doseq [system-timezone-id ["UTC" "US/Pacific"]] (mt/with-system-timezone-id system-timezone-id (mt/with-clock (t/mock-clock (t/instant (t/zoned-date-time (t/local-date "2019-11-18") (t/local-time 0) (t/zone-id system-timezone-id))) (t/zone-id system-timezone-id)) (do-with-some-fields (fn [{:keys [db table date-field]}] (is (= {:metrics "ga:users" :dimensions "ga:date" :start-date "2019-07-01" :end-date "2019-10-31" :sort "ga:date"} (-> {:query {:source-table (:id table) :filter [:time-interval [:field (:id date-field) nil] -4 :month] :aggregation [[:metric "ga:users"]] :breakout [[:field (:id date-field) {:temporal-unit :day}]]} :type :query :database (:id db)} qp/query->native :query (select-keys [:start-date :end-date :dimensions :metrics :sort]))) "Last 4 months should includy July, August, September, and October (July 1st - October 31st)")))))))) ;;; ------------------------------------------------ Saving GA Cards ------------------------------------------------- ;; Can we *save* a GA query that has two aggregations? (deftest save-ga-query-test (mt/with-temp* [Database [db {:engine :googleanalytics}] Table [table {:db_id (u/the-id db)}] Field [field {:table_id (u/the-id table)}]] (let [cnt (->> (mt/user-http-request :crowberto :post 202 "card" {:name "Metabase Websites, Sessions and 1 Day Active Users, Grouped by Date (day)" :display :table :visualization_settings {} :dataset_query {:database (u/the-id db) :type :query :query {:source-table (u/the-id table) :aggregation [[:METRIC "ga:sessions"] [:METRIC "ga:1dayUsers"]] :breakout [[:field (u/the-id field) {:temporal-unit :day}]]}} :result_metadata [{:base_type :type/Date :display_name "Date" :name "ga:date" :description "The date of the session formatted as YYYYMMDD." :unit :day} {:base_type :type/Integer :display_name "Ga:1day Users" :name "ga:1dayUsers"} {:base_type :type/Integer :display_name "Ga:sessions" :name "ga:sessions"}] :metadata_checksum "i3uR1PM5q6uZfIpm0qZbb6Brcfw8S3/wejWolU0Bl1n1Dz/yqvLGxf/XX<KEY>6/<KEY>OBB75Wh<KEY>9<KEY>8pIw<KEY>rl<KEY>9w="}) ;; just make sure the API call actually worked by checking that the created Card is actually ;; successfully saved in the DB u/the-id (db/count Card :id))] (is (= 1 cnt)))))
true
(ns metabase.driver.googleanalytics-test "Tests for the Google Analytics driver and query processor." (:require [clojure.test :refer :all] [java-time :as t] [medley.core :as m] [metabase.driver :as driver] metabase.driver.googleanalytics [metabase.driver.googleanalytics.execute :as ga.execute] [metabase.driver.googleanalytics.query-processor :as ga.qp] [metabase.models :refer [Card Database Field Table]] [metabase.query-processor :as qp] [metabase.query-processor.context :as qp.context] [metabase.query-processor.store :as qp.store] [metabase.test :as mt] [metabase.test.fixtures :as fixtures] [metabase.test.util :as tu] [metabase.util :as u] [toucan.db :as db])) (comment metabase.driver.googleanalytics/keep-me) (use-fixtures :once (fixtures/initialize :db)) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | MBQL->NATIVE (QUERY -> GA QUERY) | ;;; +----------------------------------------------------------------------------------------------------------------+ (defn- ga-query [inner-query] {:query (merge {:ids "ga:0123456" :dimensions "" :start-date "2005-01-01" :end-date "today" :max-results 10000 :include-empty-rows false} inner-query) :mbql? true}) (defn- mbql->native [query] (binding [qp.store/*store* (atom {:tables {1 #metabase.models.table.TableInstance{:name "0123456" :schema nil :id 1}}})] (driver/mbql->native :googleanalytics (update query :query (partial merge {:source-table 1}))))) (deftest basic-compilation-test (testing "just check that a basic almost-empty MBQL query can be compiled" (is (= (ga-query {}) (mbql->native {})))) (testing "try a basic query with a metric (aggregation)" (is (= (ga-query {:metrics "ga:users"}) (mbql->native {:query {:aggregation [[:metric "ga:users"]]}})))) (testing "query with metric (aggregation) + breakout" (is (= (ga-query {:metrics "ga:users" :dimensions "ga:browser"}) (mbql->native {:query {:aggregation [[:metric "ga:users"]] :breakout [[:field "ga:browser" nil]]}})))) (testing "query w/ segment (filter)" (is (= (ga-query {:segment "gaid::-4"}) (mbql->native {:query {:filter [:segment "gaid::-4"]}})))) (testing "query w/ non-segment filter" (is (= (ga-query {:filters "ga:continent==North America"}) (mbql->native {:query {:filter [:= [:field "ga:continent" nil] [:value "North America"]]}})))) (testing "query w/ segment & non-segment filter" (is (= (ga-query {:filters "ga:continent==North America" :segment "gaid::-4"}) (mbql->native {:query {:filter [:and [:segment "gaid::-4"] [:= [:field "ga:continent" nil] [:value "North America"]]]}}))))) (defn- ga-date-field [unit] [:field "ga:date" {:temporal-unit unit}]) (deftest filter-by-absolute-datetime-test (is (= (ga-query {:start-date "2016-11-08", :end-date "2016-11-08"}) (mbql->native {:query {:filter [:= (ga-date-field :day) [:absolute-datetime (t/local-date "2016-11-08") :day]]}}))) (testing "tests off by one day correction for gt/lt operators (GA doesn't support exclusive ranges)" (is (= (ga-query {:start-date "2016-11-09", :end-date "today"}) (mbql->native {:query {:filter [:> (ga-date-field :day) [:absolute-datetime (t/local-date "2016-11-08") :day]]}}))) (is (= (ga-query {:start-date "2005-01-01", :end-date "2016-10-01"}) (mbql->native {:query {:filter [:< (ga-date-field :day) [:absolute-datetime (t/local-date "2016-10-02") :day]]}}))) (is (= (ga-query {:start-date "2005-01-01", :end-date "2016-10-02"}) (mbql->native {:query {:filter [:<= (ga-date-field :day) [:absolute-datetime (t/local-date "2016-10-02") :day]]}}))) (is (= (ga-query {:start-date "2016-09-10", :end-date "2016-10-01"}) (mbql->native {:query {:filter [:and [:< (ga-date-field :day) [:absolute-datetime (t/local-date "2016-10-02") :day]] [:> (ga-date-field :day) [:absolute-datetime (t/local-date "2016-09-09") :day]]]}}))) (is (= (ga-query {:start-date "2016-09-10", :end-date "2016-10-02"}) (mbql->native {:query {:filter [:and [:<= (ga-date-field :day) [:absolute-datetime (t/local-date "2016-10-02") :day]] [:> (ga-date-field :day) [:absolute-datetime (t/local-date "2016-09-09") :day]]]}}))))) (deftest filter-by-relative-date-test (mt/with-database-timezone-id nil (testing "\nsystem timezone should not affect the queries that get generated" (doseq [system-timezone-id ["UTC" "US/Pacific"]] (mt/with-system-timezone-id system-timezone-id (mt/with-clock (t/mock-clock (t/instant (t/zoned-date-time (t/local-date "2019-11-18") (t/local-time 0) (t/zone-id system-timezone-id))) (t/zone-id system-timezone-id)) (testing "last month" (is (= (ga-query {:start-date "2019-10-01" :end-date "2019-10-31"}) (mbql->native {:query {:filter [:= (ga-date-field :month) [:relative-datetime -1 :month]]}})))) (testing "this month" (is (= (ga-query {:start-date "2019-11-01" :end-date "2019-11-30"}) (mbql->native {:query {:filter [:= (ga-date-field :month) [:relative-datetime 0 :month]]}})))) (testing "next month" (is (= (ga-query {:start-date "2019-12-01" :end-date "2019-12-31"}) (mbql->native {:query {:filter [:= (ga-date-field :month) [:relative-datetime 1 :month]]}})))) (testing "month is 2 months from current month" (is (= (ga-query {:start-date "2020-01-01" :end-date "2020-01-31"}) (mbql->native {:query {:filter [:= (ga-date-field :month) [:relative-datetime 2 :month]]}})))) (testing "last year" (is (= (ga-query {:start-date "2018-01-01" :end-date "2018-12-31"}) (mbql->native {:query {:filter [:= (ga-date-field :year) [:relative-datetime -1 :year]]}})))) (testing "day is > yesterday (start-date should be today)" (is (= (ga-query {:start-date "today", :end-date "today"}) (mbql->native {:query {:filter [:> (ga-date-field :day) [:relative-datetime -1 :day]]}})))) (testing "day is > 30 days ago (start-date should be 29 days ago)" (is (= (ga-query {:start-date "29daysAgo" :end-date "today"}) (mbql->native {:query {:filter [:> (ga-date-field :day) [:relative-datetime -30 :day]]}})))) (testing "day is >= 30 days ago (start-date should be 30 days ago)" (is (= (ga-query {:start-date "30daysAgo" :end-date "today"}) (mbql->native {:query {:filter [:>= (ga-date-field :day) [:relative-datetime -30 :day]]}})))) (testing "day > last year" ;; [:relative-datetime -1 :year] => 2018 ;; day > 2018 => day >= 2018-01-02 (GA filters are inclusive) ;; (This query doesn't really make a ton of sense, but this matches the behavior of the SQL drivers) (is (= (ga-query {:start-date "2018-01-02" :end-date "today"}) (mbql->native {:query {:filter [:> (ga-date-field :day) [:relative-datetime -1 :year]]}})))) (testing "year > last year" ;; [:relative-datetime -1 :year] => 2018 ;; year > 2018 => year >= 2019 => year >= 2019 (is (= (ga-query {:start-date "2019-01-01" :end-date "today"}) (mbql->native {:query {:filter [:> (ga-date-field :year) [:relative-datetime -1 :year]]}})))) (testing "month is between 4 months ago and 1 month ago (:between is inclusive) (i.e., July, August, September, or Octover)" (is (= (ga-query {:start-date "2019-07-01", :end-date "2019-10-31"}) (mbql->native {:query {:filter [:between (ga-date-field :month) [:relative-datetime -4 :month] [:relative-datetime -1 :month]]}})))))))))) (deftest limit-test (is (= (ga-query {:max-results 25}) (mbql->native {:query {:limit 25}})))) ;;; ----------------------------------------------- (Almost) E2E tests ----------------------------------------------- (defn do-with-some-fields [thunk] (mt/with-temp* [Database [db {:engine "googleanalytics"}] Table [table {:name "98765432", :db_id (u/the-id db)}] Field [event-action-field {:name "ga:eventAction", :base_type "type/Text", :table_id (u/the-id table)}] Field [event-label-field {:name "ga:eventLabel", :base_type "type/Text", :table_id (u/the-id table)}] Field [date-field {:name "ga:date", :base_type "type/Date", :table_id (u/the-id table)}]] (mt/with-db db (thunk {:db db :table table :event-action-field event-action-field :event-label-field event-label-field :date-field date-field})))) (defmacro with-some-fields [fields-binding & body] `(do-with-some-fields (fn [~(or (first fields-binding) '_)] ~@body))) ;; let's try a real-life GA query and see how it looks when it's all put together. This one has already been ;; preprocessed, so we're just checking it gets converted to the correct native query (def ^:private expected-ga-query {:query {:ids "ga:98765432" :dimensions "ga:eventLabel" :metrics "ga:totalEvents" :segment "gaid::-4" :start-date "30daysAgo" :end-date "yesterday" :filters "ga:eventAction==Run Query;ga:eventLabel!=(not set);ga:eventLabel!=url" :sort "ga:eventLabel" :max-results 10000 :include-empty-rows false} :mbql? true}) (defn- preprocessed-query-with-some-fields [{:keys [db table event-action-field event-label-field date-field]}] {:database (u/the-id db) :type :query :query {:source-table (u/the-id table) :aggregation [[:metric "ga:totalEvents"]] :breakout [[:field (u/the-id event-label-field) nil]] :filter [:and [:segment "gaid::-4"] [:= [:field (u/the-id event-action-field) nil] [:value "Run Query" {:base_type :type/Text, :semantic_type nil, :database_type "VARCHAR"}]] [:between [:field (u/the-id date-field) {:temporal-unit :day}] [:relative-datetime -30 :day] [:relative-datetime -1 :day]] [:!= [:field (u/the-id event-label-field) nil] [:value "(not set)" {:base_type :type/Text, :semantic_type nil, :database_type "VARCHAR"}]] [:!= [:field (u/the-id event-label-field) nil] [:value "url" {:base_type :type/Text, :semantic_type nil, :database_type "VARCHAR"}]]] :order-by [[:asc [:field (u/the-id event-label-field) nil]]]}}) (deftest almost-e2e-test-1 ;; system timezone ID shouldn't affect generated query (doseq [system-timezone-id ["UTC" "US/Pacific"]] (mt/with-system-timezone-id system-timezone-id (mt/with-clock (t/mock-clock (t/instant (t/zoned-date-time (t/local-date "2019-11-18") (t/local-time 0) (t/zone-id system-timezone-id))) (t/zone-id system-timezone-id)) (is (= expected-ga-query (do-with-some-fields (fn [{:keys [db table event-action-field event-label-field date-field], :as objects}] (qp.store/with-store (qp.store/fetch-and-store-database! (u/the-id db)) (qp.store/fetch-and-store-tables! [(u/the-id table)]) (qp.store/fetch-and-store-fields! (map u/the-id [event-action-field event-label-field date-field])) (ga.qp/mbql->native (preprocessed-query-with-some-fields objects))))))))))) ;; this was the above query before it was preprocessed. Make sure we actually handle everything correctly end-to-end ;; for the entire preprocessing process (defn- query-with-some-fields [{:keys [db table event-action-field event-label-field date-field]}] {:database (u/the-id db) :type :query :query {:source-table (u/the-id table) :aggregation [[:metric "ga:totalEvents"]] :filter [:and [:segment "gaid::-4"] [:= [:field (u/the-id event-action-field) nil] "Run Query"] [:time-interval [:field (u/the-id date-field) nil] -30 :day] [:!= [:field (u/the-id event-label-field) nil] "(not set)" "url"]] :breakout [[:field (u/the-id event-label-field) nil]]}}) (deftest almost-e2e-test-2 (doseq [system-timezone-id ["UTC" "US/Pacific"]] (mt/with-system-timezone-id system-timezone-id (mt/with-clock (t/mock-clock (t/instant (t/zoned-date-time (t/local-date "2019-11-18") (t/local-time 0) (t/zone-id system-timezone-id))) (t/zone-id system-timezone-id)) (is (= expected-ga-query (do-with-some-fields (comp qp/query->native query-with-some-fields)))))))) ;; ok, now do the same query again, but run the entire QP pipeline, swapping out a few things so nothing is actually ;; run externally. (deftest almost-e2e-test-3 (testing "system timezone ID shouldn't affect generated query" (doseq [system-timezone-id ["UTC" "US/Pacific"]] (mt/with-system-timezone-id system-timezone-id (mt/with-clock (t/mock-clock (t/instant (t/zoned-date-time (t/local-date "2019-11-18") (t/local-time 0) (t/zone-id system-timezone-id))) (t/zone-id system-timezone-id)) (with-redefs [ga.execute/memoized-column-metadata (fn [_ column-name] {:display_name column-name :description (str "This is " column-name) :base_type :type/Text})] (do-with-some-fields (fn [objects] (let [query (query-with-some-fields objects) cols (for [col [{:name "ga:eventLabel"} {:name "ga:totalEvents", :base_type :type/Text}]] (#'ga.execute/add-col-metadata query col)) rows [["Toucan Sighting" 1000]] context {:timeout 500 :runf (fn [query rff context] (let [metadata {:cols cols}] (qp.context/reducef rff context metadata rows)))} qp (fn [query] (qp/process-query query context))] (is (= {:row_count 1 :status :completed :data {:rows [["Toucan Sighting" 1000]] :native_form expected-ga-query :cols [{:description "This is ga:eventLabel" :semantic_type nil :name "ga:eventLabel" :settings nil :source :breakout :parent_id nil :visibility_type :normal :display_name "ga:eventLabel" :fingerprint nil :base_type :type/Text :effective_type :type/Text :coercion_strategy nil} {:name "metric" :display_name "ga:totalEvents" :source :aggregation :description "This is ga:totalEvents" :base_type :type/Text :effective_type :type/Text}] :results_timezone system-timezone-id}} (-> (tu/doall-recursive (qp query)) (update-in [:data :cols] #(for [col %] (dissoc col :table_id :id :field_ref))) (m/dissoc-in [:data :results_metadata]) (m/dissoc-in [:data :insights]))))))))))))) (deftest almost-e2e-time-interval-test (testing "Make sure filtering by the previous 4 months actually filters against the right months (#10701)" (doseq [system-timezone-id ["UTC" "US/Pacific"]] (mt/with-system-timezone-id system-timezone-id (mt/with-clock (t/mock-clock (t/instant (t/zoned-date-time (t/local-date "2019-11-18") (t/local-time 0) (t/zone-id system-timezone-id))) (t/zone-id system-timezone-id)) (do-with-some-fields (fn [{:keys [db table date-field]}] (is (= {:metrics "ga:users" :dimensions "ga:date" :start-date "2019-07-01" :end-date "2019-10-31" :sort "ga:date"} (-> {:query {:source-table (:id table) :filter [:time-interval [:field (:id date-field) nil] -4 :month] :aggregation [[:metric "ga:users"]] :breakout [[:field (:id date-field) {:temporal-unit :day}]]} :type :query :database (:id db)} qp/query->native :query (select-keys [:start-date :end-date :dimensions :metrics :sort]))) "Last 4 months should includy July, August, September, and October (July 1st - October 31st)")))))))) ;;; ------------------------------------------------ Saving GA Cards ------------------------------------------------- ;; Can we *save* a GA query that has two aggregations? (deftest save-ga-query-test (mt/with-temp* [Database [db {:engine :googleanalytics}] Table [table {:db_id (u/the-id db)}] Field [field {:table_id (u/the-id table)}]] (let [cnt (->> (mt/user-http-request :crowberto :post 202 "card" {:name "Metabase Websites, Sessions and 1 Day Active Users, Grouped by Date (day)" :display :table :visualization_settings {} :dataset_query {:database (u/the-id db) :type :query :query {:source-table (u/the-id table) :aggregation [[:METRIC "ga:sessions"] [:METRIC "ga:1dayUsers"]] :breakout [[:field (u/the-id field) {:temporal-unit :day}]]}} :result_metadata [{:base_type :type/Date :display_name "Date" :name "ga:date" :description "The date of the session formatted as YYYYMMDD." :unit :day} {:base_type :type/Integer :display_name "Ga:1day Users" :name "ga:1dayUsers"} {:base_type :type/Integer :display_name "Ga:sessions" :name "ga:sessions"}] :metadata_checksum "i3uR1PM5q6uZfIpm0qZbb6Brcfw8S3/wejWolU0Bl1n1Dz/yqvLGxf/XXPI:KEY:<KEY>END_PI6/PI:KEY:<KEY>END_PIOBB75WhPI:KEY:<KEY>END_PI9PI:KEY:<KEY>END_PI8pIwPI:KEY:<KEY>END_PIrlPI:KEY:<KEY>END_PI9w="}) ;; just make sure the API call actually worked by checking that the created Card is actually ;; successfully saved in the DB u/the-id (db/count Card :id))] (is (= 1 cnt)))))
[ { "context": "northeast-1.compute.internal\",\n;;=> :global-ip \"54.199.234.18\",\n;;=> :private-ip \"10.0.0.212\"}\n;;=> {:node-n", "end": 1725, "score": 0.9997119307518005, "start": 1712, "tag": "IP_ADDRESS", "value": "54.199.234.18" }, { "context": " :global-ip \"54.199.234.18\",\n;;=> :private-ip \"10.0.0.212\"}\n;;=> {:node-name \"EcsInstanceAs\n;;=> :status", "end": 1758, "score": 0.9996854066848755, "start": 1748, "tag": "IP_ADDRESS", "value": "10.0.0.212" } ]
Chapter 10 Code/aws-examples/src/aws_examples/ec2_example.clj
PacktPublishing/Clojure-Programming-Cookbook
14
(ns aws-examples.ec2-example (:require [amazonica.aws.ec2 :as ec2] [amazonica.core :as core])) ;;=> nil (core/defcredential "Your Access Key" "Your Secret Access Key" "your region") ;;=> {:access-key "Your Access Key", :secret-key "Your Secret Access Key", :endpoint "your region"} (ec2/describe-regions) ;;=> {:regions [{:region-name "ap-south-1", :endpoint "ec2.ap-south-1.amazonaws.com"} ;;=> ..... ;;=> {:region-name "ap-northeast-2", :endpoint "ec2.ap-northeast-2.amazonaws.com"} ;;=> {:region-name "ap-northeast-1", :endpoint (ec2/describe-instances) ;;=> {:reservations [{:reservation-id "r-8efe3c2b", :requester-id "226008221399", ;;=> :owner-id "182672843130", :group-names [], :groups [], .... (defn get-instances-info[] (let [inst (ec2/describe-instances)] (->> (mapcat :instances (inst :reservations)) (map #(vector [:node-name (->> (filter (fn [x] (= (:key x)) "Name" ) (:tags %)) first :value)] [:status (get-in % [:state :name])] [:instance-id (:instance-id %)] [:private-dns-name (:private-dns-name %)] [:global-ip (-> % :network-interfaces first :private-ip-addresses first :association :public-ip)] [:private-ip (-> % :network-interfaces first :private-ip-addresses first :private-ip-address)])) (map #(into {} %)) (sort-by :node-name)))) ;;=> #'aws-examples.ec2-example/get-instances-info (get-instances-info) ;;=> ({:node-name "ECS Instance - amazon-ecs-cli-setup-my-cluster", ;;=> :status "running", ;;=> :instance-id "i-a1257a3e", ;;=> :private-dns-name "ip-10-0-0-212.ap-northeast-1.compute.internal", ;;=> :global-ip "54.199.234.18", ;;=> :private-ip "10.0.0.212"} ;;=> {:node-name "EcsInstanceAs ;;=> :status "terminated", ;;=> :instance-id "i-c5bbef5a", ;;=> :private-dns-name "", ;;=> :global-ip nil, ;;=> :private-ip nil}) (ec2/start-instances :instance-ids '("i-c5bbef5a")) ;;=> {:starting-instances ;;=> [{:previous-state {:code 80, :name "stopped"}, ;;=> :current-state {:code 0, :name "pending"}, ;;=> :instance-id "i-c5bbef5a"}]} (ec2/stop-instances :instance-ids '("i-c5bbef5a")) ;;=> {:stopping-instances ;;=> [{:previous-state {:code 16, :name "running"}, ;;=> :current-state {:code 64, :name "stopping"}, ;;=> :instance-id "i-c5bbef5a"}]}
88437
(ns aws-examples.ec2-example (:require [amazonica.aws.ec2 :as ec2] [amazonica.core :as core])) ;;=> nil (core/defcredential "Your Access Key" "Your Secret Access Key" "your region") ;;=> {:access-key "Your Access Key", :secret-key "Your Secret Access Key", :endpoint "your region"} (ec2/describe-regions) ;;=> {:regions [{:region-name "ap-south-1", :endpoint "ec2.ap-south-1.amazonaws.com"} ;;=> ..... ;;=> {:region-name "ap-northeast-2", :endpoint "ec2.ap-northeast-2.amazonaws.com"} ;;=> {:region-name "ap-northeast-1", :endpoint (ec2/describe-instances) ;;=> {:reservations [{:reservation-id "r-8efe3c2b", :requester-id "226008221399", ;;=> :owner-id "182672843130", :group-names [], :groups [], .... (defn get-instances-info[] (let [inst (ec2/describe-instances)] (->> (mapcat :instances (inst :reservations)) (map #(vector [:node-name (->> (filter (fn [x] (= (:key x)) "Name" ) (:tags %)) first :value)] [:status (get-in % [:state :name])] [:instance-id (:instance-id %)] [:private-dns-name (:private-dns-name %)] [:global-ip (-> % :network-interfaces first :private-ip-addresses first :association :public-ip)] [:private-ip (-> % :network-interfaces first :private-ip-addresses first :private-ip-address)])) (map #(into {} %)) (sort-by :node-name)))) ;;=> #'aws-examples.ec2-example/get-instances-info (get-instances-info) ;;=> ({:node-name "ECS Instance - amazon-ecs-cli-setup-my-cluster", ;;=> :status "running", ;;=> :instance-id "i-a1257a3e", ;;=> :private-dns-name "ip-10-0-0-212.ap-northeast-1.compute.internal", ;;=> :global-ip "172.16.58.3", ;;=> :private-ip "10.0.0.212"} ;;=> {:node-name "EcsInstanceAs ;;=> :status "terminated", ;;=> :instance-id "i-c5bbef5a", ;;=> :private-dns-name "", ;;=> :global-ip nil, ;;=> :private-ip nil}) (ec2/start-instances :instance-ids '("i-c5bbef5a")) ;;=> {:starting-instances ;;=> [{:previous-state {:code 80, :name "stopped"}, ;;=> :current-state {:code 0, :name "pending"}, ;;=> :instance-id "i-c5bbef5a"}]} (ec2/stop-instances :instance-ids '("i-c5bbef5a")) ;;=> {:stopping-instances ;;=> [{:previous-state {:code 16, :name "running"}, ;;=> :current-state {:code 64, :name "stopping"}, ;;=> :instance-id "i-c5bbef5a"}]}
true
(ns aws-examples.ec2-example (:require [amazonica.aws.ec2 :as ec2] [amazonica.core :as core])) ;;=> nil (core/defcredential "Your Access Key" "Your Secret Access Key" "your region") ;;=> {:access-key "Your Access Key", :secret-key "Your Secret Access Key", :endpoint "your region"} (ec2/describe-regions) ;;=> {:regions [{:region-name "ap-south-1", :endpoint "ec2.ap-south-1.amazonaws.com"} ;;=> ..... ;;=> {:region-name "ap-northeast-2", :endpoint "ec2.ap-northeast-2.amazonaws.com"} ;;=> {:region-name "ap-northeast-1", :endpoint (ec2/describe-instances) ;;=> {:reservations [{:reservation-id "r-8efe3c2b", :requester-id "226008221399", ;;=> :owner-id "182672843130", :group-names [], :groups [], .... (defn get-instances-info[] (let [inst (ec2/describe-instances)] (->> (mapcat :instances (inst :reservations)) (map #(vector [:node-name (->> (filter (fn [x] (= (:key x)) "Name" ) (:tags %)) first :value)] [:status (get-in % [:state :name])] [:instance-id (:instance-id %)] [:private-dns-name (:private-dns-name %)] [:global-ip (-> % :network-interfaces first :private-ip-addresses first :association :public-ip)] [:private-ip (-> % :network-interfaces first :private-ip-addresses first :private-ip-address)])) (map #(into {} %)) (sort-by :node-name)))) ;;=> #'aws-examples.ec2-example/get-instances-info (get-instances-info) ;;=> ({:node-name "ECS Instance - amazon-ecs-cli-setup-my-cluster", ;;=> :status "running", ;;=> :instance-id "i-a1257a3e", ;;=> :private-dns-name "ip-10-0-0-212.ap-northeast-1.compute.internal", ;;=> :global-ip "PI:IP_ADDRESS:172.16.58.3END_PI", ;;=> :private-ip "10.0.0.212"} ;;=> {:node-name "EcsInstanceAs ;;=> :status "terminated", ;;=> :instance-id "i-c5bbef5a", ;;=> :private-dns-name "", ;;=> :global-ip nil, ;;=> :private-ip nil}) (ec2/start-instances :instance-ids '("i-c5bbef5a")) ;;=> {:starting-instances ;;=> [{:previous-state {:code 80, :name "stopped"}, ;;=> :current-state {:code 0, :name "pending"}, ;;=> :instance-id "i-c5bbef5a"}]} (ec2/stop-instances :instance-ids '("i-c5bbef5a")) ;;=> {:stopping-instances ;;=> [{:previous-state {:code 16, :name "running"}, ;;=> :current-state {:code 64, :name "stopping"}, ;;=> :instance-id "i-c5bbef5a"}]}
[ { "context": "fy email if no tx in last 20 minutes\n :api-key \"12345\" ;; API Key for Eth", "end": 1753, "score": 0.9201300740242004, "start": 1748, "tag": "KEY", "value": "12345" }, { "context": "y for Etherscan (optional)\n :gmail-cred {:user \"example@gmail.com\" ;; Gmail login info for sending out the ", "end": 1861, "score": 0.9999237060546875, "start": 1844, "tag": "EMAIL", "value": "example@gmail.com" }, { "context": " for sending out the email\n :pass \"examplepassword\"}\n :notify-email \"info@example.com\")) ", "end": 1955, "score": 0.9992332458496094, "start": 1940, "tag": "PASSWORD", "value": "examplepassword" }, { "context": " :pass \"examplepassword\"}\n :notify-email \"info@example.com\")) ;; where to send notification emai", "end": 1992, "score": 0.9999257326126099, "start": 1976, "tag": "EMAIL", "value": "info@example.com" } ]
src/tx_monitor/core.clj
clearcoin/tx-monitor
1
(ns tx-monitor.core (:require [clj-http.client :as client] [cheshire.core :refer [parse-string]] [postal.core :refer [send-message]])) (defn any-tx-since-time? [address mins-ago & {:keys [api-key]}] (->> (client/get (str "http://api.etherscan.io/api?module=account&action=txlist" "&address=" address "&startblock=0&endblock=99999999&sort=desc&page=1&offset=10" (when api-key (str "&apikey=" api-key))) {:accept :json}) :body (#(parse-string % true)) :result (map #(select-keys % [:hash :timeStamp])) (filter (comp (partial < (- (quot (System/currentTimeMillis) 1000) (* 60 mins-ago))) #(Integer. %) :timeStamp)) count pos?)) (defn alert-if-no-tx-since-time [address mins-ago & {:keys [api-key gmail-cred notify-email]}] (when-not (any-tx-since-time? address mins-ago :api-key api-key) (send-message (merge {:host "smtp.gmail.com" :ssl :yes!!!11} gmail-cred) {:from (:user gmail-cred) :to notify-email :subject "No Recent Transactions" :body (str "This is an alert that there have not been any " "transactions in the past " mins-ago " minutes " "on address " address ".")}))) (defn -main [] (alert-if-no-tx-since-time "0x1E26b3D07E57F453caE30F7DDd2f945f5bF3EF33" ;; Ethereum address to track 20 ;; notify email if no tx in last 20 minutes :api-key "12345" ;; API Key for Etherscan (optional) :gmail-cred {:user "example@gmail.com" ;; Gmail login info for sending out the email :pass "examplepassword"} :notify-email "info@example.com")) ;; where to send notification email to
88122
(ns tx-monitor.core (:require [clj-http.client :as client] [cheshire.core :refer [parse-string]] [postal.core :refer [send-message]])) (defn any-tx-since-time? [address mins-ago & {:keys [api-key]}] (->> (client/get (str "http://api.etherscan.io/api?module=account&action=txlist" "&address=" address "&startblock=0&endblock=99999999&sort=desc&page=1&offset=10" (when api-key (str "&apikey=" api-key))) {:accept :json}) :body (#(parse-string % true)) :result (map #(select-keys % [:hash :timeStamp])) (filter (comp (partial < (- (quot (System/currentTimeMillis) 1000) (* 60 mins-ago))) #(Integer. %) :timeStamp)) count pos?)) (defn alert-if-no-tx-since-time [address mins-ago & {:keys [api-key gmail-cred notify-email]}] (when-not (any-tx-since-time? address mins-ago :api-key api-key) (send-message (merge {:host "smtp.gmail.com" :ssl :yes!!!11} gmail-cred) {:from (:user gmail-cred) :to notify-email :subject "No Recent Transactions" :body (str "This is an alert that there have not been any " "transactions in the past " mins-ago " minutes " "on address " address ".")}))) (defn -main [] (alert-if-no-tx-since-time "0x1E26b3D07E57F453caE30F7DDd2f945f5bF3EF33" ;; Ethereum address to track 20 ;; notify email if no tx in last 20 minutes :api-key "<KEY>" ;; API Key for Etherscan (optional) :gmail-cred {:user "<EMAIL>" ;; Gmail login info for sending out the email :pass "<PASSWORD>"} :notify-email "<EMAIL>")) ;; where to send notification email to
true
(ns tx-monitor.core (:require [clj-http.client :as client] [cheshire.core :refer [parse-string]] [postal.core :refer [send-message]])) (defn any-tx-since-time? [address mins-ago & {:keys [api-key]}] (->> (client/get (str "http://api.etherscan.io/api?module=account&action=txlist" "&address=" address "&startblock=0&endblock=99999999&sort=desc&page=1&offset=10" (when api-key (str "&apikey=" api-key))) {:accept :json}) :body (#(parse-string % true)) :result (map #(select-keys % [:hash :timeStamp])) (filter (comp (partial < (- (quot (System/currentTimeMillis) 1000) (* 60 mins-ago))) #(Integer. %) :timeStamp)) count pos?)) (defn alert-if-no-tx-since-time [address mins-ago & {:keys [api-key gmail-cred notify-email]}] (when-not (any-tx-since-time? address mins-ago :api-key api-key) (send-message (merge {:host "smtp.gmail.com" :ssl :yes!!!11} gmail-cred) {:from (:user gmail-cred) :to notify-email :subject "No Recent Transactions" :body (str "This is an alert that there have not been any " "transactions in the past " mins-ago " minutes " "on address " address ".")}))) (defn -main [] (alert-if-no-tx-since-time "0x1E26b3D07E57F453caE30F7DDd2f945f5bF3EF33" ;; Ethereum address to track 20 ;; notify email if no tx in last 20 minutes :api-key "PI:KEY:<KEY>END_PI" ;; API Key for Etherscan (optional) :gmail-cred {:user "PI:EMAIL:<EMAIL>END_PI" ;; Gmail login info for sending out the email :pass "PI:PASSWORD:<PASSWORD>END_PI"} :notify-email "PI:EMAIL:<EMAIL>END_PI")) ;; where to send notification email to
[ { "context": "))\n\n\n(deftest key-reads\n (let [k1 (key/create [1 2 3])\n r1 {:foo 123}\n k2 (key/create ", "end": 519, "score": 0.6979838609695435, "start": 518, "tag": "KEY", "value": "2" }, { "context": "\n\n\n(deftest key-reads\n (let [k1 (key/create [1 2 3])\n r1 {:foo 123}\n k2 (key/create [4", "end": 521, "score": 0.6503474712371826, "start": 520, "tag": "KEY", "value": "3" }, { "context": "3])\n r1 {:foo 123}\n k2 (key/create [4 5 6])\n r2 {:foo 456}\n tablet (tablet/fr", "end": 575, "score": 0.9804102182388306, "start": 570, "tag": "KEY", "value": "4 5 6" }, { "context": "))\n\n\n(deftest batch-reads\n (let [k1 (key/create [1 2 3])\n r1 {:foo 123}\n k2 (key/create [4", "end": 1067, "score": 0.7872893214225769, "start": 1062, "tag": "KEY", "value": "1 2 3" }, { "context": "3])\n r1 {:foo 123}\n k2 (key/create [4 5 6])\n r2 {:foo 456}\n tablet (tablet/fr", "end": 1121, "score": 0.9646856188774109, "start": 1116, "tag": "KEY", "value": "4 5 6" } ]
lib/core/test/merkle_db/tablet_test.clj
greglook/merkle-db
47
(ns merkle-db.tablet-test (:require [clojure.spec.alpha :as s] [clojure.test :refer :all] [merkle-db.key :as key] [merkle-db.tablet :as tablet] [merkle-db.test-utils])) (def empty-tablet (tablet/from-records [])) (deftest tablet-spec (is (invalid? ::tablet/node-data nil)) (is (invalid? ::tablet/node-data [])) (is (invalid? ::tablet/node-data {})) (is (valid? ::tablet/node-data (tablet/from-records [[(key/create [0]) {:a 123}]])))) (deftest key-reads (let [k1 (key/create [1 2 3]) r1 {:foo 123} k2 (key/create [4 5 6]) r2 {:foo 456} tablet (tablet/from-records {k1 r1, k2 r2})] (is (= k2 (tablet/nth-key tablet 1))) (is (thrown? Exception (tablet/nth-key tablet -1))) (is (thrown? Exception (tablet/nth-key tablet 3))) (is (= [k1 k2] (tablet/keys tablet))) (is (= [[k1 r1]] (tablet/read-batch tablet #{k1}))) (is (= [[k1 r1] [k2 r2]] (tablet/read-batch tablet #{k1 k2}))))) (deftest batch-reads (let [k1 (key/create [1 2 3]) r1 {:foo 123} k2 (key/create [4 5 6]) r2 {:foo 456} tablet (tablet/from-records {k1 r1, k2 r2})] (is (empty? (tablet/read-batch empty-tablet nil))) (is (= [[k1 r1]] (tablet/read-batch tablet #{k1}))) (is (= [[k1 r1] [k2 r2]] (tablet/read-batch tablet #{k1 k2}))))) (deftest range-reads (let [k0 (key/create [0]) k1 (key/create [1]) k2 (key/create [2]) r0 {:foo 123} r1 {:foo 456} r2 {:foo 789} tablet (tablet/from-records {k0 r0, k1 r1, k2 r2})] (is (empty? (tablet/read-range empty-tablet nil nil))) (is (= [[k0 r0] [k1 r1] [k2 r2]] (tablet/read-range tablet nil nil))) (is (= [[k0 r0] [k1 r1]] (tablet/read-range tablet nil k1))) (is (= [[k2 r2]] (tablet/read-range tablet k2 nil))) (is (= [[k1 r1]] (tablet/read-range tablet (key/create [0 0]) (key/create [1 5])))) (is (empty? (tablet/read-range tablet (key/create [3]) (key/create [7])))))) (deftest tablet-utilities (let [k1 (key/create [1 2 3]) r1 {:foo 123} k2 (key/create [2 3 4]) r2 {:bar "baz"} tablet (tablet/from-records {k1 r1, k2 r2})] (is (= k1 (tablet/first-key tablet))) (is (= k2 (tablet/last-key tablet))))) (deftest tablet-joining (let [k1 (key/create [1 2 3]) r1 {:foo 123} t1 (tablet/from-records {k1 r1}) k2 (key/create [2 3 4]) r2 {:bar "baz"} t2 (tablet/from-records {k2 r2})] (is (thrown? Exception (tablet/join t2 t1))) (let [tablet (tablet/join t1 t2)] (is (= [[k1 r1] [k2 r2]] (tablet/read-all tablet)))) (is (identical? t1 (tablet/join t1 nil))) (is (identical? t2 (tablet/join nil t2))))) (deftest record-pruning (let [k1 (key/create [1 2 3]) r1 {:foo 123} k2 (key/create [4 5 6]) r2 {:foo 456} k3 (key/create [7 8 9]) r3 {:foo 789} tablet (tablet/from-records {k1 r1, k2 r2, k3 r3})] (is (= [[k1 r1]] (tablet/read-all (tablet/prune (tablet/from-records {k1 r1, k2 {}})))))))
104120
(ns merkle-db.tablet-test (:require [clojure.spec.alpha :as s] [clojure.test :refer :all] [merkle-db.key :as key] [merkle-db.tablet :as tablet] [merkle-db.test-utils])) (def empty-tablet (tablet/from-records [])) (deftest tablet-spec (is (invalid? ::tablet/node-data nil)) (is (invalid? ::tablet/node-data [])) (is (invalid? ::tablet/node-data {})) (is (valid? ::tablet/node-data (tablet/from-records [[(key/create [0]) {:a 123}]])))) (deftest key-reads (let [k1 (key/create [1 <KEY> <KEY>]) r1 {:foo 123} k2 (key/create [<KEY>]) r2 {:foo 456} tablet (tablet/from-records {k1 r1, k2 r2})] (is (= k2 (tablet/nth-key tablet 1))) (is (thrown? Exception (tablet/nth-key tablet -1))) (is (thrown? Exception (tablet/nth-key tablet 3))) (is (= [k1 k2] (tablet/keys tablet))) (is (= [[k1 r1]] (tablet/read-batch tablet #{k1}))) (is (= [[k1 r1] [k2 r2]] (tablet/read-batch tablet #{k1 k2}))))) (deftest batch-reads (let [k1 (key/create [<KEY>]) r1 {:foo 123} k2 (key/create [<KEY>]) r2 {:foo 456} tablet (tablet/from-records {k1 r1, k2 r2})] (is (empty? (tablet/read-batch empty-tablet nil))) (is (= [[k1 r1]] (tablet/read-batch tablet #{k1}))) (is (= [[k1 r1] [k2 r2]] (tablet/read-batch tablet #{k1 k2}))))) (deftest range-reads (let [k0 (key/create [0]) k1 (key/create [1]) k2 (key/create [2]) r0 {:foo 123} r1 {:foo 456} r2 {:foo 789} tablet (tablet/from-records {k0 r0, k1 r1, k2 r2})] (is (empty? (tablet/read-range empty-tablet nil nil))) (is (= [[k0 r0] [k1 r1] [k2 r2]] (tablet/read-range tablet nil nil))) (is (= [[k0 r0] [k1 r1]] (tablet/read-range tablet nil k1))) (is (= [[k2 r2]] (tablet/read-range tablet k2 nil))) (is (= [[k1 r1]] (tablet/read-range tablet (key/create [0 0]) (key/create [1 5])))) (is (empty? (tablet/read-range tablet (key/create [3]) (key/create [7])))))) (deftest tablet-utilities (let [k1 (key/create [1 2 3]) r1 {:foo 123} k2 (key/create [2 3 4]) r2 {:bar "baz"} tablet (tablet/from-records {k1 r1, k2 r2})] (is (= k1 (tablet/first-key tablet))) (is (= k2 (tablet/last-key tablet))))) (deftest tablet-joining (let [k1 (key/create [1 2 3]) r1 {:foo 123} t1 (tablet/from-records {k1 r1}) k2 (key/create [2 3 4]) r2 {:bar "baz"} t2 (tablet/from-records {k2 r2})] (is (thrown? Exception (tablet/join t2 t1))) (let [tablet (tablet/join t1 t2)] (is (= [[k1 r1] [k2 r2]] (tablet/read-all tablet)))) (is (identical? t1 (tablet/join t1 nil))) (is (identical? t2 (tablet/join nil t2))))) (deftest record-pruning (let [k1 (key/create [1 2 3]) r1 {:foo 123} k2 (key/create [4 5 6]) r2 {:foo 456} k3 (key/create [7 8 9]) r3 {:foo 789} tablet (tablet/from-records {k1 r1, k2 r2, k3 r3})] (is (= [[k1 r1]] (tablet/read-all (tablet/prune (tablet/from-records {k1 r1, k2 {}})))))))
true
(ns merkle-db.tablet-test (:require [clojure.spec.alpha :as s] [clojure.test :refer :all] [merkle-db.key :as key] [merkle-db.tablet :as tablet] [merkle-db.test-utils])) (def empty-tablet (tablet/from-records [])) (deftest tablet-spec (is (invalid? ::tablet/node-data nil)) (is (invalid? ::tablet/node-data [])) (is (invalid? ::tablet/node-data {})) (is (valid? ::tablet/node-data (tablet/from-records [[(key/create [0]) {:a 123}]])))) (deftest key-reads (let [k1 (key/create [1 PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI]) r1 {:foo 123} k2 (key/create [PI:KEY:<KEY>END_PI]) r2 {:foo 456} tablet (tablet/from-records {k1 r1, k2 r2})] (is (= k2 (tablet/nth-key tablet 1))) (is (thrown? Exception (tablet/nth-key tablet -1))) (is (thrown? Exception (tablet/nth-key tablet 3))) (is (= [k1 k2] (tablet/keys tablet))) (is (= [[k1 r1]] (tablet/read-batch tablet #{k1}))) (is (= [[k1 r1] [k2 r2]] (tablet/read-batch tablet #{k1 k2}))))) (deftest batch-reads (let [k1 (key/create [PI:KEY:<KEY>END_PI]) r1 {:foo 123} k2 (key/create [PI:KEY:<KEY>END_PI]) r2 {:foo 456} tablet (tablet/from-records {k1 r1, k2 r2})] (is (empty? (tablet/read-batch empty-tablet nil))) (is (= [[k1 r1]] (tablet/read-batch tablet #{k1}))) (is (= [[k1 r1] [k2 r2]] (tablet/read-batch tablet #{k1 k2}))))) (deftest range-reads (let [k0 (key/create [0]) k1 (key/create [1]) k2 (key/create [2]) r0 {:foo 123} r1 {:foo 456} r2 {:foo 789} tablet (tablet/from-records {k0 r0, k1 r1, k2 r2})] (is (empty? (tablet/read-range empty-tablet nil nil))) (is (= [[k0 r0] [k1 r1] [k2 r2]] (tablet/read-range tablet nil nil))) (is (= [[k0 r0] [k1 r1]] (tablet/read-range tablet nil k1))) (is (= [[k2 r2]] (tablet/read-range tablet k2 nil))) (is (= [[k1 r1]] (tablet/read-range tablet (key/create [0 0]) (key/create [1 5])))) (is (empty? (tablet/read-range tablet (key/create [3]) (key/create [7])))))) (deftest tablet-utilities (let [k1 (key/create [1 2 3]) r1 {:foo 123} k2 (key/create [2 3 4]) r2 {:bar "baz"} tablet (tablet/from-records {k1 r1, k2 r2})] (is (= k1 (tablet/first-key tablet))) (is (= k2 (tablet/last-key tablet))))) (deftest tablet-joining (let [k1 (key/create [1 2 3]) r1 {:foo 123} t1 (tablet/from-records {k1 r1}) k2 (key/create [2 3 4]) r2 {:bar "baz"} t2 (tablet/from-records {k2 r2})] (is (thrown? Exception (tablet/join t2 t1))) (let [tablet (tablet/join t1 t2)] (is (= [[k1 r1] [k2 r2]] (tablet/read-all tablet)))) (is (identical? t1 (tablet/join t1 nil))) (is (identical? t2 (tablet/join nil t2))))) (deftest record-pruning (let [k1 (key/create [1 2 3]) r1 {:foo 123} k2 (key/create [4 5 6]) r2 {:foo 456} k3 (key/create [7 8 9]) r3 {:foo 789} tablet (tablet/from-records {k1 r1, k2 r2, k3 r3})] (is (= [[k1 r1]] (tablet/read-all (tablet/prune (tablet/from-records {k1 r1, k2 {}})))))))
[ { "context": "nsole-print!)\n\n(def app-state (api/init {:apikey \"test\" ;:host \"95.217.155.168:7000\"\n ", "end": 168, "score": 0.8016061186790466, "start": 164, "tag": "KEY", "value": "test" }, { "context": "\n(def app-state (api/init {:apikey \"test\" ;:host \"95.217.155.168:7000\"\n :protocol :https ", "end": 192, "score": 0.999732494354248, "start": 178, "tag": "IP_ADDRESS", "value": "95.217.155.168" } ]
src/cljs/template/app.cljs
liszper/command-control
0
(ns template.app (:require [reagent.core :as r] [brave.cmc :as api] [bide.core :as b])) (enable-console-print!) (def app-state (api/init {:apikey "test" ;:host "95.217.155.168:7000" :protocol :https :reagent? true})) (defn home-page [app-state] [:div "Home 2" [:p (str @app-state)] [:a {:on-click #(swap! app-state assoc "counter" (rand-int 1000))} "Assoc"] ]) (defn about-page [] [:div "About"]) (defn transform-map [rmap] (into [] (for [[r u] rmap] [u r]))) (defn make-bide-router [rmap] (b/router (transform-map rmap))) (def route-map {:template.home "/home" :template.about "/about"}) (def router (make-bide-router route-map)) (defn nav-link [route text] [:a {:href (route route-map) :on-click #(do (-> % .preventDefault) (b/navigate! router route))} text]) (defn page [name app-state] [:div [:nav [:div [nav-link :template.home "Home"]] [:div [nav-link :template.about "About"]]] (case name :template.home (home-page app-state) :template.about [about-page])]) (defn ^:export render [name] (r/render [page name app-state] (js/document.getElementById "app"))) (defn ^:export navigate "A function which will be called on each route change." [name params query] (println "Route change to: " name params query) (render name)) (defn ^:export init [] (println "Loading..") (b/start! router {:default :template.home :html5? true :on-navigate (fn [name params query] (navigate name params query))}))
77584
(ns template.app (:require [reagent.core :as r] [brave.cmc :as api] [bide.core :as b])) (enable-console-print!) (def app-state (api/init {:apikey "<KEY>" ;:host "172.16.17.32:7000" :protocol :https :reagent? true})) (defn home-page [app-state] [:div "Home 2" [:p (str @app-state)] [:a {:on-click #(swap! app-state assoc "counter" (rand-int 1000))} "Assoc"] ]) (defn about-page [] [:div "About"]) (defn transform-map [rmap] (into [] (for [[r u] rmap] [u r]))) (defn make-bide-router [rmap] (b/router (transform-map rmap))) (def route-map {:template.home "/home" :template.about "/about"}) (def router (make-bide-router route-map)) (defn nav-link [route text] [:a {:href (route route-map) :on-click #(do (-> % .preventDefault) (b/navigate! router route))} text]) (defn page [name app-state] [:div [:nav [:div [nav-link :template.home "Home"]] [:div [nav-link :template.about "About"]]] (case name :template.home (home-page app-state) :template.about [about-page])]) (defn ^:export render [name] (r/render [page name app-state] (js/document.getElementById "app"))) (defn ^:export navigate "A function which will be called on each route change." [name params query] (println "Route change to: " name params query) (render name)) (defn ^:export init [] (println "Loading..") (b/start! router {:default :template.home :html5? true :on-navigate (fn [name params query] (navigate name params query))}))
true
(ns template.app (:require [reagent.core :as r] [brave.cmc :as api] [bide.core :as b])) (enable-console-print!) (def app-state (api/init {:apikey "PI:KEY:<KEY>END_PI" ;:host "PI:IP_ADDRESS:172.16.17.32END_PI:7000" :protocol :https :reagent? true})) (defn home-page [app-state] [:div "Home 2" [:p (str @app-state)] [:a {:on-click #(swap! app-state assoc "counter" (rand-int 1000))} "Assoc"] ]) (defn about-page [] [:div "About"]) (defn transform-map [rmap] (into [] (for [[r u] rmap] [u r]))) (defn make-bide-router [rmap] (b/router (transform-map rmap))) (def route-map {:template.home "/home" :template.about "/about"}) (def router (make-bide-router route-map)) (defn nav-link [route text] [:a {:href (route route-map) :on-click #(do (-> % .preventDefault) (b/navigate! router route))} text]) (defn page [name app-state] [:div [:nav [:div [nav-link :template.home "Home"]] [:div [nav-link :template.about "About"]]] (case name :template.home (home-page app-state) :template.about [about-page])]) (defn ^:export render [name] (r/render [page name app-state] (js/document.getElementById "app"))) (defn ^:export navigate "A function which will be called on each route change." [name params query] (println "Route change to: " name params query) (render name)) (defn ^:export init [] (println "Loading..") (b/start! router {:default :template.home :html5? true :on-navigate (fn [name params query] (navigate name params query))}))
[ { "context": " spam-word \"ICO\")\n\n(def messages\n '(\"Hi, it's me, Ronald. Let's go bowling?\"\n \"@richhickey approved you", "end": 166, "score": 0.9992169737815857, "start": 160, "tag": "NAME", "value": "Ronald" }, { "context": " '(\"Hi, it's me, Ronald. Let's go bowling?\"\n \"@richhickey approved your Pull Request.\"\n \"New promising s", "end": 203, "score": 0.9995929598808289, "start": 193, "tag": "USERNAME", "value": "richhickey" }, { "context": "on machine. Participate in ICO now!\"\n \"Hi, it's Greg, are you up for a beer tonight?\"))\n\n(defn spam?\n ", "end": 340, "score": 0.9985274076461792, "start": 336, "tag": "NAME", "value": "Greg" } ]
src/laxam_clojure_tutorial_part2_spam_filter/core.clj
laxamenator/laxam-clojure-tutorial-part2-spam-filter
0
(ns laxam-clojure-tutorial-part2-spam-filter.core (:require [clojure.string :as str]) (:gen-class)) (def spam-word "ICO") (def messages '("Hi, it's me, Ronald. Let's go bowling?" "@richhickey approved your Pull Request." "New promising startup works on a perpetual motion machine. Participate in ICO now!" "Hi, it's Greg, are you up for a beer tonight?")) (defn spam? "Takes one message as an argument and returns true if it is spam, otherwise false" [message] (contains? (set (str/split message #"\W+")) spam-word)) (defn -main [& args] (doall (map println (remove spam? messages))))
92727
(ns laxam-clojure-tutorial-part2-spam-filter.core (:require [clojure.string :as str]) (:gen-class)) (def spam-word "ICO") (def messages '("Hi, it's me, <NAME>. Let's go bowling?" "@richhickey approved your Pull Request." "New promising startup works on a perpetual motion machine. Participate in ICO now!" "Hi, it's <NAME>, are you up for a beer tonight?")) (defn spam? "Takes one message as an argument and returns true if it is spam, otherwise false" [message] (contains? (set (str/split message #"\W+")) spam-word)) (defn -main [& args] (doall (map println (remove spam? messages))))
true
(ns laxam-clojure-tutorial-part2-spam-filter.core (:require [clojure.string :as str]) (:gen-class)) (def spam-word "ICO") (def messages '("Hi, it's me, PI:NAME:<NAME>END_PI. Let's go bowling?" "@richhickey approved your Pull Request." "New promising startup works on a perpetual motion machine. Participate in ICO now!" "Hi, it's PI:NAME:<NAME>END_PI, are you up for a beer tonight?")) (defn spam? "Takes one message as an argument and returns true if it is spam, otherwise false" [message] (contains? (set (str/split message #"\W+")) spam-word)) (defn -main [& args] (doall (map println (remove spam? messages))))
[ { "context": "cha - ChaCha\n :salsa20 - Salsa20\"\n {:author \"Jason Ozias\"})\n\n(defmulti iv-size-bits\n \"### iv-size", "end": 328, "score": 0.9998800158500671, "start": 317, "tag": "NAME", "value": "Jason Ozias" } ]
data/train/clojure/ceed65fb02a886a0afdb792ac8e24d68eb261925streamcipher.clj
harshp8l/deep-learning-lang-detection
84
(ns azjure.cipher.streamcipher "## Stream Cipher Stream cipher multimethod definitions. All stream ciphers should define defmethods for these multimethods. The currently supported stream cipher type keywords for use in the configuration map are: :chacha - ChaCha :salsa20 - Salsa20" {:author "Jason Ozias"}) (defmulti iv-size-bits "### iv-size-bits Evaluates to the IV size in bits supported by the stream cipher in bits" {:added "0.2.0"} :type) (defmulti keystream-size-bytes "### keystream-size-bytes Evaluates to the keystream size supported by the stream cipher in bytes under one key. This is generally a large value." {:added "0.2.0"} :type) (defmulti generate-keystream "### generate-keystream Generate the stream cipher keystream" {:added "0.2.0"} :type)
75266
(ns azjure.cipher.streamcipher "## Stream Cipher Stream cipher multimethod definitions. All stream ciphers should define defmethods for these multimethods. The currently supported stream cipher type keywords for use in the configuration map are: :chacha - ChaCha :salsa20 - Salsa20" {:author "<NAME>"}) (defmulti iv-size-bits "### iv-size-bits Evaluates to the IV size in bits supported by the stream cipher in bits" {:added "0.2.0"} :type) (defmulti keystream-size-bytes "### keystream-size-bytes Evaluates to the keystream size supported by the stream cipher in bytes under one key. This is generally a large value." {:added "0.2.0"} :type) (defmulti generate-keystream "### generate-keystream Generate the stream cipher keystream" {:added "0.2.0"} :type)
true
(ns azjure.cipher.streamcipher "## Stream Cipher Stream cipher multimethod definitions. All stream ciphers should define defmethods for these multimethods. The currently supported stream cipher type keywords for use in the configuration map are: :chacha - ChaCha :salsa20 - Salsa20" {:author "PI:NAME:<NAME>END_PI"}) (defmulti iv-size-bits "### iv-size-bits Evaluates to the IV size in bits supported by the stream cipher in bits" {:added "0.2.0"} :type) (defmulti keystream-size-bytes "### keystream-size-bytes Evaluates to the keystream size supported by the stream cipher in bytes under one key. This is generally a large value." {:added "0.2.0"} :type) (defmulti generate-keystream "### generate-keystream Generate the stream cipher keystream" {:added "0.2.0"} :type)
[ { "context": " \"Can mention user with message\"\n (t/is (= \"@**Miles McInnis** hey\"\n (sut/mention \"Miles McInnis\" ", "end": 357, "score": 0.9957035779953003, "start": 344, "tag": "USERNAME", "value": "Miles McInnis" }, { "context": "**Miles McInnis** hey\"\n (sut/mention \"Miles McInnis\" \"hey\"))))\n (t/testing \"Can mention user without", "end": 405, "score": 0.8213086128234863, "start": 392, "tag": "NAME", "value": "Miles McInnis" } ]
test/breakfastbot/markdown_test.clj
MNSignalProcessing/breakfastbot
0
(ns breakfastbot.markdown-test (:require [breakfastbot.markdown :as sut] [clojure.test :as t])) (t/deftest bullet-list (t/testing "Can create bullet list" (t/is (= "* Foo\n* Bar\n* Baz" (sut/bullet-list ["Foo" "Bar" "Baz"]))))) (t/deftest mention (t/testing "Can mention user with message" (t/is (= "@**Miles McInnis** hey" (sut/mention "Miles McInnis" "hey")))) (t/testing "Can mention user without message" (t/is (= "@**Firstname Lastname**" (sut/mention "Firstname Lastname")))))
100454
(ns breakfastbot.markdown-test (:require [breakfastbot.markdown :as sut] [clojure.test :as t])) (t/deftest bullet-list (t/testing "Can create bullet list" (t/is (= "* Foo\n* Bar\n* Baz" (sut/bullet-list ["Foo" "Bar" "Baz"]))))) (t/deftest mention (t/testing "Can mention user with message" (t/is (= "@**Miles McInnis** hey" (sut/mention "<NAME>" "hey")))) (t/testing "Can mention user without message" (t/is (= "@**Firstname Lastname**" (sut/mention "Firstname Lastname")))))
true
(ns breakfastbot.markdown-test (:require [breakfastbot.markdown :as sut] [clojure.test :as t])) (t/deftest bullet-list (t/testing "Can create bullet list" (t/is (= "* Foo\n* Bar\n* Baz" (sut/bullet-list ["Foo" "Bar" "Baz"]))))) (t/deftest mention (t/testing "Can mention user with message" (t/is (= "@**Miles McInnis** hey" (sut/mention "PI:NAME:<NAME>END_PI" "hey")))) (t/testing "Can mention user without message" (t/is (= "@**Firstname Lastname**" (sut/mention "Firstname Lastname")))))
[ { "context": "(ns ^{:author \"Adam Berger\"} ulvm.core-spec-test\n \"Spec tests for ulvm.core", "end": 26, "score": 0.9998553395271301, "start": 15, "tag": "NAME", "value": "Adam Berger" }, { "context": "/runnable-env-descriptor {:url \"http://github.com/ulvm/contrib/1.2.3/runnable-env-loaders.ulvm\"}}})\n\n (", "end": 3042, "score": 0.9945651292800903, "start": 3038, "tag": "USERNAME", "value": "ulvm" }, { "context": "/runnable-env-descriptor {:url \"http://github.com/ulvm/contrib/1.2.3/runnable-env-loaders.ulvm\"}}\n :", "end": 3340, "score": 0.9981476068496704, "start": 3336, "tag": "USERNAME", "value": "ulvm" } ]
test/ulvm/core_spec_test.clj
abrgr/ulvm
0
(ns ^{:author "Adam Berger"} ulvm.core-spec-test "Spec tests for ulvm.core" (:require [clojure.spec.test :as st] [ulvm.core :as ulvm]) (:use [clojure.test :only [deftest]])) (defn flowfile-examples [] (ulvm/defmodcombinator :mvn "Description of mvn combinator" {:ulvm.core/runnable-env-ref {:ulvm.core/builtin-runnable-env-loader-name :ulvm.runnable-env-loaders/http :ulvm.core/runnable-env-descriptor {:url "http://github.com/ulvm/contrib/1.2.3/mvn-runnable-env.ulvm"}}}) (ulvm/defscope :my-scope "Description of scope" {:ulvm.core/runnable-env-ref {:ulvm.core/builtin-runnable-env-loader-name :ulvm.core/project-file :ulvm.core/runnable-env-descriptor {:path "scopes/nodejs.ulvm"}} :ulvm.core/modules {:adder {:ulvm.core/mod-combinator-name :mvn :ulvm.core/mod-descriptor {:name "my-adder"}} :db-saver {:ulvm.core/mod-combinator-name :mvn :ulvm.core/mod-descriptor {:name "my-db-saver"}}} :ulvm.core/init ((adder {:v1 42} :as my-adder))}) (ulvm/defflow :simple [] ; this flow's result has g as its error value and c as its default return value {:ulvm.core/output-descriptor {:err [g], :ret [c]}} ; invoke module A in scope-1 with no args, result is named 'a ((:A scope-1) {} :as a) ; invoke module B in scope-2 with arg-1 set to the default return of a, result is named 'b ((:B scope-2) {:arg-1 a} :as b) ; invoke module C in scope-1 with val set to the default return of a, result is named 'c ((:C scope-1) {:val a} :as c) ; invoke module G in scope-1 with first-val set to the other-ret return of a ((:G scope-1) {:first-val (:other-ret a)}) ; invoke module D in scope-2 with v1 set to the default return of b and v2 set to the default return of c ((:D scope-2) {:v1 b, :v2 c})) (ulvm/defflow :err-handling [] ; this flow's result has g as its error value and c as its default return value {:ulvm.core/output-descriptor {:err [g], :ret [c]}} ; invoke module A in scope-1 with no args, result is named 'a ((:A scope-1) {} :as a) ((:B scope-1) {:the-val a} :as v1) ((:C scope-1) {:val-1 a, :val-2 v1} :as c) ((:log-err scope-1) {:err (:err a)} :as g)) (ulvm/defflow :err-recovery [] ; this flow's result has c as its default return value {:ulvm.core/output-descriptor {:ret [c b]}} ; invoke module A in scope-1 with no args, result is named 'a ((:A scope-1) {} :as a) ; log and b are calculated iff a returns an error ((:log-err scope-1) {:err (:err a)} :as log) ((:B scope-1) {} :as b :after log))) (defn runnable-env-examples [] (ulvm.core/defrunnableenvloader :auth-http-re-loader "Defines an http runnable environment loader that uses some special auth scheme" {:ulvm.core/runnable-env-ref {:ulvm.core/builtin-runnable-env-loader-name :ulvm.runnable-env-loaders/http :ulvm.core/runnable-env-descriptor {:url "http://github.com/ulvm/contrib/1.2.3/runnable-env-loaders.ulvm"}}}) (ulvm.core/defrunner :http-get-runner "Sends a get request" {:ulvm.core/runnable-env-ref {:ulvm.core/builtin-runnable-env-loader-name :ulvm.runnable-env-loaders/http :ulvm.core/runnable-env-descriptor {:url "http://github.com/ulvm/contrib/1.2.3/runnable-env-loaders.ulvm"}} :ulvm.core/ideal-flow ulvm.core.get-runnable-env}) (ulvm.core/defrunnableenv :mvn "Maven Loader Environment" {:ulvm.core/ns :org.ulvm.maven :ulvm.core/runnable-scopes {:mvn {:ulvm.core/artifact-loader {:ulvm.core/builtin-artifact-loader-name :ulvm.artifact-loaders/docker-hub :ulvm.core/artifact-descriptor {:name "ulvm-mvn" :version "1.0"}} ; module adds items to env under joint namespace ({ns}, ulvm.artifact-loaders.docker-hub)/{scope-name}/ (e.g. #{org.ulvm.maven ulvm.artifact-loaders.docker-hub}/mvn/{docker-image, version, etc}) :ulvm.core/runner {:ulvm.core/builtin-runner-name :ulvm.runners/docker-container :ulvm.core/runner-descriptor {:volumes [{:src (ulvm.core/from-env :org.ulvm.maven/mvn-cache-dir) :dest "/m2/cache" :mode "ro"}]} :env {:mvn-username :org.ulvm.maven/mvn-username}}}} :ulvm.core/exported-flows {:org.ulvm.maven/mvn-install {:ulvm.core/runner {:ulvm.core/runner-name :ulvm.runners/http :ulvm.core/runner-descriptor {:method "post" :host (ulvm.core/from-env [#{:org.ulvm.maven :ulvm.runners.docker-container} :mvn :container-ip]) :body :ulvm.core/mod-descriptor}} :ulvm.core/ideal-flows #{:org.ulvm.mod-combinator}}}})) (deftest flowfile-examples-match-specs (st/instrument (st/instrumentable-syms 'ulvm)) (flowfile-examples)) ; TODO: a custom loader specifies a runnable-env loader; we pull the env-template, run all of the scopes (do we need ordering among them?), find the org.ulvm.loader ideal-flow, and invoke it. ; TODO: we build up an environment map with the results returned from running all scopes and make that env available when running a flow runner (deftest runnable-env-examples-match-specs (st/instrument (st/instrumentable-syms 'ulvm)) (runnable-env-examples))
18055
(ns ^{:author "<NAME>"} ulvm.core-spec-test "Spec tests for ulvm.core" (:require [clojure.spec.test :as st] [ulvm.core :as ulvm]) (:use [clojure.test :only [deftest]])) (defn flowfile-examples [] (ulvm/defmodcombinator :mvn "Description of mvn combinator" {:ulvm.core/runnable-env-ref {:ulvm.core/builtin-runnable-env-loader-name :ulvm.runnable-env-loaders/http :ulvm.core/runnable-env-descriptor {:url "http://github.com/ulvm/contrib/1.2.3/mvn-runnable-env.ulvm"}}}) (ulvm/defscope :my-scope "Description of scope" {:ulvm.core/runnable-env-ref {:ulvm.core/builtin-runnable-env-loader-name :ulvm.core/project-file :ulvm.core/runnable-env-descriptor {:path "scopes/nodejs.ulvm"}} :ulvm.core/modules {:adder {:ulvm.core/mod-combinator-name :mvn :ulvm.core/mod-descriptor {:name "my-adder"}} :db-saver {:ulvm.core/mod-combinator-name :mvn :ulvm.core/mod-descriptor {:name "my-db-saver"}}} :ulvm.core/init ((adder {:v1 42} :as my-adder))}) (ulvm/defflow :simple [] ; this flow's result has g as its error value and c as its default return value {:ulvm.core/output-descriptor {:err [g], :ret [c]}} ; invoke module A in scope-1 with no args, result is named 'a ((:A scope-1) {} :as a) ; invoke module B in scope-2 with arg-1 set to the default return of a, result is named 'b ((:B scope-2) {:arg-1 a} :as b) ; invoke module C in scope-1 with val set to the default return of a, result is named 'c ((:C scope-1) {:val a} :as c) ; invoke module G in scope-1 with first-val set to the other-ret return of a ((:G scope-1) {:first-val (:other-ret a)}) ; invoke module D in scope-2 with v1 set to the default return of b and v2 set to the default return of c ((:D scope-2) {:v1 b, :v2 c})) (ulvm/defflow :err-handling [] ; this flow's result has g as its error value and c as its default return value {:ulvm.core/output-descriptor {:err [g], :ret [c]}} ; invoke module A in scope-1 with no args, result is named 'a ((:A scope-1) {} :as a) ((:B scope-1) {:the-val a} :as v1) ((:C scope-1) {:val-1 a, :val-2 v1} :as c) ((:log-err scope-1) {:err (:err a)} :as g)) (ulvm/defflow :err-recovery [] ; this flow's result has c as its default return value {:ulvm.core/output-descriptor {:ret [c b]}} ; invoke module A in scope-1 with no args, result is named 'a ((:A scope-1) {} :as a) ; log and b are calculated iff a returns an error ((:log-err scope-1) {:err (:err a)} :as log) ((:B scope-1) {} :as b :after log))) (defn runnable-env-examples [] (ulvm.core/defrunnableenvloader :auth-http-re-loader "Defines an http runnable environment loader that uses some special auth scheme" {:ulvm.core/runnable-env-ref {:ulvm.core/builtin-runnable-env-loader-name :ulvm.runnable-env-loaders/http :ulvm.core/runnable-env-descriptor {:url "http://github.com/ulvm/contrib/1.2.3/runnable-env-loaders.ulvm"}}}) (ulvm.core/defrunner :http-get-runner "Sends a get request" {:ulvm.core/runnable-env-ref {:ulvm.core/builtin-runnable-env-loader-name :ulvm.runnable-env-loaders/http :ulvm.core/runnable-env-descriptor {:url "http://github.com/ulvm/contrib/1.2.3/runnable-env-loaders.ulvm"}} :ulvm.core/ideal-flow ulvm.core.get-runnable-env}) (ulvm.core/defrunnableenv :mvn "Maven Loader Environment" {:ulvm.core/ns :org.ulvm.maven :ulvm.core/runnable-scopes {:mvn {:ulvm.core/artifact-loader {:ulvm.core/builtin-artifact-loader-name :ulvm.artifact-loaders/docker-hub :ulvm.core/artifact-descriptor {:name "ulvm-mvn" :version "1.0"}} ; module adds items to env under joint namespace ({ns}, ulvm.artifact-loaders.docker-hub)/{scope-name}/ (e.g. #{org.ulvm.maven ulvm.artifact-loaders.docker-hub}/mvn/{docker-image, version, etc}) :ulvm.core/runner {:ulvm.core/builtin-runner-name :ulvm.runners/docker-container :ulvm.core/runner-descriptor {:volumes [{:src (ulvm.core/from-env :org.ulvm.maven/mvn-cache-dir) :dest "/m2/cache" :mode "ro"}]} :env {:mvn-username :org.ulvm.maven/mvn-username}}}} :ulvm.core/exported-flows {:org.ulvm.maven/mvn-install {:ulvm.core/runner {:ulvm.core/runner-name :ulvm.runners/http :ulvm.core/runner-descriptor {:method "post" :host (ulvm.core/from-env [#{:org.ulvm.maven :ulvm.runners.docker-container} :mvn :container-ip]) :body :ulvm.core/mod-descriptor}} :ulvm.core/ideal-flows #{:org.ulvm.mod-combinator}}}})) (deftest flowfile-examples-match-specs (st/instrument (st/instrumentable-syms 'ulvm)) (flowfile-examples)) ; TODO: a custom loader specifies a runnable-env loader; we pull the env-template, run all of the scopes (do we need ordering among them?), find the org.ulvm.loader ideal-flow, and invoke it. ; TODO: we build up an environment map with the results returned from running all scopes and make that env available when running a flow runner (deftest runnable-env-examples-match-specs (st/instrument (st/instrumentable-syms 'ulvm)) (runnable-env-examples))
true
(ns ^{:author "PI:NAME:<NAME>END_PI"} ulvm.core-spec-test "Spec tests for ulvm.core" (:require [clojure.spec.test :as st] [ulvm.core :as ulvm]) (:use [clojure.test :only [deftest]])) (defn flowfile-examples [] (ulvm/defmodcombinator :mvn "Description of mvn combinator" {:ulvm.core/runnable-env-ref {:ulvm.core/builtin-runnable-env-loader-name :ulvm.runnable-env-loaders/http :ulvm.core/runnable-env-descriptor {:url "http://github.com/ulvm/contrib/1.2.3/mvn-runnable-env.ulvm"}}}) (ulvm/defscope :my-scope "Description of scope" {:ulvm.core/runnable-env-ref {:ulvm.core/builtin-runnable-env-loader-name :ulvm.core/project-file :ulvm.core/runnable-env-descriptor {:path "scopes/nodejs.ulvm"}} :ulvm.core/modules {:adder {:ulvm.core/mod-combinator-name :mvn :ulvm.core/mod-descriptor {:name "my-adder"}} :db-saver {:ulvm.core/mod-combinator-name :mvn :ulvm.core/mod-descriptor {:name "my-db-saver"}}} :ulvm.core/init ((adder {:v1 42} :as my-adder))}) (ulvm/defflow :simple [] ; this flow's result has g as its error value and c as its default return value {:ulvm.core/output-descriptor {:err [g], :ret [c]}} ; invoke module A in scope-1 with no args, result is named 'a ((:A scope-1) {} :as a) ; invoke module B in scope-2 with arg-1 set to the default return of a, result is named 'b ((:B scope-2) {:arg-1 a} :as b) ; invoke module C in scope-1 with val set to the default return of a, result is named 'c ((:C scope-1) {:val a} :as c) ; invoke module G in scope-1 with first-val set to the other-ret return of a ((:G scope-1) {:first-val (:other-ret a)}) ; invoke module D in scope-2 with v1 set to the default return of b and v2 set to the default return of c ((:D scope-2) {:v1 b, :v2 c})) (ulvm/defflow :err-handling [] ; this flow's result has g as its error value and c as its default return value {:ulvm.core/output-descriptor {:err [g], :ret [c]}} ; invoke module A in scope-1 with no args, result is named 'a ((:A scope-1) {} :as a) ((:B scope-1) {:the-val a} :as v1) ((:C scope-1) {:val-1 a, :val-2 v1} :as c) ((:log-err scope-1) {:err (:err a)} :as g)) (ulvm/defflow :err-recovery [] ; this flow's result has c as its default return value {:ulvm.core/output-descriptor {:ret [c b]}} ; invoke module A in scope-1 with no args, result is named 'a ((:A scope-1) {} :as a) ; log and b are calculated iff a returns an error ((:log-err scope-1) {:err (:err a)} :as log) ((:B scope-1) {} :as b :after log))) (defn runnable-env-examples [] (ulvm.core/defrunnableenvloader :auth-http-re-loader "Defines an http runnable environment loader that uses some special auth scheme" {:ulvm.core/runnable-env-ref {:ulvm.core/builtin-runnable-env-loader-name :ulvm.runnable-env-loaders/http :ulvm.core/runnable-env-descriptor {:url "http://github.com/ulvm/contrib/1.2.3/runnable-env-loaders.ulvm"}}}) (ulvm.core/defrunner :http-get-runner "Sends a get request" {:ulvm.core/runnable-env-ref {:ulvm.core/builtin-runnable-env-loader-name :ulvm.runnable-env-loaders/http :ulvm.core/runnable-env-descriptor {:url "http://github.com/ulvm/contrib/1.2.3/runnable-env-loaders.ulvm"}} :ulvm.core/ideal-flow ulvm.core.get-runnable-env}) (ulvm.core/defrunnableenv :mvn "Maven Loader Environment" {:ulvm.core/ns :org.ulvm.maven :ulvm.core/runnable-scopes {:mvn {:ulvm.core/artifact-loader {:ulvm.core/builtin-artifact-loader-name :ulvm.artifact-loaders/docker-hub :ulvm.core/artifact-descriptor {:name "ulvm-mvn" :version "1.0"}} ; module adds items to env under joint namespace ({ns}, ulvm.artifact-loaders.docker-hub)/{scope-name}/ (e.g. #{org.ulvm.maven ulvm.artifact-loaders.docker-hub}/mvn/{docker-image, version, etc}) :ulvm.core/runner {:ulvm.core/builtin-runner-name :ulvm.runners/docker-container :ulvm.core/runner-descriptor {:volumes [{:src (ulvm.core/from-env :org.ulvm.maven/mvn-cache-dir) :dest "/m2/cache" :mode "ro"}]} :env {:mvn-username :org.ulvm.maven/mvn-username}}}} :ulvm.core/exported-flows {:org.ulvm.maven/mvn-install {:ulvm.core/runner {:ulvm.core/runner-name :ulvm.runners/http :ulvm.core/runner-descriptor {:method "post" :host (ulvm.core/from-env [#{:org.ulvm.maven :ulvm.runners.docker-container} :mvn :container-ip]) :body :ulvm.core/mod-descriptor}} :ulvm.core/ideal-flows #{:org.ulvm.mod-combinator}}}})) (deftest flowfile-examples-match-specs (st/instrument (st/instrumentable-syms 'ulvm)) (flowfile-examples)) ; TODO: a custom loader specifies a runnable-env loader; we pull the env-template, run all of the scopes (do we need ordering among them?), find the org.ulvm.loader ideal-flow, and invoke it. ; TODO: we build up an environment map with the results returned from running all scopes and make that env available when running a flow runner (deftest runnable-env-examples-match-specs (st/instrument (st/instrumentable-syms 'ulvm)) (runnable-env-examples))
[ { "context": "12 (count (all-matches nav \"//Name\"))))\n (is (= \"John Boehner\" (first (all-matches nav \"//Name\"))))\n (is (= \"L", "end": 3457, "score": 0.999879002571106, "start": 3445, "tag": "NAME", "value": "John Boehner" }, { "context": "r\" (first (all-matches nav \"//Name\"))))\n (is (= \"Lady Gaga\" (last (all-matches nav \"//Name\"))))\n ;; Run all", "end": 3515, "score": 0.9998853206634521, "start": 3506, "tag": "NAME", "value": "Lady Gaga" }, { "context": "matches president \"Employee/Name\"))))\n (is (= \"Barack Obama\" (first (all-matches\n ", "end": 3852, "score": 0.9998997449874878, "start": 3840, "tag": "NAME", "value": "Barack Obama" }, { "context": "Employee[@role='President']/Name\"))))\n (is (= \"Lady Gaga\" (last (all-matches president \"Employee/Name\"))))", "end": 4012, "score": 0.9998911023139954, "start": 4003, "tag": "NAME", "value": "Lady Gaga" }, { "context": "\"<Employee role=\\\"Elected Member\\\">\n <Name>John McCain</Name>\n </Employee>\"\n (first (get-xm", "end": 4592, "score": 0.9997081756591797, "start": 4581, "tag": "NAME", "value": "John McCain" }, { "context": " :attrs nil,\n :content [\"John McCain\"]}]}))\n (is (= 12 (count (get-hash nav \"//Employ", "end": 5321, "score": 0.9998334646224976, "start": 5310, "tag": "NAME", "value": "John McCain" }, { "context": "ns)\n org2 (nth organizations 1)]\n (is (= \"John Boehner\" (first-match org1 \"Employee/Name\")))\n (is (= \"", "end": 7272, "score": 0.999868631362915, "start": 7260, "tag": "NAME", "value": "John Boehner" }, { "context": "\" (first-match org1 \"Employee/Name\")))\n (is (= \"Willie Williams\" (first-match org1 \"Employee[@role='Staff']/Name\"", "end": 7337, "score": 0.9998828768730164, "start": 7322, "tag": "NAME", "value": "Willie Williams" }, { "context": "org1 \"Employee[@role='Staff']/Name\")))\n (is (= \"John McCain\" (first-match org2 \"Employee/Name\")))\n (is (= \"", "end": 7413, "score": 0.9998723864555359, "start": 7402, "tag": "NAME", "value": "John McCain" }, { "context": "\" (first-match org2 \"Employee/Name\")))\n (is (= \"Cassandra Hadoop\" (first-match org2 \"Employee[@role='Staff']/Name\"", "end": 7479, "score": 0.6834588646888733, "start": 7463, "tag": "NAME", "value": "Cassandra Hadoop" }, { "context": "Employee\")) ;; returns true on success\n (is (= \"John Boehner\" (first-match org1 \"Name\")))))\n\n\n;; -------------", "end": 11452, "score": 0.9996014833450317, "start": 11440, "tag": "NAME", "value": "John Boehner" }, { "context": " \"Employee\")) ;; move to last Employee\n (is (= \"Willie Williams\" (first-match org1 \"Name\")))\n (is (to-last-chil", "end": 12946, "score": 0.9997367262840271, "start": 12931, "tag": "NAME", "value": "Willie Williams" }, { "context": "ns)\n org2 (nth organizations 1)]\n (is (= \"John Boehner\" (first-match org1 \"ns2:Employee/Name\" ns-hash)))", "end": 17634, "score": 0.9998236894607544, "start": 17622, "tag": "NAME", "value": "John Boehner" }, { "context": "ch org1 \"ns2:Employee/Name\" ns-hash)))\n (is (= \"Willie Williams\" (first-match org1\n ", "end": 17711, "score": 0.9996256232261658, "start": 17696, "tag": "NAME", "value": "Willie Williams" }, { "context": " ns-hash)))\n (is (= \"John McCain\" (first-match org2 \"ns2:Employee/Name\" ns-hash)))", "end": 17881, "score": 0.999835729598999, "start": 17870, "tag": "NAME", "value": "John McCain" }, { "context": "h org2 \"ns2:Employee/Name\" ns-hash)))\n (is (= \"Cassandra Hadoop\" (first-match org2\n ", "end": 17959, "score": 0.9775833487510681, "start": 17944, "tag": "NAME", "value": "assandra Hadoop" }, { "context": "all-matches nav-ns \"//Name\" ns-hash))))\n (is (= \"John Boehner\" (first (all-matches nav-ns\n ", "end": 18445, "score": 0.9998307824134827, "start": 18433, "tag": "NAME", "value": "John Boehner" }, { "context": " ns-hash))))\n (is (= \"Lady Gaga\" (last (all-matches nav-ns\n ", "end": 18616, "score": 0.9995499849319458, "start": 18607, "tag": "NAME", "value": "Lady Gaga" }, { "context": "hes president \"ns2:Employee/Name\"))))\n (is (= \"Barack Obama\" (first (all-matches\n ", "end": 19141, "score": 0.9998896718025208, "start": 19129, "tag": "NAME", "value": "Barack Obama" }, { "context": "Employee[@role='President']/Name\"))))\n (is (= \"Lady Gaga\" (last (all-matches president \"ns2:Employee/Name\"", "end": 19305, "score": 0.9998860359191895, "start": 19296, "tag": "NAME", "value": "Lady Gaga" }, { "context": "2:Employee role=\\\"Elected Member\\\">\n <Name>John McCain</Name>\n </ns2:Employee>\"\n (first (ge", "end": 19714, "score": 0.9998608827590942, "start": 19703, "tag": "NAME", "value": "John McCain" }, { "context": " :attrs nil,\n :content [\"John McCain\"]}]}))\n (is (= 12 (count (get-hash nav-ns \"//ns2", "end": 20352, "score": 0.9997996091842651, "start": 20341, "tag": "NAME", "value": "John McCain" } ]
test/clj_vtd_xml/test/core.clj
diamondap/clj-vtd-xml
1
(ns clj-vtd-xml.test.core (:use [clj-vtd-xml.core]) (:use [clojure.test]) (:import [java.io.File]) (:require [clojure.pprint :as pp] [clojure.string :as string])) (defn dirname "Given a file path, returns the directory that contains the file." [path] (.getParent (java.io.File. path))) (defn expand-path "Given a relative path, returns an absolute path." [path] (.getCanonicalPath (java.io.File. path))) (defn file-path "Returns absolute path the specified file in the same directory as this source file" [file-name] (str (expand-path (dirname (str "test/" *file*))) "/" file-name)) ;; ---------------------------------------------------------------- ;; Read XML files into strings. One file with namespaces, one ;; without. ;; ---------------------------------------------------------------- (def xml (slurp (file-path "sample.xml"))) (def xml-ns (slurp (file-path "sample_ns.xml"))) ;; ---------------------------------------------------------------- ;; This are the VTDNav object, which contains XML in the form of ;; a raw byte stream, plus an index of Virtual Token Descriptors. ;; ---------------------------------------------------------------- (def nav (navigator xml true)) (def nav-ns (navigator xml-ns true)) ;; ---------------------------------------------------------------- ;; The XML doc sample_ns.xml uses these two namespaces. ;; When clj-vtd-xml does namespace-aware XPATH processing, it ;; needs a hash mapping namespace prefixes to namespace URLs. ;; ---------------------------------------------------------------- (def ns-hash {"ns1" "http://www.skeema.kom/ns1" "ns2" "http://www.skeema.kom/ns2"}) ;; ---------------------------------------------------------------- ;; find-indexes should return a seq of VTDNav objects. Each object ;; points to an element that matches the specified XPATH. ;; ---------------------------------------------------------------- (deftest find-indexes-test (is (= 4 (count (find-indexes nav "/Directory/Organizations/Organization")))) (is (= 4 (count (find-indexes nav (str "/Directory/Organizations" "/Organization" "/Employee[@role='Elected Member']"))))) (is (= 12 (count (find-indexes nav "//Name")))) ;; Get a VTDNav object pointing to the first organization element. ;; When we run relative XPATH queries on this, it should return only ;; the self or descendants of this element. (let [first-org (first (find-indexes nav "/Directory/Organizations/Organization"))] (is (= 3 (count (find-indexes first-org "Employee")))) (is (= 3 (count (find-indexes first-org "Employee/Name")))) (is (= 3 (count (find-indexes first-org "Employee//Name")))))) ;; ---------------------------------------------------------------- ;; all-matches returns the content of whatever we find at the ;; specified xpath. The xpath must point to an attribute or to ;; a node that contains only text. It may not point to a complex ;; element that contains other elements. ;; ;; all-matches returns a seq of strings, not VTDNav objects ;; ;; When nav points to an element within the main document, ;; all-matches returns matches within that element. ;; ---------------------------------------------------------------- (deftest all-matches-test (is (= 12 (count (all-matches nav "//Name")))) (is (= "John Boehner" (first (all-matches nav "//Name")))) (is (= "Lady Gaga" (last (all-matches nav "//Name")))) ;; Run all-matches on elements within a single element. ;; In this case, the last organization element. (let [president (last (find-indexes nav "/Directory/Organizations/Organization"))] (is (= 3 (count (all-matches president "Employee/Name")))) (is (= "Barack Obama" (first (all-matches president "Employee[@role='President']/Name")))) (is (= "Lady Gaga" (last (all-matches president "Employee/Name")))))) (def senate-xpath "/Directory/Organizations/Organization[@name='US Senate']/Employee") (def senate-xpath-ns (str "/Directory/ns1:Organizations" "/ns1:Organization[@name='US Senate']/ns2:Employee")) ;; ---------------------------------------------------------------- ;; get-xml returns a seq containing the literal XML of all matching ;; nodes ;; ---------------------------------------------------------------- (deftest get-xml-test (is (= "<Employee role=\"Elected Member\"> <Name>John McCain</Name> </Employee>" (first (get-xml nav senate-xpath)))) (is (= 12 (count (get-xml nav "//Employee"))))) ;; ---------------------------------------------------------------- ;; get-hash returns a seq of XML elements matching the specified ;; XPATH. Each element comes back in the form of a hash with the ;; structure shown below. The raw XML of this structure appears ;; in the get-xml-test above. ;; ---------------------------------------------------------------- (deftest get-hash-test (is (= (first (get-hash nav senate-xpath)) {:tag :Employee, :attrs {:role "Elected Member"}, :content [{:tag :Name, :attrs nil, :content ["John McCain"]}]})) (is (= 12 (count (get-hash nav "//Employee"))))) ;; ---------------------------------------------------------------- ;; normalize-text should remove all extraneous spaces from text. ;; ---------------------------------------------------------------- (deftest normalize-text-test (is (= "this is a string" (normalize-text " this is a string ")))) ;; ---------------------------------------------------------------- ;; is-within? should return true if the second element is a ;; descendant of the first, or if an element's start position is ;; between start and end ;; ---------------------------------------------------------------- (deftest is-within-test (let [first-organization (first (find-indexes nav "/Directory/Organizations/Organization")) names (find-indexes nav "//Name") position (position first-organization) start (:offset position) end (+ start (:length position))] (is (is-within? first-organization (- start 1) (+ end 1))) (is (not (is-within? first-organization (+ start 1) (+ end 1)))) (is (not (is-within? first-organization (- start 1) start))) (is (is-within? first-organization (first names))) (is (not (is-within? first-organization (last names)))))) ;; ---------------------------------------------------------------- ;; first-match should return the content of first node matching ;; the specified XPATH expression that is either 1) the node nav is ;; pointing to or 2) descendants of the node nav points to. ;; ;; Note that XPATH is relative to whatever node the nav is currently ;; pointing to. ;; ---------------------------------------------------------------- (deftest first-match-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org1 (first organizations) org2 (nth organizations 1)] (is (= "John Boehner" (first-match org1 "Employee/Name"))) (is (= "Willie Williams" (first-match org1 "Employee[@role='Staff']/Name"))) (is (= "John McCain" (first-match org2 "Employee/Name"))) (is (= "Cassandra Hadoop" (first-match org2 "Employee[@role='Staff']/Name"))))) ;; ---------------------------------------------------------------- ;; first-match should return nil, not throw exceptions, when given ;; an XPATH it can't find. ;; ---------------------------------------------------------------- (deftest first-match-no-match-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org1 (first organizations)] (is (nil? (first-match org1 "dybbx/FAKE_ELEMENT"))) (is (nil? (first-match org1 "wtwtwetsdgsh/@iioookkjj"))))) ;; ---------------------------------------------------------------- ;; all-matches should return an empty seq, not throw exceptions, ;; when given an XPATH it can't find. ;; ---------------------------------------------------------------- (deftest all-matches-no-match-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org1 (first organizations)] (is (= () (all-matches org1 "dybbx/FAKE_ELEMENT"))) (is (= () (all-matches org1 "wtwtwetsdgsh/@iioookkjj"))))) ;; ---------------------------------------------------------------- ;; node-name returns the name of the element or attribute that the ;; navigator currently points to ;; ---------------------------------------------------------------- (deftest node-name-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org1 (first organizations) attr (first (find-indexes org1 "@name"))] (is (= "Organization" (node-name org1))) (is (= "name" (node-name attr))))) ;; ---------------------------------------------------------------- ;; attribute? returns true when the VTD nav is pointing to ;; an attribute. ;; ---------------------------------------------------------------- (deftest attribute-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org1 (first organizations) attr (first (find-indexes org1 "@name"))] (is (not (attribute? org1)) (is (attribute? attr))))) ;; ---------------------------------------------------------------- ;; element? correctly indictes when nav object is pointing to ;; an element. ;; ---------------------------------------------------------------- (deftest element-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org1 (first organizations) attr (first (find-indexes org1 "@name"))] (is (element? org1)) (is (not (element? attr))))) ;; ---------------------------------------------------------------- ;; to-parent! moves the nav pointer to the parent of the current ;; element. It returns true on success, false on failure. ;; Note that all of these to-xxx functions alter the state of ;; VTDNav pointer! ;; ---------------------------------------------------------------- (deftest to-parent-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org1 (first organizations)] ;; Make sure we're on Organization before moving up (is (= "Organization" (node-name org1))) (is (to-parent! org1)) ;; returns true on success (is (= "Organizations" (node-name org1))) (is (to-parent! org1)) (is (= "Directory" (node-name org1))))) ;; ---------------------------------------------------------------- ;; to-first-child! with name param goes to the first child having ;; the specified name ;; ---------------------------------------------------------------- (deftest to-first-child-with-name-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org1 (first organizations)] (is (to-first-child! org1 "Employee")) ;; returns true on success (is (= "John Boehner" (first-match org1 "Name"))))) ;; ---------------------------------------------------------------- ;; to-first-child! with no name goes to the first child ;; ---------------------------------------------------------------- (deftest to-first-child-without-name-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org1 (first organizations)] (is (to-first-child! org1)) ;; returns true on success (is (= "Location" (node-name org1))))) ;; ---------------------------------------------------------------- ;; to-first-child! returns false if the requested node does ;; not exist ;; ---------------------------------------------------------------- (deftest to-first-child-return-test (let [org (first(find-indexes nav "/Directory/Organizations/Organization"))] (is (not (to-first-child! org "NonExistantNode"))) (is (not (to-first-child! org "@NonExistantAttr"))))) ;; ---------------------------------------------------------------- ;; to-last-child! with name param goes to the last child with the ;; specified name ;; ---------------------------------------------------------------- (deftest to-last-child-name-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org1 (first organizations) org2 (nth organizations 1)] (is (to-last-child! org1 "Employee")) ;; move to last Employee (is (= "Willie Williams" (first-match org1 "Name"))) (is (to-last-child! org2 "Location")) (is (= "US Capitol" (first-match org2 "."))))) ;; ---------------------------------------------------------------- ;; to-next-sibling! goes to the correct sibling (if no name param, ;; should go to next sibling; if name param exists, should go to ;; next element with that name). ;; ---------------------------------------------------------------- (deftest to-next-sibling-test (let [nav-obj (first (find-indexes nav "/Directory/Organizations/Organization/Location"))] (is (to-next-sibling! nav-obj)) (is (= "Employee" (node-name nav-obj))) (is (to-next-sibling! nav-obj "ApprovalRating")) (is (= "ApprovalRating" (node-name nav-obj))))) ;; ---------------------------------------------------------------- ;; to-next-sibling! returns false if there is no next sibling ;; or if there is no next sibling with the specified name ;; ---------------------------------------------------------------- (deftest to-next-sibling-not-found-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org-first (first organizations) org-last (last organizations)] (is (not (to-next-sibling! org-last))) (is (not (to-next-sibling! org-first "IDontExist"))))) ;; ---------------------------------------------------------------- ;; to-prev-sibling! goes to the correct sibling (if no name param, ;; should go to next sibling; if name param exists, should go to ;; next element with that name). ;; ---------------------------------------------------------------- (deftest to-prev-sibling-test (let [employee (first (find-indexes nav "/Directory/Organizations/Organization/Employee")) approval (first (find-indexes nav "/Directory/Organizations/Organization/ApprovalRating"))] (is (to-prev-sibling! employee)) (is (= "Location" (node-name employee))) (is (to-prev-sibling! approval "Location")) (is (= "Location" (node-name approval))))) ;; ---------------------------------------------------------------- ;; to-prev-sibling! returns false if there is no previous sibling ;; or if there is no previous sibling with the specified name ;; ---------------------------------------------------------------- (deftest to-prev-sibling-no-match-test (let [org1 (first (find-indexes nav "//Directory/Organizations/Organization"))] (is (not (to-prev-sibling! org1))) (is (not (to-prev-sibling! org1 "IDontExist"))))) ;; ---------------------------------------------------------------- ;; --------------- NAMESPACE TESTS FROM HERE DOWN ----------------- ;; ---------------------------------------------------------------- ;; ---------------------------------------------------------------- ;; Make sure that find-indexes works with XPATH namespaces. ;; Pass in an optional namespace hash. ;; ---------------------------------------------------------------- (deftest find-indexes-ns-test (is (= 4 (count (find-indexes nav-ns "/Directory/ns1:Organizations/ns1:Organization" ns-hash)))) (is (= 5 (count (find-indexes nav-ns (str "/Directory/ns1:Organizations" "/ns1:Organization" "/ns2:Employee[@role='Elected Member']") ns-hash)))) (is (= 12 (count (find-indexes nav-ns "//Name" ns-hash)))) ;; Get a VTDNav object pointing to the first organization element. ;; When we run relative XPATH queries on this, it should return only ;; the self or descendants of this element. (let [first-org (first (find-indexes nav-ns "/Directory/ns1:Organizations/ns1:Organization" ns-hash))] (is (= 3 (count (find-indexes first-org "ns2:Employee" ns-hash)))) (is (= 3 (count (find-indexes first-org "ns2:Employee/Name" ns-hash)))) (is (= 3 (count (find-indexes first-org "ns2:Employee//Name" ns-hash)))))) ;; ---------------------------------------------------------------- ;; List first-match-test above, but with namespaces ;; ---------------------------------------------------------------- (deftest first-match-ns-test (let [organizations (find-indexes nav-ns "/Directory/ns1:Organizations/ns1:Organization" ns-hash) org1 (first organizations) org2 (nth organizations 1)] (is (= "John Boehner" (first-match org1 "ns2:Employee/Name" ns-hash))) (is (= "Willie Williams" (first-match org1 "ns2:Employee[@role='Staff']/Name" ns-hash))) (is (= "John McCain" (first-match org2 "ns2:Employee/Name" ns-hash))) (is (= "Cassandra Hadoop" (first-match org2 "ns2:Employee[@role='Staff']/Name" ns-hash))))) ;; ---------------------------------------------------------------- ;; The all-matches test is described above. This is the same test ;; with namespaces. ;; ---------------------------------------------------------------- (deftest all-matches-ns-test (is (= 12 (count (all-matches nav-ns "//Name" ns-hash)))) (is (= "John Boehner" (first (all-matches nav-ns "//ns2:Employee//Name" ns-hash)))) (is (= "Lady Gaga" (last (all-matches nav-ns "//ns2:Employee//Name" ns-hash)))) ;; Run all-matches on elements within a single element. ;; In this case, the last organization element. (let [president (last (find-indexes nav-ns "/Directory/ns1:Organizations/ns1:Organization" ns-hash))] (is (= 3 (count (all-matches president "ns2:Employee/Name")))) (is (= "Barack Obama" (first (all-matches president "ns2:Employee[@role='President']/Name")))) (is (= "Lady Gaga" (last (all-matches president "ns2:Employee/Name")))))) ;; ---------------------------------------------------------------- ;; get-xml returns a seq containing the literal XML of all matching ;; nodes. Make sure this works with namespaces ;; ---------------------------------------------------------------- (deftest get-xml-ns-test (is (= "<ns2:Employee role=\"Elected Member\"> <Name>John McCain</Name> </ns2:Employee>" (first (get-xml nav-ns senate-xpath-ns ns-hash)))) (is (= 12 (count (get-xml nav-ns "//ns2:Employee" ns-hash))))) ;; ---------------------------------------------------------------- ;; get-hash is described above. This tests to ensure it works with ;; namespaces ;; ---------------------------------------------------------------- (deftest get-hash-ns-test (is (= (first (get-hash nav-ns senate-xpath-ns ns-hash)) {:tag :ns2:Employee, :attrs {:role "Elected Member"}, :content [{:tag :Name, :attrs nil, :content ["John McCain"]}]})) (is (= 12 (count (get-hash nav-ns "//ns2:Employee" ns-hash)))))
75613
(ns clj-vtd-xml.test.core (:use [clj-vtd-xml.core]) (:use [clojure.test]) (:import [java.io.File]) (:require [clojure.pprint :as pp] [clojure.string :as string])) (defn dirname "Given a file path, returns the directory that contains the file." [path] (.getParent (java.io.File. path))) (defn expand-path "Given a relative path, returns an absolute path." [path] (.getCanonicalPath (java.io.File. path))) (defn file-path "Returns absolute path the specified file in the same directory as this source file" [file-name] (str (expand-path (dirname (str "test/" *file*))) "/" file-name)) ;; ---------------------------------------------------------------- ;; Read XML files into strings. One file with namespaces, one ;; without. ;; ---------------------------------------------------------------- (def xml (slurp (file-path "sample.xml"))) (def xml-ns (slurp (file-path "sample_ns.xml"))) ;; ---------------------------------------------------------------- ;; This are the VTDNav object, which contains XML in the form of ;; a raw byte stream, plus an index of Virtual Token Descriptors. ;; ---------------------------------------------------------------- (def nav (navigator xml true)) (def nav-ns (navigator xml-ns true)) ;; ---------------------------------------------------------------- ;; The XML doc sample_ns.xml uses these two namespaces. ;; When clj-vtd-xml does namespace-aware XPATH processing, it ;; needs a hash mapping namespace prefixes to namespace URLs. ;; ---------------------------------------------------------------- (def ns-hash {"ns1" "http://www.skeema.kom/ns1" "ns2" "http://www.skeema.kom/ns2"}) ;; ---------------------------------------------------------------- ;; find-indexes should return a seq of VTDNav objects. Each object ;; points to an element that matches the specified XPATH. ;; ---------------------------------------------------------------- (deftest find-indexes-test (is (= 4 (count (find-indexes nav "/Directory/Organizations/Organization")))) (is (= 4 (count (find-indexes nav (str "/Directory/Organizations" "/Organization" "/Employee[@role='Elected Member']"))))) (is (= 12 (count (find-indexes nav "//Name")))) ;; Get a VTDNav object pointing to the first organization element. ;; When we run relative XPATH queries on this, it should return only ;; the self or descendants of this element. (let [first-org (first (find-indexes nav "/Directory/Organizations/Organization"))] (is (= 3 (count (find-indexes first-org "Employee")))) (is (= 3 (count (find-indexes first-org "Employee/Name")))) (is (= 3 (count (find-indexes first-org "Employee//Name")))))) ;; ---------------------------------------------------------------- ;; all-matches returns the content of whatever we find at the ;; specified xpath. The xpath must point to an attribute or to ;; a node that contains only text. It may not point to a complex ;; element that contains other elements. ;; ;; all-matches returns a seq of strings, not VTDNav objects ;; ;; When nav points to an element within the main document, ;; all-matches returns matches within that element. ;; ---------------------------------------------------------------- (deftest all-matches-test (is (= 12 (count (all-matches nav "//Name")))) (is (= "<NAME>" (first (all-matches nav "//Name")))) (is (= "<NAME>" (last (all-matches nav "//Name")))) ;; Run all-matches on elements within a single element. ;; In this case, the last organization element. (let [president (last (find-indexes nav "/Directory/Organizations/Organization"))] (is (= 3 (count (all-matches president "Employee/Name")))) (is (= "<NAME>" (first (all-matches president "Employee[@role='President']/Name")))) (is (= "<NAME>" (last (all-matches president "Employee/Name")))))) (def senate-xpath "/Directory/Organizations/Organization[@name='US Senate']/Employee") (def senate-xpath-ns (str "/Directory/ns1:Organizations" "/ns1:Organization[@name='US Senate']/ns2:Employee")) ;; ---------------------------------------------------------------- ;; get-xml returns a seq containing the literal XML of all matching ;; nodes ;; ---------------------------------------------------------------- (deftest get-xml-test (is (= "<Employee role=\"Elected Member\"> <Name><NAME></Name> </Employee>" (first (get-xml nav senate-xpath)))) (is (= 12 (count (get-xml nav "//Employee"))))) ;; ---------------------------------------------------------------- ;; get-hash returns a seq of XML elements matching the specified ;; XPATH. Each element comes back in the form of a hash with the ;; structure shown below. The raw XML of this structure appears ;; in the get-xml-test above. ;; ---------------------------------------------------------------- (deftest get-hash-test (is (= (first (get-hash nav senate-xpath)) {:tag :Employee, :attrs {:role "Elected Member"}, :content [{:tag :Name, :attrs nil, :content ["<NAME>"]}]})) (is (= 12 (count (get-hash nav "//Employee"))))) ;; ---------------------------------------------------------------- ;; normalize-text should remove all extraneous spaces from text. ;; ---------------------------------------------------------------- (deftest normalize-text-test (is (= "this is a string" (normalize-text " this is a string ")))) ;; ---------------------------------------------------------------- ;; is-within? should return true if the second element is a ;; descendant of the first, or if an element's start position is ;; between start and end ;; ---------------------------------------------------------------- (deftest is-within-test (let [first-organization (first (find-indexes nav "/Directory/Organizations/Organization")) names (find-indexes nav "//Name") position (position first-organization) start (:offset position) end (+ start (:length position))] (is (is-within? first-organization (- start 1) (+ end 1))) (is (not (is-within? first-organization (+ start 1) (+ end 1)))) (is (not (is-within? first-organization (- start 1) start))) (is (is-within? first-organization (first names))) (is (not (is-within? first-organization (last names)))))) ;; ---------------------------------------------------------------- ;; first-match should return the content of first node matching ;; the specified XPATH expression that is either 1) the node nav is ;; pointing to or 2) descendants of the node nav points to. ;; ;; Note that XPATH is relative to whatever node the nav is currently ;; pointing to. ;; ---------------------------------------------------------------- (deftest first-match-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org1 (first organizations) org2 (nth organizations 1)] (is (= "<NAME>" (first-match org1 "Employee/Name"))) (is (= "<NAME>" (first-match org1 "Employee[@role='Staff']/Name"))) (is (= "<NAME>" (first-match org2 "Employee/Name"))) (is (= "<NAME>" (first-match org2 "Employee[@role='Staff']/Name"))))) ;; ---------------------------------------------------------------- ;; first-match should return nil, not throw exceptions, when given ;; an XPATH it can't find. ;; ---------------------------------------------------------------- (deftest first-match-no-match-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org1 (first organizations)] (is (nil? (first-match org1 "dybbx/FAKE_ELEMENT"))) (is (nil? (first-match org1 "wtwtwetsdgsh/@iioookkjj"))))) ;; ---------------------------------------------------------------- ;; all-matches should return an empty seq, not throw exceptions, ;; when given an XPATH it can't find. ;; ---------------------------------------------------------------- (deftest all-matches-no-match-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org1 (first organizations)] (is (= () (all-matches org1 "dybbx/FAKE_ELEMENT"))) (is (= () (all-matches org1 "wtwtwetsdgsh/@iioookkjj"))))) ;; ---------------------------------------------------------------- ;; node-name returns the name of the element or attribute that the ;; navigator currently points to ;; ---------------------------------------------------------------- (deftest node-name-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org1 (first organizations) attr (first (find-indexes org1 "@name"))] (is (= "Organization" (node-name org1))) (is (= "name" (node-name attr))))) ;; ---------------------------------------------------------------- ;; attribute? returns true when the VTD nav is pointing to ;; an attribute. ;; ---------------------------------------------------------------- (deftest attribute-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org1 (first organizations) attr (first (find-indexes org1 "@name"))] (is (not (attribute? org1)) (is (attribute? attr))))) ;; ---------------------------------------------------------------- ;; element? correctly indictes when nav object is pointing to ;; an element. ;; ---------------------------------------------------------------- (deftest element-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org1 (first organizations) attr (first (find-indexes org1 "@name"))] (is (element? org1)) (is (not (element? attr))))) ;; ---------------------------------------------------------------- ;; to-parent! moves the nav pointer to the parent of the current ;; element. It returns true on success, false on failure. ;; Note that all of these to-xxx functions alter the state of ;; VTDNav pointer! ;; ---------------------------------------------------------------- (deftest to-parent-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org1 (first organizations)] ;; Make sure we're on Organization before moving up (is (= "Organization" (node-name org1))) (is (to-parent! org1)) ;; returns true on success (is (= "Organizations" (node-name org1))) (is (to-parent! org1)) (is (= "Directory" (node-name org1))))) ;; ---------------------------------------------------------------- ;; to-first-child! with name param goes to the first child having ;; the specified name ;; ---------------------------------------------------------------- (deftest to-first-child-with-name-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org1 (first organizations)] (is (to-first-child! org1 "Employee")) ;; returns true on success (is (= "<NAME>" (first-match org1 "Name"))))) ;; ---------------------------------------------------------------- ;; to-first-child! with no name goes to the first child ;; ---------------------------------------------------------------- (deftest to-first-child-without-name-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org1 (first organizations)] (is (to-first-child! org1)) ;; returns true on success (is (= "Location" (node-name org1))))) ;; ---------------------------------------------------------------- ;; to-first-child! returns false if the requested node does ;; not exist ;; ---------------------------------------------------------------- (deftest to-first-child-return-test (let [org (first(find-indexes nav "/Directory/Organizations/Organization"))] (is (not (to-first-child! org "NonExistantNode"))) (is (not (to-first-child! org "@NonExistantAttr"))))) ;; ---------------------------------------------------------------- ;; to-last-child! with name param goes to the last child with the ;; specified name ;; ---------------------------------------------------------------- (deftest to-last-child-name-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org1 (first organizations) org2 (nth organizations 1)] (is (to-last-child! org1 "Employee")) ;; move to last Employee (is (= "<NAME>" (first-match org1 "Name"))) (is (to-last-child! org2 "Location")) (is (= "US Capitol" (first-match org2 "."))))) ;; ---------------------------------------------------------------- ;; to-next-sibling! goes to the correct sibling (if no name param, ;; should go to next sibling; if name param exists, should go to ;; next element with that name). ;; ---------------------------------------------------------------- (deftest to-next-sibling-test (let [nav-obj (first (find-indexes nav "/Directory/Organizations/Organization/Location"))] (is (to-next-sibling! nav-obj)) (is (= "Employee" (node-name nav-obj))) (is (to-next-sibling! nav-obj "ApprovalRating")) (is (= "ApprovalRating" (node-name nav-obj))))) ;; ---------------------------------------------------------------- ;; to-next-sibling! returns false if there is no next sibling ;; or if there is no next sibling with the specified name ;; ---------------------------------------------------------------- (deftest to-next-sibling-not-found-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org-first (first organizations) org-last (last organizations)] (is (not (to-next-sibling! org-last))) (is (not (to-next-sibling! org-first "IDontExist"))))) ;; ---------------------------------------------------------------- ;; to-prev-sibling! goes to the correct sibling (if no name param, ;; should go to next sibling; if name param exists, should go to ;; next element with that name). ;; ---------------------------------------------------------------- (deftest to-prev-sibling-test (let [employee (first (find-indexes nav "/Directory/Organizations/Organization/Employee")) approval (first (find-indexes nav "/Directory/Organizations/Organization/ApprovalRating"))] (is (to-prev-sibling! employee)) (is (= "Location" (node-name employee))) (is (to-prev-sibling! approval "Location")) (is (= "Location" (node-name approval))))) ;; ---------------------------------------------------------------- ;; to-prev-sibling! returns false if there is no previous sibling ;; or if there is no previous sibling with the specified name ;; ---------------------------------------------------------------- (deftest to-prev-sibling-no-match-test (let [org1 (first (find-indexes nav "//Directory/Organizations/Organization"))] (is (not (to-prev-sibling! org1))) (is (not (to-prev-sibling! org1 "IDontExist"))))) ;; ---------------------------------------------------------------- ;; --------------- NAMESPACE TESTS FROM HERE DOWN ----------------- ;; ---------------------------------------------------------------- ;; ---------------------------------------------------------------- ;; Make sure that find-indexes works with XPATH namespaces. ;; Pass in an optional namespace hash. ;; ---------------------------------------------------------------- (deftest find-indexes-ns-test (is (= 4 (count (find-indexes nav-ns "/Directory/ns1:Organizations/ns1:Organization" ns-hash)))) (is (= 5 (count (find-indexes nav-ns (str "/Directory/ns1:Organizations" "/ns1:Organization" "/ns2:Employee[@role='Elected Member']") ns-hash)))) (is (= 12 (count (find-indexes nav-ns "//Name" ns-hash)))) ;; Get a VTDNav object pointing to the first organization element. ;; When we run relative XPATH queries on this, it should return only ;; the self or descendants of this element. (let [first-org (first (find-indexes nav-ns "/Directory/ns1:Organizations/ns1:Organization" ns-hash))] (is (= 3 (count (find-indexes first-org "ns2:Employee" ns-hash)))) (is (= 3 (count (find-indexes first-org "ns2:Employee/Name" ns-hash)))) (is (= 3 (count (find-indexes first-org "ns2:Employee//Name" ns-hash)))))) ;; ---------------------------------------------------------------- ;; List first-match-test above, but with namespaces ;; ---------------------------------------------------------------- (deftest first-match-ns-test (let [organizations (find-indexes nav-ns "/Directory/ns1:Organizations/ns1:Organization" ns-hash) org1 (first organizations) org2 (nth organizations 1)] (is (= "<NAME>" (first-match org1 "ns2:Employee/Name" ns-hash))) (is (= "<NAME>" (first-match org1 "ns2:Employee[@role='Staff']/Name" ns-hash))) (is (= "<NAME>" (first-match org2 "ns2:Employee/Name" ns-hash))) (is (= "C<NAME>" (first-match org2 "ns2:Employee[@role='Staff']/Name" ns-hash))))) ;; ---------------------------------------------------------------- ;; The all-matches test is described above. This is the same test ;; with namespaces. ;; ---------------------------------------------------------------- (deftest all-matches-ns-test (is (= 12 (count (all-matches nav-ns "//Name" ns-hash)))) (is (= "<NAME>" (first (all-matches nav-ns "//ns2:Employee//Name" ns-hash)))) (is (= "<NAME>" (last (all-matches nav-ns "//ns2:Employee//Name" ns-hash)))) ;; Run all-matches on elements within a single element. ;; In this case, the last organization element. (let [president (last (find-indexes nav-ns "/Directory/ns1:Organizations/ns1:Organization" ns-hash))] (is (= 3 (count (all-matches president "ns2:Employee/Name")))) (is (= "<NAME>" (first (all-matches president "ns2:Employee[@role='President']/Name")))) (is (= "<NAME>" (last (all-matches president "ns2:Employee/Name")))))) ;; ---------------------------------------------------------------- ;; get-xml returns a seq containing the literal XML of all matching ;; nodes. Make sure this works with namespaces ;; ---------------------------------------------------------------- (deftest get-xml-ns-test (is (= "<ns2:Employee role=\"Elected Member\"> <Name><NAME></Name> </ns2:Employee>" (first (get-xml nav-ns senate-xpath-ns ns-hash)))) (is (= 12 (count (get-xml nav-ns "//ns2:Employee" ns-hash))))) ;; ---------------------------------------------------------------- ;; get-hash is described above. This tests to ensure it works with ;; namespaces ;; ---------------------------------------------------------------- (deftest get-hash-ns-test (is (= (first (get-hash nav-ns senate-xpath-ns ns-hash)) {:tag :ns2:Employee, :attrs {:role "Elected Member"}, :content [{:tag :Name, :attrs nil, :content ["<NAME>"]}]})) (is (= 12 (count (get-hash nav-ns "//ns2:Employee" ns-hash)))))
true
(ns clj-vtd-xml.test.core (:use [clj-vtd-xml.core]) (:use [clojure.test]) (:import [java.io.File]) (:require [clojure.pprint :as pp] [clojure.string :as string])) (defn dirname "Given a file path, returns the directory that contains the file." [path] (.getParent (java.io.File. path))) (defn expand-path "Given a relative path, returns an absolute path." [path] (.getCanonicalPath (java.io.File. path))) (defn file-path "Returns absolute path the specified file in the same directory as this source file" [file-name] (str (expand-path (dirname (str "test/" *file*))) "/" file-name)) ;; ---------------------------------------------------------------- ;; Read XML files into strings. One file with namespaces, one ;; without. ;; ---------------------------------------------------------------- (def xml (slurp (file-path "sample.xml"))) (def xml-ns (slurp (file-path "sample_ns.xml"))) ;; ---------------------------------------------------------------- ;; This are the VTDNav object, which contains XML in the form of ;; a raw byte stream, plus an index of Virtual Token Descriptors. ;; ---------------------------------------------------------------- (def nav (navigator xml true)) (def nav-ns (navigator xml-ns true)) ;; ---------------------------------------------------------------- ;; The XML doc sample_ns.xml uses these two namespaces. ;; When clj-vtd-xml does namespace-aware XPATH processing, it ;; needs a hash mapping namespace prefixes to namespace URLs. ;; ---------------------------------------------------------------- (def ns-hash {"ns1" "http://www.skeema.kom/ns1" "ns2" "http://www.skeema.kom/ns2"}) ;; ---------------------------------------------------------------- ;; find-indexes should return a seq of VTDNav objects. Each object ;; points to an element that matches the specified XPATH. ;; ---------------------------------------------------------------- (deftest find-indexes-test (is (= 4 (count (find-indexes nav "/Directory/Organizations/Organization")))) (is (= 4 (count (find-indexes nav (str "/Directory/Organizations" "/Organization" "/Employee[@role='Elected Member']"))))) (is (= 12 (count (find-indexes nav "//Name")))) ;; Get a VTDNav object pointing to the first organization element. ;; When we run relative XPATH queries on this, it should return only ;; the self or descendants of this element. (let [first-org (first (find-indexes nav "/Directory/Organizations/Organization"))] (is (= 3 (count (find-indexes first-org "Employee")))) (is (= 3 (count (find-indexes first-org "Employee/Name")))) (is (= 3 (count (find-indexes first-org "Employee//Name")))))) ;; ---------------------------------------------------------------- ;; all-matches returns the content of whatever we find at the ;; specified xpath. The xpath must point to an attribute or to ;; a node that contains only text. It may not point to a complex ;; element that contains other elements. ;; ;; all-matches returns a seq of strings, not VTDNav objects ;; ;; When nav points to an element within the main document, ;; all-matches returns matches within that element. ;; ---------------------------------------------------------------- (deftest all-matches-test (is (= 12 (count (all-matches nav "//Name")))) (is (= "PI:NAME:<NAME>END_PI" (first (all-matches nav "//Name")))) (is (= "PI:NAME:<NAME>END_PI" (last (all-matches nav "//Name")))) ;; Run all-matches on elements within a single element. ;; In this case, the last organization element. (let [president (last (find-indexes nav "/Directory/Organizations/Organization"))] (is (= 3 (count (all-matches president "Employee/Name")))) (is (= "PI:NAME:<NAME>END_PI" (first (all-matches president "Employee[@role='President']/Name")))) (is (= "PI:NAME:<NAME>END_PI" (last (all-matches president "Employee/Name")))))) (def senate-xpath "/Directory/Organizations/Organization[@name='US Senate']/Employee") (def senate-xpath-ns (str "/Directory/ns1:Organizations" "/ns1:Organization[@name='US Senate']/ns2:Employee")) ;; ---------------------------------------------------------------- ;; get-xml returns a seq containing the literal XML of all matching ;; nodes ;; ---------------------------------------------------------------- (deftest get-xml-test (is (= "<Employee role=\"Elected Member\"> <Name>PI:NAME:<NAME>END_PI</Name> </Employee>" (first (get-xml nav senate-xpath)))) (is (= 12 (count (get-xml nav "//Employee"))))) ;; ---------------------------------------------------------------- ;; get-hash returns a seq of XML elements matching the specified ;; XPATH. Each element comes back in the form of a hash with the ;; structure shown below. The raw XML of this structure appears ;; in the get-xml-test above. ;; ---------------------------------------------------------------- (deftest get-hash-test (is (= (first (get-hash nav senate-xpath)) {:tag :Employee, :attrs {:role "Elected Member"}, :content [{:tag :Name, :attrs nil, :content ["PI:NAME:<NAME>END_PI"]}]})) (is (= 12 (count (get-hash nav "//Employee"))))) ;; ---------------------------------------------------------------- ;; normalize-text should remove all extraneous spaces from text. ;; ---------------------------------------------------------------- (deftest normalize-text-test (is (= "this is a string" (normalize-text " this is a string ")))) ;; ---------------------------------------------------------------- ;; is-within? should return true if the second element is a ;; descendant of the first, or if an element's start position is ;; between start and end ;; ---------------------------------------------------------------- (deftest is-within-test (let [first-organization (first (find-indexes nav "/Directory/Organizations/Organization")) names (find-indexes nav "//Name") position (position first-organization) start (:offset position) end (+ start (:length position))] (is (is-within? first-organization (- start 1) (+ end 1))) (is (not (is-within? first-organization (+ start 1) (+ end 1)))) (is (not (is-within? first-organization (- start 1) start))) (is (is-within? first-organization (first names))) (is (not (is-within? first-organization (last names)))))) ;; ---------------------------------------------------------------- ;; first-match should return the content of first node matching ;; the specified XPATH expression that is either 1) the node nav is ;; pointing to or 2) descendants of the node nav points to. ;; ;; Note that XPATH is relative to whatever node the nav is currently ;; pointing to. ;; ---------------------------------------------------------------- (deftest first-match-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org1 (first organizations) org2 (nth organizations 1)] (is (= "PI:NAME:<NAME>END_PI" (first-match org1 "Employee/Name"))) (is (= "PI:NAME:<NAME>END_PI" (first-match org1 "Employee[@role='Staff']/Name"))) (is (= "PI:NAME:<NAME>END_PI" (first-match org2 "Employee/Name"))) (is (= "PI:NAME:<NAME>END_PI" (first-match org2 "Employee[@role='Staff']/Name"))))) ;; ---------------------------------------------------------------- ;; first-match should return nil, not throw exceptions, when given ;; an XPATH it can't find. ;; ---------------------------------------------------------------- (deftest first-match-no-match-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org1 (first organizations)] (is (nil? (first-match org1 "dybbx/FAKE_ELEMENT"))) (is (nil? (first-match org1 "wtwtwetsdgsh/@iioookkjj"))))) ;; ---------------------------------------------------------------- ;; all-matches should return an empty seq, not throw exceptions, ;; when given an XPATH it can't find. ;; ---------------------------------------------------------------- (deftest all-matches-no-match-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org1 (first organizations)] (is (= () (all-matches org1 "dybbx/FAKE_ELEMENT"))) (is (= () (all-matches org1 "wtwtwetsdgsh/@iioookkjj"))))) ;; ---------------------------------------------------------------- ;; node-name returns the name of the element or attribute that the ;; navigator currently points to ;; ---------------------------------------------------------------- (deftest node-name-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org1 (first organizations) attr (first (find-indexes org1 "@name"))] (is (= "Organization" (node-name org1))) (is (= "name" (node-name attr))))) ;; ---------------------------------------------------------------- ;; attribute? returns true when the VTD nav is pointing to ;; an attribute. ;; ---------------------------------------------------------------- (deftest attribute-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org1 (first organizations) attr (first (find-indexes org1 "@name"))] (is (not (attribute? org1)) (is (attribute? attr))))) ;; ---------------------------------------------------------------- ;; element? correctly indictes when nav object is pointing to ;; an element. ;; ---------------------------------------------------------------- (deftest element-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org1 (first organizations) attr (first (find-indexes org1 "@name"))] (is (element? org1)) (is (not (element? attr))))) ;; ---------------------------------------------------------------- ;; to-parent! moves the nav pointer to the parent of the current ;; element. It returns true on success, false on failure. ;; Note that all of these to-xxx functions alter the state of ;; VTDNav pointer! ;; ---------------------------------------------------------------- (deftest to-parent-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org1 (first organizations)] ;; Make sure we're on Organization before moving up (is (= "Organization" (node-name org1))) (is (to-parent! org1)) ;; returns true on success (is (= "Organizations" (node-name org1))) (is (to-parent! org1)) (is (= "Directory" (node-name org1))))) ;; ---------------------------------------------------------------- ;; to-first-child! with name param goes to the first child having ;; the specified name ;; ---------------------------------------------------------------- (deftest to-first-child-with-name-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org1 (first organizations)] (is (to-first-child! org1 "Employee")) ;; returns true on success (is (= "PI:NAME:<NAME>END_PI" (first-match org1 "Name"))))) ;; ---------------------------------------------------------------- ;; to-first-child! with no name goes to the first child ;; ---------------------------------------------------------------- (deftest to-first-child-without-name-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org1 (first organizations)] (is (to-first-child! org1)) ;; returns true on success (is (= "Location" (node-name org1))))) ;; ---------------------------------------------------------------- ;; to-first-child! returns false if the requested node does ;; not exist ;; ---------------------------------------------------------------- (deftest to-first-child-return-test (let [org (first(find-indexes nav "/Directory/Organizations/Organization"))] (is (not (to-first-child! org "NonExistantNode"))) (is (not (to-first-child! org "@NonExistantAttr"))))) ;; ---------------------------------------------------------------- ;; to-last-child! with name param goes to the last child with the ;; specified name ;; ---------------------------------------------------------------- (deftest to-last-child-name-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org1 (first organizations) org2 (nth organizations 1)] (is (to-last-child! org1 "Employee")) ;; move to last Employee (is (= "PI:NAME:<NAME>END_PI" (first-match org1 "Name"))) (is (to-last-child! org2 "Location")) (is (= "US Capitol" (first-match org2 "."))))) ;; ---------------------------------------------------------------- ;; to-next-sibling! goes to the correct sibling (if no name param, ;; should go to next sibling; if name param exists, should go to ;; next element with that name). ;; ---------------------------------------------------------------- (deftest to-next-sibling-test (let [nav-obj (first (find-indexes nav "/Directory/Organizations/Organization/Location"))] (is (to-next-sibling! nav-obj)) (is (= "Employee" (node-name nav-obj))) (is (to-next-sibling! nav-obj "ApprovalRating")) (is (= "ApprovalRating" (node-name nav-obj))))) ;; ---------------------------------------------------------------- ;; to-next-sibling! returns false if there is no next sibling ;; or if there is no next sibling with the specified name ;; ---------------------------------------------------------------- (deftest to-next-sibling-not-found-test (let [organizations (find-indexes nav "/Directory/Organizations/Organization") org-first (first organizations) org-last (last organizations)] (is (not (to-next-sibling! org-last))) (is (not (to-next-sibling! org-first "IDontExist"))))) ;; ---------------------------------------------------------------- ;; to-prev-sibling! goes to the correct sibling (if no name param, ;; should go to next sibling; if name param exists, should go to ;; next element with that name). ;; ---------------------------------------------------------------- (deftest to-prev-sibling-test (let [employee (first (find-indexes nav "/Directory/Organizations/Organization/Employee")) approval (first (find-indexes nav "/Directory/Organizations/Organization/ApprovalRating"))] (is (to-prev-sibling! employee)) (is (= "Location" (node-name employee))) (is (to-prev-sibling! approval "Location")) (is (= "Location" (node-name approval))))) ;; ---------------------------------------------------------------- ;; to-prev-sibling! returns false if there is no previous sibling ;; or if there is no previous sibling with the specified name ;; ---------------------------------------------------------------- (deftest to-prev-sibling-no-match-test (let [org1 (first (find-indexes nav "//Directory/Organizations/Organization"))] (is (not (to-prev-sibling! org1))) (is (not (to-prev-sibling! org1 "IDontExist"))))) ;; ---------------------------------------------------------------- ;; --------------- NAMESPACE TESTS FROM HERE DOWN ----------------- ;; ---------------------------------------------------------------- ;; ---------------------------------------------------------------- ;; Make sure that find-indexes works with XPATH namespaces. ;; Pass in an optional namespace hash. ;; ---------------------------------------------------------------- (deftest find-indexes-ns-test (is (= 4 (count (find-indexes nav-ns "/Directory/ns1:Organizations/ns1:Organization" ns-hash)))) (is (= 5 (count (find-indexes nav-ns (str "/Directory/ns1:Organizations" "/ns1:Organization" "/ns2:Employee[@role='Elected Member']") ns-hash)))) (is (= 12 (count (find-indexes nav-ns "//Name" ns-hash)))) ;; Get a VTDNav object pointing to the first organization element. ;; When we run relative XPATH queries on this, it should return only ;; the self or descendants of this element. (let [first-org (first (find-indexes nav-ns "/Directory/ns1:Organizations/ns1:Organization" ns-hash))] (is (= 3 (count (find-indexes first-org "ns2:Employee" ns-hash)))) (is (= 3 (count (find-indexes first-org "ns2:Employee/Name" ns-hash)))) (is (= 3 (count (find-indexes first-org "ns2:Employee//Name" ns-hash)))))) ;; ---------------------------------------------------------------- ;; List first-match-test above, but with namespaces ;; ---------------------------------------------------------------- (deftest first-match-ns-test (let [organizations (find-indexes nav-ns "/Directory/ns1:Organizations/ns1:Organization" ns-hash) org1 (first organizations) org2 (nth organizations 1)] (is (= "PI:NAME:<NAME>END_PI" (first-match org1 "ns2:Employee/Name" ns-hash))) (is (= "PI:NAME:<NAME>END_PI" (first-match org1 "ns2:Employee[@role='Staff']/Name" ns-hash))) (is (= "PI:NAME:<NAME>END_PI" (first-match org2 "ns2:Employee/Name" ns-hash))) (is (= "CPI:NAME:<NAME>END_PI" (first-match org2 "ns2:Employee[@role='Staff']/Name" ns-hash))))) ;; ---------------------------------------------------------------- ;; The all-matches test is described above. This is the same test ;; with namespaces. ;; ---------------------------------------------------------------- (deftest all-matches-ns-test (is (= 12 (count (all-matches nav-ns "//Name" ns-hash)))) (is (= "PI:NAME:<NAME>END_PI" (first (all-matches nav-ns "//ns2:Employee//Name" ns-hash)))) (is (= "PI:NAME:<NAME>END_PI" (last (all-matches nav-ns "//ns2:Employee//Name" ns-hash)))) ;; Run all-matches on elements within a single element. ;; In this case, the last organization element. (let [president (last (find-indexes nav-ns "/Directory/ns1:Organizations/ns1:Organization" ns-hash))] (is (= 3 (count (all-matches president "ns2:Employee/Name")))) (is (= "PI:NAME:<NAME>END_PI" (first (all-matches president "ns2:Employee[@role='President']/Name")))) (is (= "PI:NAME:<NAME>END_PI" (last (all-matches president "ns2:Employee/Name")))))) ;; ---------------------------------------------------------------- ;; get-xml returns a seq containing the literal XML of all matching ;; nodes. Make sure this works with namespaces ;; ---------------------------------------------------------------- (deftest get-xml-ns-test (is (= "<ns2:Employee role=\"Elected Member\"> <Name>PI:NAME:<NAME>END_PI</Name> </ns2:Employee>" (first (get-xml nav-ns senate-xpath-ns ns-hash)))) (is (= 12 (count (get-xml nav-ns "//ns2:Employee" ns-hash))))) ;; ---------------------------------------------------------------- ;; get-hash is described above. This tests to ensure it works with ;; namespaces ;; ---------------------------------------------------------------- (deftest get-hash-ns-test (is (= (first (get-hash nav-ns senate-xpath-ns ns-hash)) {:tag :ns2:Employee, :attrs {:role "Elected Member"}, :content [{:tag :Name, :attrs nil, :content ["PI:NAME:<NAME>END_PI"]}]})) (is (= 12 (count (get-hash nav-ns "//ns2:Employee" ns-hash)))))
[ { "context": ";; Copyright (c) 2015-2016 Andrey Antukh <niwi@niwi.nz>\n;; Copyright (c) 2015-2016 Alejand", "end": 40, "score": 0.9998942613601685, "start": 27, "tag": "NAME", "value": "Andrey Antukh" }, { "context": ";; Copyright (c) 2015-2016 Andrey Antukh <niwi@niwi.nz>\n;; Copyright (c) 2015-2016 Alejandro Gómez <alej", "end": 54, "score": 0.999930202960968, "start": 42, "tag": "EMAIL", "value": "niwi@niwi.nz" }, { "context": "y Antukh <niwi@niwi.nz>\n;; Copyright (c) 2015-2016 Alejandro Gómez <alejandro@dialelo.com>\n;; All rights reserved.\n;", "end": 98, "score": 0.9998888373374939, "start": 83, "tag": "NAME", "value": "Alejandro Gómez" }, { "context": "i.nz>\n;; Copyright (c) 2015-2016 Alejandro Gómez <alejandro@dialelo.com>\n;; All rights reserved.\n;;\n;; Redistribution and", "end": 121, "score": 0.9999344944953918, "start": 100, "tag": "EMAIL", "value": "alejandro@dialelo.com" } ]
src/cats/labs/manifold.clj
klausharbo/cats
896
;; Copyright (c) 2015-2016 Andrey Antukh <niwi@niwi.nz> ;; Copyright (c) 2015-2016 Alejandro Gómez <alejandro@dialelo.com> ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions ;; are met: ;; ;; 1. Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; 2. Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ;; IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, ;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (ns cats.labs.manifold (:require [manifold.deferred :as d] [manifold.stream :as s] [cats.context :as ctx] [cats.core :as m] [cats.protocols :as p] [cats.monad.either :as either] [cats.util :as util])) (defn- with-timeout [timeout timeout-value d] (when timeout (if timeout-value (d/timeout! d timeout timeout-value) (d/timeout! d timeout))) d) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Monad definition ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (deftype DeferredContext [timeout timeout-value] Object (equals [self other] ;; Two context with different values are considered ;; equals because as context they are represent ;; the same context. ;; FIXME: abstract this using own abstraction ;; without overriding the default equality checks. (instance? DeferredContext other)) p/Context p/Functor (-fmap [_ f mv] (with-timeout timeout timeout-value (d/chain mv f))) p/Applicative (-pure [_ v] (d/success-deferred v)) (-fapply [mn af av] (with-timeout timeout timeout-value (d/chain (d/zip' af av) (fn [[afv avv]] (afv avv))))) p/Semigroup (-mappend [ctx mv mv'] (with-timeout timeout timeout-value (d/chain (d/zip' mv mv') (fn [[mvv mvv']] (let [ctx (p/-get-context mvv)] (p/-mappend ctx mvv mvv')))))) p/Monad (-mreturn [_ v] (d/success-deferred v)) (-mbind [it mv f] (with-timeout timeout timeout-value (d/chain mv (fn [v] (ctx/with-context it (f v)))))) p/Printable (-repr [_] "#<Deferred>")) (defn deferred-context* ([] (deferred-context* nil nil)) ([timeout] (deferred-context* timeout nil)) ([timeout timeout-value] (DeferredContext. timeout timeout-value))) (def ^{:doc "A default context for manifold deferred."} deferred-context (deferred-context*)) (util/make-printable (type deferred-context)) (extend-type manifold.deferred.Deferred p/Contextual (-get-context [_] deferred-context)) (extend-type manifold.deferred.SuccessDeferred p/Contextual (-get-context [_] deferred-context)) (extend-type manifold.deferred.ErrorDeferred p/Contextual (-get-context [_] deferred-context))
42940
;; Copyright (c) 2015-2016 <NAME> <<EMAIL>> ;; 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: ;; ;; 1. Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; 2. Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ;; IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, ;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (ns cats.labs.manifold (:require [manifold.deferred :as d] [manifold.stream :as s] [cats.context :as ctx] [cats.core :as m] [cats.protocols :as p] [cats.monad.either :as either] [cats.util :as util])) (defn- with-timeout [timeout timeout-value d] (when timeout (if timeout-value (d/timeout! d timeout timeout-value) (d/timeout! d timeout))) d) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Monad definition ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (deftype DeferredContext [timeout timeout-value] Object (equals [self other] ;; Two context with different values are considered ;; equals because as context they are represent ;; the same context. ;; FIXME: abstract this using own abstraction ;; without overriding the default equality checks. (instance? DeferredContext other)) p/Context p/Functor (-fmap [_ f mv] (with-timeout timeout timeout-value (d/chain mv f))) p/Applicative (-pure [_ v] (d/success-deferred v)) (-fapply [mn af av] (with-timeout timeout timeout-value (d/chain (d/zip' af av) (fn [[afv avv]] (afv avv))))) p/Semigroup (-mappend [ctx mv mv'] (with-timeout timeout timeout-value (d/chain (d/zip' mv mv') (fn [[mvv mvv']] (let [ctx (p/-get-context mvv)] (p/-mappend ctx mvv mvv')))))) p/Monad (-mreturn [_ v] (d/success-deferred v)) (-mbind [it mv f] (with-timeout timeout timeout-value (d/chain mv (fn [v] (ctx/with-context it (f v)))))) p/Printable (-repr [_] "#<Deferred>")) (defn deferred-context* ([] (deferred-context* nil nil)) ([timeout] (deferred-context* timeout nil)) ([timeout timeout-value] (DeferredContext. timeout timeout-value))) (def ^{:doc "A default context for manifold deferred."} deferred-context (deferred-context*)) (util/make-printable (type deferred-context)) (extend-type manifold.deferred.Deferred p/Contextual (-get-context [_] deferred-context)) (extend-type manifold.deferred.SuccessDeferred p/Contextual (-get-context [_] deferred-context)) (extend-type manifold.deferred.ErrorDeferred p/Contextual (-get-context [_] deferred-context))
true
;; Copyright (c) 2015-2016 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ;; 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: ;; ;; 1. Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; 2. Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ;; IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, ;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (ns cats.labs.manifold (:require [manifold.deferred :as d] [manifold.stream :as s] [cats.context :as ctx] [cats.core :as m] [cats.protocols :as p] [cats.monad.either :as either] [cats.util :as util])) (defn- with-timeout [timeout timeout-value d] (when timeout (if timeout-value (d/timeout! d timeout timeout-value) (d/timeout! d timeout))) d) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Monad definition ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (deftype DeferredContext [timeout timeout-value] Object (equals [self other] ;; Two context with different values are considered ;; equals because as context they are represent ;; the same context. ;; FIXME: abstract this using own abstraction ;; without overriding the default equality checks. (instance? DeferredContext other)) p/Context p/Functor (-fmap [_ f mv] (with-timeout timeout timeout-value (d/chain mv f))) p/Applicative (-pure [_ v] (d/success-deferred v)) (-fapply [mn af av] (with-timeout timeout timeout-value (d/chain (d/zip' af av) (fn [[afv avv]] (afv avv))))) p/Semigroup (-mappend [ctx mv mv'] (with-timeout timeout timeout-value (d/chain (d/zip' mv mv') (fn [[mvv mvv']] (let [ctx (p/-get-context mvv)] (p/-mappend ctx mvv mvv')))))) p/Monad (-mreturn [_ v] (d/success-deferred v)) (-mbind [it mv f] (with-timeout timeout timeout-value (d/chain mv (fn [v] (ctx/with-context it (f v)))))) p/Printable (-repr [_] "#<Deferred>")) (defn deferred-context* ([] (deferred-context* nil nil)) ([timeout] (deferred-context* timeout nil)) ([timeout timeout-value] (DeferredContext. timeout timeout-value))) (def ^{:doc "A default context for manifold deferred."} deferred-context (deferred-context*)) (util/make-printable (type deferred-context)) (extend-type manifold.deferred.Deferred p/Contextual (-get-context [_] deferred-context)) (extend-type manifold.deferred.SuccessDeferred p/Contextual (-get-context [_] deferred-context)) (extend-type manifold.deferred.ErrorDeferred p/Contextual (-get-context [_] deferred-context))