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": "|enogtredefte)\"\n {:dim :ordinal\n :value (get {\"første\" 1 \"andre\" 2 \"tredje\" 3 \"fjerde\" 4 \"femte\" 5\n ",
"end": 5370,
"score": 0.7553068399429321,
"start": 5364,
"tag": "NAME",
"value": "første"
},
{
"context": "te)\"\n {:dim :ordinal\n :value (get {\"første\" 1 \"andre\" 2 \"tredje\" 3 \"fjerde\" 4 \"femte\" 5\n ",
"end": 5380,
"score": 0.8899174928665161,
"start": 5375,
"tag": "NAME",
"value": "andre"
},
{
"context": "im :ordinal\n :value (get {\"første\" 1 \"andre\" 2 \"tredje\" 3 \"fjerde\" 4 \"femte\" 5\n \"sjette\" 6 ",
"end": 5391,
"score": 0.6156057119369507,
"start": 5385,
"tag": "NAME",
"value": "tredje"
},
{
"context": " :value (get {\"første\" 1 \"andre\" 2 \"tredje\" 3 \"fjerde\" 4 \"femte\" 5\n \"sjette\" 6 \"syvende\"",
"end": 5400,
"score": 0.5989408493041992,
"start": 5397,
"tag": "NAME",
"value": "jer"
}
] | resources/languages/nb/rules/numbers.clj | sebastianmika/duckling | 0 | (
"intersect"
[(dim :number :grain #(> (:grain %) 1)) (dim :number)] ; grain 1 are taken care of by specific rule
(compose-numbers %1 %2)
"intersect (with and)"
[(dim :number :grain #(> (:grain %) 1)) #"(?i)og" (dim :number)] ; grain 1 are taken care of by specific rule
(compose-numbers %1 %3)
;;
;; Integers
;;
"integer (0..19)"
#"(?i)(intet|ingen|null|en|ett|én|to|tretten|tre|fire|femten|fem|seksten|seks|syv|sju|åtte|nitten|ni|ti|elleve|tolv|fjorten|sytten|søtten|atten)"
; fourteen must be before four, or it won't work because the regex will stop at four
{:dim :number
:integer true
:value (get {"intet" 0 "ingen" 0 "null" 0 "en" 1 "ett" 1 "én" 1 "to" 2 "tre" 3 "fire" 4 "fem" 5
"seks" 6 "syv" 7 "sju" 7 "otte" 8 "ni" 9 "ti" 10 "elleve" 11
"tolv" 12 "tretten" 13 "fjorten" 14 "femten" 15 "seksten" 16
"sytten" 17 "søtten" 17 "atten" 18 "nitten" 19}
(-> %1 :groups first .toLowerCase))}
"ten"
#"(?i)ti"
{:dim :number :integer true :value 10 :grain 1}
"single"
#"(?i)enkelt"
{:dim :number :integer true :value 1 :grain 1}
"a pair"
#"(?i)et par"
{:dim :number :integer true :value 2 :grain 1}
"dozen"
#"(?i)dusin"
{:dim :number :integer true :value 12 :grain 1 :grouping true} ;;restrict composition and prevent "2 12"
"hundred"
#"(?i)hundrede?"
{:dim :number :integer true :value 100 :grain 2}
"thousand"
#"(?i)tusen?"
{:dim :number :integer true :value 1000 :grain 3}
"million"
#"(?i)million(er)?"
{:dim :number :integer true :value 1000000 :grain 6}
"couple"
#"et par"
{:dim :number :integer true :value 2}
"few" ; TODO set assumption
#"(noen )?få"
{:dim :number :integer true :precision :approximate :value 3}
"integer (20..90)"
#"(?i)(tyve|tjue|tredve|førti|femti|seksti|sytti|åtti|nitti)"
{:dim :number
:integer true
:value (get {"tyve" 20 "tjue" 20 "tredve" 30 "førti" 40 "femti" 50 "seksti" 60
"sytti" 70 "åtti" 80 "nitti" 90}
(-> %1 :groups first .toLowerCase))
:grain 1}
"integer 21..99"
[(integer 10 90 #(#{20 30 40 50 60 70 80 90} (:value %))) (integer 1 9)]
{:dim :number
:integer true
:value (+ (:value %1) (:value %2))}
"integer (numeric)"
#"(\d{1,18})"
{:dim :number
:integer true
:value (Long/parseLong (first (:groups %1)))}
"integer with thousands separator ."
#"(\d{1,3}(\.\d\d\d){1,5})"
{:dim :number
:integer true
:value (-> (:groups %1)
first
(clojure.string/replace #"\." "")
Long/parseLong)}
"number hundreds"
[(integer 1 99) (integer 100 100)]
{:dim :number
:integer true
:value (* (:value %1) (:value %2))
:grain (:grain %2)}
"number thousands"
[(integer 1 999) (integer 1000 1000)]
{:dim :number
:integer true
:value (* (:value %1) (:value %2))
:grain (:grain %2)}
"number millions"
[(integer 1 99) (integer 1000000 1000000)]
{:dim :number
:integer true
:value (* (:value %1) (:value %2))
:grain (:grain %2)}
;;
;; Decimals
;;
"decimal number"
#"(\d*,\d+)"
{:dim :number
:value (-> (:groups %1)
first
(clojure.string/replace #"," ".")
Double/parseDouble)}
"number dot number"
[(dim :number #(not (:number-prefixed %))) #"(?i)komma" (dim :number #(not (:number-suffixed %)))]
{:dim :number
:value (+ (* 0.1 (:value %3)) (:value %1))}
"decimal with thousands separator"
#"(\d+(\.\d\d\d)+\,\d+)"
{:dim :number
:value (-> (:groups %1)
first
(clojure.string/replace #"\." "")
Double/parseDouble)}
;; negative number
"numbers prefix with -, negative or minus"
[#"(?i)-|minus\s?|negativ\s?" (dim :number #(not (:number-prefixed %)))]
(let [multiplier -1
value (* (:value %2) multiplier)
int? (zero? (mod value 1)) ; often true, but we could have 1.1111K
value (if int? (long value) value)] ; cleaner if we have the right type
(assoc %2 :value value
:integer int?
:number-prefixed true)) ; prevent "- -3km" to be 3 billions
;; suffixes
; note that we check for a space-like char after the M, K or G
; to avoid matching 3 Mandarins
"numbers suffixes (K, M, G)"
[(dim :number #(not (:number-suffixed %))) #"(?i)([kmg])(?=[\W\$€]|$)"]
(let [multiplier (get {"k" 1000 "m" 1000000 "g" 1000000000}
(-> %2 :groups first .toLowerCase))
value (* (:value %1) multiplier)
int? (zero? (mod value 1)) ; often true, but we could have 1.1111K
value (if int? (long value) value)] ; cleaner if we have the right type
(assoc %1 :value value
:integer int?
:number-suffixed true)) ; prevent "3km" to be 3 billions
;;
;; Ordinal numbers
;;
"ordinals (first..31st)"
#"(?i)(første|andre|tredje|fjerde|femte|sjette|syvende|åttende|niende|tiende|ellevte|tolvte|trettende|fjortende|femtende|sekstende|syttende|attende|nittende|tyvende|tjuende|enogtyvende|toogtyvende|treogtyvende|fireogtyvende|femogtyvende|seksogtyvende|syvogtyvende|åtteogtyvende|niogtyvende|enogtjuende|toogtjuende|treogtjuende|fireogtjuende|femogtjuende|seksogtjuende|syvogtjuende|åtteogtyvend|niogtjuende|tredefte|enogtredefte)"
{:dim :ordinal
:value (get {"første" 1 "andre" 2 "tredje" 3 "fjerde" 4 "femte" 5
"sjette" 6 "syvende" 7 "åttende" 8 "niende" 9 "tiende" 10 "ellevte" 11
"tolvte" 12 "trettende" 13 "fjortende" 14 "femtende" 15 "sekstende" 16
"syttende" 17 "attende" 18 "nittende" 19 "tyvende" 20 "tjuende" 20 "enogtyvende" 21
"toogtyvende" 22 "treogtyvende" 23 "fireogtyvende" 24 "femogtyvende" 25
"seksogtyvende" 26 "syvogtyvende" 27 "åtteogtyvende" 28 "niogtyvende" 29 "enogtjuende" 21
"toogtjuende" 22 "treogtjuende" 23 "fireogtjuende" 24 "femogtjuende" 25
"seksogtjuende" 26 "syvogtjuende" 27 "åtteogtjuende" 28 "niogtjuende" 29
"tredefte" 30 "enogtredefte" 31}
(-> %1 :groups first .toLowerCase))}
"ordinal (digits)"
#"0*(\d+)(\.|ste?)"
{:dim :ordinal
:value (read-string (first (:groups %1)))} ; read-string not the safest
)
| 29377 | (
"intersect"
[(dim :number :grain #(> (:grain %) 1)) (dim :number)] ; grain 1 are taken care of by specific rule
(compose-numbers %1 %2)
"intersect (with and)"
[(dim :number :grain #(> (:grain %) 1)) #"(?i)og" (dim :number)] ; grain 1 are taken care of by specific rule
(compose-numbers %1 %3)
;;
;; Integers
;;
"integer (0..19)"
#"(?i)(intet|ingen|null|en|ett|én|to|tretten|tre|fire|femten|fem|seksten|seks|syv|sju|åtte|nitten|ni|ti|elleve|tolv|fjorten|sytten|søtten|atten)"
; fourteen must be before four, or it won't work because the regex will stop at four
{:dim :number
:integer true
:value (get {"intet" 0 "ingen" 0 "null" 0 "en" 1 "ett" 1 "én" 1 "to" 2 "tre" 3 "fire" 4 "fem" 5
"seks" 6 "syv" 7 "sju" 7 "otte" 8 "ni" 9 "ti" 10 "elleve" 11
"tolv" 12 "tretten" 13 "fjorten" 14 "femten" 15 "seksten" 16
"sytten" 17 "søtten" 17 "atten" 18 "nitten" 19}
(-> %1 :groups first .toLowerCase))}
"ten"
#"(?i)ti"
{:dim :number :integer true :value 10 :grain 1}
"single"
#"(?i)enkelt"
{:dim :number :integer true :value 1 :grain 1}
"a pair"
#"(?i)et par"
{:dim :number :integer true :value 2 :grain 1}
"dozen"
#"(?i)dusin"
{:dim :number :integer true :value 12 :grain 1 :grouping true} ;;restrict composition and prevent "2 12"
"hundred"
#"(?i)hundrede?"
{:dim :number :integer true :value 100 :grain 2}
"thousand"
#"(?i)tusen?"
{:dim :number :integer true :value 1000 :grain 3}
"million"
#"(?i)million(er)?"
{:dim :number :integer true :value 1000000 :grain 6}
"couple"
#"et par"
{:dim :number :integer true :value 2}
"few" ; TODO set assumption
#"(noen )?få"
{:dim :number :integer true :precision :approximate :value 3}
"integer (20..90)"
#"(?i)(tyve|tjue|tredve|førti|femti|seksti|sytti|åtti|nitti)"
{:dim :number
:integer true
:value (get {"tyve" 20 "tjue" 20 "tredve" 30 "førti" 40 "femti" 50 "seksti" 60
"sytti" 70 "åtti" 80 "nitti" 90}
(-> %1 :groups first .toLowerCase))
:grain 1}
"integer 21..99"
[(integer 10 90 #(#{20 30 40 50 60 70 80 90} (:value %))) (integer 1 9)]
{:dim :number
:integer true
:value (+ (:value %1) (:value %2))}
"integer (numeric)"
#"(\d{1,18})"
{:dim :number
:integer true
:value (Long/parseLong (first (:groups %1)))}
"integer with thousands separator ."
#"(\d{1,3}(\.\d\d\d){1,5})"
{:dim :number
:integer true
:value (-> (:groups %1)
first
(clojure.string/replace #"\." "")
Long/parseLong)}
"number hundreds"
[(integer 1 99) (integer 100 100)]
{:dim :number
:integer true
:value (* (:value %1) (:value %2))
:grain (:grain %2)}
"number thousands"
[(integer 1 999) (integer 1000 1000)]
{:dim :number
:integer true
:value (* (:value %1) (:value %2))
:grain (:grain %2)}
"number millions"
[(integer 1 99) (integer 1000000 1000000)]
{:dim :number
:integer true
:value (* (:value %1) (:value %2))
:grain (:grain %2)}
;;
;; Decimals
;;
"decimal number"
#"(\d*,\d+)"
{:dim :number
:value (-> (:groups %1)
first
(clojure.string/replace #"," ".")
Double/parseDouble)}
"number dot number"
[(dim :number #(not (:number-prefixed %))) #"(?i)komma" (dim :number #(not (:number-suffixed %)))]
{:dim :number
:value (+ (* 0.1 (:value %3)) (:value %1))}
"decimal with thousands separator"
#"(\d+(\.\d\d\d)+\,\d+)"
{:dim :number
:value (-> (:groups %1)
first
(clojure.string/replace #"\." "")
Double/parseDouble)}
;; negative number
"numbers prefix with -, negative or minus"
[#"(?i)-|minus\s?|negativ\s?" (dim :number #(not (:number-prefixed %)))]
(let [multiplier -1
value (* (:value %2) multiplier)
int? (zero? (mod value 1)) ; often true, but we could have 1.1111K
value (if int? (long value) value)] ; cleaner if we have the right type
(assoc %2 :value value
:integer int?
:number-prefixed true)) ; prevent "- -3km" to be 3 billions
;; suffixes
; note that we check for a space-like char after the M, K or G
; to avoid matching 3 Mandarins
"numbers suffixes (K, M, G)"
[(dim :number #(not (:number-suffixed %))) #"(?i)([kmg])(?=[\W\$€]|$)"]
(let [multiplier (get {"k" 1000 "m" 1000000 "g" 1000000000}
(-> %2 :groups first .toLowerCase))
value (* (:value %1) multiplier)
int? (zero? (mod value 1)) ; often true, but we could have 1.1111K
value (if int? (long value) value)] ; cleaner if we have the right type
(assoc %1 :value value
:integer int?
:number-suffixed true)) ; prevent "3km" to be 3 billions
;;
;; Ordinal numbers
;;
"ordinals (first..31st)"
#"(?i)(første|andre|tredje|fjerde|femte|sjette|syvende|åttende|niende|tiende|ellevte|tolvte|trettende|fjortende|femtende|sekstende|syttende|attende|nittende|tyvende|tjuende|enogtyvende|toogtyvende|treogtyvende|fireogtyvende|femogtyvende|seksogtyvende|syvogtyvende|åtteogtyvende|niogtyvende|enogtjuende|toogtjuende|treogtjuende|fireogtjuende|femogtjuende|seksogtjuende|syvogtjuende|åtteogtyvend|niogtjuende|tredefte|enogtredefte)"
{:dim :ordinal
:value (get {"<NAME>" 1 "<NAME>" 2 "<NAME>" 3 "f<NAME>de" 4 "femte" 5
"sjette" 6 "syvende" 7 "åttende" 8 "niende" 9 "tiende" 10 "ellevte" 11
"tolvte" 12 "trettende" 13 "fjortende" 14 "femtende" 15 "sekstende" 16
"syttende" 17 "attende" 18 "nittende" 19 "tyvende" 20 "tjuende" 20 "enogtyvende" 21
"toogtyvende" 22 "treogtyvende" 23 "fireogtyvende" 24 "femogtyvende" 25
"seksogtyvende" 26 "syvogtyvende" 27 "åtteogtyvende" 28 "niogtyvende" 29 "enogtjuende" 21
"toogtjuende" 22 "treogtjuende" 23 "fireogtjuende" 24 "femogtjuende" 25
"seksogtjuende" 26 "syvogtjuende" 27 "åtteogtjuende" 28 "niogtjuende" 29
"tredefte" 30 "enogtredefte" 31}
(-> %1 :groups first .toLowerCase))}
"ordinal (digits)"
#"0*(\d+)(\.|ste?)"
{:dim :ordinal
:value (read-string (first (:groups %1)))} ; read-string not the safest
)
| true | (
"intersect"
[(dim :number :grain #(> (:grain %) 1)) (dim :number)] ; grain 1 are taken care of by specific rule
(compose-numbers %1 %2)
"intersect (with and)"
[(dim :number :grain #(> (:grain %) 1)) #"(?i)og" (dim :number)] ; grain 1 are taken care of by specific rule
(compose-numbers %1 %3)
;;
;; Integers
;;
"integer (0..19)"
#"(?i)(intet|ingen|null|en|ett|én|to|tretten|tre|fire|femten|fem|seksten|seks|syv|sju|åtte|nitten|ni|ti|elleve|tolv|fjorten|sytten|søtten|atten)"
; fourteen must be before four, or it won't work because the regex will stop at four
{:dim :number
:integer true
:value (get {"intet" 0 "ingen" 0 "null" 0 "en" 1 "ett" 1 "én" 1 "to" 2 "tre" 3 "fire" 4 "fem" 5
"seks" 6 "syv" 7 "sju" 7 "otte" 8 "ni" 9 "ti" 10 "elleve" 11
"tolv" 12 "tretten" 13 "fjorten" 14 "femten" 15 "seksten" 16
"sytten" 17 "søtten" 17 "atten" 18 "nitten" 19}
(-> %1 :groups first .toLowerCase))}
"ten"
#"(?i)ti"
{:dim :number :integer true :value 10 :grain 1}
"single"
#"(?i)enkelt"
{:dim :number :integer true :value 1 :grain 1}
"a pair"
#"(?i)et par"
{:dim :number :integer true :value 2 :grain 1}
"dozen"
#"(?i)dusin"
{:dim :number :integer true :value 12 :grain 1 :grouping true} ;;restrict composition and prevent "2 12"
"hundred"
#"(?i)hundrede?"
{:dim :number :integer true :value 100 :grain 2}
"thousand"
#"(?i)tusen?"
{:dim :number :integer true :value 1000 :grain 3}
"million"
#"(?i)million(er)?"
{:dim :number :integer true :value 1000000 :grain 6}
"couple"
#"et par"
{:dim :number :integer true :value 2}
"few" ; TODO set assumption
#"(noen )?få"
{:dim :number :integer true :precision :approximate :value 3}
"integer (20..90)"
#"(?i)(tyve|tjue|tredve|førti|femti|seksti|sytti|åtti|nitti)"
{:dim :number
:integer true
:value (get {"tyve" 20 "tjue" 20 "tredve" 30 "førti" 40 "femti" 50 "seksti" 60
"sytti" 70 "åtti" 80 "nitti" 90}
(-> %1 :groups first .toLowerCase))
:grain 1}
"integer 21..99"
[(integer 10 90 #(#{20 30 40 50 60 70 80 90} (:value %))) (integer 1 9)]
{:dim :number
:integer true
:value (+ (:value %1) (:value %2))}
"integer (numeric)"
#"(\d{1,18})"
{:dim :number
:integer true
:value (Long/parseLong (first (:groups %1)))}
"integer with thousands separator ."
#"(\d{1,3}(\.\d\d\d){1,5})"
{:dim :number
:integer true
:value (-> (:groups %1)
first
(clojure.string/replace #"\." "")
Long/parseLong)}
"number hundreds"
[(integer 1 99) (integer 100 100)]
{:dim :number
:integer true
:value (* (:value %1) (:value %2))
:grain (:grain %2)}
"number thousands"
[(integer 1 999) (integer 1000 1000)]
{:dim :number
:integer true
:value (* (:value %1) (:value %2))
:grain (:grain %2)}
"number millions"
[(integer 1 99) (integer 1000000 1000000)]
{:dim :number
:integer true
:value (* (:value %1) (:value %2))
:grain (:grain %2)}
;;
;; Decimals
;;
"decimal number"
#"(\d*,\d+)"
{:dim :number
:value (-> (:groups %1)
first
(clojure.string/replace #"," ".")
Double/parseDouble)}
"number dot number"
[(dim :number #(not (:number-prefixed %))) #"(?i)komma" (dim :number #(not (:number-suffixed %)))]
{:dim :number
:value (+ (* 0.1 (:value %3)) (:value %1))}
"decimal with thousands separator"
#"(\d+(\.\d\d\d)+\,\d+)"
{:dim :number
:value (-> (:groups %1)
first
(clojure.string/replace #"\." "")
Double/parseDouble)}
;; negative number
"numbers prefix with -, negative or minus"
[#"(?i)-|minus\s?|negativ\s?" (dim :number #(not (:number-prefixed %)))]
(let [multiplier -1
value (* (:value %2) multiplier)
int? (zero? (mod value 1)) ; often true, but we could have 1.1111K
value (if int? (long value) value)] ; cleaner if we have the right type
(assoc %2 :value value
:integer int?
:number-prefixed true)) ; prevent "- -3km" to be 3 billions
;; suffixes
; note that we check for a space-like char after the M, K or G
; to avoid matching 3 Mandarins
"numbers suffixes (K, M, G)"
[(dim :number #(not (:number-suffixed %))) #"(?i)([kmg])(?=[\W\$€]|$)"]
(let [multiplier (get {"k" 1000 "m" 1000000 "g" 1000000000}
(-> %2 :groups first .toLowerCase))
value (* (:value %1) multiplier)
int? (zero? (mod value 1)) ; often true, but we could have 1.1111K
value (if int? (long value) value)] ; cleaner if we have the right type
(assoc %1 :value value
:integer int?
:number-suffixed true)) ; prevent "3km" to be 3 billions
;;
;; Ordinal numbers
;;
"ordinals (first..31st)"
#"(?i)(første|andre|tredje|fjerde|femte|sjette|syvende|åttende|niende|tiende|ellevte|tolvte|trettende|fjortende|femtende|sekstende|syttende|attende|nittende|tyvende|tjuende|enogtyvende|toogtyvende|treogtyvende|fireogtyvende|femogtyvende|seksogtyvende|syvogtyvende|åtteogtyvende|niogtyvende|enogtjuende|toogtjuende|treogtjuende|fireogtjuende|femogtjuende|seksogtjuende|syvogtjuende|åtteogtyvend|niogtjuende|tredefte|enogtredefte)"
{:dim :ordinal
:value (get {"PI:NAME:<NAME>END_PI" 1 "PI:NAME:<NAME>END_PI" 2 "PI:NAME:<NAME>END_PI" 3 "fPI:NAME:<NAME>END_PIde" 4 "femte" 5
"sjette" 6 "syvende" 7 "åttende" 8 "niende" 9 "tiende" 10 "ellevte" 11
"tolvte" 12 "trettende" 13 "fjortende" 14 "femtende" 15 "sekstende" 16
"syttende" 17 "attende" 18 "nittende" 19 "tyvende" 20 "tjuende" 20 "enogtyvende" 21
"toogtyvende" 22 "treogtyvende" 23 "fireogtyvende" 24 "femogtyvende" 25
"seksogtyvende" 26 "syvogtyvende" 27 "åtteogtyvende" 28 "niogtyvende" 29 "enogtjuende" 21
"toogtjuende" 22 "treogtjuende" 23 "fireogtjuende" 24 "femogtjuende" 25
"seksogtjuende" 26 "syvogtjuende" 27 "åtteogtjuende" 28 "niogtjuende" 29
"tredefte" 30 "enogtredefte" 31}
(-> %1 :groups first .toLowerCase))}
"ordinal (digits)"
#"0*(\d+)(\.|ste?)"
{:dim :ordinal
:value (read-string (first (:groups %1)))} ; read-string not the safest
)
|
[
{
"context": "QL_USER\" \"clj\"\n \"MYSQL_PASSWORD\" \"s3cr3t\"\n \"MYSQL_ROOT_PASSWORD\" \"root\"\n \"TZ\" ",
"end": 309,
"score": 0.9988753199577332,
"start": 303,
"tag": "PASSWORD",
"value": "s3cr3t"
},
{
"context": "PASSWORD\" \"s3cr3t\"\n \"MYSQL_ROOT_PASSWORD\" \"root\"\n \"TZ\" \"UTC\"})\n\n(defn- contain",
"end": 341,
"score": 0.9960999488830566,
"start": 337,
"tag": "PASSWORD",
"value": "root"
}
] | test/com/chicoalmeida/mysqlx_clj/config/docker_lifecycle.clj | chicoalmeida/mysqlx-clj | 4 | (ns com.chicoalmeida.mysqlx-clj.config.docker-lifecycle
(:import (org.testcontainers.containers GenericContainer)
(org.testcontainers.containers.wait.strategy Wait)))
(def connection-properties
{"MYSQL_DATABASE" "mysqlx-clj"
"MYSQL_USER" "clj"
"MYSQL_PASSWORD" "s3cr3t"
"MYSQL_ROOT_PASSWORD" "root"
"TZ" "UTC"})
(defn- container []
(let [image-tag "mysql:8.0.13"
x-port (into-array Integer [(Integer. 33060)])
startup-signal (Wait/forLogMessage ".*X Plugin ready for connections.*\\s" 2)
environment connection-properties]
(-> (GenericContainer. image-tag)
(.withEnv environment)
(.withExposedPorts x-port)
(.waitingFor startup-signal))))
(defn initialize []
(let [mysql-8-container (container)]
(.start mysql-8-container)
mysql-8-container))
(defn running? [container]
(if container
(.isRunning container)))
(defn host-address [container]
(if container
(.getIpAddress container)
"localhost"))
(defn host-port [container]
(if container
(.getMappedPort container 33060)
30000))
(defn destroy [container]
(.stop container))
| 38487 | (ns com.chicoalmeida.mysqlx-clj.config.docker-lifecycle
(:import (org.testcontainers.containers GenericContainer)
(org.testcontainers.containers.wait.strategy Wait)))
(def connection-properties
{"MYSQL_DATABASE" "mysqlx-clj"
"MYSQL_USER" "clj"
"MYSQL_PASSWORD" "<PASSWORD>"
"MYSQL_ROOT_PASSWORD" "<PASSWORD>"
"TZ" "UTC"})
(defn- container []
(let [image-tag "mysql:8.0.13"
x-port (into-array Integer [(Integer. 33060)])
startup-signal (Wait/forLogMessage ".*X Plugin ready for connections.*\\s" 2)
environment connection-properties]
(-> (GenericContainer. image-tag)
(.withEnv environment)
(.withExposedPorts x-port)
(.waitingFor startup-signal))))
(defn initialize []
(let [mysql-8-container (container)]
(.start mysql-8-container)
mysql-8-container))
(defn running? [container]
(if container
(.isRunning container)))
(defn host-address [container]
(if container
(.getIpAddress container)
"localhost"))
(defn host-port [container]
(if container
(.getMappedPort container 33060)
30000))
(defn destroy [container]
(.stop container))
| true | (ns com.chicoalmeida.mysqlx-clj.config.docker-lifecycle
(:import (org.testcontainers.containers GenericContainer)
(org.testcontainers.containers.wait.strategy Wait)))
(def connection-properties
{"MYSQL_DATABASE" "mysqlx-clj"
"MYSQL_USER" "clj"
"MYSQL_PASSWORD" "PI:PASSWORD:<PASSWORD>END_PI"
"MYSQL_ROOT_PASSWORD" "PI:PASSWORD:<PASSWORD>END_PI"
"TZ" "UTC"})
(defn- container []
(let [image-tag "mysql:8.0.13"
x-port (into-array Integer [(Integer. 33060)])
startup-signal (Wait/forLogMessage ".*X Plugin ready for connections.*\\s" 2)
environment connection-properties]
(-> (GenericContainer. image-tag)
(.withEnv environment)
(.withExposedPorts x-port)
(.waitingFor startup-signal))))
(defn initialize []
(let [mysql-8-container (container)]
(.start mysql-8-container)
mysql-8-container))
(defn running? [container]
(if container
(.isRunning container)))
(defn host-address [container]
(if container
(.getIpAddress container)
"localhost"))
(defn host-port [container]
(if container
(.getMappedPort container 33060)
30000))
(defn destroy [container]
(.stop container))
|
[
{
"context": "ites_count 0, :time_zone \"London\",\n :name \"Emeka Mosanya\",\n :id_str \"19400021\", :listed_count 1, :u",
"end": 2656,
"score": 0.9998900890350342,
"start": 2643,
"tag": "NAME",
"value": "Emeka Mosanya"
},
{
"context": "rofile_text_color \"333333\",\n :screen_name \"EmekaMosanya\"}}\n\n",
"end": 3529,
"score": 0.999686062335968,
"start": 3517,
"tag": "USERNAME",
"value": "EmekaMosanya"
}
] | test/twitter-emeka-mosanya.clf.clj | emeka/londonstartup | 1 | {:status {:code 200, :msg "OK",
:protocol "HTTP/1.1", :major 1, :minor 1},
:headers {:cache-control "no-cache, no-store, must-revalidate, pre-check=0, post-check=0",
:content-length "2287", :content-type "application/json;charset=utf-8", :date "Fri, 05 Jul 2013 15:26:45 GMT",
:expires "Tue, 31 Mar 1981 05:00:00 GMT", :last-modified "Fri, 05 Jul 2013 15:26:45 GMT", :pragma "no-cache",
:server "tfe", :set-cookie ["lang=en" "guest_id=v1%3A137303800541742730; Domain=.twitter.com; Path=/; Expires=Sun, 05-Jul-2015 15:26:45 UTC"],
:status "200 OK", :x-access-level "read", :x-frame-options "SAMEORIGIN", :x-rate-limit-limit "180",
:x-rate-limit-remaining "179", :x-rate-limit-reset "1373038905", :x-transaction "5751479f293053ef",
:x-xss-protection "1; mode=block"},
:body {:status {:favorite_count 2,
:entities {:hashtags [], :symbols [],
:urls [{:url "http://t.co/7DXQqxLBTx",
:expanded_url "http://bit.ly/14hdWrQ",
:display_url "bit.ly/14hdWrQ", :indices [66 88]}], :user_mentions []},
:text "My second post on integrating Clojure, Noir and MongoDB on Heroku http://t.co/7DXQqxLBTx including local and remote integration tests",
:retweet_count 0, :coordinates nil, :possibly_sensitive false, :in_reply_to_status_id_str nil,
:contributors nil, :in_reply_to_user_id_str nil,
:id_str "342329773290311680", :in_reply_to_screen_name nil,
:retweeted false, :truncated false, :created_at "Wed Jun 05 17:19:12 +0000 2013",
:lang "en", :geo nil, :place nil, :in_reply_to_status_id nil,
:favorited false,
:source "<a href=\"http://twitter.com/tweetbutton\" rel=\"nofollow\">Tweet Button</a>",
:id 342329773290311680, :in_reply_to_user_id nil}, :profile_use_background_image true,
:follow_request_sent false,
:entities {:url {:urls [{:url "http://t.co/7yxenrx7q5",
:expanded_url "http://emekamosanya.com",
:display_url "emekamosanya.com", :indices [0 22]}]},
:description {:urls []}}, :default_profile true, :profile_sidebar_fill_color "DDEEF6",
:protected false, :following false, :profile_background_image_url "http://a0.twimg.com/images/themes/theme1/bg.png",
:default_profile_image false,
:contributors_enabled false, :favourites_count 0, :time_zone "London",
:name "Emeka Mosanya",
:id_str "19400021", :listed_count 1, :utc_offset 0, :profile_link_color "0084B4", :profile_background_tile false,
:location "London", :statuses_count 61, :followers_count 58, :friends_count 96, :created_at "Fri Jan 23 16:09:46 +0000 2009", :lang "en",
:profile_sidebar_border_color "C0DEED", :url "http://t.co/7yxenrx7q5", :notifications false,
:profile_background_color "C0DEED",
:geo_enabled false, :profile_image_url_https "https://si0.twimg.com/profile_images/605965984/IMG_0215_normal.JPG",
:is_translator false, :profile_image_url "http://a0.twimg.com/profile_images/605965984/IMG_0215_normal.JPG",
:verified false, :id 19400021, :profile_background_image_url_https "https://si0.twimg.com/images/themes/theme1/bg.png",
:description "", :profile_text_color "333333",
:screen_name "EmekaMosanya"}}
| 109467 | {:status {:code 200, :msg "OK",
:protocol "HTTP/1.1", :major 1, :minor 1},
:headers {:cache-control "no-cache, no-store, must-revalidate, pre-check=0, post-check=0",
:content-length "2287", :content-type "application/json;charset=utf-8", :date "Fri, 05 Jul 2013 15:26:45 GMT",
:expires "Tue, 31 Mar 1981 05:00:00 GMT", :last-modified "Fri, 05 Jul 2013 15:26:45 GMT", :pragma "no-cache",
:server "tfe", :set-cookie ["lang=en" "guest_id=v1%3A137303800541742730; Domain=.twitter.com; Path=/; Expires=Sun, 05-Jul-2015 15:26:45 UTC"],
:status "200 OK", :x-access-level "read", :x-frame-options "SAMEORIGIN", :x-rate-limit-limit "180",
:x-rate-limit-remaining "179", :x-rate-limit-reset "1373038905", :x-transaction "5751479f293053ef",
:x-xss-protection "1; mode=block"},
:body {:status {:favorite_count 2,
:entities {:hashtags [], :symbols [],
:urls [{:url "http://t.co/7DXQqxLBTx",
:expanded_url "http://bit.ly/14hdWrQ",
:display_url "bit.ly/14hdWrQ", :indices [66 88]}], :user_mentions []},
:text "My second post on integrating Clojure, Noir and MongoDB on Heroku http://t.co/7DXQqxLBTx including local and remote integration tests",
:retweet_count 0, :coordinates nil, :possibly_sensitive false, :in_reply_to_status_id_str nil,
:contributors nil, :in_reply_to_user_id_str nil,
:id_str "342329773290311680", :in_reply_to_screen_name nil,
:retweeted false, :truncated false, :created_at "Wed Jun 05 17:19:12 +0000 2013",
:lang "en", :geo nil, :place nil, :in_reply_to_status_id nil,
:favorited false,
:source "<a href=\"http://twitter.com/tweetbutton\" rel=\"nofollow\">Tweet Button</a>",
:id 342329773290311680, :in_reply_to_user_id nil}, :profile_use_background_image true,
:follow_request_sent false,
:entities {:url {:urls [{:url "http://t.co/7yxenrx7q5",
:expanded_url "http://emekamosanya.com",
:display_url "emekamosanya.com", :indices [0 22]}]},
:description {:urls []}}, :default_profile true, :profile_sidebar_fill_color "DDEEF6",
:protected false, :following false, :profile_background_image_url "http://a0.twimg.com/images/themes/theme1/bg.png",
:default_profile_image false,
:contributors_enabled false, :favourites_count 0, :time_zone "London",
:name "<NAME>",
:id_str "19400021", :listed_count 1, :utc_offset 0, :profile_link_color "0084B4", :profile_background_tile false,
:location "London", :statuses_count 61, :followers_count 58, :friends_count 96, :created_at "Fri Jan 23 16:09:46 +0000 2009", :lang "en",
:profile_sidebar_border_color "C0DEED", :url "http://t.co/7yxenrx7q5", :notifications false,
:profile_background_color "C0DEED",
:geo_enabled false, :profile_image_url_https "https://si0.twimg.com/profile_images/605965984/IMG_0215_normal.JPG",
:is_translator false, :profile_image_url "http://a0.twimg.com/profile_images/605965984/IMG_0215_normal.JPG",
:verified false, :id 19400021, :profile_background_image_url_https "https://si0.twimg.com/images/themes/theme1/bg.png",
:description "", :profile_text_color "333333",
:screen_name "EmekaMosanya"}}
| true | {:status {:code 200, :msg "OK",
:protocol "HTTP/1.1", :major 1, :minor 1},
:headers {:cache-control "no-cache, no-store, must-revalidate, pre-check=0, post-check=0",
:content-length "2287", :content-type "application/json;charset=utf-8", :date "Fri, 05 Jul 2013 15:26:45 GMT",
:expires "Tue, 31 Mar 1981 05:00:00 GMT", :last-modified "Fri, 05 Jul 2013 15:26:45 GMT", :pragma "no-cache",
:server "tfe", :set-cookie ["lang=en" "guest_id=v1%3A137303800541742730; Domain=.twitter.com; Path=/; Expires=Sun, 05-Jul-2015 15:26:45 UTC"],
:status "200 OK", :x-access-level "read", :x-frame-options "SAMEORIGIN", :x-rate-limit-limit "180",
:x-rate-limit-remaining "179", :x-rate-limit-reset "1373038905", :x-transaction "5751479f293053ef",
:x-xss-protection "1; mode=block"},
:body {:status {:favorite_count 2,
:entities {:hashtags [], :symbols [],
:urls [{:url "http://t.co/7DXQqxLBTx",
:expanded_url "http://bit.ly/14hdWrQ",
:display_url "bit.ly/14hdWrQ", :indices [66 88]}], :user_mentions []},
:text "My second post on integrating Clojure, Noir and MongoDB on Heroku http://t.co/7DXQqxLBTx including local and remote integration tests",
:retweet_count 0, :coordinates nil, :possibly_sensitive false, :in_reply_to_status_id_str nil,
:contributors nil, :in_reply_to_user_id_str nil,
:id_str "342329773290311680", :in_reply_to_screen_name nil,
:retweeted false, :truncated false, :created_at "Wed Jun 05 17:19:12 +0000 2013",
:lang "en", :geo nil, :place nil, :in_reply_to_status_id nil,
:favorited false,
:source "<a href=\"http://twitter.com/tweetbutton\" rel=\"nofollow\">Tweet Button</a>",
:id 342329773290311680, :in_reply_to_user_id nil}, :profile_use_background_image true,
:follow_request_sent false,
:entities {:url {:urls [{:url "http://t.co/7yxenrx7q5",
:expanded_url "http://emekamosanya.com",
:display_url "emekamosanya.com", :indices [0 22]}]},
:description {:urls []}}, :default_profile true, :profile_sidebar_fill_color "DDEEF6",
:protected false, :following false, :profile_background_image_url "http://a0.twimg.com/images/themes/theme1/bg.png",
:default_profile_image false,
:contributors_enabled false, :favourites_count 0, :time_zone "London",
:name "PI:NAME:<NAME>END_PI",
:id_str "19400021", :listed_count 1, :utc_offset 0, :profile_link_color "0084B4", :profile_background_tile false,
:location "London", :statuses_count 61, :followers_count 58, :friends_count 96, :created_at "Fri Jan 23 16:09:46 +0000 2009", :lang "en",
:profile_sidebar_border_color "C0DEED", :url "http://t.co/7yxenrx7q5", :notifications false,
:profile_background_color "C0DEED",
:geo_enabled false, :profile_image_url_https "https://si0.twimg.com/profile_images/605965984/IMG_0215_normal.JPG",
:is_translator false, :profile_image_url "http://a0.twimg.com/profile_images/605965984/IMG_0215_normal.JPG",
:verified false, :id 19400021, :profile_background_image_url_https "https://si0.twimg.com/images/themes/theme1/bg.png",
:description "", :profile_text_color "333333",
:screen_name "EmekaMosanya"}}
|
[
{
"context": " \"Authorization\" \"Basic narfdorfle\"}})\n map (core/headers->map (.headers req)",
"end": 526,
"score": 0.655317485332489,
"start": 517,
"tag": "PASSWORD",
"value": "arfdorfle"
}
] | test/aleph/http/core_test.clj | 7theta/aleph | 123 | (ns aleph.http.core-test
(:use
[clojure test])
(:require
[aleph.http.core :as core])
(:import
[io.netty.handler.codec.http
DefaultHttpRequest]))
(deftest test-HeaderMap-keys
(let [^DefaultHttpRequest req (core/ring-request->netty-request
{:uri "http://example.com"
:request-method "get"
:headers {"Accept" "text/html"
"Authorization" "Basic narfdorfle"}})
map (core/headers->map (.headers req))
dissoc-map (dissoc map "authorization")]
(is (= #{"accept"} (-> dissoc-map keys set)))))
| 12807 | (ns aleph.http.core-test
(:use
[clojure test])
(:require
[aleph.http.core :as core])
(:import
[io.netty.handler.codec.http
DefaultHttpRequest]))
(deftest test-HeaderMap-keys
(let [^DefaultHttpRequest req (core/ring-request->netty-request
{:uri "http://example.com"
:request-method "get"
:headers {"Accept" "text/html"
"Authorization" "Basic n<PASSWORD>"}})
map (core/headers->map (.headers req))
dissoc-map (dissoc map "authorization")]
(is (= #{"accept"} (-> dissoc-map keys set)))))
| true | (ns aleph.http.core-test
(:use
[clojure test])
(:require
[aleph.http.core :as core])
(:import
[io.netty.handler.codec.http
DefaultHttpRequest]))
(deftest test-HeaderMap-keys
(let [^DefaultHttpRequest req (core/ring-request->netty-request
{:uri "http://example.com"
:request-method "get"
:headers {"Accept" "text/html"
"Authorization" "Basic nPI:PASSWORD:<PASSWORD>END_PI"}})
map (core/headers->map (.headers req))
dissoc-map (dissoc map "authorization")]
(is (= #{"accept"} (-> dissoc-map keys set)))))
|
[
{
"context": "map\"\n (read-csv test-file) => [{:scientificName \"Aphelandra longiflora\" :latitude \"10.10\" :longitude \"20.20\" :locality \"",
"end": 277,
"score": 0.9998716711997986,
"start": 256,
"tag": "NAME",
"value": "Aphelandra longiflora"
},
{
"context": "un\"}\n {:scientificName \"Vicia faba\" :latitude \"30.3\" :longitude \"8.9\" :locality \"\"}]",
"end": 393,
"score": 0.9998474717140198,
"start": 383,
"tag": "NAME",
"value": "Vicia faba"
},
{
"context": "\"}]\n (read-csv test-file2) => [{:scientificName \"Aphelandra longiflora\" :latitude \"10.10\" :longitude \"20.20\" :locality \"",
"end": 511,
"score": 0.9998632669448853,
"start": 490,
"tag": "NAME",
"value": "Aphelandra longiflora"
},
{
"context": "un\"}\n {:scientificName \"Vicia faba\" :latitude \"30.3\" :longitude \"8.9\" :locality \"\"}]",
"end": 627,
"score": 0.9998486638069153,
"start": 617,
"tag": "NAME",
"value": "Vicia faba"
},
{
"context": "t \"Can write csv\"\n (write-csv [{:scientificName \"Foo\" :locality \"Riverrun\" }\n {:scientifi",
"end": 819,
"score": 0.9544396996498108,
"start": 816,
"tag": "NAME",
"value": "Foo"
}
] | test/dwc_io/csv_test.clj | biodivdev/dwc | 0 | (ns dwc-io.csv-test
(:use midje.sweet)
(:use dwc-io.csv))
(def test-file "resources/dwc.csv")
(def test-file2 "resources/dwc2.csv")
(def test-file3 "resources/dwc3.csv")
(fact "Can read csv into hash-map"
(read-csv test-file) => [{:scientificName "Aphelandra longiflora" :latitude "10.10" :longitude "20.20" :locality "riverrun"}
{:scientificName "Vicia faba" :latitude "30.3" :longitude "8.9" :locality ""}]
(read-csv test-file2) => [{:scientificName "Aphelandra longiflora" :latitude "10.10" :longitude "20.20" :locality "riverrun"}
{:scientificName "Vicia faba" :latitude "30.3" :longitude "8.9" :locality ""}]
(:collectionID (last (read-csv test-file3))) => "urn:lsid:biocol.org:col:15528")
(fact "Can write csv"
(write-csv [{:scientificName "Foo" :locality "Riverrun" }
{:scientificName "Bar" :id 1 :habitat "test" :decimalLongitude 20.20 :decimalLatitude 10.10}
{:scientificName "\"err\"" :foo "bar" }
])
=> (str "\"scientificName\",\"locality\",\"id\",\"habitat\",\"decimalLongitude\",\"decimalLatitude\",\"foo\"\n"
"\"Foo\",\"Riverrun\",\"\",\"\",\"\",\"\",\"\"\n"
"\"Bar\",\"\",\"1\",\"test\",\"20.2\",\"10.1\",\"\"\n\"'err'\",\"\",\"\",\"\",\"\",\"\",\"bar\""))
| 45040 | (ns dwc-io.csv-test
(:use midje.sweet)
(:use dwc-io.csv))
(def test-file "resources/dwc.csv")
(def test-file2 "resources/dwc2.csv")
(def test-file3 "resources/dwc3.csv")
(fact "Can read csv into hash-map"
(read-csv test-file) => [{:scientificName "<NAME>" :latitude "10.10" :longitude "20.20" :locality "riverrun"}
{:scientificName "<NAME>" :latitude "30.3" :longitude "8.9" :locality ""}]
(read-csv test-file2) => [{:scientificName "<NAME>" :latitude "10.10" :longitude "20.20" :locality "riverrun"}
{:scientificName "<NAME>" :latitude "30.3" :longitude "8.9" :locality ""}]
(:collectionID (last (read-csv test-file3))) => "urn:lsid:biocol.org:col:15528")
(fact "Can write csv"
(write-csv [{:scientificName "<NAME>" :locality "Riverrun" }
{:scientificName "Bar" :id 1 :habitat "test" :decimalLongitude 20.20 :decimalLatitude 10.10}
{:scientificName "\"err\"" :foo "bar" }
])
=> (str "\"scientificName\",\"locality\",\"id\",\"habitat\",\"decimalLongitude\",\"decimalLatitude\",\"foo\"\n"
"\"Foo\",\"Riverrun\",\"\",\"\",\"\",\"\",\"\"\n"
"\"Bar\",\"\",\"1\",\"test\",\"20.2\",\"10.1\",\"\"\n\"'err'\",\"\",\"\",\"\",\"\",\"\",\"bar\""))
| true | (ns dwc-io.csv-test
(:use midje.sweet)
(:use dwc-io.csv))
(def test-file "resources/dwc.csv")
(def test-file2 "resources/dwc2.csv")
(def test-file3 "resources/dwc3.csv")
(fact "Can read csv into hash-map"
(read-csv test-file) => [{:scientificName "PI:NAME:<NAME>END_PI" :latitude "10.10" :longitude "20.20" :locality "riverrun"}
{:scientificName "PI:NAME:<NAME>END_PI" :latitude "30.3" :longitude "8.9" :locality ""}]
(read-csv test-file2) => [{:scientificName "PI:NAME:<NAME>END_PI" :latitude "10.10" :longitude "20.20" :locality "riverrun"}
{:scientificName "PI:NAME:<NAME>END_PI" :latitude "30.3" :longitude "8.9" :locality ""}]
(:collectionID (last (read-csv test-file3))) => "urn:lsid:biocol.org:col:15528")
(fact "Can write csv"
(write-csv [{:scientificName "PI:NAME:<NAME>END_PI" :locality "Riverrun" }
{:scientificName "Bar" :id 1 :habitat "test" :decimalLongitude 20.20 :decimalLatitude 10.10}
{:scientificName "\"err\"" :foo "bar" }
])
=> (str "\"scientificName\",\"locality\",\"id\",\"habitat\",\"decimalLongitude\",\"decimalLatitude\",\"foo\"\n"
"\"Foo\",\"Riverrun\",\"\",\"\",\"\",\"\",\"\"\n"
"\"Bar\",\"\",\"1\",\"test\",\"20.2\",\"10.1\",\"\"\n\"'err'\",\"\",\"\",\"\",\"\",\"\",\"bar\""))
|
[
{
"context": "(ns hello-seymore.core)\n\n(.log js/console \"Hey Seymore Mert3\")\n\n",
"end": 60,
"score": 0.9277136921882629,
"start": 47,
"tag": "NAME",
"value": "Seymore Mert3"
}
] | clj/ex/study_figwheel/hello_seymore/src/hello_seymore/core.cljs | mertnuhoglu/study | 1 | (ns hello-seymore.core)
(.log js/console "Hey Seymore Mert3")
| 21069 | (ns hello-seymore.core)
(.log js/console "Hey <NAME>")
| true | (ns hello-seymore.core)
(.log js/console "Hey PI:NAME:<NAME>END_PI")
|
[
{
"context": "(ns ^{:author \"Ikenna Nwaiwu\"} memjore.views.addmember\n (:require [memjore.vi",
"end": 28,
"score": 0.9998763203620911,
"start": 15,
"tag": "NAME",
"value": "Ikenna Nwaiwu"
}
] | data/train/clojure/7d024d126d4ee7c610f481afccbda9f5e72ccf1daddmember.clj | harshp8l/deep-learning-lang-detection | 84 | (ns ^{:author "Ikenna Nwaiwu"} memjore.views.addmember
(:require [memjore.views.common :as common])
(:use [noir.core :only [defpage defpartial render url-for pre-route]]
[memjore.models.db :as db]
[noir.response :only [redirect]]
[hiccup.form :only [form-to]]))
(defpage addmember [:get "/manage/members/add"] {:keys [error] :as req}
(common/layout
[:h2 "Add Member"]
(form-to [:post "/manage/members/add"]
(common/user-fields req))))
(defpage addmember-handler [:post "/manage/members/add"] {:as req}
(let [result (db/add-member req)]
(if (successful-update? result)
(redirect "/manage/members")
(addmember (merge result req))))) | 112753 | (ns ^{:author "<NAME>"} memjore.views.addmember
(:require [memjore.views.common :as common])
(:use [noir.core :only [defpage defpartial render url-for pre-route]]
[memjore.models.db :as db]
[noir.response :only [redirect]]
[hiccup.form :only [form-to]]))
(defpage addmember [:get "/manage/members/add"] {:keys [error] :as req}
(common/layout
[:h2 "Add Member"]
(form-to [:post "/manage/members/add"]
(common/user-fields req))))
(defpage addmember-handler [:post "/manage/members/add"] {:as req}
(let [result (db/add-member req)]
(if (successful-update? result)
(redirect "/manage/members")
(addmember (merge result req))))) | true | (ns ^{:author "PI:NAME:<NAME>END_PI"} memjore.views.addmember
(:require [memjore.views.common :as common])
(:use [noir.core :only [defpage defpartial render url-for pre-route]]
[memjore.models.db :as db]
[noir.response :only [redirect]]
[hiccup.form :only [form-to]]))
(defpage addmember [:get "/manage/members/add"] {:keys [error] :as req}
(common/layout
[:h2 "Add Member"]
(form-to [:post "/manage/members/add"]
(common/user-fields req))))
(defpage addmember-handler [:post "/manage/members/add"] {:as req}
(let [result (db/add-member req)]
(if (successful-update? result)
(redirect "/manage/members")
(addmember (merge result req))))) |
[
{
"context": " :password (System/getenv \"CLOJARS_PASS\")}])))\n\n(require\n '[orchestra.spec.test ",
"end": 1377,
"score": 0.6660771369934082,
"start": 1373,
"tag": "PASSWORD",
"value": "CLOJ"
},
{
"context": " :password (System/getenv \"CLOJARS_PASS\")}])))\n\n(require\n '[orchestra.spec.test :refer [",
"end": 1385,
"score": 0.5371652245521545,
"start": 1381,
"tag": "PASSWORD",
"value": "PASS"
},
{
"context": "ript\"\n \"Url\" \"https://github.com/oakes/Nightcode\"}\n :file \"project.jar\"})\n\n(deftas",
"end": 2032,
"score": 0.9994852542877197,
"start": 2027,
"tag": "USERNAME",
"value": "oakes"
}
] | build.boot | based2/Nightcode | 0 | (defn read-deps-edn [aliases-to-include]
(let [{:keys [paths deps aliases]} (-> "deps.edn" slurp clojure.edn/read-string)
deps (->> (select-keys aliases aliases-to-include)
vals
(mapcat :extra-deps)
(into deps)
(reduce
(fn [deps [artifact info]]
(if-let [version (:mvn/version info)]
(conj deps
(transduce cat conj [artifact version]
(select-keys info [:scope :exclusions])))
deps))
[]))]
{:dependencies deps
:source-paths (set paths)
:resource-paths (set paths)}))
(let [{:keys [source-paths resource-paths dependencies]} (read-deps-edn [])]
(set-env!
:source-paths source-paths
:resource-paths resource-paths
:dependencies (into '[[adzerk/boot-cljs "2.1.4" :scope "test"]
[javax.xml.bind/jaxb-api "2.3.0" :scope "test"]
[orchestra "2017.11.12-1" :scope "test"]]
dependencies)
:repositories (conj (get-env :repositories)
["clojars" {:url "https://clojars.org/repo/"
:username (System/getenv "CLOJARS_USER")
:password (System/getenv "CLOJARS_PASS")}])))
(require
'[orchestra.spec.test :refer [instrument]]
'[adzerk.boot-cljs :refer [cljs]]
'[clojure.java.io :as io])
(task-options!
sift {:include #{#"project.jar$"}}
pom {:project 'nightcode
:version "2.6.1-SNAPSHOT"
:description "An IDE for Clojure"
:url "https://github.com/oakes/Nightcode"
:license {"Public Domain" "http://unlicense.org/UNLICENSE"}}
push {:repo "clojars"}
aot {:namespace '#{nightcode.core
nightcode.lein}}
jar {:main 'nightcode.core
:manifest {"Description" "An IDE for Clojure and ClojureScript"
"Url" "https://github.com/oakes/Nightcode"}
:file "project.jar"})
(deftask run []
(comp
(aot)
(with-pass-thru _
(require '[nightcode.core :refer [dev-main]])
(instrument)
((resolve 'dev-main)))))
(def jar-exclusions
(conj boot.pod/standard-jar-exclusions
;; the standard exclusions don't work on windows,
;; because we need to use backslashes
#"(?i)^META-INF\\[^\\]*\.(MF|SF|RSA|DSA)$"
#"(?i)^META-INF\\INDEX.LIST$"
;; exclude soundfont file from edna
#".*\.sf2$"))
(deftask build []
(comp (aot) (pom) (uber :exclude jar-exclusions) (jar) (sift) (target)))
(deftask build-cljs []
(set-env!
:resource-paths #(conj % "dev-resources")
:dependencies #(into (set %) (:dependencies (read-deps-edn [:cljs]))))
(comp
(cljs :optimizations :advanced)
(target)
(with-pass-thru _
(io/copy (io/file "target/public/paren-soup.js") (io/file "resources/public/paren-soup.js"))
(io/copy (io/file "target/public/codemirror.js") (io/file "resources/public/codemirror.js")))))
(deftask local []
(comp (pom) (jar) (install)))
(deftask deploy []
(comp (pom) (jar) (push)))
| 86116 | (defn read-deps-edn [aliases-to-include]
(let [{:keys [paths deps aliases]} (-> "deps.edn" slurp clojure.edn/read-string)
deps (->> (select-keys aliases aliases-to-include)
vals
(mapcat :extra-deps)
(into deps)
(reduce
(fn [deps [artifact info]]
(if-let [version (:mvn/version info)]
(conj deps
(transduce cat conj [artifact version]
(select-keys info [:scope :exclusions])))
deps))
[]))]
{:dependencies deps
:source-paths (set paths)
:resource-paths (set paths)}))
(let [{:keys [source-paths resource-paths dependencies]} (read-deps-edn [])]
(set-env!
:source-paths source-paths
:resource-paths resource-paths
:dependencies (into '[[adzerk/boot-cljs "2.1.4" :scope "test"]
[javax.xml.bind/jaxb-api "2.3.0" :scope "test"]
[orchestra "2017.11.12-1" :scope "test"]]
dependencies)
:repositories (conj (get-env :repositories)
["clojars" {:url "https://clojars.org/repo/"
:username (System/getenv "CLOJARS_USER")
:password (System/getenv "<PASSWORD>ARS_<PASSWORD>")}])))
(require
'[orchestra.spec.test :refer [instrument]]
'[adzerk.boot-cljs :refer [cljs]]
'[clojure.java.io :as io])
(task-options!
sift {:include #{#"project.jar$"}}
pom {:project 'nightcode
:version "2.6.1-SNAPSHOT"
:description "An IDE for Clojure"
:url "https://github.com/oakes/Nightcode"
:license {"Public Domain" "http://unlicense.org/UNLICENSE"}}
push {:repo "clojars"}
aot {:namespace '#{nightcode.core
nightcode.lein}}
jar {:main 'nightcode.core
:manifest {"Description" "An IDE for Clojure and ClojureScript"
"Url" "https://github.com/oakes/Nightcode"}
:file "project.jar"})
(deftask run []
(comp
(aot)
(with-pass-thru _
(require '[nightcode.core :refer [dev-main]])
(instrument)
((resolve 'dev-main)))))
(def jar-exclusions
(conj boot.pod/standard-jar-exclusions
;; the standard exclusions don't work on windows,
;; because we need to use backslashes
#"(?i)^META-INF\\[^\\]*\.(MF|SF|RSA|DSA)$"
#"(?i)^META-INF\\INDEX.LIST$"
;; exclude soundfont file from edna
#".*\.sf2$"))
(deftask build []
(comp (aot) (pom) (uber :exclude jar-exclusions) (jar) (sift) (target)))
(deftask build-cljs []
(set-env!
:resource-paths #(conj % "dev-resources")
:dependencies #(into (set %) (:dependencies (read-deps-edn [:cljs]))))
(comp
(cljs :optimizations :advanced)
(target)
(with-pass-thru _
(io/copy (io/file "target/public/paren-soup.js") (io/file "resources/public/paren-soup.js"))
(io/copy (io/file "target/public/codemirror.js") (io/file "resources/public/codemirror.js")))))
(deftask local []
(comp (pom) (jar) (install)))
(deftask deploy []
(comp (pom) (jar) (push)))
| true | (defn read-deps-edn [aliases-to-include]
(let [{:keys [paths deps aliases]} (-> "deps.edn" slurp clojure.edn/read-string)
deps (->> (select-keys aliases aliases-to-include)
vals
(mapcat :extra-deps)
(into deps)
(reduce
(fn [deps [artifact info]]
(if-let [version (:mvn/version info)]
(conj deps
(transduce cat conj [artifact version]
(select-keys info [:scope :exclusions])))
deps))
[]))]
{:dependencies deps
:source-paths (set paths)
:resource-paths (set paths)}))
(let [{:keys [source-paths resource-paths dependencies]} (read-deps-edn [])]
(set-env!
:source-paths source-paths
:resource-paths resource-paths
:dependencies (into '[[adzerk/boot-cljs "2.1.4" :scope "test"]
[javax.xml.bind/jaxb-api "2.3.0" :scope "test"]
[orchestra "2017.11.12-1" :scope "test"]]
dependencies)
:repositories (conj (get-env :repositories)
["clojars" {:url "https://clojars.org/repo/"
:username (System/getenv "CLOJARS_USER")
:password (System/getenv "PI:PASSWORD:<PASSWORD>END_PIARS_PI:PASSWORD:<PASSWORD>END_PI")}])))
(require
'[orchestra.spec.test :refer [instrument]]
'[adzerk.boot-cljs :refer [cljs]]
'[clojure.java.io :as io])
(task-options!
sift {:include #{#"project.jar$"}}
pom {:project 'nightcode
:version "2.6.1-SNAPSHOT"
:description "An IDE for Clojure"
:url "https://github.com/oakes/Nightcode"
:license {"Public Domain" "http://unlicense.org/UNLICENSE"}}
push {:repo "clojars"}
aot {:namespace '#{nightcode.core
nightcode.lein}}
jar {:main 'nightcode.core
:manifest {"Description" "An IDE for Clojure and ClojureScript"
"Url" "https://github.com/oakes/Nightcode"}
:file "project.jar"})
(deftask run []
(comp
(aot)
(with-pass-thru _
(require '[nightcode.core :refer [dev-main]])
(instrument)
((resolve 'dev-main)))))
(def jar-exclusions
(conj boot.pod/standard-jar-exclusions
;; the standard exclusions don't work on windows,
;; because we need to use backslashes
#"(?i)^META-INF\\[^\\]*\.(MF|SF|RSA|DSA)$"
#"(?i)^META-INF\\INDEX.LIST$"
;; exclude soundfont file from edna
#".*\.sf2$"))
(deftask build []
(comp (aot) (pom) (uber :exclude jar-exclusions) (jar) (sift) (target)))
(deftask build-cljs []
(set-env!
:resource-paths #(conj % "dev-resources")
:dependencies #(into (set %) (:dependencies (read-deps-edn [:cljs]))))
(comp
(cljs :optimizations :advanced)
(target)
(with-pass-thru _
(io/copy (io/file "target/public/paren-soup.js") (io/file "resources/public/paren-soup.js"))
(io/copy (io/file "target/public/codemirror.js") (io/file "resources/public/codemirror.js")))))
(deftask local []
(comp (pom) (jar) (install)))
(deftask deploy []
(comp (pom) (jar) (push)))
|
[
{
"context": "tryTitle \"entry-title1\"})\n {:token \"mock-echo-system-token\"})]\n (testing \"ingest on PROV3, guest is not g",
"end": 2297,
"score": 0.5109575986862183,
"start": 2275,
"tag": "KEY",
"value": "mock-echo-system-token"
},
{
"context": " user1-token (echo-util/login (system/context) \"user1\")\n response (ingest/delete-concept con",
"end": 4516,
"score": 0.66748046875,
"start": 4511,
"tag": "USERNAME",
"value": "user1"
},
{
"context": "tryTitle \"entry-title1\"})\n {:token \"mock-echo-system-token\"})]\n (testing \"ingest of new concept\"\n ",
"end": 8560,
"score": 0.585002601146698,
"start": 8544,
"tag": "PASSWORD",
"value": "mock-echo-system"
},
{
"context": "yTitle \"entry-title1\"})\n {:token \"mock-echo-system-token\"})\n concept (subscription-util/make-subs",
"end": 16748,
"score": 0.7974390387535095,
"start": 16726,
"tag": "KEY",
"value": "mock-echo-system-token"
},
{
"context": "ser1-token (echo-util/login (system/context) \"user1\" [user1-group-id])\n _ (echo-util/ungran",
"end": 18255,
"score": 0.5518139600753784,
"start": 18254,
"tag": "USERNAME",
"value": "1"
},
{
"context": " {:token \"mock-echo-system-token\"})\n :items\n ",
"end": 18695,
"score": 0.6751213073730469,
"start": 18673,
"tag": "KEY",
"value": "mock-echo-system-token"
},
{
"context": " {:token \"mock-echo-system-token\"})\n :items\n ",
"end": 19254,
"score": 0.76264888048172,
"start": 19232,
"tag": "KEY",
"value": "mock-echo-system-token"
},
{
"context": " {:token \"mock-echo-system-token\"})\n coll2 (data-core/i",
"end": 21112,
"score": 0.5168028473854065,
"start": 21112,
"tag": "KEY",
"value": ""
},
{
"context": " :SubscriberId \"user1\"\n ",
"end": 21846,
"score": 0.9993801116943359,
"start": 21841,
"tag": "USERNAME",
"value": "user1"
},
{
"context": " :EmailAddress \"user1@nasa.gov\"\n ",
"end": 21931,
"score": 0.9998937249183655,
"start": 21917,
"tag": "EMAIL",
"value": "user1@nasa.gov"
},
{
"context": " :SubscriberId \"user1\"\n ",
"end": 22505,
"score": 0.9993869662284851,
"start": 22500,
"tag": "USERNAME",
"value": "user1"
},
{
"context": " :EmailAddress \"user1@nasa.gov\"\n ",
"end": 22590,
"score": 0.9999009966850281,
"start": 22576,
"tag": "EMAIL",
"value": "user1@nasa.gov"
},
{
"context": "ser-token (echo-util/login (system/context) \"admin-user\" [admin-group])]\n (echo-util/grant-all-s",
"end": 29265,
"score": 0.7177659273147583,
"start": 29265,
"tag": "USERNAME",
"value": ""
},
{
"context": "t [user1-token (echo-util/login (system/context) \"user1\")\n user2-token (echo-util/login (syste",
"end": 29788,
"score": 0.6808747053146362,
"start": 29783,
"tag": "USERNAME",
"value": "user1"
},
{
"context": "ser2-token (echo-util/login (system/context) \"user2\")\n coll1 (data-core/ingest-umm-spec-co",
"end": 29855,
"score": 0.6781392097473145,
"start": 29854,
"tag": "USERNAME",
"value": "2"
}
] | system-int-test/test/cmr/system_int_test/ingest/subscription_ingest_test.clj | jaybarra/Common-Metadata-Repository | 0 | (ns cmr.system-int-test.ingest.subscription-ingest-test
"CMR subscription ingest integration tests.
For subscription permissions tests, see `provider-ingest-permissions-test`."
(:require
[clojure.test :refer :all]
[cmr.access-control.test.util :as ac-util]
[cmr.common.util :refer [are3]]
[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.dev-system-util :as dev-sys-util]
[cmr.system-int-test.utils.index-util :as index]
[cmr.system-int-test.utils.ingest-util :as ingest]
[cmr.system-int-test.utils.metadata-db-util :as mdb]
[cmr.system-int-test.utils.subscription-util :as subscription-util]
[cmr.transmit.access-control :as access-control]
[cmr.transmit.config :as transmit-config]
[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])
(dev-sys-util/freeze-resume-time-fixture)
(subscription-util/grant-all-subscription-fixture {"provguid1" "PROV3"}
[:read]
[:read :update])]))
(defn- 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)
(map #(select-keys % [:concept-id :extra-fields :metadata])))]
(#'jobs/process-subscriptions (system/context) subscriptions)))
(deftest subscription-ingest-on-prov3-test
(let [coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})]
(testing "ingest on PROV3, guest is not granted ingest permission for SUBSCRIPTION_MANAGEMENT ACL"
(let [concept (subscription-util/make-subscription-concept {:provider-id "PROV3"
:CollectionConceptId (:concept-id coll1)})
guest-token (echo-util/login-guest (system/context))
response (ingest/ingest-concept concept {:token guest-token})]
(is (= ["You do not have permission to perform that action."] (:errors response)))))
(testing "ingest on PROV3, registered user is granted ingest permission for SUBSCRIPTION_MANAGEMENT ACL"
(let [concept (subscription-util/make-subscription-concept {:provider-id "PROV3"
:CollectionConceptId (:concept-id coll1)})
user1-token (echo-util/login (system/context) "user1")
response (ingest/ingest-concept concept {:token user1-token})]
(is (= 201 (:status response)))))))
(deftest subscription-delete-on-prov3-test
(let [coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})]
(testing "delete on PROV3, guest is not granted update permission for SUBSCRIPTION_MANAGEMENT ACL"
(let [concept (subscription-util/make-subscription-concept {:provider-id "PROV3"
:CollectionConceptId (:concept-id coll1)})
guest-token (echo-util/login-guest (system/context))
response (ingest/delete-concept concept {:token guest-token})]
(is (= ["You do not have permission to perform that action."] (:errors response)))))
(testing "delete on PROV3, registered user is granted update permission for SUBSCRIPTION_MANAGEMENT ACL"
(let [concept (subscription-util/make-subscription-concept {:provider-id "PROV3"
:CollectionConceptId (:concept-id coll1)})
user1-token (echo-util/login (system/context) "user1")
response (ingest/delete-concept concept {:token user1-token})]
;; it passes the permission validation, and gets to the point where the subscription doesn't exist
;; since we didn't ingest it.
(is (= 404 (:status response)))))))
(deftest subscription-ingest-test
(let [coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})]
(testing "ingest of a new subscription concept"
(let [concept (subscription-util/make-subscription-concept
{:CollectionConceptId (:concept-id coll1)})
{:keys [concept-id revision-id]} (ingest/ingest-concept concept)]
(is (mdb/concept-exists-in-mdb? concept-id revision-id))
(is (= 1 revision-id))))
(testing "ingest of a subscription concept with a revision id"
(let [concept (subscription-util/make-subscription-concept
{:CollectionConceptId (:concept-id coll1)}
{:revision-id 5})
{:keys [concept-id revision-id]} (ingest/ingest-concept concept)]
(is (= 5 revision-id))
(is (mdb/concept-exists-in-mdb? concept-id 5))))))
;; Verify that the accept header works
(deftest subscription-ingest-accept-header-response-test
(let [supplied-concept-id "SUB1000-PROV1"
coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})]
(testing "json response"
(let [response (ingest/ingest-concept
(subscription-util/make-subscription-concept
{:concept-id supplied-concept-id
:CollectionConceptId (:concept-id coll1)})
{:accept-format :json
:raw? true})]
(is (= {:revision-id 1
:concept-id supplied-concept-id}
(ingest/parse-ingest-body :json response)))))
(testing "xml response"
(let [response (ingest/ingest-concept
(subscription-util/make-subscription-concept
{:concept-id supplied-concept-id
:CollectionConceptId (:concept-id coll1)})
{:accept-format :xml
:raw? true})]
(is (= {:revision-id 2
:concept-id supplied-concept-id}
(ingest/parse-ingest-body :xml response)))))))
;; Verify that the accept header works with returned errors
(deftest subscription-ingest-with-errors-accept-header-test
(testing "json response"
(let [concept-no-metadata (assoc (subscription-util/make-subscription-concept)
:metadata "")
response (ingest/ingest-concept
concept-no-metadata
{:accept-format :json
:raw? true})
{:keys [errors]} (ingest/parse-ingest-body :json response)]
(is (re-find #"Request content is too short." (first errors)))))
(testing "xml response"
(let [concept-no-metadata (assoc (subscription-util/make-subscription-concept)
:metadata "")
response (ingest/ingest-concept
concept-no-metadata
{:accept-format :xml
:raw? true})
{:keys [errors]} (ingest/parse-ingest-body :xml response)]
(is (re-find #"Request content is too short." (first errors))))))
;; Verify that user-id is saved from User-Id or token header
(deftest subscription-ingest-user-id-test
(let [coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})]
(testing "ingest of new concept"
(are3 [ingest-headers expected-user-id]
(let [concept (subscription-util/make-subscription-concept {:CollectionConceptId (:concept-id coll1)})
{:keys [concept-id revision-id]} (ingest/ingest-concept concept ingest-headers)]
(ingest/assert-user-id concept-id revision-id expected-user-id))
"user id from token"
{:token (echo-util/login (system/context) "user1")} "user1"
"user id from user-id header"
{:user-id "user2"} "user2"
"both user-id and token in the header results in the revision getting user id from user-id header"
{:token (echo-util/login (system/context) "user3")
:user-id "user4"} "user4"
"neither user-id nor token in the header"
{} nil))
(testing "update of existing concept with new user-id"
(are3 [ingest-header1 expected-user-id1
ingest-header2 expected-user-id2
ingest-header3 expected-user-id3
ingest-header4 expected-user-id4]
(let [concept (subscription-util/make-subscription-concept {:CollectionConceptId (:concept-id coll1)})
{:keys [concept-id revision-id]} (ingest/ingest-concept concept ingest-header1)]
(ingest/ingest-concept concept ingest-header2)
(ingest/delete-concept concept ingest-header3)
(ingest/ingest-concept concept ingest-header4)
(ingest/assert-user-id concept-id revision-id expected-user-id1)
(ingest/assert-user-id concept-id (inc revision-id) expected-user-id2)
(ingest/assert-user-id concept-id (inc (inc revision-id)) expected-user-id3)
(ingest/assert-user-id concept-id (inc (inc (inc revision-id))) expected-user-id4))
"user id from token"
{:token (echo-util/login (system/context) "user1")} "user1"
{:token (echo-util/login (system/context) "user2")} "user2"
{:token (echo-util/login (system/context) "user3")} "user3"
{:token nil} nil
"user id from user-id header"
{:user-id "user1"} "user1"
{:user-id "user2"} "user2"
{:user-id "user3"} "user3"
{:user-id nil} nil))))
;; Subscription with concept-id ingest and update scenarios.
(deftest subscription-w-concept-id-ingest-test
(let [supplied-concept-id "SUB1000-PROV1"
coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})
metadata {:concept-id supplied-concept-id
:CollectionConceptId (:concept-id coll1)
:native-id "Atlantic-1"}
concept (subscription-util/make-subscription-concept metadata)]
(testing "ingest of a new subscription concept with concept-id present"
(let [{:keys [concept-id revision-id]} (ingest/ingest-concept concept)]
(is (mdb/concept-exists-in-mdb? concept-id revision-id))
(is (= [supplied-concept-id 1] [concept-id revision-id]))))
(testing "ingest of same native id and different providers is allowed"
(let [concept2-id "SUB1000-PROV2"
concept2 (subscription-util/make-subscription-concept
(assoc metadata :provider-id "PROV2"
:concept-id concept2-id))
{:keys [concept-id revision-id]} (ingest/ingest-concept concept2)]
(is (mdb/concept-exists-in-mdb? concept-id revision-id))
(is (= [concept2-id 1] [concept-id revision-id]))))
(testing "update the concept with the concept-id"
(let [{:keys [concept-id revision-id]} (ingest/ingest-concept concept)]
(is (= [supplied-concept-id 2] [concept-id revision-id]))))
(testing "update the concept without the concept-id"
(let [{:keys [concept-id revision-id]} (ingest/ingest-concept
(dissoc concept :concept-id))]
(is (= [supplied-concept-id 3] [concept-id revision-id]))))))
(deftest update-subscription-notification
(system/only-with-real-database
(let [_ (dev-sys-util/freeze-time! "2020-01-01T10:00:00Z")
coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})
supplied-concept-id "SUB1000-PROV1"
metadata {:concept-id supplied-concept-id
:CollectionConceptId (:concept-id coll1)
:native-id "Atlantic-1"}
concept (subscription-util/make-subscription-concept metadata)]
(subscription-util/ingest-subscription concept)
(testing "send an update event to an new subscription"
(let [resp (subscription-util/update-subscription-notification supplied-concept-id)]
(is (= 204 (:status resp))))
(let [resp (subscription-util/update-subscription-notification "-Fake-Id-")]
(is (= 404 (:status resp))))
(let [resp (subscription-util/update-subscription-notification "SUB8675309-foobar")]
(is (= 404 (:status resp))))))))
(deftest subscription-ingest-schema-validation-test
(testing "ingest of subscription concept JSON schema validation missing field"
(let [concept (subscription-util/make-subscription-concept {:SubscriberId ""})
{:keys [status errors]} (ingest/ingest-concept concept)]
(is (= 400 status))
(is (= ["#/SubscriberId: expected minLength: 1, actual: 0"]
errors))))
(testing "ingest of subscription concept JSON schema validation invalid field"
(let [concept (subscription-util/make-subscription-concept {:InvalidField "xxx"})
{:keys [status errors]} (ingest/ingest-concept concept)]
(is (= 400 status))
(is (= ["#: extraneous key [InvalidField] is not permitted"]
errors)))))
(deftest subscription-update-error-test
(let [supplied-concept-id "SUB1000-PROV1"
coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})
concept (subscription-util/make-subscription-concept
{:concept-id supplied-concept-id
:CollectionConceptId (:concept-id coll1)
:native-id "Atlantic-1"})
_ (ingest/ingest-concept concept)]
(testing "update concept with a different concept-id is invalid"
(let [{:keys [status errors]} (ingest/ingest-concept
(assoc concept :concept-id "SUB1111-PROV1"))]
(is (= [409 [(str "A concept with concept-id [SUB1000-PROV1] and "
"native-id [Atlantic-1] already exists for "
"concept-type [:subscription] provider-id [PROV1]. "
"The given concept-id [SUB1111-PROV1] and native-id "
"[Atlantic-1] would conflict with that one.")]]
[status errors]))))
(testing "update concept with a different native-id is invalid"
(let [{:keys [status errors]} (ingest/ingest-concept
(assoc concept :native-id "other"))]
(is (= [409 [(str "A concept with concept-id [SUB1000-PROV1] and "
"native-id [Atlantic-1] already exists for "
"concept-type [:subscription] provider-id [PROV1]. "
"The given concept-id [SUB1000-PROV1] and native-id "
"[other] would conflict with that one.")]]
[status errors]))))))
(deftest delete-subscription-ingest-test
(testing "delete a subscription"
(let [coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})
concept (subscription-util/make-subscription-concept {:CollectionConceptId (:concept-id coll1)})
_ (subscription-util/ingest-subscription concept)
{:keys [status concept-id revision-id]} (ingest/delete-concept concept)
fetched (mdb/get-concept concept-id revision-id)]
(is (= 200 status))
(is (= 2 revision-id))
(is (= (:native-id concept)
(:native-id fetched)))
(is (:deleted fetched))
(testing "delete a deleted subscription"
(let [{:keys [status errors]} (ingest/delete-concept concept)]
(is (= [status errors]
[404 [(format "Concept with native-id [%s] and concept-id [%s] is already deleted."
(:native-id concept) concept-id)]]))))
(testing "create a subscription over a subscription's tombstone"
(let [response (subscription-util/ingest-subscription
(subscription-util/make-subscription-concept {:CollectionConceptId (:concept-id coll1)}))
{:keys [status concept-id revision-id]} response]
(is (= 200 status))
(is (= 3 revision-id)))))))
(deftest subscription-email-processing
(testing "Tests subscriber-id filtering in subscription email processing job"
(system/only-with-real-database
(let [user1-group-id (echo-util/get-or-create-group (system/context) "group1")
;; User 1 is in group1
user1-token (echo-util/login (system/context) "user1" [user1-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/ungrant (system/context)
(-> (access-control/search-for-acls (system/context)
{:provider "PROV2"
:identity-type "catalog_item"}
{:token "mock-echo-system-token"})
:items
first
:concept_id))
_ (echo-util/grant (system/context)
[{:group_id user1-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}}})
_ (echo-util/grant (system/context)
[{:user_type :registered
:permissions [:read]}]
:catalog_item_identity
{:provider_id "PROV2"
:name "Provider collection/granule ACL registered users"
:collection_applicable true
:granule_applicable true
:granule_identifier {:access_value {:include_undefined_value true
:min_value 100 :max_value 200}}})
_ (ac-util/wait-until-indexed)
;; Setup collections
coll1 (data-core/ingest-umm-spec-collection "PROV1"
(data-umm-c/collection {:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})
coll2 (data-core/ingest-umm-spec-collection "PROV2"
(data-umm-c/collection {:ShortName "coll2"
:EntryTitle "entry-title2"})
{:token "mock-echo-system-token"})
_ (index/wait-until-indexed)
;; Setup subscriptions for each collection, for user1
_ (subscription-util/ingest-subscription (subscription-util/make-subscription-concept
{:Name "test_sub_prov1"
:SubscriberId "user1"
:EmailAddress "user1@nasa.gov"
:CollectionConceptId (:concept-id coll1)
:Query " "})
{:token "mock-echo-system-token"})
_ (subscription-util/ingest-subscription (subscription-util/make-subscription-concept
{:provider-id "PROV2"
:Name "test_sub_prov1"
:SubscriberId "user1"
:EmailAddress "user1@nasa.gov"
:CollectionConceptId (:concept-id coll2)
:Query " "})
{:token "mock-echo-system-token"})
_ (index/wait-until-indexed)
;; Setup granules, gran1 and gran3 with acl matched access-value
;; gran 2 does not match, and should not be readable by user1
gran1 (data-core/ingest "PROV1"
(data-granule/granule-with-umm-spec-collection coll1
(:concept-id coll1)
{:granule-ur "Granule1"
:access-value 33})
{:token "mock-echo-system-token"})
gran2 (data-core/ingest "PROV1"
(data-granule/granule-with-umm-spec-collection coll1
(:concept-id coll1)
{:granule-ur "Granule2"
:access-value 66})
{:token "mock-echo-system-token"})
gran3 (data-core/ingest "PROV2"
(data-granule/granule-with-umm-spec-collection coll2
(:concept-id coll2)
{:granule-ur "Granule3"
:access-value 133})
{:token "mock-echo-system-token"})
_ (index/wait-until-indexed)
expected (set [(:concept-id gran1) (:concept-id gran3)])
actual (->> (process-subscriptions)
(map #(nth % 1))
flatten
(map :concept-id)
set)]
(is (= expected actual))))))
(deftest roll-your-own-subscription-tests
;; Use cases coming from EarthData Search wanting to allow their users to create
;; subscriptions without the need to have any acls
(let [acls (ac-util/search-for-acls (transmit-config/echo-system-token)
{:identity-type "provider"
:provider "PROV1"
:target "INGEST_MANAGEMENT_ACL"})
_ (echo-util/ungrant (system/context) (:concept_id (first (:items acls))))
_ (ac-util/wait-until-indexed)
supplied-concept-id "SUB1000-PROV1"
user1-token (echo-util/login (system/context) "user1")
coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})
concept (subscription-util/make-subscription-concept {:concept-id supplied-concept-id
:CollectionConceptId (:concept-id coll1)
:SubscriberId "user1"
:native-id "Atlantic-1"})]
;; caes 1 test against guest token - no subscription
(testing "guest token - guests can not create subscriptions - passes"
(let [{:keys [status errors]} (ingest/ingest-concept concept)]
(is (= 401 status))
(is (= ["You do not have permission to perform that action."] errors))))
;; case 2 test on system token (ECHO token) - should pass
(testing "system token - admins can create subscriptions - passes"
(let [{:keys [status errors]} (ingest/ingest-concept concept {:token (transmit-config/echo-system-token)})]
(is (or (= 200 status) (= 201 status)))
(is (nil? errors))))
;; case 3 test account 1 which matches metadata data user - should pass
(testing "use an account which matches the metadata and does not have ACL - passes"
(let [{:keys [status errors]} (ingest/ingest-concept concept {:token user1-token})]
(is (= 200 status))
(is (nil? errors))))
;; case 4 test account 3 which does NOT match metadata user and account does not have prems
(testing "use an account which does not matches the metadata and does not have ACL - fails"
(let [user3-token (echo-util/login (system/context) "user3")
{:keys [status errors]} (ingest/ingest-concept concept {:token user3-token})]
(is (= 401 status))
(is (= ["You do not have permission to perform that action."] errors))))))
;; case 5 test account 2 which does NOT match metadata user and account has prems ; this should be MMT's use case
(deftest roll-your-own-subscription-and-have-acls-tests-with-acls
(testing "Use an account which does not match matches the metadata and DOES have an ACL"
(let [user2-token (echo-util/login (system/context) "user2")
supplied-concept-id "SUB1000-PROV1"
coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})
concept (subscription-util/make-subscription-concept {:concept-id supplied-concept-id
:SubscriberId "user1"
:CollectionConceptId (:concept-id coll1)
:native-id "Atlantic-1"})
{:keys [status errors]} (ingest/ingest-concept concept {:token user2-token})]
(is (= 201 status))
(is (nil? errors)))))
(deftest ingest-update-and-delete-subscription-as-subscriber
(testing "Tests updating and deleting subscriptions as subscriber"
(echo-util/ungrant-by-search (system/context)
{:provider "PROV1"
:target ["SUBSCRIPTION_MANAGEMENT" "INGEST_MANAGEMENT_ACL"]})
(ac-util/wait-until-indexed)
(let [admin-group (echo-util/get-or-create-group (system/context) "admin-group")
admin-user-token (echo-util/login (system/context) "admin-user" [admin-group])]
(echo-util/grant-all-subscription-group-sm (system/context)
"PROV1"
admin-group
[:read :update])
(echo-util/grant-groups-ingest (system/context)
"PROV1"
[admin-group])
(ac-util/wait-until-indexed)
(let [user1-token (echo-util/login (system/context) "user1")
user2-token (echo-util/login (system/context) "user2")
coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})
concept1-user1 (subscription-util/make-subscription-concept {:SubscriberId "user1"
:CollectionConceptId (:concept-id coll1)})
concept1-user2 (subscription-util/make-subscription-concept {:SubscriberId "user2"
:CollectionConceptId (:concept-id coll1)})
concept2 (subscription-util/make-subscription-concept {:SubscriberId "user1"
:native-id "new-concept"
:CollectionConceptId (:concept-id coll1)})
{:keys [concept-id revision-id status]} (ingest/ingest-concept concept1-user1 {:token user1-token})
concept1-user1 (merge {:concept-id concept-id} concept1-user1)
concept1-user2 (merge {:concept-id concept-id} concept1-user2)]
(is (= 201 status))
(are3 [ingest-api-call args expected-status expected-errors]
(let [{:keys [status errors]} (apply ingest-api-call args)]
(is (= expected-status status))
(is (= expected-errors errors)))
"Attempt to update subscription as user2"
ingest/ingest-concept [concept1-user2 {:token user2-token}] 401 ["You do not have permission to perform that action."]
"Attempt to delete subscription as user2"
ingest/delete-concept [concept1-user2 {:token user2-token}] 401 ["You do not have permission to perform that action."]
"Update subscription as user1"
ingest/ingest-concept [concept1-user1 {:token user1-token}] 200 nil
"Delete subscription as user1"
ingest/delete-concept [concept1-user1 {:token user1-token}] 200 nil
"Ingest subscription as admin"
ingest/ingest-concept [concept2 {:token admin-user-token}] 201 nil
"Update subscription as admin"
ingest/ingest-concept [concept2 {:token admin-user-token}] 200 nil
"Delete subscription as admin"
ingest/delete-concept [concept2 {:token admin-user-token}] 200 nil)))))
(deftest subscription-ingest-subscriber-collection-permission-check-test
(testing "Tests that the subscriber has permission to view the collection before allowing ingest"
(let [admin-group (echo-util/get-or-create-group (system/context) "admin-group")
group1 (echo-util/get-or-create-group (system/context) "group1")
admin-user-token (echo-util/login (system/context) "admin-user" [admin-group])
user-token (echo-util/login (system/context) "user1" [group1])
coll1 (data-core/ingest-umm-spec-collection "PROV1"
(data-umm-c/collection {:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})
fake-concept (subscription-util/make-subscription-concept {:SubscriberId "user1"
:CollectionConceptId "FAKE"})
concept (subscription-util/make-subscription-concept {:SubscriberId "user1"
:CollectionConceptId (:concept-id coll1)})]
;; adjust permissions
(echo-util/ungrant-by-search (system/context)
{:provider "PROV1"
:target ["SUBSCRIPTION_MANAGEMENT" "INGEST_MANAGEMENT_ACL"]})
(echo-util/ungrant-by-search (system/context)
{:provider "PROV1"
:identity-type "catalog_item"})
(echo-util/grant-all-subscription-group-sm (system/context)
"PROV1"
admin-group
[:read :update])
(echo-util/grant-groups-ingest (system/context)
"PROV1"
[admin-group])
(ac-util/wait-until-indexed)
(testing "non-existent collection concept-id"
(let [{:keys [status errors]} (ingest/ingest-concept fake-concept {:token "mock-echo-system-token"})]
(is (= 401 status))
(is (= [(format "Collection with concept id [FAKE] does not exist or subscriber-id [user1] does not have permission to view the collection.")]
errors))))
(testing "user doesn't have permission to view collection"
(are3 [ingest-api-call args expected-status expected-errors]
(let [{:keys [status errors]} (apply ingest-api-call args)]
(is (= expected-status status))
(is (= expected-errors errors)))
"Attempt to ingest subscription as user1"
ingest/ingest-concept [concept {:token user-token}] 401 [(format "Collection with concept id [%s] does not exist or subscriber-id [user1] does not have permission to view the collection." (:concept-id coll1))]
"Attempt to ingest subscription as admin-user"
ingest/ingest-concept [concept {:token admin-user-token}] 401 [(format "Collection with concept id [%s] does not exist or subscriber-id [user1] does not have permission to view the collection." (:concept-id coll1))]))
(echo-util/ungrant-by-search (system/context)
{:provider "PROV1"
:identity-type "catalog_item"})
(ac-util/create-acl "mock-echo-system-token"
{:group_permissions [{:group_id group1
:permissions ["read" "order"]}]
:catalog_item_identity {:name "coll1 ACL"
:provider_id "PROV1"
:collection_applicable true
:collection_identifier {:entry_titles [(:EntryTitle coll1)]}}})
(ac-util/wait-until-indexed)
(testing "user now has permission to view collection - by group-id"
(are3 [ingest-api-call args expected-status expected-errors]
(let [{:keys [status errors]} (apply ingest-api-call args)]
(is (= expected-status status))
(is (= expected-errors errors)))
"Ingest subscription as admin"
ingest/ingest-concept [concept {:token admin-user-token}] 201 nil
"Update subscription as admin"
ingest/ingest-concept [concept {:token admin-user-token}] 200 nil
"Delete subscription as admin"
ingest/delete-concept [concept {:token admin-user-token}] 200 nil
"Ingest subscription as user1"
ingest/ingest-concept [concept {:token user-token}] 200 nil
"Update subscription as user1"
ingest/ingest-concept [concept {:token user-token}] 200 nil
"Delete subscription as user1"
ingest/delete-concept [concept {:token user-token}] 200 nil))
(ac-util/create-acl "mock-echo-system-token"
{:group_permissions [{:user_type "registered"
:permissions ["read" "order"]}]
:catalog_item_identity {:name "coll1 ACL"
:provider_id "PROV1"
:collection_applicable true
:collection_identifier {:entry_titles [(:EntryTitle coll1)]}}})
(ac-util/wait-until-indexed)
(testing "user now has permission to view collection - by registered"
(are3 [ingest-api-call args expected-status expected-errors]
(let [{:keys [status errors]} (apply ingest-api-call args)]
(is (= expected-status status))
(is (= expected-errors errors)))
"Ingest subscription as admin"
ingest/ingest-concept [concept {:token admin-user-token}] 200 nil
"Update subscription as admin"
ingest/ingest-concept [concept {:token admin-user-token}] 200 nil
"Delete subscription as admin"
ingest/delete-concept [concept {:token admin-user-token}] 200 nil
"Ingest subscription as user1"
ingest/ingest-concept [concept {:token user-token}] 200 nil
"Update subscription as user1"
ingest/ingest-concept [concept {:token user-token}] 200 nil
"Delete subscription as user1"
ingest/delete-concept [concept {:token user-token}] 200 nil)))))
| 103169 | (ns cmr.system-int-test.ingest.subscription-ingest-test
"CMR subscription ingest integration tests.
For subscription permissions tests, see `provider-ingest-permissions-test`."
(:require
[clojure.test :refer :all]
[cmr.access-control.test.util :as ac-util]
[cmr.common.util :refer [are3]]
[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.dev-system-util :as dev-sys-util]
[cmr.system-int-test.utils.index-util :as index]
[cmr.system-int-test.utils.ingest-util :as ingest]
[cmr.system-int-test.utils.metadata-db-util :as mdb]
[cmr.system-int-test.utils.subscription-util :as subscription-util]
[cmr.transmit.access-control :as access-control]
[cmr.transmit.config :as transmit-config]
[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])
(dev-sys-util/freeze-resume-time-fixture)
(subscription-util/grant-all-subscription-fixture {"provguid1" "PROV3"}
[:read]
[:read :update])]))
(defn- 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)
(map #(select-keys % [:concept-id :extra-fields :metadata])))]
(#'jobs/process-subscriptions (system/context) subscriptions)))
(deftest subscription-ingest-on-prov3-test
(let [coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "<KEY>"})]
(testing "ingest on PROV3, guest is not granted ingest permission for SUBSCRIPTION_MANAGEMENT ACL"
(let [concept (subscription-util/make-subscription-concept {:provider-id "PROV3"
:CollectionConceptId (:concept-id coll1)})
guest-token (echo-util/login-guest (system/context))
response (ingest/ingest-concept concept {:token guest-token})]
(is (= ["You do not have permission to perform that action."] (:errors response)))))
(testing "ingest on PROV3, registered user is granted ingest permission for SUBSCRIPTION_MANAGEMENT ACL"
(let [concept (subscription-util/make-subscription-concept {:provider-id "PROV3"
:CollectionConceptId (:concept-id coll1)})
user1-token (echo-util/login (system/context) "user1")
response (ingest/ingest-concept concept {:token user1-token})]
(is (= 201 (:status response)))))))
(deftest subscription-delete-on-prov3-test
(let [coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})]
(testing "delete on PROV3, guest is not granted update permission for SUBSCRIPTION_MANAGEMENT ACL"
(let [concept (subscription-util/make-subscription-concept {:provider-id "PROV3"
:CollectionConceptId (:concept-id coll1)})
guest-token (echo-util/login-guest (system/context))
response (ingest/delete-concept concept {:token guest-token})]
(is (= ["You do not have permission to perform that action."] (:errors response)))))
(testing "delete on PROV3, registered user is granted update permission for SUBSCRIPTION_MANAGEMENT ACL"
(let [concept (subscription-util/make-subscription-concept {:provider-id "PROV3"
:CollectionConceptId (:concept-id coll1)})
user1-token (echo-util/login (system/context) "user1")
response (ingest/delete-concept concept {:token user1-token})]
;; it passes the permission validation, and gets to the point where the subscription doesn't exist
;; since we didn't ingest it.
(is (= 404 (:status response)))))))
(deftest subscription-ingest-test
(let [coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})]
(testing "ingest of a new subscription concept"
(let [concept (subscription-util/make-subscription-concept
{:CollectionConceptId (:concept-id coll1)})
{:keys [concept-id revision-id]} (ingest/ingest-concept concept)]
(is (mdb/concept-exists-in-mdb? concept-id revision-id))
(is (= 1 revision-id))))
(testing "ingest of a subscription concept with a revision id"
(let [concept (subscription-util/make-subscription-concept
{:CollectionConceptId (:concept-id coll1)}
{:revision-id 5})
{:keys [concept-id revision-id]} (ingest/ingest-concept concept)]
(is (= 5 revision-id))
(is (mdb/concept-exists-in-mdb? concept-id 5))))))
;; Verify that the accept header works
(deftest subscription-ingest-accept-header-response-test
(let [supplied-concept-id "SUB1000-PROV1"
coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})]
(testing "json response"
(let [response (ingest/ingest-concept
(subscription-util/make-subscription-concept
{:concept-id supplied-concept-id
:CollectionConceptId (:concept-id coll1)})
{:accept-format :json
:raw? true})]
(is (= {:revision-id 1
:concept-id supplied-concept-id}
(ingest/parse-ingest-body :json response)))))
(testing "xml response"
(let [response (ingest/ingest-concept
(subscription-util/make-subscription-concept
{:concept-id supplied-concept-id
:CollectionConceptId (:concept-id coll1)})
{:accept-format :xml
:raw? true})]
(is (= {:revision-id 2
:concept-id supplied-concept-id}
(ingest/parse-ingest-body :xml response)))))))
;; Verify that the accept header works with returned errors
(deftest subscription-ingest-with-errors-accept-header-test
(testing "json response"
(let [concept-no-metadata (assoc (subscription-util/make-subscription-concept)
:metadata "")
response (ingest/ingest-concept
concept-no-metadata
{:accept-format :json
:raw? true})
{:keys [errors]} (ingest/parse-ingest-body :json response)]
(is (re-find #"Request content is too short." (first errors)))))
(testing "xml response"
(let [concept-no-metadata (assoc (subscription-util/make-subscription-concept)
:metadata "")
response (ingest/ingest-concept
concept-no-metadata
{:accept-format :xml
:raw? true})
{:keys [errors]} (ingest/parse-ingest-body :xml response)]
(is (re-find #"Request content is too short." (first errors))))))
;; Verify that user-id is saved from User-Id or token header
(deftest subscription-ingest-user-id-test
(let [coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "<PASSWORD>-token"})]
(testing "ingest of new concept"
(are3 [ingest-headers expected-user-id]
(let [concept (subscription-util/make-subscription-concept {:CollectionConceptId (:concept-id coll1)})
{:keys [concept-id revision-id]} (ingest/ingest-concept concept ingest-headers)]
(ingest/assert-user-id concept-id revision-id expected-user-id))
"user id from token"
{:token (echo-util/login (system/context) "user1")} "user1"
"user id from user-id header"
{:user-id "user2"} "user2"
"both user-id and token in the header results in the revision getting user id from user-id header"
{:token (echo-util/login (system/context) "user3")
:user-id "user4"} "user4"
"neither user-id nor token in the header"
{} nil))
(testing "update of existing concept with new user-id"
(are3 [ingest-header1 expected-user-id1
ingest-header2 expected-user-id2
ingest-header3 expected-user-id3
ingest-header4 expected-user-id4]
(let [concept (subscription-util/make-subscription-concept {:CollectionConceptId (:concept-id coll1)})
{:keys [concept-id revision-id]} (ingest/ingest-concept concept ingest-header1)]
(ingest/ingest-concept concept ingest-header2)
(ingest/delete-concept concept ingest-header3)
(ingest/ingest-concept concept ingest-header4)
(ingest/assert-user-id concept-id revision-id expected-user-id1)
(ingest/assert-user-id concept-id (inc revision-id) expected-user-id2)
(ingest/assert-user-id concept-id (inc (inc revision-id)) expected-user-id3)
(ingest/assert-user-id concept-id (inc (inc (inc revision-id))) expected-user-id4))
"user id from token"
{:token (echo-util/login (system/context) "user1")} "user1"
{:token (echo-util/login (system/context) "user2")} "user2"
{:token (echo-util/login (system/context) "user3")} "user3"
{:token nil} nil
"user id from user-id header"
{:user-id "user1"} "user1"
{:user-id "user2"} "user2"
{:user-id "user3"} "user3"
{:user-id nil} nil))))
;; Subscription with concept-id ingest and update scenarios.
(deftest subscription-w-concept-id-ingest-test
(let [supplied-concept-id "SUB1000-PROV1"
coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})
metadata {:concept-id supplied-concept-id
:CollectionConceptId (:concept-id coll1)
:native-id "Atlantic-1"}
concept (subscription-util/make-subscription-concept metadata)]
(testing "ingest of a new subscription concept with concept-id present"
(let [{:keys [concept-id revision-id]} (ingest/ingest-concept concept)]
(is (mdb/concept-exists-in-mdb? concept-id revision-id))
(is (= [supplied-concept-id 1] [concept-id revision-id]))))
(testing "ingest of same native id and different providers is allowed"
(let [concept2-id "SUB1000-PROV2"
concept2 (subscription-util/make-subscription-concept
(assoc metadata :provider-id "PROV2"
:concept-id concept2-id))
{:keys [concept-id revision-id]} (ingest/ingest-concept concept2)]
(is (mdb/concept-exists-in-mdb? concept-id revision-id))
(is (= [concept2-id 1] [concept-id revision-id]))))
(testing "update the concept with the concept-id"
(let [{:keys [concept-id revision-id]} (ingest/ingest-concept concept)]
(is (= [supplied-concept-id 2] [concept-id revision-id]))))
(testing "update the concept without the concept-id"
(let [{:keys [concept-id revision-id]} (ingest/ingest-concept
(dissoc concept :concept-id))]
(is (= [supplied-concept-id 3] [concept-id revision-id]))))))
(deftest update-subscription-notification
(system/only-with-real-database
(let [_ (dev-sys-util/freeze-time! "2020-01-01T10:00:00Z")
coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})
supplied-concept-id "SUB1000-PROV1"
metadata {:concept-id supplied-concept-id
:CollectionConceptId (:concept-id coll1)
:native-id "Atlantic-1"}
concept (subscription-util/make-subscription-concept metadata)]
(subscription-util/ingest-subscription concept)
(testing "send an update event to an new subscription"
(let [resp (subscription-util/update-subscription-notification supplied-concept-id)]
(is (= 204 (:status resp))))
(let [resp (subscription-util/update-subscription-notification "-Fake-Id-")]
(is (= 404 (:status resp))))
(let [resp (subscription-util/update-subscription-notification "SUB8675309-foobar")]
(is (= 404 (:status resp))))))))
(deftest subscription-ingest-schema-validation-test
(testing "ingest of subscription concept JSON schema validation missing field"
(let [concept (subscription-util/make-subscription-concept {:SubscriberId ""})
{:keys [status errors]} (ingest/ingest-concept concept)]
(is (= 400 status))
(is (= ["#/SubscriberId: expected minLength: 1, actual: 0"]
errors))))
(testing "ingest of subscription concept JSON schema validation invalid field"
(let [concept (subscription-util/make-subscription-concept {:InvalidField "xxx"})
{:keys [status errors]} (ingest/ingest-concept concept)]
(is (= 400 status))
(is (= ["#: extraneous key [InvalidField] is not permitted"]
errors)))))
(deftest subscription-update-error-test
(let [supplied-concept-id "SUB1000-PROV1"
coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})
concept (subscription-util/make-subscription-concept
{:concept-id supplied-concept-id
:CollectionConceptId (:concept-id coll1)
:native-id "Atlantic-1"})
_ (ingest/ingest-concept concept)]
(testing "update concept with a different concept-id is invalid"
(let [{:keys [status errors]} (ingest/ingest-concept
(assoc concept :concept-id "SUB1111-PROV1"))]
(is (= [409 [(str "A concept with concept-id [SUB1000-PROV1] and "
"native-id [Atlantic-1] already exists for "
"concept-type [:subscription] provider-id [PROV1]. "
"The given concept-id [SUB1111-PROV1] and native-id "
"[Atlantic-1] would conflict with that one.")]]
[status errors]))))
(testing "update concept with a different native-id is invalid"
(let [{:keys [status errors]} (ingest/ingest-concept
(assoc concept :native-id "other"))]
(is (= [409 [(str "A concept with concept-id [SUB1000-PROV1] and "
"native-id [Atlantic-1] already exists for "
"concept-type [:subscription] provider-id [PROV1]. "
"The given concept-id [SUB1000-PROV1] and native-id "
"[other] would conflict with that one.")]]
[status errors]))))))
(deftest delete-subscription-ingest-test
(testing "delete a subscription"
(let [coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "<KEY>"})
concept (subscription-util/make-subscription-concept {:CollectionConceptId (:concept-id coll1)})
_ (subscription-util/ingest-subscription concept)
{:keys [status concept-id revision-id]} (ingest/delete-concept concept)
fetched (mdb/get-concept concept-id revision-id)]
(is (= 200 status))
(is (= 2 revision-id))
(is (= (:native-id concept)
(:native-id fetched)))
(is (:deleted fetched))
(testing "delete a deleted subscription"
(let [{:keys [status errors]} (ingest/delete-concept concept)]
(is (= [status errors]
[404 [(format "Concept with native-id [%s] and concept-id [%s] is already deleted."
(:native-id concept) concept-id)]]))))
(testing "create a subscription over a subscription's tombstone"
(let [response (subscription-util/ingest-subscription
(subscription-util/make-subscription-concept {:CollectionConceptId (:concept-id coll1)}))
{:keys [status concept-id revision-id]} response]
(is (= 200 status))
(is (= 3 revision-id)))))))
(deftest subscription-email-processing
(testing "Tests subscriber-id filtering in subscription email processing job"
(system/only-with-real-database
(let [user1-group-id (echo-util/get-or-create-group (system/context) "group1")
;; User 1 is in group1
user1-token (echo-util/login (system/context) "user1" [user1-group-id])
_ (echo-util/ungrant (system/context)
(-> (access-control/search-for-acls (system/context)
{:provider "PROV1"
:identity-type "catalog_item"}
{:token "<KEY>"})
:items
first
:concept_id))
_ (echo-util/ungrant (system/context)
(-> (access-control/search-for-acls (system/context)
{:provider "PROV2"
:identity-type "catalog_item"}
{:token "<KEY>"})
:items
first
:concept_id))
_ (echo-util/grant (system/context)
[{:group_id user1-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}}})
_ (echo-util/grant (system/context)
[{:user_type :registered
:permissions [:read]}]
:catalog_item_identity
{:provider_id "PROV2"
:name "Provider collection/granule ACL registered users"
:collection_applicable true
:granule_applicable true
:granule_identifier {:access_value {:include_undefined_value true
:min_value 100 :max_value 200}}})
_ (ac-util/wait-until-indexed)
;; Setup collections
coll1 (data-core/ingest-umm-spec-collection "PROV1"
(data-umm-c/collection {:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock<KEY>-echo-system-token"})
coll2 (data-core/ingest-umm-spec-collection "PROV2"
(data-umm-c/collection {:ShortName "coll2"
:EntryTitle "entry-title2"})
{:token "mock-echo-system-token"})
_ (index/wait-until-indexed)
;; Setup subscriptions for each collection, for user1
_ (subscription-util/ingest-subscription (subscription-util/make-subscription-concept
{:Name "test_sub_prov1"
:SubscriberId "user1"
:EmailAddress "<EMAIL>"
:CollectionConceptId (:concept-id coll1)
:Query " "})
{:token "mock-echo-system-token"})
_ (subscription-util/ingest-subscription (subscription-util/make-subscription-concept
{:provider-id "PROV2"
:Name "test_sub_prov1"
:SubscriberId "user1"
:EmailAddress "<EMAIL>"
:CollectionConceptId (:concept-id coll2)
:Query " "})
{:token "mock-echo-system-token"})
_ (index/wait-until-indexed)
;; Setup granules, gran1 and gran3 with acl matched access-value
;; gran 2 does not match, and should not be readable by user1
gran1 (data-core/ingest "PROV1"
(data-granule/granule-with-umm-spec-collection coll1
(:concept-id coll1)
{:granule-ur "Granule1"
:access-value 33})
{:token "mock-echo-system-token"})
gran2 (data-core/ingest "PROV1"
(data-granule/granule-with-umm-spec-collection coll1
(:concept-id coll1)
{:granule-ur "Granule2"
:access-value 66})
{:token "mock-echo-system-token"})
gran3 (data-core/ingest "PROV2"
(data-granule/granule-with-umm-spec-collection coll2
(:concept-id coll2)
{:granule-ur "Granule3"
:access-value 133})
{:token "mock-echo-system-token"})
_ (index/wait-until-indexed)
expected (set [(:concept-id gran1) (:concept-id gran3)])
actual (->> (process-subscriptions)
(map #(nth % 1))
flatten
(map :concept-id)
set)]
(is (= expected actual))))))
(deftest roll-your-own-subscription-tests
;; Use cases coming from EarthData Search wanting to allow their users to create
;; subscriptions without the need to have any acls
(let [acls (ac-util/search-for-acls (transmit-config/echo-system-token)
{:identity-type "provider"
:provider "PROV1"
:target "INGEST_MANAGEMENT_ACL"})
_ (echo-util/ungrant (system/context) (:concept_id (first (:items acls))))
_ (ac-util/wait-until-indexed)
supplied-concept-id "SUB1000-PROV1"
user1-token (echo-util/login (system/context) "user1")
coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})
concept (subscription-util/make-subscription-concept {:concept-id supplied-concept-id
:CollectionConceptId (:concept-id coll1)
:SubscriberId "user1"
:native-id "Atlantic-1"})]
;; caes 1 test against guest token - no subscription
(testing "guest token - guests can not create subscriptions - passes"
(let [{:keys [status errors]} (ingest/ingest-concept concept)]
(is (= 401 status))
(is (= ["You do not have permission to perform that action."] errors))))
;; case 2 test on system token (ECHO token) - should pass
(testing "system token - admins can create subscriptions - passes"
(let [{:keys [status errors]} (ingest/ingest-concept concept {:token (transmit-config/echo-system-token)})]
(is (or (= 200 status) (= 201 status)))
(is (nil? errors))))
;; case 3 test account 1 which matches metadata data user - should pass
(testing "use an account which matches the metadata and does not have ACL - passes"
(let [{:keys [status errors]} (ingest/ingest-concept concept {:token user1-token})]
(is (= 200 status))
(is (nil? errors))))
;; case 4 test account 3 which does NOT match metadata user and account does not have prems
(testing "use an account which does not matches the metadata and does not have ACL - fails"
(let [user3-token (echo-util/login (system/context) "user3")
{:keys [status errors]} (ingest/ingest-concept concept {:token user3-token})]
(is (= 401 status))
(is (= ["You do not have permission to perform that action."] errors))))))
;; case 5 test account 2 which does NOT match metadata user and account has prems ; this should be MMT's use case
(deftest roll-your-own-subscription-and-have-acls-tests-with-acls
(testing "Use an account which does not match matches the metadata and DOES have an ACL"
(let [user2-token (echo-util/login (system/context) "user2")
supplied-concept-id "SUB1000-PROV1"
coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})
concept (subscription-util/make-subscription-concept {:concept-id supplied-concept-id
:SubscriberId "user1"
:CollectionConceptId (:concept-id coll1)
:native-id "Atlantic-1"})
{:keys [status errors]} (ingest/ingest-concept concept {:token user2-token})]
(is (= 201 status))
(is (nil? errors)))))
(deftest ingest-update-and-delete-subscription-as-subscriber
(testing "Tests updating and deleting subscriptions as subscriber"
(echo-util/ungrant-by-search (system/context)
{:provider "PROV1"
:target ["SUBSCRIPTION_MANAGEMENT" "INGEST_MANAGEMENT_ACL"]})
(ac-util/wait-until-indexed)
(let [admin-group (echo-util/get-or-create-group (system/context) "admin-group")
admin-user-token (echo-util/login (system/context) "admin-user" [admin-group])]
(echo-util/grant-all-subscription-group-sm (system/context)
"PROV1"
admin-group
[:read :update])
(echo-util/grant-groups-ingest (system/context)
"PROV1"
[admin-group])
(ac-util/wait-until-indexed)
(let [user1-token (echo-util/login (system/context) "user1")
user2-token (echo-util/login (system/context) "user2")
coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})
concept1-user1 (subscription-util/make-subscription-concept {:SubscriberId "user1"
:CollectionConceptId (:concept-id coll1)})
concept1-user2 (subscription-util/make-subscription-concept {:SubscriberId "user2"
:CollectionConceptId (:concept-id coll1)})
concept2 (subscription-util/make-subscription-concept {:SubscriberId "user1"
:native-id "new-concept"
:CollectionConceptId (:concept-id coll1)})
{:keys [concept-id revision-id status]} (ingest/ingest-concept concept1-user1 {:token user1-token})
concept1-user1 (merge {:concept-id concept-id} concept1-user1)
concept1-user2 (merge {:concept-id concept-id} concept1-user2)]
(is (= 201 status))
(are3 [ingest-api-call args expected-status expected-errors]
(let [{:keys [status errors]} (apply ingest-api-call args)]
(is (= expected-status status))
(is (= expected-errors errors)))
"Attempt to update subscription as user2"
ingest/ingest-concept [concept1-user2 {:token user2-token}] 401 ["You do not have permission to perform that action."]
"Attempt to delete subscription as user2"
ingest/delete-concept [concept1-user2 {:token user2-token}] 401 ["You do not have permission to perform that action."]
"Update subscription as user1"
ingest/ingest-concept [concept1-user1 {:token user1-token}] 200 nil
"Delete subscription as user1"
ingest/delete-concept [concept1-user1 {:token user1-token}] 200 nil
"Ingest subscription as admin"
ingest/ingest-concept [concept2 {:token admin-user-token}] 201 nil
"Update subscription as admin"
ingest/ingest-concept [concept2 {:token admin-user-token}] 200 nil
"Delete subscription as admin"
ingest/delete-concept [concept2 {:token admin-user-token}] 200 nil)))))
(deftest subscription-ingest-subscriber-collection-permission-check-test
(testing "Tests that the subscriber has permission to view the collection before allowing ingest"
(let [admin-group (echo-util/get-or-create-group (system/context) "admin-group")
group1 (echo-util/get-or-create-group (system/context) "group1")
admin-user-token (echo-util/login (system/context) "admin-user" [admin-group])
user-token (echo-util/login (system/context) "user1" [group1])
coll1 (data-core/ingest-umm-spec-collection "PROV1"
(data-umm-c/collection {:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})
fake-concept (subscription-util/make-subscription-concept {:SubscriberId "user1"
:CollectionConceptId "FAKE"})
concept (subscription-util/make-subscription-concept {:SubscriberId "user1"
:CollectionConceptId (:concept-id coll1)})]
;; adjust permissions
(echo-util/ungrant-by-search (system/context)
{:provider "PROV1"
:target ["SUBSCRIPTION_MANAGEMENT" "INGEST_MANAGEMENT_ACL"]})
(echo-util/ungrant-by-search (system/context)
{:provider "PROV1"
:identity-type "catalog_item"})
(echo-util/grant-all-subscription-group-sm (system/context)
"PROV1"
admin-group
[:read :update])
(echo-util/grant-groups-ingest (system/context)
"PROV1"
[admin-group])
(ac-util/wait-until-indexed)
(testing "non-existent collection concept-id"
(let [{:keys [status errors]} (ingest/ingest-concept fake-concept {:token "mock-echo-system-token"})]
(is (= 401 status))
(is (= [(format "Collection with concept id [FAKE] does not exist or subscriber-id [user1] does not have permission to view the collection.")]
errors))))
(testing "user doesn't have permission to view collection"
(are3 [ingest-api-call args expected-status expected-errors]
(let [{:keys [status errors]} (apply ingest-api-call args)]
(is (= expected-status status))
(is (= expected-errors errors)))
"Attempt to ingest subscription as user1"
ingest/ingest-concept [concept {:token user-token}] 401 [(format "Collection with concept id [%s] does not exist or subscriber-id [user1] does not have permission to view the collection." (:concept-id coll1))]
"Attempt to ingest subscription as admin-user"
ingest/ingest-concept [concept {:token admin-user-token}] 401 [(format "Collection with concept id [%s] does not exist or subscriber-id [user1] does not have permission to view the collection." (:concept-id coll1))]))
(echo-util/ungrant-by-search (system/context)
{:provider "PROV1"
:identity-type "catalog_item"})
(ac-util/create-acl "mock-echo-system-token"
{:group_permissions [{:group_id group1
:permissions ["read" "order"]}]
:catalog_item_identity {:name "coll1 ACL"
:provider_id "PROV1"
:collection_applicable true
:collection_identifier {:entry_titles [(:EntryTitle coll1)]}}})
(ac-util/wait-until-indexed)
(testing "user now has permission to view collection - by group-id"
(are3 [ingest-api-call args expected-status expected-errors]
(let [{:keys [status errors]} (apply ingest-api-call args)]
(is (= expected-status status))
(is (= expected-errors errors)))
"Ingest subscription as admin"
ingest/ingest-concept [concept {:token admin-user-token}] 201 nil
"Update subscription as admin"
ingest/ingest-concept [concept {:token admin-user-token}] 200 nil
"Delete subscription as admin"
ingest/delete-concept [concept {:token admin-user-token}] 200 nil
"Ingest subscription as user1"
ingest/ingest-concept [concept {:token user-token}] 200 nil
"Update subscription as user1"
ingest/ingest-concept [concept {:token user-token}] 200 nil
"Delete subscription as user1"
ingest/delete-concept [concept {:token user-token}] 200 nil))
(ac-util/create-acl "mock-echo-system-token"
{:group_permissions [{:user_type "registered"
:permissions ["read" "order"]}]
:catalog_item_identity {:name "coll1 ACL"
:provider_id "PROV1"
:collection_applicable true
:collection_identifier {:entry_titles [(:EntryTitle coll1)]}}})
(ac-util/wait-until-indexed)
(testing "user now has permission to view collection - by registered"
(are3 [ingest-api-call args expected-status expected-errors]
(let [{:keys [status errors]} (apply ingest-api-call args)]
(is (= expected-status status))
(is (= expected-errors errors)))
"Ingest subscription as admin"
ingest/ingest-concept [concept {:token admin-user-token}] 200 nil
"Update subscription as admin"
ingest/ingest-concept [concept {:token admin-user-token}] 200 nil
"Delete subscription as admin"
ingest/delete-concept [concept {:token admin-user-token}] 200 nil
"Ingest subscription as user1"
ingest/ingest-concept [concept {:token user-token}] 200 nil
"Update subscription as user1"
ingest/ingest-concept [concept {:token user-token}] 200 nil
"Delete subscription as user1"
ingest/delete-concept [concept {:token user-token}] 200 nil)))))
| true | (ns cmr.system-int-test.ingest.subscription-ingest-test
"CMR subscription ingest integration tests.
For subscription permissions tests, see `provider-ingest-permissions-test`."
(:require
[clojure.test :refer :all]
[cmr.access-control.test.util :as ac-util]
[cmr.common.util :refer [are3]]
[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.dev-system-util :as dev-sys-util]
[cmr.system-int-test.utils.index-util :as index]
[cmr.system-int-test.utils.ingest-util :as ingest]
[cmr.system-int-test.utils.metadata-db-util :as mdb]
[cmr.system-int-test.utils.subscription-util :as subscription-util]
[cmr.transmit.access-control :as access-control]
[cmr.transmit.config :as transmit-config]
[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])
(dev-sys-util/freeze-resume-time-fixture)
(subscription-util/grant-all-subscription-fixture {"provguid1" "PROV3"}
[:read]
[:read :update])]))
(defn- 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)
(map #(select-keys % [:concept-id :extra-fields :metadata])))]
(#'jobs/process-subscriptions (system/context) subscriptions)))
(deftest subscription-ingest-on-prov3-test
(let [coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "PI:KEY:<KEY>END_PI"})]
(testing "ingest on PROV3, guest is not granted ingest permission for SUBSCRIPTION_MANAGEMENT ACL"
(let [concept (subscription-util/make-subscription-concept {:provider-id "PROV3"
:CollectionConceptId (:concept-id coll1)})
guest-token (echo-util/login-guest (system/context))
response (ingest/ingest-concept concept {:token guest-token})]
(is (= ["You do not have permission to perform that action."] (:errors response)))))
(testing "ingest on PROV3, registered user is granted ingest permission for SUBSCRIPTION_MANAGEMENT ACL"
(let [concept (subscription-util/make-subscription-concept {:provider-id "PROV3"
:CollectionConceptId (:concept-id coll1)})
user1-token (echo-util/login (system/context) "user1")
response (ingest/ingest-concept concept {:token user1-token})]
(is (= 201 (:status response)))))))
(deftest subscription-delete-on-prov3-test
(let [coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})]
(testing "delete on PROV3, guest is not granted update permission for SUBSCRIPTION_MANAGEMENT ACL"
(let [concept (subscription-util/make-subscription-concept {:provider-id "PROV3"
:CollectionConceptId (:concept-id coll1)})
guest-token (echo-util/login-guest (system/context))
response (ingest/delete-concept concept {:token guest-token})]
(is (= ["You do not have permission to perform that action."] (:errors response)))))
(testing "delete on PROV3, registered user is granted update permission for SUBSCRIPTION_MANAGEMENT ACL"
(let [concept (subscription-util/make-subscription-concept {:provider-id "PROV3"
:CollectionConceptId (:concept-id coll1)})
user1-token (echo-util/login (system/context) "user1")
response (ingest/delete-concept concept {:token user1-token})]
;; it passes the permission validation, and gets to the point where the subscription doesn't exist
;; since we didn't ingest it.
(is (= 404 (:status response)))))))
(deftest subscription-ingest-test
(let [coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})]
(testing "ingest of a new subscription concept"
(let [concept (subscription-util/make-subscription-concept
{:CollectionConceptId (:concept-id coll1)})
{:keys [concept-id revision-id]} (ingest/ingest-concept concept)]
(is (mdb/concept-exists-in-mdb? concept-id revision-id))
(is (= 1 revision-id))))
(testing "ingest of a subscription concept with a revision id"
(let [concept (subscription-util/make-subscription-concept
{:CollectionConceptId (:concept-id coll1)}
{:revision-id 5})
{:keys [concept-id revision-id]} (ingest/ingest-concept concept)]
(is (= 5 revision-id))
(is (mdb/concept-exists-in-mdb? concept-id 5))))))
;; Verify that the accept header works
(deftest subscription-ingest-accept-header-response-test
(let [supplied-concept-id "SUB1000-PROV1"
coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})]
(testing "json response"
(let [response (ingest/ingest-concept
(subscription-util/make-subscription-concept
{:concept-id supplied-concept-id
:CollectionConceptId (:concept-id coll1)})
{:accept-format :json
:raw? true})]
(is (= {:revision-id 1
:concept-id supplied-concept-id}
(ingest/parse-ingest-body :json response)))))
(testing "xml response"
(let [response (ingest/ingest-concept
(subscription-util/make-subscription-concept
{:concept-id supplied-concept-id
:CollectionConceptId (:concept-id coll1)})
{:accept-format :xml
:raw? true})]
(is (= {:revision-id 2
:concept-id supplied-concept-id}
(ingest/parse-ingest-body :xml response)))))))
;; Verify that the accept header works with returned errors
(deftest subscription-ingest-with-errors-accept-header-test
(testing "json response"
(let [concept-no-metadata (assoc (subscription-util/make-subscription-concept)
:metadata "")
response (ingest/ingest-concept
concept-no-metadata
{:accept-format :json
:raw? true})
{:keys [errors]} (ingest/parse-ingest-body :json response)]
(is (re-find #"Request content is too short." (first errors)))))
(testing "xml response"
(let [concept-no-metadata (assoc (subscription-util/make-subscription-concept)
:metadata "")
response (ingest/ingest-concept
concept-no-metadata
{:accept-format :xml
:raw? true})
{:keys [errors]} (ingest/parse-ingest-body :xml response)]
(is (re-find #"Request content is too short." (first errors))))))
;; Verify that user-id is saved from User-Id or token header
(deftest subscription-ingest-user-id-test
(let [coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "PI:PASSWORD:<PASSWORD>END_PI-token"})]
(testing "ingest of new concept"
(are3 [ingest-headers expected-user-id]
(let [concept (subscription-util/make-subscription-concept {:CollectionConceptId (:concept-id coll1)})
{:keys [concept-id revision-id]} (ingest/ingest-concept concept ingest-headers)]
(ingest/assert-user-id concept-id revision-id expected-user-id))
"user id from token"
{:token (echo-util/login (system/context) "user1")} "user1"
"user id from user-id header"
{:user-id "user2"} "user2"
"both user-id and token in the header results in the revision getting user id from user-id header"
{:token (echo-util/login (system/context) "user3")
:user-id "user4"} "user4"
"neither user-id nor token in the header"
{} nil))
(testing "update of existing concept with new user-id"
(are3 [ingest-header1 expected-user-id1
ingest-header2 expected-user-id2
ingest-header3 expected-user-id3
ingest-header4 expected-user-id4]
(let [concept (subscription-util/make-subscription-concept {:CollectionConceptId (:concept-id coll1)})
{:keys [concept-id revision-id]} (ingest/ingest-concept concept ingest-header1)]
(ingest/ingest-concept concept ingest-header2)
(ingest/delete-concept concept ingest-header3)
(ingest/ingest-concept concept ingest-header4)
(ingest/assert-user-id concept-id revision-id expected-user-id1)
(ingest/assert-user-id concept-id (inc revision-id) expected-user-id2)
(ingest/assert-user-id concept-id (inc (inc revision-id)) expected-user-id3)
(ingest/assert-user-id concept-id (inc (inc (inc revision-id))) expected-user-id4))
"user id from token"
{:token (echo-util/login (system/context) "user1")} "user1"
{:token (echo-util/login (system/context) "user2")} "user2"
{:token (echo-util/login (system/context) "user3")} "user3"
{:token nil} nil
"user id from user-id header"
{:user-id "user1"} "user1"
{:user-id "user2"} "user2"
{:user-id "user3"} "user3"
{:user-id nil} nil))))
;; Subscription with concept-id ingest and update scenarios.
(deftest subscription-w-concept-id-ingest-test
(let [supplied-concept-id "SUB1000-PROV1"
coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})
metadata {:concept-id supplied-concept-id
:CollectionConceptId (:concept-id coll1)
:native-id "Atlantic-1"}
concept (subscription-util/make-subscription-concept metadata)]
(testing "ingest of a new subscription concept with concept-id present"
(let [{:keys [concept-id revision-id]} (ingest/ingest-concept concept)]
(is (mdb/concept-exists-in-mdb? concept-id revision-id))
(is (= [supplied-concept-id 1] [concept-id revision-id]))))
(testing "ingest of same native id and different providers is allowed"
(let [concept2-id "SUB1000-PROV2"
concept2 (subscription-util/make-subscription-concept
(assoc metadata :provider-id "PROV2"
:concept-id concept2-id))
{:keys [concept-id revision-id]} (ingest/ingest-concept concept2)]
(is (mdb/concept-exists-in-mdb? concept-id revision-id))
(is (= [concept2-id 1] [concept-id revision-id]))))
(testing "update the concept with the concept-id"
(let [{:keys [concept-id revision-id]} (ingest/ingest-concept concept)]
(is (= [supplied-concept-id 2] [concept-id revision-id]))))
(testing "update the concept without the concept-id"
(let [{:keys [concept-id revision-id]} (ingest/ingest-concept
(dissoc concept :concept-id))]
(is (= [supplied-concept-id 3] [concept-id revision-id]))))))
(deftest update-subscription-notification
(system/only-with-real-database
(let [_ (dev-sys-util/freeze-time! "2020-01-01T10:00:00Z")
coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})
supplied-concept-id "SUB1000-PROV1"
metadata {:concept-id supplied-concept-id
:CollectionConceptId (:concept-id coll1)
:native-id "Atlantic-1"}
concept (subscription-util/make-subscription-concept metadata)]
(subscription-util/ingest-subscription concept)
(testing "send an update event to an new subscription"
(let [resp (subscription-util/update-subscription-notification supplied-concept-id)]
(is (= 204 (:status resp))))
(let [resp (subscription-util/update-subscription-notification "-Fake-Id-")]
(is (= 404 (:status resp))))
(let [resp (subscription-util/update-subscription-notification "SUB8675309-foobar")]
(is (= 404 (:status resp))))))))
(deftest subscription-ingest-schema-validation-test
(testing "ingest of subscription concept JSON schema validation missing field"
(let [concept (subscription-util/make-subscription-concept {:SubscriberId ""})
{:keys [status errors]} (ingest/ingest-concept concept)]
(is (= 400 status))
(is (= ["#/SubscriberId: expected minLength: 1, actual: 0"]
errors))))
(testing "ingest of subscription concept JSON schema validation invalid field"
(let [concept (subscription-util/make-subscription-concept {:InvalidField "xxx"})
{:keys [status errors]} (ingest/ingest-concept concept)]
(is (= 400 status))
(is (= ["#: extraneous key [InvalidField] is not permitted"]
errors)))))
(deftest subscription-update-error-test
(let [supplied-concept-id "SUB1000-PROV1"
coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})
concept (subscription-util/make-subscription-concept
{:concept-id supplied-concept-id
:CollectionConceptId (:concept-id coll1)
:native-id "Atlantic-1"})
_ (ingest/ingest-concept concept)]
(testing "update concept with a different concept-id is invalid"
(let [{:keys [status errors]} (ingest/ingest-concept
(assoc concept :concept-id "SUB1111-PROV1"))]
(is (= [409 [(str "A concept with concept-id [SUB1000-PROV1] and "
"native-id [Atlantic-1] already exists for "
"concept-type [:subscription] provider-id [PROV1]. "
"The given concept-id [SUB1111-PROV1] and native-id "
"[Atlantic-1] would conflict with that one.")]]
[status errors]))))
(testing "update concept with a different native-id is invalid"
(let [{:keys [status errors]} (ingest/ingest-concept
(assoc concept :native-id "other"))]
(is (= [409 [(str "A concept with concept-id [SUB1000-PROV1] and "
"native-id [Atlantic-1] already exists for "
"concept-type [:subscription] provider-id [PROV1]. "
"The given concept-id [SUB1000-PROV1] and native-id "
"[other] would conflict with that one.")]]
[status errors]))))))
(deftest delete-subscription-ingest-test
(testing "delete a subscription"
(let [coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "PI:KEY:<KEY>END_PI"})
concept (subscription-util/make-subscription-concept {:CollectionConceptId (:concept-id coll1)})
_ (subscription-util/ingest-subscription concept)
{:keys [status concept-id revision-id]} (ingest/delete-concept concept)
fetched (mdb/get-concept concept-id revision-id)]
(is (= 200 status))
(is (= 2 revision-id))
(is (= (:native-id concept)
(:native-id fetched)))
(is (:deleted fetched))
(testing "delete a deleted subscription"
(let [{:keys [status errors]} (ingest/delete-concept concept)]
(is (= [status errors]
[404 [(format "Concept with native-id [%s] and concept-id [%s] is already deleted."
(:native-id concept) concept-id)]]))))
(testing "create a subscription over a subscription's tombstone"
(let [response (subscription-util/ingest-subscription
(subscription-util/make-subscription-concept {:CollectionConceptId (:concept-id coll1)}))
{:keys [status concept-id revision-id]} response]
(is (= 200 status))
(is (= 3 revision-id)))))))
(deftest subscription-email-processing
(testing "Tests subscriber-id filtering in subscription email processing job"
(system/only-with-real-database
(let [user1-group-id (echo-util/get-or-create-group (system/context) "group1")
;; User 1 is in group1
user1-token (echo-util/login (system/context) "user1" [user1-group-id])
_ (echo-util/ungrant (system/context)
(-> (access-control/search-for-acls (system/context)
{:provider "PROV1"
:identity-type "catalog_item"}
{:token "PI:KEY:<KEY>END_PI"})
:items
first
:concept_id))
_ (echo-util/ungrant (system/context)
(-> (access-control/search-for-acls (system/context)
{:provider "PROV2"
:identity-type "catalog_item"}
{:token "PI:KEY:<KEY>END_PI"})
:items
first
:concept_id))
_ (echo-util/grant (system/context)
[{:group_id user1-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}}})
_ (echo-util/grant (system/context)
[{:user_type :registered
:permissions [:read]}]
:catalog_item_identity
{:provider_id "PROV2"
:name "Provider collection/granule ACL registered users"
:collection_applicable true
:granule_applicable true
:granule_identifier {:access_value {:include_undefined_value true
:min_value 100 :max_value 200}}})
_ (ac-util/wait-until-indexed)
;; Setup collections
coll1 (data-core/ingest-umm-spec-collection "PROV1"
(data-umm-c/collection {:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mockPI:KEY:<KEY>END_PI-echo-system-token"})
coll2 (data-core/ingest-umm-spec-collection "PROV2"
(data-umm-c/collection {:ShortName "coll2"
:EntryTitle "entry-title2"})
{:token "mock-echo-system-token"})
_ (index/wait-until-indexed)
;; Setup subscriptions for each collection, for user1
_ (subscription-util/ingest-subscription (subscription-util/make-subscription-concept
{:Name "test_sub_prov1"
:SubscriberId "user1"
:EmailAddress "PI:EMAIL:<EMAIL>END_PI"
:CollectionConceptId (:concept-id coll1)
:Query " "})
{:token "mock-echo-system-token"})
_ (subscription-util/ingest-subscription (subscription-util/make-subscription-concept
{:provider-id "PROV2"
:Name "test_sub_prov1"
:SubscriberId "user1"
:EmailAddress "PI:EMAIL:<EMAIL>END_PI"
:CollectionConceptId (:concept-id coll2)
:Query " "})
{:token "mock-echo-system-token"})
_ (index/wait-until-indexed)
;; Setup granules, gran1 and gran3 with acl matched access-value
;; gran 2 does not match, and should not be readable by user1
gran1 (data-core/ingest "PROV1"
(data-granule/granule-with-umm-spec-collection coll1
(:concept-id coll1)
{:granule-ur "Granule1"
:access-value 33})
{:token "mock-echo-system-token"})
gran2 (data-core/ingest "PROV1"
(data-granule/granule-with-umm-spec-collection coll1
(:concept-id coll1)
{:granule-ur "Granule2"
:access-value 66})
{:token "mock-echo-system-token"})
gran3 (data-core/ingest "PROV2"
(data-granule/granule-with-umm-spec-collection coll2
(:concept-id coll2)
{:granule-ur "Granule3"
:access-value 133})
{:token "mock-echo-system-token"})
_ (index/wait-until-indexed)
expected (set [(:concept-id gran1) (:concept-id gran3)])
actual (->> (process-subscriptions)
(map #(nth % 1))
flatten
(map :concept-id)
set)]
(is (= expected actual))))))
(deftest roll-your-own-subscription-tests
;; Use cases coming from EarthData Search wanting to allow their users to create
;; subscriptions without the need to have any acls
(let [acls (ac-util/search-for-acls (transmit-config/echo-system-token)
{:identity-type "provider"
:provider "PROV1"
:target "INGEST_MANAGEMENT_ACL"})
_ (echo-util/ungrant (system/context) (:concept_id (first (:items acls))))
_ (ac-util/wait-until-indexed)
supplied-concept-id "SUB1000-PROV1"
user1-token (echo-util/login (system/context) "user1")
coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})
concept (subscription-util/make-subscription-concept {:concept-id supplied-concept-id
:CollectionConceptId (:concept-id coll1)
:SubscriberId "user1"
:native-id "Atlantic-1"})]
;; caes 1 test against guest token - no subscription
(testing "guest token - guests can not create subscriptions - passes"
(let [{:keys [status errors]} (ingest/ingest-concept concept)]
(is (= 401 status))
(is (= ["You do not have permission to perform that action."] errors))))
;; case 2 test on system token (ECHO token) - should pass
(testing "system token - admins can create subscriptions - passes"
(let [{:keys [status errors]} (ingest/ingest-concept concept {:token (transmit-config/echo-system-token)})]
(is (or (= 200 status) (= 201 status)))
(is (nil? errors))))
;; case 3 test account 1 which matches metadata data user - should pass
(testing "use an account which matches the metadata and does not have ACL - passes"
(let [{:keys [status errors]} (ingest/ingest-concept concept {:token user1-token})]
(is (= 200 status))
(is (nil? errors))))
;; case 4 test account 3 which does NOT match metadata user and account does not have prems
(testing "use an account which does not matches the metadata and does not have ACL - fails"
(let [user3-token (echo-util/login (system/context) "user3")
{:keys [status errors]} (ingest/ingest-concept concept {:token user3-token})]
(is (= 401 status))
(is (= ["You do not have permission to perform that action."] errors))))))
;; case 5 test account 2 which does NOT match metadata user and account has prems ; this should be MMT's use case
(deftest roll-your-own-subscription-and-have-acls-tests-with-acls
(testing "Use an account which does not match matches the metadata and DOES have an ACL"
(let [user2-token (echo-util/login (system/context) "user2")
supplied-concept-id "SUB1000-PROV1"
coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})
concept (subscription-util/make-subscription-concept {:concept-id supplied-concept-id
:SubscriberId "user1"
:CollectionConceptId (:concept-id coll1)
:native-id "Atlantic-1"})
{:keys [status errors]} (ingest/ingest-concept concept {:token user2-token})]
(is (= 201 status))
(is (nil? errors)))))
(deftest ingest-update-and-delete-subscription-as-subscriber
(testing "Tests updating and deleting subscriptions as subscriber"
(echo-util/ungrant-by-search (system/context)
{:provider "PROV1"
:target ["SUBSCRIPTION_MANAGEMENT" "INGEST_MANAGEMENT_ACL"]})
(ac-util/wait-until-indexed)
(let [admin-group (echo-util/get-or-create-group (system/context) "admin-group")
admin-user-token (echo-util/login (system/context) "admin-user" [admin-group])]
(echo-util/grant-all-subscription-group-sm (system/context)
"PROV1"
admin-group
[:read :update])
(echo-util/grant-groups-ingest (system/context)
"PROV1"
[admin-group])
(ac-util/wait-until-indexed)
(let [user1-token (echo-util/login (system/context) "user1")
user2-token (echo-util/login (system/context) "user2")
coll1 (data-core/ingest-umm-spec-collection
"PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})
concept1-user1 (subscription-util/make-subscription-concept {:SubscriberId "user1"
:CollectionConceptId (:concept-id coll1)})
concept1-user2 (subscription-util/make-subscription-concept {:SubscriberId "user2"
:CollectionConceptId (:concept-id coll1)})
concept2 (subscription-util/make-subscription-concept {:SubscriberId "user1"
:native-id "new-concept"
:CollectionConceptId (:concept-id coll1)})
{:keys [concept-id revision-id status]} (ingest/ingest-concept concept1-user1 {:token user1-token})
concept1-user1 (merge {:concept-id concept-id} concept1-user1)
concept1-user2 (merge {:concept-id concept-id} concept1-user2)]
(is (= 201 status))
(are3 [ingest-api-call args expected-status expected-errors]
(let [{:keys [status errors]} (apply ingest-api-call args)]
(is (= expected-status status))
(is (= expected-errors errors)))
"Attempt to update subscription as user2"
ingest/ingest-concept [concept1-user2 {:token user2-token}] 401 ["You do not have permission to perform that action."]
"Attempt to delete subscription as user2"
ingest/delete-concept [concept1-user2 {:token user2-token}] 401 ["You do not have permission to perform that action."]
"Update subscription as user1"
ingest/ingest-concept [concept1-user1 {:token user1-token}] 200 nil
"Delete subscription as user1"
ingest/delete-concept [concept1-user1 {:token user1-token}] 200 nil
"Ingest subscription as admin"
ingest/ingest-concept [concept2 {:token admin-user-token}] 201 nil
"Update subscription as admin"
ingest/ingest-concept [concept2 {:token admin-user-token}] 200 nil
"Delete subscription as admin"
ingest/delete-concept [concept2 {:token admin-user-token}] 200 nil)))))
(deftest subscription-ingest-subscriber-collection-permission-check-test
(testing "Tests that the subscriber has permission to view the collection before allowing ingest"
(let [admin-group (echo-util/get-or-create-group (system/context) "admin-group")
group1 (echo-util/get-or-create-group (system/context) "group1")
admin-user-token (echo-util/login (system/context) "admin-user" [admin-group])
user-token (echo-util/login (system/context) "user1" [group1])
coll1 (data-core/ingest-umm-spec-collection "PROV1"
(data-umm-c/collection {:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})
fake-concept (subscription-util/make-subscription-concept {:SubscriberId "user1"
:CollectionConceptId "FAKE"})
concept (subscription-util/make-subscription-concept {:SubscriberId "user1"
:CollectionConceptId (:concept-id coll1)})]
;; adjust permissions
(echo-util/ungrant-by-search (system/context)
{:provider "PROV1"
:target ["SUBSCRIPTION_MANAGEMENT" "INGEST_MANAGEMENT_ACL"]})
(echo-util/ungrant-by-search (system/context)
{:provider "PROV1"
:identity-type "catalog_item"})
(echo-util/grant-all-subscription-group-sm (system/context)
"PROV1"
admin-group
[:read :update])
(echo-util/grant-groups-ingest (system/context)
"PROV1"
[admin-group])
(ac-util/wait-until-indexed)
(testing "non-existent collection concept-id"
(let [{:keys [status errors]} (ingest/ingest-concept fake-concept {:token "mock-echo-system-token"})]
(is (= 401 status))
(is (= [(format "Collection with concept id [FAKE] does not exist or subscriber-id [user1] does not have permission to view the collection.")]
errors))))
(testing "user doesn't have permission to view collection"
(are3 [ingest-api-call args expected-status expected-errors]
(let [{:keys [status errors]} (apply ingest-api-call args)]
(is (= expected-status status))
(is (= expected-errors errors)))
"Attempt to ingest subscription as user1"
ingest/ingest-concept [concept {:token user-token}] 401 [(format "Collection with concept id [%s] does not exist or subscriber-id [user1] does not have permission to view the collection." (:concept-id coll1))]
"Attempt to ingest subscription as admin-user"
ingest/ingest-concept [concept {:token admin-user-token}] 401 [(format "Collection with concept id [%s] does not exist or subscriber-id [user1] does not have permission to view the collection." (:concept-id coll1))]))
(echo-util/ungrant-by-search (system/context)
{:provider "PROV1"
:identity-type "catalog_item"})
(ac-util/create-acl "mock-echo-system-token"
{:group_permissions [{:group_id group1
:permissions ["read" "order"]}]
:catalog_item_identity {:name "coll1 ACL"
:provider_id "PROV1"
:collection_applicable true
:collection_identifier {:entry_titles [(:EntryTitle coll1)]}}})
(ac-util/wait-until-indexed)
(testing "user now has permission to view collection - by group-id"
(are3 [ingest-api-call args expected-status expected-errors]
(let [{:keys [status errors]} (apply ingest-api-call args)]
(is (= expected-status status))
(is (= expected-errors errors)))
"Ingest subscription as admin"
ingest/ingest-concept [concept {:token admin-user-token}] 201 nil
"Update subscription as admin"
ingest/ingest-concept [concept {:token admin-user-token}] 200 nil
"Delete subscription as admin"
ingest/delete-concept [concept {:token admin-user-token}] 200 nil
"Ingest subscription as user1"
ingest/ingest-concept [concept {:token user-token}] 200 nil
"Update subscription as user1"
ingest/ingest-concept [concept {:token user-token}] 200 nil
"Delete subscription as user1"
ingest/delete-concept [concept {:token user-token}] 200 nil))
(ac-util/create-acl "mock-echo-system-token"
{:group_permissions [{:user_type "registered"
:permissions ["read" "order"]}]
:catalog_item_identity {:name "coll1 ACL"
:provider_id "PROV1"
:collection_applicable true
:collection_identifier {:entry_titles [(:EntryTitle coll1)]}}})
(ac-util/wait-until-indexed)
(testing "user now has permission to view collection - by registered"
(are3 [ingest-api-call args expected-status expected-errors]
(let [{:keys [status errors]} (apply ingest-api-call args)]
(is (= expected-status status))
(is (= expected-errors errors)))
"Ingest subscription as admin"
ingest/ingest-concept [concept {:token admin-user-token}] 200 nil
"Update subscription as admin"
ingest/ingest-concept [concept {:token admin-user-token}] 200 nil
"Delete subscription as admin"
ingest/delete-concept [concept {:token admin-user-token}] 200 nil
"Ingest subscription as user1"
ingest/ingest-concept [concept {:token user-token}] 200 nil
"Update subscription as user1"
ingest/ingest-concept [concept {:token user-token}] 200 nil
"Delete subscription as user1"
ingest/delete-concept [concept {:token user-token}] 200 nil)))))
|
[
{
"context": "to spaces\n (str \";USER=GUEST;PASSWORD=guest\"))})) ; specify the GUEST user account created fo",
"end": 1223,
"score": 0.8983317017555237,
"start": 1218,
"tag": "PASSWORD",
"value": "guest"
}
] | c#-metabase/src/metabase/sample_data.clj | hanakhry/Crime_Admin | 0 | (ns metabase.sample-data
(:require [clojure.java.io :as io]
[clojure.string :as str]
[clojure.tools.logging :as log]
[metabase.models.database :refer [Database]]
[metabase.sync :as sync]
[metabase.util.i18n :refer [trs]]
[toucan.db :as db]))
(def ^:private ^String sample-dataset-name "Sample Dataset")
(def ^:private ^String sample-dataset-filename "sample-dataset.db.mv.db")
(defn- db-details []
(let [resource (io/resource sample-dataset-filename)]
(when-not resource
(throw (Exception. (trs "Sample dataset DB file ''{0}'' cannot be found."
sample-dataset-filename))))
{:db (-> (.getPath resource)
(str/replace #"^file:" "zip:") ; to connect to an H2 DB inside a JAR just replace file: with zip: (this doesn't do anything when running from the Clojure CLI, which has no `file:` prefix)
(str/replace #"\.mv\.db$" "") ; strip the .mv.db suffix from the path
(str/replace #"%20" " ") ; for some reason the path can get URL-encoded and replace spaces with `%20`; this breaks things so switch them back to spaces
(str ";USER=GUEST;PASSWORD=guest"))})) ; specify the GUEST user account created for the DB
(defn add-sample-dataset!
"Add the sample dataset as a Metabase DB if it doesn't already exist."
[]
(when-not (db/exists? Database :is_sample true)
(try
(log/info (trs "Loading sample dataset..."))
(sync/sync-database! (db/insert! Database
:name sample-dataset-name
:details (db-details)
:engine :h2
:is_sample true))
(catch Throwable e
(log/error e (trs "Failed to load sample dataset"))))))
(defn update-sample-dataset-if-needed!
"Update the path to the sample dataset DB if it exists in case the JAR has moved."
[]
(when-let [db (Database :is_sample true)]
(db/update! Database (:id db)
:details (db-details))))
| 72572 | (ns metabase.sample-data
(:require [clojure.java.io :as io]
[clojure.string :as str]
[clojure.tools.logging :as log]
[metabase.models.database :refer [Database]]
[metabase.sync :as sync]
[metabase.util.i18n :refer [trs]]
[toucan.db :as db]))
(def ^:private ^String sample-dataset-name "Sample Dataset")
(def ^:private ^String sample-dataset-filename "sample-dataset.db.mv.db")
(defn- db-details []
(let [resource (io/resource sample-dataset-filename)]
(when-not resource
(throw (Exception. (trs "Sample dataset DB file ''{0}'' cannot be found."
sample-dataset-filename))))
{:db (-> (.getPath resource)
(str/replace #"^file:" "zip:") ; to connect to an H2 DB inside a JAR just replace file: with zip: (this doesn't do anything when running from the Clojure CLI, which has no `file:` prefix)
(str/replace #"\.mv\.db$" "") ; strip the .mv.db suffix from the path
(str/replace #"%20" " ") ; for some reason the path can get URL-encoded and replace spaces with `%20`; this breaks things so switch them back to spaces
(str ";USER=GUEST;PASSWORD=<PASSWORD>"))})) ; specify the GUEST user account created for the DB
(defn add-sample-dataset!
"Add the sample dataset as a Metabase DB if it doesn't already exist."
[]
(when-not (db/exists? Database :is_sample true)
(try
(log/info (trs "Loading sample dataset..."))
(sync/sync-database! (db/insert! Database
:name sample-dataset-name
:details (db-details)
:engine :h2
:is_sample true))
(catch Throwable e
(log/error e (trs "Failed to load sample dataset"))))))
(defn update-sample-dataset-if-needed!
"Update the path to the sample dataset DB if it exists in case the JAR has moved."
[]
(when-let [db (Database :is_sample true)]
(db/update! Database (:id db)
:details (db-details))))
| true | (ns metabase.sample-data
(:require [clojure.java.io :as io]
[clojure.string :as str]
[clojure.tools.logging :as log]
[metabase.models.database :refer [Database]]
[metabase.sync :as sync]
[metabase.util.i18n :refer [trs]]
[toucan.db :as db]))
(def ^:private ^String sample-dataset-name "Sample Dataset")
(def ^:private ^String sample-dataset-filename "sample-dataset.db.mv.db")
(defn- db-details []
(let [resource (io/resource sample-dataset-filename)]
(when-not resource
(throw (Exception. (trs "Sample dataset DB file ''{0}'' cannot be found."
sample-dataset-filename))))
{:db (-> (.getPath resource)
(str/replace #"^file:" "zip:") ; to connect to an H2 DB inside a JAR just replace file: with zip: (this doesn't do anything when running from the Clojure CLI, which has no `file:` prefix)
(str/replace #"\.mv\.db$" "") ; strip the .mv.db suffix from the path
(str/replace #"%20" " ") ; for some reason the path can get URL-encoded and replace spaces with `%20`; this breaks things so switch them back to spaces
(str ";USER=GUEST;PASSWORD=PI:PASSWORD:<PASSWORD>END_PI"))})) ; specify the GUEST user account created for the DB
(defn add-sample-dataset!
"Add the sample dataset as a Metabase DB if it doesn't already exist."
[]
(when-not (db/exists? Database :is_sample true)
(try
(log/info (trs "Loading sample dataset..."))
(sync/sync-database! (db/insert! Database
:name sample-dataset-name
:details (db-details)
:engine :h2
:is_sample true))
(catch Throwable e
(log/error e (trs "Failed to load sample dataset"))))))
(defn update-sample-dataset-if-needed!
"Update the path to the sample dataset DB if it exists in case the JAR has moved."
[]
(when-let [db (Database :is_sample true)]
(db/update! Database (:id db)
:details (db-details))))
|
[
{
"context": "e-google-user [ctx google-user]\n (let [{:keys [id given_name family_name picture email locale]} google-us",
"end": 1143,
"score": 0.839113712310791,
"start": 1138,
"tag": "NAME",
"value": "given"
},
{
"context": "er [ctx google-user]\n (let [{:keys [id given_name family_name picture email locale]} google-user\n [",
"end": 1155,
"score": 0.5934640765190125,
"start": 1149,
"tag": "NAME",
"value": "family"
},
{
"context": "ser_id id\n :email email\n :first_name given_name\n :last_name family_name\n :coun",
"end": 1749,
"score": 0.9854768514633179,
"start": 1744,
"tag": "NAME",
"value": "given"
},
{
"context": "\n :first_name given_name\n :last_name family_name\n :country country\n :language l",
"end": 1780,
"score": 0.9816533923149109,
"start": 1774,
"tag": "NAME",
"value": "family"
}
] | src/clj/salava/oauth/google.clj | discendum/salava | 17 | (ns salava.oauth.google
(:require [slingshot.slingshot :refer :all]
[salava.oauth.db :as d]
[salava.user.db :as u]
[salava.core.countries :refer [all-countries]]
[salava.core.util :refer [get-site-url get-base-path]]))
(def api {:access-token-api "https://www.googleapis.com/oauth2/v4/token"
:user-info-api "https://www.googleapis.com/oauth2/v2/userinfo"
:revoke-token-api "https://accounts.google.com/o/oauth2/revoke"})
(defn google-access-token [ctx code redirect-path]
(let [app-id (get-in ctx [:config :oauth :google :app-id])
app-secret (get-in ctx [:config :oauth :google :app-secret])
redirect-url (str (get-site-url ctx) (get-base-path ctx) redirect-path)
opts {:query-params {:code code
:client_id app-id
:client_secret app-secret
:redirect_uri redirect-url
:grant_type "authorization_code"}}]
(d/access-token :post (:access-token-api api) opts)))
(defn parse-google-user [ctx google-user]
(let [{:keys [id given_name family_name picture email locale]} google-user
[_ language country] (if (and (string? locale) (= (count locale) 5))
(re-find #"([a-z]{2})-([A-Z]{2})" locale))
country (if (get all-countries country)
country
(get-in ctx [:config :user :default-country]))
language (if (some #(= (keyword language) %) (get-in ctx [:config :core :languages]))
language
(get-in ctx [:config :user :default-language]))]
{:oauth_user_id id
:email email
:first_name given_name
:last_name family_name
:country country
:language language
:picture_url picture}))
(defn google-login [ctx code current-user-id error]
(try+
(if (or error (clojure.string/blank? code))
(throw+ "oauth/Unexpectederroroccured")
(let [access-token (google-access-token ctx code "/oauth/google")
google-user (d/oauth-user ctx (str (:user-info-api api)"?access_token=" access-token ) {} parse-google-user)
user (d/get-or-create-user ctx "google" google-user current-user-id)
user-id (if (map? user) (:user-id user) user)]
(do
(d/update-user-last_login ctx user-id)
(if (map? user) (merge {:status "success"} user) {:status "success" :user-id user-id}))))
(catch Object _
{:status "error" :message _})))
(defn google-deauthorize [ctx code current-user-id]
(try+
(let [access-token (google-access-token ctx code "/oauth/google/deauthorize")]
(d/oauth-request :post (str (:revoke-token-api api)"?token=" access-token) {})
(d/remove-oauth-user ctx current-user-id "google")
{:status "success"})
(catch Object _
{:status "error" :message (str _)})))
| 10467 | (ns salava.oauth.google
(:require [slingshot.slingshot :refer :all]
[salava.oauth.db :as d]
[salava.user.db :as u]
[salava.core.countries :refer [all-countries]]
[salava.core.util :refer [get-site-url get-base-path]]))
(def api {:access-token-api "https://www.googleapis.com/oauth2/v4/token"
:user-info-api "https://www.googleapis.com/oauth2/v2/userinfo"
:revoke-token-api "https://accounts.google.com/o/oauth2/revoke"})
(defn google-access-token [ctx code redirect-path]
(let [app-id (get-in ctx [:config :oauth :google :app-id])
app-secret (get-in ctx [:config :oauth :google :app-secret])
redirect-url (str (get-site-url ctx) (get-base-path ctx) redirect-path)
opts {:query-params {:code code
:client_id app-id
:client_secret app-secret
:redirect_uri redirect-url
:grant_type "authorization_code"}}]
(d/access-token :post (:access-token-api api) opts)))
(defn parse-google-user [ctx google-user]
(let [{:keys [id <NAME>_name <NAME>_name picture email locale]} google-user
[_ language country] (if (and (string? locale) (= (count locale) 5))
(re-find #"([a-z]{2})-([A-Z]{2})" locale))
country (if (get all-countries country)
country
(get-in ctx [:config :user :default-country]))
language (if (some #(= (keyword language) %) (get-in ctx [:config :core :languages]))
language
(get-in ctx [:config :user :default-language]))]
{:oauth_user_id id
:email email
:first_name <NAME>_name
:last_name <NAME>_name
:country country
:language language
:picture_url picture}))
(defn google-login [ctx code current-user-id error]
(try+
(if (or error (clojure.string/blank? code))
(throw+ "oauth/Unexpectederroroccured")
(let [access-token (google-access-token ctx code "/oauth/google")
google-user (d/oauth-user ctx (str (:user-info-api api)"?access_token=" access-token ) {} parse-google-user)
user (d/get-or-create-user ctx "google" google-user current-user-id)
user-id (if (map? user) (:user-id user) user)]
(do
(d/update-user-last_login ctx user-id)
(if (map? user) (merge {:status "success"} user) {:status "success" :user-id user-id}))))
(catch Object _
{:status "error" :message _})))
(defn google-deauthorize [ctx code current-user-id]
(try+
(let [access-token (google-access-token ctx code "/oauth/google/deauthorize")]
(d/oauth-request :post (str (:revoke-token-api api)"?token=" access-token) {})
(d/remove-oauth-user ctx current-user-id "google")
{:status "success"})
(catch Object _
{:status "error" :message (str _)})))
| true | (ns salava.oauth.google
(:require [slingshot.slingshot :refer :all]
[salava.oauth.db :as d]
[salava.user.db :as u]
[salava.core.countries :refer [all-countries]]
[salava.core.util :refer [get-site-url get-base-path]]))
(def api {:access-token-api "https://www.googleapis.com/oauth2/v4/token"
:user-info-api "https://www.googleapis.com/oauth2/v2/userinfo"
:revoke-token-api "https://accounts.google.com/o/oauth2/revoke"})
(defn google-access-token [ctx code redirect-path]
(let [app-id (get-in ctx [:config :oauth :google :app-id])
app-secret (get-in ctx [:config :oauth :google :app-secret])
redirect-url (str (get-site-url ctx) (get-base-path ctx) redirect-path)
opts {:query-params {:code code
:client_id app-id
:client_secret app-secret
:redirect_uri redirect-url
:grant_type "authorization_code"}}]
(d/access-token :post (:access-token-api api) opts)))
(defn parse-google-user [ctx google-user]
(let [{:keys [id PI:NAME:<NAME>END_PI_name PI:NAME:<NAME>END_PI_name picture email locale]} google-user
[_ language country] (if (and (string? locale) (= (count locale) 5))
(re-find #"([a-z]{2})-([A-Z]{2})" locale))
country (if (get all-countries country)
country
(get-in ctx [:config :user :default-country]))
language (if (some #(= (keyword language) %) (get-in ctx [:config :core :languages]))
language
(get-in ctx [:config :user :default-language]))]
{:oauth_user_id id
:email email
:first_name PI:NAME:<NAME>END_PI_name
:last_name PI:NAME:<NAME>END_PI_name
:country country
:language language
:picture_url picture}))
(defn google-login [ctx code current-user-id error]
(try+
(if (or error (clojure.string/blank? code))
(throw+ "oauth/Unexpectederroroccured")
(let [access-token (google-access-token ctx code "/oauth/google")
google-user (d/oauth-user ctx (str (:user-info-api api)"?access_token=" access-token ) {} parse-google-user)
user (d/get-or-create-user ctx "google" google-user current-user-id)
user-id (if (map? user) (:user-id user) user)]
(do
(d/update-user-last_login ctx user-id)
(if (map? user) (merge {:status "success"} user) {:status "success" :user-id user-id}))))
(catch Object _
{:status "error" :message _})))
(defn google-deauthorize [ctx code current-user-id]
(try+
(let [access-token (google-access-token ctx code "/oauth/google/deauthorize")]
(d/oauth-request :post (str (:revoke-token-api api)"?token=" access-token) {})
(d/remove-oauth-user ctx current-user-id "google")
{:status "success"})
(catch Object _
{:status "error" :message (str _)})))
|
[
{
"context": ")\n\n(deftest test-map-schema-serdes\n (let [data {\"Alice\" 50\n \"Bob\" 55\n \"Chad\" 8",
"end": 15865,
"score": 0.9997903108596802,
"start": 15860,
"tag": "NAME",
"value": "Alice"
},
{
"context": "ma-serdes\n (let [data {\"Alice\" 50\n \"Bob\" 55\n \"Chad\" 89}\n encoded (l/s",
"end": 15888,
"score": 0.9998266696929932,
"start": 15885,
"tag": "NAME",
"value": "Bob"
},
{
"context": "{\"Alice\" 50\n \"Bob\" 55\n \"Chad\" 89}\n encoded (l/serialize ages-schema dat",
"end": 15912,
"score": 0.9994263648986816,
"start": 15908,
"tag": "NAME",
"value": "Chad"
},
{
"context": "(deftest test-array-schema-serdes\n (let [names [\"Ferdinand\" \"Omar\" \"Lin\"]\n encoded (l/serialize simpl",
"end": 16633,
"score": 0.9998192191123962,
"start": 16624,
"tag": "NAME",
"value": "Ferdinand"
},
{
"context": "t-array-schema-serdes\n (let [names [\"Ferdinand\" \"Omar\" \"Lin\"]\n encoded (l/serialize simple-array",
"end": 16640,
"score": 0.9997899532318115,
"start": 16636,
"tag": "NAME",
"value": "Omar"
},
{
"context": "-schema-serdes\n (let [names [\"Ferdinand\" \"Omar\" \"Lin\"]\n encoded (l/serialize simple-array-schem",
"end": 16646,
"score": 0.9997048377990723,
"start": 16643,
"tag": "NAME",
"value": "Lin"
},
{
"context": "rd-union-schema-serdes\n (let [data #:dog{:name \"Fido\" :owner \"Zach\"}\n encoded (l/serialize pers",
"end": 24773,
"score": 0.9612697958946228,
"start": 24770,
"tag": "NAME",
"value": "ido"
},
{
"context": "ma-serdes\n (let [data #:dog{:name \"Fido\" :owner \"Zach\"}\n encoded (l/serialize person-or-dog-sche",
"end": 24787,
"score": 0.9937304258346558,
"start": 24783,
"tag": "NAME",
"value": "Zach"
},
{
"context": "is (= data decoded))\n data #:person{:name \"Bill\" :age 50}\n encoded (l/serialize person-or-",
"end": 25115,
"score": 0.9997074604034424,
"start": 25111,
"tag": "NAME",
"value": "Bill"
},
{
"context": "st test-map-or-array-schema-serdes\n (let [data {\"Zeke\" 22 \"Adeline\" 88}\n encoded (l/serialize ma",
"end": 25971,
"score": 0.995714545249939,
"start": 25967,
"tag": "NAME",
"value": "Zeke"
},
{
"context": "p-or-array-schema-serdes\n (let [data {\"Zeke\" 22 \"Adeline\" 88}\n encoded (l/serialize map-or-array-sc",
"end": 25984,
"score": 0.9981123805046082,
"start": 25977,
"tag": "NAME",
"value": "Adeline"
},
{
"context": "deftest test-mopodoa-schema-serdes\n (let [data {\"Zeke\" 22 \"Adeline\" 88}\n encoded (l/serialize mo",
"end": 27673,
"score": 0.9956355094909668,
"start": 27669,
"tag": "NAME",
"value": "Zeke"
},
{
"context": "st-mopodoa-schema-serdes\n (let [data {\"Zeke\" 22 \"Adeline\" 88}\n encoded (l/serialize mopodoa-schema ",
"end": 27686,
"score": 0.9962275624275208,
"start": 27679,
"tag": "NAME",
"value": "Adeline"
},
{
"context": "ec-w-array-and-enum-serdes\n (let [data {:names [\"Aria\" \"Beth\" \"Cindy\"]\n :why :stock}\n ",
"end": 30366,
"score": 0.99980229139328,
"start": 30362,
"tag": "NAME",
"value": "Aria"
},
{
"context": "ray-and-enum-serdes\n (let [data {:names [\"Aria\" \"Beth\" \"Cindy\"]\n :why :stock}\n enco",
"end": 30373,
"score": 0.9997881650924683,
"start": 30369,
"tag": "NAME",
"value": "Beth"
},
{
"context": "-enum-serdes\n (let [data {:names [\"Aria\" \"Beth\" \"Cindy\"]\n :why :stock}\n encoded (l/s",
"end": 30381,
"score": 0.9997798800468445,
"start": 30376,
"tag": "NAME",
"value": "Cindy"
},
{
"context": "est-rec-w-map-serdes\n (let [data {:name-to-age {\"Aria\" 22\n \"Beth\" 33\n ",
"end": 31403,
"score": 0.9994140267372131,
"start": 31399,
"tag": "NAME",
"value": "Aria"
},
{
"context": "me-to-age {\"Aria\" 22\n \"Beth\" 33\n \"Cindy\" 44}\n ",
"end": 31441,
"score": 0.9990415573120117,
"start": 31437,
"tag": "NAME",
"value": "Beth"
},
{
"context": " \"Beth\" 33\n \"Cindy\" 44}\n :what \"yo\"}\n encoded (l",
"end": 31480,
"score": 0.9992449283599854,
"start": 31475,
"tag": "NAME",
"value": "Cindy"
},
{
"context": "d-serdes-missing-maybe-field\n (let [data {:name \"Sharon\"}\n encoded (l/serialize rec-w-maybe-field-",
"end": 33689,
"score": 0.9992172718048096,
"start": 33683,
"tag": "NAME",
"value": "Sharon"
},
{
"context": " 1}))\n (is (round-trip? schema #:person{:name \"Chad\" :age 18}))))\n\n(deftest test-ns-enum\n (is (round",
"end": 38308,
"score": 0.9994187951087952,
"start": 38304,
"tag": "NAME",
"value": "Chad"
}
] | test/deercreeklabs/unit/lancaster_test.cljc | yanatan16/lancaster | 0 | (ns deercreeklabs.unit.lancaster-test
(:require
[clojure.test :refer [deftest is]]
[clojure.walk :as walk]
[deercreeklabs.baracus :as ba]
[deercreeklabs.lancaster :as l]
[deercreeklabs.lancaster.pcf-utils :as pcf-utils]
[deercreeklabs.lancaster.utils :as u]
[schema.core :as s :include-macros true])
#?(:clj
(:import
(clojure.lang ExceptionInfo)
(org.apache.avro Schema
SchemaNormalization
Schema$Parser))))
;; Use this instead of fixtures, which are hard to make work w/ async testing.
(s/set-fn-validation! true)
(defn abs-err [expected actual]
(let [err (- expected actual)]
(if (neg? err)
(- err)
err)))
(defn rel-err [expected actual]
(/ (abs-err expected actual) expected))
(defn xf-byte-arrays
[edn]
(walk/postwalk #(if (ba/byte-array? %)
(u/byte-array->byte-str %)
%)
edn))
#?(:clj
(defn fp-matches? [schema]
(let [json-schema (l/json schema)
parser (Schema$Parser.)
java-schema (.parse parser ^String json-schema)
java-fp (SchemaNormalization/parsingFingerprint64 java-schema)
clj-fp (l/fingerprint64 schema)]
(or (= java-fp clj-fp)
(let [java-pcf (SchemaNormalization/toParsingForm java-schema)
clj-pcf (l/pcf schema)
err-str (str "Fingerprints do not match!\n"
"java-fp: " java-fp "\n"
"clj-fp: " clj-fp "\n"
"java-pcf:\n" java-pcf "\n"
"clj-pcf:\n" clj-pcf "\n")]
(println err-str))))))
(defn round-trip? [schema data]
(let [serialized (l/serialize schema data)
deserialized (l/deserialize-same schema serialized)]
(= data deserialized)))
(l/def-record-schema add-to-cart-req-schema
[:sku :required l/int-schema]
[:qty-requested l/int-schema])
(def add-to-cart-req-v2-schema
(l/record-schema ::add-to-cart-req
[[:sku l/int-schema]
[:qty-requested l/int-schema]
[:note l/string-schema]]))
(def add-to-cart-req-v3-schema ;; qtys are floats!
(l/record-schema ::add-to-cart-req
[[:sku l/int-schema]
[:qty-requested l/float-schema]
[:note l/string-schema]]))
(def add-to-cart-req-v4-schema
(l/record-schema ::add-to-cart-req
[[:sku l/int-schema]
[:qty-requested l/int-schema]
[:comment l/string-schema]]))
(l/def-enum-schema why-schema
:all :stock :limit)
(l/def-enum-schema suit-schema
:suit/hearts :suit/clubs :suit/spades :suit/diamonds)
(l/def-fixed-schema a-fixed-schema
2)
(l/def-maybe-schema maybe-int-schema
l/int-schema)
(l/def-record-schema rec-w-maybe-field-schema
[:name l/string-schema]
[:age maybe-int-schema])
(l/def-record-schema rec-w-fixed-no-default-schema
[:data :required a-fixed-schema])
(l/def-record-schema add-to-cart-rsp-schema
[:qty-requested l/int-schema]
[:qty-added l/int-schema]
[:current-qty l/int-schema]
[:req :required add-to-cart-req-schema {:sku 10 :qty-requested 1}]
[:the-reason-why :required why-schema :stock]
[:data :required a-fixed-schema (ba/byte-array [77 88])]
[:other-data l/bytes-schema])
(l/def-array-schema simple-array-schema
l/string-schema)
(l/def-array-schema rsps-schema
add-to-cart-rsp-schema)
(l/def-record-schema rec-w-array-and-enum-schema
[:names :required simple-array-schema]
[:why why-schema])
(l/def-map-schema ages-schema
l/int-schema)
(l/def-record-schema rec-w-map-schema
[:name-to-age ages-schema]
[:what l/string-schema])
(l/def-map-schema nested-map-schema
add-to-cart-rsp-schema)
(l/def-union-schema union-schema
l/int-schema add-to-cart-req-schema a-fixed-schema)
(l/def-record-schema person-schema
[:person/name :required l/string-schema "No name"]
[:person/age :required l/int-schema 0])
(l/def-record-schema dog-schema
[:dog/name l/string-schema]
[:dog/owner l/string-schema])
(def dog-v2-schema
(l/record-schema ::dog
[[:dog/name l/string-schema]
[:dog/owner l/string-schema]
[:dog/tag-number l/int-schema]]))
(l/def-record-schema fish-schema
[:fish/name l/string-schema]
[:tank-num l/int-schema])
(l/def-union-schema person-or-dog-schema
person-schema dog-schema)
(l/def-union-schema fish-or-person-or-dog-v2-schema
fish-schema person-schema dog-v2-schema)
(l/def-union-schema map-or-array-schema
ages-schema simple-array-schema)
(l/def-union-schema mopodoa-schema
ages-schema person-schema dog-schema simple-array-schema)
(l/def-record-schema date-schema
[:year l/int-schema]
[:month l/int-schema]
[:day l/int-schema])
(l/def-record-schema time-schema
[:hour l/int-schema]
[:minute l/int-schema]
[:second (l/maybe l/int-schema)])
(l/def-record-schema date-time-schema
;; Note that this does not include seconds.
[:year l/int-schema]
[:month l/int-schema]
[:day l/int-schema]
[:hour l/int-schema]
[:minute l/int-schema])
(l/def-record-schema tree-schema
[:value :required l/int-schema]
[:right :tree]
[:left :tree])
(deftest test-record-schema
(let [expected-pcf (str
"{\"name\":\"deercreeklabs.unit.lancaster_test."
"AddToCartReq\",\"type\":\"record\",\"fields\":"
"[{\"name\":\"sku\",\"type\":\"int\"},{\"name\":"
"\"qtyRequested\",\"type\":[\"null\",\"int\"]}]}")
expected-edn {:name :deercreeklabs.unit.lancaster-test/add-to-cart-req
:type :record
:fields
[{:name :sku
:type :int
:default -1}
{:name :qty-requested
:type [:null :int]
:default nil}]}]
#?(:clj (is (fp-matches? add-to-cart-req-schema)))
(is (= "3703990475150151424"
(u/long->str (l/fingerprint64 add-to-cart-req-schema))))
(is (= expected-edn (l/edn add-to-cart-req-schema)))
(is (= expected-pcf (l/pcf
add-to-cart-req-schema)))))
(deftest test-def-record-schema-serdes
(let [data {:sku 123
:qty-requested 5}
encoded (l/serialize add-to-cart-req-schema data)
decoded (l/deserialize-same add-to-cart-req-schema encoded)]
(is (= "9gECCg==" (ba/byte-array->b64 encoded)))
(is (= data decoded))))
(deftest test-def-record-schema-mixed-ns
(is (= {:name :deercreeklabs.unit.lancaster-test/fish
:type :record
:fields [{:name :fish/name
:type [:null :string]
:default nil}
{:name :tank-num
:type [:null :int]
:default nil}]}
(l/edn fish-schema)))
(is (= (str
"{\"name\":\"deercreeklabs.unit.lancaster_test.Fish\",\"type\":"
"\"record\",\"fields\":[{\"name\":\"fishName\",\"type\":[\"null\","
"\"string\"],\"default\":null},{\"name\":\"tankNum\",\"type\":"
"[\"null\",\"int\"],\"default\":null}]}")
(l/json fish-schema))))
(deftest test-def-enum-schema
(is (= {:name :deercreeklabs.unit.lancaster-test/why
:type :enum
:symbols [:all :stock :limit]
:default :all}
(l/edn why-schema)))
#?(:clj (is (fp-matches? why-schema)))
(is (= (str "{\"name\":\"deercreeklabs.unit.lancaster_test.Why\",\"type\":"
"\"enum\",\"symbols\":[\"ALL\",\"STOCK\",\"LIMIT\"],\"default\":"
"\"ALL\"}")
(l/json why-schema)))
(is (= (str "{\"name\":\"deercreeklabs.unit.lancaster_test.Why\",\"type\":"
"\"enum\",\"symbols\":[\"ALL\",\"STOCK\",\"LIMIT\"]}")
(l/pcf why-schema)))
(is (= "3321246333858425949"
(u/long->str (l/fingerprint64 why-schema)))))
(deftest test-def-enum-schema-serdes
(let [data :stock
encoded (l/serialize why-schema data)
decoded (l/deserialize-same why-schema encoded)]
(is (ba/equivalent-byte-arrays? (ba/byte-array [2]) encoded))
(is (= data decoded))))
(deftest test-def-fixed-schema
(is (= {:name :deercreeklabs.unit.lancaster-test/a-fixed
:type :fixed
:size 2}
(l/edn a-fixed-schema)))
#?(:clj (is (fp-matches? a-fixed-schema)))
(is (= (str "{\"name\":\"deercreeklabs.unit.lancaster_test.AFixed\",\"type\":"
"\"fixed\",\"size\":2}")
(l/pcf a-fixed-schema)))
(is (= "-1031156250377191762"
(u/long->str (l/fingerprint64 a-fixed-schema)))))
(deftest test-def-fixed-schema-serdes
(let [data (ba/byte-array [12 24])
encoded (l/serialize a-fixed-schema data)
decoded (l/deserialize-same a-fixed-schema encoded)]
(is (ba/equivalent-byte-arrays?
data encoded))
(is (ba/equivalent-byte-arrays? data decoded))))
(deftest test-nested-record-schema
(let [expected {:name :deercreeklabs.unit.lancaster-test/add-to-cart-rsp
:type :record
:fields
[{:name :qty-requested
:type [:null :int]
:default nil}
{:name :qty-added
:type [:null :int]
:default nil}
{:name :current-qty
:type [:null :int]
:default nil}
{:name :req
:type
{:name :deercreeklabs.unit.lancaster-test/add-to-cart-req
:type :record
:fields [{:name :sku :type :int :default -1}
{:name :qty-requested
:type [:null :int]
:default nil}]}
:default {:sku 10
:qty-requested nil}}
{:name :the-reason-why
:type {:name :deercreeklabs.unit.lancaster-test/why
:type :enum
:symbols [:all :stock :limit]
:default :all}
:default :stock}
{:name :data
:type {:name :deercreeklabs.unit.lancaster-test/a-fixed
:type :fixed
:size 2}
:default "MX"}
{:name :other-data
:type [:null :bytes]
:default nil}]}]
#?(:clj (is (fp-matches? add-to-cart-rsp-schema)))
(is (= (str
"{\"name\":\"deercreeklabs.unit.lancaster_test.AddToCartRsp\","
"\"type\":\"record\",\"fields\":[{\"name\":\"qtyRequested\","
"\"type\":[\"null\",\"int\"]},{\"name\":\"qtyAdded\",\"type\":"
"[\"null\",\"int\"]},{\"name\":\"currentQty\",\"type\":[\"null\","
"\"int\"]},{\"name\":\"req\",\"type\":{\"name\":\"deercreeklabs."
"unit.lancaster_test.AddToCartReq\",\"type\":\"record\",\"fields\":"
"[{\"name\":\"sku\",\"type\":\"int\"},{\"name\":\"qtyRequested\","
"\"type\":[\"null\",\"int\"]}]}},{\"name\":\"theReasonWhy\","
"\"type\":{\"name\":\"deercreeklabs.unit.lancaster_test.Why\","
"\"type\":\"enum\",\"symbols\":[\"ALL\",\"STOCK\",\"LIMIT\"]}},"
"{\"name\":\"data\",\"type\":{\"name\":\"deercreeklabs.unit."
"lancaster_test.AFixed\",\"type\":\"fixed\",\"size\":2}},"
"{\"name\":\"otherData\",\"type\":[\"null\",\"bytes\"]}]}")
(l/pcf add-to-cart-rsp-schema)))
(is (= expected (l/edn add-to-cart-rsp-schema))))
(is (= "3835051015389218749"
(u/long->str (l/fingerprint64 add-to-cart-rsp-schema)))))
(deftest test-nested-record-serdes
(let [data {:qty-requested 123
:qty-added 10
:current-qty 10
:req {:sku 123
:qty-requested 123}
:the-reason-why :limit
:data (ba/byte-array [66 67])
:other-data (ba/byte-array [123 123])}
encoded (l/serialize add-to-cart-rsp-schema data)
decoded (l/deserialize-same add-to-cart-rsp-schema
encoded)]
(is (= "AvYBAhQCFPYBAvYBBEJDAgR7ew==" (ba/byte-array->b64 encoded)))
(is (= (xf-byte-arrays data)
(xf-byte-arrays decoded)))))
(deftest test-null-schema
(let [data nil
encoded (l/serialize l/null-schema data)
decoded (l/deserialize-same l/null-schema encoded)]
#?(:clj (is (fp-matches? l/null-schema)))
(is (ba/equivalent-byte-arrays? (ba/byte-array []) encoded))
(is (= data decoded))))
(deftest test-boolean-schema
(let [data true
encoded (l/serialize l/boolean-schema data)
decoded (l/deserialize-same l/boolean-schema encoded)]
#?(:clj (is (fp-matches? l/boolean-schema)))
(is (ba/equivalent-byte-arrays? (ba/byte-array [1]) encoded))
(is (= data decoded))))
(deftest test-int-schema-serdes
(let [data 7890
encoded (l/serialize l/int-schema data)
decoded (l/deserialize-same l/int-schema encoded)]
#?(:clj (is (fp-matches? l/int-schema)))
(is (ba/equivalent-byte-arrays? (ba/byte-array [-92 123]) encoded))
(is (= data decoded))))
(deftest test-long-schema-serdes
(let [data (u/ints->long 2147483647 -1)
encoded (l/serialize l/long-schema data)
decoded (l/deserialize-same l/long-schema encoded)]
#?(:clj (is (fp-matches? l/long-schema)))
(is (ba/equivalent-byte-arrays?
(ba/byte-array [-2 -1 -1 -1 -1 -1 -1 -1 -1 1])
encoded))
(is (= data decoded))))
(deftest test-int->long
(let [in (int -1)
l (u/int->long in)]
(is (= "-1" (u/long->str l)))))
(deftest test-float-schema
(let [data (float 3.14159)
encoded (l/serialize l/float-schema data)
decoded (l/deserialize-same l/float-schema encoded)
abs-err (abs-err data decoded)]
#?(:clj (is (fp-matches? l/float-schema)))
(is (ba/equivalent-byte-arrays? (ba/byte-array [-48 15 73 64]) encoded))
(is (< abs-err 0.000001))))
(deftest test-double-schema
(let [data (double 3.14159265359)
encoded (l/serialize l/double-schema data)
decoded (l/deserialize-same l/double-schema encoded)
abs-err (abs-err data decoded)]
#?(:clj (is (fp-matches? l/double-schema)))
(is (ba/equivalent-byte-arrays? (ba/byte-array [-22 46 68 84 -5 33 9 64])
encoded))
(is (< abs-err 0.000001))))
(deftest test-bytes-schema
(let [data (ba/byte-array [1 1 2 3 5 8 13 21])
encoded (l/serialize l/bytes-schema data)
decoded (l/deserialize-same l/bytes-schema encoded)]
#?(:clj (is (fp-matches? l/bytes-schema)))
(is (ba/equivalent-byte-arrays? (ba/byte-array [16 1 1 2 3 5 8 13 21])
encoded))
(is (ba/equivalent-byte-arrays? data decoded))))
(deftest test-string-schema
(let [data "Hello world!"
encoded (l/serialize l/string-schema data)
decoded (l/deserialize-same l/string-schema encoded)]
#?(:clj (is (fp-matches? l/string-schema)))
(is (ba/equivalent-byte-arrays?
(ba/byte-array [24 72 101 108 108 111 32 119 111 114 108 100 33])
encoded))
(is (= data decoded))))
(deftest test-def-map-schema
(is (= {:type :map :values :int}
(l/edn ages-schema)))
#?(:clj (is (fp-matches? ages-schema)))
(is (= "{\"type\":\"map\",\"values\":\"int\"}"
(l/pcf ages-schema)))
(is (= "-2649837581481768589"
(u/long->str (l/fingerprint64 ages-schema)))))
(deftest test-map-schema-serdes
(let [data {"Alice" 50
"Bob" 55
"Chad" 89}
encoded (l/serialize ages-schema data)
decoded (l/deserialize-same ages-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [6 10 65 108 105 99 101 100 6 66 111 98 110 8
67 104 97 100 -78 1 0])
encoded))
(is (= data decoded))))
(deftest test-def-array-schema
#?(:clj (is (fp-matches? simple-array-schema)))
(is (= {:type :array :items :string}
(l/edn simple-array-schema)))
(is (= "{\"type\":\"array\",\"items\":\"string\"}"
(l/pcf simple-array-schema)))
(is (= "-3577210133426481249"
(u/long->str (l/fingerprint64 simple-array-schema)))))
(deftest test-array-schema-serdes
(let [names ["Ferdinand" "Omar" "Lin"]
encoded (l/serialize simple-array-schema names)
decoded (l/deserialize-same simple-array-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [6 18 70 101 114 100 105 110 97 110 100 8 79
109 97 114 6 76 105 110 0])
encoded))
(is (= names decoded))))
(deftest test-empty-array-serdes
(let [sch (l/array-schema l/int-schema)
data []
encoded (l/serialize sch data)
_ (is (ba/equivalent-byte-arrays?
(ba/byte-array [0])
encoded))
decoded (l/deserialize-same sch encoded)]
(is (= data decoded))))
(deftest test-nested-array-schema
#?(:clj (is (fp-matches? rsps-schema)))
(is (= {:type :array
:items
{:name :deercreeklabs.unit.lancaster-test/add-to-cart-rsp
:type :record
:fields
[{:name :qty-requested
:type [:null :int]
:default nil}
{:name :qty-added
:type [:null :int]
:default nil}
{:name :current-qty
:type [:null :int]
:default nil}
{:name :req
:type {:name :deercreeklabs.unit.lancaster-test/add-to-cart-req
:type :record
:fields [{:name :sku
:type :int
:default -1}
{:name :qty-requested
:type [:null :int]
:default nil}]}
:default {:sku 10 :qty-requested nil}}
{:name :the-reason-why
:type {:name :deercreeklabs.unit.lancaster-test/why
:type :enum
:symbols [:all :stock :limit]
:default :all}
:default :stock}
{:name :data
:type
{:name :deercreeklabs.unit.lancaster-test/a-fixed
:type :fixed
:size 2}
:default "MX"}
{:name :other-data
:type [:null :bytes]
:default nil}]}}
(l/edn rsps-schema)))
(is (= "3719708605096203323"
(u/long->str (l/fingerprint64 rsps-schema)))))
(deftest test-nested-array-schema-serdes
(let [data [{:qty-requested 123
:qty-added 4
:current-qty 10
:req
{:sku 123 :qty-requested 123}
:the-reason-why :limit
:data (ba/byte-array [66 67])
:other-data (ba/byte-array [123 123])}
{:qty-requested 4
:qty-added 4
:current-qty 4
:req
{:sku 10 :qty-requested 4}
:the-reason-why :all
:data (ba/byte-array [100 110])
:other-data (ba/byte-array [64 74])}]
encoded (l/serialize rsps-schema data)
decoded (l/deserialize-same rsps-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [4 2 246 1 2 8 2 20 246 1 2 246 1 4 66 67 2 4 123 123
2 8 2 8 2 8 20 2 8 0 100 110 2 4 64 74 0])
encoded))
(is (= (xf-byte-arrays data)
(xf-byte-arrays decoded)))))
(deftest test-nested-map-schema
#?(:clj (is (fp-matches? nested-map-schema)))
(is (= {:type :map
:values
{:name :deercreeklabs.unit.lancaster-test/add-to-cart-rsp
:type :record
:fields
[{:name :qty-requested :type [:null :int] :default nil}
{:name :qty-added :type [:null :int] :default nil}
{:name :current-qty :type [:null :int] :default nil}
{:name :req
:type {:name :deercreeklabs.unit.lancaster-test/add-to-cart-req
:type :record
:fields [{:name :sku :type :int :default -1}
{:name :qty-requested
:type [:null :int]
:default nil}]}
:default {:sku 10 :qty-requested nil}}
{:name :the-reason-why
:type {:name :deercreeklabs.unit.lancaster-test/why
:type :enum
:symbols [:all :stock :limit]
:default :all}
:default :stock}
{:name :data
:type
{:name :deercreeklabs.unit.lancaster-test/a-fixed
:type :fixed
:size 2}
:default "MX"}
{:name :other-data
:type [:null :bytes]
:default nil}]}}
(l/edn nested-map-schema)))
(is (= "-6484319793187085262"
(u/long->str (l/fingerprint64 nested-map-schema)))))
(deftest test-nested-map-schema-serdes
(let [data {"A" {:qty-requested 123
:qty-added 4
:current-qty 10
:req {:sku 123
:qty-requested 123}
:the-reason-why :limit
:data (ba/byte-array [66 67])
:other-data (ba/byte-array [123 123])}
"B" {:qty-requested 4
:qty-added 4
:current-qty 4
:req {:sku 10
:qty-requested 4}
:the-reason-why :all
:data (ba/byte-array [100 110])
:other-data (ba/byte-array [64 74])}}
encoded (l/serialize nested-map-schema data)
decoded (l/deserialize-same nested-map-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [4 2 65 2 246 1 2 8 2 20 246 1 2 246 1 4 66 67 2 4 123
123 2 66 2 8 2 8 2 8 20 2 8 0 100 110 2 4 64 74 0])
encoded))
(is (= (xf-byte-arrays data)
(xf-byte-arrays decoded)))))
(deftest test-empty-map-serdes
(let [sch (l/map-schema l/int-schema)
data {}
encoded (l/serialize sch data)
_ (is (ba/equivalent-byte-arrays?
(ba/byte-array [0])
encoded))
decoded (l/deserialize-same sch encoded)]
(is (= data decoded))))
(deftest test-union-schema
#?(:clj (is (fp-matches? union-schema)))
(is (= [:int
{:name :deercreeklabs.unit.lancaster-test/add-to-cart-req
:type :record
:fields [{:name :sku
:type :int
:default -1}
{:name :qty-requested
:type [:null :int]
:default nil}]}
{:name :deercreeklabs.unit.lancaster-test/a-fixed
:type :fixed
:size 2}]
(l/edn union-schema)))
(is (= "-193173046069528093"
(u/long->str (l/fingerprint64 union-schema)))))
(deftest test-union-schema-serdes
(let [data {:sku 123 :qty-requested 4}
encoded (l/serialize union-schema data)
decoded (l/deserialize-same union-schema encoded)
_ (is (ba/equivalent-byte-arrays? (ba/byte-array [2 246 1 2 8])
encoded))
_ (is (= data decoded))
data 5
encoded (l/serialize union-schema data)
decoded (l/deserialize-same union-schema encoded)]
(is (ba/equivalent-byte-arrays? (ba/byte-array [0 10])
encoded))
(is (= data decoded))))
(deftest test-union-schema-w-multiple-records
#?(:clj (is (fp-matches? person-or-dog-schema)))
(is (= [{:name :deercreeklabs.unit.lancaster-test/person
:type :record
:fields
[{:name :person/name :type :string :default "No name"}
{:name :person/age :type :int :default 0}]}
{:name :deercreeklabs.unit.lancaster-test/dog
:type :record
:fields
[{:name :dog/name :type [:null :string] :default nil}
{:name :dog/owner :type [:null :string] :default nil}]}]
(l/edn person-or-dog-schema)))
(is (= "-5174754347720548939"
(u/long->str (l/fingerprint64 person-or-dog-schema)))))
(deftest test-multi-record-union-schema-serdes
(let [data #:dog{:name "Fido" :owner "Zach"}
encoded (l/serialize person-or-dog-schema data)
decoded (l/deserialize-same person-or-dog-schema encoded)
_ (is (ba/equivalent-byte-arrays?
(ba/byte-array [2 2 8 70 105 100 111 2 8 90 97 99 104])
encoded))
_ (is (= data decoded))
data #:person{:name "Bill" :age 50}
encoded (l/serialize person-or-dog-schema data)
decoded (l/deserialize-same person-or-dog-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [0 8 66 105 108 108 100])
encoded))
(is (= data decoded))))
(deftest test-multi-record-schema-serdes-non-existent
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"does not match any schema in the union schema"
(l/serialize person-or-dog-schema {:k 1}))))
(deftest test-map-or-array-schema
#?(:clj (is (fp-matches? map-or-array-schema)))
(is (= [{:type :map :values :int}
{:type :array :items :string}]
(l/edn map-or-array-schema)))
(is (= "4441440791563688855"
(u/long->str (l/fingerprint64 map-or-array-schema)))))
(deftest test-map-or-array-schema-serdes
(let [data {"Zeke" 22 "Adeline" 88}
encoded (l/serialize map-or-array-schema data)
decoded (l/deserialize-same map-or-array-schema encoded)
_ (is (ba/equivalent-byte-arrays?
(ba/byte-array [0 4 8 90 101 107 101 44 14 65 100 101 108 105
110 101 -80 1 0])
encoded))
_ (is (= data decoded))
data ["a thing" "another thing"]
encoded (l/serialize map-or-array-schema data)
decoded (l/deserialize-same map-or-array-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [2 4 14 97 32 116 104 105 110 103 26 97 110
111 116 104 101 114 32 116 104 105 110 103 0])
encoded))
(is (= data decoded))))
(deftest test-mopodoa-schema
#?(:clj (is (fp-matches? mopodoa-schema)))
(is (= [{:type :map :values :int}
{:name :deercreeklabs.unit.lancaster-test/person
:type :record
:fields [{:name :person/name
:type :string
:default "No name"}
{:name :person/age
:type :int
:default 0}]}
{:name :deercreeklabs.unit.lancaster-test/dog
:type :record
:fields [{:name :dog/name
:type [:null :string]
:default nil}
{:name :dog/owner
:type [:null :string]
:default nil}]}
{:type :array :items :string}]
(l/edn mopodoa-schema)))
(is (= "-2196893583124300899"
(u/long->str (l/fingerprint64 mopodoa-schema)))))
(deftest test-mopodoa-schema-serdes
(let [data {"Zeke" 22 "Adeline" 88}
encoded (l/serialize mopodoa-schema data)
decoded (l/deserialize-same mopodoa-schema encoded)
_ (is (ba/equivalent-byte-arrays?
(ba/byte-array [0 4 8 90 101 107 101 44 14 65 100 101 108 105
110 101 -80 1 0])
encoded))
_ (is (= data decoded))
data ["a thing" "another thing"]
encoded (l/serialize mopodoa-schema data)
decoded (l/deserialize-same mopodoa-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [6 4 14 97 32 116 104 105 110 103 26 97 110
111 116 104 101 114 32 116 104 105 110 103 0])
encoded))
(is (= data decoded))))
(deftest test-recursive-schema
(is (= {:name :deercreeklabs.unit.lancaster-test/tree
:type :record
:fields
[{:name :value :type :int :default -1}
{:name :right
:type [:null :tree]
:default nil}
{:name :left
:type [:null :tree]
:default nil}]}
(l/edn tree-schema)))
#?(:clj (is (fp-matches? tree-schema)))
(is (= "-3297333764539234889"
(u/long->str (l/fingerprint64 tree-schema)))))
(deftest test-edn-schemas-match?-recursive-schema
(is (u/edn-schemas-match? (l/edn tree-schema) (l/edn tree-schema) {} {})))
(deftest test-recursive-schema-serdes
(let [data {:value 5
:right {:value -10
:right {:value -20}}
:left {:value 10
:left {:value 20
:left {:value 40}}}}
encoded (l/serialize tree-schema data)
decoded (l/deserialize-same tree-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [10 2 19 2 39 0 0 0 2 20 0 2 40 0 2 80 0 0])
encoded))
(is (= data decoded))))
(deftest test-rec-w-array-and-enum-schema
#?(:clj (is (fp-matches? rec-w-array-and-enum-schema)))
(is (= {:name :deercreeklabs.unit.lancaster-test/rec-w-array-and-enum
:type :record
:fields
[{:name :names
:type {:type :array :items :string}
:default []}
{:name :why
:type [:null
{:default :all
:name :deercreeklabs.unit.lancaster-test/why
:symbols [:all :stock :limit]
:type :enum}]
:default nil}]}
(l/edn rec-w-array-and-enum-schema)))
(is (= "-7358640627267953104"
(u/long->str (l/fingerprint64
rec-w-array-and-enum-schema)))))
(deftest test-rec-w-array-and-enum-serdes
(let [data {:names ["Aria" "Beth" "Cindy"]
:why :stock}
encoded (l/serialize rec-w-array-and-enum-schema data)
decoded (l/deserialize-same rec-w-array-and-enum-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [6 8 65 114 105 97 8 66 101 116 104 10 67 105 110 100
121 0 2 2])
encoded))
(is (= data decoded))))
(deftest test-rec-w-map-schema
#?(:clj (is (fp-matches? rec-w-map-schema)))
(is (= {:name :deercreeklabs.unit.lancaster-test/rec-w-map
:type :record
:fields [{:name :name-to-age
:type [:null {:type :map
:values :int}]
:default nil}
{:name :what
:type [:null :string]
:default nil}]}
(l/edn rec-w-map-schema)))
(is (= "1679652566194036700"
(u/long->str (l/fingerprint64
rec-w-map-schema)))))
(deftest test-rec-w-map-serdes
(let [data {:name-to-age {"Aria" 22
"Beth" 33
"Cindy" 44}
:what "yo"}
encoded (l/serialize rec-w-map-schema data)
decoded (l/deserialize-same rec-w-map-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [2 6 8 65 114 105 97 44 8 66 101 116 104 66 10 67 105
110 100 121 88 0 2 4 121 111])
encoded))
(is (= data decoded))))
(deftest test-rec-w-fixed-no-default
#?(:clj (is (fp-matches? rec-w-fixed-no-default-schema)))
(is (= {:name :deercreeklabs.unit.lancaster-test/rec-w-fixed-no-default
:type :record
:fields
[{:name :data
:type
{:name :deercreeklabs.unit.lancaster-test/a-fixed
:type :fixed
:size 2}
:default "\0\0"}]}
(l/edn rec-w-fixed-no-default-schema)))
(is (= "-6875395607105571061"
(u/long->str (l/fingerprint64
rec-w-fixed-no-default-schema)))))
(deftest test-rec-w-fixed-no-default-serdes
(let [data {:data (ba/byte-array [1 2])}
encoded (l/serialize rec-w-fixed-no-default-schema data)
decoded (l/deserialize-same rec-w-fixed-no-default-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [1 2])
encoded))
(is (ba/equivalent-byte-arrays?
(:data data)
(:data decoded)))))
(deftest test-rec-w-maybe-field
#?(:clj (is (fp-matches? rec-w-maybe-field-schema)))
(is (= {:name :deercreeklabs.unit.lancaster-test/rec-w-maybe-field
:type :record
:fields [{:name :name
:type [:null :string]
:default nil}
{:name :age
:type [:null :int]
:default nil}]}
(l/edn rec-w-maybe-field-schema)))
(is (= "-5686522258470805846"
(u/long->str (l/fingerprint64 rec-w-maybe-field-schema)))))
(deftest test-record-serdes-missing-field
(let [data {:qty-requested 100}]
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Record data is missing key `:sku`"
(l/serialize add-to-cart-req-schema data)))))
(deftest test-record-serdes-missing-maybe-field
(let [data {:name "Sharon"}
encoded (l/serialize rec-w-maybe-field-schema data)
decoded (l/deserialize-same rec-w-maybe-field-schema encoded)]
(is (= data decoded))))
(deftest test-schema?
(is (l/schema? person-or-dog-schema))
(is (not (l/schema? :foo))))
(deftest test-bad-serialize-arg
(s/without-fn-validation ;; Allow built-in handlers to throw
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"First argument to serialize must be a schema object"
(l/serialize nil nil)))))
(deftest test-bad-deserialize-args
(s/without-fn-validation ;; Allow built-in handlers to throw
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"First argument to deserialize must be a schema object"
(l/deserialize nil nil nil)))
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Second argument to deserialize must be a "
(l/deserialize why-schema nil (ba/byte-array []))))
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"argument to deserialize must be a byte array"
(l/deserialize why-schema why-schema [])))))
(deftest test-field-default-validation
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Bad default value for field `:int-field`. Got `a`."
(l/record-schema :test-schema
[[:int-field l/int-schema "a"]]))))
(deftest test-default-data
(is (= :all (l/default-data why-schema)))
(is (= {:sku -1
:qty-requested nil}
(l/default-data add-to-cart-req-schema))))
(deftest test-bad-field-name
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Name keywords must start with a letter and subsequently"
(l/record-schema :test-schema
[[:bad? l/boolean-schema]]))))
(deftest test-bad-record-name
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Name keywords must start with a letter and subsequently"
(l/record-schema :*test-schema*
[[:is-good l/boolean-schema]]))))
(deftest test-duplicate-field-name
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Field names must be unique."
(l/record-schema :test-schema
[[:int-field l/int-schema]
[:int-field l/int-schema]]))))
(deftest test-good-union
(let [sch1 (l/record-schema ::sch1 [[:a l/int-schema]
[:b l/string-schema]])
sch2 (l/record-schema ::sch2 [[:different-ns/b l/string-schema]])
sch3 (l/union-schema [sch1 sch2])]
(is (round-trip? sch3 {:different-ns/b "hi"}))
(is (round-trip? sch3 {:a 1 :b "hi"}))))
(deftest test-bad-union
(let [sch1 (l/record-schema ::sch1 [[:a l/int-schema]
[:b l/string-schema]])
sch2 (l/record-schema ::sch2 [[:b l/string-schema]])]
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Ambiguous union"
(l/union-schema [sch1 sch2])))))
(deftest test-serialize-bad-union-member
(let [schema (l/union-schema [l/null-schema l/int-schema])]
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"does not match any schema in the union schema"
(l/serialize schema :foo)))))
(deftest test-maybe-w-union-arg
(let [schema-1 (l/maybe (l/union-schema [l/int-schema l/string-schema]))
schema-2 (l/maybe (l/union-schema [l/null-schema l/int-schema]))]
(is (round-trip? schema-1 nil))
(is (round-trip? schema-2 nil))
(is (round-trip? schema-1 34))
(is (round-trip? schema-2 34))))
(deftest test-more-than-one-numeric-type-in-a-union
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Unions may not contain more than one numeric schema"
(l/union-schema [l/int-schema l/float-schema]))))
(deftest test-more-than-one-bytes-type-in-a-union
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Unions may not contain more than one byte-array schema"
(l/union-schema [l/bytes-schema (l/fixed-schema :foo 16)]))))
(deftest test-serialize-empty-map-multi-rec-union
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Record data is missing key `:person/name`"
(l/serialize person-or-dog-schema {}))))
(deftest test-map-and-rec-union
(let [schema (l/union-schema [(l/map-schema l/int-schema) person-schema])]
(is (round-trip? schema {"foo" 1}))
(is (round-trip? schema #:person{:name "Chad" :age 18}))))
(deftest test-ns-enum
(is (round-trip? suit-schema :suit/spades))
(is (= {:name :deercreeklabs.unit.lancaster-test/suit
:type :enum
:symbols [:suit/hearts :suit/clubs :suit/spades :suit/diamonds]
:default :suit/hearts}
(l/edn suit-schema)))
(is (= (str "{\"name\":\"deercreeklabs.unit.lancaster_test.Suit\",\"type\":"
"\"enum\",\"symbols\":[\"HEARTS\",\"CLUBS\",\"SPADES\","
"\"DIAMONDS\"],\"default\":\"HEARTS\"}")
(l/json suit-schema))))
(deftest test-identical-schemas-in-union
(let [sch1 (l/enum-schema ::a-name [:a :b])
sch2 (l/enum-schema ::a-name [:a :b])]
(is (not= sch1 sch2))
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Identical schemas in union"
(l/union-schema [l/string-schema sch1 sch2])))))
(deftest test-schemas-match?
(let [sch1 (l/enum-schema ::a-name [:a :b])
sch2 (l/enum-schema ::a-name [:a :b])
sch3 (l/enum-schema ::x-name [:a :b])]
(is (l/schemas-match? sch1 sch2))
(is (not (l/schemas-match? sch1 sch3)))))
(deftest test-missing-record-field
(let [sch1 (l/record-schema ::test [[:a :required l/int-schema]])
sch2 (l/union-schema [l/int-schema sch1])
sch3 (l/record-schema ::sch3 [[:arg sch2]])
sch4 (l/array-schema sch3)]
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Record data is missing key `:a`"
(l/serialize sch1 {:b 1})))
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Record data is missing key `:a`"
(l/serialize sch2 {:b 1})))
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Record data is missing key `:a`"
(l/serialize sch3 {:arg {:b 1}})))
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Record data is missing key `:a`"
(l/serialize sch4 [{:arg {:a 1}}
{:arg {:b 1}}])))))
(deftest serialize-small-double-into-float-union
(let [sch (l/union-schema [l/null-schema l/float-schema])
v (double 6.0)
encoded (l/serialize sch v)
decoded (l/deserialize-same sch encoded)]
(is (= v decoded))))
(deftest serialize-long-into-union
(let [sch (l/union-schema [l/null-schema l/long-schema])
v (u/str->long "-5442038735385698765")
encoded (l/serialize sch v)
decoded (l/deserialize-same sch encoded)]
(is (= v decoded))))
(deftest serialize-lazy-sequence-into-union
(let [sch (l/union-schema [l/null-schema (l/array-schema l/int-schema)])
v (map identity [42 681 1024]) ; Make a lazy seq
encoded (l/serialize sch v)
decoded (l/deserialize-same sch encoded)]
(is (= v decoded))))
(deftest test-rt-set
(let [sch l/string-set-schema
v #{"a" "b" "1234" "c45"}
encoded (l/serialize sch v)
decoded (l/deserialize-same sch encoded)]
(is (= v decoded))))
(deftest test-bad-set-type
(let [sch l/string-set-schema
v #{"2" :k}] ;; not strictly string members
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Set element `:k` .* is not a valid string"
(l/serialize sch v)))))
(deftest test-bad-set-type-map-of-nils
(let [sch (l/map-schema l/null-schema) ;; equivalent to l/string-set-schema
v {"a" nil "b" nil}] ;; Must be a set
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"is not a valid Clojure set"
(l/serialize sch v)))))
| 120831 | (ns deercreeklabs.unit.lancaster-test
(:require
[clojure.test :refer [deftest is]]
[clojure.walk :as walk]
[deercreeklabs.baracus :as ba]
[deercreeklabs.lancaster :as l]
[deercreeklabs.lancaster.pcf-utils :as pcf-utils]
[deercreeklabs.lancaster.utils :as u]
[schema.core :as s :include-macros true])
#?(:clj
(:import
(clojure.lang ExceptionInfo)
(org.apache.avro Schema
SchemaNormalization
Schema$Parser))))
;; Use this instead of fixtures, which are hard to make work w/ async testing.
(s/set-fn-validation! true)
(defn abs-err [expected actual]
(let [err (- expected actual)]
(if (neg? err)
(- err)
err)))
(defn rel-err [expected actual]
(/ (abs-err expected actual) expected))
(defn xf-byte-arrays
[edn]
(walk/postwalk #(if (ba/byte-array? %)
(u/byte-array->byte-str %)
%)
edn))
#?(:clj
(defn fp-matches? [schema]
(let [json-schema (l/json schema)
parser (Schema$Parser.)
java-schema (.parse parser ^String json-schema)
java-fp (SchemaNormalization/parsingFingerprint64 java-schema)
clj-fp (l/fingerprint64 schema)]
(or (= java-fp clj-fp)
(let [java-pcf (SchemaNormalization/toParsingForm java-schema)
clj-pcf (l/pcf schema)
err-str (str "Fingerprints do not match!\n"
"java-fp: " java-fp "\n"
"clj-fp: " clj-fp "\n"
"java-pcf:\n" java-pcf "\n"
"clj-pcf:\n" clj-pcf "\n")]
(println err-str))))))
(defn round-trip? [schema data]
(let [serialized (l/serialize schema data)
deserialized (l/deserialize-same schema serialized)]
(= data deserialized)))
(l/def-record-schema add-to-cart-req-schema
[:sku :required l/int-schema]
[:qty-requested l/int-schema])
(def add-to-cart-req-v2-schema
(l/record-schema ::add-to-cart-req
[[:sku l/int-schema]
[:qty-requested l/int-schema]
[:note l/string-schema]]))
(def add-to-cart-req-v3-schema ;; qtys are floats!
(l/record-schema ::add-to-cart-req
[[:sku l/int-schema]
[:qty-requested l/float-schema]
[:note l/string-schema]]))
(def add-to-cart-req-v4-schema
(l/record-schema ::add-to-cart-req
[[:sku l/int-schema]
[:qty-requested l/int-schema]
[:comment l/string-schema]]))
(l/def-enum-schema why-schema
:all :stock :limit)
(l/def-enum-schema suit-schema
:suit/hearts :suit/clubs :suit/spades :suit/diamonds)
(l/def-fixed-schema a-fixed-schema
2)
(l/def-maybe-schema maybe-int-schema
l/int-schema)
(l/def-record-schema rec-w-maybe-field-schema
[:name l/string-schema]
[:age maybe-int-schema])
(l/def-record-schema rec-w-fixed-no-default-schema
[:data :required a-fixed-schema])
(l/def-record-schema add-to-cart-rsp-schema
[:qty-requested l/int-schema]
[:qty-added l/int-schema]
[:current-qty l/int-schema]
[:req :required add-to-cart-req-schema {:sku 10 :qty-requested 1}]
[:the-reason-why :required why-schema :stock]
[:data :required a-fixed-schema (ba/byte-array [77 88])]
[:other-data l/bytes-schema])
(l/def-array-schema simple-array-schema
l/string-schema)
(l/def-array-schema rsps-schema
add-to-cart-rsp-schema)
(l/def-record-schema rec-w-array-and-enum-schema
[:names :required simple-array-schema]
[:why why-schema])
(l/def-map-schema ages-schema
l/int-schema)
(l/def-record-schema rec-w-map-schema
[:name-to-age ages-schema]
[:what l/string-schema])
(l/def-map-schema nested-map-schema
add-to-cart-rsp-schema)
(l/def-union-schema union-schema
l/int-schema add-to-cart-req-schema a-fixed-schema)
(l/def-record-schema person-schema
[:person/name :required l/string-schema "No name"]
[:person/age :required l/int-schema 0])
(l/def-record-schema dog-schema
[:dog/name l/string-schema]
[:dog/owner l/string-schema])
(def dog-v2-schema
(l/record-schema ::dog
[[:dog/name l/string-schema]
[:dog/owner l/string-schema]
[:dog/tag-number l/int-schema]]))
(l/def-record-schema fish-schema
[:fish/name l/string-schema]
[:tank-num l/int-schema])
(l/def-union-schema person-or-dog-schema
person-schema dog-schema)
(l/def-union-schema fish-or-person-or-dog-v2-schema
fish-schema person-schema dog-v2-schema)
(l/def-union-schema map-or-array-schema
ages-schema simple-array-schema)
(l/def-union-schema mopodoa-schema
ages-schema person-schema dog-schema simple-array-schema)
(l/def-record-schema date-schema
[:year l/int-schema]
[:month l/int-schema]
[:day l/int-schema])
(l/def-record-schema time-schema
[:hour l/int-schema]
[:minute l/int-schema]
[:second (l/maybe l/int-schema)])
(l/def-record-schema date-time-schema
;; Note that this does not include seconds.
[:year l/int-schema]
[:month l/int-schema]
[:day l/int-schema]
[:hour l/int-schema]
[:minute l/int-schema])
(l/def-record-schema tree-schema
[:value :required l/int-schema]
[:right :tree]
[:left :tree])
(deftest test-record-schema
(let [expected-pcf (str
"{\"name\":\"deercreeklabs.unit.lancaster_test."
"AddToCartReq\",\"type\":\"record\",\"fields\":"
"[{\"name\":\"sku\",\"type\":\"int\"},{\"name\":"
"\"qtyRequested\",\"type\":[\"null\",\"int\"]}]}")
expected-edn {:name :deercreeklabs.unit.lancaster-test/add-to-cart-req
:type :record
:fields
[{:name :sku
:type :int
:default -1}
{:name :qty-requested
:type [:null :int]
:default nil}]}]
#?(:clj (is (fp-matches? add-to-cart-req-schema)))
(is (= "3703990475150151424"
(u/long->str (l/fingerprint64 add-to-cart-req-schema))))
(is (= expected-edn (l/edn add-to-cart-req-schema)))
(is (= expected-pcf (l/pcf
add-to-cart-req-schema)))))
(deftest test-def-record-schema-serdes
(let [data {:sku 123
:qty-requested 5}
encoded (l/serialize add-to-cart-req-schema data)
decoded (l/deserialize-same add-to-cart-req-schema encoded)]
(is (= "9gECCg==" (ba/byte-array->b64 encoded)))
(is (= data decoded))))
(deftest test-def-record-schema-mixed-ns
(is (= {:name :deercreeklabs.unit.lancaster-test/fish
:type :record
:fields [{:name :fish/name
:type [:null :string]
:default nil}
{:name :tank-num
:type [:null :int]
:default nil}]}
(l/edn fish-schema)))
(is (= (str
"{\"name\":\"deercreeklabs.unit.lancaster_test.Fish\",\"type\":"
"\"record\",\"fields\":[{\"name\":\"fishName\",\"type\":[\"null\","
"\"string\"],\"default\":null},{\"name\":\"tankNum\",\"type\":"
"[\"null\",\"int\"],\"default\":null}]}")
(l/json fish-schema))))
(deftest test-def-enum-schema
(is (= {:name :deercreeklabs.unit.lancaster-test/why
:type :enum
:symbols [:all :stock :limit]
:default :all}
(l/edn why-schema)))
#?(:clj (is (fp-matches? why-schema)))
(is (= (str "{\"name\":\"deercreeklabs.unit.lancaster_test.Why\",\"type\":"
"\"enum\",\"symbols\":[\"ALL\",\"STOCK\",\"LIMIT\"],\"default\":"
"\"ALL\"}")
(l/json why-schema)))
(is (= (str "{\"name\":\"deercreeklabs.unit.lancaster_test.Why\",\"type\":"
"\"enum\",\"symbols\":[\"ALL\",\"STOCK\",\"LIMIT\"]}")
(l/pcf why-schema)))
(is (= "3321246333858425949"
(u/long->str (l/fingerprint64 why-schema)))))
(deftest test-def-enum-schema-serdes
(let [data :stock
encoded (l/serialize why-schema data)
decoded (l/deserialize-same why-schema encoded)]
(is (ba/equivalent-byte-arrays? (ba/byte-array [2]) encoded))
(is (= data decoded))))
(deftest test-def-fixed-schema
(is (= {:name :deercreeklabs.unit.lancaster-test/a-fixed
:type :fixed
:size 2}
(l/edn a-fixed-schema)))
#?(:clj (is (fp-matches? a-fixed-schema)))
(is (= (str "{\"name\":\"deercreeklabs.unit.lancaster_test.AFixed\",\"type\":"
"\"fixed\",\"size\":2}")
(l/pcf a-fixed-schema)))
(is (= "-1031156250377191762"
(u/long->str (l/fingerprint64 a-fixed-schema)))))
(deftest test-def-fixed-schema-serdes
(let [data (ba/byte-array [12 24])
encoded (l/serialize a-fixed-schema data)
decoded (l/deserialize-same a-fixed-schema encoded)]
(is (ba/equivalent-byte-arrays?
data encoded))
(is (ba/equivalent-byte-arrays? data decoded))))
(deftest test-nested-record-schema
(let [expected {:name :deercreeklabs.unit.lancaster-test/add-to-cart-rsp
:type :record
:fields
[{:name :qty-requested
:type [:null :int]
:default nil}
{:name :qty-added
:type [:null :int]
:default nil}
{:name :current-qty
:type [:null :int]
:default nil}
{:name :req
:type
{:name :deercreeklabs.unit.lancaster-test/add-to-cart-req
:type :record
:fields [{:name :sku :type :int :default -1}
{:name :qty-requested
:type [:null :int]
:default nil}]}
:default {:sku 10
:qty-requested nil}}
{:name :the-reason-why
:type {:name :deercreeklabs.unit.lancaster-test/why
:type :enum
:symbols [:all :stock :limit]
:default :all}
:default :stock}
{:name :data
:type {:name :deercreeklabs.unit.lancaster-test/a-fixed
:type :fixed
:size 2}
:default "MX"}
{:name :other-data
:type [:null :bytes]
:default nil}]}]
#?(:clj (is (fp-matches? add-to-cart-rsp-schema)))
(is (= (str
"{\"name\":\"deercreeklabs.unit.lancaster_test.AddToCartRsp\","
"\"type\":\"record\",\"fields\":[{\"name\":\"qtyRequested\","
"\"type\":[\"null\",\"int\"]},{\"name\":\"qtyAdded\",\"type\":"
"[\"null\",\"int\"]},{\"name\":\"currentQty\",\"type\":[\"null\","
"\"int\"]},{\"name\":\"req\",\"type\":{\"name\":\"deercreeklabs."
"unit.lancaster_test.AddToCartReq\",\"type\":\"record\",\"fields\":"
"[{\"name\":\"sku\",\"type\":\"int\"},{\"name\":\"qtyRequested\","
"\"type\":[\"null\",\"int\"]}]}},{\"name\":\"theReasonWhy\","
"\"type\":{\"name\":\"deercreeklabs.unit.lancaster_test.Why\","
"\"type\":\"enum\",\"symbols\":[\"ALL\",\"STOCK\",\"LIMIT\"]}},"
"{\"name\":\"data\",\"type\":{\"name\":\"deercreeklabs.unit."
"lancaster_test.AFixed\",\"type\":\"fixed\",\"size\":2}},"
"{\"name\":\"otherData\",\"type\":[\"null\",\"bytes\"]}]}")
(l/pcf add-to-cart-rsp-schema)))
(is (= expected (l/edn add-to-cart-rsp-schema))))
(is (= "3835051015389218749"
(u/long->str (l/fingerprint64 add-to-cart-rsp-schema)))))
(deftest test-nested-record-serdes
(let [data {:qty-requested 123
:qty-added 10
:current-qty 10
:req {:sku 123
:qty-requested 123}
:the-reason-why :limit
:data (ba/byte-array [66 67])
:other-data (ba/byte-array [123 123])}
encoded (l/serialize add-to-cart-rsp-schema data)
decoded (l/deserialize-same add-to-cart-rsp-schema
encoded)]
(is (= "AvYBAhQCFPYBAvYBBEJDAgR7ew==" (ba/byte-array->b64 encoded)))
(is (= (xf-byte-arrays data)
(xf-byte-arrays decoded)))))
(deftest test-null-schema
(let [data nil
encoded (l/serialize l/null-schema data)
decoded (l/deserialize-same l/null-schema encoded)]
#?(:clj (is (fp-matches? l/null-schema)))
(is (ba/equivalent-byte-arrays? (ba/byte-array []) encoded))
(is (= data decoded))))
(deftest test-boolean-schema
(let [data true
encoded (l/serialize l/boolean-schema data)
decoded (l/deserialize-same l/boolean-schema encoded)]
#?(:clj (is (fp-matches? l/boolean-schema)))
(is (ba/equivalent-byte-arrays? (ba/byte-array [1]) encoded))
(is (= data decoded))))
(deftest test-int-schema-serdes
(let [data 7890
encoded (l/serialize l/int-schema data)
decoded (l/deserialize-same l/int-schema encoded)]
#?(:clj (is (fp-matches? l/int-schema)))
(is (ba/equivalent-byte-arrays? (ba/byte-array [-92 123]) encoded))
(is (= data decoded))))
(deftest test-long-schema-serdes
(let [data (u/ints->long 2147483647 -1)
encoded (l/serialize l/long-schema data)
decoded (l/deserialize-same l/long-schema encoded)]
#?(:clj (is (fp-matches? l/long-schema)))
(is (ba/equivalent-byte-arrays?
(ba/byte-array [-2 -1 -1 -1 -1 -1 -1 -1 -1 1])
encoded))
(is (= data decoded))))
(deftest test-int->long
(let [in (int -1)
l (u/int->long in)]
(is (= "-1" (u/long->str l)))))
(deftest test-float-schema
(let [data (float 3.14159)
encoded (l/serialize l/float-schema data)
decoded (l/deserialize-same l/float-schema encoded)
abs-err (abs-err data decoded)]
#?(:clj (is (fp-matches? l/float-schema)))
(is (ba/equivalent-byte-arrays? (ba/byte-array [-48 15 73 64]) encoded))
(is (< abs-err 0.000001))))
(deftest test-double-schema
(let [data (double 3.14159265359)
encoded (l/serialize l/double-schema data)
decoded (l/deserialize-same l/double-schema encoded)
abs-err (abs-err data decoded)]
#?(:clj (is (fp-matches? l/double-schema)))
(is (ba/equivalent-byte-arrays? (ba/byte-array [-22 46 68 84 -5 33 9 64])
encoded))
(is (< abs-err 0.000001))))
(deftest test-bytes-schema
(let [data (ba/byte-array [1 1 2 3 5 8 13 21])
encoded (l/serialize l/bytes-schema data)
decoded (l/deserialize-same l/bytes-schema encoded)]
#?(:clj (is (fp-matches? l/bytes-schema)))
(is (ba/equivalent-byte-arrays? (ba/byte-array [16 1 1 2 3 5 8 13 21])
encoded))
(is (ba/equivalent-byte-arrays? data decoded))))
(deftest test-string-schema
(let [data "Hello world!"
encoded (l/serialize l/string-schema data)
decoded (l/deserialize-same l/string-schema encoded)]
#?(:clj (is (fp-matches? l/string-schema)))
(is (ba/equivalent-byte-arrays?
(ba/byte-array [24 72 101 108 108 111 32 119 111 114 108 100 33])
encoded))
(is (= data decoded))))
(deftest test-def-map-schema
(is (= {:type :map :values :int}
(l/edn ages-schema)))
#?(:clj (is (fp-matches? ages-schema)))
(is (= "{\"type\":\"map\",\"values\":\"int\"}"
(l/pcf ages-schema)))
(is (= "-2649837581481768589"
(u/long->str (l/fingerprint64 ages-schema)))))
(deftest test-map-schema-serdes
(let [data {"<NAME>" 50
"<NAME>" 55
"<NAME>" 89}
encoded (l/serialize ages-schema data)
decoded (l/deserialize-same ages-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [6 10 65 108 105 99 101 100 6 66 111 98 110 8
67 104 97 100 -78 1 0])
encoded))
(is (= data decoded))))
(deftest test-def-array-schema
#?(:clj (is (fp-matches? simple-array-schema)))
(is (= {:type :array :items :string}
(l/edn simple-array-schema)))
(is (= "{\"type\":\"array\",\"items\":\"string\"}"
(l/pcf simple-array-schema)))
(is (= "-3577210133426481249"
(u/long->str (l/fingerprint64 simple-array-schema)))))
(deftest test-array-schema-serdes
(let [names ["<NAME>" "<NAME>" "<NAME>"]
encoded (l/serialize simple-array-schema names)
decoded (l/deserialize-same simple-array-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [6 18 70 101 114 100 105 110 97 110 100 8 79
109 97 114 6 76 105 110 0])
encoded))
(is (= names decoded))))
(deftest test-empty-array-serdes
(let [sch (l/array-schema l/int-schema)
data []
encoded (l/serialize sch data)
_ (is (ba/equivalent-byte-arrays?
(ba/byte-array [0])
encoded))
decoded (l/deserialize-same sch encoded)]
(is (= data decoded))))
(deftest test-nested-array-schema
#?(:clj (is (fp-matches? rsps-schema)))
(is (= {:type :array
:items
{:name :deercreeklabs.unit.lancaster-test/add-to-cart-rsp
:type :record
:fields
[{:name :qty-requested
:type [:null :int]
:default nil}
{:name :qty-added
:type [:null :int]
:default nil}
{:name :current-qty
:type [:null :int]
:default nil}
{:name :req
:type {:name :deercreeklabs.unit.lancaster-test/add-to-cart-req
:type :record
:fields [{:name :sku
:type :int
:default -1}
{:name :qty-requested
:type [:null :int]
:default nil}]}
:default {:sku 10 :qty-requested nil}}
{:name :the-reason-why
:type {:name :deercreeklabs.unit.lancaster-test/why
:type :enum
:symbols [:all :stock :limit]
:default :all}
:default :stock}
{:name :data
:type
{:name :deercreeklabs.unit.lancaster-test/a-fixed
:type :fixed
:size 2}
:default "MX"}
{:name :other-data
:type [:null :bytes]
:default nil}]}}
(l/edn rsps-schema)))
(is (= "3719708605096203323"
(u/long->str (l/fingerprint64 rsps-schema)))))
(deftest test-nested-array-schema-serdes
(let [data [{:qty-requested 123
:qty-added 4
:current-qty 10
:req
{:sku 123 :qty-requested 123}
:the-reason-why :limit
:data (ba/byte-array [66 67])
:other-data (ba/byte-array [123 123])}
{:qty-requested 4
:qty-added 4
:current-qty 4
:req
{:sku 10 :qty-requested 4}
:the-reason-why :all
:data (ba/byte-array [100 110])
:other-data (ba/byte-array [64 74])}]
encoded (l/serialize rsps-schema data)
decoded (l/deserialize-same rsps-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [4 2 246 1 2 8 2 20 246 1 2 246 1 4 66 67 2 4 123 123
2 8 2 8 2 8 20 2 8 0 100 110 2 4 64 74 0])
encoded))
(is (= (xf-byte-arrays data)
(xf-byte-arrays decoded)))))
(deftest test-nested-map-schema
#?(:clj (is (fp-matches? nested-map-schema)))
(is (= {:type :map
:values
{:name :deercreeklabs.unit.lancaster-test/add-to-cart-rsp
:type :record
:fields
[{:name :qty-requested :type [:null :int] :default nil}
{:name :qty-added :type [:null :int] :default nil}
{:name :current-qty :type [:null :int] :default nil}
{:name :req
:type {:name :deercreeklabs.unit.lancaster-test/add-to-cart-req
:type :record
:fields [{:name :sku :type :int :default -1}
{:name :qty-requested
:type [:null :int]
:default nil}]}
:default {:sku 10 :qty-requested nil}}
{:name :the-reason-why
:type {:name :deercreeklabs.unit.lancaster-test/why
:type :enum
:symbols [:all :stock :limit]
:default :all}
:default :stock}
{:name :data
:type
{:name :deercreeklabs.unit.lancaster-test/a-fixed
:type :fixed
:size 2}
:default "MX"}
{:name :other-data
:type [:null :bytes]
:default nil}]}}
(l/edn nested-map-schema)))
(is (= "-6484319793187085262"
(u/long->str (l/fingerprint64 nested-map-schema)))))
(deftest test-nested-map-schema-serdes
(let [data {"A" {:qty-requested 123
:qty-added 4
:current-qty 10
:req {:sku 123
:qty-requested 123}
:the-reason-why :limit
:data (ba/byte-array [66 67])
:other-data (ba/byte-array [123 123])}
"B" {:qty-requested 4
:qty-added 4
:current-qty 4
:req {:sku 10
:qty-requested 4}
:the-reason-why :all
:data (ba/byte-array [100 110])
:other-data (ba/byte-array [64 74])}}
encoded (l/serialize nested-map-schema data)
decoded (l/deserialize-same nested-map-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [4 2 65 2 246 1 2 8 2 20 246 1 2 246 1 4 66 67 2 4 123
123 2 66 2 8 2 8 2 8 20 2 8 0 100 110 2 4 64 74 0])
encoded))
(is (= (xf-byte-arrays data)
(xf-byte-arrays decoded)))))
(deftest test-empty-map-serdes
(let [sch (l/map-schema l/int-schema)
data {}
encoded (l/serialize sch data)
_ (is (ba/equivalent-byte-arrays?
(ba/byte-array [0])
encoded))
decoded (l/deserialize-same sch encoded)]
(is (= data decoded))))
(deftest test-union-schema
#?(:clj (is (fp-matches? union-schema)))
(is (= [:int
{:name :deercreeklabs.unit.lancaster-test/add-to-cart-req
:type :record
:fields [{:name :sku
:type :int
:default -1}
{:name :qty-requested
:type [:null :int]
:default nil}]}
{:name :deercreeklabs.unit.lancaster-test/a-fixed
:type :fixed
:size 2}]
(l/edn union-schema)))
(is (= "-193173046069528093"
(u/long->str (l/fingerprint64 union-schema)))))
(deftest test-union-schema-serdes
(let [data {:sku 123 :qty-requested 4}
encoded (l/serialize union-schema data)
decoded (l/deserialize-same union-schema encoded)
_ (is (ba/equivalent-byte-arrays? (ba/byte-array [2 246 1 2 8])
encoded))
_ (is (= data decoded))
data 5
encoded (l/serialize union-schema data)
decoded (l/deserialize-same union-schema encoded)]
(is (ba/equivalent-byte-arrays? (ba/byte-array [0 10])
encoded))
(is (= data decoded))))
(deftest test-union-schema-w-multiple-records
#?(:clj (is (fp-matches? person-or-dog-schema)))
(is (= [{:name :deercreeklabs.unit.lancaster-test/person
:type :record
:fields
[{:name :person/name :type :string :default "No name"}
{:name :person/age :type :int :default 0}]}
{:name :deercreeklabs.unit.lancaster-test/dog
:type :record
:fields
[{:name :dog/name :type [:null :string] :default nil}
{:name :dog/owner :type [:null :string] :default nil}]}]
(l/edn person-or-dog-schema)))
(is (= "-5174754347720548939"
(u/long->str (l/fingerprint64 person-or-dog-schema)))))
(deftest test-multi-record-union-schema-serdes
(let [data #:dog{:name "F<NAME>" :owner "<NAME>"}
encoded (l/serialize person-or-dog-schema data)
decoded (l/deserialize-same person-or-dog-schema encoded)
_ (is (ba/equivalent-byte-arrays?
(ba/byte-array [2 2 8 70 105 100 111 2 8 90 97 99 104])
encoded))
_ (is (= data decoded))
data #:person{:name "<NAME>" :age 50}
encoded (l/serialize person-or-dog-schema data)
decoded (l/deserialize-same person-or-dog-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [0 8 66 105 108 108 100])
encoded))
(is (= data decoded))))
(deftest test-multi-record-schema-serdes-non-existent
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"does not match any schema in the union schema"
(l/serialize person-or-dog-schema {:k 1}))))
(deftest test-map-or-array-schema
#?(:clj (is (fp-matches? map-or-array-schema)))
(is (= [{:type :map :values :int}
{:type :array :items :string}]
(l/edn map-or-array-schema)))
(is (= "4441440791563688855"
(u/long->str (l/fingerprint64 map-or-array-schema)))))
(deftest test-map-or-array-schema-serdes
(let [data {"<NAME>" 22 "<NAME>" 88}
encoded (l/serialize map-or-array-schema data)
decoded (l/deserialize-same map-or-array-schema encoded)
_ (is (ba/equivalent-byte-arrays?
(ba/byte-array [0 4 8 90 101 107 101 44 14 65 100 101 108 105
110 101 -80 1 0])
encoded))
_ (is (= data decoded))
data ["a thing" "another thing"]
encoded (l/serialize map-or-array-schema data)
decoded (l/deserialize-same map-or-array-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [2 4 14 97 32 116 104 105 110 103 26 97 110
111 116 104 101 114 32 116 104 105 110 103 0])
encoded))
(is (= data decoded))))
(deftest test-mopodoa-schema
#?(:clj (is (fp-matches? mopodoa-schema)))
(is (= [{:type :map :values :int}
{:name :deercreeklabs.unit.lancaster-test/person
:type :record
:fields [{:name :person/name
:type :string
:default "No name"}
{:name :person/age
:type :int
:default 0}]}
{:name :deercreeklabs.unit.lancaster-test/dog
:type :record
:fields [{:name :dog/name
:type [:null :string]
:default nil}
{:name :dog/owner
:type [:null :string]
:default nil}]}
{:type :array :items :string}]
(l/edn mopodoa-schema)))
(is (= "-2196893583124300899"
(u/long->str (l/fingerprint64 mopodoa-schema)))))
(deftest test-mopodoa-schema-serdes
(let [data {"<NAME>" 22 "<NAME>" 88}
encoded (l/serialize mopodoa-schema data)
decoded (l/deserialize-same mopodoa-schema encoded)
_ (is (ba/equivalent-byte-arrays?
(ba/byte-array [0 4 8 90 101 107 101 44 14 65 100 101 108 105
110 101 -80 1 0])
encoded))
_ (is (= data decoded))
data ["a thing" "another thing"]
encoded (l/serialize mopodoa-schema data)
decoded (l/deserialize-same mopodoa-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [6 4 14 97 32 116 104 105 110 103 26 97 110
111 116 104 101 114 32 116 104 105 110 103 0])
encoded))
(is (= data decoded))))
(deftest test-recursive-schema
(is (= {:name :deercreeklabs.unit.lancaster-test/tree
:type :record
:fields
[{:name :value :type :int :default -1}
{:name :right
:type [:null :tree]
:default nil}
{:name :left
:type [:null :tree]
:default nil}]}
(l/edn tree-schema)))
#?(:clj (is (fp-matches? tree-schema)))
(is (= "-3297333764539234889"
(u/long->str (l/fingerprint64 tree-schema)))))
(deftest test-edn-schemas-match?-recursive-schema
(is (u/edn-schemas-match? (l/edn tree-schema) (l/edn tree-schema) {} {})))
(deftest test-recursive-schema-serdes
(let [data {:value 5
:right {:value -10
:right {:value -20}}
:left {:value 10
:left {:value 20
:left {:value 40}}}}
encoded (l/serialize tree-schema data)
decoded (l/deserialize-same tree-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [10 2 19 2 39 0 0 0 2 20 0 2 40 0 2 80 0 0])
encoded))
(is (= data decoded))))
(deftest test-rec-w-array-and-enum-schema
#?(:clj (is (fp-matches? rec-w-array-and-enum-schema)))
(is (= {:name :deercreeklabs.unit.lancaster-test/rec-w-array-and-enum
:type :record
:fields
[{:name :names
:type {:type :array :items :string}
:default []}
{:name :why
:type [:null
{:default :all
:name :deercreeklabs.unit.lancaster-test/why
:symbols [:all :stock :limit]
:type :enum}]
:default nil}]}
(l/edn rec-w-array-and-enum-schema)))
(is (= "-7358640627267953104"
(u/long->str (l/fingerprint64
rec-w-array-and-enum-schema)))))
(deftest test-rec-w-array-and-enum-serdes
(let [data {:names ["<NAME>" "<NAME>" "<NAME>"]
:why :stock}
encoded (l/serialize rec-w-array-and-enum-schema data)
decoded (l/deserialize-same rec-w-array-and-enum-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [6 8 65 114 105 97 8 66 101 116 104 10 67 105 110 100
121 0 2 2])
encoded))
(is (= data decoded))))
(deftest test-rec-w-map-schema
#?(:clj (is (fp-matches? rec-w-map-schema)))
(is (= {:name :deercreeklabs.unit.lancaster-test/rec-w-map
:type :record
:fields [{:name :name-to-age
:type [:null {:type :map
:values :int}]
:default nil}
{:name :what
:type [:null :string]
:default nil}]}
(l/edn rec-w-map-schema)))
(is (= "1679652566194036700"
(u/long->str (l/fingerprint64
rec-w-map-schema)))))
(deftest test-rec-w-map-serdes
(let [data {:name-to-age {"<NAME>" 22
"<NAME>" 33
"<NAME>" 44}
:what "yo"}
encoded (l/serialize rec-w-map-schema data)
decoded (l/deserialize-same rec-w-map-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [2 6 8 65 114 105 97 44 8 66 101 116 104 66 10 67 105
110 100 121 88 0 2 4 121 111])
encoded))
(is (= data decoded))))
(deftest test-rec-w-fixed-no-default
#?(:clj (is (fp-matches? rec-w-fixed-no-default-schema)))
(is (= {:name :deercreeklabs.unit.lancaster-test/rec-w-fixed-no-default
:type :record
:fields
[{:name :data
:type
{:name :deercreeklabs.unit.lancaster-test/a-fixed
:type :fixed
:size 2}
:default "\0\0"}]}
(l/edn rec-w-fixed-no-default-schema)))
(is (= "-6875395607105571061"
(u/long->str (l/fingerprint64
rec-w-fixed-no-default-schema)))))
(deftest test-rec-w-fixed-no-default-serdes
(let [data {:data (ba/byte-array [1 2])}
encoded (l/serialize rec-w-fixed-no-default-schema data)
decoded (l/deserialize-same rec-w-fixed-no-default-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [1 2])
encoded))
(is (ba/equivalent-byte-arrays?
(:data data)
(:data decoded)))))
(deftest test-rec-w-maybe-field
#?(:clj (is (fp-matches? rec-w-maybe-field-schema)))
(is (= {:name :deercreeklabs.unit.lancaster-test/rec-w-maybe-field
:type :record
:fields [{:name :name
:type [:null :string]
:default nil}
{:name :age
:type [:null :int]
:default nil}]}
(l/edn rec-w-maybe-field-schema)))
(is (= "-5686522258470805846"
(u/long->str (l/fingerprint64 rec-w-maybe-field-schema)))))
(deftest test-record-serdes-missing-field
(let [data {:qty-requested 100}]
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Record data is missing key `:sku`"
(l/serialize add-to-cart-req-schema data)))))
(deftest test-record-serdes-missing-maybe-field
(let [data {:name "<NAME>"}
encoded (l/serialize rec-w-maybe-field-schema data)
decoded (l/deserialize-same rec-w-maybe-field-schema encoded)]
(is (= data decoded))))
(deftest test-schema?
(is (l/schema? person-or-dog-schema))
(is (not (l/schema? :foo))))
(deftest test-bad-serialize-arg
(s/without-fn-validation ;; Allow built-in handlers to throw
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"First argument to serialize must be a schema object"
(l/serialize nil nil)))))
(deftest test-bad-deserialize-args
(s/without-fn-validation ;; Allow built-in handlers to throw
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"First argument to deserialize must be a schema object"
(l/deserialize nil nil nil)))
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Second argument to deserialize must be a "
(l/deserialize why-schema nil (ba/byte-array []))))
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"argument to deserialize must be a byte array"
(l/deserialize why-schema why-schema [])))))
(deftest test-field-default-validation
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Bad default value for field `:int-field`. Got `a`."
(l/record-schema :test-schema
[[:int-field l/int-schema "a"]]))))
(deftest test-default-data
(is (= :all (l/default-data why-schema)))
(is (= {:sku -1
:qty-requested nil}
(l/default-data add-to-cart-req-schema))))
(deftest test-bad-field-name
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Name keywords must start with a letter and subsequently"
(l/record-schema :test-schema
[[:bad? l/boolean-schema]]))))
(deftest test-bad-record-name
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Name keywords must start with a letter and subsequently"
(l/record-schema :*test-schema*
[[:is-good l/boolean-schema]]))))
(deftest test-duplicate-field-name
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Field names must be unique."
(l/record-schema :test-schema
[[:int-field l/int-schema]
[:int-field l/int-schema]]))))
(deftest test-good-union
(let [sch1 (l/record-schema ::sch1 [[:a l/int-schema]
[:b l/string-schema]])
sch2 (l/record-schema ::sch2 [[:different-ns/b l/string-schema]])
sch3 (l/union-schema [sch1 sch2])]
(is (round-trip? sch3 {:different-ns/b "hi"}))
(is (round-trip? sch3 {:a 1 :b "hi"}))))
(deftest test-bad-union
(let [sch1 (l/record-schema ::sch1 [[:a l/int-schema]
[:b l/string-schema]])
sch2 (l/record-schema ::sch2 [[:b l/string-schema]])]
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Ambiguous union"
(l/union-schema [sch1 sch2])))))
(deftest test-serialize-bad-union-member
(let [schema (l/union-schema [l/null-schema l/int-schema])]
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"does not match any schema in the union schema"
(l/serialize schema :foo)))))
(deftest test-maybe-w-union-arg
(let [schema-1 (l/maybe (l/union-schema [l/int-schema l/string-schema]))
schema-2 (l/maybe (l/union-schema [l/null-schema l/int-schema]))]
(is (round-trip? schema-1 nil))
(is (round-trip? schema-2 nil))
(is (round-trip? schema-1 34))
(is (round-trip? schema-2 34))))
(deftest test-more-than-one-numeric-type-in-a-union
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Unions may not contain more than one numeric schema"
(l/union-schema [l/int-schema l/float-schema]))))
(deftest test-more-than-one-bytes-type-in-a-union
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Unions may not contain more than one byte-array schema"
(l/union-schema [l/bytes-schema (l/fixed-schema :foo 16)]))))
(deftest test-serialize-empty-map-multi-rec-union
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Record data is missing key `:person/name`"
(l/serialize person-or-dog-schema {}))))
(deftest test-map-and-rec-union
(let [schema (l/union-schema [(l/map-schema l/int-schema) person-schema])]
(is (round-trip? schema {"foo" 1}))
(is (round-trip? schema #:person{:name "<NAME>" :age 18}))))
(deftest test-ns-enum
(is (round-trip? suit-schema :suit/spades))
(is (= {:name :deercreeklabs.unit.lancaster-test/suit
:type :enum
:symbols [:suit/hearts :suit/clubs :suit/spades :suit/diamonds]
:default :suit/hearts}
(l/edn suit-schema)))
(is (= (str "{\"name\":\"deercreeklabs.unit.lancaster_test.Suit\",\"type\":"
"\"enum\",\"symbols\":[\"HEARTS\",\"CLUBS\",\"SPADES\","
"\"DIAMONDS\"],\"default\":\"HEARTS\"}")
(l/json suit-schema))))
(deftest test-identical-schemas-in-union
(let [sch1 (l/enum-schema ::a-name [:a :b])
sch2 (l/enum-schema ::a-name [:a :b])]
(is (not= sch1 sch2))
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Identical schemas in union"
(l/union-schema [l/string-schema sch1 sch2])))))
(deftest test-schemas-match?
(let [sch1 (l/enum-schema ::a-name [:a :b])
sch2 (l/enum-schema ::a-name [:a :b])
sch3 (l/enum-schema ::x-name [:a :b])]
(is (l/schemas-match? sch1 sch2))
(is (not (l/schemas-match? sch1 sch3)))))
(deftest test-missing-record-field
(let [sch1 (l/record-schema ::test [[:a :required l/int-schema]])
sch2 (l/union-schema [l/int-schema sch1])
sch3 (l/record-schema ::sch3 [[:arg sch2]])
sch4 (l/array-schema sch3)]
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Record data is missing key `:a`"
(l/serialize sch1 {:b 1})))
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Record data is missing key `:a`"
(l/serialize sch2 {:b 1})))
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Record data is missing key `:a`"
(l/serialize sch3 {:arg {:b 1}})))
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Record data is missing key `:a`"
(l/serialize sch4 [{:arg {:a 1}}
{:arg {:b 1}}])))))
(deftest serialize-small-double-into-float-union
(let [sch (l/union-schema [l/null-schema l/float-schema])
v (double 6.0)
encoded (l/serialize sch v)
decoded (l/deserialize-same sch encoded)]
(is (= v decoded))))
(deftest serialize-long-into-union
(let [sch (l/union-schema [l/null-schema l/long-schema])
v (u/str->long "-5442038735385698765")
encoded (l/serialize sch v)
decoded (l/deserialize-same sch encoded)]
(is (= v decoded))))
(deftest serialize-lazy-sequence-into-union
(let [sch (l/union-schema [l/null-schema (l/array-schema l/int-schema)])
v (map identity [42 681 1024]) ; Make a lazy seq
encoded (l/serialize sch v)
decoded (l/deserialize-same sch encoded)]
(is (= v decoded))))
(deftest test-rt-set
(let [sch l/string-set-schema
v #{"a" "b" "1234" "c45"}
encoded (l/serialize sch v)
decoded (l/deserialize-same sch encoded)]
(is (= v decoded))))
(deftest test-bad-set-type
(let [sch l/string-set-schema
v #{"2" :k}] ;; not strictly string members
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Set element `:k` .* is not a valid string"
(l/serialize sch v)))))
(deftest test-bad-set-type-map-of-nils
(let [sch (l/map-schema l/null-schema) ;; equivalent to l/string-set-schema
v {"a" nil "b" nil}] ;; Must be a set
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"is not a valid Clojure set"
(l/serialize sch v)))))
| true | (ns deercreeklabs.unit.lancaster-test
(:require
[clojure.test :refer [deftest is]]
[clojure.walk :as walk]
[deercreeklabs.baracus :as ba]
[deercreeklabs.lancaster :as l]
[deercreeklabs.lancaster.pcf-utils :as pcf-utils]
[deercreeklabs.lancaster.utils :as u]
[schema.core :as s :include-macros true])
#?(:clj
(:import
(clojure.lang ExceptionInfo)
(org.apache.avro Schema
SchemaNormalization
Schema$Parser))))
;; Use this instead of fixtures, which are hard to make work w/ async testing.
(s/set-fn-validation! true)
(defn abs-err [expected actual]
(let [err (- expected actual)]
(if (neg? err)
(- err)
err)))
(defn rel-err [expected actual]
(/ (abs-err expected actual) expected))
(defn xf-byte-arrays
[edn]
(walk/postwalk #(if (ba/byte-array? %)
(u/byte-array->byte-str %)
%)
edn))
#?(:clj
(defn fp-matches? [schema]
(let [json-schema (l/json schema)
parser (Schema$Parser.)
java-schema (.parse parser ^String json-schema)
java-fp (SchemaNormalization/parsingFingerprint64 java-schema)
clj-fp (l/fingerprint64 schema)]
(or (= java-fp clj-fp)
(let [java-pcf (SchemaNormalization/toParsingForm java-schema)
clj-pcf (l/pcf schema)
err-str (str "Fingerprints do not match!\n"
"java-fp: " java-fp "\n"
"clj-fp: " clj-fp "\n"
"java-pcf:\n" java-pcf "\n"
"clj-pcf:\n" clj-pcf "\n")]
(println err-str))))))
(defn round-trip? [schema data]
(let [serialized (l/serialize schema data)
deserialized (l/deserialize-same schema serialized)]
(= data deserialized)))
(l/def-record-schema add-to-cart-req-schema
[:sku :required l/int-schema]
[:qty-requested l/int-schema])
(def add-to-cart-req-v2-schema
(l/record-schema ::add-to-cart-req
[[:sku l/int-schema]
[:qty-requested l/int-schema]
[:note l/string-schema]]))
(def add-to-cart-req-v3-schema ;; qtys are floats!
(l/record-schema ::add-to-cart-req
[[:sku l/int-schema]
[:qty-requested l/float-schema]
[:note l/string-schema]]))
(def add-to-cart-req-v4-schema
(l/record-schema ::add-to-cart-req
[[:sku l/int-schema]
[:qty-requested l/int-schema]
[:comment l/string-schema]]))
(l/def-enum-schema why-schema
:all :stock :limit)
(l/def-enum-schema suit-schema
:suit/hearts :suit/clubs :suit/spades :suit/diamonds)
(l/def-fixed-schema a-fixed-schema
2)
(l/def-maybe-schema maybe-int-schema
l/int-schema)
(l/def-record-schema rec-w-maybe-field-schema
[:name l/string-schema]
[:age maybe-int-schema])
(l/def-record-schema rec-w-fixed-no-default-schema
[:data :required a-fixed-schema])
(l/def-record-schema add-to-cart-rsp-schema
[:qty-requested l/int-schema]
[:qty-added l/int-schema]
[:current-qty l/int-schema]
[:req :required add-to-cart-req-schema {:sku 10 :qty-requested 1}]
[:the-reason-why :required why-schema :stock]
[:data :required a-fixed-schema (ba/byte-array [77 88])]
[:other-data l/bytes-schema])
(l/def-array-schema simple-array-schema
l/string-schema)
(l/def-array-schema rsps-schema
add-to-cart-rsp-schema)
(l/def-record-schema rec-w-array-and-enum-schema
[:names :required simple-array-schema]
[:why why-schema])
(l/def-map-schema ages-schema
l/int-schema)
(l/def-record-schema rec-w-map-schema
[:name-to-age ages-schema]
[:what l/string-schema])
(l/def-map-schema nested-map-schema
add-to-cart-rsp-schema)
(l/def-union-schema union-schema
l/int-schema add-to-cart-req-schema a-fixed-schema)
(l/def-record-schema person-schema
[:person/name :required l/string-schema "No name"]
[:person/age :required l/int-schema 0])
(l/def-record-schema dog-schema
[:dog/name l/string-schema]
[:dog/owner l/string-schema])
(def dog-v2-schema
(l/record-schema ::dog
[[:dog/name l/string-schema]
[:dog/owner l/string-schema]
[:dog/tag-number l/int-schema]]))
(l/def-record-schema fish-schema
[:fish/name l/string-schema]
[:tank-num l/int-schema])
(l/def-union-schema person-or-dog-schema
person-schema dog-schema)
(l/def-union-schema fish-or-person-or-dog-v2-schema
fish-schema person-schema dog-v2-schema)
(l/def-union-schema map-or-array-schema
ages-schema simple-array-schema)
(l/def-union-schema mopodoa-schema
ages-schema person-schema dog-schema simple-array-schema)
(l/def-record-schema date-schema
[:year l/int-schema]
[:month l/int-schema]
[:day l/int-schema])
(l/def-record-schema time-schema
[:hour l/int-schema]
[:minute l/int-schema]
[:second (l/maybe l/int-schema)])
(l/def-record-schema date-time-schema
;; Note that this does not include seconds.
[:year l/int-schema]
[:month l/int-schema]
[:day l/int-schema]
[:hour l/int-schema]
[:minute l/int-schema])
(l/def-record-schema tree-schema
[:value :required l/int-schema]
[:right :tree]
[:left :tree])
(deftest test-record-schema
(let [expected-pcf (str
"{\"name\":\"deercreeklabs.unit.lancaster_test."
"AddToCartReq\",\"type\":\"record\",\"fields\":"
"[{\"name\":\"sku\",\"type\":\"int\"},{\"name\":"
"\"qtyRequested\",\"type\":[\"null\",\"int\"]}]}")
expected-edn {:name :deercreeklabs.unit.lancaster-test/add-to-cart-req
:type :record
:fields
[{:name :sku
:type :int
:default -1}
{:name :qty-requested
:type [:null :int]
:default nil}]}]
#?(:clj (is (fp-matches? add-to-cart-req-schema)))
(is (= "3703990475150151424"
(u/long->str (l/fingerprint64 add-to-cart-req-schema))))
(is (= expected-edn (l/edn add-to-cart-req-schema)))
(is (= expected-pcf (l/pcf
add-to-cart-req-schema)))))
(deftest test-def-record-schema-serdes
(let [data {:sku 123
:qty-requested 5}
encoded (l/serialize add-to-cart-req-schema data)
decoded (l/deserialize-same add-to-cart-req-schema encoded)]
(is (= "9gECCg==" (ba/byte-array->b64 encoded)))
(is (= data decoded))))
(deftest test-def-record-schema-mixed-ns
(is (= {:name :deercreeklabs.unit.lancaster-test/fish
:type :record
:fields [{:name :fish/name
:type [:null :string]
:default nil}
{:name :tank-num
:type [:null :int]
:default nil}]}
(l/edn fish-schema)))
(is (= (str
"{\"name\":\"deercreeklabs.unit.lancaster_test.Fish\",\"type\":"
"\"record\",\"fields\":[{\"name\":\"fishName\",\"type\":[\"null\","
"\"string\"],\"default\":null},{\"name\":\"tankNum\",\"type\":"
"[\"null\",\"int\"],\"default\":null}]}")
(l/json fish-schema))))
(deftest test-def-enum-schema
(is (= {:name :deercreeklabs.unit.lancaster-test/why
:type :enum
:symbols [:all :stock :limit]
:default :all}
(l/edn why-schema)))
#?(:clj (is (fp-matches? why-schema)))
(is (= (str "{\"name\":\"deercreeklabs.unit.lancaster_test.Why\",\"type\":"
"\"enum\",\"symbols\":[\"ALL\",\"STOCK\",\"LIMIT\"],\"default\":"
"\"ALL\"}")
(l/json why-schema)))
(is (= (str "{\"name\":\"deercreeklabs.unit.lancaster_test.Why\",\"type\":"
"\"enum\",\"symbols\":[\"ALL\",\"STOCK\",\"LIMIT\"]}")
(l/pcf why-schema)))
(is (= "3321246333858425949"
(u/long->str (l/fingerprint64 why-schema)))))
(deftest test-def-enum-schema-serdes
(let [data :stock
encoded (l/serialize why-schema data)
decoded (l/deserialize-same why-schema encoded)]
(is (ba/equivalent-byte-arrays? (ba/byte-array [2]) encoded))
(is (= data decoded))))
(deftest test-def-fixed-schema
(is (= {:name :deercreeklabs.unit.lancaster-test/a-fixed
:type :fixed
:size 2}
(l/edn a-fixed-schema)))
#?(:clj (is (fp-matches? a-fixed-schema)))
(is (= (str "{\"name\":\"deercreeklabs.unit.lancaster_test.AFixed\",\"type\":"
"\"fixed\",\"size\":2}")
(l/pcf a-fixed-schema)))
(is (= "-1031156250377191762"
(u/long->str (l/fingerprint64 a-fixed-schema)))))
(deftest test-def-fixed-schema-serdes
(let [data (ba/byte-array [12 24])
encoded (l/serialize a-fixed-schema data)
decoded (l/deserialize-same a-fixed-schema encoded)]
(is (ba/equivalent-byte-arrays?
data encoded))
(is (ba/equivalent-byte-arrays? data decoded))))
(deftest test-nested-record-schema
(let [expected {:name :deercreeklabs.unit.lancaster-test/add-to-cart-rsp
:type :record
:fields
[{:name :qty-requested
:type [:null :int]
:default nil}
{:name :qty-added
:type [:null :int]
:default nil}
{:name :current-qty
:type [:null :int]
:default nil}
{:name :req
:type
{:name :deercreeklabs.unit.lancaster-test/add-to-cart-req
:type :record
:fields [{:name :sku :type :int :default -1}
{:name :qty-requested
:type [:null :int]
:default nil}]}
:default {:sku 10
:qty-requested nil}}
{:name :the-reason-why
:type {:name :deercreeklabs.unit.lancaster-test/why
:type :enum
:symbols [:all :stock :limit]
:default :all}
:default :stock}
{:name :data
:type {:name :deercreeklabs.unit.lancaster-test/a-fixed
:type :fixed
:size 2}
:default "MX"}
{:name :other-data
:type [:null :bytes]
:default nil}]}]
#?(:clj (is (fp-matches? add-to-cart-rsp-schema)))
(is (= (str
"{\"name\":\"deercreeklabs.unit.lancaster_test.AddToCartRsp\","
"\"type\":\"record\",\"fields\":[{\"name\":\"qtyRequested\","
"\"type\":[\"null\",\"int\"]},{\"name\":\"qtyAdded\",\"type\":"
"[\"null\",\"int\"]},{\"name\":\"currentQty\",\"type\":[\"null\","
"\"int\"]},{\"name\":\"req\",\"type\":{\"name\":\"deercreeklabs."
"unit.lancaster_test.AddToCartReq\",\"type\":\"record\",\"fields\":"
"[{\"name\":\"sku\",\"type\":\"int\"},{\"name\":\"qtyRequested\","
"\"type\":[\"null\",\"int\"]}]}},{\"name\":\"theReasonWhy\","
"\"type\":{\"name\":\"deercreeklabs.unit.lancaster_test.Why\","
"\"type\":\"enum\",\"symbols\":[\"ALL\",\"STOCK\",\"LIMIT\"]}},"
"{\"name\":\"data\",\"type\":{\"name\":\"deercreeklabs.unit."
"lancaster_test.AFixed\",\"type\":\"fixed\",\"size\":2}},"
"{\"name\":\"otherData\",\"type\":[\"null\",\"bytes\"]}]}")
(l/pcf add-to-cart-rsp-schema)))
(is (= expected (l/edn add-to-cart-rsp-schema))))
(is (= "3835051015389218749"
(u/long->str (l/fingerprint64 add-to-cart-rsp-schema)))))
(deftest test-nested-record-serdes
(let [data {:qty-requested 123
:qty-added 10
:current-qty 10
:req {:sku 123
:qty-requested 123}
:the-reason-why :limit
:data (ba/byte-array [66 67])
:other-data (ba/byte-array [123 123])}
encoded (l/serialize add-to-cart-rsp-schema data)
decoded (l/deserialize-same add-to-cart-rsp-schema
encoded)]
(is (= "AvYBAhQCFPYBAvYBBEJDAgR7ew==" (ba/byte-array->b64 encoded)))
(is (= (xf-byte-arrays data)
(xf-byte-arrays decoded)))))
(deftest test-null-schema
(let [data nil
encoded (l/serialize l/null-schema data)
decoded (l/deserialize-same l/null-schema encoded)]
#?(:clj (is (fp-matches? l/null-schema)))
(is (ba/equivalent-byte-arrays? (ba/byte-array []) encoded))
(is (= data decoded))))
(deftest test-boolean-schema
(let [data true
encoded (l/serialize l/boolean-schema data)
decoded (l/deserialize-same l/boolean-schema encoded)]
#?(:clj (is (fp-matches? l/boolean-schema)))
(is (ba/equivalent-byte-arrays? (ba/byte-array [1]) encoded))
(is (= data decoded))))
(deftest test-int-schema-serdes
(let [data 7890
encoded (l/serialize l/int-schema data)
decoded (l/deserialize-same l/int-schema encoded)]
#?(:clj (is (fp-matches? l/int-schema)))
(is (ba/equivalent-byte-arrays? (ba/byte-array [-92 123]) encoded))
(is (= data decoded))))
(deftest test-long-schema-serdes
(let [data (u/ints->long 2147483647 -1)
encoded (l/serialize l/long-schema data)
decoded (l/deserialize-same l/long-schema encoded)]
#?(:clj (is (fp-matches? l/long-schema)))
(is (ba/equivalent-byte-arrays?
(ba/byte-array [-2 -1 -1 -1 -1 -1 -1 -1 -1 1])
encoded))
(is (= data decoded))))
(deftest test-int->long
(let [in (int -1)
l (u/int->long in)]
(is (= "-1" (u/long->str l)))))
(deftest test-float-schema
(let [data (float 3.14159)
encoded (l/serialize l/float-schema data)
decoded (l/deserialize-same l/float-schema encoded)
abs-err (abs-err data decoded)]
#?(:clj (is (fp-matches? l/float-schema)))
(is (ba/equivalent-byte-arrays? (ba/byte-array [-48 15 73 64]) encoded))
(is (< abs-err 0.000001))))
(deftest test-double-schema
(let [data (double 3.14159265359)
encoded (l/serialize l/double-schema data)
decoded (l/deserialize-same l/double-schema encoded)
abs-err (abs-err data decoded)]
#?(:clj (is (fp-matches? l/double-schema)))
(is (ba/equivalent-byte-arrays? (ba/byte-array [-22 46 68 84 -5 33 9 64])
encoded))
(is (< abs-err 0.000001))))
(deftest test-bytes-schema
(let [data (ba/byte-array [1 1 2 3 5 8 13 21])
encoded (l/serialize l/bytes-schema data)
decoded (l/deserialize-same l/bytes-schema encoded)]
#?(:clj (is (fp-matches? l/bytes-schema)))
(is (ba/equivalent-byte-arrays? (ba/byte-array [16 1 1 2 3 5 8 13 21])
encoded))
(is (ba/equivalent-byte-arrays? data decoded))))
(deftest test-string-schema
(let [data "Hello world!"
encoded (l/serialize l/string-schema data)
decoded (l/deserialize-same l/string-schema encoded)]
#?(:clj (is (fp-matches? l/string-schema)))
(is (ba/equivalent-byte-arrays?
(ba/byte-array [24 72 101 108 108 111 32 119 111 114 108 100 33])
encoded))
(is (= data decoded))))
(deftest test-def-map-schema
(is (= {:type :map :values :int}
(l/edn ages-schema)))
#?(:clj (is (fp-matches? ages-schema)))
(is (= "{\"type\":\"map\",\"values\":\"int\"}"
(l/pcf ages-schema)))
(is (= "-2649837581481768589"
(u/long->str (l/fingerprint64 ages-schema)))))
(deftest test-map-schema-serdes
(let [data {"PI:NAME:<NAME>END_PI" 50
"PI:NAME:<NAME>END_PI" 55
"PI:NAME:<NAME>END_PI" 89}
encoded (l/serialize ages-schema data)
decoded (l/deserialize-same ages-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [6 10 65 108 105 99 101 100 6 66 111 98 110 8
67 104 97 100 -78 1 0])
encoded))
(is (= data decoded))))
(deftest test-def-array-schema
#?(:clj (is (fp-matches? simple-array-schema)))
(is (= {:type :array :items :string}
(l/edn simple-array-schema)))
(is (= "{\"type\":\"array\",\"items\":\"string\"}"
(l/pcf simple-array-schema)))
(is (= "-3577210133426481249"
(u/long->str (l/fingerprint64 simple-array-schema)))))
(deftest test-array-schema-serdes
(let [names ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]
encoded (l/serialize simple-array-schema names)
decoded (l/deserialize-same simple-array-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [6 18 70 101 114 100 105 110 97 110 100 8 79
109 97 114 6 76 105 110 0])
encoded))
(is (= names decoded))))
(deftest test-empty-array-serdes
(let [sch (l/array-schema l/int-schema)
data []
encoded (l/serialize sch data)
_ (is (ba/equivalent-byte-arrays?
(ba/byte-array [0])
encoded))
decoded (l/deserialize-same sch encoded)]
(is (= data decoded))))
(deftest test-nested-array-schema
#?(:clj (is (fp-matches? rsps-schema)))
(is (= {:type :array
:items
{:name :deercreeklabs.unit.lancaster-test/add-to-cart-rsp
:type :record
:fields
[{:name :qty-requested
:type [:null :int]
:default nil}
{:name :qty-added
:type [:null :int]
:default nil}
{:name :current-qty
:type [:null :int]
:default nil}
{:name :req
:type {:name :deercreeklabs.unit.lancaster-test/add-to-cart-req
:type :record
:fields [{:name :sku
:type :int
:default -1}
{:name :qty-requested
:type [:null :int]
:default nil}]}
:default {:sku 10 :qty-requested nil}}
{:name :the-reason-why
:type {:name :deercreeklabs.unit.lancaster-test/why
:type :enum
:symbols [:all :stock :limit]
:default :all}
:default :stock}
{:name :data
:type
{:name :deercreeklabs.unit.lancaster-test/a-fixed
:type :fixed
:size 2}
:default "MX"}
{:name :other-data
:type [:null :bytes]
:default nil}]}}
(l/edn rsps-schema)))
(is (= "3719708605096203323"
(u/long->str (l/fingerprint64 rsps-schema)))))
(deftest test-nested-array-schema-serdes
(let [data [{:qty-requested 123
:qty-added 4
:current-qty 10
:req
{:sku 123 :qty-requested 123}
:the-reason-why :limit
:data (ba/byte-array [66 67])
:other-data (ba/byte-array [123 123])}
{:qty-requested 4
:qty-added 4
:current-qty 4
:req
{:sku 10 :qty-requested 4}
:the-reason-why :all
:data (ba/byte-array [100 110])
:other-data (ba/byte-array [64 74])}]
encoded (l/serialize rsps-schema data)
decoded (l/deserialize-same rsps-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [4 2 246 1 2 8 2 20 246 1 2 246 1 4 66 67 2 4 123 123
2 8 2 8 2 8 20 2 8 0 100 110 2 4 64 74 0])
encoded))
(is (= (xf-byte-arrays data)
(xf-byte-arrays decoded)))))
(deftest test-nested-map-schema
#?(:clj (is (fp-matches? nested-map-schema)))
(is (= {:type :map
:values
{:name :deercreeklabs.unit.lancaster-test/add-to-cart-rsp
:type :record
:fields
[{:name :qty-requested :type [:null :int] :default nil}
{:name :qty-added :type [:null :int] :default nil}
{:name :current-qty :type [:null :int] :default nil}
{:name :req
:type {:name :deercreeklabs.unit.lancaster-test/add-to-cart-req
:type :record
:fields [{:name :sku :type :int :default -1}
{:name :qty-requested
:type [:null :int]
:default nil}]}
:default {:sku 10 :qty-requested nil}}
{:name :the-reason-why
:type {:name :deercreeklabs.unit.lancaster-test/why
:type :enum
:symbols [:all :stock :limit]
:default :all}
:default :stock}
{:name :data
:type
{:name :deercreeklabs.unit.lancaster-test/a-fixed
:type :fixed
:size 2}
:default "MX"}
{:name :other-data
:type [:null :bytes]
:default nil}]}}
(l/edn nested-map-schema)))
(is (= "-6484319793187085262"
(u/long->str (l/fingerprint64 nested-map-schema)))))
(deftest test-nested-map-schema-serdes
(let [data {"A" {:qty-requested 123
:qty-added 4
:current-qty 10
:req {:sku 123
:qty-requested 123}
:the-reason-why :limit
:data (ba/byte-array [66 67])
:other-data (ba/byte-array [123 123])}
"B" {:qty-requested 4
:qty-added 4
:current-qty 4
:req {:sku 10
:qty-requested 4}
:the-reason-why :all
:data (ba/byte-array [100 110])
:other-data (ba/byte-array [64 74])}}
encoded (l/serialize nested-map-schema data)
decoded (l/deserialize-same nested-map-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [4 2 65 2 246 1 2 8 2 20 246 1 2 246 1 4 66 67 2 4 123
123 2 66 2 8 2 8 2 8 20 2 8 0 100 110 2 4 64 74 0])
encoded))
(is (= (xf-byte-arrays data)
(xf-byte-arrays decoded)))))
(deftest test-empty-map-serdes
(let [sch (l/map-schema l/int-schema)
data {}
encoded (l/serialize sch data)
_ (is (ba/equivalent-byte-arrays?
(ba/byte-array [0])
encoded))
decoded (l/deserialize-same sch encoded)]
(is (= data decoded))))
(deftest test-union-schema
#?(:clj (is (fp-matches? union-schema)))
(is (= [:int
{:name :deercreeklabs.unit.lancaster-test/add-to-cart-req
:type :record
:fields [{:name :sku
:type :int
:default -1}
{:name :qty-requested
:type [:null :int]
:default nil}]}
{:name :deercreeklabs.unit.lancaster-test/a-fixed
:type :fixed
:size 2}]
(l/edn union-schema)))
(is (= "-193173046069528093"
(u/long->str (l/fingerprint64 union-schema)))))
(deftest test-union-schema-serdes
(let [data {:sku 123 :qty-requested 4}
encoded (l/serialize union-schema data)
decoded (l/deserialize-same union-schema encoded)
_ (is (ba/equivalent-byte-arrays? (ba/byte-array [2 246 1 2 8])
encoded))
_ (is (= data decoded))
data 5
encoded (l/serialize union-schema data)
decoded (l/deserialize-same union-schema encoded)]
(is (ba/equivalent-byte-arrays? (ba/byte-array [0 10])
encoded))
(is (= data decoded))))
(deftest test-union-schema-w-multiple-records
#?(:clj (is (fp-matches? person-or-dog-schema)))
(is (= [{:name :deercreeklabs.unit.lancaster-test/person
:type :record
:fields
[{:name :person/name :type :string :default "No name"}
{:name :person/age :type :int :default 0}]}
{:name :deercreeklabs.unit.lancaster-test/dog
:type :record
:fields
[{:name :dog/name :type [:null :string] :default nil}
{:name :dog/owner :type [:null :string] :default nil}]}]
(l/edn person-or-dog-schema)))
(is (= "-5174754347720548939"
(u/long->str (l/fingerprint64 person-or-dog-schema)))))
(deftest test-multi-record-union-schema-serdes
(let [data #:dog{:name "FPI:NAME:<NAME>END_PI" :owner "PI:NAME:<NAME>END_PI"}
encoded (l/serialize person-or-dog-schema data)
decoded (l/deserialize-same person-or-dog-schema encoded)
_ (is (ba/equivalent-byte-arrays?
(ba/byte-array [2 2 8 70 105 100 111 2 8 90 97 99 104])
encoded))
_ (is (= data decoded))
data #:person{:name "PI:NAME:<NAME>END_PI" :age 50}
encoded (l/serialize person-or-dog-schema data)
decoded (l/deserialize-same person-or-dog-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [0 8 66 105 108 108 100])
encoded))
(is (= data decoded))))
(deftest test-multi-record-schema-serdes-non-existent
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"does not match any schema in the union schema"
(l/serialize person-or-dog-schema {:k 1}))))
(deftest test-map-or-array-schema
#?(:clj (is (fp-matches? map-or-array-schema)))
(is (= [{:type :map :values :int}
{:type :array :items :string}]
(l/edn map-or-array-schema)))
(is (= "4441440791563688855"
(u/long->str (l/fingerprint64 map-or-array-schema)))))
(deftest test-map-or-array-schema-serdes
(let [data {"PI:NAME:<NAME>END_PI" 22 "PI:NAME:<NAME>END_PI" 88}
encoded (l/serialize map-or-array-schema data)
decoded (l/deserialize-same map-or-array-schema encoded)
_ (is (ba/equivalent-byte-arrays?
(ba/byte-array [0 4 8 90 101 107 101 44 14 65 100 101 108 105
110 101 -80 1 0])
encoded))
_ (is (= data decoded))
data ["a thing" "another thing"]
encoded (l/serialize map-or-array-schema data)
decoded (l/deserialize-same map-or-array-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [2 4 14 97 32 116 104 105 110 103 26 97 110
111 116 104 101 114 32 116 104 105 110 103 0])
encoded))
(is (= data decoded))))
(deftest test-mopodoa-schema
#?(:clj (is (fp-matches? mopodoa-schema)))
(is (= [{:type :map :values :int}
{:name :deercreeklabs.unit.lancaster-test/person
:type :record
:fields [{:name :person/name
:type :string
:default "No name"}
{:name :person/age
:type :int
:default 0}]}
{:name :deercreeklabs.unit.lancaster-test/dog
:type :record
:fields [{:name :dog/name
:type [:null :string]
:default nil}
{:name :dog/owner
:type [:null :string]
:default nil}]}
{:type :array :items :string}]
(l/edn mopodoa-schema)))
(is (= "-2196893583124300899"
(u/long->str (l/fingerprint64 mopodoa-schema)))))
(deftest test-mopodoa-schema-serdes
(let [data {"PI:NAME:<NAME>END_PI" 22 "PI:NAME:<NAME>END_PI" 88}
encoded (l/serialize mopodoa-schema data)
decoded (l/deserialize-same mopodoa-schema encoded)
_ (is (ba/equivalent-byte-arrays?
(ba/byte-array [0 4 8 90 101 107 101 44 14 65 100 101 108 105
110 101 -80 1 0])
encoded))
_ (is (= data decoded))
data ["a thing" "another thing"]
encoded (l/serialize mopodoa-schema data)
decoded (l/deserialize-same mopodoa-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [6 4 14 97 32 116 104 105 110 103 26 97 110
111 116 104 101 114 32 116 104 105 110 103 0])
encoded))
(is (= data decoded))))
(deftest test-recursive-schema
(is (= {:name :deercreeklabs.unit.lancaster-test/tree
:type :record
:fields
[{:name :value :type :int :default -1}
{:name :right
:type [:null :tree]
:default nil}
{:name :left
:type [:null :tree]
:default nil}]}
(l/edn tree-schema)))
#?(:clj (is (fp-matches? tree-schema)))
(is (= "-3297333764539234889"
(u/long->str (l/fingerprint64 tree-schema)))))
(deftest test-edn-schemas-match?-recursive-schema
(is (u/edn-schemas-match? (l/edn tree-schema) (l/edn tree-schema) {} {})))
(deftest test-recursive-schema-serdes
(let [data {:value 5
:right {:value -10
:right {:value -20}}
:left {:value 10
:left {:value 20
:left {:value 40}}}}
encoded (l/serialize tree-schema data)
decoded (l/deserialize-same tree-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [10 2 19 2 39 0 0 0 2 20 0 2 40 0 2 80 0 0])
encoded))
(is (= data decoded))))
(deftest test-rec-w-array-and-enum-schema
#?(:clj (is (fp-matches? rec-w-array-and-enum-schema)))
(is (= {:name :deercreeklabs.unit.lancaster-test/rec-w-array-and-enum
:type :record
:fields
[{:name :names
:type {:type :array :items :string}
:default []}
{:name :why
:type [:null
{:default :all
:name :deercreeklabs.unit.lancaster-test/why
:symbols [:all :stock :limit]
:type :enum}]
:default nil}]}
(l/edn rec-w-array-and-enum-schema)))
(is (= "-7358640627267953104"
(u/long->str (l/fingerprint64
rec-w-array-and-enum-schema)))))
(deftest test-rec-w-array-and-enum-serdes
(let [data {:names ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]
:why :stock}
encoded (l/serialize rec-w-array-and-enum-schema data)
decoded (l/deserialize-same rec-w-array-and-enum-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [6 8 65 114 105 97 8 66 101 116 104 10 67 105 110 100
121 0 2 2])
encoded))
(is (= data decoded))))
(deftest test-rec-w-map-schema
#?(:clj (is (fp-matches? rec-w-map-schema)))
(is (= {:name :deercreeklabs.unit.lancaster-test/rec-w-map
:type :record
:fields [{:name :name-to-age
:type [:null {:type :map
:values :int}]
:default nil}
{:name :what
:type [:null :string]
:default nil}]}
(l/edn rec-w-map-schema)))
(is (= "1679652566194036700"
(u/long->str (l/fingerprint64
rec-w-map-schema)))))
(deftest test-rec-w-map-serdes
(let [data {:name-to-age {"PI:NAME:<NAME>END_PI" 22
"PI:NAME:<NAME>END_PI" 33
"PI:NAME:<NAME>END_PI" 44}
:what "yo"}
encoded (l/serialize rec-w-map-schema data)
decoded (l/deserialize-same rec-w-map-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [2 6 8 65 114 105 97 44 8 66 101 116 104 66 10 67 105
110 100 121 88 0 2 4 121 111])
encoded))
(is (= data decoded))))
(deftest test-rec-w-fixed-no-default
#?(:clj (is (fp-matches? rec-w-fixed-no-default-schema)))
(is (= {:name :deercreeklabs.unit.lancaster-test/rec-w-fixed-no-default
:type :record
:fields
[{:name :data
:type
{:name :deercreeklabs.unit.lancaster-test/a-fixed
:type :fixed
:size 2}
:default "\0\0"}]}
(l/edn rec-w-fixed-no-default-schema)))
(is (= "-6875395607105571061"
(u/long->str (l/fingerprint64
rec-w-fixed-no-default-schema)))))
(deftest test-rec-w-fixed-no-default-serdes
(let [data {:data (ba/byte-array [1 2])}
encoded (l/serialize rec-w-fixed-no-default-schema data)
decoded (l/deserialize-same rec-w-fixed-no-default-schema encoded)]
(is (ba/equivalent-byte-arrays?
(ba/byte-array [1 2])
encoded))
(is (ba/equivalent-byte-arrays?
(:data data)
(:data decoded)))))
(deftest test-rec-w-maybe-field
#?(:clj (is (fp-matches? rec-w-maybe-field-schema)))
(is (= {:name :deercreeklabs.unit.lancaster-test/rec-w-maybe-field
:type :record
:fields [{:name :name
:type [:null :string]
:default nil}
{:name :age
:type [:null :int]
:default nil}]}
(l/edn rec-w-maybe-field-schema)))
(is (= "-5686522258470805846"
(u/long->str (l/fingerprint64 rec-w-maybe-field-schema)))))
(deftest test-record-serdes-missing-field
(let [data {:qty-requested 100}]
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Record data is missing key `:sku`"
(l/serialize add-to-cart-req-schema data)))))
(deftest test-record-serdes-missing-maybe-field
(let [data {:name "PI:NAME:<NAME>END_PI"}
encoded (l/serialize rec-w-maybe-field-schema data)
decoded (l/deserialize-same rec-w-maybe-field-schema encoded)]
(is (= data decoded))))
(deftest test-schema?
(is (l/schema? person-or-dog-schema))
(is (not (l/schema? :foo))))
(deftest test-bad-serialize-arg
(s/without-fn-validation ;; Allow built-in handlers to throw
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"First argument to serialize must be a schema object"
(l/serialize nil nil)))))
(deftest test-bad-deserialize-args
(s/without-fn-validation ;; Allow built-in handlers to throw
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"First argument to deserialize must be a schema object"
(l/deserialize nil nil nil)))
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Second argument to deserialize must be a "
(l/deserialize why-schema nil (ba/byte-array []))))
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"argument to deserialize must be a byte array"
(l/deserialize why-schema why-schema [])))))
(deftest test-field-default-validation
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Bad default value for field `:int-field`. Got `a`."
(l/record-schema :test-schema
[[:int-field l/int-schema "a"]]))))
(deftest test-default-data
(is (= :all (l/default-data why-schema)))
(is (= {:sku -1
:qty-requested nil}
(l/default-data add-to-cart-req-schema))))
(deftest test-bad-field-name
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Name keywords must start with a letter and subsequently"
(l/record-schema :test-schema
[[:bad? l/boolean-schema]]))))
(deftest test-bad-record-name
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Name keywords must start with a letter and subsequently"
(l/record-schema :*test-schema*
[[:is-good l/boolean-schema]]))))
(deftest test-duplicate-field-name
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Field names must be unique."
(l/record-schema :test-schema
[[:int-field l/int-schema]
[:int-field l/int-schema]]))))
(deftest test-good-union
(let [sch1 (l/record-schema ::sch1 [[:a l/int-schema]
[:b l/string-schema]])
sch2 (l/record-schema ::sch2 [[:different-ns/b l/string-schema]])
sch3 (l/union-schema [sch1 sch2])]
(is (round-trip? sch3 {:different-ns/b "hi"}))
(is (round-trip? sch3 {:a 1 :b "hi"}))))
(deftest test-bad-union
(let [sch1 (l/record-schema ::sch1 [[:a l/int-schema]
[:b l/string-schema]])
sch2 (l/record-schema ::sch2 [[:b l/string-schema]])]
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Ambiguous union"
(l/union-schema [sch1 sch2])))))
(deftest test-serialize-bad-union-member
(let [schema (l/union-schema [l/null-schema l/int-schema])]
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"does not match any schema in the union schema"
(l/serialize schema :foo)))))
(deftest test-maybe-w-union-arg
(let [schema-1 (l/maybe (l/union-schema [l/int-schema l/string-schema]))
schema-2 (l/maybe (l/union-schema [l/null-schema l/int-schema]))]
(is (round-trip? schema-1 nil))
(is (round-trip? schema-2 nil))
(is (round-trip? schema-1 34))
(is (round-trip? schema-2 34))))
(deftest test-more-than-one-numeric-type-in-a-union
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Unions may not contain more than one numeric schema"
(l/union-schema [l/int-schema l/float-schema]))))
(deftest test-more-than-one-bytes-type-in-a-union
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Unions may not contain more than one byte-array schema"
(l/union-schema [l/bytes-schema (l/fixed-schema :foo 16)]))))
(deftest test-serialize-empty-map-multi-rec-union
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Record data is missing key `:person/name`"
(l/serialize person-or-dog-schema {}))))
(deftest test-map-and-rec-union
(let [schema (l/union-schema [(l/map-schema l/int-schema) person-schema])]
(is (round-trip? schema {"foo" 1}))
(is (round-trip? schema #:person{:name "PI:NAME:<NAME>END_PI" :age 18}))))
(deftest test-ns-enum
(is (round-trip? suit-schema :suit/spades))
(is (= {:name :deercreeklabs.unit.lancaster-test/suit
:type :enum
:symbols [:suit/hearts :suit/clubs :suit/spades :suit/diamonds]
:default :suit/hearts}
(l/edn suit-schema)))
(is (= (str "{\"name\":\"deercreeklabs.unit.lancaster_test.Suit\",\"type\":"
"\"enum\",\"symbols\":[\"HEARTS\",\"CLUBS\",\"SPADES\","
"\"DIAMONDS\"],\"default\":\"HEARTS\"}")
(l/json suit-schema))))
(deftest test-identical-schemas-in-union
(let [sch1 (l/enum-schema ::a-name [:a :b])
sch2 (l/enum-schema ::a-name [:a :b])]
(is (not= sch1 sch2))
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Identical schemas in union"
(l/union-schema [l/string-schema sch1 sch2])))))
(deftest test-schemas-match?
(let [sch1 (l/enum-schema ::a-name [:a :b])
sch2 (l/enum-schema ::a-name [:a :b])
sch3 (l/enum-schema ::x-name [:a :b])]
(is (l/schemas-match? sch1 sch2))
(is (not (l/schemas-match? sch1 sch3)))))
(deftest test-missing-record-field
(let [sch1 (l/record-schema ::test [[:a :required l/int-schema]])
sch2 (l/union-schema [l/int-schema sch1])
sch3 (l/record-schema ::sch3 [[:arg sch2]])
sch4 (l/array-schema sch3)]
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Record data is missing key `:a`"
(l/serialize sch1 {:b 1})))
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Record data is missing key `:a`"
(l/serialize sch2 {:b 1})))
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Record data is missing key `:a`"
(l/serialize sch3 {:arg {:b 1}})))
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Record data is missing key `:a`"
(l/serialize sch4 [{:arg {:a 1}}
{:arg {:b 1}}])))))
(deftest serialize-small-double-into-float-union
(let [sch (l/union-schema [l/null-schema l/float-schema])
v (double 6.0)
encoded (l/serialize sch v)
decoded (l/deserialize-same sch encoded)]
(is (= v decoded))))
(deftest serialize-long-into-union
(let [sch (l/union-schema [l/null-schema l/long-schema])
v (u/str->long "-5442038735385698765")
encoded (l/serialize sch v)
decoded (l/deserialize-same sch encoded)]
(is (= v decoded))))
(deftest serialize-lazy-sequence-into-union
(let [sch (l/union-schema [l/null-schema (l/array-schema l/int-schema)])
v (map identity [42 681 1024]) ; Make a lazy seq
encoded (l/serialize sch v)
decoded (l/deserialize-same sch encoded)]
(is (= v decoded))))
(deftest test-rt-set
(let [sch l/string-set-schema
v #{"a" "b" "1234" "c45"}
encoded (l/serialize sch v)
decoded (l/deserialize-same sch encoded)]
(is (= v decoded))))
(deftest test-bad-set-type
(let [sch l/string-set-schema
v #{"2" :k}] ;; not strictly string members
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"Set element `:k` .* is not a valid string"
(l/serialize sch v)))))
(deftest test-bad-set-type-map-of-nils
(let [sch (l/map-schema l/null-schema) ;; equivalent to l/string-set-schema
v {"a" nil "b" nil}] ;; Must be a set
(is (thrown-with-msg?
#?(:clj ExceptionInfo :cljs js/Error)
#"is not a valid Clojure set"
(l/serialize sch v)))))
|
[
{
"context": ";; Copyright Fabian Schneider and Gunnar Völkel © 2014-2020\n;;\n;; Permission is",
"end": 29,
"score": 0.9998487830162048,
"start": 13,
"tag": "NAME",
"value": "Fabian Schneider"
},
{
"context": ";; Copyright Fabian Schneider and Gunnar Völkel © 2014-2020\n;;\n;; Permission is hereby granted, f",
"end": 47,
"score": 0.9998400807380676,
"start": 34,
"tag": "NAME",
"value": "Gunnar Völkel"
},
{
"context": "flowcellnr \"Flow Cell Number\",\n; :customername \"Customer Name\",\n; :customeremail \"Customer E-Mail\",\n :descr",
"end": 6690,
"score": 0.9903424978256226,
"start": 6677,
"tag": "NAME",
"value": "Customer Name"
}
] | src/traqbio/actions/project.clj | sysbio-bioinf/iBioTraq | 2 | ;; Copyright Fabian Schneider and Gunnar Völkel © 2014-2020
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
;; THE SOFTWARE.
(ns traqbio.actions.project
(:require
[clojure.data :as data]
[clojure.java.io :as io]
[clojure.set :as set]
[clojure.string :as str]
[clojure.stacktrace :refer [print-cause-trace]]
[clojure.tools.logging :as log]
[cemerick.friend :as friend]
[ring.util.http-response :as r]
[traqbio.config :as c]
[traqbio.common :as common]
[traqbio.db.crud :as crud]
[traqbio.actions.mail :as mail]
[traqbio.actions.tools :as t]
[traqbio.actions.diff :as diff])
(:import
java.util.UUID))
(defn- render-tracking-link
[tracking-nr]
(str "http://" (c/tracking-server-domain) (c/server-location "/track/") tracking-nr))
(defn- render-edit-link
[project-id]
(str "http://" (c/tracking-server-domain) (c/server-location "/prj/edit/") project-id))
(defn normalize-email-list
[emaillist]
(some-> emaillist
(str/split #",")
(->>
(mapv str/trim)
(str/join ", "))))
(defn user-notification-map->vector
[filtered-state, user-map]
(reduce-kv
(fn [result, user, notify]
(cond-> result (= notify filtered-state) (conj (name user))))
[]
user-map))
(defn distinct-customers
[customers]
(let [customers (common/->vector customers)
n (count customers)]
(loop [i 0, customer-key-set #{}, unique []]
(if (< i n)
(let [customer (nth customers i)
customer-key (crud/customer-key customer)]
(recur
(inc i),
(conj customer-key-set customer-key),
(cond-> unique
(not (contains? customer-key-set customer-key))
(conj (crud/normalize-customer-attributes customer)))))
unique))))
(defn project-created-message
[data-map]
(when-let [customers (get-in data-map [:parameters, :project, :customers])]
(if (== 1 (count customers))
(format "for customer %s" (->> customers first :name))
(format "for customers %s" (->> customers (map :name) (str/join ", "))))))
(t/defaction create-project
"Creates a tracking number, sends an email to the customer and finally generates the project itself. "
{:description "Project \"{{result.body.projectnumber}}\" created",
:message project-created-message,
:error "Project creation failed",
:projectid "{{result.body.projectid}}"
:action-type :create}
[{:keys [projectnumber] :as project}]
(if (empty? (:customers project))
{:status 400, :body {:error "Customer data is missing."}}
(let [trackingNr (-> (UUID/randomUUID) (.toString)),
projectnumber (if (str/blank? projectnumber) (crud/next-default-projectnumber) projectnumber),
project (-> project
(set/rename-keys {:templatesteps :projectsteps})
(assoc
:dateofreceipt (t/now)
:trackingnr trackingNr
:trackinglink (render-tracking-link trackingNr)
:projectnumber projectnumber
:done 0)
(dissoc :id)
(update-in [:customers] distinct-customers)
(update-in [:notifycustomer] #(if (= % 1) 1 0))
(update-in [:additionalnotificationemails] normalize-email-list)
(update-in [:notifiedusers] (partial user-notification-map->vector 1))),
project-id (crud/create-project project),
mail? (c/send-mail?),
; send mail asynchronous (faster response on project creation), errors will be reported in the timeline by the mailing function
; We would only get errors about failed mail server configuration here anyway.
send-mail-result (when mail?
(future
(mail/send-project-notification-mail
(assoc project
:id project-id
:editlink (render-edit-link project-id)),
(crud/user-email-addresses (:notifiedusers project)),
:project-creation)))]
{:status 200 ; success, even on mail error since that is handled separately (otherwise the project creation would be reported as failed in the timeline)
:body {:trackingnr trackingNr, :trackinglink (render-tracking-link trackingNr), :projectnumber projectnumber, :projectid project-id
:customerinfos (mapv (fn [{:keys [name, email]}] (format "%s (%s)" name email)) (:customers project))}})))
(defn- process-timestamps
[project-steps, now]
(mapv
(fn [{:keys [state, timestamp] :as step}]
; comment: application logic depending on property "timestamp" sent by UI :(
(if (== state 1)
; set timestamp if unset
(cond-> step (str/blank? timestamp) (assoc :timestamp now))
; remove timestamp if set
(cond-> step (not (str/blank? timestamp)) (assoc :timestamp ""))))
project-steps))
(defn- update-progress
[{:keys [projectsteps] :as project}]
(let [n (count projectsteps)
finished (count (filter #(== 1 (:state %)) projectsteps))]
(assoc project
:step-count n
:finished-step-count finished
:done (if (== n finished) 1 0))))
(defn- process-project
[project]
(-> project
(update-in [:projectsteps] process-timestamps (t/now))
(update-in [:customers] distinct-customers)
update-progress))
(def ^:private project-attributes
{:flowcellnr "Flow Cell Number",
; :customername "Customer Name",
; :customeremail "Customer E-Mail",
:description "Description",
:advisor "Advisor",
:samplesheet "Sample Sheet",
:orderform "Order Form"})
(defn changed-project-attributes
[old-project, new-project]
(keep
#(when-not (t/equal? (% old-project) (% new-project))
(% project-attributes))
[:flowcellnr #_:customername #_:customeremail :description :advisor :samplesheet :orderform]))
(defn project-diff
[p+r-map]
(let [new-project (process-project (get-in p+r-map [:parameters, :data :project])),
old-project (process-project (get-in p+r-map [:parameters, :data :oldproject])),
projectnumber-changed? (not (t/equal? (:projectnumber old-project) (:projectnumber new-project))),
changed-attributes (seq (changed-project-attributes old-project, new-project)),
completed? (and (= 0 (:done old-project)) (= 1 (:done new-project))),
customer-notification-changed? (not= (:notifycustomer new-project) (:notifycustomer old-project))
notifiedusers-delta (first (data/diff (:notifiedusers new-project) (:notifiedusers old-project)))
added-users (user-notification-map->vector 1, notifiedusers-delta),
removed-users (user-notification-map->vector 0, notifiedusers-delta),
staff-notification-changed? (or (pos? (count added-users)) (pos? (count removed-users))),
state-changes (->> (map #(= (:state %1) (:state %2)) (:projectsteps old-project) (:projectsteps new-project))
(remove true?)
count),
changed-step-diff (diff/describe-modifications (diff/step-modifications (:projectsteps new-project), (:projectsteps old-project))),
;TODO: let changed-module-diff call with (diff/module-modifications (:textmodules new-project), (:textmodules old-project))
diff (cond-> []
projectnumber-changed?
(conj (format "Project \"%s\" has been renamed to \"%s\"." (:projectnumber old-project) (:projectnumber new-project)))
completed?
(conj "Project has been completed.")
(and (not completed?) (pos? state-changes))
(conj (format "The state of %s project steps has changed. (%s/%s completed)" state-changes, (:finished-step-count new-project), (:step-count new-project)))
changed-attributes
(conj (format "Changed project attributes: %s" (str/join ", " changed-attributes)))
customer-notification-changed?
(conj (if (= 1 (:notifycustomer new-project)) "The customer will be notified about project step completion." "The customer is not notified about project step completion anymore."))
staff-notification-changed?
(conj (str "The notified staff has been changed:\n"
(str/join "\n"
(remove nil?
[(when (seq added-users)
(str " added: " (str/join ", " added-users)))
(when (seq removed-users)
(str " removed: " (str/join ", " removed-users)))]))
"."))
(or projectnumber-changed? completed? (pos? state-changes))
(conj "")
changed-step-diff
(into changed-step-diff))];end of cond, end of let
(when (seq diff)
(str/join "\n" diff))))
(defn load-project
[project-id]
(process-project (crud/read-project project-id)))
(defn filter2
"Filter the elements of xs based on a predicate applied to the values of xs and ys at the same sequential position.
If #xs > ys#, the funtion can filter at most #ys elements. The predicate is defined to be false for the remaining elements of xs."
[pred, xs, ys]
(let [xs (common/->vector xs),
ys (common/->vector ys),
nx (count xs),
ny (count ys),
n (min nx, ny)]
(loop [i 0, result (transient [])]
(if (< i n)
(let [x_i (nth xs i),
y_i (nth ys i)]
(recur
(unchecked-inc i),
(cond-> result (pred x_i, y_i) (conj! x_i))))
(persistent! result)))))
(defn progress-information
"Determines the progress information that can be included in notification e-mails."
[new-project, old-project]
(let [completed-steps (filter2
(fn [new-step, old-step]
(and
(== (:state new-step) 1)
(== (:state old-step) 0)))
(sort-by :id (:projectsteps new-project)),
(sort-by :id (:projectsteps old-project))),
n (count completed-steps),
step-information (->> completed-steps
(sort-by :sequence)
(mapv
(fn [{:keys [type, freetext]}]
(format "Step: %s\n%s", type, (if (str/blank? freetext) "" (str "\n " (str/replace freetext "\n" "\n ")))))))]
(str/join "\n\n"
(list*
(format "The following %s been completed:" (if (< 1 n) (str n " steps have") "step has"))
(cond-> step-information
(== (:done new-project) 1) (conj "The project has been finished."))))))
(defn step-completion-notification
[new-project, old-project]
(try
(let [notifycustomer (== (:notifycustomer new-project) 1),
notifiedusers (user-notification-map->vector 1 (:notifiedusers new-project))]
(when (or notifycustomer (seq notifiedusers))
(mail/send-project-notification-mail
(assoc new-project
:progressinfo (progress-information new-project, old-project),
:trackinglink (render-tracking-link (:trackingnr new-project))
:editlink (render-edit-link (:id new-project))),
(crud/user-email-addresses notifiedusers),
:project-progress)))
(catch Throwable t
(log/errorf "Failed to determine step completion before sending the notification e-mails. Error:\n%s"
(with-out-str (print-cause-trace t))))))
(defn completion
[{:keys [finished-step-count, projectsteps]}]
(/ (double finished-step-count) (count projectsteps)))
(defn customer-map
[project]
(let [customers (map-indexed #(assoc (crud/normalize-customer-data %2) :sequence %1) (:customers project))]
(zipmap (map #(select-keys % [:name :email]) customers) customers)))
(defn customers-diff
[new-project, old-project]
(let [old-customer-map (customer-map old-project),
[only-new-customers, only-old-customers] (data/diff (customer-map new-project), old-customer-map)]
(reduce
(fn [result-map, name+email]
(if (contains? only-new-customers name+email)
(if (contains? only-old-customers name+email)
; customer has been modified (e.g. sequence)
(update-in result-map [:modified-customers] conj (merge name+email (get only-new-customers name+email)))
; customer has been added
(update-in result-map [:added-customers] conj (get only-new-customers name+email)))
; customer has been removed
(update-in result-map [:removed-customers] conj (get only-old-customers name+email))))
{:added-customers [],
:removed-customers [],
:modified-customers []}
(distinct (concat (keys only-new-customers) (keys only-old-customers))))))
(t/defaction update-project
"Updates the changes to a project. Marks a project as completed when all steps are completed."
{:description "Project \"{{parameters.data.project.projectnumber}}\" updated",
;:capture (load-project (:id project)),
:message project-diff,
:projectid "{{result.body.projectid}}"
:error "Update of project \"{{parameters.data.project.projectnumber}}\" failed",
:action-type :update}
[{new-project :project, old-project :oldproject :as data}]
(let [new-project (process-project new-project),
old-project (process-project old-project),
project-diff (-> (data/diff (dissoc new-project :projectsteps), (dissoc old-project :projectsteps))
; extract modifications of the new project (newest wins with respect to modified properties)
first
; add project id to diff
(assoc :id (:id old-project))
; remove :notifiedusers since the diff is handled separately
(dissoc :notifiedusers)),
step-changes (diff/step-modifications (:projectsteps new-project), (:projectsteps old-project))
;TODO: let module-changes (diff/module-modifications (:textmodules new-project), (:textmodules old-project))
notifiedusers-delta (first (data/diff (:notifiedusers new-project) (:notifiedusers old-project))),
added-users (user-notification-map->vector 1, notifiedusers-delta),
removed-users (user-notification-map->vector 0, notifiedusers-delta),
{:keys [added-customers, removed-customers, modified-customers]} (customers-diff new-project, old-project),
project-id (:id new-project),
steps-completed? (> (completion new-project) (completion old-project))]
; update of notified users must be handled here to determine the differences
(if (and
(crud/update-project project-diff, step-changes)
(crud/add-customers project-id, added-customers)
(crud/modify-customers project-id, modified-customers)
(crud/remove-customers project-id, removed-customers)
(crud/add-notified-user-for-project project-id, added-users)
(crud/remove-notified-user-from-project project-id, removed-users))
(do
; after everything has been update sent notification (if needed and specified)
(when (and steps-completed? (c/send-mail?))
(future (step-completion-notification new-project, old-project)))
{:status 200, :body {:projectid project-id}})
{:status 500})))
(defn- create-filename
"Builds filename"
[tmp-file-name nr]
(str (c/upload-path) nr "/" tmp-file-name))
(defn upload
"File upload. Needs multi-param-file and tracking number"
[file nr]
(if (and file nr)
(let [tmp-file (:tempfile file)
new-file-name (create-filename (:filename file) nr)
new-file (io/file new-file-name)]
(.mkdirs (io/file (str (c/upload-path) nr)))
(io/copy tmp-file new-file)
{:status 200})
{:status 500}))
(t/defaction delete-project
"Delete Project with id"
{:description "Project \"{{captured.projectnumber}}\" deleted",
:capture (load-project id),
:error "Failed to delete project \"{{captured.projectnumber}}\"",
:action-type :delete}
[id]
(if (crud/delete-project id)
{:status 200, :body {}}
{:status 500}))
| 62888 | ;; Copyright <NAME> and <NAME> © 2014-2020
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
;; THE SOFTWARE.
(ns traqbio.actions.project
(:require
[clojure.data :as data]
[clojure.java.io :as io]
[clojure.set :as set]
[clojure.string :as str]
[clojure.stacktrace :refer [print-cause-trace]]
[clojure.tools.logging :as log]
[cemerick.friend :as friend]
[ring.util.http-response :as r]
[traqbio.config :as c]
[traqbio.common :as common]
[traqbio.db.crud :as crud]
[traqbio.actions.mail :as mail]
[traqbio.actions.tools :as t]
[traqbio.actions.diff :as diff])
(:import
java.util.UUID))
(defn- render-tracking-link
[tracking-nr]
(str "http://" (c/tracking-server-domain) (c/server-location "/track/") tracking-nr))
(defn- render-edit-link
[project-id]
(str "http://" (c/tracking-server-domain) (c/server-location "/prj/edit/") project-id))
(defn normalize-email-list
[emaillist]
(some-> emaillist
(str/split #",")
(->>
(mapv str/trim)
(str/join ", "))))
(defn user-notification-map->vector
[filtered-state, user-map]
(reduce-kv
(fn [result, user, notify]
(cond-> result (= notify filtered-state) (conj (name user))))
[]
user-map))
(defn distinct-customers
[customers]
(let [customers (common/->vector customers)
n (count customers)]
(loop [i 0, customer-key-set #{}, unique []]
(if (< i n)
(let [customer (nth customers i)
customer-key (crud/customer-key customer)]
(recur
(inc i),
(conj customer-key-set customer-key),
(cond-> unique
(not (contains? customer-key-set customer-key))
(conj (crud/normalize-customer-attributes customer)))))
unique))))
(defn project-created-message
[data-map]
(when-let [customers (get-in data-map [:parameters, :project, :customers])]
(if (== 1 (count customers))
(format "for customer %s" (->> customers first :name))
(format "for customers %s" (->> customers (map :name) (str/join ", "))))))
(t/defaction create-project
"Creates a tracking number, sends an email to the customer and finally generates the project itself. "
{:description "Project \"{{result.body.projectnumber}}\" created",
:message project-created-message,
:error "Project creation failed",
:projectid "{{result.body.projectid}}"
:action-type :create}
[{:keys [projectnumber] :as project}]
(if (empty? (:customers project))
{:status 400, :body {:error "Customer data is missing."}}
(let [trackingNr (-> (UUID/randomUUID) (.toString)),
projectnumber (if (str/blank? projectnumber) (crud/next-default-projectnumber) projectnumber),
project (-> project
(set/rename-keys {:templatesteps :projectsteps})
(assoc
:dateofreceipt (t/now)
:trackingnr trackingNr
:trackinglink (render-tracking-link trackingNr)
:projectnumber projectnumber
:done 0)
(dissoc :id)
(update-in [:customers] distinct-customers)
(update-in [:notifycustomer] #(if (= % 1) 1 0))
(update-in [:additionalnotificationemails] normalize-email-list)
(update-in [:notifiedusers] (partial user-notification-map->vector 1))),
project-id (crud/create-project project),
mail? (c/send-mail?),
; send mail asynchronous (faster response on project creation), errors will be reported in the timeline by the mailing function
; We would only get errors about failed mail server configuration here anyway.
send-mail-result (when mail?
(future
(mail/send-project-notification-mail
(assoc project
:id project-id
:editlink (render-edit-link project-id)),
(crud/user-email-addresses (:notifiedusers project)),
:project-creation)))]
{:status 200 ; success, even on mail error since that is handled separately (otherwise the project creation would be reported as failed in the timeline)
:body {:trackingnr trackingNr, :trackinglink (render-tracking-link trackingNr), :projectnumber projectnumber, :projectid project-id
:customerinfos (mapv (fn [{:keys [name, email]}] (format "%s (%s)" name email)) (:customers project))}})))
(defn- process-timestamps
[project-steps, now]
(mapv
(fn [{:keys [state, timestamp] :as step}]
; comment: application logic depending on property "timestamp" sent by UI :(
(if (== state 1)
; set timestamp if unset
(cond-> step (str/blank? timestamp) (assoc :timestamp now))
; remove timestamp if set
(cond-> step (not (str/blank? timestamp)) (assoc :timestamp ""))))
project-steps))
(defn- update-progress
[{:keys [projectsteps] :as project}]
(let [n (count projectsteps)
finished (count (filter #(== 1 (:state %)) projectsteps))]
(assoc project
:step-count n
:finished-step-count finished
:done (if (== n finished) 1 0))))
(defn- process-project
[project]
(-> project
(update-in [:projectsteps] process-timestamps (t/now))
(update-in [:customers] distinct-customers)
update-progress))
(def ^:private project-attributes
{:flowcellnr "Flow Cell Number",
; :customername "<NAME>",
; :customeremail "Customer E-Mail",
:description "Description",
:advisor "Advisor",
:samplesheet "Sample Sheet",
:orderform "Order Form"})
(defn changed-project-attributes
[old-project, new-project]
(keep
#(when-not (t/equal? (% old-project) (% new-project))
(% project-attributes))
[:flowcellnr #_:customername #_:customeremail :description :advisor :samplesheet :orderform]))
(defn project-diff
[p+r-map]
(let [new-project (process-project (get-in p+r-map [:parameters, :data :project])),
old-project (process-project (get-in p+r-map [:parameters, :data :oldproject])),
projectnumber-changed? (not (t/equal? (:projectnumber old-project) (:projectnumber new-project))),
changed-attributes (seq (changed-project-attributes old-project, new-project)),
completed? (and (= 0 (:done old-project)) (= 1 (:done new-project))),
customer-notification-changed? (not= (:notifycustomer new-project) (:notifycustomer old-project))
notifiedusers-delta (first (data/diff (:notifiedusers new-project) (:notifiedusers old-project)))
added-users (user-notification-map->vector 1, notifiedusers-delta),
removed-users (user-notification-map->vector 0, notifiedusers-delta),
staff-notification-changed? (or (pos? (count added-users)) (pos? (count removed-users))),
state-changes (->> (map #(= (:state %1) (:state %2)) (:projectsteps old-project) (:projectsteps new-project))
(remove true?)
count),
changed-step-diff (diff/describe-modifications (diff/step-modifications (:projectsteps new-project), (:projectsteps old-project))),
;TODO: let changed-module-diff call with (diff/module-modifications (:textmodules new-project), (:textmodules old-project))
diff (cond-> []
projectnumber-changed?
(conj (format "Project \"%s\" has been renamed to \"%s\"." (:projectnumber old-project) (:projectnumber new-project)))
completed?
(conj "Project has been completed.")
(and (not completed?) (pos? state-changes))
(conj (format "The state of %s project steps has changed. (%s/%s completed)" state-changes, (:finished-step-count new-project), (:step-count new-project)))
changed-attributes
(conj (format "Changed project attributes: %s" (str/join ", " changed-attributes)))
customer-notification-changed?
(conj (if (= 1 (:notifycustomer new-project)) "The customer will be notified about project step completion." "The customer is not notified about project step completion anymore."))
staff-notification-changed?
(conj (str "The notified staff has been changed:\n"
(str/join "\n"
(remove nil?
[(when (seq added-users)
(str " added: " (str/join ", " added-users)))
(when (seq removed-users)
(str " removed: " (str/join ", " removed-users)))]))
"."))
(or projectnumber-changed? completed? (pos? state-changes))
(conj "")
changed-step-diff
(into changed-step-diff))];end of cond, end of let
(when (seq diff)
(str/join "\n" diff))))
(defn load-project
[project-id]
(process-project (crud/read-project project-id)))
(defn filter2
"Filter the elements of xs based on a predicate applied to the values of xs and ys at the same sequential position.
If #xs > ys#, the funtion can filter at most #ys elements. The predicate is defined to be false for the remaining elements of xs."
[pred, xs, ys]
(let [xs (common/->vector xs),
ys (common/->vector ys),
nx (count xs),
ny (count ys),
n (min nx, ny)]
(loop [i 0, result (transient [])]
(if (< i n)
(let [x_i (nth xs i),
y_i (nth ys i)]
(recur
(unchecked-inc i),
(cond-> result (pred x_i, y_i) (conj! x_i))))
(persistent! result)))))
(defn progress-information
"Determines the progress information that can be included in notification e-mails."
[new-project, old-project]
(let [completed-steps (filter2
(fn [new-step, old-step]
(and
(== (:state new-step) 1)
(== (:state old-step) 0)))
(sort-by :id (:projectsteps new-project)),
(sort-by :id (:projectsteps old-project))),
n (count completed-steps),
step-information (->> completed-steps
(sort-by :sequence)
(mapv
(fn [{:keys [type, freetext]}]
(format "Step: %s\n%s", type, (if (str/blank? freetext) "" (str "\n " (str/replace freetext "\n" "\n ")))))))]
(str/join "\n\n"
(list*
(format "The following %s been completed:" (if (< 1 n) (str n " steps have") "step has"))
(cond-> step-information
(== (:done new-project) 1) (conj "The project has been finished."))))))
(defn step-completion-notification
[new-project, old-project]
(try
(let [notifycustomer (== (:notifycustomer new-project) 1),
notifiedusers (user-notification-map->vector 1 (:notifiedusers new-project))]
(when (or notifycustomer (seq notifiedusers))
(mail/send-project-notification-mail
(assoc new-project
:progressinfo (progress-information new-project, old-project),
:trackinglink (render-tracking-link (:trackingnr new-project))
:editlink (render-edit-link (:id new-project))),
(crud/user-email-addresses notifiedusers),
:project-progress)))
(catch Throwable t
(log/errorf "Failed to determine step completion before sending the notification e-mails. Error:\n%s"
(with-out-str (print-cause-trace t))))))
(defn completion
[{:keys [finished-step-count, projectsteps]}]
(/ (double finished-step-count) (count projectsteps)))
(defn customer-map
[project]
(let [customers (map-indexed #(assoc (crud/normalize-customer-data %2) :sequence %1) (:customers project))]
(zipmap (map #(select-keys % [:name :email]) customers) customers)))
(defn customers-diff
[new-project, old-project]
(let [old-customer-map (customer-map old-project),
[only-new-customers, only-old-customers] (data/diff (customer-map new-project), old-customer-map)]
(reduce
(fn [result-map, name+email]
(if (contains? only-new-customers name+email)
(if (contains? only-old-customers name+email)
; customer has been modified (e.g. sequence)
(update-in result-map [:modified-customers] conj (merge name+email (get only-new-customers name+email)))
; customer has been added
(update-in result-map [:added-customers] conj (get only-new-customers name+email)))
; customer has been removed
(update-in result-map [:removed-customers] conj (get only-old-customers name+email))))
{:added-customers [],
:removed-customers [],
:modified-customers []}
(distinct (concat (keys only-new-customers) (keys only-old-customers))))))
(t/defaction update-project
"Updates the changes to a project. Marks a project as completed when all steps are completed."
{:description "Project \"{{parameters.data.project.projectnumber}}\" updated",
;:capture (load-project (:id project)),
:message project-diff,
:projectid "{{result.body.projectid}}"
:error "Update of project \"{{parameters.data.project.projectnumber}}\" failed",
:action-type :update}
[{new-project :project, old-project :oldproject :as data}]
(let [new-project (process-project new-project),
old-project (process-project old-project),
project-diff (-> (data/diff (dissoc new-project :projectsteps), (dissoc old-project :projectsteps))
; extract modifications of the new project (newest wins with respect to modified properties)
first
; add project id to diff
(assoc :id (:id old-project))
; remove :notifiedusers since the diff is handled separately
(dissoc :notifiedusers)),
step-changes (diff/step-modifications (:projectsteps new-project), (:projectsteps old-project))
;TODO: let module-changes (diff/module-modifications (:textmodules new-project), (:textmodules old-project))
notifiedusers-delta (first (data/diff (:notifiedusers new-project) (:notifiedusers old-project))),
added-users (user-notification-map->vector 1, notifiedusers-delta),
removed-users (user-notification-map->vector 0, notifiedusers-delta),
{:keys [added-customers, removed-customers, modified-customers]} (customers-diff new-project, old-project),
project-id (:id new-project),
steps-completed? (> (completion new-project) (completion old-project))]
; update of notified users must be handled here to determine the differences
(if (and
(crud/update-project project-diff, step-changes)
(crud/add-customers project-id, added-customers)
(crud/modify-customers project-id, modified-customers)
(crud/remove-customers project-id, removed-customers)
(crud/add-notified-user-for-project project-id, added-users)
(crud/remove-notified-user-from-project project-id, removed-users))
(do
; after everything has been update sent notification (if needed and specified)
(when (and steps-completed? (c/send-mail?))
(future (step-completion-notification new-project, old-project)))
{:status 200, :body {:projectid project-id}})
{:status 500})))
(defn- create-filename
"Builds filename"
[tmp-file-name nr]
(str (c/upload-path) nr "/" tmp-file-name))
(defn upload
"File upload. Needs multi-param-file and tracking number"
[file nr]
(if (and file nr)
(let [tmp-file (:tempfile file)
new-file-name (create-filename (:filename file) nr)
new-file (io/file new-file-name)]
(.mkdirs (io/file (str (c/upload-path) nr)))
(io/copy tmp-file new-file)
{:status 200})
{:status 500}))
(t/defaction delete-project
"Delete Project with id"
{:description "Project \"{{captured.projectnumber}}\" deleted",
:capture (load-project id),
:error "Failed to delete project \"{{captured.projectnumber}}\"",
:action-type :delete}
[id]
(if (crud/delete-project id)
{:status 200, :body {}}
{:status 500}))
| true | ;; Copyright PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI © 2014-2020
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
;; THE SOFTWARE.
(ns traqbio.actions.project
(:require
[clojure.data :as data]
[clojure.java.io :as io]
[clojure.set :as set]
[clojure.string :as str]
[clojure.stacktrace :refer [print-cause-trace]]
[clojure.tools.logging :as log]
[cemerick.friend :as friend]
[ring.util.http-response :as r]
[traqbio.config :as c]
[traqbio.common :as common]
[traqbio.db.crud :as crud]
[traqbio.actions.mail :as mail]
[traqbio.actions.tools :as t]
[traqbio.actions.diff :as diff])
(:import
java.util.UUID))
(defn- render-tracking-link
[tracking-nr]
(str "http://" (c/tracking-server-domain) (c/server-location "/track/") tracking-nr))
(defn- render-edit-link
[project-id]
(str "http://" (c/tracking-server-domain) (c/server-location "/prj/edit/") project-id))
(defn normalize-email-list
[emaillist]
(some-> emaillist
(str/split #",")
(->>
(mapv str/trim)
(str/join ", "))))
(defn user-notification-map->vector
[filtered-state, user-map]
(reduce-kv
(fn [result, user, notify]
(cond-> result (= notify filtered-state) (conj (name user))))
[]
user-map))
(defn distinct-customers
[customers]
(let [customers (common/->vector customers)
n (count customers)]
(loop [i 0, customer-key-set #{}, unique []]
(if (< i n)
(let [customer (nth customers i)
customer-key (crud/customer-key customer)]
(recur
(inc i),
(conj customer-key-set customer-key),
(cond-> unique
(not (contains? customer-key-set customer-key))
(conj (crud/normalize-customer-attributes customer)))))
unique))))
(defn project-created-message
[data-map]
(when-let [customers (get-in data-map [:parameters, :project, :customers])]
(if (== 1 (count customers))
(format "for customer %s" (->> customers first :name))
(format "for customers %s" (->> customers (map :name) (str/join ", "))))))
(t/defaction create-project
"Creates a tracking number, sends an email to the customer and finally generates the project itself. "
{:description "Project \"{{result.body.projectnumber}}\" created",
:message project-created-message,
:error "Project creation failed",
:projectid "{{result.body.projectid}}"
:action-type :create}
[{:keys [projectnumber] :as project}]
(if (empty? (:customers project))
{:status 400, :body {:error "Customer data is missing."}}
(let [trackingNr (-> (UUID/randomUUID) (.toString)),
projectnumber (if (str/blank? projectnumber) (crud/next-default-projectnumber) projectnumber),
project (-> project
(set/rename-keys {:templatesteps :projectsteps})
(assoc
:dateofreceipt (t/now)
:trackingnr trackingNr
:trackinglink (render-tracking-link trackingNr)
:projectnumber projectnumber
:done 0)
(dissoc :id)
(update-in [:customers] distinct-customers)
(update-in [:notifycustomer] #(if (= % 1) 1 0))
(update-in [:additionalnotificationemails] normalize-email-list)
(update-in [:notifiedusers] (partial user-notification-map->vector 1))),
project-id (crud/create-project project),
mail? (c/send-mail?),
; send mail asynchronous (faster response on project creation), errors will be reported in the timeline by the mailing function
; We would only get errors about failed mail server configuration here anyway.
send-mail-result (when mail?
(future
(mail/send-project-notification-mail
(assoc project
:id project-id
:editlink (render-edit-link project-id)),
(crud/user-email-addresses (:notifiedusers project)),
:project-creation)))]
{:status 200 ; success, even on mail error since that is handled separately (otherwise the project creation would be reported as failed in the timeline)
:body {:trackingnr trackingNr, :trackinglink (render-tracking-link trackingNr), :projectnumber projectnumber, :projectid project-id
:customerinfos (mapv (fn [{:keys [name, email]}] (format "%s (%s)" name email)) (:customers project))}})))
(defn- process-timestamps
[project-steps, now]
(mapv
(fn [{:keys [state, timestamp] :as step}]
; comment: application logic depending on property "timestamp" sent by UI :(
(if (== state 1)
; set timestamp if unset
(cond-> step (str/blank? timestamp) (assoc :timestamp now))
; remove timestamp if set
(cond-> step (not (str/blank? timestamp)) (assoc :timestamp ""))))
project-steps))
(defn- update-progress
[{:keys [projectsteps] :as project}]
(let [n (count projectsteps)
finished (count (filter #(== 1 (:state %)) projectsteps))]
(assoc project
:step-count n
:finished-step-count finished
:done (if (== n finished) 1 0))))
(defn- process-project
[project]
(-> project
(update-in [:projectsteps] process-timestamps (t/now))
(update-in [:customers] distinct-customers)
update-progress))
(def ^:private project-attributes
{:flowcellnr "Flow Cell Number",
; :customername "PI:NAME:<NAME>END_PI",
; :customeremail "Customer E-Mail",
:description "Description",
:advisor "Advisor",
:samplesheet "Sample Sheet",
:orderform "Order Form"})
(defn changed-project-attributes
[old-project, new-project]
(keep
#(when-not (t/equal? (% old-project) (% new-project))
(% project-attributes))
[:flowcellnr #_:customername #_:customeremail :description :advisor :samplesheet :orderform]))
(defn project-diff
[p+r-map]
(let [new-project (process-project (get-in p+r-map [:parameters, :data :project])),
old-project (process-project (get-in p+r-map [:parameters, :data :oldproject])),
projectnumber-changed? (not (t/equal? (:projectnumber old-project) (:projectnumber new-project))),
changed-attributes (seq (changed-project-attributes old-project, new-project)),
completed? (and (= 0 (:done old-project)) (= 1 (:done new-project))),
customer-notification-changed? (not= (:notifycustomer new-project) (:notifycustomer old-project))
notifiedusers-delta (first (data/diff (:notifiedusers new-project) (:notifiedusers old-project)))
added-users (user-notification-map->vector 1, notifiedusers-delta),
removed-users (user-notification-map->vector 0, notifiedusers-delta),
staff-notification-changed? (or (pos? (count added-users)) (pos? (count removed-users))),
state-changes (->> (map #(= (:state %1) (:state %2)) (:projectsteps old-project) (:projectsteps new-project))
(remove true?)
count),
changed-step-diff (diff/describe-modifications (diff/step-modifications (:projectsteps new-project), (:projectsteps old-project))),
;TODO: let changed-module-diff call with (diff/module-modifications (:textmodules new-project), (:textmodules old-project))
diff (cond-> []
projectnumber-changed?
(conj (format "Project \"%s\" has been renamed to \"%s\"." (:projectnumber old-project) (:projectnumber new-project)))
completed?
(conj "Project has been completed.")
(and (not completed?) (pos? state-changes))
(conj (format "The state of %s project steps has changed. (%s/%s completed)" state-changes, (:finished-step-count new-project), (:step-count new-project)))
changed-attributes
(conj (format "Changed project attributes: %s" (str/join ", " changed-attributes)))
customer-notification-changed?
(conj (if (= 1 (:notifycustomer new-project)) "The customer will be notified about project step completion." "The customer is not notified about project step completion anymore."))
staff-notification-changed?
(conj (str "The notified staff has been changed:\n"
(str/join "\n"
(remove nil?
[(when (seq added-users)
(str " added: " (str/join ", " added-users)))
(when (seq removed-users)
(str " removed: " (str/join ", " removed-users)))]))
"."))
(or projectnumber-changed? completed? (pos? state-changes))
(conj "")
changed-step-diff
(into changed-step-diff))];end of cond, end of let
(when (seq diff)
(str/join "\n" diff))))
(defn load-project
[project-id]
(process-project (crud/read-project project-id)))
(defn filter2
"Filter the elements of xs based on a predicate applied to the values of xs and ys at the same sequential position.
If #xs > ys#, the funtion can filter at most #ys elements. The predicate is defined to be false for the remaining elements of xs."
[pred, xs, ys]
(let [xs (common/->vector xs),
ys (common/->vector ys),
nx (count xs),
ny (count ys),
n (min nx, ny)]
(loop [i 0, result (transient [])]
(if (< i n)
(let [x_i (nth xs i),
y_i (nth ys i)]
(recur
(unchecked-inc i),
(cond-> result (pred x_i, y_i) (conj! x_i))))
(persistent! result)))))
(defn progress-information
"Determines the progress information that can be included in notification e-mails."
[new-project, old-project]
(let [completed-steps (filter2
(fn [new-step, old-step]
(and
(== (:state new-step) 1)
(== (:state old-step) 0)))
(sort-by :id (:projectsteps new-project)),
(sort-by :id (:projectsteps old-project))),
n (count completed-steps),
step-information (->> completed-steps
(sort-by :sequence)
(mapv
(fn [{:keys [type, freetext]}]
(format "Step: %s\n%s", type, (if (str/blank? freetext) "" (str "\n " (str/replace freetext "\n" "\n ")))))))]
(str/join "\n\n"
(list*
(format "The following %s been completed:" (if (< 1 n) (str n " steps have") "step has"))
(cond-> step-information
(== (:done new-project) 1) (conj "The project has been finished."))))))
(defn step-completion-notification
[new-project, old-project]
(try
(let [notifycustomer (== (:notifycustomer new-project) 1),
notifiedusers (user-notification-map->vector 1 (:notifiedusers new-project))]
(when (or notifycustomer (seq notifiedusers))
(mail/send-project-notification-mail
(assoc new-project
:progressinfo (progress-information new-project, old-project),
:trackinglink (render-tracking-link (:trackingnr new-project))
:editlink (render-edit-link (:id new-project))),
(crud/user-email-addresses notifiedusers),
:project-progress)))
(catch Throwable t
(log/errorf "Failed to determine step completion before sending the notification e-mails. Error:\n%s"
(with-out-str (print-cause-trace t))))))
(defn completion
[{:keys [finished-step-count, projectsteps]}]
(/ (double finished-step-count) (count projectsteps)))
(defn customer-map
[project]
(let [customers (map-indexed #(assoc (crud/normalize-customer-data %2) :sequence %1) (:customers project))]
(zipmap (map #(select-keys % [:name :email]) customers) customers)))
(defn customers-diff
[new-project, old-project]
(let [old-customer-map (customer-map old-project),
[only-new-customers, only-old-customers] (data/diff (customer-map new-project), old-customer-map)]
(reduce
(fn [result-map, name+email]
(if (contains? only-new-customers name+email)
(if (contains? only-old-customers name+email)
; customer has been modified (e.g. sequence)
(update-in result-map [:modified-customers] conj (merge name+email (get only-new-customers name+email)))
; customer has been added
(update-in result-map [:added-customers] conj (get only-new-customers name+email)))
; customer has been removed
(update-in result-map [:removed-customers] conj (get only-old-customers name+email))))
{:added-customers [],
:removed-customers [],
:modified-customers []}
(distinct (concat (keys only-new-customers) (keys only-old-customers))))))
(t/defaction update-project
"Updates the changes to a project. Marks a project as completed when all steps are completed."
{:description "Project \"{{parameters.data.project.projectnumber}}\" updated",
;:capture (load-project (:id project)),
:message project-diff,
:projectid "{{result.body.projectid}}"
:error "Update of project \"{{parameters.data.project.projectnumber}}\" failed",
:action-type :update}
[{new-project :project, old-project :oldproject :as data}]
(let [new-project (process-project new-project),
old-project (process-project old-project),
project-diff (-> (data/diff (dissoc new-project :projectsteps), (dissoc old-project :projectsteps))
; extract modifications of the new project (newest wins with respect to modified properties)
first
; add project id to diff
(assoc :id (:id old-project))
; remove :notifiedusers since the diff is handled separately
(dissoc :notifiedusers)),
step-changes (diff/step-modifications (:projectsteps new-project), (:projectsteps old-project))
;TODO: let module-changes (diff/module-modifications (:textmodules new-project), (:textmodules old-project))
notifiedusers-delta (first (data/diff (:notifiedusers new-project) (:notifiedusers old-project))),
added-users (user-notification-map->vector 1, notifiedusers-delta),
removed-users (user-notification-map->vector 0, notifiedusers-delta),
{:keys [added-customers, removed-customers, modified-customers]} (customers-diff new-project, old-project),
project-id (:id new-project),
steps-completed? (> (completion new-project) (completion old-project))]
; update of notified users must be handled here to determine the differences
(if (and
(crud/update-project project-diff, step-changes)
(crud/add-customers project-id, added-customers)
(crud/modify-customers project-id, modified-customers)
(crud/remove-customers project-id, removed-customers)
(crud/add-notified-user-for-project project-id, added-users)
(crud/remove-notified-user-from-project project-id, removed-users))
(do
; after everything has been update sent notification (if needed and specified)
(when (and steps-completed? (c/send-mail?))
(future (step-completion-notification new-project, old-project)))
{:status 200, :body {:projectid project-id}})
{:status 500})))
(defn- create-filename
"Builds filename"
[tmp-file-name nr]
(str (c/upload-path) nr "/" tmp-file-name))
(defn upload
"File upload. Needs multi-param-file and tracking number"
[file nr]
(if (and file nr)
(let [tmp-file (:tempfile file)
new-file-name (create-filename (:filename file) nr)
new-file (io/file new-file-name)]
(.mkdirs (io/file (str (c/upload-path) nr)))
(io/copy tmp-file new-file)
{:status 200})
{:status 500}))
(t/defaction delete-project
"Delete Project with id"
{:description "Project \"{{captured.projectnumber}}\" deleted",
:capture (load-project id),
:error "Failed to delete project \"{{captured.projectnumber}}\"",
:action-type :delete}
[id]
(if (crud/delete-project id)
{:status 200, :body {}}
{:status 500}))
|
[
{
"context": " (catch Throwable e))\n `(do ~@body)))\n\n;; From Medley, C Weavejester\n(defn editable? [coll]\n (instance",
"end": 1221,
"score": 0.9992226958274841,
"start": 1215,
"tag": "NAME",
"value": "Medley"
},
{
"context": " Throwable e))\n `(do ~@body)))\n\n;; From Medley, C Weavejester\n(defn editable? [coll]\n (instance? clojure.lang.",
"end": 1236,
"score": 0.9990116357803345,
"start": 1223,
"tag": "NAME",
"value": "C Weavejester"
}
] | src/java_time/util.clj | robdaemon/clojure.java-time | 405 | (ns java-time.util
(:require [clojure.string :as string])
(:import [java.lang.reflect Field]))
(defn get-static-fields-of-type [^Class klass, ^Class of-type]
(->> (seq (.getFields klass))
(map (fn [^Field f]
(when (.isAssignableFrom of-type (.getType f))
[(.getName f) (.get f nil)])) )
(keep identity)
(into {})))
(defn dashize [camelcase]
(let [words (re-seq #"([^A-Z]+|[A-Z]+[^A-Z]*)" camelcase)]
(string/join "-" (map (comp string/lower-case first) words))))
(defmacro if-threeten-extra [then-body else-body]
(if (try (Class/forName "org.threeten.extra.Temporals")
(catch Throwable e))
`(do ~then-body)
`(do ~else-body)))
(defmacro when-threeten-extra [& body]
(if (try (Class/forName "org.threeten.extra.Temporals")
(catch Throwable e))
`(do ~@body)))
(defmacro when-joda-time-loaded
"Execute the `body` when Joda-Time classes are found on the classpath.
Take care - when AOT-compiling code using this macro, the Joda-Time classes
must be on the classpath at compile time!"
[& body]
(if (try (Class/forName "org.joda.time.DateTime")
(catch Throwable e))
`(do ~@body)))
;; From Medley, C Weavejester
(defn editable? [coll]
(instance? clojure.lang.IEditableCollection coll))
(defn reduce-map [f coll]
(if (editable? coll)
(persistent! (reduce-kv (f assoc!) (transient (empty coll)) coll))
(reduce-kv (f assoc) (empty coll) coll)))
(defn map-vals
"Maps a function over the values of an associative collection."
[f coll]
(reduce-map (fn [xf] (fn [m k v] (xf m k (f v)))) coll))
(defn map-kv
"Maps a function over the key/value pairs of an associate collection. Expects
a function that takes two arguments, the key and value, and returns the new
key and value as a collection of two elements."
[f coll]
(reduce-map (fn [xf] (fn [m k v] (let [[k v] (f k v)] (xf m k v)))) coll))
| 70587 | (ns java-time.util
(:require [clojure.string :as string])
(:import [java.lang.reflect Field]))
(defn get-static-fields-of-type [^Class klass, ^Class of-type]
(->> (seq (.getFields klass))
(map (fn [^Field f]
(when (.isAssignableFrom of-type (.getType f))
[(.getName f) (.get f nil)])) )
(keep identity)
(into {})))
(defn dashize [camelcase]
(let [words (re-seq #"([^A-Z]+|[A-Z]+[^A-Z]*)" camelcase)]
(string/join "-" (map (comp string/lower-case first) words))))
(defmacro if-threeten-extra [then-body else-body]
(if (try (Class/forName "org.threeten.extra.Temporals")
(catch Throwable e))
`(do ~then-body)
`(do ~else-body)))
(defmacro when-threeten-extra [& body]
(if (try (Class/forName "org.threeten.extra.Temporals")
(catch Throwable e))
`(do ~@body)))
(defmacro when-joda-time-loaded
"Execute the `body` when Joda-Time classes are found on the classpath.
Take care - when AOT-compiling code using this macro, the Joda-Time classes
must be on the classpath at compile time!"
[& body]
(if (try (Class/forName "org.joda.time.DateTime")
(catch Throwable e))
`(do ~@body)))
;; From <NAME>, <NAME>
(defn editable? [coll]
(instance? clojure.lang.IEditableCollection coll))
(defn reduce-map [f coll]
(if (editable? coll)
(persistent! (reduce-kv (f assoc!) (transient (empty coll)) coll))
(reduce-kv (f assoc) (empty coll) coll)))
(defn map-vals
"Maps a function over the values of an associative collection."
[f coll]
(reduce-map (fn [xf] (fn [m k v] (xf m k (f v)))) coll))
(defn map-kv
"Maps a function over the key/value pairs of an associate collection. Expects
a function that takes two arguments, the key and value, and returns the new
key and value as a collection of two elements."
[f coll]
(reduce-map (fn [xf] (fn [m k v] (let [[k v] (f k v)] (xf m k v)))) coll))
| true | (ns java-time.util
(:require [clojure.string :as string])
(:import [java.lang.reflect Field]))
(defn get-static-fields-of-type [^Class klass, ^Class of-type]
(->> (seq (.getFields klass))
(map (fn [^Field f]
(when (.isAssignableFrom of-type (.getType f))
[(.getName f) (.get f nil)])) )
(keep identity)
(into {})))
(defn dashize [camelcase]
(let [words (re-seq #"([^A-Z]+|[A-Z]+[^A-Z]*)" camelcase)]
(string/join "-" (map (comp string/lower-case first) words))))
(defmacro if-threeten-extra [then-body else-body]
(if (try (Class/forName "org.threeten.extra.Temporals")
(catch Throwable e))
`(do ~then-body)
`(do ~else-body)))
(defmacro when-threeten-extra [& body]
(if (try (Class/forName "org.threeten.extra.Temporals")
(catch Throwable e))
`(do ~@body)))
(defmacro when-joda-time-loaded
"Execute the `body` when Joda-Time classes are found on the classpath.
Take care - when AOT-compiling code using this macro, the Joda-Time classes
must be on the classpath at compile time!"
[& body]
(if (try (Class/forName "org.joda.time.DateTime")
(catch Throwable e))
`(do ~@body)))
;; From PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI
(defn editable? [coll]
(instance? clojure.lang.IEditableCollection coll))
(defn reduce-map [f coll]
(if (editable? coll)
(persistent! (reduce-kv (f assoc!) (transient (empty coll)) coll))
(reduce-kv (f assoc) (empty coll) coll)))
(defn map-vals
"Maps a function over the values of an associative collection."
[f coll]
(reduce-map (fn [xf] (fn [m k v] (xf m k (f v)))) coll))
(defn map-kv
"Maps a function over the key/value pairs of an associate collection. Expects
a function that takes two arguments, the key and value, and returns the new
key and value as a collection of two elements."
[f coll]
(reduce-map (fn [xf] (fn [m k v] (let [[k v] (f k v)] (xf m k v)))) coll))
|
[
{
"context": "; Copyright (C) 2017 Joseph Fosco. All Rights Reserved\n;\n; This program is free ",
"end": 37,
"score": 0.9998456835746765,
"start": 25,
"tag": "NAME",
"value": "Joseph Fosco"
}
] | data/test/clojure/61fc616b827a95e16a11094d2b631f9fac078ea4motif.clj | harshp8l/deep-learning-lang-detection | 84 | ; Copyright (C) 2017 Joseph Fosco. All Rights Reserved
;
; This program is free software: you can redistribute it and/or modify
; it under the terms of the GNU General Public License as published by
; the Free Software Foundation, either version 3 of the License, or
; (at your option) any later version.
;
; This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU General Public License for more details.
;
; You should have received a copy of the GNU General Public License
; along with this program. If not, see <http://www.gnu.org/licenses/>.
(ns transit.player.structures.motif
(:require
[transit.player.structures.base-structure :refer [create-base-structure
get-base-strength
]]
)
)
(defrecord Motif [base
strength-fn
melody-fn
melody-event-ids
type ;; FREE or METERED (METERED has mm and rhythmic values)
complete? ;; is this a complete motif
])
(defn create-motif
[& {:keys [melody-event-ids type complete?]} :or
{melody-event-ids nil complete? false}]
(Motif. (create-base-structure)
get-strength
get-melody-event
melody-event-ids
type
complete?
)
)
(defn get-strength
[motif]
(get-base-strength (:base motif))
)
(defn get-melody-event
[player motif next-id]
(create-melody-event
:id next-id
:note 60
:dur-info (DurInfo. 500 nil)
:volume 0.7
:instrument-info (:instrument-info player)
:player-id player-id
:event-time nil
)
)
| 121005 | ; Copyright (C) 2017 <NAME>. All Rights Reserved
;
; This program is free software: you can redistribute it and/or modify
; it under the terms of the GNU General Public License as published by
; the Free Software Foundation, either version 3 of the License, or
; (at your option) any later version.
;
; This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU General Public License for more details.
;
; You should have received a copy of the GNU General Public License
; along with this program. If not, see <http://www.gnu.org/licenses/>.
(ns transit.player.structures.motif
(:require
[transit.player.structures.base-structure :refer [create-base-structure
get-base-strength
]]
)
)
(defrecord Motif [base
strength-fn
melody-fn
melody-event-ids
type ;; FREE or METERED (METERED has mm and rhythmic values)
complete? ;; is this a complete motif
])
(defn create-motif
[& {:keys [melody-event-ids type complete?]} :or
{melody-event-ids nil complete? false}]
(Motif. (create-base-structure)
get-strength
get-melody-event
melody-event-ids
type
complete?
)
)
(defn get-strength
[motif]
(get-base-strength (:base motif))
)
(defn get-melody-event
[player motif next-id]
(create-melody-event
:id next-id
:note 60
:dur-info (DurInfo. 500 nil)
:volume 0.7
:instrument-info (:instrument-info player)
:player-id player-id
:event-time nil
)
)
| true | ; Copyright (C) 2017 PI:NAME:<NAME>END_PI. All Rights Reserved
;
; This program is free software: you can redistribute it and/or modify
; it under the terms of the GNU General Public License as published by
; the Free Software Foundation, either version 3 of the License, or
; (at your option) any later version.
;
; This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU General Public License for more details.
;
; You should have received a copy of the GNU General Public License
; along with this program. If not, see <http://www.gnu.org/licenses/>.
(ns transit.player.structures.motif
(:require
[transit.player.structures.base-structure :refer [create-base-structure
get-base-strength
]]
)
)
(defrecord Motif [base
strength-fn
melody-fn
melody-event-ids
type ;; FREE or METERED (METERED has mm and rhythmic values)
complete? ;; is this a complete motif
])
(defn create-motif
[& {:keys [melody-event-ids type complete?]} :or
{melody-event-ids nil complete? false}]
(Motif. (create-base-structure)
get-strength
get-melody-event
melody-event-ids
type
complete?
)
)
(defn get-strength
[motif]
(get-base-strength (:base motif))
)
(defn get-melody-event
[player motif next-id]
(create-melody-event
:id next-id
:note 60
:dur-info (DurInfo. 500 nil)
:volume 0.7
:instrument-info (:instrument-info player)
:player-id player-id
:event-time nil
)
)
|
[
{
"context": "ses fired events in a thread pool.\"\n :author \"Jeff Rose, Sam Aaron\"}\n overtone.libs.event\n (:require [o",
"end": 106,
"score": 0.9998814463615417,
"start": 97,
"tag": "NAME",
"value": "Jeff Rose"
},
{
"context": "events in a thread pool.\"\n :author \"Jeff Rose, Sam Aaron\"}\n overtone.libs.event\n (:require [overtone.uti",
"end": 117,
"score": 0.9998751282691956,
"start": 108,
"tag": "NAME",
"value": "Sam Aaron"
}
] | src/overtone/libs/event.clj | rosejn/overtone | 4 | (ns
^{:doc "A simple event system that processes fired events in a thread pool."
:author "Jeff Rose, Sam Aaron"}
overtone.libs.event
(:require [overtone.util.log :as log]
[overtone.libs.handlers :as handlers]))
(defonce handler-pool (handlers/mk-handler-pool "Overtone Event Handlers"))
(defn on-event
"Asynchronously runs handler whenever events of event-type are
fired. This asynchronous behaviour can be overridden if required -
see sync-event for more information. Events may be triggered with
the fns event and sync-event.
Takes an event-type (name of the event), a handler fn and a key (to
refer back to this handler in the future). The handler can
optionally accept a single event argument, which is a map containing
the :event-type property and any other properties specified when it
was fired.
(on-event \"/tr\" handler ::status-check )
(on-event :midi-note-down (fn [event]
(funky-bass (:note event)))
::midi-note-down-hdlr)
Handlers can return :overtone/remove-handler to be removed from the
handler list after execution."
[event-type handler key]
(log/debug "Registering async event handler:: " event-type key)
(handlers/add-handler handler-pool event-type key handler ))
(defn on-sync-event
"Synchronously runs handler whenever events of type event-type are
fired on the event handling thread i.e. causes the event handling
thread to block until all sync events have been handled. Events may
be triggered with the fns event and sync-event.
Takes an event-type (name of the event), a handler fn and a key (to
refer back to this handler in the future). The handler can
optionally accept a single event argument, which is a map containing
the :event-type property and any other properties specified when it
was fired.
(on-event \"/tr\" handler ::status-check )
(on-event :midi-note-down (fn [event]
(funky-bass (:note event)))
::midi-note-down-hdlr)
Handlers can return :overtone/remove-handler to be removed from the
handler list after execution."
[event-type handler key]
(log/debug "Registering sync event handler:: " event-type key)
(handlers/add-sync-handler handler-pool event-type key handler))
(defn remove-handler
"Remove an event handler previously registered to handle events of
event-type. Removes both sync and async handlers with a given key
for a particular event type.
(defn my-foo-handler [event] (do-stuff (:val event))
(on-event :foo my-foo-handler ::bar-key)
(event :foo :val 200) ; my-foo-handler gets called with:
; {:event-type :foo :val 200}
(remove-handler :foo ::bar-key)
(event :foo :val 200) ; my-foo-handler no longer called"
[event-type key]
(handlers/remove-handler handler-pool event-type key))
(defn remove-all-handlers
"Remove all handlers (both sync and async) for events of type
event-type."
[event-type]
(handlers/remove-event-handlers handler-pool event-type))
(defn event
"Fire an event of type event-type with any number of additional
properties.
NOTE: an event requires key/value pairs, and everything gets wrapped
into an event map. It will not work if you just pass values.
(event ::my-event)
(event ::filter-sweep-done :instrument :phat-bass)"
[event-type & args]
(log/debug "event: " event-type " " args)
(binding [overtone.libs.handlers/*log-fn* log/error]
(apply handlers/event handler-pool event-type args)))
(defn sync-event
"Runs all event handlers synchronously of type event-tye regardless
of whether they were declared as async or not. If handlers create
new threads which generate events, these will revert back to the
default behaviour of event (i.e. not forced sync). See event."
[event-type & args]
(log/debug "sync-event: " event-type args)
(binding [overtone.libs.handlers/*log-fn* log/error]
(apply handlers/sync-event handler-pool event-type args)))
| 114867 | (ns
^{:doc "A simple event system that processes fired events in a thread pool."
:author "<NAME>, <NAME>"}
overtone.libs.event
(:require [overtone.util.log :as log]
[overtone.libs.handlers :as handlers]))
(defonce handler-pool (handlers/mk-handler-pool "Overtone Event Handlers"))
(defn on-event
"Asynchronously runs handler whenever events of event-type are
fired. This asynchronous behaviour can be overridden if required -
see sync-event for more information. Events may be triggered with
the fns event and sync-event.
Takes an event-type (name of the event), a handler fn and a key (to
refer back to this handler in the future). The handler can
optionally accept a single event argument, which is a map containing
the :event-type property and any other properties specified when it
was fired.
(on-event \"/tr\" handler ::status-check )
(on-event :midi-note-down (fn [event]
(funky-bass (:note event)))
::midi-note-down-hdlr)
Handlers can return :overtone/remove-handler to be removed from the
handler list after execution."
[event-type handler key]
(log/debug "Registering async event handler:: " event-type key)
(handlers/add-handler handler-pool event-type key handler ))
(defn on-sync-event
"Synchronously runs handler whenever events of type event-type are
fired on the event handling thread i.e. causes the event handling
thread to block until all sync events have been handled. Events may
be triggered with the fns event and sync-event.
Takes an event-type (name of the event), a handler fn and a key (to
refer back to this handler in the future). The handler can
optionally accept a single event argument, which is a map containing
the :event-type property and any other properties specified when it
was fired.
(on-event \"/tr\" handler ::status-check )
(on-event :midi-note-down (fn [event]
(funky-bass (:note event)))
::midi-note-down-hdlr)
Handlers can return :overtone/remove-handler to be removed from the
handler list after execution."
[event-type handler key]
(log/debug "Registering sync event handler:: " event-type key)
(handlers/add-sync-handler handler-pool event-type key handler))
(defn remove-handler
"Remove an event handler previously registered to handle events of
event-type. Removes both sync and async handlers with a given key
for a particular event type.
(defn my-foo-handler [event] (do-stuff (:val event))
(on-event :foo my-foo-handler ::bar-key)
(event :foo :val 200) ; my-foo-handler gets called with:
; {:event-type :foo :val 200}
(remove-handler :foo ::bar-key)
(event :foo :val 200) ; my-foo-handler no longer called"
[event-type key]
(handlers/remove-handler handler-pool event-type key))
(defn remove-all-handlers
"Remove all handlers (both sync and async) for events of type
event-type."
[event-type]
(handlers/remove-event-handlers handler-pool event-type))
(defn event
"Fire an event of type event-type with any number of additional
properties.
NOTE: an event requires key/value pairs, and everything gets wrapped
into an event map. It will not work if you just pass values.
(event ::my-event)
(event ::filter-sweep-done :instrument :phat-bass)"
[event-type & args]
(log/debug "event: " event-type " " args)
(binding [overtone.libs.handlers/*log-fn* log/error]
(apply handlers/event handler-pool event-type args)))
(defn sync-event
"Runs all event handlers synchronously of type event-tye regardless
of whether they were declared as async or not. If handlers create
new threads which generate events, these will revert back to the
default behaviour of event (i.e. not forced sync). See event."
[event-type & args]
(log/debug "sync-event: " event-type args)
(binding [overtone.libs.handlers/*log-fn* log/error]
(apply handlers/sync-event handler-pool event-type args)))
| true | (ns
^{:doc "A simple event system that processes fired events in a thread pool."
:author "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI"}
overtone.libs.event
(:require [overtone.util.log :as log]
[overtone.libs.handlers :as handlers]))
(defonce handler-pool (handlers/mk-handler-pool "Overtone Event Handlers"))
(defn on-event
"Asynchronously runs handler whenever events of event-type are
fired. This asynchronous behaviour can be overridden if required -
see sync-event for more information. Events may be triggered with
the fns event and sync-event.
Takes an event-type (name of the event), a handler fn and a key (to
refer back to this handler in the future). The handler can
optionally accept a single event argument, which is a map containing
the :event-type property and any other properties specified when it
was fired.
(on-event \"/tr\" handler ::status-check )
(on-event :midi-note-down (fn [event]
(funky-bass (:note event)))
::midi-note-down-hdlr)
Handlers can return :overtone/remove-handler to be removed from the
handler list after execution."
[event-type handler key]
(log/debug "Registering async event handler:: " event-type key)
(handlers/add-handler handler-pool event-type key handler ))
(defn on-sync-event
"Synchronously runs handler whenever events of type event-type are
fired on the event handling thread i.e. causes the event handling
thread to block until all sync events have been handled. Events may
be triggered with the fns event and sync-event.
Takes an event-type (name of the event), a handler fn and a key (to
refer back to this handler in the future). The handler can
optionally accept a single event argument, which is a map containing
the :event-type property and any other properties specified when it
was fired.
(on-event \"/tr\" handler ::status-check )
(on-event :midi-note-down (fn [event]
(funky-bass (:note event)))
::midi-note-down-hdlr)
Handlers can return :overtone/remove-handler to be removed from the
handler list after execution."
[event-type handler key]
(log/debug "Registering sync event handler:: " event-type key)
(handlers/add-sync-handler handler-pool event-type key handler))
(defn remove-handler
"Remove an event handler previously registered to handle events of
event-type. Removes both sync and async handlers with a given key
for a particular event type.
(defn my-foo-handler [event] (do-stuff (:val event))
(on-event :foo my-foo-handler ::bar-key)
(event :foo :val 200) ; my-foo-handler gets called with:
; {:event-type :foo :val 200}
(remove-handler :foo ::bar-key)
(event :foo :val 200) ; my-foo-handler no longer called"
[event-type key]
(handlers/remove-handler handler-pool event-type key))
(defn remove-all-handlers
"Remove all handlers (both sync and async) for events of type
event-type."
[event-type]
(handlers/remove-event-handlers handler-pool event-type))
(defn event
"Fire an event of type event-type with any number of additional
properties.
NOTE: an event requires key/value pairs, and everything gets wrapped
into an event map. It will not work if you just pass values.
(event ::my-event)
(event ::filter-sweep-done :instrument :phat-bass)"
[event-type & args]
(log/debug "event: " event-type " " args)
(binding [overtone.libs.handlers/*log-fn* log/error]
(apply handlers/event handler-pool event-type args)))
(defn sync-event
"Runs all event handlers synchronously of type event-tye regardless
of whether they were declared as async or not. If handlers create
new threads which generate events, these will revert back to the
default behaviour of event (i.e. not forced sync). See event."
[event-type & args]
(log/debug "sync-event: " event-type args)
(binding [overtone.libs.handlers/*log-fn* log/error]
(apply handlers/sync-event handler-pool event-type args)))
|
[
{
"context": "and conceptually acts as a separate process.\n;;\n;; Isaiah Peng <issaria@gmail.com>\n;;\n\n(defrecord Worker [name]\n",
"end": 363,
"score": 0.9998598098754883,
"start": 352,
"tag": "NAME",
"value": "Isaiah Peng"
},
{
"context": "ly acts as a separate process.\n;;\n;; Isaiah Peng <issaria@gmail.com>\n;;\n\n(defrecord Worker [name]\n Runnable\n (run [",
"end": 382,
"score": 0.9999273419380188,
"start": 365,
"tag": "EMAIL",
"value": "issaria@gmail.com"
}
] | docs/zeroMQ-guide2/examples/Clojure/rtdealer.clj | krattai/noo-ebs | 2 | (ns rtdealer
(:refer-clojure :exclude [send])
(:require [zhelpers :as mq])
(:import [java.util Random]))
;;
;; Custom routing Router to Dealer
;;
;; While this example runs in a single process, that is just to make
;; it easier to start and stop the example. Each thread has its own
;; context and conceptually acts as a separate process.
;;
;; Isaiah Peng <issaria@gmail.com>
;;
(defrecord Worker [name]
Runnable
(run [this]
(let [ctx (mq/context 1)
worker (mq/socket ctx mq/dealer)]
(mq/identify worker name)
(mq/connect worker "ipc://routing.ipc")
(loop [total 0]
(let [request (mq/recv-str worker)]
(if (= "END" request)
(println (format "%s received: %d" name total))
(recur (inc total))))))))
(defn -main []
(let [ctx (mq/context 1)
client (mq/socket ctx mq/dealer)
srandom (Random. (System/currentTimeMillis))]
(mq/bind client "ipc://routing.ipc")
(-> "A" Worker. Thread. .start)
(-> "B" Worker. Thread. .start)
;; Wait for threads to connect, since otherwise the messages
;; we send won't be routable.
(Thread/sleep 1000)
;; Send 10 tasks scattered to A twice as often as B
(dotimes [i 10]
;; Send two message parts, first the address...
(if (= 0 (.nextInt srandom 3))
(mq/send-more client "B")
(mq/send-more client "A"))
;; And then the workload
(mq/send client "This is the workload"))
(mq/send-more client "A")
(mq/send client "END")
(mq/send-more client "B")
(mq/send client "END")
(.close client)
(.term ctx)))
| 69618 | (ns rtdealer
(:refer-clojure :exclude [send])
(:require [zhelpers :as mq])
(:import [java.util Random]))
;;
;; Custom routing Router to Dealer
;;
;; While this example runs in a single process, that is just to make
;; it easier to start and stop the example. Each thread has its own
;; context and conceptually acts as a separate process.
;;
;; <NAME> <<EMAIL>>
;;
(defrecord Worker [name]
Runnable
(run [this]
(let [ctx (mq/context 1)
worker (mq/socket ctx mq/dealer)]
(mq/identify worker name)
(mq/connect worker "ipc://routing.ipc")
(loop [total 0]
(let [request (mq/recv-str worker)]
(if (= "END" request)
(println (format "%s received: %d" name total))
(recur (inc total))))))))
(defn -main []
(let [ctx (mq/context 1)
client (mq/socket ctx mq/dealer)
srandom (Random. (System/currentTimeMillis))]
(mq/bind client "ipc://routing.ipc")
(-> "A" Worker. Thread. .start)
(-> "B" Worker. Thread. .start)
;; Wait for threads to connect, since otherwise the messages
;; we send won't be routable.
(Thread/sleep 1000)
;; Send 10 tasks scattered to A twice as often as B
(dotimes [i 10]
;; Send two message parts, first the address...
(if (= 0 (.nextInt srandom 3))
(mq/send-more client "B")
(mq/send-more client "A"))
;; And then the workload
(mq/send client "This is the workload"))
(mq/send-more client "A")
(mq/send client "END")
(mq/send-more client "B")
(mq/send client "END")
(.close client)
(.term ctx)))
| true | (ns rtdealer
(:refer-clojure :exclude [send])
(:require [zhelpers :as mq])
(:import [java.util Random]))
;;
;; Custom routing Router to Dealer
;;
;; While this example runs in a single process, that is just to make
;; it easier to start and stop the example. Each thread has its own
;; context and conceptually acts as a separate process.
;;
;; PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;;
(defrecord Worker [name]
Runnable
(run [this]
(let [ctx (mq/context 1)
worker (mq/socket ctx mq/dealer)]
(mq/identify worker name)
(mq/connect worker "ipc://routing.ipc")
(loop [total 0]
(let [request (mq/recv-str worker)]
(if (= "END" request)
(println (format "%s received: %d" name total))
(recur (inc total))))))))
(defn -main []
(let [ctx (mq/context 1)
client (mq/socket ctx mq/dealer)
srandom (Random. (System/currentTimeMillis))]
(mq/bind client "ipc://routing.ipc")
(-> "A" Worker. Thread. .start)
(-> "B" Worker. Thread. .start)
;; Wait for threads to connect, since otherwise the messages
;; we send won't be routable.
(Thread/sleep 1000)
;; Send 10 tasks scattered to A twice as often as B
(dotimes [i 10]
;; Send two message parts, first the address...
(if (= 0 (.nextInt srandom 3))
(mq/send-more client "B")
(mq/send-more client "A"))
;; And then the workload
(mq/send client "This is the workload"))
(mq/send-more client "A")
(mq/send client "END")
(mq/send-more client "B")
(mq/send client "END")
(.close client)
(.term ctx)))
|
[
{
"context": " (println slot new old))\n v {:name \"World\"\n :action (cI nil :slot :v-action\n ",
"end": 3869,
"score": 0.9920244216918945,
"start": 3864,
"tag": "NAME",
"value": "World"
},
{
"context": " (println slot new old))\n v {:name \"World\"\n :action (cI nil\n ",
"end": 4778,
"score": 0.9936833381652832,
"start": 4773,
"tag": "NAME",
"value": "World"
},
{
"context": "hen new (trx visitor-did new)))\n v {:name \"World\"\n :action (cI nil\n ",
"end": 5852,
"score": 0.6280995607376099,
"start": 5847,
"tag": "NAME",
"value": "World"
}
] | cljs/matrix/test/tiltontec/cell/hello_cells_test.cljc | kennytilton/matrix | 84 | (ns tiltontec.cell.hello-cells-test
(:require
#?(:clj [clojure.test :refer :all]
:cljs [cljs.test
:refer-macros [deftest is are]])
#?(:cljs [tiltontec.util.base
:refer-macros [trx prog1 *trx?*]]
:clj [tiltontec.util.base
:refer :all])
[tiltontec.util.core :refer [type-of err]]
#?(:clj [tiltontec.cell.base :refer :all :as cty]
:cljs [tiltontec.cell.base
:refer-macros [without-c-dependency]
:refer [cells-init c-optimized-away? c-formula? c-value c-optimize
c-unbound? c-input? ia-type?
c-model mdead? c-valid? c-useds c-ref? md-ref?
c-state +pulse+ c-pulse-observed
*call-stack* *defer-changes* unbound
c-rule c-me c-value-state c-callers caller-ensure
unlink-from-callers *causation*
c-slot-name c-synaptic? caller-drop
c-pulse c-pulse-last-changed c-ephemeral? c-slot c-slots
*depender* *not-to-be*
*c-prop-depth* md-slot-owning? c-lazy] :as cty])
#?(:cljs [tiltontec.cell.integrity
:refer-macros [with-integrity]]
:clj [tiltontec.cell.integrity :refer [with-integrity]])
#?(:clj [tiltontec.cell.observer
:refer [defobserver fn-obs]]
:cljs [tiltontec.cell.observer
:refer-macros [defobserver fn-obs]])
#?(:cljs [tiltontec.cell.core
:refer-macros [cF cF+ c-reset-next! cFonce cFn]
:refer [cI c-reset! make-cell make-c-formula]]
:clj [tiltontec.cell.core :refer :all])
[tiltontec.cell.evaluate :refer [c-get c-awaken]]
))
(deftest hw-01
(let [v ;;"visitor"
{:name "World"
:action (make-cell :value "knocks"
:input? true)}]
(println (c-get (:name v))
(c-get (:action v)))
(is (= (c-get (:name v)) "World"))
(is (= (c-get (:action v)) "knocks"))))
(deftest hw-02
(let [obs-action (atom nil)
v ;;"visitor"
{:name "World"
:action (cI nil
:slot :v-action
:obs ;; short for observer
(fn [slot me new old c]
(reset! obs-action new)
(println :observing slot new old)))}]
(is (= (c-get (:name v)) "World"))
(c-reset! (:action v) "knocks")
(is (= (c-get (:action v)) "knocks"))
(is (= "knocks" @obs-action))))
(deftest hw-03
(let [action (atom nil)
obs-action (fn [slot me new old c]
(reset! action new)
(println :observing slot new old))
v {:name "World"
:action (cI nil :slot :v-action
:obs obs-action)}]
(is (nil? (c-get (:action v))))
(is (nil? @action))
(c-reset! (:action v) "knock-knock")
(is (= "knock-knock" @action))
(is (= (c-get (:action v)) "knock-knock"))))
(defn gobs
[slot me new old c]
(println :gobs> slot new old))
(deftest hw-04
(let [r-action (cI nil
:slot :r-action
:obs gobs)
r-loc (make-c-formula
:slot :r-loc
:obs gobs
:rule (fn [c]
(case (c-get r-action)
:leave :away
:return :at-home
:missing)))]
(c-awaken r-loc)
(is (= :missing (:value @r-loc)))
(println :---about-to-leave------------------)
(c-reset! r-action :leave)
(println :---left------------------)
(is (= :away (c-get r-loc)))))
(deftest hw-5
(println :--go------------------)
(let [obs-action (fn [slot me new old c]
(println slot new old))
v {:name "World"
:action (cI nil :slot :v-action
:obs obs-action)}
r-action (cI nil)
r-loc (cF+ [:obs (fn-obs (when new (trx :honey-im new)))]
(case (c-get r-action)
:leave :away
:return :home
:missing))
r-response (cF+ [:obs (fn-obs (trx :r-resp new))]
(when (= :home (c-get r-loc))
(when-let [act (c-get (:action v))]
(case act
:knock-knock "hello, world"))))]
(is (nil? (c-get r-response)))
(c-reset! (:action v) :knock-knock)
(c-reset! r-action :return)
(is (= :home (c-get r-loc)))))
(deftest hello-world
(println :--go------------------)
(let [obs-action (fn [slot me new old c]
(println slot new old))
v {:name "World"
:action (cI nil
:slot :v-action
:ephemeral? true
:obs obs-action)}
r-action (cI nil)
r-loc (cF+ [:obs (fn-obs (when new (trx :honey-im new)))]
(case (c-get r-action)
:leave :away
:return :home
:missing))
r-response (cF+ [:obs (fn-obs (trx :r-response new))
:ephemeral? true]
(when (= :home (c-get r-loc))
(when-let [act (c-get (:action v))]
(case act
:knock-knock "hello, world"))))]
(is (nil? (c-get r-response)))
(c-reset! (:action v) :knock-knock)
(c-reset! r-action :return)
(is (= :home (c-get r-loc)))
(c-reset! (:action v) :knock-knock)))
(deftest hello-world-2
(println :--go------------------)
(let [obs-action (fn [slot me new old c]
(when new (trx visitor-did new)))
v {:name "World"
:action (cI nil
:slot :v-action
:ephemeral? true
:obs obs-action)}
r-action (cI nil)
r-loc (cF+ [:obs (fn-obs (when new (trx :honey-im new)))]
(case (c-get r-action)
:leave :away
:return :home
:missing))
r-response (cF+ [:obs (fn-obs (when new
(trx :r-response new)))
:ephemeral? true
]
(when (= :home (c-get r-loc))
(when-let [act (c-get (:action v))]
(case act
:knock-knock "hello, world"))))
alarm (cF+ [:obs (fn-obs
(trx :telling-alarm-api new))]
(if (= :home (c-get r-loc)) :off :on))
alarm-do (cF+ [:obs (fn-obs
(case new
:call-police (trx :auto-dialing-911)
nil))]
(when (= :on (c-get alarm))
(when-let [action (c-get (:action v))]
(case action
:smashing-window :call-police
nil))))]
(c-awaken [alarm-do r-response r-loc (:action v)])
(is (= :missing (:value @r-loc)))
(c-reset! (:action v) :knock-knock)
(c-reset! (:action v) :smashing-window)
(c-reset! r-action :return)
(is (= :home (c-get r-loc)))
(c-reset! (:action v) :knock-knock)
))
#?(:cljs (do
(cljs.test/run-tests)
))
| 18444 | (ns tiltontec.cell.hello-cells-test
(:require
#?(:clj [clojure.test :refer :all]
:cljs [cljs.test
:refer-macros [deftest is are]])
#?(:cljs [tiltontec.util.base
:refer-macros [trx prog1 *trx?*]]
:clj [tiltontec.util.base
:refer :all])
[tiltontec.util.core :refer [type-of err]]
#?(:clj [tiltontec.cell.base :refer :all :as cty]
:cljs [tiltontec.cell.base
:refer-macros [without-c-dependency]
:refer [cells-init c-optimized-away? c-formula? c-value c-optimize
c-unbound? c-input? ia-type?
c-model mdead? c-valid? c-useds c-ref? md-ref?
c-state +pulse+ c-pulse-observed
*call-stack* *defer-changes* unbound
c-rule c-me c-value-state c-callers caller-ensure
unlink-from-callers *causation*
c-slot-name c-synaptic? caller-drop
c-pulse c-pulse-last-changed c-ephemeral? c-slot c-slots
*depender* *not-to-be*
*c-prop-depth* md-slot-owning? c-lazy] :as cty])
#?(:cljs [tiltontec.cell.integrity
:refer-macros [with-integrity]]
:clj [tiltontec.cell.integrity :refer [with-integrity]])
#?(:clj [tiltontec.cell.observer
:refer [defobserver fn-obs]]
:cljs [tiltontec.cell.observer
:refer-macros [defobserver fn-obs]])
#?(:cljs [tiltontec.cell.core
:refer-macros [cF cF+ c-reset-next! cFonce cFn]
:refer [cI c-reset! make-cell make-c-formula]]
:clj [tiltontec.cell.core :refer :all])
[tiltontec.cell.evaluate :refer [c-get c-awaken]]
))
(deftest hw-01
(let [v ;;"visitor"
{:name "World"
:action (make-cell :value "knocks"
:input? true)}]
(println (c-get (:name v))
(c-get (:action v)))
(is (= (c-get (:name v)) "World"))
(is (= (c-get (:action v)) "knocks"))))
(deftest hw-02
(let [obs-action (atom nil)
v ;;"visitor"
{:name "World"
:action (cI nil
:slot :v-action
:obs ;; short for observer
(fn [slot me new old c]
(reset! obs-action new)
(println :observing slot new old)))}]
(is (= (c-get (:name v)) "World"))
(c-reset! (:action v) "knocks")
(is (= (c-get (:action v)) "knocks"))
(is (= "knocks" @obs-action))))
(deftest hw-03
(let [action (atom nil)
obs-action (fn [slot me new old c]
(reset! action new)
(println :observing slot new old))
v {:name "World"
:action (cI nil :slot :v-action
:obs obs-action)}]
(is (nil? (c-get (:action v))))
(is (nil? @action))
(c-reset! (:action v) "knock-knock")
(is (= "knock-knock" @action))
(is (= (c-get (:action v)) "knock-knock"))))
(defn gobs
[slot me new old c]
(println :gobs> slot new old))
(deftest hw-04
(let [r-action (cI nil
:slot :r-action
:obs gobs)
r-loc (make-c-formula
:slot :r-loc
:obs gobs
:rule (fn [c]
(case (c-get r-action)
:leave :away
:return :at-home
:missing)))]
(c-awaken r-loc)
(is (= :missing (:value @r-loc)))
(println :---about-to-leave------------------)
(c-reset! r-action :leave)
(println :---left------------------)
(is (= :away (c-get r-loc)))))
(deftest hw-5
(println :--go------------------)
(let [obs-action (fn [slot me new old c]
(println slot new old))
v {:name "<NAME>"
:action (cI nil :slot :v-action
:obs obs-action)}
r-action (cI nil)
r-loc (cF+ [:obs (fn-obs (when new (trx :honey-im new)))]
(case (c-get r-action)
:leave :away
:return :home
:missing))
r-response (cF+ [:obs (fn-obs (trx :r-resp new))]
(when (= :home (c-get r-loc))
(when-let [act (c-get (:action v))]
(case act
:knock-knock "hello, world"))))]
(is (nil? (c-get r-response)))
(c-reset! (:action v) :knock-knock)
(c-reset! r-action :return)
(is (= :home (c-get r-loc)))))
(deftest hello-world
(println :--go------------------)
(let [obs-action (fn [slot me new old c]
(println slot new old))
v {:name "<NAME>"
:action (cI nil
:slot :v-action
:ephemeral? true
:obs obs-action)}
r-action (cI nil)
r-loc (cF+ [:obs (fn-obs (when new (trx :honey-im new)))]
(case (c-get r-action)
:leave :away
:return :home
:missing))
r-response (cF+ [:obs (fn-obs (trx :r-response new))
:ephemeral? true]
(when (= :home (c-get r-loc))
(when-let [act (c-get (:action v))]
(case act
:knock-knock "hello, world"))))]
(is (nil? (c-get r-response)))
(c-reset! (:action v) :knock-knock)
(c-reset! r-action :return)
(is (= :home (c-get r-loc)))
(c-reset! (:action v) :knock-knock)))
(deftest hello-world-2
(println :--go------------------)
(let [obs-action (fn [slot me new old c]
(when new (trx visitor-did new)))
v {:name "<NAME>"
:action (cI nil
:slot :v-action
:ephemeral? true
:obs obs-action)}
r-action (cI nil)
r-loc (cF+ [:obs (fn-obs (when new (trx :honey-im new)))]
(case (c-get r-action)
:leave :away
:return :home
:missing))
r-response (cF+ [:obs (fn-obs (when new
(trx :r-response new)))
:ephemeral? true
]
(when (= :home (c-get r-loc))
(when-let [act (c-get (:action v))]
(case act
:knock-knock "hello, world"))))
alarm (cF+ [:obs (fn-obs
(trx :telling-alarm-api new))]
(if (= :home (c-get r-loc)) :off :on))
alarm-do (cF+ [:obs (fn-obs
(case new
:call-police (trx :auto-dialing-911)
nil))]
(when (= :on (c-get alarm))
(when-let [action (c-get (:action v))]
(case action
:smashing-window :call-police
nil))))]
(c-awaken [alarm-do r-response r-loc (:action v)])
(is (= :missing (:value @r-loc)))
(c-reset! (:action v) :knock-knock)
(c-reset! (:action v) :smashing-window)
(c-reset! r-action :return)
(is (= :home (c-get r-loc)))
(c-reset! (:action v) :knock-knock)
))
#?(:cljs (do
(cljs.test/run-tests)
))
| true | (ns tiltontec.cell.hello-cells-test
(:require
#?(:clj [clojure.test :refer :all]
:cljs [cljs.test
:refer-macros [deftest is are]])
#?(:cljs [tiltontec.util.base
:refer-macros [trx prog1 *trx?*]]
:clj [tiltontec.util.base
:refer :all])
[tiltontec.util.core :refer [type-of err]]
#?(:clj [tiltontec.cell.base :refer :all :as cty]
:cljs [tiltontec.cell.base
:refer-macros [without-c-dependency]
:refer [cells-init c-optimized-away? c-formula? c-value c-optimize
c-unbound? c-input? ia-type?
c-model mdead? c-valid? c-useds c-ref? md-ref?
c-state +pulse+ c-pulse-observed
*call-stack* *defer-changes* unbound
c-rule c-me c-value-state c-callers caller-ensure
unlink-from-callers *causation*
c-slot-name c-synaptic? caller-drop
c-pulse c-pulse-last-changed c-ephemeral? c-slot c-slots
*depender* *not-to-be*
*c-prop-depth* md-slot-owning? c-lazy] :as cty])
#?(:cljs [tiltontec.cell.integrity
:refer-macros [with-integrity]]
:clj [tiltontec.cell.integrity :refer [with-integrity]])
#?(:clj [tiltontec.cell.observer
:refer [defobserver fn-obs]]
:cljs [tiltontec.cell.observer
:refer-macros [defobserver fn-obs]])
#?(:cljs [tiltontec.cell.core
:refer-macros [cF cF+ c-reset-next! cFonce cFn]
:refer [cI c-reset! make-cell make-c-formula]]
:clj [tiltontec.cell.core :refer :all])
[tiltontec.cell.evaluate :refer [c-get c-awaken]]
))
(deftest hw-01
(let [v ;;"visitor"
{:name "World"
:action (make-cell :value "knocks"
:input? true)}]
(println (c-get (:name v))
(c-get (:action v)))
(is (= (c-get (:name v)) "World"))
(is (= (c-get (:action v)) "knocks"))))
(deftest hw-02
(let [obs-action (atom nil)
v ;;"visitor"
{:name "World"
:action (cI nil
:slot :v-action
:obs ;; short for observer
(fn [slot me new old c]
(reset! obs-action new)
(println :observing slot new old)))}]
(is (= (c-get (:name v)) "World"))
(c-reset! (:action v) "knocks")
(is (= (c-get (:action v)) "knocks"))
(is (= "knocks" @obs-action))))
(deftest hw-03
(let [action (atom nil)
obs-action (fn [slot me new old c]
(reset! action new)
(println :observing slot new old))
v {:name "World"
:action (cI nil :slot :v-action
:obs obs-action)}]
(is (nil? (c-get (:action v))))
(is (nil? @action))
(c-reset! (:action v) "knock-knock")
(is (= "knock-knock" @action))
(is (= (c-get (:action v)) "knock-knock"))))
(defn gobs
[slot me new old c]
(println :gobs> slot new old))
(deftest hw-04
(let [r-action (cI nil
:slot :r-action
:obs gobs)
r-loc (make-c-formula
:slot :r-loc
:obs gobs
:rule (fn [c]
(case (c-get r-action)
:leave :away
:return :at-home
:missing)))]
(c-awaken r-loc)
(is (= :missing (:value @r-loc)))
(println :---about-to-leave------------------)
(c-reset! r-action :leave)
(println :---left------------------)
(is (= :away (c-get r-loc)))))
(deftest hw-5
(println :--go------------------)
(let [obs-action (fn [slot me new old c]
(println slot new old))
v {:name "PI:NAME:<NAME>END_PI"
:action (cI nil :slot :v-action
:obs obs-action)}
r-action (cI nil)
r-loc (cF+ [:obs (fn-obs (when new (trx :honey-im new)))]
(case (c-get r-action)
:leave :away
:return :home
:missing))
r-response (cF+ [:obs (fn-obs (trx :r-resp new))]
(when (= :home (c-get r-loc))
(when-let [act (c-get (:action v))]
(case act
:knock-knock "hello, world"))))]
(is (nil? (c-get r-response)))
(c-reset! (:action v) :knock-knock)
(c-reset! r-action :return)
(is (= :home (c-get r-loc)))))
(deftest hello-world
(println :--go------------------)
(let [obs-action (fn [slot me new old c]
(println slot new old))
v {:name "PI:NAME:<NAME>END_PI"
:action (cI nil
:slot :v-action
:ephemeral? true
:obs obs-action)}
r-action (cI nil)
r-loc (cF+ [:obs (fn-obs (when new (trx :honey-im new)))]
(case (c-get r-action)
:leave :away
:return :home
:missing))
r-response (cF+ [:obs (fn-obs (trx :r-response new))
:ephemeral? true]
(when (= :home (c-get r-loc))
(when-let [act (c-get (:action v))]
(case act
:knock-knock "hello, world"))))]
(is (nil? (c-get r-response)))
(c-reset! (:action v) :knock-knock)
(c-reset! r-action :return)
(is (= :home (c-get r-loc)))
(c-reset! (:action v) :knock-knock)))
(deftest hello-world-2
(println :--go------------------)
(let [obs-action (fn [slot me new old c]
(when new (trx visitor-did new)))
v {:name "PI:NAME:<NAME>END_PI"
:action (cI nil
:slot :v-action
:ephemeral? true
:obs obs-action)}
r-action (cI nil)
r-loc (cF+ [:obs (fn-obs (when new (trx :honey-im new)))]
(case (c-get r-action)
:leave :away
:return :home
:missing))
r-response (cF+ [:obs (fn-obs (when new
(trx :r-response new)))
:ephemeral? true
]
(when (= :home (c-get r-loc))
(when-let [act (c-get (:action v))]
(case act
:knock-knock "hello, world"))))
alarm (cF+ [:obs (fn-obs
(trx :telling-alarm-api new))]
(if (= :home (c-get r-loc)) :off :on))
alarm-do (cF+ [:obs (fn-obs
(case new
:call-police (trx :auto-dialing-911)
nil))]
(when (= :on (c-get alarm))
(when-let [action (c-get (:action v))]
(case action
:smashing-window :call-police
nil))))]
(c-awaken [alarm-do r-response r-loc (:action v)])
(is (= :missing (:value @r-loc)))
(c-reset! (:action v) :knock-knock)
(c-reset! (:action v) :smashing-window)
(c-reset! r-action :return)
(is (= :home (c-get r-loc)))
(c-reset! (:action v) :knock-knock)
))
#?(:cljs (do
(cljs.test/run-tests)
))
|
[
{
"context": "[mysql/mysql-connector-java \"5.1.41\"]\n [seancorfield/next.jdbc \"1.0.424\"]])\n\n(require '[next.jdbc :as ",
"end": 574,
"score": 0.791438102722168,
"start": 564,
"tag": "USERNAME",
"value": "ancorfield"
},
{
"context": "q77-db\n {:dbtype \"mysql\" :user \"root\" :password \"the-pw\" :dbname \"refseq77\"})\n(def r77con (-> refseq77-db",
"end": 929,
"score": 0.9994408488273621,
"start": 923,
"tag": "PASSWORD",
"value": "the-pw"
}
] | resources/Code/TMD/tmd-tc-deps-req.clj | jsa-aerial/aerosaite | 0 |
;;; Base deps and requires for TMD and TC
(deps '[[techascent/tech.ml.dataset "6.065"]
[scicloj/tablecloth "6.051"]])
(require '[tech.v3.dataset :as ds]
'[tech.v3.datatype :as dtype]
'[tech.v3.datatype.functional :as df]
'[tech.v3.dataset.reductions :as dsr]
'[tablecloth.api :as tc])
;;; If you are using SQL, first need connector and next.jdbc
;;; next.jdbc supports data-source connection that is a java
;;; connector class instance suitable for TMD.SQL
(deps '[[mysql/mysql-connector-java "5.1.41"]
[seancorfield/next.jdbc "1.0.424"]])
(require '[next.jdbc :as jdbc]
'[next.jdbc.result-set :as rs])
;;; Actual tmd.sql deps / requires
(deps '[[techascent/tech.ml.dataset.sql "6.046-01"]])
(require '[tech.v3.dataset.sql :as dsql])
;;; Example data-source and connection usable by tmd.sql:
(def refseq77-db
{:dbtype "mysql" :user "root" :password "the-pw" :dbname "refseq77"})
(def r77con (-> refseq77-db jdbc/get-datasource jdbc/get-connection))
;;; Now r77con is usable by tmd.sql:
(dsql/sql->dataset r77con "select count(*) from bioentry")
(require '[tech.v3.dataset.rolling :as drl]
'[tech.v3.dataset.column :as dsc])
(-> [[:a [1 2 3]] [:b [6 7 8]]]
tc/dataset
(drl/rolling {:window-type :fixed
:window-size 2
:relative-window-position :right
:edge-mode :zero}
{:suma (drl/sum :a) :sumb (drl/sum :b)})
(tc/add-column
:sum (fn[ds]
(dsc/column-map
(fn[a b] (+ a b))
:long
(ds :suma) (ds :sumb))))) | 97521 |
;;; Base deps and requires for TMD and TC
(deps '[[techascent/tech.ml.dataset "6.065"]
[scicloj/tablecloth "6.051"]])
(require '[tech.v3.dataset :as ds]
'[tech.v3.datatype :as dtype]
'[tech.v3.datatype.functional :as df]
'[tech.v3.dataset.reductions :as dsr]
'[tablecloth.api :as tc])
;;; If you are using SQL, first need connector and next.jdbc
;;; next.jdbc supports data-source connection that is a java
;;; connector class instance suitable for TMD.SQL
(deps '[[mysql/mysql-connector-java "5.1.41"]
[seancorfield/next.jdbc "1.0.424"]])
(require '[next.jdbc :as jdbc]
'[next.jdbc.result-set :as rs])
;;; Actual tmd.sql deps / requires
(deps '[[techascent/tech.ml.dataset.sql "6.046-01"]])
(require '[tech.v3.dataset.sql :as dsql])
;;; Example data-source and connection usable by tmd.sql:
(def refseq77-db
{:dbtype "mysql" :user "root" :password "<PASSWORD>" :dbname "refseq77"})
(def r77con (-> refseq77-db jdbc/get-datasource jdbc/get-connection))
;;; Now r77con is usable by tmd.sql:
(dsql/sql->dataset r77con "select count(*) from bioentry")
(require '[tech.v3.dataset.rolling :as drl]
'[tech.v3.dataset.column :as dsc])
(-> [[:a [1 2 3]] [:b [6 7 8]]]
tc/dataset
(drl/rolling {:window-type :fixed
:window-size 2
:relative-window-position :right
:edge-mode :zero}
{:suma (drl/sum :a) :sumb (drl/sum :b)})
(tc/add-column
:sum (fn[ds]
(dsc/column-map
(fn[a b] (+ a b))
:long
(ds :suma) (ds :sumb))))) | true |
;;; Base deps and requires for TMD and TC
(deps '[[techascent/tech.ml.dataset "6.065"]
[scicloj/tablecloth "6.051"]])
(require '[tech.v3.dataset :as ds]
'[tech.v3.datatype :as dtype]
'[tech.v3.datatype.functional :as df]
'[tech.v3.dataset.reductions :as dsr]
'[tablecloth.api :as tc])
;;; If you are using SQL, first need connector and next.jdbc
;;; next.jdbc supports data-source connection that is a java
;;; connector class instance suitable for TMD.SQL
(deps '[[mysql/mysql-connector-java "5.1.41"]
[seancorfield/next.jdbc "1.0.424"]])
(require '[next.jdbc :as jdbc]
'[next.jdbc.result-set :as rs])
;;; Actual tmd.sql deps / requires
(deps '[[techascent/tech.ml.dataset.sql "6.046-01"]])
(require '[tech.v3.dataset.sql :as dsql])
;;; Example data-source and connection usable by tmd.sql:
(def refseq77-db
{:dbtype "mysql" :user "root" :password "PI:PASSWORD:<PASSWORD>END_PI" :dbname "refseq77"})
(def r77con (-> refseq77-db jdbc/get-datasource jdbc/get-connection))
;;; Now r77con is usable by tmd.sql:
(dsql/sql->dataset r77con "select count(*) from bioentry")
(require '[tech.v3.dataset.rolling :as drl]
'[tech.v3.dataset.column :as dsc])
(-> [[:a [1 2 3]] [:b [6 7 8]]]
tc/dataset
(drl/rolling {:window-type :fixed
:window-size 2
:relative-window-position :right
:edge-mode :zero}
{:suma (drl/sum :a) :sumb (drl/sum :b)})
(tc/add-column
:sum (fn[ds]
(dsc/column-map
(fn[a b] (+ a b))
:long
(ds :suma) (ds :sumb))))) |
[
{
"context": " [react app]))\n\n(def ^:private dummy-data {:name \"Pete\"})\n\n(defn- react-render [component]\n (.eval nash",
"end": 978,
"score": 0.9867784380912781,
"start": 974,
"tag": "NAME",
"value": "Pete"
}
] | src/clojure_react_renderer_proof_of_concept/core/renderer.clj | ethagnawl/Clojure-React-Renderer-Proof-of-Concept | 1 | (ns clojure-react-renderer-proof-of-concept.core.renderer
(:import [
javax.script
ScriptEngineManager])
(:require
[clojure.data.json :as json]
[clojure-react-renderer-proof-of-concept.core.views.clojure-react-renderer-proof-of-concept-layout :refer [common-layout]]))
(defn- local-script [path]
(clojure.java.io/resource (str "public/javascripts/" path)))
(defn- create-engine
"Creates a new nashorn script engine and loads dependencies into its context."
[dependencies]
(let [nashorn (.getEngineByName (ScriptEngineManager.) "nashorn")
scripts (map #(str "load('" % "');") dependencies)]
(.eval nashorn "var global = this;")
(doseq [script scripts] (.eval nashorn script))
nashorn))
(def ^:private react "http://cdnjs.cloudflare.com/ajax/libs/react/0.12.2/react.min.js")
(def ^:private app (local-script "app.js"))
(def ^:private nashorn (create-engine [react app]))
(def ^:private dummy-data {:name "Pete"})
(defn- react-render [component]
(.eval nashorn (str "React.renderComponentToString(" component ")")))
(defn- dummy-component [data]
(str "MyApp.create(" (json/write-str data) ")"))
(defn render [_] (react-render (dummy-component dummy-data)))
| 66981 | (ns clojure-react-renderer-proof-of-concept.core.renderer
(:import [
javax.script
ScriptEngineManager])
(:require
[clojure.data.json :as json]
[clojure-react-renderer-proof-of-concept.core.views.clojure-react-renderer-proof-of-concept-layout :refer [common-layout]]))
(defn- local-script [path]
(clojure.java.io/resource (str "public/javascripts/" path)))
(defn- create-engine
"Creates a new nashorn script engine and loads dependencies into its context."
[dependencies]
(let [nashorn (.getEngineByName (ScriptEngineManager.) "nashorn")
scripts (map #(str "load('" % "');") dependencies)]
(.eval nashorn "var global = this;")
(doseq [script scripts] (.eval nashorn script))
nashorn))
(def ^:private react "http://cdnjs.cloudflare.com/ajax/libs/react/0.12.2/react.min.js")
(def ^:private app (local-script "app.js"))
(def ^:private nashorn (create-engine [react app]))
(def ^:private dummy-data {:name "<NAME>"})
(defn- react-render [component]
(.eval nashorn (str "React.renderComponentToString(" component ")")))
(defn- dummy-component [data]
(str "MyApp.create(" (json/write-str data) ")"))
(defn render [_] (react-render (dummy-component dummy-data)))
| true | (ns clojure-react-renderer-proof-of-concept.core.renderer
(:import [
javax.script
ScriptEngineManager])
(:require
[clojure.data.json :as json]
[clojure-react-renderer-proof-of-concept.core.views.clojure-react-renderer-proof-of-concept-layout :refer [common-layout]]))
(defn- local-script [path]
(clojure.java.io/resource (str "public/javascripts/" path)))
(defn- create-engine
"Creates a new nashorn script engine and loads dependencies into its context."
[dependencies]
(let [nashorn (.getEngineByName (ScriptEngineManager.) "nashorn")
scripts (map #(str "load('" % "');") dependencies)]
(.eval nashorn "var global = this;")
(doseq [script scripts] (.eval nashorn script))
nashorn))
(def ^:private react "http://cdnjs.cloudflare.com/ajax/libs/react/0.12.2/react.min.js")
(def ^:private app (local-script "app.js"))
(def ^:private nashorn (create-engine [react app]))
(def ^:private dummy-data {:name "PI:NAME:<NAME>END_PI"})
(defn- react-render [component]
(.eval nashorn (str "React.renderComponentToString(" component ")")))
(defn- dummy-component [data]
(str "MyApp.create(" (json/write-str data) ")"))
(defn render [_] (react-render (dummy-component dummy-data)))
|
[
{
"context": " :http-port 8068\n :env :prd\n :db {:username \"postgres\"\n :password \"123\"\n :server-name ",
"end": 76,
"score": 0.9995056390762329,
"start": 68,
"tag": "USERNAME",
"value": "postgres"
},
{
"context": " {:username \"postgres\"\n :password \"123\"\n :server-name \"192.168.1.47\"\n :port-",
"end": 103,
"score": 0.9990522265434265,
"start": 100,
"tag": "PASSWORD",
"value": "123"
},
{
"context": "\n :password \"123\"\n :server-name \"192.168.1.47\"\n :port-number 5432\n :database-name \"",
"end": 139,
"score": 0.9995903372764587,
"start": 127,
"tag": "IP_ADDRESS",
"value": "192.168.1.47"
},
{
"context": "abase-name \"wallet\"}\n :chain-importer-url \"http://39.104.136.10:6526/api/txs/signed\"\n }\n\n",
"end": 240,
"score": 0.9829930663108826,
"start": 227,
"tag": "IP_ADDRESS",
"value": "39.104.136.10"
}
] | conf/config.clj | sealchain/mobile-wallet-backend | 1 | {:nrepl-port 7467
:http-port 8068
:env :prd
:db {:username "postgres"
:password "123"
:server-name "192.168.1.47"
:port-number 5432
:database-name "wallet"}
:chain-importer-url "http://39.104.136.10:6526/api/txs/signed"
}
| 59359 | {:nrepl-port 7467
:http-port 8068
:env :prd
:db {:username "postgres"
:password "<PASSWORD>"
:server-name "192.168.1.47"
:port-number 5432
:database-name "wallet"}
:chain-importer-url "http://192.168.3.11:6526/api/txs/signed"
}
| true | {:nrepl-port 7467
:http-port 8068
:env :prd
:db {:username "postgres"
:password "PI:PASSWORD:<PASSWORD>END_PI"
:server-name "192.168.1.47"
:port-number 5432
:database-name "wallet"}
:chain-importer-url "http://PI:IP_ADDRESS:192.168.3.11END_PI:6526/api/txs/signed"
}
|
[
{
"context": "-util]))\r\n\r\n(def records [\r\n { :id 1\r\n :name \"test-identity\"\r\n :public_key \"blah\"\r\n :public_key_algorit",
"end": 224,
"score": 0.9972205758094788,
"start": 211,
"tag": "USERNAME",
"value": "test-identity"
},
{
"context": "id 1\r\n :name \"test-identity\"\r\n :public_key \"blah\"\r\n :public_key_algorithm \"RSA\"\r\n :peer_id 1",
"end": 248,
"score": 0.9877617955207825,
"start": 244,
"tag": "KEY",
"value": "blah"
},
{
"context": " :public_key \"blah\"\r\n :public_key_algorithm \"RSA\"\r\n :peer_id 1 }\r\n { :id 2\r\n :name \"test-us",
"end": 281,
"score": 0.6928858757019043,
"start": 278,
"tag": "KEY",
"value": "RSA"
},
{
"context": "hm \"RSA\"\r\n :peer_id 1 }\r\n { :id 2\r\n :name \"test-user\"\r\n :public_key \"\"\r\n :public_key_algorithm \"",
"end": 333,
"score": 0.9986453652381897,
"start": 324,
"tag": "USERNAME",
"value": "test-user"
},
{
"context": "hm \"RSA\"\r\n :peer_id 1 }\r\n { :id 3\r\n :name \"test-identity2\"\r\n :public_key \"blah2\"\r\n :public_key_algori",
"end": 443,
"score": 0.9950510263442993,
"start": 429,
"tag": "USERNAME",
"value": "test-identity2"
},
{
"context": "d 3\r\n :name \"test-identity2\"\r\n :public_key \"blah2\"\r\n :public_key_algorithm \"RSA\"\r\n :peer_id 1",
"end": 468,
"score": 0.9900966882705688,
"start": 463,
"tag": "KEY",
"value": "blah2"
},
{
"context": "hm \"RSA\"\r\n :peer_id 1 }\r\n { :id 4\r\n :name \"test-identity3\"\r\n :public_key \"blah3\"\r\n :public_key_algori",
"end": 558,
"score": 0.993728518486023,
"start": 544,
"tag": "USERNAME",
"value": "test-identity3"
},
{
"context": "d 4\r\n :name \"test-identity3\"\r\n :public_key \"blah3\"\r\n :public_key_algorithm \"RSA\"\r\n :peer_id 1",
"end": 583,
"score": 0.9923528432846069,
"start": 578,
"tag": "KEY",
"value": "blah3"
},
{
"context": " :public_key \"blah3\"\r\n :public_key_algorithm \"RSA\"\r\n :peer_id 1 }\r\n { :id 5\r\n :name \"test-id",
"end": 616,
"score": 0.5499207973480225,
"start": 613,
"tag": "KEY",
"value": "RSA"
},
{
"context": "hm \"RSA\"\r\n :peer_id 1 }\r\n { :id 5\r\n :name \"test-identity4\"\r\n :public_key \"blah3\"\r\n :public_key_algori",
"end": 673,
"score": 0.99603271484375,
"start": 659,
"tag": "USERNAME",
"value": "test-identity4"
},
{
"context": "d 5\r\n :name \"test-identity4\"\r\n :public_key \"blah3\"\r\n :public_key_algorithm \"RSA\"\r\n :peer_id 1",
"end": 698,
"score": 0.9962884187698364,
"start": 693,
"tag": "KEY",
"value": "blah3"
}
] | test/test/fixtures/identity.clj | cryptocurrent/Dark-Exchange | 36 | (ns test.fixtures.identity
(:use darkexchange.database.util)
(:require [test.fixtures.peer :as peer-fixture]
[test.fixtures.util :as fixtures-util]))
(def records [
{ :id 1
:name "test-identity"
:public_key "blah"
:public_key_algorithm "RSA"
:peer_id 1 }
{ :id 2
:name "test-user"
:public_key ""
:public_key_algorithm "RSA"
:peer_id 1 }
{ :id 3
:name "test-identity2"
:public_key "blah2"
:public_key_algorithm "RSA"
:peer_id 1 }
{ :id 4
:name "test-identity3"
:public_key "blah3"
:public_key_algorithm "RSA"
:peer_id 1 }
{ :id 5
:name "test-identity4"
:public_key "blah3"
:public_key_algorithm "RSA"
:peer_id 1 }])
(def fixture-table-name :identities)
(def fixture-map { :table fixture-table-name :records records :required-fixtures [peer-fixture/fixture-map] }) | 44156 | (ns test.fixtures.identity
(:use darkexchange.database.util)
(:require [test.fixtures.peer :as peer-fixture]
[test.fixtures.util :as fixtures-util]))
(def records [
{ :id 1
:name "test-identity"
:public_key "<KEY>"
:public_key_algorithm "<KEY>"
:peer_id 1 }
{ :id 2
:name "test-user"
:public_key ""
:public_key_algorithm "RSA"
:peer_id 1 }
{ :id 3
:name "test-identity2"
:public_key "<KEY>"
:public_key_algorithm "RSA"
:peer_id 1 }
{ :id 4
:name "test-identity3"
:public_key "<KEY>"
:public_key_algorithm "<KEY>"
:peer_id 1 }
{ :id 5
:name "test-identity4"
:public_key "<KEY>"
:public_key_algorithm "RSA"
:peer_id 1 }])
(def fixture-table-name :identities)
(def fixture-map { :table fixture-table-name :records records :required-fixtures [peer-fixture/fixture-map] }) | true | (ns test.fixtures.identity
(:use darkexchange.database.util)
(:require [test.fixtures.peer :as peer-fixture]
[test.fixtures.util :as fixtures-util]))
(def records [
{ :id 1
:name "test-identity"
:public_key "PI:KEY:<KEY>END_PI"
:public_key_algorithm "PI:KEY:<KEY>END_PI"
:peer_id 1 }
{ :id 2
:name "test-user"
:public_key ""
:public_key_algorithm "RSA"
:peer_id 1 }
{ :id 3
:name "test-identity2"
:public_key "PI:KEY:<KEY>END_PI"
:public_key_algorithm "RSA"
:peer_id 1 }
{ :id 4
:name "test-identity3"
:public_key "PI:KEY:<KEY>END_PI"
:public_key_algorithm "PI:KEY:<KEY>END_PI"
:peer_id 1 }
{ :id 5
:name "test-identity4"
:public_key "PI:KEY:<KEY>END_PI"
:public_key_algorithm "RSA"
:peer_id 1 }])
(def fixture-table-name :identities)
(def fixture-map { :table fixture-table-name :records records :required-fixtures [peer-fixture/fixture-map] }) |
[
{
"context": ";; Stream utilities\n\n;; by Konrad Hinsen\n;; last updated May 3, 2009\n\n;; Copyright (c) Kon",
"end": 40,
"score": 0.9998787641525269,
"start": 27,
"tag": "NAME",
"value": "Konrad Hinsen"
},
{
"context": "nsen\n;; last updated May 3, 2009\n\n;; Copyright (c) Konrad Hinsen, 2009. All rights reserved. The use\n;; and distr",
"end": 100,
"score": 0.9998692274093628,
"start": 87,
"tag": "NAME",
"value": "Konrad Hinsen"
},
{
"context": "any other, from this software.\n\n(ns\n #^{:author \"Konrad Hinsen\"\n :doc \"Functions for setting up computationa",
"end": 569,
"score": 0.9998825192451477,
"start": 556,
"tag": "NAME",
"value": "Konrad Hinsen"
}
] | data/test/clojure/35c5c90ed028582461cd782b5211cdd0e3f698cfstream_utils.clj | harshp8l/deep-learning-lang-detection | 84 | ;; Stream utilities
;; by Konrad Hinsen
;; last updated May 3, 2009
;; Copyright (c) Konrad Hinsen, 2009. All rights reserved. The use
;; and distribution terms for this software are covered by the Eclipse
;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this
;; distribution. By using this software in any fashion, you are
;; agreeing to be bound by the terms of this license. You must not
;; remove this notice, or any other, from this software.
(ns
#^{:author "Konrad Hinsen"
:doc "Functions for setting up computational pipelines via data streams.
NOTE: This library is experimental. It may change significantly
with future release.
This library defines:
- an abstract stream type, whose interface consists of the
multimethod stream-next
- a macro for implementing streams
- implementations of stream for
1) Clojure sequences, and vectors
2) nil, representing an empty stream
- tools for writing stream transformers, including the
monad stream-m
- various utility functions for working with streams
Streams are building blocks in the construction of computational
pipelines. A stream is represented by its current state plus
a function that takes a stream state and obtains the next item
in the stream as well as the new stream state. The state is
implemented as a Java class or a Clojure type (as defined by the
function clojure.core/type), and the function is provided as an
implementation of the multimethod stream-next for this class or type.
While setting up pipelines using this mechanism is somewhat more
cumbersome than using Clojure's lazy seq mechanisms, there are a
few advantages:
- The state of a stream can be stored in any Clojure data structure,
and the stream can be re-generated from it any number of times.
Any number of states can be stored this way.
- The elements of the stream are never cached, so keeping a reference
to a stream state does not incur an uncontrollable memory penalty.
Note that the stream mechanism is thread-safe as long as the
concrete stream implementations do not use any mutable state.
Stream transformers take any number of input streams and produce one
output stream. They are typically written using the stream-m
monad. In the definition of a stream transformer, (pick s) returns
the next value of stream argument s, whereas pick-all returns the
next value of all stream arguments in the form of a vector."}
clojure.contrib.stream-utils
(:refer-clojure :exclude (deftype))
(:use [clojure.contrib.types :only (deftype deftype-)])
(:use [clojure.contrib.monads :only (defmonad with-monad)])
(:use [clojure.contrib.def :only (defvar defvar-)])
(:require [clojure.contrib.seq-utils])
(:require [clojure.contrib.generic.collection]))
;
; Stream type and interface
;
(defvar stream-type ::stream
"The root type for the stream hierarchy. For each stream type,
add a derivation from this type.")
(defmacro defstream
"Define object of the given type as a stream whose implementation
of stream-next is defined by args and body. This macro adds
a type-specific method for stream-next and derives type
from stream-type."
[type-tag args & body]
`(do
(derive ~type-tag stream-type)
(defmethod stream-next ~type-tag ~args ~@body)))
(defvar- stream-skip ::skip
"The skip-this-item value.")
(defn- stream-skip?
"Returns true if x is the stream-skip."
[x]
(identical? x stream-skip))
(defmulti stream-next
"Returns a vector [next-value new-state] where next-value is the next
item in the data stream defined by stream-state and new-state
is the new state of the stream. At the end of the stream,
next-value and new-state are nil."
{:arglists '([stream-state])}
type)
(defmethod stream-next nil
[s]
[nil nil])
(defmethod stream-next clojure.lang.ISeq
[s]
(if (seq s)
[(first s) (rest s)]
[nil nil]))
(defmethod stream-next clojure.lang.IPersistentVector
[v]
(stream-next (seq v)))
(defn stream-seq
"Return a lazy seq on the stream. Also accessible via
clojure.contrib.seq-utils/seq-on and
clojure.contrib.generic.collection/seq for streams."
[s]
(lazy-seq
(let [[v ns] (stream-next s)]
(if (nil? ns)
nil
(cons v (stream-seq ns))))))
(defmethod clojure.contrib.seq-utils/seq-on stream-type
[s]
(stream-seq s))
(defmethod clojure.contrib.generic.collection/seq stream-type
[s]
(stream-seq s))
;
; Stream transformers
;
(defmonad stream-m
"Monad describing stream computations. The monadic values can be
of any type handled by stream-next."
[m-result (fn m-result-stream [v]
(fn [s] [v s]))
m-bind (fn m-bind-stream [mv f]
(fn [s]
(let [[v ss :as r] (mv s)]
(if (or (nil? ss) (stream-skip? v))
r
((f v) ss)))))
m-zero (fn [s] [stream-skip s])
])
(defn pick
"Return the next value of stream argument n inside a stream
transformer. When used inside of defst, the name of the stream
argument can be used instead of its index n."
[n]
(fn [streams]
(let [[v ns] (stream-next (streams n))]
(if (nil? ns)
[nil nil]
[v (assoc streams n ns)]))))
(defn pick-all
"Return a vector containing the next value of each stream argument
inside a stream transformer."
[streams]
(let [next (map stream-next streams)
values (map first next)
streams (vec (map second next))]
(if (some nil? streams)
[nil nil]
[values streams])))
(deftype ::stream-transformer st-as-stream
(fn [st streams] [st streams])
seq)
(defstream ::stream-transformer
[[st streams]]
(loop [s streams]
(let [[v ns] (st s)]
(cond (nil? ns) [nil nil]
(stream-skip? v) (recur ns)
:else [v (st-as-stream st ns)]))))
(defmacro defst
"Define the stream transformer name by body.
The non-stream arguments args and the stream arguments streams
are given separately, with args being possibly empty."
[name args streams & body]
(if (= (first streams) '&)
`(defn ~name ~(vec (concat args streams))
(let [~'st (with-monad stream-m ~@body)]
(st-as-stream ~'st ~(second streams))))
`(defn ~name ~(vec (concat args streams))
(let [~'st (with-monad stream-m
(let [~streams (range ~(count streams))]
~@body))]
(st-as-stream ~'st ~streams)))))
;
; Stream utilities
;
(defn stream-drop
"Return a stream containing all but the first n elements of stream."
[n stream]
(if (zero? n)
stream
(let [[_ s] (stream-next stream)]
(recur (dec n) s))))
; Map a function on a stream
(deftype- ::stream-map stream-map-state)
(defstream ::stream-map
[[f stream]]
(let [[v ns] (stream-next stream)]
(if (nil? ns)
[nil nil]
[(f v) (stream-map-state [f ns])])))
(defmulti stream-map
"Return a new stream by mapping the function f on the given stream."
{:arglists '([f stream])}
(fn [f stream] (type stream)))
(defmethod stream-map :default
[f stream]
(stream-map-state [f stream]))
(defmethod stream-map ::stream-map
[f [g stream]]
(stream-map-state [(comp f g) stream]))
; Filter stream elements
(deftype- ::stream-filter stream-filter-state)
(defstream ::stream-filter
[[p stream]]
(loop [stream stream]
(let [[v ns] (stream-next stream)]
(cond (nil? ns) [nil nil]
(p v) [v (stream-filter-state [p ns])]
:else (recur ns)))))
(defmulti stream-filter
"Return a new stream that contrains the elements of stream
that satisfy the predicate p."
{:arglists '([p stream])}
(fn [p stream] (type stream)))
(defmethod stream-filter :default
[p stream]
(stream-filter-state [p stream]))
(defmethod stream-filter ::stream-filter
[p [q stream]]
(stream-filter-state [(fn [v] (and (q v) (p v))) stream]))
; Flatten a stream of sequences
(deftype- ::stream-flatten stream-flatten-state)
(defstream ::stream-flatten
[[buffer stream]]
(loop [buffer buffer
stream stream]
(if (nil? buffer)
(let [[v new-stream] (stream-next stream)]
(cond (nil? new-stream) [nil nil]
(empty? v) (recur nil new-stream)
:else (recur v new-stream)))
[(first buffer) (stream-flatten-state [(next buffer) stream])])))
(defn stream-flatten
"Converts a stream of sequences into a stream of the elements of the
sequences. Flattening is not recursive, only one level of nesting
will be removed."
[s]
(stream-flatten-state [nil s]))
| 27062 | ;; Stream utilities
;; by <NAME>
;; last updated May 3, 2009
;; Copyright (c) <NAME>, 2009. All rights reserved. The use
;; and distribution terms for this software are covered by the Eclipse
;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this
;; distribution. By using this software in any fashion, you are
;; agreeing to be bound by the terms of this license. You must not
;; remove this notice, or any other, from this software.
(ns
#^{:author "<NAME>"
:doc "Functions for setting up computational pipelines via data streams.
NOTE: This library is experimental. It may change significantly
with future release.
This library defines:
- an abstract stream type, whose interface consists of the
multimethod stream-next
- a macro for implementing streams
- implementations of stream for
1) Clojure sequences, and vectors
2) nil, representing an empty stream
- tools for writing stream transformers, including the
monad stream-m
- various utility functions for working with streams
Streams are building blocks in the construction of computational
pipelines. A stream is represented by its current state plus
a function that takes a stream state and obtains the next item
in the stream as well as the new stream state. The state is
implemented as a Java class or a Clojure type (as defined by the
function clojure.core/type), and the function is provided as an
implementation of the multimethod stream-next for this class or type.
While setting up pipelines using this mechanism is somewhat more
cumbersome than using Clojure's lazy seq mechanisms, there are a
few advantages:
- The state of a stream can be stored in any Clojure data structure,
and the stream can be re-generated from it any number of times.
Any number of states can be stored this way.
- The elements of the stream are never cached, so keeping a reference
to a stream state does not incur an uncontrollable memory penalty.
Note that the stream mechanism is thread-safe as long as the
concrete stream implementations do not use any mutable state.
Stream transformers take any number of input streams and produce one
output stream. They are typically written using the stream-m
monad. In the definition of a stream transformer, (pick s) returns
the next value of stream argument s, whereas pick-all returns the
next value of all stream arguments in the form of a vector."}
clojure.contrib.stream-utils
(:refer-clojure :exclude (deftype))
(:use [clojure.contrib.types :only (deftype deftype-)])
(:use [clojure.contrib.monads :only (defmonad with-monad)])
(:use [clojure.contrib.def :only (defvar defvar-)])
(:require [clojure.contrib.seq-utils])
(:require [clojure.contrib.generic.collection]))
;
; Stream type and interface
;
(defvar stream-type ::stream
"The root type for the stream hierarchy. For each stream type,
add a derivation from this type.")
(defmacro defstream
"Define object of the given type as a stream whose implementation
of stream-next is defined by args and body. This macro adds
a type-specific method for stream-next and derives type
from stream-type."
[type-tag args & body]
`(do
(derive ~type-tag stream-type)
(defmethod stream-next ~type-tag ~args ~@body)))
(defvar- stream-skip ::skip
"The skip-this-item value.")
(defn- stream-skip?
"Returns true if x is the stream-skip."
[x]
(identical? x stream-skip))
(defmulti stream-next
"Returns a vector [next-value new-state] where next-value is the next
item in the data stream defined by stream-state and new-state
is the new state of the stream. At the end of the stream,
next-value and new-state are nil."
{:arglists '([stream-state])}
type)
(defmethod stream-next nil
[s]
[nil nil])
(defmethod stream-next clojure.lang.ISeq
[s]
(if (seq s)
[(first s) (rest s)]
[nil nil]))
(defmethod stream-next clojure.lang.IPersistentVector
[v]
(stream-next (seq v)))
(defn stream-seq
"Return a lazy seq on the stream. Also accessible via
clojure.contrib.seq-utils/seq-on and
clojure.contrib.generic.collection/seq for streams."
[s]
(lazy-seq
(let [[v ns] (stream-next s)]
(if (nil? ns)
nil
(cons v (stream-seq ns))))))
(defmethod clojure.contrib.seq-utils/seq-on stream-type
[s]
(stream-seq s))
(defmethod clojure.contrib.generic.collection/seq stream-type
[s]
(stream-seq s))
;
; Stream transformers
;
(defmonad stream-m
"Monad describing stream computations. The monadic values can be
of any type handled by stream-next."
[m-result (fn m-result-stream [v]
(fn [s] [v s]))
m-bind (fn m-bind-stream [mv f]
(fn [s]
(let [[v ss :as r] (mv s)]
(if (or (nil? ss) (stream-skip? v))
r
((f v) ss)))))
m-zero (fn [s] [stream-skip s])
])
(defn pick
"Return the next value of stream argument n inside a stream
transformer. When used inside of defst, the name of the stream
argument can be used instead of its index n."
[n]
(fn [streams]
(let [[v ns] (stream-next (streams n))]
(if (nil? ns)
[nil nil]
[v (assoc streams n ns)]))))
(defn pick-all
"Return a vector containing the next value of each stream argument
inside a stream transformer."
[streams]
(let [next (map stream-next streams)
values (map first next)
streams (vec (map second next))]
(if (some nil? streams)
[nil nil]
[values streams])))
(deftype ::stream-transformer st-as-stream
(fn [st streams] [st streams])
seq)
(defstream ::stream-transformer
[[st streams]]
(loop [s streams]
(let [[v ns] (st s)]
(cond (nil? ns) [nil nil]
(stream-skip? v) (recur ns)
:else [v (st-as-stream st ns)]))))
(defmacro defst
"Define the stream transformer name by body.
The non-stream arguments args and the stream arguments streams
are given separately, with args being possibly empty."
[name args streams & body]
(if (= (first streams) '&)
`(defn ~name ~(vec (concat args streams))
(let [~'st (with-monad stream-m ~@body)]
(st-as-stream ~'st ~(second streams))))
`(defn ~name ~(vec (concat args streams))
(let [~'st (with-monad stream-m
(let [~streams (range ~(count streams))]
~@body))]
(st-as-stream ~'st ~streams)))))
;
; Stream utilities
;
(defn stream-drop
"Return a stream containing all but the first n elements of stream."
[n stream]
(if (zero? n)
stream
(let [[_ s] (stream-next stream)]
(recur (dec n) s))))
; Map a function on a stream
(deftype- ::stream-map stream-map-state)
(defstream ::stream-map
[[f stream]]
(let [[v ns] (stream-next stream)]
(if (nil? ns)
[nil nil]
[(f v) (stream-map-state [f ns])])))
(defmulti stream-map
"Return a new stream by mapping the function f on the given stream."
{:arglists '([f stream])}
(fn [f stream] (type stream)))
(defmethod stream-map :default
[f stream]
(stream-map-state [f stream]))
(defmethod stream-map ::stream-map
[f [g stream]]
(stream-map-state [(comp f g) stream]))
; Filter stream elements
(deftype- ::stream-filter stream-filter-state)
(defstream ::stream-filter
[[p stream]]
(loop [stream stream]
(let [[v ns] (stream-next stream)]
(cond (nil? ns) [nil nil]
(p v) [v (stream-filter-state [p ns])]
:else (recur ns)))))
(defmulti stream-filter
"Return a new stream that contrains the elements of stream
that satisfy the predicate p."
{:arglists '([p stream])}
(fn [p stream] (type stream)))
(defmethod stream-filter :default
[p stream]
(stream-filter-state [p stream]))
(defmethod stream-filter ::stream-filter
[p [q stream]]
(stream-filter-state [(fn [v] (and (q v) (p v))) stream]))
; Flatten a stream of sequences
(deftype- ::stream-flatten stream-flatten-state)
(defstream ::stream-flatten
[[buffer stream]]
(loop [buffer buffer
stream stream]
(if (nil? buffer)
(let [[v new-stream] (stream-next stream)]
(cond (nil? new-stream) [nil nil]
(empty? v) (recur nil new-stream)
:else (recur v new-stream)))
[(first buffer) (stream-flatten-state [(next buffer) stream])])))
(defn stream-flatten
"Converts a stream of sequences into a stream of the elements of the
sequences. Flattening is not recursive, only one level of nesting
will be removed."
[s]
(stream-flatten-state [nil s]))
| true | ;; Stream utilities
;; by PI:NAME:<NAME>END_PI
;; last updated May 3, 2009
;; Copyright (c) PI:NAME:<NAME>END_PI, 2009. All rights reserved. The use
;; and distribution terms for this software are covered by the Eclipse
;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this
;; distribution. By using this software in any fashion, you are
;; agreeing to be bound by the terms of this license. You must not
;; remove this notice, or any other, from this software.
(ns
#^{:author "PI:NAME:<NAME>END_PI"
:doc "Functions for setting up computational pipelines via data streams.
NOTE: This library is experimental. It may change significantly
with future release.
This library defines:
- an abstract stream type, whose interface consists of the
multimethod stream-next
- a macro for implementing streams
- implementations of stream for
1) Clojure sequences, and vectors
2) nil, representing an empty stream
- tools for writing stream transformers, including the
monad stream-m
- various utility functions for working with streams
Streams are building blocks in the construction of computational
pipelines. A stream is represented by its current state plus
a function that takes a stream state and obtains the next item
in the stream as well as the new stream state. The state is
implemented as a Java class or a Clojure type (as defined by the
function clojure.core/type), and the function is provided as an
implementation of the multimethod stream-next for this class or type.
While setting up pipelines using this mechanism is somewhat more
cumbersome than using Clojure's lazy seq mechanisms, there are a
few advantages:
- The state of a stream can be stored in any Clojure data structure,
and the stream can be re-generated from it any number of times.
Any number of states can be stored this way.
- The elements of the stream are never cached, so keeping a reference
to a stream state does not incur an uncontrollable memory penalty.
Note that the stream mechanism is thread-safe as long as the
concrete stream implementations do not use any mutable state.
Stream transformers take any number of input streams and produce one
output stream. They are typically written using the stream-m
monad. In the definition of a stream transformer, (pick s) returns
the next value of stream argument s, whereas pick-all returns the
next value of all stream arguments in the form of a vector."}
clojure.contrib.stream-utils
(:refer-clojure :exclude (deftype))
(:use [clojure.contrib.types :only (deftype deftype-)])
(:use [clojure.contrib.monads :only (defmonad with-monad)])
(:use [clojure.contrib.def :only (defvar defvar-)])
(:require [clojure.contrib.seq-utils])
(:require [clojure.contrib.generic.collection]))
;
; Stream type and interface
;
(defvar stream-type ::stream
"The root type for the stream hierarchy. For each stream type,
add a derivation from this type.")
(defmacro defstream
"Define object of the given type as a stream whose implementation
of stream-next is defined by args and body. This macro adds
a type-specific method for stream-next and derives type
from stream-type."
[type-tag args & body]
`(do
(derive ~type-tag stream-type)
(defmethod stream-next ~type-tag ~args ~@body)))
(defvar- stream-skip ::skip
"The skip-this-item value.")
(defn- stream-skip?
"Returns true if x is the stream-skip."
[x]
(identical? x stream-skip))
(defmulti stream-next
"Returns a vector [next-value new-state] where next-value is the next
item in the data stream defined by stream-state and new-state
is the new state of the stream. At the end of the stream,
next-value and new-state are nil."
{:arglists '([stream-state])}
type)
(defmethod stream-next nil
[s]
[nil nil])
(defmethod stream-next clojure.lang.ISeq
[s]
(if (seq s)
[(first s) (rest s)]
[nil nil]))
(defmethod stream-next clojure.lang.IPersistentVector
[v]
(stream-next (seq v)))
(defn stream-seq
"Return a lazy seq on the stream. Also accessible via
clojure.contrib.seq-utils/seq-on and
clojure.contrib.generic.collection/seq for streams."
[s]
(lazy-seq
(let [[v ns] (stream-next s)]
(if (nil? ns)
nil
(cons v (stream-seq ns))))))
(defmethod clojure.contrib.seq-utils/seq-on stream-type
[s]
(stream-seq s))
(defmethod clojure.contrib.generic.collection/seq stream-type
[s]
(stream-seq s))
;
; Stream transformers
;
(defmonad stream-m
"Monad describing stream computations. The monadic values can be
of any type handled by stream-next."
[m-result (fn m-result-stream [v]
(fn [s] [v s]))
m-bind (fn m-bind-stream [mv f]
(fn [s]
(let [[v ss :as r] (mv s)]
(if (or (nil? ss) (stream-skip? v))
r
((f v) ss)))))
m-zero (fn [s] [stream-skip s])
])
(defn pick
"Return the next value of stream argument n inside a stream
transformer. When used inside of defst, the name of the stream
argument can be used instead of its index n."
[n]
(fn [streams]
(let [[v ns] (stream-next (streams n))]
(if (nil? ns)
[nil nil]
[v (assoc streams n ns)]))))
(defn pick-all
"Return a vector containing the next value of each stream argument
inside a stream transformer."
[streams]
(let [next (map stream-next streams)
values (map first next)
streams (vec (map second next))]
(if (some nil? streams)
[nil nil]
[values streams])))
(deftype ::stream-transformer st-as-stream
(fn [st streams] [st streams])
seq)
(defstream ::stream-transformer
[[st streams]]
(loop [s streams]
(let [[v ns] (st s)]
(cond (nil? ns) [nil nil]
(stream-skip? v) (recur ns)
:else [v (st-as-stream st ns)]))))
(defmacro defst
"Define the stream transformer name by body.
The non-stream arguments args and the stream arguments streams
are given separately, with args being possibly empty."
[name args streams & body]
(if (= (first streams) '&)
`(defn ~name ~(vec (concat args streams))
(let [~'st (with-monad stream-m ~@body)]
(st-as-stream ~'st ~(second streams))))
`(defn ~name ~(vec (concat args streams))
(let [~'st (with-monad stream-m
(let [~streams (range ~(count streams))]
~@body))]
(st-as-stream ~'st ~streams)))))
;
; Stream utilities
;
(defn stream-drop
"Return a stream containing all but the first n elements of stream."
[n stream]
(if (zero? n)
stream
(let [[_ s] (stream-next stream)]
(recur (dec n) s))))
; Map a function on a stream
(deftype- ::stream-map stream-map-state)
(defstream ::stream-map
[[f stream]]
(let [[v ns] (stream-next stream)]
(if (nil? ns)
[nil nil]
[(f v) (stream-map-state [f ns])])))
(defmulti stream-map
"Return a new stream by mapping the function f on the given stream."
{:arglists '([f stream])}
(fn [f stream] (type stream)))
(defmethod stream-map :default
[f stream]
(stream-map-state [f stream]))
(defmethod stream-map ::stream-map
[f [g stream]]
(stream-map-state [(comp f g) stream]))
; Filter stream elements
(deftype- ::stream-filter stream-filter-state)
(defstream ::stream-filter
[[p stream]]
(loop [stream stream]
(let [[v ns] (stream-next stream)]
(cond (nil? ns) [nil nil]
(p v) [v (stream-filter-state [p ns])]
:else (recur ns)))))
(defmulti stream-filter
"Return a new stream that contrains the elements of stream
that satisfy the predicate p."
{:arglists '([p stream])}
(fn [p stream] (type stream)))
(defmethod stream-filter :default
[p stream]
(stream-filter-state [p stream]))
(defmethod stream-filter ::stream-filter
[p [q stream]]
(stream-filter-state [(fn [v] (and (q v) (p v))) stream]))
; Flatten a stream of sequences
(deftype- ::stream-flatten stream-flatten-state)
(defstream ::stream-flatten
[[buffer stream]]
(loop [buffer buffer
stream stream]
(if (nil? buffer)
(let [[v new-stream] (stream-next stream)]
(cond (nil? new-stream) [nil nil]
(empty? v) (recur nil new-stream)
:else (recur v new-stream)))
[(first buffer) (stream-flatten-state [(next buffer) stream])])))
(defn stream-flatten
"Converts a stream of sequences into a stream of the elements of the
sequences. Flattening is not recursive, only one level of nesting
will be removed."
[s]
(stream-flatten-state [nil s]))
|
[
{
"context": "-------------------------------\n;;\n;;\n;; Author: PLIQUE Guillaume (Yomguithereal)\n;; Version: 0.1\n;;\n(ns clj-fuzz",
"end": 207,
"score": 0.9998169541358948,
"start": 191,
"tag": "NAME",
"value": "PLIQUE Guillaume"
},
{
"context": "------------\n;;\n;;\n;; Author: PLIQUE Guillaume (Yomguithereal)\n;; Version: 0.1\n;;\n(ns clj-fuzzy.double-metaph",
"end": 222,
"score": 0.9991182684898376,
"start": 209,
"tag": "USERNAME",
"value": "Yomguithereal"
},
{
"context": " 1)]\n (if (and (zero? pos)\n (not= \"JOSE\" (slice string pos 4)))\n [:J :A current]\n ",
"end": 7307,
"score": 0.5530878305435181,
"start": 7305,
"tag": "NAME",
"value": "JO"
},
{
"context": "up-S-1)\n (and (zero? pos)\n (= \"SUGAR\" (slice string pos 5))) (lookup-S-2)\n (= \"",
"end": 10431,
"score": 0.8185141682624817,
"start": 10426,
"tag": "NAME",
"value": "SUGAR"
}
] | src/clj_fuzzy/double_metaphone.cljc | Yomguithereal/clj-fuzzy | 222 | ;; -------------------------------------------------------------------
;; clj-fuzzy Double Metaphone
;; -------------------------------------------------------------------
;;
;;
;; Author: PLIQUE Guillaume (Yomguithereal)
;; Version: 0.1
;;
(ns clj-fuzzy.double-metaphone
(:require clojure.string)
(:use [clj-fuzzy.helpers :only [re-test?
slice
in?]]))
;; Utilities
(defn- slavo-germanic? [string] (re-test? #"W|K|CZ|WITZ" string))
(defn- vowel? [string] (re-test? #"^A|E|I|O|U|Y$" string))
(defn- conj-if-not-nil [array value]
(if (nil? value)
array
(conj array value)))
(def ^:private not-re-test? (complement re-test?))
;; Lookup functions
(defn- lookup-vowel [pos] (if (zero? pos) [:A :A 1] [nil nil 1]))
(defn- lookup-B [string pos]
[:P :P (if (= "B" (slice string (inc pos) 1)) 2 1)])
(defn- lookup-C-cedilla [] [:S :S 1])
(defn- lookup-C-1 [] [:K :K 2])
(defn- lookup-C-2 [] [:S :S 2])
(defn- lookup-C-3 [string pos]
(cond (and (pos? pos)
(= "CHAE" (slice string pos 4))) [:K :X 2]
(and (zero? pos)
(or (in? (slice string (inc pos) 5) ["HARAC" "HARIS"])
(in? (slice string (inc pos) 3) ["HOR" "HYM" "HIA" "HEM"]))
(not= "CHORE" (slice string 0 5))) [:K :K 2]
(or (in? (slice string 0 4) ["VAN " "VON "])
(= "SCH" (slice string 0 3))
(in? (slice string (- pos 2) 6) ["ORCHES" "ARCHIT" "ORCHID"])
(in? (slice string (+ pos 2) 1) ["T" "S"])
(and (or (zero? pos)
(in? (slice string (dec pos) 1) ["A" "O" "U" "E"]))
(in? (slice string (+ pos 2) 1) ["L" "R" "N" "M" "B" "H" "F" "V" "W" " "]))) [:K :K 2]
(pos? pos) [(if (= "MC" (slice string 0 2)) :K :X) :K 2]
:else [:X :X 2]))
(defn- lookup-C-4 [] [:S :X 2])
(defn- lookup-C-5 [] [:X :X 3])
(defn- lookup-C-6 [string pos]
(if (and (re-test? #"^I|E|H$" (slice string (+ pos 2) 1))
(not= "HU" (slice string (+ pos 2) 2)))
(if (or (and (= pos 1)
(= "A" (slice string (dec pos) 1)))
(re-test? #"^UCCE(E|S)$" (slice string (dec pos) 5)))
[:KS :KS 3]
[:X :X 3])
[:K :K 2]))
(defn- lookup-C-7 [] [:K :K 2])
(defn- lookup-C-8 [string pos]
[:S (if (re-test? #"^CI(O|E|A)$" (slice string pos 3)) :X :S) 2])
(defn- lookup-C-9 [string pos]
(if (re-test? #"^ (C|Q|G)$" (slice string (inc pos) 2))
[:K :K 3]
[:K :K (if (and (re-test? #"^C|K|Q$" (slice string (inc pos) 1))
(not (in? (slice string (inc pos) 2) ["CE" "CI"]))) 2 1)]))
(defn- lookup-C [string pos]
(cond (and (> pos 1)
(vowel? (slice string (- pos 2) 1))
(= "ACH" (slice string (dec pos) 3))
(not= "I" (slice string (+ pos 2) 1))
(or (not= "E" (slice string (+ pos 2) 1))
(re-test? #"^(B|M)ACHER$" (slice string (- pos 2) 6)))) (lookup-C-1)
(and (zero? pos) (= "CAESAR" (slice string pos 6))) (lookup-C-2)
(= "CHIA" (slice string pos 4)) (lookup-C-1)
(= "CH" (slice string pos 2)) (lookup-C-3 string pos)
(and (= "CZ" (slice string pos 2)) (not= "WICZ" (slice string (- pos 2) 4))) (lookup-C-4)
(= "CIA" (slice string (inc pos) 3)) (lookup-C-5)
(and (= "CC" (slice string pos 2))
(not (or (= pos 1) (= "M" (slice string 0 1))))) (lookup-C-6 string pos)
(re-test? #"^C(K|G|Q)$" (slice string pos 2)) (lookup-C-7)
(re-test? #"^C(I|E|Y)$" (slice string pos 2)) (lookup-C-8 string pos)
:else (lookup-C-9 string pos)))
(defn- lookup-D [string pos]
(if (= "DG" (slice string pos 2))
(if (re-test? #"^I|E|Y$" (slice string (+ pos 2) 1))
[:J :J 3]
[:TK :TK 2])
[:T :T (if (re-test? #"^D(T|D)$" (slice string pos 2)) 2 1)]))
(defn- lookup-F [string pos]
[:F :F (if (= "F" (slice string (inc pos) 1)) 2 1)])
(defn lookup-G-1-bis [string pos]
(cond (and (> pos 2)
(= "U" (slice string (dec pos) 1))
(re-test? #"^C|G|L|R|T$" (slice string (- pos 3) 1))) [:F :F 2]
(and (pos? pos) (not= "I" (slice string (dec pos) 1))) [:K :K 2]
:else [nil nil 2]))
(defn- lookup-G-1 [string pos]
(cond (and (pos? pos)
(not (vowel? (slice string (dec pos) 1)))) [:K :K 2]
(zero? pos) (if (= "I" (slice string (+ pos 2) 1)) [:J :J 2] [:K :K 2])
(or (and (> pos 1) (re-test? #"^B|H|D$" (slice string (- pos 2) 1)))
(and (> pos 2) (re-test? #"^B|H|D$" (slice string (- pos 3) 1)))
(and (> pos 3) (re-test? #"^B|H$" (slice string (- pos 4) 1)))) [nil nil 2]
:else (lookup-G-1-bis string pos)))
(defn- lookup-G-2 [string pos]
(if (and (= pos 1)
(vowel? (slice string 0 1))
(not (slavo-germanic? string)))
[:KN :N 2]
(if (and (not= "EY" (slice string (+ pos 2) 2))
(not= "Y" (slice string (inc pos) 1))
(not (slavo-germanic? string)))
[:N :KN 2]
[:KN :KN 2])))
(defn- lookup-G-3 [] [:KL :L 2])
(defn- lookup-G-4 [] [:K :J 2])
(defn- lookup-G-5 [] [:K :J 2])
(defn- lookup-G-6 [string pos]
(if (or (re-test? #"^V(A|O)N $" (slice string 0 4))
(= "SCH" (slice string 0 3))
(= "ET" (slice string (inc pos) 2)))
[:K :K 2]
(if (= "IER " (slice string (inc pos) 4))
[:J :J 2]
[:J :K 2])))
(defn- lookup-G-7 [] [:K :K 2])
(defn- lookup-G-8 [] [:K :K 1])
(defn- lookup-G [string pos]
(cond (= "H" (slice string (inc pos) 1)) (lookup-G-1 string pos)
(= "N" (slice string (inc pos) 1)) (lookup-G-2 string pos)
(and (= "LI" (slice string (inc pos) 2)) (not (slavo-germanic? string))) (lookup-G-3)
(and (zero? pos)
(or (= "Y" (slice string (inc pos) 1))
(re-test? #"^(E(S|P|B|L|Y|I|R)|I(B|L|N|E))$" (slice string (inc pos) 2)))) (lookup-G-4)
(and (or (= "ER" (slice string (inc pos) 2)) (= "Y" (slice string (inc pos) 1)))
(not-re-test? #"^(D|R|M)ANGER$" (slice string 0 6))
(not-re-test? #"^E|I$" (slice string (dec pos) 1))
(not-re-test? #"^(R|O)GY$" (slice string (dec pos) 3))) (lookup-G-5)
(or (re-test? #"^E|I|Y$" (slice string (inc pos) 1))
(re-test? #"^(A|O)GGI$" (slice string (dec pos) 4))) (lookup-G-6 string pos)
(= "G" (slice string (inc pos) 1)) (lookup-G-7)
:else (lookup-G-8)))
(defn- lookup-H [string pos]
(if (and (or (zero? pos) (vowel? (slice string (dec pos) 1)))
(vowel? (slice string (inc pos) 1)))
[:H :H 2]
[nil nil 1]))
(defn- lookup-J-1 [string pos]
(if (or (and (zero? pos)
(= " " (slice string (+ pos 4) 1)))
(= "SAN " (slice string 0 4)))
[:H :H 1]
[:J :H 1]))
(defn- lookup-J-2-bis [current] [:J :H current])
(defn- lookup-J-2-ter [string pos lastp current]
(if (= lastp pos)
[:J nil current]
(if (and (not-re-test? #"^L|T|K|S|N|M|B|Z$" (slice string (inc pos) 1))
(not-re-test? #"^S|K|L$" (slice string (dec pos) 1)))
[:J :J current]
[nil nil current])))
(defn- lookup-J-2 [string pos lastp]
(let [current (if (= "J" (slice string (inc pos) 1)) 2 1)]
(if (and (zero? pos)
(not= "JOSE" (slice string pos 4)))
[:J :A current]
(if (and (vowel? (slice string (dec pos) 1))
(not (slavo-germanic? string))
(re-test? #"^A|O$" (slice string (inc pos) 1)))
(lookup-J-2-bis current)
(lookup-J-2-ter string pos lastp current)))))
(defn- lookup-J [string pos lastp]
(if (or (= "JOSE" (slice string pos 4)) (= "SAN " (slice string 0 4)))
(lookup-J-1 string pos)
(lookup-J-2 string pos lastp)))
(defn- lookup-K [string pos]
[:K :K (if (= "K" (slice string (inc pos) 1)) 2 1)])
(defn- lookup-L-1 [string pos length lastp]
(if (or (and (= (- length 3) pos) (re-test? #"^(ILL(O|A)|ALLE)$" (slice string (dec pos) 4)))
(and (or (re-test? #"^(A|O)S$" (slice string (dec lastp) 2))
(re-test? #"^A|O$" (slice string lastp 1)))
(= "ALLE" (slice string (dec pos) 4))))
[:L nil 2]
[:L :L 2]))
(defn- lookup-L [string pos length lastp]
(if (= "L" (slice string (inc pos) 1))
(lookup-L-1 string pos length lastp)
[:L :L 1]))
(defn- lookup-M [string pos lastp]
(if (or (and (= "UMB" (slice string (dec pos) 3))
(or (= (dec lastp) pos)
(= "ER" (slice string (+ pos 2) 2))))
(= "M" (slice string (inc pos) 1)))
[:M :M 2]
[:M :M 1]))
(defn- lookup-N [string pos]
[:N :N (if (= "N" (slice string (inc pos) 1)) 2 1)])
(defn- lookup-NY [string pos]
[:N :N 1])
(defn- lookup-P [string pos]
(if (= "H" (slice string (inc pos) 1))
[:F :F 2]
[:P :P (if (re-test? #"^P|B$" (slice string (inc pos) 1)) 2 1)]))
(defn- lookup-Q [string pos]
[:K :K (if (= "Q" (slice string (inc pos) 1)) 2 1)])
(defn- lookup-R [string pos lastp]
(let [current (if (= "R" (slice string (inc pos) 1)) 2 1)]
(if (and (= lastp pos)
(not (slavo-germanic? string))
(= "IE" (slice string (- pos 2) 2))
(not-re-test? #"^M(E|A)$" (slice string (- pos 4) 2)))
[nil :R current]
[:R :R current])))
(defn- lookup-S-1 [] [nil nil 1])
(defn- lookup-S-2 [] [:X :S 1])
(defn- lookup-S-3 [string pos]
(if (re-test? #"^H(EIM|OEK|OLM|OLZ)$" (slice string (inc pos) 4))
[:S :S 2]
[:X :X 2]))
(defn- lookup-S-4 [string]
[:S (if (slavo-germanic? string) :S :X) 3])
(defn- lookup-S-5 [string pos]
[:S :X (if (= "Z" (slice string (inc pos) 1)) 2 1)])
(defn- lookup-S-6 [string pos]
(cond (= "H" (slice string (+ pos 2) 1)) (if (re-test? #"^OO|ER|EN|UY|ED|EM$" (slice string (+ pos 3) 2))
[(if (re-test? #"^E(R|N)$" (slice string (+ pos 3) 2)) :X :SK) :SK 3]
[:X (if (and (zero? pos)
(not (vowel? (slice string 3 1)))
(not= "W" (slice string (+ pos 3) 1))) :S :X) 3])
(re-test? #"^I|E|Y$" (slice string (+ pos 2) 1)) [:S :S 3]
:else [:SK :SK 3]))
(defn- lookup-S [string pos lastp]
(cond (re-test? #"^(I|Y)SL$" (slice string (dec pos) 3)) (lookup-S-1)
(and (zero? pos)
(= "SUGAR" (slice string pos 5))) (lookup-S-2)
(= "SH" (slice string pos 2)) (lookup-S-3 string pos)
(or (re-test? #"^SI(O|A)$" (slice string pos 3))
(= "SIAN" (slice string pos 4))) (lookup-S-4 string)
(or (and (zero? pos)
(re-test? #"^M|N|L|W$" (slice string (inc pos) 1)))
(= "Z" (slice string (inc pos) 1))) (lookup-S-5 string pos)
(= "SC" (slice string pos 2)) (lookup-S-6 string pos)
:else [(when-not (and (= lastp pos)
(re-test? #"^(A|O)I$" (slice string (- pos 2) 2)))
:S)
:S
(if (re-test? #"^S|Z$" (slice string (inc pos) 1)) 2 1)]))
(defn- lookup-T-1 [] [:X :X 3])
(defn- lookup-T-2 [string pos]
(if (or (re-test? #"^(O|A)M$" (slice string (+ pos 2) 2))
(re-test? #"^V(A|O)N " (slice string 0 4))
(= "SCH" (slice string 0 3)))
[:T :T 2]
[:0 :T 2]))
(defn- lookup-T [string pos]
(cond (= "TION" (slice string pos 4)) (lookup-T-1)
(re-test? #"^T(IA|CH)$" (slice string pos 3)) (lookup-T-1)
(or (= "TH" (slice string pos 2))
(= "TTH" (slice string pos 3))) (lookup-T-2 string pos)
:else [:T :T (if (re-test? #"^T|D$" (slice string (inc pos) 1)) 2 1)]))
(defn- lookup-V [string pos]
[:F :F (if (= "V" (slice string (inc pos) 1)) 2 1)])
(defn- let-lookup-W [string pos]
(if (and (zero? pos)
(or (vowel? (slice string (inc pos) 1))
(= "WH" (slice string pos 2))))
["A" (if (vowel? (slice string (inc pos) 1)) "F" "A")]
[nil nil]))
(defn- lookup-W-1 [] [:R :R 2])
(defn- lookup-W-2 [pri sec]
[(keyword pri) (keyword (str sec "F")) 1])
(defn- lookup-W-3 [pri sec]
[(keyword (str pri "TS")) (keyword (str sec "FX")) 4])
(defn- lookup-W [string pos lastp]
(if (= "WR" (slice string pos 2))
(lookup-W-1)
(let [[pri sec] (let-lookup-W string pos)]
(cond (or (and (= lastp pos)
(vowel? (slice string (dec pos) 1)))
(= "SCH" (slice string 0 3))
(re-test? #"^EWSKI|EWSKY|OWSKI|OWSKY$" (slice string (dec pos) 5))) (lookup-W-2 pri sec)
(re-test? #"^WI(C|T)Z$" (slice string pos 4)) (lookup-W-3 pri sec)
:else [(keyword pri) (keyword sec) 1]))))
(defn- lookup-X [string pos lastp]
(if (zero? pos)
[:S :S 1]
(let [current (if (re-test? #"^C|X$" (slice string (inc pos) 1)) 2 1)]
(if-not (and (= lastp pos)
(or (re-test? #"^(I|E)AU$" (slice string (- pos 3) 3))
(re-test? #"^(A|O)U$" (slice string (- pos 2) 2))))
[:KS :KS current]
[nil nil current]))))
(defn- lookup-Z-1 [] [:J :J 2])
(defn- lookup-Z-2 [current] [:S :TS current])
(defn- lookup-Z-3 [current] [:S :S current])
(defn- lookup-Z [string pos]
(if (="H" (slice string (inc pos) 1))
(lookup-Z-1)
(let [current (if (= "Z" (slice string (inc pos) 1)) 2 1)]
(if (or (re-test? #"^Z(O|I|A)$" (slice string (inc pos) 2))
(and (slavo-germanic? string)
(pos? pos)
(not= "T" (slice string (dec pos) 1))))
(lookup-Z-2 current)
(lookup-Z-3 current)))))
(defn lookup [string pos length lastp]
(let [char-to-lookup (slice string pos 1)]
(cond (vowel? char-to-lookup) (lookup-vowel pos)
(= "B" char-to-lookup) (lookup-B string pos)
(= "Ç" char-to-lookup) (lookup-C-cedilla)
(= "C" char-to-lookup) (lookup-C string pos)
(= "D" char-to-lookup) (lookup-D string pos)
(= "F" char-to-lookup) (lookup-F string pos)
(= "G" char-to-lookup) (lookup-G string pos)
(= "H" char-to-lookup) (lookup-H string pos)
(= "J" char-to-lookup) (lookup-J string pos lastp)
(= "K" char-to-lookup) (lookup-K string pos)
(= "L" char-to-lookup) (lookup-L string pos length lastp)
(= "M" char-to-lookup) (lookup-M string pos lastp)
(= "N" char-to-lookup) (lookup-N string pos)
(= "Ñ" char-to-lookup) (lookup-NY string pos)
(= "P" char-to-lookup) (lookup-P string pos)
(= "Q" char-to-lookup) (lookup-Q string pos)
(= "R" char-to-lookup) (lookup-R string pos lastp)
(= "S" char-to-lookup) (lookup-S string pos lastp)
(= "T" char-to-lookup) (lookup-T string pos)
(= "V" char-to-lookup) (lookup-V string pos)
(= "W" char-to-lookup) (lookup-W string pos lastp)
(= "X" char-to-lookup) (lookup-X string pos lastp)
(= "Z" char-to-lookup) (lookup-Z string pos)
:else [nil nil 1])))
;; Main functions
(defn- prep-string
"Prepare the [string] before its passage through the Double Metaphone
Algorithm."
[string]
(str (clojure.string/upper-case string) " "))
(defn- define-start-position [pstring] (if (re-test? #"^GN|KN|PN|WR|PS$" (slice pstring 0 2)) 1 0))
(defn- symbols->string [symbols] (slice (apply str (map name symbols)) 0 4))
(defn process
"Applying the Double Metaphone algorithm to a single [string]."
[string]
(let [pstring (prep-string string)
current (define-start-position pstring)
length (count string)
lastp (dec length)]
(loop [pos current
primary []
secondary []]
(if (or (> pos length)
(and (>= (count primary) 4)
(>= (count secondary) 4)))
[(symbols->string primary) (symbols->string secondary)]
(let [[newp news offset] (lookup pstring pos length lastp)]
(recur (+ offset pos)
(conj-if-not-nil primary newp)
(conj-if-not-nil secondary news)))))))
| 22840 | ;; -------------------------------------------------------------------
;; clj-fuzzy Double Metaphone
;; -------------------------------------------------------------------
;;
;;
;; Author: <NAME> (Yomguithereal)
;; Version: 0.1
;;
(ns clj-fuzzy.double-metaphone
(:require clojure.string)
(:use [clj-fuzzy.helpers :only [re-test?
slice
in?]]))
;; Utilities
(defn- slavo-germanic? [string] (re-test? #"W|K|CZ|WITZ" string))
(defn- vowel? [string] (re-test? #"^A|E|I|O|U|Y$" string))
(defn- conj-if-not-nil [array value]
(if (nil? value)
array
(conj array value)))
(def ^:private not-re-test? (complement re-test?))
;; Lookup functions
(defn- lookup-vowel [pos] (if (zero? pos) [:A :A 1] [nil nil 1]))
(defn- lookup-B [string pos]
[:P :P (if (= "B" (slice string (inc pos) 1)) 2 1)])
(defn- lookup-C-cedilla [] [:S :S 1])
(defn- lookup-C-1 [] [:K :K 2])
(defn- lookup-C-2 [] [:S :S 2])
(defn- lookup-C-3 [string pos]
(cond (and (pos? pos)
(= "CHAE" (slice string pos 4))) [:K :X 2]
(and (zero? pos)
(or (in? (slice string (inc pos) 5) ["HARAC" "HARIS"])
(in? (slice string (inc pos) 3) ["HOR" "HYM" "HIA" "HEM"]))
(not= "CHORE" (slice string 0 5))) [:K :K 2]
(or (in? (slice string 0 4) ["VAN " "VON "])
(= "SCH" (slice string 0 3))
(in? (slice string (- pos 2) 6) ["ORCHES" "ARCHIT" "ORCHID"])
(in? (slice string (+ pos 2) 1) ["T" "S"])
(and (or (zero? pos)
(in? (slice string (dec pos) 1) ["A" "O" "U" "E"]))
(in? (slice string (+ pos 2) 1) ["L" "R" "N" "M" "B" "H" "F" "V" "W" " "]))) [:K :K 2]
(pos? pos) [(if (= "MC" (slice string 0 2)) :K :X) :K 2]
:else [:X :X 2]))
(defn- lookup-C-4 [] [:S :X 2])
(defn- lookup-C-5 [] [:X :X 3])
(defn- lookup-C-6 [string pos]
(if (and (re-test? #"^I|E|H$" (slice string (+ pos 2) 1))
(not= "HU" (slice string (+ pos 2) 2)))
(if (or (and (= pos 1)
(= "A" (slice string (dec pos) 1)))
(re-test? #"^UCCE(E|S)$" (slice string (dec pos) 5)))
[:KS :KS 3]
[:X :X 3])
[:K :K 2]))
(defn- lookup-C-7 [] [:K :K 2])
(defn- lookup-C-8 [string pos]
[:S (if (re-test? #"^CI(O|E|A)$" (slice string pos 3)) :X :S) 2])
(defn- lookup-C-9 [string pos]
(if (re-test? #"^ (C|Q|G)$" (slice string (inc pos) 2))
[:K :K 3]
[:K :K (if (and (re-test? #"^C|K|Q$" (slice string (inc pos) 1))
(not (in? (slice string (inc pos) 2) ["CE" "CI"]))) 2 1)]))
(defn- lookup-C [string pos]
(cond (and (> pos 1)
(vowel? (slice string (- pos 2) 1))
(= "ACH" (slice string (dec pos) 3))
(not= "I" (slice string (+ pos 2) 1))
(or (not= "E" (slice string (+ pos 2) 1))
(re-test? #"^(B|M)ACHER$" (slice string (- pos 2) 6)))) (lookup-C-1)
(and (zero? pos) (= "CAESAR" (slice string pos 6))) (lookup-C-2)
(= "CHIA" (slice string pos 4)) (lookup-C-1)
(= "CH" (slice string pos 2)) (lookup-C-3 string pos)
(and (= "CZ" (slice string pos 2)) (not= "WICZ" (slice string (- pos 2) 4))) (lookup-C-4)
(= "CIA" (slice string (inc pos) 3)) (lookup-C-5)
(and (= "CC" (slice string pos 2))
(not (or (= pos 1) (= "M" (slice string 0 1))))) (lookup-C-6 string pos)
(re-test? #"^C(K|G|Q)$" (slice string pos 2)) (lookup-C-7)
(re-test? #"^C(I|E|Y)$" (slice string pos 2)) (lookup-C-8 string pos)
:else (lookup-C-9 string pos)))
(defn- lookup-D [string pos]
(if (= "DG" (slice string pos 2))
(if (re-test? #"^I|E|Y$" (slice string (+ pos 2) 1))
[:J :J 3]
[:TK :TK 2])
[:T :T (if (re-test? #"^D(T|D)$" (slice string pos 2)) 2 1)]))
(defn- lookup-F [string pos]
[:F :F (if (= "F" (slice string (inc pos) 1)) 2 1)])
(defn lookup-G-1-bis [string pos]
(cond (and (> pos 2)
(= "U" (slice string (dec pos) 1))
(re-test? #"^C|G|L|R|T$" (slice string (- pos 3) 1))) [:F :F 2]
(and (pos? pos) (not= "I" (slice string (dec pos) 1))) [:K :K 2]
:else [nil nil 2]))
(defn- lookup-G-1 [string pos]
(cond (and (pos? pos)
(not (vowel? (slice string (dec pos) 1)))) [:K :K 2]
(zero? pos) (if (= "I" (slice string (+ pos 2) 1)) [:J :J 2] [:K :K 2])
(or (and (> pos 1) (re-test? #"^B|H|D$" (slice string (- pos 2) 1)))
(and (> pos 2) (re-test? #"^B|H|D$" (slice string (- pos 3) 1)))
(and (> pos 3) (re-test? #"^B|H$" (slice string (- pos 4) 1)))) [nil nil 2]
:else (lookup-G-1-bis string pos)))
(defn- lookup-G-2 [string pos]
(if (and (= pos 1)
(vowel? (slice string 0 1))
(not (slavo-germanic? string)))
[:KN :N 2]
(if (and (not= "EY" (slice string (+ pos 2) 2))
(not= "Y" (slice string (inc pos) 1))
(not (slavo-germanic? string)))
[:N :KN 2]
[:KN :KN 2])))
(defn- lookup-G-3 [] [:KL :L 2])
(defn- lookup-G-4 [] [:K :J 2])
(defn- lookup-G-5 [] [:K :J 2])
(defn- lookup-G-6 [string pos]
(if (or (re-test? #"^V(A|O)N $" (slice string 0 4))
(= "SCH" (slice string 0 3))
(= "ET" (slice string (inc pos) 2)))
[:K :K 2]
(if (= "IER " (slice string (inc pos) 4))
[:J :J 2]
[:J :K 2])))
(defn- lookup-G-7 [] [:K :K 2])
(defn- lookup-G-8 [] [:K :K 1])
(defn- lookup-G [string pos]
(cond (= "H" (slice string (inc pos) 1)) (lookup-G-1 string pos)
(= "N" (slice string (inc pos) 1)) (lookup-G-2 string pos)
(and (= "LI" (slice string (inc pos) 2)) (not (slavo-germanic? string))) (lookup-G-3)
(and (zero? pos)
(or (= "Y" (slice string (inc pos) 1))
(re-test? #"^(E(S|P|B|L|Y|I|R)|I(B|L|N|E))$" (slice string (inc pos) 2)))) (lookup-G-4)
(and (or (= "ER" (slice string (inc pos) 2)) (= "Y" (slice string (inc pos) 1)))
(not-re-test? #"^(D|R|M)ANGER$" (slice string 0 6))
(not-re-test? #"^E|I$" (slice string (dec pos) 1))
(not-re-test? #"^(R|O)GY$" (slice string (dec pos) 3))) (lookup-G-5)
(or (re-test? #"^E|I|Y$" (slice string (inc pos) 1))
(re-test? #"^(A|O)GGI$" (slice string (dec pos) 4))) (lookup-G-6 string pos)
(= "G" (slice string (inc pos) 1)) (lookup-G-7)
:else (lookup-G-8)))
(defn- lookup-H [string pos]
(if (and (or (zero? pos) (vowel? (slice string (dec pos) 1)))
(vowel? (slice string (inc pos) 1)))
[:H :H 2]
[nil nil 1]))
(defn- lookup-J-1 [string pos]
(if (or (and (zero? pos)
(= " " (slice string (+ pos 4) 1)))
(= "SAN " (slice string 0 4)))
[:H :H 1]
[:J :H 1]))
(defn- lookup-J-2-bis [current] [:J :H current])
(defn- lookup-J-2-ter [string pos lastp current]
(if (= lastp pos)
[:J nil current]
(if (and (not-re-test? #"^L|T|K|S|N|M|B|Z$" (slice string (inc pos) 1))
(not-re-test? #"^S|K|L$" (slice string (dec pos) 1)))
[:J :J current]
[nil nil current])))
(defn- lookup-J-2 [string pos lastp]
(let [current (if (= "J" (slice string (inc pos) 1)) 2 1)]
(if (and (zero? pos)
(not= "<NAME>SE" (slice string pos 4)))
[:J :A current]
(if (and (vowel? (slice string (dec pos) 1))
(not (slavo-germanic? string))
(re-test? #"^A|O$" (slice string (inc pos) 1)))
(lookup-J-2-bis current)
(lookup-J-2-ter string pos lastp current)))))
(defn- lookup-J [string pos lastp]
(if (or (= "JOSE" (slice string pos 4)) (= "SAN " (slice string 0 4)))
(lookup-J-1 string pos)
(lookup-J-2 string pos lastp)))
(defn- lookup-K [string pos]
[:K :K (if (= "K" (slice string (inc pos) 1)) 2 1)])
(defn- lookup-L-1 [string pos length lastp]
(if (or (and (= (- length 3) pos) (re-test? #"^(ILL(O|A)|ALLE)$" (slice string (dec pos) 4)))
(and (or (re-test? #"^(A|O)S$" (slice string (dec lastp) 2))
(re-test? #"^A|O$" (slice string lastp 1)))
(= "ALLE" (slice string (dec pos) 4))))
[:L nil 2]
[:L :L 2]))
(defn- lookup-L [string pos length lastp]
(if (= "L" (slice string (inc pos) 1))
(lookup-L-1 string pos length lastp)
[:L :L 1]))
(defn- lookup-M [string pos lastp]
(if (or (and (= "UMB" (slice string (dec pos) 3))
(or (= (dec lastp) pos)
(= "ER" (slice string (+ pos 2) 2))))
(= "M" (slice string (inc pos) 1)))
[:M :M 2]
[:M :M 1]))
(defn- lookup-N [string pos]
[:N :N (if (= "N" (slice string (inc pos) 1)) 2 1)])
(defn- lookup-NY [string pos]
[:N :N 1])
(defn- lookup-P [string pos]
(if (= "H" (slice string (inc pos) 1))
[:F :F 2]
[:P :P (if (re-test? #"^P|B$" (slice string (inc pos) 1)) 2 1)]))
(defn- lookup-Q [string pos]
[:K :K (if (= "Q" (slice string (inc pos) 1)) 2 1)])
(defn- lookup-R [string pos lastp]
(let [current (if (= "R" (slice string (inc pos) 1)) 2 1)]
(if (and (= lastp pos)
(not (slavo-germanic? string))
(= "IE" (slice string (- pos 2) 2))
(not-re-test? #"^M(E|A)$" (slice string (- pos 4) 2)))
[nil :R current]
[:R :R current])))
(defn- lookup-S-1 [] [nil nil 1])
(defn- lookup-S-2 [] [:X :S 1])
(defn- lookup-S-3 [string pos]
(if (re-test? #"^H(EIM|OEK|OLM|OLZ)$" (slice string (inc pos) 4))
[:S :S 2]
[:X :X 2]))
(defn- lookup-S-4 [string]
[:S (if (slavo-germanic? string) :S :X) 3])
(defn- lookup-S-5 [string pos]
[:S :X (if (= "Z" (slice string (inc pos) 1)) 2 1)])
(defn- lookup-S-6 [string pos]
(cond (= "H" (slice string (+ pos 2) 1)) (if (re-test? #"^OO|ER|EN|UY|ED|EM$" (slice string (+ pos 3) 2))
[(if (re-test? #"^E(R|N)$" (slice string (+ pos 3) 2)) :X :SK) :SK 3]
[:X (if (and (zero? pos)
(not (vowel? (slice string 3 1)))
(not= "W" (slice string (+ pos 3) 1))) :S :X) 3])
(re-test? #"^I|E|Y$" (slice string (+ pos 2) 1)) [:S :S 3]
:else [:SK :SK 3]))
(defn- lookup-S [string pos lastp]
(cond (re-test? #"^(I|Y)SL$" (slice string (dec pos) 3)) (lookup-S-1)
(and (zero? pos)
(= "<NAME>" (slice string pos 5))) (lookup-S-2)
(= "SH" (slice string pos 2)) (lookup-S-3 string pos)
(or (re-test? #"^SI(O|A)$" (slice string pos 3))
(= "SIAN" (slice string pos 4))) (lookup-S-4 string)
(or (and (zero? pos)
(re-test? #"^M|N|L|W$" (slice string (inc pos) 1)))
(= "Z" (slice string (inc pos) 1))) (lookup-S-5 string pos)
(= "SC" (slice string pos 2)) (lookup-S-6 string pos)
:else [(when-not (and (= lastp pos)
(re-test? #"^(A|O)I$" (slice string (- pos 2) 2)))
:S)
:S
(if (re-test? #"^S|Z$" (slice string (inc pos) 1)) 2 1)]))
(defn- lookup-T-1 [] [:X :X 3])
(defn- lookup-T-2 [string pos]
(if (or (re-test? #"^(O|A)M$" (slice string (+ pos 2) 2))
(re-test? #"^V(A|O)N " (slice string 0 4))
(= "SCH" (slice string 0 3)))
[:T :T 2]
[:0 :T 2]))
(defn- lookup-T [string pos]
(cond (= "TION" (slice string pos 4)) (lookup-T-1)
(re-test? #"^T(IA|CH)$" (slice string pos 3)) (lookup-T-1)
(or (= "TH" (slice string pos 2))
(= "TTH" (slice string pos 3))) (lookup-T-2 string pos)
:else [:T :T (if (re-test? #"^T|D$" (slice string (inc pos) 1)) 2 1)]))
(defn- lookup-V [string pos]
[:F :F (if (= "V" (slice string (inc pos) 1)) 2 1)])
(defn- let-lookup-W [string pos]
(if (and (zero? pos)
(or (vowel? (slice string (inc pos) 1))
(= "WH" (slice string pos 2))))
["A" (if (vowel? (slice string (inc pos) 1)) "F" "A")]
[nil nil]))
(defn- lookup-W-1 [] [:R :R 2])
(defn- lookup-W-2 [pri sec]
[(keyword pri) (keyword (str sec "F")) 1])
(defn- lookup-W-3 [pri sec]
[(keyword (str pri "TS")) (keyword (str sec "FX")) 4])
(defn- lookup-W [string pos lastp]
(if (= "WR" (slice string pos 2))
(lookup-W-1)
(let [[pri sec] (let-lookup-W string pos)]
(cond (or (and (= lastp pos)
(vowel? (slice string (dec pos) 1)))
(= "SCH" (slice string 0 3))
(re-test? #"^EWSKI|EWSKY|OWSKI|OWSKY$" (slice string (dec pos) 5))) (lookup-W-2 pri sec)
(re-test? #"^WI(C|T)Z$" (slice string pos 4)) (lookup-W-3 pri sec)
:else [(keyword pri) (keyword sec) 1]))))
(defn- lookup-X [string pos lastp]
(if (zero? pos)
[:S :S 1]
(let [current (if (re-test? #"^C|X$" (slice string (inc pos) 1)) 2 1)]
(if-not (and (= lastp pos)
(or (re-test? #"^(I|E)AU$" (slice string (- pos 3) 3))
(re-test? #"^(A|O)U$" (slice string (- pos 2) 2))))
[:KS :KS current]
[nil nil current]))))
(defn- lookup-Z-1 [] [:J :J 2])
(defn- lookup-Z-2 [current] [:S :TS current])
(defn- lookup-Z-3 [current] [:S :S current])
(defn- lookup-Z [string pos]
(if (="H" (slice string (inc pos) 1))
(lookup-Z-1)
(let [current (if (= "Z" (slice string (inc pos) 1)) 2 1)]
(if (or (re-test? #"^Z(O|I|A)$" (slice string (inc pos) 2))
(and (slavo-germanic? string)
(pos? pos)
(not= "T" (slice string (dec pos) 1))))
(lookup-Z-2 current)
(lookup-Z-3 current)))))
(defn lookup [string pos length lastp]
(let [char-to-lookup (slice string pos 1)]
(cond (vowel? char-to-lookup) (lookup-vowel pos)
(= "B" char-to-lookup) (lookup-B string pos)
(= "Ç" char-to-lookup) (lookup-C-cedilla)
(= "C" char-to-lookup) (lookup-C string pos)
(= "D" char-to-lookup) (lookup-D string pos)
(= "F" char-to-lookup) (lookup-F string pos)
(= "G" char-to-lookup) (lookup-G string pos)
(= "H" char-to-lookup) (lookup-H string pos)
(= "J" char-to-lookup) (lookup-J string pos lastp)
(= "K" char-to-lookup) (lookup-K string pos)
(= "L" char-to-lookup) (lookup-L string pos length lastp)
(= "M" char-to-lookup) (lookup-M string pos lastp)
(= "N" char-to-lookup) (lookup-N string pos)
(= "Ñ" char-to-lookup) (lookup-NY string pos)
(= "P" char-to-lookup) (lookup-P string pos)
(= "Q" char-to-lookup) (lookup-Q string pos)
(= "R" char-to-lookup) (lookup-R string pos lastp)
(= "S" char-to-lookup) (lookup-S string pos lastp)
(= "T" char-to-lookup) (lookup-T string pos)
(= "V" char-to-lookup) (lookup-V string pos)
(= "W" char-to-lookup) (lookup-W string pos lastp)
(= "X" char-to-lookup) (lookup-X string pos lastp)
(= "Z" char-to-lookup) (lookup-Z string pos)
:else [nil nil 1])))
;; Main functions
(defn- prep-string
"Prepare the [string] before its passage through the Double Metaphone
Algorithm."
[string]
(str (clojure.string/upper-case string) " "))
(defn- define-start-position [pstring] (if (re-test? #"^GN|KN|PN|WR|PS$" (slice pstring 0 2)) 1 0))
(defn- symbols->string [symbols] (slice (apply str (map name symbols)) 0 4))
(defn process
"Applying the Double Metaphone algorithm to a single [string]."
[string]
(let [pstring (prep-string string)
current (define-start-position pstring)
length (count string)
lastp (dec length)]
(loop [pos current
primary []
secondary []]
(if (or (> pos length)
(and (>= (count primary) 4)
(>= (count secondary) 4)))
[(symbols->string primary) (symbols->string secondary)]
(let [[newp news offset] (lookup pstring pos length lastp)]
(recur (+ offset pos)
(conj-if-not-nil primary newp)
(conj-if-not-nil secondary news)))))))
| true | ;; -------------------------------------------------------------------
;; clj-fuzzy Double Metaphone
;; -------------------------------------------------------------------
;;
;;
;; Author: PI:NAME:<NAME>END_PI (Yomguithereal)
;; Version: 0.1
;;
(ns clj-fuzzy.double-metaphone
(:require clojure.string)
(:use [clj-fuzzy.helpers :only [re-test?
slice
in?]]))
;; Utilities
(defn- slavo-germanic? [string] (re-test? #"W|K|CZ|WITZ" string))
(defn- vowel? [string] (re-test? #"^A|E|I|O|U|Y$" string))
(defn- conj-if-not-nil [array value]
(if (nil? value)
array
(conj array value)))
(def ^:private not-re-test? (complement re-test?))
;; Lookup functions
(defn- lookup-vowel [pos] (if (zero? pos) [:A :A 1] [nil nil 1]))
(defn- lookup-B [string pos]
[:P :P (if (= "B" (slice string (inc pos) 1)) 2 1)])
(defn- lookup-C-cedilla [] [:S :S 1])
(defn- lookup-C-1 [] [:K :K 2])
(defn- lookup-C-2 [] [:S :S 2])
(defn- lookup-C-3 [string pos]
(cond (and (pos? pos)
(= "CHAE" (slice string pos 4))) [:K :X 2]
(and (zero? pos)
(or (in? (slice string (inc pos) 5) ["HARAC" "HARIS"])
(in? (slice string (inc pos) 3) ["HOR" "HYM" "HIA" "HEM"]))
(not= "CHORE" (slice string 0 5))) [:K :K 2]
(or (in? (slice string 0 4) ["VAN " "VON "])
(= "SCH" (slice string 0 3))
(in? (slice string (- pos 2) 6) ["ORCHES" "ARCHIT" "ORCHID"])
(in? (slice string (+ pos 2) 1) ["T" "S"])
(and (or (zero? pos)
(in? (slice string (dec pos) 1) ["A" "O" "U" "E"]))
(in? (slice string (+ pos 2) 1) ["L" "R" "N" "M" "B" "H" "F" "V" "W" " "]))) [:K :K 2]
(pos? pos) [(if (= "MC" (slice string 0 2)) :K :X) :K 2]
:else [:X :X 2]))
(defn- lookup-C-4 [] [:S :X 2])
(defn- lookup-C-5 [] [:X :X 3])
(defn- lookup-C-6 [string pos]
(if (and (re-test? #"^I|E|H$" (slice string (+ pos 2) 1))
(not= "HU" (slice string (+ pos 2) 2)))
(if (or (and (= pos 1)
(= "A" (slice string (dec pos) 1)))
(re-test? #"^UCCE(E|S)$" (slice string (dec pos) 5)))
[:KS :KS 3]
[:X :X 3])
[:K :K 2]))
(defn- lookup-C-7 [] [:K :K 2])
(defn- lookup-C-8 [string pos]
[:S (if (re-test? #"^CI(O|E|A)$" (slice string pos 3)) :X :S) 2])
(defn- lookup-C-9 [string pos]
(if (re-test? #"^ (C|Q|G)$" (slice string (inc pos) 2))
[:K :K 3]
[:K :K (if (and (re-test? #"^C|K|Q$" (slice string (inc pos) 1))
(not (in? (slice string (inc pos) 2) ["CE" "CI"]))) 2 1)]))
(defn- lookup-C [string pos]
(cond (and (> pos 1)
(vowel? (slice string (- pos 2) 1))
(= "ACH" (slice string (dec pos) 3))
(not= "I" (slice string (+ pos 2) 1))
(or (not= "E" (slice string (+ pos 2) 1))
(re-test? #"^(B|M)ACHER$" (slice string (- pos 2) 6)))) (lookup-C-1)
(and (zero? pos) (= "CAESAR" (slice string pos 6))) (lookup-C-2)
(= "CHIA" (slice string pos 4)) (lookup-C-1)
(= "CH" (slice string pos 2)) (lookup-C-3 string pos)
(and (= "CZ" (slice string pos 2)) (not= "WICZ" (slice string (- pos 2) 4))) (lookup-C-4)
(= "CIA" (slice string (inc pos) 3)) (lookup-C-5)
(and (= "CC" (slice string pos 2))
(not (or (= pos 1) (= "M" (slice string 0 1))))) (lookup-C-6 string pos)
(re-test? #"^C(K|G|Q)$" (slice string pos 2)) (lookup-C-7)
(re-test? #"^C(I|E|Y)$" (slice string pos 2)) (lookup-C-8 string pos)
:else (lookup-C-9 string pos)))
(defn- lookup-D [string pos]
(if (= "DG" (slice string pos 2))
(if (re-test? #"^I|E|Y$" (slice string (+ pos 2) 1))
[:J :J 3]
[:TK :TK 2])
[:T :T (if (re-test? #"^D(T|D)$" (slice string pos 2)) 2 1)]))
(defn- lookup-F [string pos]
[:F :F (if (= "F" (slice string (inc pos) 1)) 2 1)])
(defn lookup-G-1-bis [string pos]
(cond (and (> pos 2)
(= "U" (slice string (dec pos) 1))
(re-test? #"^C|G|L|R|T$" (slice string (- pos 3) 1))) [:F :F 2]
(and (pos? pos) (not= "I" (slice string (dec pos) 1))) [:K :K 2]
:else [nil nil 2]))
(defn- lookup-G-1 [string pos]
(cond (and (pos? pos)
(not (vowel? (slice string (dec pos) 1)))) [:K :K 2]
(zero? pos) (if (= "I" (slice string (+ pos 2) 1)) [:J :J 2] [:K :K 2])
(or (and (> pos 1) (re-test? #"^B|H|D$" (slice string (- pos 2) 1)))
(and (> pos 2) (re-test? #"^B|H|D$" (slice string (- pos 3) 1)))
(and (> pos 3) (re-test? #"^B|H$" (slice string (- pos 4) 1)))) [nil nil 2]
:else (lookup-G-1-bis string pos)))
(defn- lookup-G-2 [string pos]
(if (and (= pos 1)
(vowel? (slice string 0 1))
(not (slavo-germanic? string)))
[:KN :N 2]
(if (and (not= "EY" (slice string (+ pos 2) 2))
(not= "Y" (slice string (inc pos) 1))
(not (slavo-germanic? string)))
[:N :KN 2]
[:KN :KN 2])))
(defn- lookup-G-3 [] [:KL :L 2])
(defn- lookup-G-4 [] [:K :J 2])
(defn- lookup-G-5 [] [:K :J 2])
(defn- lookup-G-6 [string pos]
(if (or (re-test? #"^V(A|O)N $" (slice string 0 4))
(= "SCH" (slice string 0 3))
(= "ET" (slice string (inc pos) 2)))
[:K :K 2]
(if (= "IER " (slice string (inc pos) 4))
[:J :J 2]
[:J :K 2])))
(defn- lookup-G-7 [] [:K :K 2])
(defn- lookup-G-8 [] [:K :K 1])
(defn- lookup-G [string pos]
(cond (= "H" (slice string (inc pos) 1)) (lookup-G-1 string pos)
(= "N" (slice string (inc pos) 1)) (lookup-G-2 string pos)
(and (= "LI" (slice string (inc pos) 2)) (not (slavo-germanic? string))) (lookup-G-3)
(and (zero? pos)
(or (= "Y" (slice string (inc pos) 1))
(re-test? #"^(E(S|P|B|L|Y|I|R)|I(B|L|N|E))$" (slice string (inc pos) 2)))) (lookup-G-4)
(and (or (= "ER" (slice string (inc pos) 2)) (= "Y" (slice string (inc pos) 1)))
(not-re-test? #"^(D|R|M)ANGER$" (slice string 0 6))
(not-re-test? #"^E|I$" (slice string (dec pos) 1))
(not-re-test? #"^(R|O)GY$" (slice string (dec pos) 3))) (lookup-G-5)
(or (re-test? #"^E|I|Y$" (slice string (inc pos) 1))
(re-test? #"^(A|O)GGI$" (slice string (dec pos) 4))) (lookup-G-6 string pos)
(= "G" (slice string (inc pos) 1)) (lookup-G-7)
:else (lookup-G-8)))
(defn- lookup-H [string pos]
(if (and (or (zero? pos) (vowel? (slice string (dec pos) 1)))
(vowel? (slice string (inc pos) 1)))
[:H :H 2]
[nil nil 1]))
(defn- lookup-J-1 [string pos]
(if (or (and (zero? pos)
(= " " (slice string (+ pos 4) 1)))
(= "SAN " (slice string 0 4)))
[:H :H 1]
[:J :H 1]))
(defn- lookup-J-2-bis [current] [:J :H current])
(defn- lookup-J-2-ter [string pos lastp current]
(if (= lastp pos)
[:J nil current]
(if (and (not-re-test? #"^L|T|K|S|N|M|B|Z$" (slice string (inc pos) 1))
(not-re-test? #"^S|K|L$" (slice string (dec pos) 1)))
[:J :J current]
[nil nil current])))
(defn- lookup-J-2 [string pos lastp]
(let [current (if (= "J" (slice string (inc pos) 1)) 2 1)]
(if (and (zero? pos)
(not= "PI:NAME:<NAME>END_PISE" (slice string pos 4)))
[:J :A current]
(if (and (vowel? (slice string (dec pos) 1))
(not (slavo-germanic? string))
(re-test? #"^A|O$" (slice string (inc pos) 1)))
(lookup-J-2-bis current)
(lookup-J-2-ter string pos lastp current)))))
(defn- lookup-J [string pos lastp]
(if (or (= "JOSE" (slice string pos 4)) (= "SAN " (slice string 0 4)))
(lookup-J-1 string pos)
(lookup-J-2 string pos lastp)))
(defn- lookup-K [string pos]
[:K :K (if (= "K" (slice string (inc pos) 1)) 2 1)])
(defn- lookup-L-1 [string pos length lastp]
(if (or (and (= (- length 3) pos) (re-test? #"^(ILL(O|A)|ALLE)$" (slice string (dec pos) 4)))
(and (or (re-test? #"^(A|O)S$" (slice string (dec lastp) 2))
(re-test? #"^A|O$" (slice string lastp 1)))
(= "ALLE" (slice string (dec pos) 4))))
[:L nil 2]
[:L :L 2]))
(defn- lookup-L [string pos length lastp]
(if (= "L" (slice string (inc pos) 1))
(lookup-L-1 string pos length lastp)
[:L :L 1]))
(defn- lookup-M [string pos lastp]
(if (or (and (= "UMB" (slice string (dec pos) 3))
(or (= (dec lastp) pos)
(= "ER" (slice string (+ pos 2) 2))))
(= "M" (slice string (inc pos) 1)))
[:M :M 2]
[:M :M 1]))
(defn- lookup-N [string pos]
[:N :N (if (= "N" (slice string (inc pos) 1)) 2 1)])
(defn- lookup-NY [string pos]
[:N :N 1])
(defn- lookup-P [string pos]
(if (= "H" (slice string (inc pos) 1))
[:F :F 2]
[:P :P (if (re-test? #"^P|B$" (slice string (inc pos) 1)) 2 1)]))
(defn- lookup-Q [string pos]
[:K :K (if (= "Q" (slice string (inc pos) 1)) 2 1)])
(defn- lookup-R [string pos lastp]
(let [current (if (= "R" (slice string (inc pos) 1)) 2 1)]
(if (and (= lastp pos)
(not (slavo-germanic? string))
(= "IE" (slice string (- pos 2) 2))
(not-re-test? #"^M(E|A)$" (slice string (- pos 4) 2)))
[nil :R current]
[:R :R current])))
(defn- lookup-S-1 [] [nil nil 1])
(defn- lookup-S-2 [] [:X :S 1])
(defn- lookup-S-3 [string pos]
(if (re-test? #"^H(EIM|OEK|OLM|OLZ)$" (slice string (inc pos) 4))
[:S :S 2]
[:X :X 2]))
(defn- lookup-S-4 [string]
[:S (if (slavo-germanic? string) :S :X) 3])
(defn- lookup-S-5 [string pos]
[:S :X (if (= "Z" (slice string (inc pos) 1)) 2 1)])
(defn- lookup-S-6 [string pos]
(cond (= "H" (slice string (+ pos 2) 1)) (if (re-test? #"^OO|ER|EN|UY|ED|EM$" (slice string (+ pos 3) 2))
[(if (re-test? #"^E(R|N)$" (slice string (+ pos 3) 2)) :X :SK) :SK 3]
[:X (if (and (zero? pos)
(not (vowel? (slice string 3 1)))
(not= "W" (slice string (+ pos 3) 1))) :S :X) 3])
(re-test? #"^I|E|Y$" (slice string (+ pos 2) 1)) [:S :S 3]
:else [:SK :SK 3]))
(defn- lookup-S [string pos lastp]
(cond (re-test? #"^(I|Y)SL$" (slice string (dec pos) 3)) (lookup-S-1)
(and (zero? pos)
(= "PI:NAME:<NAME>END_PI" (slice string pos 5))) (lookup-S-2)
(= "SH" (slice string pos 2)) (lookup-S-3 string pos)
(or (re-test? #"^SI(O|A)$" (slice string pos 3))
(= "SIAN" (slice string pos 4))) (lookup-S-4 string)
(or (and (zero? pos)
(re-test? #"^M|N|L|W$" (slice string (inc pos) 1)))
(= "Z" (slice string (inc pos) 1))) (lookup-S-5 string pos)
(= "SC" (slice string pos 2)) (lookup-S-6 string pos)
:else [(when-not (and (= lastp pos)
(re-test? #"^(A|O)I$" (slice string (- pos 2) 2)))
:S)
:S
(if (re-test? #"^S|Z$" (slice string (inc pos) 1)) 2 1)]))
(defn- lookup-T-1 [] [:X :X 3])
(defn- lookup-T-2 [string pos]
(if (or (re-test? #"^(O|A)M$" (slice string (+ pos 2) 2))
(re-test? #"^V(A|O)N " (slice string 0 4))
(= "SCH" (slice string 0 3)))
[:T :T 2]
[:0 :T 2]))
(defn- lookup-T [string pos]
(cond (= "TION" (slice string pos 4)) (lookup-T-1)
(re-test? #"^T(IA|CH)$" (slice string pos 3)) (lookup-T-1)
(or (= "TH" (slice string pos 2))
(= "TTH" (slice string pos 3))) (lookup-T-2 string pos)
:else [:T :T (if (re-test? #"^T|D$" (slice string (inc pos) 1)) 2 1)]))
(defn- lookup-V [string pos]
[:F :F (if (= "V" (slice string (inc pos) 1)) 2 1)])
(defn- let-lookup-W [string pos]
(if (and (zero? pos)
(or (vowel? (slice string (inc pos) 1))
(= "WH" (slice string pos 2))))
["A" (if (vowel? (slice string (inc pos) 1)) "F" "A")]
[nil nil]))
(defn- lookup-W-1 [] [:R :R 2])
(defn- lookup-W-2 [pri sec]
[(keyword pri) (keyword (str sec "F")) 1])
(defn- lookup-W-3 [pri sec]
[(keyword (str pri "TS")) (keyword (str sec "FX")) 4])
(defn- lookup-W [string pos lastp]
(if (= "WR" (slice string pos 2))
(lookup-W-1)
(let [[pri sec] (let-lookup-W string pos)]
(cond (or (and (= lastp pos)
(vowel? (slice string (dec pos) 1)))
(= "SCH" (slice string 0 3))
(re-test? #"^EWSKI|EWSKY|OWSKI|OWSKY$" (slice string (dec pos) 5))) (lookup-W-2 pri sec)
(re-test? #"^WI(C|T)Z$" (slice string pos 4)) (lookup-W-3 pri sec)
:else [(keyword pri) (keyword sec) 1]))))
(defn- lookup-X [string pos lastp]
(if (zero? pos)
[:S :S 1]
(let [current (if (re-test? #"^C|X$" (slice string (inc pos) 1)) 2 1)]
(if-not (and (= lastp pos)
(or (re-test? #"^(I|E)AU$" (slice string (- pos 3) 3))
(re-test? #"^(A|O)U$" (slice string (- pos 2) 2))))
[:KS :KS current]
[nil nil current]))))
(defn- lookup-Z-1 [] [:J :J 2])
(defn- lookup-Z-2 [current] [:S :TS current])
(defn- lookup-Z-3 [current] [:S :S current])
(defn- lookup-Z [string pos]
(if (="H" (slice string (inc pos) 1))
(lookup-Z-1)
(let [current (if (= "Z" (slice string (inc pos) 1)) 2 1)]
(if (or (re-test? #"^Z(O|I|A)$" (slice string (inc pos) 2))
(and (slavo-germanic? string)
(pos? pos)
(not= "T" (slice string (dec pos) 1))))
(lookup-Z-2 current)
(lookup-Z-3 current)))))
(defn lookup [string pos length lastp]
(let [char-to-lookup (slice string pos 1)]
(cond (vowel? char-to-lookup) (lookup-vowel pos)
(= "B" char-to-lookup) (lookup-B string pos)
(= "Ç" char-to-lookup) (lookup-C-cedilla)
(= "C" char-to-lookup) (lookup-C string pos)
(= "D" char-to-lookup) (lookup-D string pos)
(= "F" char-to-lookup) (lookup-F string pos)
(= "G" char-to-lookup) (lookup-G string pos)
(= "H" char-to-lookup) (lookup-H string pos)
(= "J" char-to-lookup) (lookup-J string pos lastp)
(= "K" char-to-lookup) (lookup-K string pos)
(= "L" char-to-lookup) (lookup-L string pos length lastp)
(= "M" char-to-lookup) (lookup-M string pos lastp)
(= "N" char-to-lookup) (lookup-N string pos)
(= "Ñ" char-to-lookup) (lookup-NY string pos)
(= "P" char-to-lookup) (lookup-P string pos)
(= "Q" char-to-lookup) (lookup-Q string pos)
(= "R" char-to-lookup) (lookup-R string pos lastp)
(= "S" char-to-lookup) (lookup-S string pos lastp)
(= "T" char-to-lookup) (lookup-T string pos)
(= "V" char-to-lookup) (lookup-V string pos)
(= "W" char-to-lookup) (lookup-W string pos lastp)
(= "X" char-to-lookup) (lookup-X string pos lastp)
(= "Z" char-to-lookup) (lookup-Z string pos)
:else [nil nil 1])))
;; Main functions
(defn- prep-string
"Prepare the [string] before its passage through the Double Metaphone
Algorithm."
[string]
(str (clojure.string/upper-case string) " "))
(defn- define-start-position [pstring] (if (re-test? #"^GN|KN|PN|WR|PS$" (slice pstring 0 2)) 1 0))
(defn- symbols->string [symbols] (slice (apply str (map name symbols)) 0 4))
(defn process
"Applying the Double Metaphone algorithm to a single [string]."
[string]
(let [pstring (prep-string string)
current (define-start-position pstring)
length (count string)
lastp (dec length)]
(loop [pos current
primary []
secondary []]
(if (or (> pos length)
(and (>= (count primary) 4)
(>= (count secondary) 4)))
[(symbols->string primary) (symbols->string secondary)]
(let [[newp news offset] (lookup pstring pos length lastp)]
(recur (+ offset pos)
(conj-if-not-nil primary newp)
(conj-if-not-nil secondary news)))))))
|
[
{
"context": " {:api-host \"http://127.0.0.1:123\"\n ",
"end": 1980,
"score": 0.9997256398200989,
"start": 1971,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": " :write-key \"bar\"})]\n (is (instance? HoneyClient client))))\n ",
"end": 2258,
"score": 0.9745104908943176,
"start": 2255,
"tag": "KEY",
"value": "bar"
},
{
"context": " :write-key \"bar\"})]\n (is (instance? HoneyClient client))\n ",
"end": 2871,
"score": 0.8987507820129395,
"start": 2868,
"tag": "KEY",
"value": "bar"
}
] | test/clj_honeycomb/testing_utils_test.clj | conormcd/clj-honeycomb | 17 | (ns clj-honeycomb.testing-utils-test
(:require [clojure.spec.alpha :as s]
[clojure.spec.gen.alpha :as gen]
[clojure.spec.test.alpha :refer (with-instrument-disabled)]
[clojure.test :refer (deftest is testing)]
[clj-honeycomb.core :as honeycomb]
[clj-honeycomb.fixtures :refer (kitchen-sink-realized
make-kitchen-sink
use-fixtures)]
[clj-honeycomb.testing-utils :as tu])
(:import (io.honeycomb.libhoney Event
HoneyClient
ResponseObserver)
(io.honeycomb.libhoney.responses ClientRejected
ServerAccepted
ServerRejected
Unknown)))
(use-fixtures)
(deftest no-op-client-works
(testing "Default options work"
(is (instance? HoneyClient (tu/no-op-client {:data-set "data-set"
:write-key "write-key"}))))
(testing "Sending events works"
(with-open [client (tu/no-op-client {:data-set "data-set"
:write-key "write-key"})]
(honeycomb/send client {:foo "bar"})))
(testing "Random options work"
(doseq [client-options (gen/sample (s/gen :clj-honeycomb.core/client-options))]
(with-open [client (tu/no-op-client client-options)]
(honeycomb/send client {:foo "bar"})))))
(deftest recording-client-works
(testing "Default options work"
(is (instance? HoneyClient (tu/recording-client (atom []) {:data-set "data-set"
:write-key "write-key"}))))
(testing "Additional client options can be set"
(with-open [client (tu/recording-client (atom [])
{:api-host "http://127.0.0.1:123"
:data-set "foo"
:response-observer {:on-unknown (fn [_] nil)}
:sample-rate 3
:write-key "bar"})]
(is (instance? HoneyClient client))))
(testing "Randomly generated options"
(doseq [client-options (gen/sample (s/gen :clj-honeycomb.core/client-options))]
(with-open [client (tu/recording-client (atom []) client-options)]
(is (instance? HoneyClient client)))))
(testing "Global fields work"
(let [events (atom [])]
(with-open [client (tu/recording-client events
{:data-set "foo"
:global-fields (make-kitchen-sink)
:write-key "bar"})]
(is (instance? HoneyClient client))
(honeycomb/send client {:foo "bar"}))
(is (= 1 (count @events)))
(let [expected (assoc kitchen-sink-realized "foo" "bar")
event (into {} (.getFields ^Event (first @events)))]
(is (= (sort (keys expected)) (sort (keys event))))
(doseq [[k v] expected]
(is (= v (get event k)) (str k))))))
(testing "The first argument must be an atom-wrapped vector"
(with-instrument-disabled
(is (thrown? IllegalArgumentException (tu/recording-client nil {})))
(is (thrown? IllegalArgumentException (tu/recording-client (atom nil) {}))))))
(deftest recording-response-observer-works
(testing "It records only the errors"
(let [cr (reify ClientRejected)
sa (reify ServerAccepted)
sr (reify ServerRejected)
u (reify Unknown)
errors (atom [])
^ResponseObserver rro (#'tu/recording-response-observer errors)]
(.onClientRejected rro cr)
(.onServerAccepted rro sa)
(.onServerRejected rro sr)
(.onUnknown rro u)
(is (= [cr sr u] @errors))))
(testing "The first argument must be an atom-wrapped vector"
(with-instrument-disabled
(try
(#'tu/recording-response-observer nil)
(catch IllegalArgumentException e
(is e))))))
(deftest validate-events-works
(tu/validate-events
(fn []
(honeycomb/send (make-kitchen-sink)))
(fn [events errors]
(is (empty? errors))
(is (= 1 (count events)))
(is (= kitchen-sink-realized (.getFields ^Event (first events)))))))
| 104729 | (ns clj-honeycomb.testing-utils-test
(:require [clojure.spec.alpha :as s]
[clojure.spec.gen.alpha :as gen]
[clojure.spec.test.alpha :refer (with-instrument-disabled)]
[clojure.test :refer (deftest is testing)]
[clj-honeycomb.core :as honeycomb]
[clj-honeycomb.fixtures :refer (kitchen-sink-realized
make-kitchen-sink
use-fixtures)]
[clj-honeycomb.testing-utils :as tu])
(:import (io.honeycomb.libhoney Event
HoneyClient
ResponseObserver)
(io.honeycomb.libhoney.responses ClientRejected
ServerAccepted
ServerRejected
Unknown)))
(use-fixtures)
(deftest no-op-client-works
(testing "Default options work"
(is (instance? HoneyClient (tu/no-op-client {:data-set "data-set"
:write-key "write-key"}))))
(testing "Sending events works"
(with-open [client (tu/no-op-client {:data-set "data-set"
:write-key "write-key"})]
(honeycomb/send client {:foo "bar"})))
(testing "Random options work"
(doseq [client-options (gen/sample (s/gen :clj-honeycomb.core/client-options))]
(with-open [client (tu/no-op-client client-options)]
(honeycomb/send client {:foo "bar"})))))
(deftest recording-client-works
(testing "Default options work"
(is (instance? HoneyClient (tu/recording-client (atom []) {:data-set "data-set"
:write-key "write-key"}))))
(testing "Additional client options can be set"
(with-open [client (tu/recording-client (atom [])
{:api-host "http://127.0.0.1:123"
:data-set "foo"
:response-observer {:on-unknown (fn [_] nil)}
:sample-rate 3
:write-key "<KEY>"})]
(is (instance? HoneyClient client))))
(testing "Randomly generated options"
(doseq [client-options (gen/sample (s/gen :clj-honeycomb.core/client-options))]
(with-open [client (tu/recording-client (atom []) client-options)]
(is (instance? HoneyClient client)))))
(testing "Global fields work"
(let [events (atom [])]
(with-open [client (tu/recording-client events
{:data-set "foo"
:global-fields (make-kitchen-sink)
:write-key "<KEY>"})]
(is (instance? HoneyClient client))
(honeycomb/send client {:foo "bar"}))
(is (= 1 (count @events)))
(let [expected (assoc kitchen-sink-realized "foo" "bar")
event (into {} (.getFields ^Event (first @events)))]
(is (= (sort (keys expected)) (sort (keys event))))
(doseq [[k v] expected]
(is (= v (get event k)) (str k))))))
(testing "The first argument must be an atom-wrapped vector"
(with-instrument-disabled
(is (thrown? IllegalArgumentException (tu/recording-client nil {})))
(is (thrown? IllegalArgumentException (tu/recording-client (atom nil) {}))))))
(deftest recording-response-observer-works
(testing "It records only the errors"
(let [cr (reify ClientRejected)
sa (reify ServerAccepted)
sr (reify ServerRejected)
u (reify Unknown)
errors (atom [])
^ResponseObserver rro (#'tu/recording-response-observer errors)]
(.onClientRejected rro cr)
(.onServerAccepted rro sa)
(.onServerRejected rro sr)
(.onUnknown rro u)
(is (= [cr sr u] @errors))))
(testing "The first argument must be an atom-wrapped vector"
(with-instrument-disabled
(try
(#'tu/recording-response-observer nil)
(catch IllegalArgumentException e
(is e))))))
(deftest validate-events-works
(tu/validate-events
(fn []
(honeycomb/send (make-kitchen-sink)))
(fn [events errors]
(is (empty? errors))
(is (= 1 (count events)))
(is (= kitchen-sink-realized (.getFields ^Event (first events)))))))
| true | (ns clj-honeycomb.testing-utils-test
(:require [clojure.spec.alpha :as s]
[clojure.spec.gen.alpha :as gen]
[clojure.spec.test.alpha :refer (with-instrument-disabled)]
[clojure.test :refer (deftest is testing)]
[clj-honeycomb.core :as honeycomb]
[clj-honeycomb.fixtures :refer (kitchen-sink-realized
make-kitchen-sink
use-fixtures)]
[clj-honeycomb.testing-utils :as tu])
(:import (io.honeycomb.libhoney Event
HoneyClient
ResponseObserver)
(io.honeycomb.libhoney.responses ClientRejected
ServerAccepted
ServerRejected
Unknown)))
(use-fixtures)
(deftest no-op-client-works
(testing "Default options work"
(is (instance? HoneyClient (tu/no-op-client {:data-set "data-set"
:write-key "write-key"}))))
(testing "Sending events works"
(with-open [client (tu/no-op-client {:data-set "data-set"
:write-key "write-key"})]
(honeycomb/send client {:foo "bar"})))
(testing "Random options work"
(doseq [client-options (gen/sample (s/gen :clj-honeycomb.core/client-options))]
(with-open [client (tu/no-op-client client-options)]
(honeycomb/send client {:foo "bar"})))))
(deftest recording-client-works
(testing "Default options work"
(is (instance? HoneyClient (tu/recording-client (atom []) {:data-set "data-set"
:write-key "write-key"}))))
(testing "Additional client options can be set"
(with-open [client (tu/recording-client (atom [])
{:api-host "http://127.0.0.1:123"
:data-set "foo"
:response-observer {:on-unknown (fn [_] nil)}
:sample-rate 3
:write-key "PI:KEY:<KEY>END_PI"})]
(is (instance? HoneyClient client))))
(testing "Randomly generated options"
(doseq [client-options (gen/sample (s/gen :clj-honeycomb.core/client-options))]
(with-open [client (tu/recording-client (atom []) client-options)]
(is (instance? HoneyClient client)))))
(testing "Global fields work"
(let [events (atom [])]
(with-open [client (tu/recording-client events
{:data-set "foo"
:global-fields (make-kitchen-sink)
:write-key "PI:KEY:<KEY>END_PI"})]
(is (instance? HoneyClient client))
(honeycomb/send client {:foo "bar"}))
(is (= 1 (count @events)))
(let [expected (assoc kitchen-sink-realized "foo" "bar")
event (into {} (.getFields ^Event (first @events)))]
(is (= (sort (keys expected)) (sort (keys event))))
(doseq [[k v] expected]
(is (= v (get event k)) (str k))))))
(testing "The first argument must be an atom-wrapped vector"
(with-instrument-disabled
(is (thrown? IllegalArgumentException (tu/recording-client nil {})))
(is (thrown? IllegalArgumentException (tu/recording-client (atom nil) {}))))))
(deftest recording-response-observer-works
(testing "It records only the errors"
(let [cr (reify ClientRejected)
sa (reify ServerAccepted)
sr (reify ServerRejected)
u (reify Unknown)
errors (atom [])
^ResponseObserver rro (#'tu/recording-response-observer errors)]
(.onClientRejected rro cr)
(.onServerAccepted rro sa)
(.onServerRejected rro sr)
(.onUnknown rro u)
(is (= [cr sr u] @errors))))
(testing "The first argument must be an atom-wrapped vector"
(with-instrument-disabled
(try
(#'tu/recording-response-observer nil)
(catch IllegalArgumentException e
(is e))))))
(deftest validate-events-works
(tu/validate-events
(fn []
(honeycomb/send (make-kitchen-sink)))
(fn [events errors]
(is (empty? errors))
(is (= 1 (count events)))
(is (= kitchen-sink-realized (.getFields ^Event (first events)))))))
|
[
{
"context": "NS:puppet.vpn.puppetlabs.net\"]\n :fingerprint \"F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B",
"end": 2246,
"score": 0.9265917539596558,
"start": 2226,
"tag": "IP_ADDRESS",
"value": "F3:12:6C:81:AC:14:03"
},
{
"context": "bs.net\"]\n :fingerprint \"F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:B",
"end": 2249,
"score": 0.8730086088180542,
"start": 2248,
"tag": "IP_ADDRESS",
"value": "D"
},
{
"context": "net\"]\n :fingerprint \"F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1",
"end": 2252,
"score": 0.8299930095672607,
"start": 2251,
"tag": "IP_ADDRESS",
"value": "3"
},
{
"context": "\"]\n :fingerprint \"F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:0",
"end": 2255,
"score": 0.753706693649292,
"start": 2254,
"tag": "IP_ADDRESS",
"value": "7"
},
{
"context": " :fingerprint \"F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:9",
"end": 2258,
"score": 0.729862630367279,
"start": 2257,
"tag": "IP_ADDRESS",
"value": "2"
},
{
"context": ":fingerprint \"F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:C",
"end": 2261,
"score": 0.8546399474143982,
"start": 2260,
"tag": "IP_ADDRESS",
"value": "4"
},
{
"context": "ingerprint \"F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F",
"end": 2264,
"score": 0.9497044086456299,
"start": 2262,
"tag": "IP_ADDRESS",
"value": "C4"
},
{
"context": "rprint \"F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1",
"end": 2267,
"score": 0.9717229008674622,
"start": 2266,
"tag": "IP_ADDRESS",
"value": "D"
},
{
"context": "int \"F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:7",
"end": 2270,
"score": 0.8585360050201416,
"start": 2269,
"tag": "IP_ADDRESS",
"value": "1"
},
{
"context": " \"F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73\"\n",
"end": 2273,
"score": 0.753781259059906,
"start": 2272,
"tag": "IP_ADDRESS",
"value": "1"
},
{
"context": "\"F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73\"\n ",
"end": 2276,
"score": 0.6980752944946289,
"start": 2275,
"tag": "IP_ADDRESS",
"value": "5"
},
{
"context": ":12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73\"\n :fi",
"end": 2279,
"score": 0.748031735420227,
"start": 2278,
"tag": "IP_ADDRESS",
"value": "E"
},
{
"context": ":6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73\"\n :finge",
"end": 2282,
"score": 0.7360320091247559,
"start": 2281,
"tag": "IP_ADDRESS",
"value": "8"
},
{
"context": ":81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73\"\n :fingerpr",
"end": 2285,
"score": 0.6914435029029846,
"start": 2284,
"tag": "IP_ADDRESS",
"value": "7"
},
{
"context": ":AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73\"\n :fingerprint",
"end": 2288,
"score": 0.7174841165542603,
"start": 2287,
"tag": "IP_ADDRESS",
"value": "F"
},
{
"context": "4:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73\"\n :fingerprints {:S",
"end": 2294,
"score": 0.5948795080184937,
"start": 2292,
"tag": "IP_ADDRESS",
"value": "BD"
},
{
"context": ":8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73\"\n :fingerprints {:SHA1",
"end": 2297,
"score": 0.8210790753364563,
"start": 2296,
"tag": "IP_ADDRESS",
"value": "B"
},
{
"context": ":37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73\"\n :fingerprints {:SHA1 \"DB:3",
"end": 2303,
"score": 0.5917266011238098,
"start": 2302,
"tag": "IP_ADDRESS",
"value": "A"
},
{
"context": "F:1A:02:96:CE:F8:1C:73\"\n :fingerprints {:SHA1 \"DB:32:CD:AB:88:86:E0:64:0A:B7:5B:88:76:E4:60:3A:CD:9E:36:C1\"\n ",
"end": 2378,
"score": 0.9496643543243408,
"start": 2349,
"tag": "IP_ADDRESS",
"value": "DB:32:CD:AB:88:86:E0:64:0A:B7"
},
{
"context": "ngerprints {:SHA1 \"DB:32:CD:AB:88:86:E0:64:0A:B7:5B:88:76:E4:60:3A:CD:9E:36:C1\"\n :S",
"end": 2381,
"score": 0.7706059217453003,
"start": 2379,
"tag": "IP_ADDRESS",
"value": "5B"
},
{
"context": "rprints {:SHA1 \"DB:32:CD:AB:88:86:E0:64:0A:B7:5B:88:76:E4:60:3A:CD:9E:36:C1\"\n :SHA2",
"end": 2384,
"score": 0.7681088447570801,
"start": 2382,
"tag": "IP_ADDRESS",
"value": "88"
},
{
"context": "ints {:SHA1 \"DB:32:CD:AB:88:86:E0:64:0A:B7:5B:88:76:E4:60:3A:CD:9E:36:C1\"\n :SHA256 ",
"end": 2387,
"score": 0.792062520980835,
"start": 2385,
"tag": "IP_ADDRESS",
"value": "76"
},
{
"context": "s {:SHA1 \"DB:32:CD:AB:88:86:E0:64:0A:B7:5B:88:76:E4:60:3A:CD:9E:36:C1\"\n :SHA256 \"F3",
"end": 2390,
"score": 0.7827932834625244,
"start": 2388,
"tag": "IP_ADDRESS",
"value": "E4"
},
{
"context": ":SHA1 \"DB:32:CD:AB:88:86:E0:64:0A:B7:5B:88:76:E4:60:3A:CD:9E:36:C1\"\n :SHA256 \"F3:12",
"end": 2393,
"score": 0.6433404684066772,
"start": 2392,
"tag": "IP_ADDRESS",
"value": "0"
},
{
"context": "E4:60:3A:CD:9E:36:C1\"\n :SHA256 \"F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF",
"end": 2461,
"score": 0.9386953115463257,
"start": 2438,
"tag": "IP_ADDRESS",
"value": "F3:12:6C:81:AC:14:03:8D"
},
{
"context": " :SHA256 \"F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A",
"end": 2464,
"score": 0.7323108911514282,
"start": 2463,
"tag": "IP_ADDRESS",
"value": "3"
},
{
"context": " :SHA256 \"F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:0",
"end": 2467,
"score": 0.8829466104507446,
"start": 2466,
"tag": "IP_ADDRESS",
"value": "7"
},
{
"context": " :SHA256 \"F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:9",
"end": 2470,
"score": 0.8116574287414551,
"start": 2469,
"tag": "IP_ADDRESS",
"value": "2"
},
{
"context": " :SHA256 \"F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:C",
"end": 2473,
"score": 0.876227855682373,
"start": 2472,
"tag": "IP_ADDRESS",
"value": "4"
},
{
"context": " :SHA256 \"F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F",
"end": 2476,
"score": 0.6966350078582764,
"start": 2474,
"tag": "IP_ADDRESS",
"value": "C4"
},
{
"context": " :SHA256 \"F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1",
"end": 2479,
"score": 0.9163360595703125,
"start": 2478,
"tag": "IP_ADDRESS",
"value": "D"
},
{
"context": "HA256 \"F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:7",
"end": 2482,
"score": 0.8622335195541382,
"start": 2481,
"tag": "IP_ADDRESS",
"value": "1"
},
{
"context": "56 \"F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73\"\n",
"end": 2485,
"score": 0.8547623753547668,
"start": 2484,
"tag": "IP_ADDRESS",
"value": "1"
},
{
"context": "\"F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73\"\n ",
"end": 2488,
"score": 0.7969810962677002,
"start": 2487,
"tag": "IP_ADDRESS",
"value": "5"
},
{
"context": ":12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73\"\n ",
"end": 2491,
"score": 0.821097195148468,
"start": 2490,
"tag": "IP_ADDRESS",
"value": "E"
},
{
"context": ":6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73\"\n ",
"end": 2494,
"score": 0.791953980922699,
"start": 2493,
"tag": "IP_ADDRESS",
"value": "8"
},
{
"context": ":81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73\"\n ",
"end": 2497,
"score": 0.6980327367782593,
"start": 2496,
"tag": "IP_ADDRESS",
"value": "7"
},
{
"context": ":AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73\"\n ",
"end": 2500,
"score": 0.6711968183517456,
"start": 2499,
"tag": "IP_ADDRESS",
"value": "F"
},
{
"context": "4:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73\"\n :S",
"end": 2506,
"score": 0.6721050143241882,
"start": 2504,
"tag": "IP_ADDRESS",
"value": "BD"
},
{
"context": ":8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73\"\n :SHA5",
"end": 2509,
"score": 0.8255658149719238,
"start": 2508,
"tag": "IP_ADDRESS",
"value": "B"
},
{
"context": ":37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73\"\n :SHA512 \"58",
"end": 2515,
"score": 0.7595439553260803,
"start": 2514,
"tag": "IP_ADDRESS",
"value": "A"
},
{
"context": ":82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73\"\n :SHA512 \"58:22",
"end": 2518,
"score": 0.657386302947998,
"start": 2517,
"tag": "IP_ADDRESS",
"value": "2"
},
{
"context": ":E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73\"\n :SHA512 \"58:22:32",
"end": 2521,
"score": 0.5303519368171692,
"start": 2520,
"tag": "IP_ADDRESS",
"value": "6"
},
{
"context": "1A:02:96:CE:F8:1C:73\"\n :SHA512 \"58:22:32:60:CE:E7:E9:C9:CB:6A:01:52:81:ED:24:D4:69:8E:9E:CF:D8:A7:4E:6E",
"end": 2583,
"score": 0.926324725151062,
"start": 2563,
"tag": "IP_ADDRESS",
"value": "58:22:32:60:CE:E7:E9"
},
{
"context": " :SHA512 \"58:22:32:60:CE:E7:E9:C9:CB:6A:01:52:81:ED:24:D4:69:8E:9E:CF:D8:A7:4E:6E:B5",
"end": 2586,
"score": 0.7899813652038574,
"start": 2585,
"tag": "IP_ADDRESS",
"value": "9"
},
{
"context": " :SHA512 \"58:22:32:60:CE:E7:E9:C9:CB:6A:01:52:81:ED:24:D4:69:8E:9E:CF:D8:A7:4E:6E:B5:C7",
"end": 2589,
"score": 0.613784670829773,
"start": 2589,
"tag": "IP_ADDRESS",
"value": ""
},
{
"context": " :SHA512 \"58:22:32:60:CE:E7:E9:C9:CB:6A:01:52:81:ED:24:D4:69:8E:9E:CF:D8:A7:4E:6E:B5:C7:E7",
"end": 2592,
"score": 0.7268753051757812,
"start": 2591,
"tag": "IP_ADDRESS",
"value": "A"
},
{
"context": " :SHA512 \"58:22:32:60:CE:E7:E9:C9:CB:6A:01:52:81:ED:24:D4:69:8E:9E:CF:D8:A7:4E:6E:B5:C7:E7:1",
"end": 2595,
"score": 0.8730177879333496,
"start": 2594,
"tag": "IP_ADDRESS",
"value": "1"
},
{
"context": " :SHA512 \"58:22:32:60:CE:E7:E9:C9:CB:6A:01:52:81:ED:24:D4:69:8E:9E:CF:D8:A7:4E:6E:B5:C7:E7:18:5",
"end": 2598,
"score": 0.8164182305335999,
"start": 2597,
"tag": "IP_ADDRESS",
"value": "2"
},
{
"context": " :SHA512 \"58:22:32:60:CE:E7:E9:C9:CB:6A:01:52:81:ED:24:D4:69:8E:9E:CF:D8:A7:4E:6E:B5:C7:E7:18:59:5F:81",
"end": 2604,
"score": 0.6440538167953491,
"start": 2600,
"tag": "IP_ADDRESS",
"value": "1:ED"
},
{
"context": "HA512 \"58:22:32:60:CE:E7:E9:C9:CB:6A:01:52:81:ED:24:D4:69:8E:9E:CF:D8:A7:4E:6E:B5:C7:E7:18:59:5F:81:4",
"end": 2607,
"score": 0.8385813236236572,
"start": 2606,
"tag": "IP_ADDRESS",
"value": "4"
},
{
"context": "12 \"58:22:32:60:CE:E7:E9:C9:CB:6A:01:52:81:ED:24:D4:69:8E:9E:CF:D8:A7:4E:6E:B5:C7:E7:18:59:5F:81:4C:9",
"end": 2610,
"score": 0.7297072410583496,
"start": 2609,
"tag": "IP_ADDRESS",
"value": "4"
},
{
"context": "\"58:22:32:60:CE:E7:E9:C9:CB:6A:01:52:81:ED:24:D4:69:8E:9E:CF:D8:A7:4E:6E:B5:C7:E7:18:59:5F:81:4C:93:1",
"end": 2613,
"score": 0.7419313192367554,
"start": 2612,
"tag": "IP_ADDRESS",
"value": "9"
},
{
"context": ":22:32:60:CE:E7:E9:C9:CB:6A:01:52:81:ED:24:D4:69:8E:9E:CF:D8:A7:4E:6E:B5:C7:E7:18:59:5F:81:4C:93:11:7",
"end": 2616,
"score": 0.7815911173820496,
"start": 2615,
"tag": "IP_ADDRESS",
"value": "E"
},
{
"context": ":32:60:CE:E7:E9:C9:CB:6A:01:52:81:ED:24:D4:69:8E:9E:CF:D8:A7:4E:6E:B5:C7:E7:18:59:5F:81:4C:93:11:77:E",
"end": 2619,
"score": 0.7361211180686951,
"start": 2618,
"tag": "IP_ADDRESS",
"value": "E"
},
{
"context": ":CE:E7:E9:C9:CB:6A:01:52:81:ED:24:D4:69:8E:9E:CF:D8:A7:4E:6E:B5:C7:E7:18:59:5F:81:4C:93:11:77:E6:F0:4",
"end": 2625,
"score": 0.7594215869903564,
"start": 2624,
"tag": "IP_ADDRESS",
"value": "8"
},
{
"context": ":E7:E9:C9:CB:6A:01:52:81:ED:24:D4:69:8E:9E:CF:D8:A7:4E:6E:B5:C7:E7:18:59:5F:81:4C:93:11:77:E6:F0:40:7",
"end": 2628,
"score": 0.7173778414726257,
"start": 2627,
"tag": "IP_ADDRESS",
"value": "7"
},
{
"context": ":E9:C9:CB:6A:01:52:81:ED:24:D4:69:8E:9E:CF:D8:A7:4E:6E:B5:C7:E7:18:59:5F:81:4C:93:11:77:E6:F0:40:70:5",
"end": 2631,
"score": 0.7815760374069214,
"start": 2630,
"tag": "IP_ADDRESS",
"value": "E"
},
{
"context": ":C9:CB:6A:01:52:81:ED:24:D4:69:8E:9E:CF:D8:A7:4E:6E:B5:C7:E7:18:59:5F:81:4C:93:11:77:E6:F0:40:70:5B:9",
"end": 2634,
"score": 0.873053789138794,
"start": 2633,
"tag": "IP_ADDRESS",
"value": "E"
},
{
"context": ":CB:6A:01:52:81:ED:24:D4:69:8E:9E:CF:D8:A7:4E:6E:B5:C7:E7:18:59:5F:81:4C:93:11:77:E6:F0:40:70:5B:9C:9",
"end": 2637,
"score": 0.8019163012504578,
"start": 2636,
"tag": "IP_ADDRESS",
"value": "5"
},
{
"context": ":6A:01:52:81:ED:24:D4:69:8E:9E:CF:D8:A7:4E:6E:B5:C7:E7:18:59:5F:81:4C:93:11:77:E6:F0:40:70:5B:9C:9D:B",
"end": 2640,
"score": 0.7358892560005188,
"start": 2639,
"tag": "IP_ADDRESS",
"value": "7"
},
{
"context": ":01:52:81:ED:24:D4:69:8E:9E:CF:D8:A7:4E:6E:B5:C7:E7:18:59:5F:81:4C:93:11:77:E6:F0:40:70:5B:9C:9D:BE:2",
"end": 2643,
"score": 0.729799747467041,
"start": 2642,
"tag": "IP_ADDRESS",
"value": "7"
},
{
"context": ":52:81:ED:24:D4:69:8E:9E:CF:D8:A7:4E:6E:B5:C7:E7:18:59:5F:81:4C:93:11:77:E6:F0:40:70:5B:9C:9D:BE:22:A",
"end": 2646,
"score": 0.7359619736671448,
"start": 2645,
"tag": "IP_ADDRESS",
"value": "8"
},
{
"context": ":81:ED:24:D4:69:8E:9E:CF:D8:A7:4E:6E:B5:C7:E7:18:59:5F:81:4C:93:11:77:E6:F0:40:70:5B:9C:9D:BE:22:A6:6",
"end": 2649,
"score": 0.6981194615364075,
"start": 2648,
"tag": "IP_ADDRESS",
"value": "9"
},
{
"context": ":ED:24:D4:69:8E:9E:CF:D8:A7:4E:6E:B5:C7:E7:18:59:5F:81:4C:93:11:77:E6:F0:40:70:5B:9C:9D:BE:22:A6:61:0",
"end": 2652,
"score": 0.6287270188331604,
"start": 2651,
"tag": "IP_ADDRESS",
"value": "F"
},
{
"context": ":24:D4:69:8E:9E:CF:D8:A7:4E:6E:B5:C7:E7:18:59:5F:81:4C:93:11:77:E6:F0:40:70:5B:9C:9D:BE:22:A6:61:0B:F",
"end": 2655,
"score": 0.5841193795204163,
"start": 2654,
"tag": "IP_ADDRESS",
"value": "1"
},
{
"context": ":D4:69:8E:9E:CF:D8:A7:4E:6E:B5:C7:E7:18:59:5F:81:4C:93:11:77:E6:F0:40:70:5B:9C:9D:BE:22:A6:61:0B:F9:4",
"end": 2658,
"score": 0.5917567014694214,
"start": 2657,
"tag": "IP_ADDRESS",
"value": "C"
},
{
"context": ":69:8E:9E:CF:D8:A7:4E:6E:B5:C7:E7:18:59:5F:81:4C:93:11:77:E6:F0:40:70:5B:9C:9D:BE:22:A6:61:0B:F9:46:7",
"end": 2661,
"score": 0.5535773038864136,
"start": 2660,
"tag": "IP_ADDRESS",
"value": "3"
},
{
"context": "E:B5:C7:E7:18:59:5F:81:4C:93:11:77:E6:F0:40:70:5B:9C:9D:BE:22:A6:61:0B:F9:46:70:43:09:58:7E:6B:B7:5B:D9:6A:54:36:09",
"end": 2697,
"score": 0.8997061848640442,
"start": 2683,
"tag": "IP_ADDRESS",
"value": "9C:9D:BE:22:A6"
},
{
"context": ":5F:81:4C:93:11:77:E6:F0:40:70:5B:9C:9D:BE:22:A6:61:0B:F9:46:70:43:09:58:7E:6B:B7:5B:D9:6A:54:36:09:53",
"end": 2700,
"score": 0.7521557807922363,
"start": 2699,
"tag": "IP_ADDRESS",
"value": "1"
},
{
"context": ":81:4C:93:11:77:E6:F0:40:70:5B:9C:9D:BE:22:A6:61:0B:F9:46:70:43:09:58:7E:6B:B7:5B:D9:6A:54:36:09:53:F9",
"end": 2703,
"score": 0.7496377229690552,
"start": 2702,
"tag": "IP_ADDRESS",
"value": "B"
},
{
"context": ":4C:93:11:77:E6:F0:40:70:5B:9C:9D:BE:22:A6:61:0B:F9:46:70:43:09:58:7E:6B:B7:5B:D9:6A:54:36:09:53:F9\"\n",
"end": 2706,
"score": 0.9159783124923706,
"start": 2705,
"tag": "IP_ADDRESS",
"value": "9"
},
{
"context": ":93:11:77:E6:F0:40:70:5B:9C:9D:BE:22:A6:61:0B:F9:46:70:43:09:58:7E:6B:B7:5B:D9:6A:54:36:09:53:F9\"\n ",
"end": 2709,
"score": 0.815991997718811,
"start": 2708,
"tag": "IP_ADDRESS",
"value": "6"
},
{
"context": ":11:77:E6:F0:40:70:5B:9C:9D:BE:22:A6:61:0B:F9:46:70:43:09:58:7E:6B:B7:5B:D9:6A:54:36:09:53:F9\"\n ",
"end": 2712,
"score": 0.8296201825141907,
"start": 2711,
"tag": "IP_ADDRESS",
"value": "0"
},
{
"context": ":77:E6:F0:40:70:5B:9C:9D:BE:22:A6:61:0B:F9:46:70:43:09:58:7E:6B:B7:5B:D9:6A:54:36:09:53:F9\"\n ",
"end": 2715,
"score": 0.8207023739814758,
"start": 2714,
"tag": "IP_ADDRESS",
"value": "3"
},
{
"context": ":E6:F0:40:70:5B:9C:9D:BE:22:A6:61:0B:F9:46:70:43:09:58:7E:6B:B7:5B:D9:6A:54:36:09:53:F9\"\n ",
"end": 2718,
"score": 0.8016549348831177,
"start": 2717,
"tag": "IP_ADDRESS",
"value": "9"
},
{
"context": ":F0:40:70:5B:9C:9D:BE:22:A6:61:0B:F9:46:70:43:09:58:7E:6B:B7:5B:D9:6A:54:36:09:53:F9\"\n ",
"end": 2721,
"score": 0.7590936422348022,
"start": 2720,
"tag": "IP_ADDRESS",
"value": "8"
},
{
"context": ":40:70:5B:9C:9D:BE:22:A6:61:0B:F9:46:70:43:09:58:7E:6B:B7:5B:D9:6A:54:36:09:53:F9\"\n ",
"end": 2724,
"score": 0.8208986520767212,
"start": 2723,
"tag": "IP_ADDRESS",
"value": "E"
},
{
"context": ":70:5B:9C:9D:BE:22:A6:61:0B:F9:46:70:43:09:58:7E:6B:B7:5B:D9:6A:54:36:09:53:F9\"\n :d",
"end": 2727,
"score": 0.8656756281852722,
"start": 2726,
"tag": "IP_ADDRESS",
"value": "B"
},
{
"context": ":5B:9C:9D:BE:22:A6:61:0B:F9:46:70:43:09:58:7E:6B:B7:5B:D9:6A:54:36:09:53:F9\"\n :defa",
"end": 2730,
"score": 0.7355698347091675,
"start": 2729,
"tag": "IP_ADDRESS",
"value": "7"
},
{
"context": ":9C:9D:BE:22:A6:61:0B:F9:46:70:43:09:58:7E:6B:B7:5B:D9:6A:54:36:09:53:F9\"\n :default",
"end": 2733,
"score": 0.7477036118507385,
"start": 2732,
"tag": "IP_ADDRESS",
"value": "B"
},
{
"context": ":9D:BE:22:A6:61:0B:F9:46:70:43:09:58:7E:6B:B7:5B:D9:6A:54:36:09:53:F9\"\n :default \"F",
"end": 2736,
"score": 0.5376781821250916,
"start": 2735,
"tag": "IP_ADDRESS",
"value": "9"
},
{
"context": ":BE:22:A6:61:0B:F9:46:70:43:09:58:7E:6B:B7:5B:D9:6A:54:36:09:53:F9\"\n :default \"F3:1",
"end": 2739,
"score": 0.5221793055534363,
"start": 2738,
"tag": "IP_ADDRESS",
"value": "A"
},
{
"context": "9:6A:54:36:09:53:F9\"\n :default \"F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF",
"end": 2808,
"score": 0.9456477165222168,
"start": 2785,
"tag": "IP_ADDRESS",
"value": "F3:12:6C:81:AC:14:03:8D"
},
{
"context": " :default \"F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A",
"end": 2811,
"score": 0.7407820224761963,
"start": 2810,
"tag": "IP_ADDRESS",
"value": "3"
},
{
"context": " :default \"F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02",
"end": 2814,
"score": 0.7110509276390076,
"start": 2813,
"tag": "IP_ADDRESS",
"value": "7"
},
{
"context": " :default \"F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96",
"end": 2817,
"score": 0.7228401899337769,
"start": 2816,
"tag": "IP_ADDRESS",
"value": "2"
},
{
"context": " :default \"F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:C",
"end": 2820,
"score": 0.9269822239875793,
"start": 2819,
"tag": "IP_ADDRESS",
"value": "4"
},
{
"context": " :default \"F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F",
"end": 2823,
"score": 0.6863641738891602,
"start": 2821,
"tag": "IP_ADDRESS",
"value": "C4"
},
{
"context": ":default \"F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1",
"end": 2826,
"score": 0.9404260516166687,
"start": 2825,
"tag": "IP_ADDRESS",
"value": "D"
},
{
"context": "fault \"F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:7",
"end": 2829,
"score": 0.8824203610420227,
"start": 2828,
"tag": "IP_ADDRESS",
"value": "1"
},
{
"context": "lt \"F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73\"}",
"end": 2832,
"score": 0.8159617781639099,
"start": 2831,
"tag": "IP_ADDRESS",
"value": "1"
},
{
"context": "\"F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73\"}\n ",
"end": 2835,
"score": 0.7232045531272888,
"start": 2834,
"tag": "IP_ADDRESS",
"value": "5"
},
{
"context": ":12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73\"}\n :n",
"end": 2838,
"score": 0.7864213585853577,
"start": 2837,
"tag": "IP_ADDRESS",
"value": "E"
},
{
"context": ":6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73\"}\n :name",
"end": 2841,
"score": 0.7863320708274841,
"start": 2840,
"tag": "IP_ADDRESS",
"value": "8"
},
{
"context": ":81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73\"}\n :name ",
"end": 2844,
"score": 0.7590314149856567,
"start": 2843,
"tag": "IP_ADDRESS",
"value": "7"
},
{
"context": ":AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73\"}\n :name ",
"end": 2847,
"score": 0.7701836228370667,
"start": 2846,
"tag": "IP_ADDRESS",
"value": "F"
},
{
"context": ":8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73\"}\n :name \"loca",
"end": 2856,
"score": 0.7474764585494995,
"start": 2855,
"tag": "IP_ADDRESS",
"value": "B"
},
{
"context": ":37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73\"}\n :name \"localhost\"",
"end": 2862,
"score": 0.6136138439178467,
"start": 2861,
"tag": "IP_ADDRESS",
"value": "A"
},
{
"context": "nt-status\n {:dns_alt_names []\n :fingerprint \"36:94:27:47:EA:51:EE:7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59",
"end": 3029,
"score": 0.9523985385894775,
"start": 3006,
"tag": "IP_ADDRESS",
"value": "36:94:27:47:EA:51:EE:7C"
},
{
"context": "es []\n :fingerprint \"36:94:27:47:EA:51:EE:7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0",
"end": 3032,
"score": 0.7568106651306152,
"start": 3031,
"tag": "IP_ADDRESS",
"value": "3"
},
{
"context": "[]\n :fingerprint \"36:94:27:47:EA:51:EE:7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94",
"end": 3038,
"score": 0.6373134851455688,
"start": 3034,
"tag": "IP_ADDRESS",
"value": "2:EC"
},
{
"context": ":fingerprint \"36:94:27:47:EA:51:EE:7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B",
"end": 3041,
"score": 0.7328328490257263,
"start": 3040,
"tag": "IP_ADDRESS",
"value": "4"
},
{
"context": "ngerprint \"36:94:27:47:EA:51:EE:7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56",
"end": 3047,
"score": 0.6736872792243958,
"start": 3043,
"tag": "IP_ADDRESS",
"value": "4:BB"
},
{
"context": "int \"36:94:27:47:EA:51:EE:7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3",
"end": 3050,
"score": 0.7227264642715454,
"start": 3049,
"tag": "IP_ADDRESS",
"value": "5"
},
{
"context": "\"36:94:27:47:EA:51:EE:7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3\"\n ",
"end": 3056,
"score": 0.8825517892837524,
"start": 3055,
"tag": "IP_ADDRESS",
"value": "A"
},
{
"context": ":94:27:47:EA:51:EE:7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3\"\n :fi",
"end": 3059,
"score": 0.8380728960037231,
"start": 3058,
"tag": "IP_ADDRESS",
"value": "1"
},
{
"context": ":EA:51:EE:7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3\"\n :fingerprint",
"end": 3068,
"score": 0.7812581658363342,
"start": 3067,
"tag": "IP_ADDRESS",
"value": "9"
},
{
"context": ":51:EE:7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3\"\n :fingerprints ",
"end": 3071,
"score": 0.6845274567604065,
"start": 3070,
"tag": "IP_ADDRESS",
"value": "7"
},
{
"context": ":EE:7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3\"\n :fingerprints {:S",
"end": 3074,
"score": 0.7107137441635132,
"start": 3073,
"tag": "IP_ADDRESS",
"value": "9"
},
{
"context": ":7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3\"\n :fingerprints {:SHA1",
"end": 3077,
"score": 0.6778483390808105,
"start": 3076,
"tag": "IP_ADDRESS",
"value": "1"
},
{
"context": ":43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3\"\n :fingerprints {:SHA1 \"E",
"end": 3080,
"score": 0.5533716082572937,
"start": 3079,
"tag": "IP_ADDRESS",
"value": "9"
},
{
"context": "9:D0:07:94:2B:2F:56:E3\"\n :fingerprints {:SHA1 \"EB:3D:7B:9C:85:3E:56:7A:3E:9D:1B:C4:7A:21:5A:91:F5:00:4D:9D\"\n ",
"end": 3155,
"score": 0.9229881763458252,
"start": 3129,
"tag": "IP_ADDRESS",
"value": "EB:3D:7B:9C:85:3E:56:7A:3E"
},
{
"context": "fingerprints {:SHA1 \"EB:3D:7B:9C:85:3E:56:7A:3E:9D:1B:C4:7A:21:5A:91:F5:00:4D:9D\"\n ",
"end": 3158,
"score": 0.7335655689239502,
"start": 3157,
"tag": "IP_ADDRESS",
"value": "D"
},
{
"context": "gerprints {:SHA1 \"EB:3D:7B:9C:85:3E:56:7A:3E:9D:1B:C4:7A:21:5A:91:F5:00:4D:9D\"\n :S",
"end": 3161,
"score": 0.9274709820747375,
"start": 3160,
"tag": "IP_ADDRESS",
"value": "B"
},
{
"context": "prints {:SHA1 \"EB:3D:7B:9C:85:3E:56:7A:3E:9D:1B:C4:7A:21:5A:91:F5:00:4D:9D\"\n :SHA2",
"end": 3164,
"score": 0.9294902682304382,
"start": 3163,
"tag": "IP_ADDRESS",
"value": "4"
},
{
"context": "nts {:SHA1 \"EB:3D:7B:9C:85:3E:56:7A:3E:9D:1B:C4:7A:21:5A:91:F5:00:4D:9D\"\n :SHA256 ",
"end": 3167,
"score": 0.9583335518836975,
"start": 3166,
"tag": "IP_ADDRESS",
"value": "A"
},
{
"context": " {:SHA1 \"EB:3D:7B:9C:85:3E:56:7A:3E:9D:1B:C4:7A:21:5A:91:F5:00:4D:9D\"\n :SHA256 \"36",
"end": 3170,
"score": 0.8694639205932617,
"start": 3169,
"tag": "IP_ADDRESS",
"value": "1"
},
{
"context": ":SHA1 \"EB:3D:7B:9C:85:3E:56:7A:3E:9D:1B:C4:7A:21:5A:91:F5:00:4D:9D\"\n :SHA256 \"36:94",
"end": 3173,
"score": 0.9488404393196106,
"start": 3172,
"tag": "IP_ADDRESS",
"value": "A"
},
{
"context": "A1 \"EB:3D:7B:9C:85:3E:56:7A:3E:9D:1B:C4:7A:21:5A:91:F5:00:4D:9D\"\n :SHA256 \"36:94:27",
"end": 3176,
"score": 0.8509013056755066,
"start": 3175,
"tag": "IP_ADDRESS",
"value": "1"
},
{
"context": "\"EB:3D:7B:9C:85:3E:56:7A:3E:9D:1B:C4:7A:21:5A:91:F5:00:4D:9D\"\n :SHA256 \"36:94:27:47",
"end": 3179,
"score": 0.5612481832504272,
"start": 3178,
"tag": "IP_ADDRESS",
"value": "5"
},
{
"context": "21:5A:91:F5:00:4D:9D\"\n :SHA256 \"36:94:27:47:EA:51:EE:7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3\"\n ",
"end": 3265,
"score": 0.876008927822113,
"start": 3218,
"tag": "IP_ADDRESS",
"value": "36:94:27:47:EA:51:EE:7C:43:D2:EC:24:24:BB:85:CD"
},
{
"context": "\"36:94:27:47:EA:51:EE:7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3\"\n ",
"end": 3268,
"score": 0.876101016998291,
"start": 3267,
"tag": "IP_ADDRESS",
"value": "A"
},
{
"context": ":94:27:47:EA:51:EE:7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3\"\n ",
"end": 3271,
"score": 0.8338746428489685,
"start": 3270,
"tag": "IP_ADDRESS",
"value": "1"
},
{
"context": "27:47:EA:51:EE:7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3\"\n ",
"end": 3274,
"score": 0.5142042636871338,
"start": 3274,
"tag": "IP_ADDRESS",
"value": ""
},
{
"context": ":EA:51:EE:7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3\"\n ",
"end": 3280,
"score": 0.7233774065971375,
"start": 3279,
"tag": "IP_ADDRESS",
"value": "9"
},
{
"context": ":51:EE:7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3\"\n ",
"end": 3283,
"score": 0.8016225099563599,
"start": 3282,
"tag": "IP_ADDRESS",
"value": "7"
},
{
"context": ":EE:7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3\"\n :S",
"end": 3286,
"score": 0.8381696939468384,
"start": 3285,
"tag": "IP_ADDRESS",
"value": "9"
},
{
"context": ":7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3\"\n :SHA5",
"end": 3289,
"score": 0.8017560839653015,
"start": 3288,
"tag": "IP_ADDRESS",
"value": "1"
},
{
"context": ":43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3\"\n :SHA512 ",
"end": 3292,
"score": 0.865756630897522,
"start": 3291,
"tag": "IP_ADDRESS",
"value": "9"
},
{
"context": ":D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3\"\n :SHA512 \"80",
"end": 3295,
"score": 0.6570121645927429,
"start": 3294,
"tag": "IP_ADDRESS",
"value": "0"
},
{
"context": ":EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3\"\n :SHA512 \"80:C5",
"end": 3298,
"score": 0.5914708971977234,
"start": 3297,
"tag": "IP_ADDRESS",
"value": "7"
},
{
"context": "D0:07:94:2B:2F:56:E3\"\n :SHA512 \"80:C5:EE:B7:A5:FB:5E:53:7C:51:3A:A0:78:AF:CD:E3:7C:BA:B1:D6:BB:BD:61:9E:A0",
"end": 3366,
"score": 0.951118528842926,
"start": 3343,
"tag": "IP_ADDRESS",
"value": "80:C5:EE:B7:A5:FB:5E:53"
},
{
"context": " :SHA512 \"80:C5:EE:B7:A5:FB:5E:53:7C:51:3A:A0:78:AF:CD:E3:7C:BA:B1:D6:BB:BD:61:9E:A0:2E",
"end": 3369,
"score": 0.806503176689148,
"start": 3368,
"tag": "IP_ADDRESS",
"value": "C"
},
{
"context": " :SHA512 \"80:C5:EE:B7:A5:FB:5E:53:7C:51:3A:A0:78:AF:CD:E3:7C:BA:B1:D6:BB:BD:61:9E:A0:2E:D2",
"end": 3372,
"score": 0.7803775072097778,
"start": 3371,
"tag": "IP_ADDRESS",
"value": "1"
},
{
"context": " :SHA512 \"80:C5:EE:B7:A5:FB:5E:53:7C:51:3A:A0:78:AF:CD:E3:7C:BA:B1:D6:BB:BD:61:9E:A0:2E:D2:1",
"end": 3375,
"score": 0.8254698514938354,
"start": 3374,
"tag": "IP_ADDRESS",
"value": "A"
},
{
"context": " :SHA512 \"80:C5:EE:B7:A5:FB:5E:53:7C:51:3A:A0:78:AF:CD:E3:7C:BA:B1:D6:BB:BD:61:9E:A0:2E:D2:12:3",
"end": 3378,
"score": 0.8254221677780151,
"start": 3377,
"tag": "IP_ADDRESS",
"value": "0"
},
{
"context": " :SHA512 \"80:C5:EE:B7:A5:FB:5E:53:7C:51:3A:A0:78:AF:CD:E3:7C:BA:B1:D6:BB:BD:61:9E:A0:2E:D2:12:3C:D",
"end": 3381,
"score": 0.8343146443367004,
"start": 3380,
"tag": "IP_ADDRESS",
"value": "8"
},
{
"context": "12 \"80:C5:EE:B7:A5:FB:5E:53:7C:51:3A:A0:78:AF:CD:E3:7C:BA:B1:D6:BB:BD:61:9E:A0:2E:D2:12:3C:D8:6E:8D:8",
"end": 3390,
"score": 0.6572940349578857,
"start": 3389,
"tag": "IP_ADDRESS",
"value": "3"
},
{
"context": "\"80:C5:EE:B7:A5:FB:5E:53:7C:51:3A:A0:78:AF:CD:E3:7C:BA:B1:D6:BB:BD:61:9E:A0:2E:D2:12:3C:D8:6E:8D:86:7",
"end": 3393,
"score": 0.6643899083137512,
"start": 3392,
"tag": "IP_ADDRESS",
"value": "C"
},
{
"context": ":EE:B7:A5:FB:5E:53:7C:51:3A:A0:78:AF:CD:E3:7C:BA:B1:D6:BB:BD:61:9E:A0:2E:D2:12:3C:D8:6E:8D:86:7C:FC:FB:4C:6B:1D:15:63:02:19:D2:F8:49:7D",
"end": 3432,
"score": 0.7466155886650085,
"start": 3398,
"tag": "IP_ADDRESS",
"value": "1:D6:BB:BD:61:9E:A0:2E:D2:12:3C:D8"
},
{
"context": ":CD:E3:7C:BA:B1:D6:BB:BD:61:9E:A0:2E:D2:12:3C:D8:6E:8D:86:7C:FC:FB:4C:6B:1D:15:63:02:19:D2:F8:49:7D:1A:11:78",
"end": 3441,
"score": 0.6499490737915039,
"start": 3434,
"tag": "IP_ADDRESS",
"value": "E:8D:86"
},
{
"context": ":BA:B1:D6:BB:BD:61:9E:A0:2E:D2:12:3C:D8:6E:8D:86:7C:FC:FB:4C:6B:1D:15:63:02:19:D2:F8:49:7D:1A:11:78:07:31:23",
"end": 3450,
"score": 0.6429325938224792,
"start": 3443,
"tag": "IP_ADDRESS",
"value": "C:FC:FB"
},
{
"context": ":BB:BD:61:9E:A0:2E:D2:12:3C:D8:6E:8D:86:7C:FC:FB:4C:6B:1D:15:63:02:19:D2:F8:49:7D:1A:11:78:07:31:23:2",
"end": 3453,
"score": 0.9111552238464355,
"start": 3452,
"tag": "IP_ADDRESS",
"value": "C"
},
{
"context": ":BD:61:9E:A0:2E:D2:12:3C:D8:6E:8D:86:7C:FC:FB:4C:6B:1D:15:63:02:19:D2:F8:49:7D:1A:11:78:07:31:23:22:3",
"end": 3456,
"score": 0.8947482109069824,
"start": 3455,
"tag": "IP_ADDRESS",
"value": "B"
},
{
"context": ":61:9E:A0:2E:D2:12:3C:D8:6E:8D:86:7C:FC:FB:4C:6B:1D:15:63:02:19:D2:F8:49:7D:1A:11:78:07:31:23:22:36:6",
"end": 3459,
"score": 0.8948002457618713,
"start": 3458,
"tag": "IP_ADDRESS",
"value": "D"
},
{
"context": ":9E:A0:2E:D2:12:3C:D8:6E:8D:86:7C:FC:FB:4C:6B:1D:15:63:02:19:D2:F8:49:7D:1A:11:78:07:31:23:22:36:61:0",
"end": 3462,
"score": 0.8857311606407166,
"start": 3461,
"tag": "IP_ADDRESS",
"value": "5"
},
{
"context": ":A0:2E:D2:12:3C:D8:6E:8D:86:7C:FC:FB:4C:6B:1D:15:63:02:19:D2:F8:49:7D:1A:11:78:07:31:23:22:36:61:0C:D",
"end": 3465,
"score": 0.8690565824508667,
"start": 3464,
"tag": "IP_ADDRESS",
"value": "3"
},
{
"context": ":2E:D2:12:3C:D8:6E:8D:86:7C:FC:FB:4C:6B:1D:15:63:02:19:D2:F8:49:7D:1A:11:78:07:31:23:22:36:61:0C:D8:E",
"end": 3468,
"score": 0.8338849544525146,
"start": 3467,
"tag": "IP_ADDRESS",
"value": "2"
},
{
"context": ":D2:12:3C:D8:6E:8D:86:7C:FC:FB:4C:6B:1D:15:63:02:19:D2:F8:49:7D:1A:11:78:07:31:23:22:36:61:0C:D8:E9:F",
"end": 3471,
"score": 0.8251075744628906,
"start": 3470,
"tag": "IP_ADDRESS",
"value": "9"
},
{
"context": ":12:3C:D8:6E:8D:86:7C:FC:FB:4C:6B:1D:15:63:02:19:D2:F8:49:7D:1A:11:78:07:31:23:22:36:61:0C:D8:E9:F4:9",
"end": 3474,
"score": 0.8250061869621277,
"start": 3473,
"tag": "IP_ADDRESS",
"value": "2"
},
{
"context": ":3C:D8:6E:8D:86:7C:FC:FB:4C:6B:1D:15:63:02:19:D2:F8:49:7D:1A:11:78:07:31:23:22:36:61:0C:D8:E9:F4:97:0",
"end": 3477,
"score": 0.8689791560173035,
"start": 3476,
"tag": "IP_ADDRESS",
"value": "8"
},
{
"context": ":D8:6E:8D:86:7C:FC:FB:4C:6B:1D:15:63:02:19:D2:F8:49:7D:1A:11:78:07:31:23:22:36:61:0C:D8:E9:F4:97:0B:6",
"end": 3480,
"score": 0.8655032515525818,
"start": 3479,
"tag": "IP_ADDRESS",
"value": "9"
},
{
"context": ":6E:8D:86:7C:FC:FB:4C:6B:1D:15:63:02:19:D2:F8:49:7D:1A:11:78:07:31:23:22:36:61:0C:D8:E9:F4:97:0B:67:4",
"end": 3483,
"score": 0.8949581980705261,
"start": 3482,
"tag": "IP_ADDRESS",
"value": "D"
},
{
"context": ":8D:86:7C:FC:FB:4C:6B:1D:15:63:02:19:D2:F8:49:7D:1A:11:78:07:31:23:22:36:61:0C:D8:E9:F4:97:0B:67:47\"\n",
"end": 3486,
"score": 0.9004769325256348,
"start": 3485,
"tag": "IP_ADDRESS",
"value": "A"
},
{
"context": ":86:7C:FC:FB:4C:6B:1D:15:63:02:19:D2:F8:49:7D:1A:11:78:07:31:23:22:36:61:0C:D8:E9:F4:97:0B:67:47\"\n ",
"end": 3489,
"score": 0.9032245874404907,
"start": 3488,
"tag": "IP_ADDRESS",
"value": "1"
},
{
"context": ":7C:FC:FB:4C:6B:1D:15:63:02:19:D2:F8:49:7D:1A:11:78:07:31:23:22:36:61:0C:D8:E9:F4:97:0B:67:47\"\n ",
"end": 3492,
"score": 0.9184216260910034,
"start": 3491,
"tag": "IP_ADDRESS",
"value": "8"
},
{
"context": ":FC:FB:4C:6B:1D:15:63:02:19:D2:F8:49:7D:1A:11:78:07:31:23:22:36:61:0C:D8:E9:F4:97:0B:67:47\"\n ",
"end": 3495,
"score": 0.8918354511260986,
"start": 3494,
"tag": "IP_ADDRESS",
"value": "7"
},
{
"context": ":FB:4C:6B:1D:15:63:02:19:D2:F8:49:7D:1A:11:78:07:31:23:22:36:61:0C:D8:E9:F4:97:0B:67:47\"\n ",
"end": 3498,
"score": 0.8793752789497375,
"start": 3497,
"tag": "IP_ADDRESS",
"value": "1"
},
{
"context": ":4C:6B:1D:15:63:02:19:D2:F8:49:7D:1A:11:78:07:31:23:22:36:61:0C:D8:E9:F4:97:0B:67:47\"\n ",
"end": 3501,
"score": 0.8655478954315186,
"start": 3500,
"tag": "IP_ADDRESS",
"value": "3"
},
{
"context": ":6B:1D:15:63:02:19:D2:F8:49:7D:1A:11:78:07:31:23:22:36:61:0C:D8:E9:F4:97:0B:67:47\"\n ",
"end": 3504,
"score": 0.8422945141792297,
"start": 3503,
"tag": "IP_ADDRESS",
"value": "2"
},
{
"context": ":1D:15:63:02:19:D2:F8:49:7D:1A:11:78:07:31:23:22:36:61:0C:D8:E9:F4:97:0B:67:47\"\n :d",
"end": 3507,
"score": 0.8581903576850891,
"start": 3506,
"tag": "IP_ADDRESS",
"value": "6"
},
{
"context": ":15:63:02:19:D2:F8:49:7D:1A:11:78:07:31:23:22:36:61:0C:D8:E9:F4:97:0B:67:47\"\n :defa",
"end": 3510,
"score": 0.8581140637397766,
"start": 3509,
"tag": "IP_ADDRESS",
"value": "1"
},
{
"context": ":63:02:19:D2:F8:49:7D:1A:11:78:07:31:23:22:36:61:0C:D8:E9:F4:97:0B:67:47\"\n :default",
"end": 3513,
"score": 0.8544674515724182,
"start": 3512,
"tag": "IP_ADDRESS",
"value": "C"
},
{
"context": ":02:19:D2:F8:49:7D:1A:11:78:07:31:23:22:36:61:0C:D8:E9:F4:97:0B:67:47\"\n :default \"3",
"end": 3516,
"score": 0.6497786641120911,
"start": 3515,
"tag": "IP_ADDRESS",
"value": "8"
},
{
"context": "8:E9:F4:97:0B:67:47\"\n :default \"36:94:27:47:EA:51:EE:7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59",
"end": 3588,
"score": 0.9531524777412415,
"start": 3565,
"tag": "IP_ADDRESS",
"value": "36:94:27:47:EA:51:EE:7C"
},
{
"context": " :default \"36:94:27:47:EA:51:EE:7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94",
"end": 3597,
"score": 0.6844204068183899,
"start": 3590,
"tag": "IP_ADDRESS",
"value": "3:D2:EC"
},
{
"context": " :default \"36:94:27:47:EA:51:EE:7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3\"}\n",
"end": 3612,
"score": 0.7344794273376465,
"start": 3599,
"tag": "IP_ADDRESS",
"value": "4:24:BB:85:CD"
},
{
"context": "\"36:94:27:47:EA:51:EE:7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3\"}\n ",
"end": 3615,
"score": 0.718837559223175,
"start": 3614,
"tag": "IP_ADDRESS",
"value": "A"
},
{
"context": ":94:27:47:EA:51:EE:7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3\"}\n :name ",
"end": 3624,
"score": 0.6641973257064819,
"start": 3617,
"tag": "IP_ADDRESS",
"value": "1:FB:BB"
},
{
"context": ":EA:51:EE:7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3\"}\n :name ",
"end": 3627,
"score": 0.8544429540634155,
"start": 3626,
"tag": "IP_ADDRESS",
"value": "9"
},
{
"context": ":51:EE:7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3\"}\n :name ",
"end": 3630,
"score": 0.7703008055686951,
"start": 3629,
"tag": "IP_ADDRESS",
"value": "7"
},
{
"context": ":EE:7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3\"}\n :name \"t",
"end": 3633,
"score": 0.7532644867897034,
"start": 3632,
"tag": "IP_ADDRESS",
"value": "9"
},
{
"context": ":7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3\"}\n :name \"test",
"end": 3636,
"score": 0.8016340136528015,
"start": 3635,
"tag": "IP_ADDRESS",
"value": "1"
},
{
"context": ":43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3\"}\n :name \"test-ag",
"end": 3639,
"score": 0.6978910565376282,
"start": 3638,
"tag": "IP_ADDRESS",
"value": "9"
},
{
"context": ":D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3\"}\n :name \"test-agent",
"end": 3642,
"score": 0.5299163460731506,
"start": 3641,
"tag": "IP_ADDRESS",
"value": "0"
},
{
"context": ":59:D0:07:94:2B:2F:56:E3\"}\n :name \"test-agent\"\n :state \"requested\"})\n\n(def revoked-ag",
"end": 3692,
"score": 0.5855058431625366,
"start": 3687,
"tag": "USERNAME",
"value": "agent"
},
{
"context": " \"DNS:revoked-agent\"]\n :fingerprint \"1C:D0:29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66",
"end": 3929,
"score": 0.8696659207344055,
"start": 3900,
"tag": "IP_ADDRESS",
"value": "1C:D0:29:04:9B:49:F5:ED:AB:E9"
},
{
"context": " :fingerprint \"1C:D0:29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E",
"end": 3935,
"score": 0.6230885982513428,
"start": 3931,
"tag": "IP_ADDRESS",
"value": "5:CC"
},
{
"context": "ngerprint \"1C:D0:29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4",
"end": 3938,
"score": 0.7644456624984741,
"start": 3937,
"tag": "IP_ADDRESS",
"value": "9"
},
{
"context": "rprint \"1C:D0:29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6",
"end": 3941,
"score": 0.9332866072654724,
"start": 3940,
"tag": "IP_ADDRESS",
"value": "F"
},
{
"context": "int \"1C:D0:29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:9",
"end": 3944,
"score": 0.8889957666397095,
"start": 3943,
"tag": "IP_ADDRESS",
"value": "0"
},
{
"context": " \"1C:D0:29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95\"\n",
"end": 3947,
"score": 0.9007263779640198,
"start": 3946,
"tag": "IP_ADDRESS",
"value": "1"
},
{
"context": "\"1C:D0:29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95\"\n ",
"end": 3950,
"score": 0.8658075332641602,
"start": 3949,
"tag": "IP_ADDRESS",
"value": "F"
},
{
"context": ":D0:29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95\"\n :fi",
"end": 3953,
"score": 0.8208604454994202,
"start": 3952,
"tag": "IP_ADDRESS",
"value": "4"
},
{
"context": ":29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95\"\n :finge",
"end": 3956,
"score": 0.8253841400146484,
"start": 3955,
"tag": "IP_ADDRESS",
"value": "6"
},
{
"context": ":04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95\"\n :fingerpr",
"end": 3959,
"score": 0.8506693840026855,
"start": 3958,
"tag": "IP_ADDRESS",
"value": "A"
},
{
"context": ":9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95\"\n :fingerprint",
"end": 3962,
"score": 0.8657864332199097,
"start": 3961,
"tag": "IP_ADDRESS",
"value": "D"
},
{
"context": ":49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95\"\n :fingerprints ",
"end": 3965,
"score": 0.8299511671066284,
"start": 3964,
"tag": "IP_ADDRESS",
"value": "7"
},
{
"context": ":F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95\"\n :fingerprints {:S",
"end": 3968,
"score": 0.7593845129013062,
"start": 3967,
"tag": "IP_ADDRESS",
"value": "9"
},
{
"context": "D:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95\"\n :fingerprints {:SHA1 \"3",
"end": 3974,
"score": 0.6758909225463867,
"start": 3972,
"tag": "IP_ADDRESS",
"value": "EA"
},
{
"context": ":E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95\"\n :fingerprints {:SHA1 \"38:5",
"end": 3977,
"score": 0.5915533304214478,
"start": 3976,
"tag": "IP_ADDRESS",
"value": "4"
},
{
"context": "A:24:66:C6:6E:D4:6D:95\"\n :fingerprints {:SHA1 \"38:56:67:FF:20:91:0E:85:C4:DF:CA:16:77:60:D2:BB:FB:DF:68:BB\"\n :SHA25",
"end": 4058,
"score": 0.9240233898162842,
"start": 4023,
"tag": "IP_ADDRESS",
"value": "38:56:67:FF:20:91:0E:85:C4:DF:CA:16"
},
{
"context": "nts {:SHA1 \"38:56:67:FF:20:91:0E:85:C4:DF:CA:16:77:60:D2:BB:FB:DF:68:BB\"\n :SHA256 ",
"end": 4061,
"score": 0.9471563100814819,
"start": 4060,
"tag": "IP_ADDRESS",
"value": "7"
},
{
"context": " {:SHA1 \"38:56:67:FF:20:91:0E:85:C4:DF:CA:16:77:60:D2:BB:FB:DF:68:BB\"\n :SHA256 \"1C:D0:29:04",
"end": 4073,
"score": 0.7167432904243469,
"start": 4063,
"tag": "IP_ADDRESS",
"value": "0:D2:BB:FB"
},
{
"context": "8:56:67:FF:20:91:0E:85:C4:DF:CA:16:77:60:D2:BB:FB:DF:68:BB\"\n :SHA256 \"1C:D0:29:04:9B",
"end": 4076,
"score": 0.5287350416183472,
"start": 4074,
"tag": "IP_ADDRESS",
"value": "DF"
},
{
"context": "60:D2:BB:FB:DF:68:BB\"\n :SHA256 \"1C:D0:29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6",
"end": 4144,
"score": 0.9271106719970703,
"start": 4112,
"tag": "IP_ADDRESS",
"value": "1C:D0:29:04:9B:49:F5:ED:AB:E9:85"
},
{
"context": " :SHA256 \"1C:D0:29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E",
"end": 4147,
"score": 0.576094388961792,
"start": 4147,
"tag": "IP_ADDRESS",
"value": ""
},
{
"context": " :SHA256 \"1C:D0:29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4",
"end": 4150,
"score": 0.6804808378219604,
"start": 4149,
"tag": "IP_ADDRESS",
"value": "9"
},
{
"context": " :SHA256 \"1C:D0:29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6",
"end": 4153,
"score": 0.8763447403907776,
"start": 4152,
"tag": "IP_ADDRESS",
"value": "F"
},
{
"context": "HA256 \"1C:D0:29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:9",
"end": 4156,
"score": 0.7760066986083984,
"start": 4155,
"tag": "IP_ADDRESS",
"value": "0"
},
{
"context": "56 \"1C:D0:29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95\"\n",
"end": 4159,
"score": 0.7969694137573242,
"start": 4158,
"tag": "IP_ADDRESS",
"value": "1"
},
{
"context": "\"1C:D0:29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95\"\n ",
"end": 4162,
"score": 0.8585821390151978,
"start": 4161,
"tag": "IP_ADDRESS",
"value": "F"
},
{
"context": ":D0:29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95\"\n ",
"end": 4165,
"score": 0.664247453212738,
"start": 4164,
"tag": "IP_ADDRESS",
"value": "4"
},
{
"context": "B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95\"\n :SHA512 \"1A",
"end": 4189,
"score": 0.8637256026268005,
"start": 4175,
"tag": "IP_ADDRESS",
"value": "37:19:ED:EA:24"
},
{
"context": ":85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95\"\n :SHA512 \"1A:E3",
"end": 4192,
"score": 0.6643654704093933,
"start": 4191,
"tag": "IP_ADDRESS",
"value": "6"
},
{
"context": "24:66:C6:6E:D4:6D:95\"\n :SHA512 \"1A:E3:12:14:81:50:38:19:3C:C6:42:4B:BB:09:16:0C:B1:8A:3C:EB:8C:64:9C:88:46:C6:7E",
"end": 4266,
"score": 0.9064966440200806,
"start": 4237,
"tag": "IP_ADDRESS",
"value": "1A:E3:12:14:81:50:38:19:3C:C6"
},
{
"context": " :SHA512 \"1A:E3:12:14:81:50:38:19:3C:C6:42:4B:BB:09:16:0C:B1:8A:3C:EB:8C:64:9C:88:46:C6:7E:35:5E:11:0C",
"end": 4278,
"score": 0.7867520451545715,
"start": 4268,
"tag": "IP_ADDRESS",
"value": "2:4B:BB:09"
},
{
"context": "HA512 \"1A:E3:12:14:81:50:38:19:3C:C6:42:4B:BB:09:16:0C:B1:8A:3C:EB:8C:64:9C:88:46:C6:7E:35:5E:11:0C:7A",
"end": 4281,
"score": 0.7528616189956665,
"start": 4280,
"tag": "IP_ADDRESS",
"value": "6"
},
{
"context": "12 \"1A:E3:12:14:81:50:38:19:3C:C6:42:4B:BB:09:16:0C:B1:8A:3C:EB:8C:64:9C:88:46:C6:7E:35:5E:11:0C:7A:CC:B2:47",
"end": 4290,
"score": 0.7128933668136597,
"start": 4283,
"tag": "IP_ADDRESS",
"value": "C:B1:8A"
},
{
"context": ":12:14:81:50:38:19:3C:C6:42:4B:BB:09:16:0C:B1:8A:3C:EB:8C:64:9C:88:46:C6:7E:35:5E:11:0C:7A:CC:B2:47:A2:EB:57:63:5C:48:68:22:57:62",
"end": 4320,
"score": 0.6913174390792847,
"start": 4292,
"tag": "IP_ADDRESS",
"value": "C:EB:8C:64:9C:88:46:C6:7E:35"
},
{
"context": ":BB:09:16:0C:B1:8A:3C:EB:8C:64:9C:88:46:C6:7E:35:5E:11:0C:7A:CC:B2:47:A2:EB:57:63:5C:48:68:22:57:62:A",
"end": 4323,
"score": 0.918363094329834,
"start": 4322,
"tag": "IP_ADDRESS",
"value": "E"
},
{
"context": ":09:16:0C:B1:8A:3C:EB:8C:64:9C:88:46:C6:7E:35:5E:11:0C:7A:CC:B2:47:A2:EB:57:63:5C:48:68:22:57:62:A1:4",
"end": 4326,
"score": 0.9085708260536194,
"start": 4325,
"tag": "IP_ADDRESS",
"value": "1"
},
{
"context": ":16:0C:B1:8A:3C:EB:8C:64:9C:88:46:C6:7E:35:5E:11:0C:7A:CC:B2:47:A2:EB:57:63:5C:48:68:22:57:62:A1:46:6",
"end": 4329,
"score": 0.9272693395614624,
"start": 4328,
"tag": "IP_ADDRESS",
"value": "C"
},
{
"context": ":0C:B1:8A:3C:EB:8C:64:9C:88:46:C6:7E:35:5E:11:0C:7A:CC:B2:47:A2:EB:57:63:5C:48:68:22:57:62:A1:46:64:B4:56:2",
"end": 4338,
"score": 0.6693810820579529,
"start": 4331,
"tag": "IP_ADDRESS",
"value": "A:CC:B2"
},
{
"context": ":3C:EB:8C:64:9C:88:46:C6:7E:35:5E:11:0C:7A:CC:B2:47:A2:EB:57:63:5C:48:68:22:57:62:A1:46:64:B4:56:29:4",
"end": 4341,
"score": 0.8918885588645935,
"start": 4340,
"tag": "IP_ADDRESS",
"value": "7"
},
{
"context": ":EB:8C:64:9C:88:46:C6:7E:35:5E:11:0C:7A:CC:B2:47:A2:EB:57:63:5C:48:68:22:57:62:A1:46:64:B4:56:29:47:A5:4",
"end": 4347,
"score": 0.6625815629959106,
"start": 4343,
"tag": "IP_ADDRESS",
"value": "2:EB"
},
{
"context": ":64:9C:88:46:C6:7E:35:5E:11:0C:7A:CC:B2:47:A2:EB:57:63:5C:48:68:22:57:62:A1:46:64:B4:56:29:47:A5:46:F",
"end": 4350,
"score": 0.9005234241485596,
"start": 4349,
"tag": "IP_ADDRESS",
"value": "7"
},
{
"context": ":9C:88:46:C6:7E:35:5E:11:0C:7A:CC:B2:47:A2:EB:57:63:5C:48:68:22:57:62:A1:46:64:B4:56:29:47:A5:46:F4:B",
"end": 4353,
"score": 0.8949205875396729,
"start": 4352,
"tag": "IP_ADDRESS",
"value": "3"
},
{
"context": ":88:46:C6:7E:35:5E:11:0C:7A:CC:B2:47:A2:EB:57:63:5C:48:68:22:57:62:A1:46:64:B4:56:29:47:A5:46:F4:BD:9",
"end": 4356,
"score": 0.8794625997543335,
"start": 4355,
"tag": "IP_ADDRESS",
"value": "C"
},
{
"context": ":46:C6:7E:35:5E:11:0C:7A:CC:B2:47:A2:EB:57:63:5C:48:68:22:57:62:A1:46:64:B4:56:29:47:A5:46:F4:BD:9B:4",
"end": 4359,
"score": 0.8655769228935242,
"start": 4358,
"tag": "IP_ADDRESS",
"value": "8"
},
{
"context": ":C6:7E:35:5E:11:0C:7A:CC:B2:47:A2:EB:57:63:5C:48:68:22:57:62:A1:46:64:B4:56:29:47:A5:46:F4:BD:9B:45:7",
"end": 4362,
"score": 0.8761062622070312,
"start": 4361,
"tag": "IP_ADDRESS",
"value": "8"
},
{
"context": ":7E:35:5E:11:0C:7A:CC:B2:47:A2:EB:57:63:5C:48:68:22:57:62:A1:46:64:B4:56:29:47:A5:46:F4:BD:9B:45:77:1",
"end": 4365,
"score": 0.8793717622756958,
"start": 4364,
"tag": "IP_ADDRESS",
"value": "2"
},
{
"context": ":35:5E:11:0C:7A:CC:B2:47:A2:EB:57:63:5C:48:68:22:57:62:A1:46:64:B4:56:29:47:A5:46:F4:BD:9B:45:77:19:9",
"end": 4368,
"score": 0.8977487683296204,
"start": 4367,
"tag": "IP_ADDRESS",
"value": "7"
},
{
"context": ":5E:11:0C:7A:CC:B2:47:A2:EB:57:63:5C:48:68:22:57:62:A1:46:64:B4:56:29:47:A5:46:F4:BD:9B:45:77:19:91:0",
"end": 4371,
"score": 0.9136384725570679,
"start": 4370,
"tag": "IP_ADDRESS",
"value": "2"
},
{
"context": "E:11:0C:7A:CC:B2:47:A2:EB:57:63:5C:48:68:22:57:62:A1:46:64:B4:56:29:47:A5:46:F4:BD:9B:45:77:19:91:0B:3",
"end": 4374,
"score": 0.7108091115951538,
"start": 4372,
"tag": "IP_ADDRESS",
"value": "A1"
},
{
"context": ":0C:7A:CC:B2:47:A2:EB:57:63:5C:48:68:22:57:62:A1:46:64:B4:56:29:47:A5:46:F4:BD:9B:45:77:19:91:0B:35:3",
"end": 4377,
"score": 0.87937331199646,
"start": 4376,
"tag": "IP_ADDRESS",
"value": "6"
},
{
"context": ":7A:CC:B2:47:A2:EB:57:63:5C:48:68:22:57:62:A1:46:64:B4:56:29:47:A5:46:F4:BD:9B:45:77:19:91:0B:35:39\"\n",
"end": 4380,
"score": 0.8691405653953552,
"start": 4379,
"tag": "IP_ADDRESS",
"value": "4"
},
{
"context": "A:CC:B2:47:A2:EB:57:63:5C:48:68:22:57:62:A1:46:64:B4:56:29:47:A5:46:F4:BD:9B:45:77:19:91:0B:35:39\"\n ",
"end": 4383,
"score": 0.6893209218978882,
"start": 4381,
"tag": "IP_ADDRESS",
"value": "B4"
},
{
"context": ":B2:47:A2:EB:57:63:5C:48:68:22:57:62:A1:46:64:B4:56:29:47:A5:46:F4:BD:9B:45:77:19:91:0B:35:39\"\n ",
"end": 4386,
"score": 0.8617921471595764,
"start": 4385,
"tag": "IP_ADDRESS",
"value": "6"
},
{
"context": ":47:A2:EB:57:63:5C:48:68:22:57:62:A1:46:64:B4:56:29:47:A5:46:F4:BD:9B:45:77:19:91:0B:35:39\"\n ",
"end": 4389,
"score": 0.8618683218955994,
"start": 4388,
"tag": "IP_ADDRESS",
"value": "9"
},
{
"context": ":A2:EB:57:63:5C:48:68:22:57:62:A1:46:64:B4:56:29:47:A5:46:F4:BD:9B:45:77:19:91:0B:35:39\"\n ",
"end": 4392,
"score": 0.8655758500099182,
"start": 4391,
"tag": "IP_ADDRESS",
"value": "7"
},
{
"context": "2:EB:57:63:5C:48:68:22:57:62:A1:46:64:B4:56:29:47:A5:46:F4:BD:9B:45:77:19:91:0B:35:39\"\n ",
"end": 4395,
"score": 0.6631614565849304,
"start": 4393,
"tag": "IP_ADDRESS",
"value": "A5"
},
{
"context": ":57:63:5C:48:68:22:57:62:A1:46:64:B4:56:29:47:A5:46:F4:BD:9B:45:77:19:91:0B:35:39\"\n ",
"end": 4398,
"score": 0.8726646304130554,
"start": 4397,
"tag": "IP_ADDRESS",
"value": "6"
},
{
"context": ":63:5C:48:68:22:57:62:A1:46:64:B4:56:29:47:A5:46:F4:BD:9B:45:77:19:91:0B:35:39\"\n :d",
"end": 4401,
"score": 0.915934681892395,
"start": 4400,
"tag": "IP_ADDRESS",
"value": "4"
},
{
"context": "3:5C:48:68:22:57:62:A1:46:64:B4:56:29:47:A5:46:F4:BD:9B:45:77:19:91:0B:35:39\"\n :defa",
"end": 4404,
"score": 0.724882185459137,
"start": 4402,
"tag": "IP_ADDRESS",
"value": "BD"
},
{
"context": "C:48:68:22:57:62:A1:46:64:B4:56:29:47:A5:46:F4:BD:9B:45:77:19:91:0B:35:39\"\n :default",
"end": 4407,
"score": 0.6958277821540833,
"start": 4405,
"tag": "IP_ADDRESS",
"value": "9B"
},
{
"context": ":68:22:57:62:A1:46:64:B4:56:29:47:A5:46:F4:BD:9B:45:77:19:91:0B:35:39\"\n :default \"1",
"end": 4410,
"score": 0.650057315826416,
"start": 4409,
"tag": "IP_ADDRESS",
"value": "5"
},
{
"context": "5:77:19:91:0B:35:39\"\n :default \"1C:D0:29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:9",
"end": 4503,
"score": 0.8534083366394043,
"start": 4459,
"tag": "IP_ADDRESS",
"value": "1C:D0:29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20"
},
{
"context": "ult \"1C:D0:29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95\"}",
"end": 4506,
"score": 0.7583999633789062,
"start": 4504,
"tag": "IP_ADDRESS",
"value": "E1"
},
{
"context": " \"1C:D0:29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95\"}\n ",
"end": 4509,
"score": 0.6989583373069763,
"start": 4507,
"tag": "IP_ADDRESS",
"value": "7F"
},
{
"context": "C:D0:29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95\"}\n :n",
"end": 4512,
"score": 0.7090640664100647,
"start": 4510,
"tag": "IP_ADDRESS",
"value": "84"
},
{
"context": ":29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95\"}\n :name",
"end": 4515,
"score": 0.8891065716743469,
"start": 4514,
"tag": "IP_ADDRESS",
"value": "6"
},
{
"context": "9:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95\"}\n :name ",
"end": 4518,
"score": 0.7020504474639893,
"start": 4516,
"tag": "IP_ADDRESS",
"value": "8A"
},
{
"context": ":9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95\"}\n :name ",
"end": 4521,
"score": 0.9606965184211731,
"start": 4520,
"tag": "IP_ADDRESS",
"value": "D"
},
{
"context": ":49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95\"}\n :name ",
"end": 4524,
"score": 0.918630063533783,
"start": 4523,
"tag": "IP_ADDRESS",
"value": "7"
},
{
"context": ":F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95\"}\n :name \"r",
"end": 4527,
"score": 0.8622762560844421,
"start": 4526,
"tag": "IP_ADDRESS",
"value": "9"
},
{
"context": "5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95\"}\n :name \"revo",
"end": 4530,
"score": 0.5023766756057739,
"start": 4528,
"tag": "IP_ADDRESS",
"value": "ED"
},
{
"context": "D:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95\"}\n :name \"revoked",
"end": 4533,
"score": 0.6629870533943176,
"start": 4531,
"tag": "IP_ADDRESS",
"value": "EA"
},
{
"context": "build-ring-handler (testutils/ca-settings cadir) \"42.42.42\")\n (wrap-with-ssl-client-ce",
"end": 12983,
"score": 0.9996802806854248,
"start": 12975,
"tag": "IP_ADDRESS",
"value": "42.42.42"
},
{
"context": " test-app (-> (build-ring-handler settings \"42.42.42\")\n (wrap-with-ssl-client-ce",
"end": 17431,
"score": 0.9997094869613647,
"start": 17423,
"tag": "IP_ADDRESS",
"value": "42.42.42"
},
{
"context": " test-app (-> (build-ring-handler settings \"42.42.42\")\n (wrap-with-ssl-cli",
"end": 20643,
"score": 0.8840528130531311,
"start": 20636,
"tag": "IP_ADDRESS",
"value": "2.42.42"
},
{
"context": "est-app (-> (build-ring-handler settings \"42.42.42\")\n (wrap-with-ssl-c",
"end": 23881,
"score": 0.9996007680892944,
"start": 23873,
"tag": "IP_ADDRESS",
"value": "42.42.42"
},
{
"context": " test-app (-> (build-ring-handler settings \"42.42.42\")\n (wrap-with-ssl-client-cert",
"end": 24683,
"score": 0.9996321201324463,
"start": 24675,
"tag": "IP_ADDRESS",
"value": "42.42.42"
},
{
"context": "est-app (-> (build-ring-handler settings \"42.42.42\")\n (wrap-with-ssl-c",
"end": 25492,
"score": 0.9996362924575806,
"start": 25484,
"tag": "IP_ADDRESS",
"value": "42.42.42"
},
{
"context": " test-app (-> (build-ring-handler settings \"42.42.42\")\n (wrap-with-ssl-client-cert",
"end": 26280,
"score": 0.9996289014816284,
"start": 26272,
"tag": "IP_ADDRESS",
"value": "42.42.42"
},
{
"context": "est-app (-> (build-ring-handler settings \"42.42.42\")\n (wrap-with-ssl-c",
"end": 27044,
"score": 0.9996796250343323,
"start": 27036,
"tag": "IP_ADDRESS",
"value": "42.42.42"
},
{
"context": " test-app (-> (build-ring-handler settings \"42.42.42\")\n (wrap-with-ssl-client-cert",
"end": 27822,
"score": 0.9996746182441711,
"start": 27814,
"tag": "IP_ADDRESS",
"value": "42.42.42"
},
{
"context": " test-app (-> (build-ring-handler settings \"42.42.42\")\n (wrap-with-ssl-client-ce",
"end": 28588,
"score": 0.9989702701568604,
"start": 28580,
"tag": "IP_ADDRESS",
"value": "42.42.42"
},
{
"context": " test-app (-> (build-ring-handler settings \"42.42.42\")\n (wrap-with-ssl-client-ce",
"end": 29366,
"score": 0.9988850355148315,
"start": 29358,
"tag": "IP_ADDRESS",
"value": "42.42.42"
}
] | test/unit/puppetlabs/services/ca/certificate_authority_core_test.clj | ahpook/puppet-server | 0 | (ns puppetlabs.services.ca.certificate-authority-core-test
(:require [cheshire.core :as json]
[clojure.java.io :as io]
[clojure.test :refer :all]
[me.raynes.fs :as fs]
[puppetlabs.ssl-utils.core :as utils]
[puppetlabs.kitchensink.core :as ks]
[puppetlabs.puppetserver.certificate-authority :as ca]
[puppetlabs.services.ca.ca-testutils :as testutils]
[puppetlabs.services.ca.certificate-authority-core :refer :all]
[puppetlabs.trapperkeeper.testutils.logging :as logutils]
[ring.mock.request :as mock]
[schema.test :as schema-test]
[puppetlabs.comidi :as comidi]))
(use-fixtures :once schema-test/validate-schemas)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Utilities
(def test-resources-dir "./dev-resources/puppetlabs/services/ca/certificate_authority_core_test")
(def cadir (str test-resources-dir "/master/conf/ssl/ca"))
(def csrdir (str cadir "/requests"))
(def test-pems-dir (str test-resources-dir "/pems"))
(def autosign-files-dir (str test-resources-dir "/autosign"))
(defn test-pem-file
[pem-file-name]
(str test-pems-dir "/" pem-file-name))
(defn test-autosign-file
[autosign-file-name]
(str autosign-files-dir "/" autosign-file-name))
(def localhost-cert
(utils/pem->cert (test-pem-file "localhost-cert.pem")))
(defn build-ring-handler
[settings puppet-version]
(get-wrapped-handler
(-> (web-routes settings)
(comidi/routes->handler))
settings
""
(fn [handler]
(fn [request]
(handler request)))
puppet-version))
(defn wrap-with-ssl-client-cert
"Wrap a compojure app so all requests will include the
localhost certificate to allow access to the certificate
status endpoint."
[app]
(fn [request]
(-> request
(assoc :ssl-client-cert localhost-cert)
(app))))
(defn body-stream
[s]
(io/input-stream (.getBytes s)))
(def localhost-status
{:dns_alt_names ["DNS:djroomba.vpn.puppetlabs.net"
"DNS:localhost"
"DNS:puppet"
"DNS:puppet.vpn.puppetlabs.net"]
:fingerprint "F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73"
:fingerprints {:SHA1 "DB:32:CD:AB:88:86:E0:64:0A:B7:5B:88:76:E4:60:3A:CD:9E:36:C1"
:SHA256 "F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73"
:SHA512 "58:22:32:60:CE:E7:E9:C9:CB:6A:01:52:81:ED:24:D4:69:8E:9E:CF:D8:A7:4E:6E:B5:C7:E7:18:59:5F:81:4C:93:11:77:E6:F0:40:70:5B:9C:9D:BE:22:A6:61:0B:F9:46:70:43:09:58:7E:6B:B7:5B:D9:6A:54:36:09:53:F9"
:default "F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73"}
:name "localhost"
:state "signed"})
(def test-agent-status
{:dns_alt_names []
:fingerprint "36:94:27:47:EA:51:EE:7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3"
:fingerprints {:SHA1 "EB:3D:7B:9C:85:3E:56:7A:3E:9D:1B:C4:7A:21:5A:91:F5:00:4D:9D"
:SHA256 "36:94:27:47:EA:51:EE:7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3"
:SHA512 "80:C5:EE:B7:A5:FB:5E:53:7C:51:3A:A0:78:AF:CD:E3:7C:BA:B1:D6:BB:BD:61:9E:A0:2E:D2:12:3C:D8:6E:8D:86:7C:FC:FB:4C:6B:1D:15:63:02:19:D2:F8:49:7D:1A:11:78:07:31:23:22:36:61:0C:D8:E9:F4:97:0B:67:47"
:default "36:94:27:47:EA:51:EE:7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3"}
:name "test-agent"
:state "requested"})
(def revoked-agent-status
{:dns_alt_names ["DNS:BAR"
"DNS:Baz4"
"DNS:foo"
"DNS:revoked-agent"]
:fingerprint "1C:D0:29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95"
:fingerprints {:SHA1 "38:56:67:FF:20:91:0E:85:C4:DF:CA:16:77:60:D2:BB:FB:DF:68:BB"
:SHA256 "1C:D0:29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95"
:SHA512 "1A:E3:12:14:81:50:38:19:3C:C6:42:4B:BB:09:16:0C:B1:8A:3C:EB:8C:64:9C:88:46:C6:7E:35:5E:11:0C:7A:CC:B2:47:A2:EB:57:63:5C:48:68:22:57:62:A1:46:64:B4:56:29:47:A5:46:F4:BD:9B:45:77:19:91:0B:35:39"
:default "1C:D0:29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95"}
:name "revoked-agent"
:state "revoked"})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Tests
(deftest crl-endpoint-test
(testing "implementation of the CRL endpoint"
(let [response (handle-get-certificate-revocation-list
{:cacrl (test-pem-file "crl.pem")})]
(is (map? response))
(is (= 200 (:status response)))
(is (= "text/plain" (get-in response [:headers "Content-Type"])))
(is (string? (:body response))))))
(deftest puppet-version-header-test
(testing "Responses contain a X-Puppet-Version header"
(let [version-number "42.42.42"
ring-app (build-ring-handler (testutils/ca-settings cadir) version-number)
;; we can just GET the /CRL endpoint, so that's an easy test here.
request (mock/request :get
"/v1/certificate_revocation_list/mynode")
response (ring-app request)]
(is (= version-number (get-in response [:headers "X-Puppet-Version"]))))))
(deftest handle-put-certificate-request!-test
(let [settings (assoc (testutils/ca-sandbox! cadir)
:allow-duplicate-certs true)
static-csr (ca/path-to-cert-request (str cadir "/requests") "test-agent")]
(logutils/with-test-logging
(testing "when autosign results in true"
(doseq [value [true
(test-autosign-file "ruby-autosign-executable")
(test-autosign-file "autosign-whitelist.conf")]]
(let [settings (assoc settings :autosign value)
csr-stream (io/input-stream static-csr)
expected-path (ca/path-to-cert (:signeddir settings) "test-agent")]
(testing "it signs the CSR, writes the certificate to disk, and
returns a 200 response with empty plaintext body"
(try
(is (false? (fs/exists? expected-path)))
(let [response (handle-put-certificate-request! "test-agent" csr-stream settings)]
(is (true? (fs/exists? expected-path)))
(is (= 200 (:status response)))
(is (= "text/plain" (get-in response [:headers "Content-Type"])))
(is (nil? (:body response))))
(finally
(fs/delete expected-path)))))))
(testing "when autosign results in false"
(doseq [value [false
(test-autosign-file "ruby-autosign-executable-false")
(test-autosign-file "autosign-whitelist.conf")]]
(let [settings (assoc settings :autosign value)
csr-stream (io/input-stream (test-pem-file "foo-agent-csr.pem"))
expected-path (ca/path-to-cert-request (:csrdir settings) "foo-agent")]
(testing "it writes the CSR to disk and returns a
200 response with empty plaintext body"
(try
(is (false? (fs/exists? expected-path)))
(let [response (handle-put-certificate-request! "foo-agent" csr-stream settings)]
(is (true? (fs/exists? expected-path)))
(is (false? (fs/exists? (ca/path-to-cert (:signeddir settings) "foo-agent"))))
(is (= 200 (:status response)))
(is (= "text/plain" (get-in response [:headers "Content-Type"])))
(is (nil? (:body response))))
(finally
(fs/delete expected-path)))))))
(testing "when $allow-duplicate-certs is false and we receive a new CSR,
return a 400 response and error message"
(let [settings (assoc settings :allow-duplicate-certs false)
csr-stream (io/input-stream static-csr)]
;; Put the duplicate in place
(fs/copy static-csr (ca/path-to-cert-request (:csrdir settings) "test-agent"))
(let [response (handle-put-certificate-request! "test-agent" csr-stream settings)]
(is (logged? #"ignoring certificate request" :error))
(is (= 400 (:status response)))
(is (true? (.contains (:body response) "ignoring certificate request"))))))
(testing "when the subject CN on a CSR does not match the hostname specified
in the URL, the response is a 400"
(let [csr-stream (io/input-stream static-csr)
response (handle-put-certificate-request! "NOT-test-agent" csr-stream settings)]
(is (= 400 (:status response)))
(is (re-matches
#"Instance name \"test-agent\" does not match requested key \"NOT-test-agent\""
(:body response)))))
(testing "when the public key on the CSR is bogus, the response is a 400"
(let [csr-with-bad-public-key (test-pem-file "luke.madstop.com-bad-public-key.pem")
csr-stream (io/input-stream csr-with-bad-public-key)
response (handle-put-certificate-request!
"luke.madstop.com" csr-stream settings)]
(is (= 400 (:status response)))
(is (= "CSR contains a public key that does not correspond to the signing key"
(:body response)))))
(testing "when the CSR has disallowed extensions on it, the response is a 400"
(let [csr-with-bad-ext (test-pem-file "meow-bad-extension.pem")
csr-stream (io/input-stream csr-with-bad-ext)
response (handle-put-certificate-request!
"meow" csr-stream settings)]
(is (= 400 (:status response)))
(is (= "Found extensions that are not permitted: 1.9.9.9.9.9.9"
(:body response))))
(let [csr-with-bad-ext (test-pem-file "woof-bad-extensions.pem")
csr-stream (io/input-stream csr-with-bad-ext)
response (handle-put-certificate-request!
"woof" csr-stream settings)]
(is (= 400 (:status response)))
(is (= "Found extensions that are not permitted: 1.9.9.9.9.9.0, 1.9.9.9.9.9.1"
(:body response)))))
(testing "when the CSR subject contains invalid characters, the response is a 400"
;; These test cases are lifted out of the puppet spec tests.
(let [bad-csrs #{{:subject "super/bad"
:csr (test-pem-file "bad-subject-name-1.pem")}
{:subject "not\neven\tkind\rof"
:csr (test-pem-file "bad-subject-name-2.pem")}
{:subject "hidden\b\b\b\b\b\bmessage"
:csr (test-pem-file "bad-subject-name-3.pem")}}]
(doseq [{:keys [subject csr]} bad-csrs]
(let [csr-stream (io/input-stream csr)
response (handle-put-certificate-request!
subject csr-stream settings)]
(is (= 400 (:status response)))
(is (= "Subject contains unprintable or non-ASCII characters"
(:body response)))))))
(testing "no wildcards allowed"
(let [csr-with-wildcard (test-pem-file "bad-subject-name-wildcard.pem")
csr-stream (io/input-stream csr-with-wildcard)
response (handle-put-certificate-request!
"foo*bar" csr-stream settings)]
(is (= 400 (:status response)))
(is (= "Subject contains a wildcard, which is not allowed: foo*bar"
(:body response)))))
(testing "a CSR w/ DNS alt-names gets a specific error response"
(let [csr (io/input-stream (test-pem-file "hostwithaltnames.pem"))
response (handle-put-certificate-request!
"hostwithaltnames" csr settings)]
(is (= 400 (:status response)))
(is (= (:body response)
(str "CSR 'hostwithaltnames' contains subject alternative names "
"(DNS:altname1, DNS:altname2, DNS:altname3), which are disallowed. "
"Use `puppet cert --allow-dns-alt-names sign hostwithaltnames` to sign this request."))))))))
(deftest certificate-status-test
(testing "read requests"
(let [test-app (-> (build-ring-handler (testutils/ca-settings cadir) "42.42.42")
(wrap-with-ssl-client-cert))]
(testing "GET /certificate_status"
(doseq [[subject status] [["localhost" localhost-status]
["test-agent" test-agent-status]
["revoked-agent" revoked-agent-status]]]
(testing subject
(let [response (test-app
{:uri (str "/v1/certificate_status/" subject)
:request-method :get})]
(is (= 200 (:status response)) (str "Error requesting status for " subject))
(is (= status (json/parse-string (:body response) true))))))
(testing "returns a 404 when a non-existent certname is given"
(let [request {:uri "/v1/certificate_status/doesnotexist"
:request-method :get}
response (test-app request)]
(is (= 404 (:status response)))))
(testing "honors 'Accept: pson' header"
(let [request {:uri "/v1/certificate_status/localhost"
:request-method :get
:headers {"accept" "pson"}}
response (test-app request)]
(is (= 200 (:status response))
(ks/pprint-to-string response))
(is (.startsWith (get-in response [:headers "Content-Type"]) "text/pson"))))
(testing "honors 'Accept: text/pson' header"
(let [request {:uri "/v1/certificate_status/localhost"
:request-method :get
:headers {"accept" "text/pson"}}
response (test-app request)]
(is (= 200 (:status response))
(ks/pprint-to-string response))
(is (.startsWith (get-in response [:headers "Content-Type"]) "text/pson"))))
(testing "honors 'Accept: application/json' header"
(let [request {:uri "/v1/certificate_status/localhost"
:request-method :get
:headers {"accept" "application/json"}}
response (test-app request)]
(is (= 200 (:status response))
(ks/pprint-to-string response))
(is (.startsWith (get-in response [:headers "Content-Type"]) "application/json")))))
(testing "GET /certificate_statuses"
(let [response (test-app
{:uri "/v1/certificate_statuses/thisisirrelevant"
:request-method :get})]
(is (= 200 (:status response)))
(is (= #{localhost-status test-agent-status revoked-agent-status}
(set (json/parse-string (:body response) true)))))
(testing "with 'Accept: pson'"
(let [response (test-app
{:uri "/v1/certificate_statuses/thisisirrelevant"
:request-method :get
:headers {"accept" "pson"}})]
(is (= 200 (:status response)))
(is (.startsWith (get-in response [:headers "Content-Type"]) "text/pson"))
(is (= #{localhost-status test-agent-status revoked-agent-status}
(set (json/parse-string (:body response) true))))))
(testing "with 'Accept: text/pson'"
(let [response (test-app
{:uri "/v1/certificate_statuses/thisisirrelevant"
:request-method :get
:headers {"accept" "text/pson"}})]
(is (= 200 (:status response)))
(is (.startsWith (get-in response [:headers "Content-Type"]) "text/pson"))
(is (= #{localhost-status test-agent-status revoked-agent-status}
(set (json/parse-string (:body response) true))))))
(testing "with 'Accept: application/json'"
(let [response (test-app
{:uri "/v1/certificate_statuses/thisisirrelevant"
:request-method :get
:headers {"accept" "application/json"}})]
(is (= 200 (:status response)))
(is (.startsWith (get-in response [:headers "Content-Type"]) "application/json"))
(is (= #{localhost-status test-agent-status revoked-agent-status}
(set (json/parse-string (:body response) true)))))))))
(testing "write requests"
(let [settings (testutils/ca-sandbox! cadir)
test-app (-> (build-ring-handler settings "42.42.42")
(wrap-with-ssl-client-cert))]
(testing "PUT"
(testing "signing a cert"
(let [signed-cert-path (ca/path-to-cert (:signeddir settings) "test-agent")]
(is (false? (fs/exists? signed-cert-path)))
(let [response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :put
:body (body-stream "{\"desired_state\":\"signed\"}")})]
(is (true? (fs/exists? signed-cert-path)))
(is (= 204 (:status response))
(ks/pprint-to-string response)))))
(testing "revoking a cert"
(let [cert (utils/pem->cert (ca/path-to-cert (:signeddir settings) "localhost"))]
(is (false? (utils/revoked? (utils/pem->crl (:cacrl settings)) cert)))
(let [response (test-app
{:uri "/v1/certificate_status/localhost"
:request-method :put
:body (body-stream "{\"desired_state\":\"revoked\"}")})]
(is (true? (utils/revoked? (utils/pem->crl (:cacrl settings)) cert)))
(is (= 204 (:status response))))))
(testing "no body results in a 400"
(let [request {:uri "/v1/certificate_status/test-agent"
:request-method :put}
response (test-app request)]
(is (= 400 (:status response)))
(is (= (:body response) "Empty request body."))))
(testing "a body that isn't JSON results in a 400"
(let [request {:body (body-stream "this is not JSON")
:uri "/v1/certificate_status/test-agent"
:request-method :put}
response (test-app request)]
(is (= 400 (:status response)))
(is (= (:body response) "Request body is not JSON."))))
(testing "invalid cert status results in a 400"
(let [request {:uri "/v1/certificate_status/test-agent"
:request-method :put
:body (body-stream "{\"desired_state\":\"bogus\"}")}
response (test-app request)]
(is (= 400 (:status response)))
(is (= (:body response)
"State bogus invalid; Must specify desired state of 'signed' or 'revoked' for host test-agent."))))
(testing "returns a 404 when a non-existent certname is given"
(let [request {:uri "/v1/certificate_status/doesnotexist"
:request-method :put
:body (body-stream "{\"desired_state\":\"signed\"}")}
response (test-app request)]
(is (= 404 (:status response)))
(is (= "text/plain; charset=UTF-8"
(get-in response [:headers "Content-Type"]))
"Unexpected content type for response")
(is (= "Invalid certificate subject." (:body response)))))
(testing "Additional error handling on PUT requests"
(let [settings (testutils/ca-sandbox! cadir)
test-app (-> (build-ring-handler settings "42.42.42")
(wrap-with-ssl-client-cert))]
(testing "Asking to revoke a cert that hasn't been signed yet is a 409"
(let [request {:uri "/v1/certificate_status/test-agent"
:request-method :put
:body (body-stream "{\"desired_state\":\"revoked\"}")}
response (test-app request)]
(is (= 409 (:status response))
(ks/pprint-to-string response))
(is (= "text/plain; charset=UTF-8"
(get-in response [:headers "Content-Type"]))
"Unexpected content type for response")
(is (= (:body response)
"Cannot revoke certificate for host test-agent without a signed certificate")
(ks/pprint-to-string response))))
(testing "trying to sign a cert that's already signed is a 409"
(let [request {:uri "/v1/certificate_status/localhost"
:request-method :put
:body (body-stream "{\"desired_state\":\"signed\"}")}
response (test-app request)]
(is (= 409 (:status response)))
(is (= "text/plain; charset=UTF-8"
(get-in response [:headers "Content-Type"]))
"Unexpected content type for response")
(is (= (:body response)
"Cannot sign certificate for host localhost without a certificate request"))))
(testing "trying to revoke a cert that's already revoked is a 204"
(let [request {:uri "/v1/certificate_status/revoked-agent"
:request-method :put
:body (body-stream "{\"desired_state\":\"revoked\"}")}
response (test-app request)]
(is (= 204 (:status response))))))))
(testing "DELETE"
(let [csr (ca/path-to-cert-request (:csrdir settings) "test-agent")]
(fs/copy (ca/path-to-cert-request csrdir "test-agent") csr)
(is (true? (fs/exists? csr)))
(is (= 204 (:status (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :delete}))))
(is (false? (fs/exists? csr))))
(let [cert (ca/path-to-cert (:signeddir settings) "revoked-agent")]
(is (true? (fs/exists? cert)))
(is (= 204 (:status (test-app
{:uri "/v1/certificate_status/revoked-agent"
:request-method :delete}))))
(is (false? (fs/exists? cert))))
(testing "returns a 404 when a non-existent certname is given"
(is (= 404 (:status (test-app
{:uri "/v1/certificate_status/doesnotexist"
:request-method :delete}))))))))
(testing "a signing request w/ a 'application/json' content-type succeeds"
(let [settings (testutils/ca-sandbox! cadir)
test-app (-> (build-ring-handler settings "42.42.42")
(wrap-with-ssl-client-cert))
signed-cert-path (ca/path-to-cert (:signeddir settings) "test-agent")]
(is (false? (fs/exists? signed-cert-path)))
(let [response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :put
:headers {"content-type" "application/json"}
:body (body-stream "{\"desired_state\":\"signed\"}")})]
(is (true? (fs/exists? signed-cert-path)))
(is (= 204 (:status response))))))
(testing "a signing request w/ a 'application/json' content-type and charset succeeds"
(let [settings (testutils/ca-sandbox! cadir)
test-app (-> (build-ring-handler settings "42.42.42")
(wrap-with-ssl-client-cert))
signed-cert-path (ca/path-to-cert (:signeddir settings) "test-agent")]
(is (false? (fs/exists? signed-cert-path)))
(let [response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :put
:headers {"content-type"
"application/json; charset=UTF-8"}
:body (body-stream "{\"desired_state\":\"signed\"}")})]
(is (true? (fs/exists? signed-cert-path)))
(is (= 204 (:status response))))))
(testing "a signing request w/ a 'text/pson' content-type succeeds"
(let [settings (testutils/ca-sandbox! cadir)
test-app (-> (build-ring-handler settings "42.42.42")
(wrap-with-ssl-client-cert))
signed-cert-path (ca/path-to-cert (:signeddir settings) "test-agent")]
(is (false? (fs/exists? signed-cert-path)))
(let [response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :put
:headers {"content-type" "text/pson"}
:body (body-stream "{\"desired_state\":\"signed\"}")})]
(is (true? (fs/exists? signed-cert-path)))
(is (= 204 (:status response))))))
(testing "a signing request w/ a 'text/pson' content-type and charset succeeds"
(let [settings (testutils/ca-sandbox! cadir)
test-app (-> (build-ring-handler settings "42.42.42")
(wrap-with-ssl-client-cert))
signed-cert-path (ca/path-to-cert (:signeddir settings) "test-agent")]
(is (false? (fs/exists? signed-cert-path)))
(let [response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :put
:headers {"content-type" "text/pson; charset=UTF-8"}
:body (body-stream "{\"desired_state\":\"signed\"}")})]
(is (true? (fs/exists? signed-cert-path)))
(is (= 204 (:status response))))))
(testing "a signing request w/ a 'pson' content-type succeeds"
(let [settings (testutils/ca-sandbox! cadir)
test-app (-> (build-ring-handler settings "42.42.42")
(wrap-with-ssl-client-cert))
signed-cert-path (ca/path-to-cert (:signeddir settings) "test-agent")]
(is (false? (fs/exists? signed-cert-path)))
(let [response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :put
:headers {"content-type" "pson"}
:body (body-stream "{\"desired_state\":\"signed\"}")})]
(is (true? (fs/exists? signed-cert-path)))
(is (= 204 (:status response))))))
(testing "a signing request w/ a 'pson' content-type and charset succeeds"
(let [settings (testutils/ca-sandbox! cadir)
test-app (-> (build-ring-handler settings "42.42.42")
(wrap-with-ssl-client-cert))
signed-cert-path (ca/path-to-cert (:signeddir settings) "test-agent")]
(is (false? (fs/exists? signed-cert-path)))
(let [response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :put
:headers {"content-type" "pson; charset=UTF-8"}
:body (body-stream "{\"desired_state\":\"signed\"}")})]
(is (true? (fs/exists? signed-cert-path)))
(is (= 204 (:status response))))))
(testing "a signing request w/ a bogus content-type header results in a HTTP 415"
(let [settings (testutils/ca-sandbox! cadir)
test-app (-> (build-ring-handler settings "42.42.42")
(wrap-with-ssl-client-cert))
response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :put
:headers {"content-type" "bogus"}
:body (body-stream "{\"desired_state\":\"signed\"}")})]
(is (= 415 (:status response))
(ks/pprint-to-string response))
(is (= (:body response) "Unsupported media type.")))))
(deftest cert-status-invalid-csrs
(testing "Asking /certificate_status to sign invalid CSRs"
(let [settings (assoc (testutils/ca-settings cadir)
:csrdir (str test-resources-dir "/alternate-csrdir"))
test-app (-> (build-ring-handler settings "42.42.42")
(wrap-with-ssl-client-cert))]
(testing "one example - a CSR with DNS alt-names"
(let [request {:uri "/v1/certificate_status/hostwithaltnames"
:request-method :put
:body (body-stream "{\"desired_state\":\"signed\"}")}
response (test-app request)]
(is (= 409 (:status response))
(ks/pprint-to-string response))
(is (= "text/plain; charset=UTF-8"
(get-in response [:headers "Content-Type"]))
"Unexpected content type for response")
(is (= (:body response)
(str "CSR 'hostwithaltnames' contains subject alternative names "
"(DNS:altname1, DNS:altname2, DNS:altname3), which are disallowed. "
"Use `puppet cert --allow-dns-alt-names sign hostwithaltnames` "
"to sign this request.")))))
(testing "another example - a CSR with an invalid extension"
(let [request {:uri "/v1/certificate_status/meow"
:request-method :put
:body (body-stream "{\"desired_state\":\"signed\"}")}
response (test-app request)]
(is (= 409 (:status response))
(ks/pprint-to-string response))
(is (= "text/plain; charset=UTF-8"
(get-in response [:headers "Content-Type"]))
"Unexpected content type for response")
(is (= (:body response)
"Found extensions that are not permitted: 1.9.9.9.9.9.9")))))))
(deftest cert-status-duplicate-certs
(testing "signing a certificate doesn't depend on $allow-duplicate-certs"
(doseq [bool [false true]]
(testing bool
(let [settings (assoc (testutils/ca-sandbox! cadir)
:allow-duplicate-certs bool)
test-app (-> (build-ring-handler settings "1.2.3.4")
(wrap-with-ssl-client-cert))
signed-path (ca/path-to-cert (:signeddir settings) "test-agent")]
(is (false? (fs/exists? signed-path)))
(let [response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :put
:body (body-stream "{\"desired_state\":\"signed\"}")})]
(is (true? (fs/exists? signed-path)))
(is (= 204 (:status response))
(ks/pprint-to-string response))))))))
(deftest cert-status-access-control
(testing "a request with no certificate is rejected with 403 Forbidden"
(let [test-app (build-ring-handler (testutils/ca-settings cadir) "1.2.3.4")]
(doseq [endpoint ["certificate_status" "certificate_statuses"]]
(testing endpoint
(let [response (test-app
{:uri (str "/v1/" endpoint "/test-agent")
:request-method :get})]
(is (= 403 (:status response)))
(is (= "Forbidden." (:body response))))))))
(testing "a request with a certificate not on the whitelist is rejected"
(let [settings (assoc (testutils/ca-settings cadir)
:access-control {:certificate-status
{:client-whitelist []}})
test-app (build-ring-handler settings "1.2.3.4")]
(doseq [endpoint ["certificate_status" "certificate_statuses"]]
(testing endpoint
(let [response (test-app
{:uri (str "/v1/" endpoint "/test-agent")
:request-method :get
:ssl-client-cert localhost-cert})]
(is (= 403 (:status response)))
(is (= "Forbidden." (:body response))))))))
(testing "a request with a certificate that is on the whitelist is allowed"
(doseq [whitelist [["localhost"] ["foo!" "localhost"]]]
(testing "certificate_status"
(let [settings (assoc (testutils/ca-settings cadir)
:access-control {:certificate-status
{:client-whitelist whitelist}})
test-app (build-ring-handler settings "1.2.3.4")
response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :get
:ssl-client-cert localhost-cert})]
(is (= 200 (:status response)))
(is (= test-agent-status (json/parse-string (:body response) true)))))
(testing "certificate_statuses"
(let [settings (assoc (testutils/ca-settings cadir)
:access-control {:certificate-status
{:client-whitelist whitelist}})
test-app (build-ring-handler settings "1.2.3.4")
response (test-app
{:uri "/v1/certificate_statuses/all"
:request-method :get
:ssl-client-cert localhost-cert})]
(is (= 200 (:status response)))
(is (= #{test-agent-status revoked-agent-status localhost-status}
(set (json/parse-string (:body response) true))))))))
(testing "access control can be disabled"
(let [settings (assoc (testutils/ca-settings cadir)
:access-control {:certificate-status
{:authorization-required false
:client-whitelist []}})
test-app (build-ring-handler settings "1.2.3.4")]
(testing "certificate_status"
(let [response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :get})]
(is (= 200 (:status response)))
(is (= test-agent-status (json/parse-string (:body response) true)))))
(testing "certificate_statuses"
(let [response (test-app
{:uri "/v1/certificate_statuses/all"
:request-method :get})]
(is (= 200 (:status response)))
(is (= #{test-agent-status revoked-agent-status localhost-status}
(set (json/parse-string (:body response) true)))))))))
| 121482 | (ns puppetlabs.services.ca.certificate-authority-core-test
(:require [cheshire.core :as json]
[clojure.java.io :as io]
[clojure.test :refer :all]
[me.raynes.fs :as fs]
[puppetlabs.ssl-utils.core :as utils]
[puppetlabs.kitchensink.core :as ks]
[puppetlabs.puppetserver.certificate-authority :as ca]
[puppetlabs.services.ca.ca-testutils :as testutils]
[puppetlabs.services.ca.certificate-authority-core :refer :all]
[puppetlabs.trapperkeeper.testutils.logging :as logutils]
[ring.mock.request :as mock]
[schema.test :as schema-test]
[puppetlabs.comidi :as comidi]))
(use-fixtures :once schema-test/validate-schemas)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Utilities
(def test-resources-dir "./dev-resources/puppetlabs/services/ca/certificate_authority_core_test")
(def cadir (str test-resources-dir "/master/conf/ssl/ca"))
(def csrdir (str cadir "/requests"))
(def test-pems-dir (str test-resources-dir "/pems"))
(def autosign-files-dir (str test-resources-dir "/autosign"))
(defn test-pem-file
[pem-file-name]
(str test-pems-dir "/" pem-file-name))
(defn test-autosign-file
[autosign-file-name]
(str autosign-files-dir "/" autosign-file-name))
(def localhost-cert
(utils/pem->cert (test-pem-file "localhost-cert.pem")))
(defn build-ring-handler
[settings puppet-version]
(get-wrapped-handler
(-> (web-routes settings)
(comidi/routes->handler))
settings
""
(fn [handler]
(fn [request]
(handler request)))
puppet-version))
(defn wrap-with-ssl-client-cert
"Wrap a compojure app so all requests will include the
localhost certificate to allow access to the certificate
status endpoint."
[app]
(fn [request]
(-> request
(assoc :ssl-client-cert localhost-cert)
(app))))
(defn body-stream
[s]
(io/input-stream (.getBytes s)))
(def localhost-status
{:dns_alt_names ["DNS:djroomba.vpn.puppetlabs.net"
"DNS:localhost"
"DNS:puppet"
"DNS:puppet.vpn.puppetlabs.net"]
:fingerprint "F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73"
:fingerprints {:SHA1 "DB:32:CD:AB:88:86:E0:64:0A:B7:5B:88:76:E4:60:3A:CD:9E:36:C1"
:SHA256 "fc00:e968:6179::de52:7100:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73"
:SHA512 "58:22:32:60:CE:E7:E9:C9:CB:6A:01:52:81:ED:24:D4:69:8E:9E:CF:D8:A7:4E:6E:B5:C7:E7:18:59:5F:81:4C:93:11:77:E6:F0:40:70:5B:9C:9D:BE:22:A6:61:0B:F9:46:70:43:09:58:7E:6B:B7:5B:D9:6A:54:36:09:53:F9"
:default "fc00:e968:6179::de52:7100:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73"}
:name "localhost"
:state "signed"})
(def test-agent-status
{:dns_alt_names []
:fingerprint "fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3"
:fingerprints {:SHA1 "EB:3D:7B:9C:85:3E:56:7A:3E:9D:1B:C4:7A:21:5A:91:F5:00:4D:9D"
:SHA256 "36:94:27:47:EA:51:EE:7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3"
:SHA512 "fdf8:f53e:61e4::18:7C:51:3A:A0:78:AF:CD:E3:7C:BA:B1:D6:BB:BD:61:9E:A0:2E:D2:12:3C:D8:6E:8D:86:7C:FC:FB:4C:6B:1D:15:63:02:19:D2:F8:49:7D:1A:11:78:07:31:23:22:36:61:0C:D8:E9:F4:97:0B:67:47"
:default "fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3"}
:name "test-agent"
:state "requested"})
(def revoked-agent-status
{:dns_alt_names ["DNS:BAR"
"DNS:Baz4"
"DNS:foo"
"DNS:revoked-agent"]
:fingerprint "1C:D0:29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95"
:fingerprints {:SHA1 "38:56:67:FF:20:91:0E:85:C4:DF:CA:16:77:60:D2:BB:FB:DF:68:BB"
:SHA256 "1C:D0:29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95"
:SHA512 "1A:E3:12:14:81:50:38:19:3C:C6:42:4B:BB:09:16:0C:B1:8A:3C:EB:8C:64:9C:88:46:C6:7E:35:5E:11:0C:7A:CC:B2:47:A2:EB:57:63:5C:48:68:22:57:62:A1:46:64:B4:56:29:47:A5:46:F4:BD:9B:45:77:19:91:0B:35:39"
:default "1C:D0:29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95"}
:name "revoked-agent"
:state "revoked"})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Tests
(deftest crl-endpoint-test
(testing "implementation of the CRL endpoint"
(let [response (handle-get-certificate-revocation-list
{:cacrl (test-pem-file "crl.pem")})]
(is (map? response))
(is (= 200 (:status response)))
(is (= "text/plain" (get-in response [:headers "Content-Type"])))
(is (string? (:body response))))))
(deftest puppet-version-header-test
(testing "Responses contain a X-Puppet-Version header"
(let [version-number "42.42.42"
ring-app (build-ring-handler (testutils/ca-settings cadir) version-number)
;; we can just GET the /CRL endpoint, so that's an easy test here.
request (mock/request :get
"/v1/certificate_revocation_list/mynode")
response (ring-app request)]
(is (= version-number (get-in response [:headers "X-Puppet-Version"]))))))
(deftest handle-put-certificate-request!-test
(let [settings (assoc (testutils/ca-sandbox! cadir)
:allow-duplicate-certs true)
static-csr (ca/path-to-cert-request (str cadir "/requests") "test-agent")]
(logutils/with-test-logging
(testing "when autosign results in true"
(doseq [value [true
(test-autosign-file "ruby-autosign-executable")
(test-autosign-file "autosign-whitelist.conf")]]
(let [settings (assoc settings :autosign value)
csr-stream (io/input-stream static-csr)
expected-path (ca/path-to-cert (:signeddir settings) "test-agent")]
(testing "it signs the CSR, writes the certificate to disk, and
returns a 200 response with empty plaintext body"
(try
(is (false? (fs/exists? expected-path)))
(let [response (handle-put-certificate-request! "test-agent" csr-stream settings)]
(is (true? (fs/exists? expected-path)))
(is (= 200 (:status response)))
(is (= "text/plain" (get-in response [:headers "Content-Type"])))
(is (nil? (:body response))))
(finally
(fs/delete expected-path)))))))
(testing "when autosign results in false"
(doseq [value [false
(test-autosign-file "ruby-autosign-executable-false")
(test-autosign-file "autosign-whitelist.conf")]]
(let [settings (assoc settings :autosign value)
csr-stream (io/input-stream (test-pem-file "foo-agent-csr.pem"))
expected-path (ca/path-to-cert-request (:csrdir settings) "foo-agent")]
(testing "it writes the CSR to disk and returns a
200 response with empty plaintext body"
(try
(is (false? (fs/exists? expected-path)))
(let [response (handle-put-certificate-request! "foo-agent" csr-stream settings)]
(is (true? (fs/exists? expected-path)))
(is (false? (fs/exists? (ca/path-to-cert (:signeddir settings) "foo-agent"))))
(is (= 200 (:status response)))
(is (= "text/plain" (get-in response [:headers "Content-Type"])))
(is (nil? (:body response))))
(finally
(fs/delete expected-path)))))))
(testing "when $allow-duplicate-certs is false and we receive a new CSR,
return a 400 response and error message"
(let [settings (assoc settings :allow-duplicate-certs false)
csr-stream (io/input-stream static-csr)]
;; Put the duplicate in place
(fs/copy static-csr (ca/path-to-cert-request (:csrdir settings) "test-agent"))
(let [response (handle-put-certificate-request! "test-agent" csr-stream settings)]
(is (logged? #"ignoring certificate request" :error))
(is (= 400 (:status response)))
(is (true? (.contains (:body response) "ignoring certificate request"))))))
(testing "when the subject CN on a CSR does not match the hostname specified
in the URL, the response is a 400"
(let [csr-stream (io/input-stream static-csr)
response (handle-put-certificate-request! "NOT-test-agent" csr-stream settings)]
(is (= 400 (:status response)))
(is (re-matches
#"Instance name \"test-agent\" does not match requested key \"NOT-test-agent\""
(:body response)))))
(testing "when the public key on the CSR is bogus, the response is a 400"
(let [csr-with-bad-public-key (test-pem-file "luke.madstop.com-bad-public-key.pem")
csr-stream (io/input-stream csr-with-bad-public-key)
response (handle-put-certificate-request!
"luke.madstop.com" csr-stream settings)]
(is (= 400 (:status response)))
(is (= "CSR contains a public key that does not correspond to the signing key"
(:body response)))))
(testing "when the CSR has disallowed extensions on it, the response is a 400"
(let [csr-with-bad-ext (test-pem-file "meow-bad-extension.pem")
csr-stream (io/input-stream csr-with-bad-ext)
response (handle-put-certificate-request!
"meow" csr-stream settings)]
(is (= 400 (:status response)))
(is (= "Found extensions that are not permitted: 1.9.9.9.9.9.9"
(:body response))))
(let [csr-with-bad-ext (test-pem-file "woof-bad-extensions.pem")
csr-stream (io/input-stream csr-with-bad-ext)
response (handle-put-certificate-request!
"woof" csr-stream settings)]
(is (= 400 (:status response)))
(is (= "Found extensions that are not permitted: 1.9.9.9.9.9.0, 1.9.9.9.9.9.1"
(:body response)))))
(testing "when the CSR subject contains invalid characters, the response is a 400"
;; These test cases are lifted out of the puppet spec tests.
(let [bad-csrs #{{:subject "super/bad"
:csr (test-pem-file "bad-subject-name-1.pem")}
{:subject "not\neven\tkind\rof"
:csr (test-pem-file "bad-subject-name-2.pem")}
{:subject "hidden\b\b\b\b\b\bmessage"
:csr (test-pem-file "bad-subject-name-3.pem")}}]
(doseq [{:keys [subject csr]} bad-csrs]
(let [csr-stream (io/input-stream csr)
response (handle-put-certificate-request!
subject csr-stream settings)]
(is (= 400 (:status response)))
(is (= "Subject contains unprintable or non-ASCII characters"
(:body response)))))))
(testing "no wildcards allowed"
(let [csr-with-wildcard (test-pem-file "bad-subject-name-wildcard.pem")
csr-stream (io/input-stream csr-with-wildcard)
response (handle-put-certificate-request!
"foo*bar" csr-stream settings)]
(is (= 400 (:status response)))
(is (= "Subject contains a wildcard, which is not allowed: foo*bar"
(:body response)))))
(testing "a CSR w/ DNS alt-names gets a specific error response"
(let [csr (io/input-stream (test-pem-file "hostwithaltnames.pem"))
response (handle-put-certificate-request!
"hostwithaltnames" csr settings)]
(is (= 400 (:status response)))
(is (= (:body response)
(str "CSR 'hostwithaltnames' contains subject alternative names "
"(DNS:altname1, DNS:altname2, DNS:altname3), which are disallowed. "
"Use `puppet cert --allow-dns-alt-names sign hostwithaltnames` to sign this request."))))))))
(deftest certificate-status-test
(testing "read requests"
(let [test-app (-> (build-ring-handler (testutils/ca-settings cadir) "42.42.42")
(wrap-with-ssl-client-cert))]
(testing "GET /certificate_status"
(doseq [[subject status] [["localhost" localhost-status]
["test-agent" test-agent-status]
["revoked-agent" revoked-agent-status]]]
(testing subject
(let [response (test-app
{:uri (str "/v1/certificate_status/" subject)
:request-method :get})]
(is (= 200 (:status response)) (str "Error requesting status for " subject))
(is (= status (json/parse-string (:body response) true))))))
(testing "returns a 404 when a non-existent certname is given"
(let [request {:uri "/v1/certificate_status/doesnotexist"
:request-method :get}
response (test-app request)]
(is (= 404 (:status response)))))
(testing "honors 'Accept: pson' header"
(let [request {:uri "/v1/certificate_status/localhost"
:request-method :get
:headers {"accept" "pson"}}
response (test-app request)]
(is (= 200 (:status response))
(ks/pprint-to-string response))
(is (.startsWith (get-in response [:headers "Content-Type"]) "text/pson"))))
(testing "honors 'Accept: text/pson' header"
(let [request {:uri "/v1/certificate_status/localhost"
:request-method :get
:headers {"accept" "text/pson"}}
response (test-app request)]
(is (= 200 (:status response))
(ks/pprint-to-string response))
(is (.startsWith (get-in response [:headers "Content-Type"]) "text/pson"))))
(testing "honors 'Accept: application/json' header"
(let [request {:uri "/v1/certificate_status/localhost"
:request-method :get
:headers {"accept" "application/json"}}
response (test-app request)]
(is (= 200 (:status response))
(ks/pprint-to-string response))
(is (.startsWith (get-in response [:headers "Content-Type"]) "application/json")))))
(testing "GET /certificate_statuses"
(let [response (test-app
{:uri "/v1/certificate_statuses/thisisirrelevant"
:request-method :get})]
(is (= 200 (:status response)))
(is (= #{localhost-status test-agent-status revoked-agent-status}
(set (json/parse-string (:body response) true)))))
(testing "with 'Accept: pson'"
(let [response (test-app
{:uri "/v1/certificate_statuses/thisisirrelevant"
:request-method :get
:headers {"accept" "pson"}})]
(is (= 200 (:status response)))
(is (.startsWith (get-in response [:headers "Content-Type"]) "text/pson"))
(is (= #{localhost-status test-agent-status revoked-agent-status}
(set (json/parse-string (:body response) true))))))
(testing "with 'Accept: text/pson'"
(let [response (test-app
{:uri "/v1/certificate_statuses/thisisirrelevant"
:request-method :get
:headers {"accept" "text/pson"}})]
(is (= 200 (:status response)))
(is (.startsWith (get-in response [:headers "Content-Type"]) "text/pson"))
(is (= #{localhost-status test-agent-status revoked-agent-status}
(set (json/parse-string (:body response) true))))))
(testing "with 'Accept: application/json'"
(let [response (test-app
{:uri "/v1/certificate_statuses/thisisirrelevant"
:request-method :get
:headers {"accept" "application/json"}})]
(is (= 200 (:status response)))
(is (.startsWith (get-in response [:headers "Content-Type"]) "application/json"))
(is (= #{localhost-status test-agent-status revoked-agent-status}
(set (json/parse-string (:body response) true)))))))))
(testing "write requests"
(let [settings (testutils/ca-sandbox! cadir)
test-app (-> (build-ring-handler settings "42.42.42")
(wrap-with-ssl-client-cert))]
(testing "PUT"
(testing "signing a cert"
(let [signed-cert-path (ca/path-to-cert (:signeddir settings) "test-agent")]
(is (false? (fs/exists? signed-cert-path)))
(let [response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :put
:body (body-stream "{\"desired_state\":\"signed\"}")})]
(is (true? (fs/exists? signed-cert-path)))
(is (= 204 (:status response))
(ks/pprint-to-string response)))))
(testing "revoking a cert"
(let [cert (utils/pem->cert (ca/path-to-cert (:signeddir settings) "localhost"))]
(is (false? (utils/revoked? (utils/pem->crl (:cacrl settings)) cert)))
(let [response (test-app
{:uri "/v1/certificate_status/localhost"
:request-method :put
:body (body-stream "{\"desired_state\":\"revoked\"}")})]
(is (true? (utils/revoked? (utils/pem->crl (:cacrl settings)) cert)))
(is (= 204 (:status response))))))
(testing "no body results in a 400"
(let [request {:uri "/v1/certificate_status/test-agent"
:request-method :put}
response (test-app request)]
(is (= 400 (:status response)))
(is (= (:body response) "Empty request body."))))
(testing "a body that isn't JSON results in a 400"
(let [request {:body (body-stream "this is not JSON")
:uri "/v1/certificate_status/test-agent"
:request-method :put}
response (test-app request)]
(is (= 400 (:status response)))
(is (= (:body response) "Request body is not JSON."))))
(testing "invalid cert status results in a 400"
(let [request {:uri "/v1/certificate_status/test-agent"
:request-method :put
:body (body-stream "{\"desired_state\":\"bogus\"}")}
response (test-app request)]
(is (= 400 (:status response)))
(is (= (:body response)
"State bogus invalid; Must specify desired state of 'signed' or 'revoked' for host test-agent."))))
(testing "returns a 404 when a non-existent certname is given"
(let [request {:uri "/v1/certificate_status/doesnotexist"
:request-method :put
:body (body-stream "{\"desired_state\":\"signed\"}")}
response (test-app request)]
(is (= 404 (:status response)))
(is (= "text/plain; charset=UTF-8"
(get-in response [:headers "Content-Type"]))
"Unexpected content type for response")
(is (= "Invalid certificate subject." (:body response)))))
(testing "Additional error handling on PUT requests"
(let [settings (testutils/ca-sandbox! cadir)
test-app (-> (build-ring-handler settings "42.42.42")
(wrap-with-ssl-client-cert))]
(testing "Asking to revoke a cert that hasn't been signed yet is a 409"
(let [request {:uri "/v1/certificate_status/test-agent"
:request-method :put
:body (body-stream "{\"desired_state\":\"revoked\"}")}
response (test-app request)]
(is (= 409 (:status response))
(ks/pprint-to-string response))
(is (= "text/plain; charset=UTF-8"
(get-in response [:headers "Content-Type"]))
"Unexpected content type for response")
(is (= (:body response)
"Cannot revoke certificate for host test-agent without a signed certificate")
(ks/pprint-to-string response))))
(testing "trying to sign a cert that's already signed is a 409"
(let [request {:uri "/v1/certificate_status/localhost"
:request-method :put
:body (body-stream "{\"desired_state\":\"signed\"}")}
response (test-app request)]
(is (= 409 (:status response)))
(is (= "text/plain; charset=UTF-8"
(get-in response [:headers "Content-Type"]))
"Unexpected content type for response")
(is (= (:body response)
"Cannot sign certificate for host localhost without a certificate request"))))
(testing "trying to revoke a cert that's already revoked is a 204"
(let [request {:uri "/v1/certificate_status/revoked-agent"
:request-method :put
:body (body-stream "{\"desired_state\":\"revoked\"}")}
response (test-app request)]
(is (= 204 (:status response))))))))
(testing "DELETE"
(let [csr (ca/path-to-cert-request (:csrdir settings) "test-agent")]
(fs/copy (ca/path-to-cert-request csrdir "test-agent") csr)
(is (true? (fs/exists? csr)))
(is (= 204 (:status (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :delete}))))
(is (false? (fs/exists? csr))))
(let [cert (ca/path-to-cert (:signeddir settings) "revoked-agent")]
(is (true? (fs/exists? cert)))
(is (= 204 (:status (test-app
{:uri "/v1/certificate_status/revoked-agent"
:request-method :delete}))))
(is (false? (fs/exists? cert))))
(testing "returns a 404 when a non-existent certname is given"
(is (= 404 (:status (test-app
{:uri "/v1/certificate_status/doesnotexist"
:request-method :delete}))))))))
(testing "a signing request w/ a 'application/json' content-type succeeds"
(let [settings (testutils/ca-sandbox! cadir)
test-app (-> (build-ring-handler settings "42.42.42")
(wrap-with-ssl-client-cert))
signed-cert-path (ca/path-to-cert (:signeddir settings) "test-agent")]
(is (false? (fs/exists? signed-cert-path)))
(let [response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :put
:headers {"content-type" "application/json"}
:body (body-stream "{\"desired_state\":\"signed\"}")})]
(is (true? (fs/exists? signed-cert-path)))
(is (= 204 (:status response))))))
(testing "a signing request w/ a 'application/json' content-type and charset succeeds"
(let [settings (testutils/ca-sandbox! cadir)
test-app (-> (build-ring-handler settings "42.42.42")
(wrap-with-ssl-client-cert))
signed-cert-path (ca/path-to-cert (:signeddir settings) "test-agent")]
(is (false? (fs/exists? signed-cert-path)))
(let [response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :put
:headers {"content-type"
"application/json; charset=UTF-8"}
:body (body-stream "{\"desired_state\":\"signed\"}")})]
(is (true? (fs/exists? signed-cert-path)))
(is (= 204 (:status response))))))
(testing "a signing request w/ a 'text/pson' content-type succeeds"
(let [settings (testutils/ca-sandbox! cadir)
test-app (-> (build-ring-handler settings "42.42.42")
(wrap-with-ssl-client-cert))
signed-cert-path (ca/path-to-cert (:signeddir settings) "test-agent")]
(is (false? (fs/exists? signed-cert-path)))
(let [response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :put
:headers {"content-type" "text/pson"}
:body (body-stream "{\"desired_state\":\"signed\"}")})]
(is (true? (fs/exists? signed-cert-path)))
(is (= 204 (:status response))))))
(testing "a signing request w/ a 'text/pson' content-type and charset succeeds"
(let [settings (testutils/ca-sandbox! cadir)
test-app (-> (build-ring-handler settings "42.42.42")
(wrap-with-ssl-client-cert))
signed-cert-path (ca/path-to-cert (:signeddir settings) "test-agent")]
(is (false? (fs/exists? signed-cert-path)))
(let [response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :put
:headers {"content-type" "text/pson; charset=UTF-8"}
:body (body-stream "{\"desired_state\":\"signed\"}")})]
(is (true? (fs/exists? signed-cert-path)))
(is (= 204 (:status response))))))
(testing "a signing request w/ a 'pson' content-type succeeds"
(let [settings (testutils/ca-sandbox! cadir)
test-app (-> (build-ring-handler settings "42.42.42")
(wrap-with-ssl-client-cert))
signed-cert-path (ca/path-to-cert (:signeddir settings) "test-agent")]
(is (false? (fs/exists? signed-cert-path)))
(let [response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :put
:headers {"content-type" "pson"}
:body (body-stream "{\"desired_state\":\"signed\"}")})]
(is (true? (fs/exists? signed-cert-path)))
(is (= 204 (:status response))))))
(testing "a signing request w/ a 'pson' content-type and charset succeeds"
(let [settings (testutils/ca-sandbox! cadir)
test-app (-> (build-ring-handler settings "42.42.42")
(wrap-with-ssl-client-cert))
signed-cert-path (ca/path-to-cert (:signeddir settings) "test-agent")]
(is (false? (fs/exists? signed-cert-path)))
(let [response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :put
:headers {"content-type" "pson; charset=UTF-8"}
:body (body-stream "{\"desired_state\":\"signed\"}")})]
(is (true? (fs/exists? signed-cert-path)))
(is (= 204 (:status response))))))
(testing "a signing request w/ a bogus content-type header results in a HTTP 415"
(let [settings (testutils/ca-sandbox! cadir)
test-app (-> (build-ring-handler settings "42.42.42")
(wrap-with-ssl-client-cert))
response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :put
:headers {"content-type" "bogus"}
:body (body-stream "{\"desired_state\":\"signed\"}")})]
(is (= 415 (:status response))
(ks/pprint-to-string response))
(is (= (:body response) "Unsupported media type.")))))
(deftest cert-status-invalid-csrs
(testing "Asking /certificate_status to sign invalid CSRs"
(let [settings (assoc (testutils/ca-settings cadir)
:csrdir (str test-resources-dir "/alternate-csrdir"))
test-app (-> (build-ring-handler settings "42.42.42")
(wrap-with-ssl-client-cert))]
(testing "one example - a CSR with DNS alt-names"
(let [request {:uri "/v1/certificate_status/hostwithaltnames"
:request-method :put
:body (body-stream "{\"desired_state\":\"signed\"}")}
response (test-app request)]
(is (= 409 (:status response))
(ks/pprint-to-string response))
(is (= "text/plain; charset=UTF-8"
(get-in response [:headers "Content-Type"]))
"Unexpected content type for response")
(is (= (:body response)
(str "CSR 'hostwithaltnames' contains subject alternative names "
"(DNS:altname1, DNS:altname2, DNS:altname3), which are disallowed. "
"Use `puppet cert --allow-dns-alt-names sign hostwithaltnames` "
"to sign this request.")))))
(testing "another example - a CSR with an invalid extension"
(let [request {:uri "/v1/certificate_status/meow"
:request-method :put
:body (body-stream "{\"desired_state\":\"signed\"}")}
response (test-app request)]
(is (= 409 (:status response))
(ks/pprint-to-string response))
(is (= "text/plain; charset=UTF-8"
(get-in response [:headers "Content-Type"]))
"Unexpected content type for response")
(is (= (:body response)
"Found extensions that are not permitted: 1.9.9.9.9.9.9")))))))
(deftest cert-status-duplicate-certs
(testing "signing a certificate doesn't depend on $allow-duplicate-certs"
(doseq [bool [false true]]
(testing bool
(let [settings (assoc (testutils/ca-sandbox! cadir)
:allow-duplicate-certs bool)
test-app (-> (build-ring-handler settings "1.2.3.4")
(wrap-with-ssl-client-cert))
signed-path (ca/path-to-cert (:signeddir settings) "test-agent")]
(is (false? (fs/exists? signed-path)))
(let [response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :put
:body (body-stream "{\"desired_state\":\"signed\"}")})]
(is (true? (fs/exists? signed-path)))
(is (= 204 (:status response))
(ks/pprint-to-string response))))))))
(deftest cert-status-access-control
(testing "a request with no certificate is rejected with 403 Forbidden"
(let [test-app (build-ring-handler (testutils/ca-settings cadir) "1.2.3.4")]
(doseq [endpoint ["certificate_status" "certificate_statuses"]]
(testing endpoint
(let [response (test-app
{:uri (str "/v1/" endpoint "/test-agent")
:request-method :get})]
(is (= 403 (:status response)))
(is (= "Forbidden." (:body response))))))))
(testing "a request with a certificate not on the whitelist is rejected"
(let [settings (assoc (testutils/ca-settings cadir)
:access-control {:certificate-status
{:client-whitelist []}})
test-app (build-ring-handler settings "1.2.3.4")]
(doseq [endpoint ["certificate_status" "certificate_statuses"]]
(testing endpoint
(let [response (test-app
{:uri (str "/v1/" endpoint "/test-agent")
:request-method :get
:ssl-client-cert localhost-cert})]
(is (= 403 (:status response)))
(is (= "Forbidden." (:body response))))))))
(testing "a request with a certificate that is on the whitelist is allowed"
(doseq [whitelist [["localhost"] ["foo!" "localhost"]]]
(testing "certificate_status"
(let [settings (assoc (testutils/ca-settings cadir)
:access-control {:certificate-status
{:client-whitelist whitelist}})
test-app (build-ring-handler settings "1.2.3.4")
response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :get
:ssl-client-cert localhost-cert})]
(is (= 200 (:status response)))
(is (= test-agent-status (json/parse-string (:body response) true)))))
(testing "certificate_statuses"
(let [settings (assoc (testutils/ca-settings cadir)
:access-control {:certificate-status
{:client-whitelist whitelist}})
test-app (build-ring-handler settings "1.2.3.4")
response (test-app
{:uri "/v1/certificate_statuses/all"
:request-method :get
:ssl-client-cert localhost-cert})]
(is (= 200 (:status response)))
(is (= #{test-agent-status revoked-agent-status localhost-status}
(set (json/parse-string (:body response) true))))))))
(testing "access control can be disabled"
(let [settings (assoc (testutils/ca-settings cadir)
:access-control {:certificate-status
{:authorization-required false
:client-whitelist []}})
test-app (build-ring-handler settings "1.2.3.4")]
(testing "certificate_status"
(let [response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :get})]
(is (= 200 (:status response)))
(is (= test-agent-status (json/parse-string (:body response) true)))))
(testing "certificate_statuses"
(let [response (test-app
{:uri "/v1/certificate_statuses/all"
:request-method :get})]
(is (= 200 (:status response)))
(is (= #{test-agent-status revoked-agent-status localhost-status}
(set (json/parse-string (:body response) true)))))))))
| true | (ns puppetlabs.services.ca.certificate-authority-core-test
(:require [cheshire.core :as json]
[clojure.java.io :as io]
[clojure.test :refer :all]
[me.raynes.fs :as fs]
[puppetlabs.ssl-utils.core :as utils]
[puppetlabs.kitchensink.core :as ks]
[puppetlabs.puppetserver.certificate-authority :as ca]
[puppetlabs.services.ca.ca-testutils :as testutils]
[puppetlabs.services.ca.certificate-authority-core :refer :all]
[puppetlabs.trapperkeeper.testutils.logging :as logutils]
[ring.mock.request :as mock]
[schema.test :as schema-test]
[puppetlabs.comidi :as comidi]))
(use-fixtures :once schema-test/validate-schemas)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Utilities
(def test-resources-dir "./dev-resources/puppetlabs/services/ca/certificate_authority_core_test")
(def cadir (str test-resources-dir "/master/conf/ssl/ca"))
(def csrdir (str cadir "/requests"))
(def test-pems-dir (str test-resources-dir "/pems"))
(def autosign-files-dir (str test-resources-dir "/autosign"))
(defn test-pem-file
[pem-file-name]
(str test-pems-dir "/" pem-file-name))
(defn test-autosign-file
[autosign-file-name]
(str autosign-files-dir "/" autosign-file-name))
(def localhost-cert
(utils/pem->cert (test-pem-file "localhost-cert.pem")))
(defn build-ring-handler
[settings puppet-version]
(get-wrapped-handler
(-> (web-routes settings)
(comidi/routes->handler))
settings
""
(fn [handler]
(fn [request]
(handler request)))
puppet-version))
(defn wrap-with-ssl-client-cert
"Wrap a compojure app so all requests will include the
localhost certificate to allow access to the certificate
status endpoint."
[app]
(fn [request]
(-> request
(assoc :ssl-client-cert localhost-cert)
(app))))
(defn body-stream
[s]
(io/input-stream (.getBytes s)))
(def localhost-status
{:dns_alt_names ["DNS:djroomba.vpn.puppetlabs.net"
"DNS:localhost"
"DNS:puppet"
"DNS:puppet.vpn.puppetlabs.net"]
:fingerprint "F3:12:6C:81:AC:14:03:8D:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73"
:fingerprints {:SHA1 "DB:32:CD:AB:88:86:E0:64:0A:B7:5B:88:76:E4:60:3A:CD:9E:36:C1"
:SHA256 "PI:IP_ADDRESS:fc00:e968:6179::de52:7100END_PI:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73"
:SHA512 "58:22:32:60:CE:E7:E9:C9:CB:6A:01:52:81:ED:24:D4:69:8E:9E:CF:D8:A7:4E:6E:B5:C7:E7:18:59:5F:81:4C:93:11:77:E6:F0:40:70:5B:9C:9D:BE:22:A6:61:0B:F9:46:70:43:09:58:7E:6B:B7:5B:D9:6A:54:36:09:53:F9"
:default "PI:IP_ADDRESS:fc00:e968:6179::de52:7100END_PI:63:37:82:E4:C4:1D:21:91:55:7E:88:67:9F:EA:BD:2B:BF:1A:02:96:CE:F8:1C:73"}
:name "localhost"
:state "signed"})
(def test-agent-status
{:dns_alt_names []
:fingerprint "PI:IP_ADDRESS:fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5bEND_PI:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3"
:fingerprints {:SHA1 "EB:3D:7B:9C:85:3E:56:7A:3E:9D:1B:C4:7A:21:5A:91:F5:00:4D:9D"
:SHA256 "36:94:27:47:EA:51:EE:7C:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3"
:SHA512 "PI:IP_ADDRESS:fdf8:f53e:61e4::18END_PI:7C:51:3A:A0:78:AF:CD:E3:7C:BA:B1:D6:BB:BD:61:9E:A0:2E:D2:12:3C:D8:6E:8D:86:7C:FC:FB:4C:6B:1D:15:63:02:19:D2:F8:49:7D:1A:11:78:07:31:23:22:36:61:0C:D8:E9:F4:97:0B:67:47"
:default "PI:IP_ADDRESS:fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5bEND_PI:43:D2:EC:24:24:BB:85:CD:4A:D1:FB:BB:09:27:D9:61:59:D0:07:94:2B:2F:56:E3"}
:name "test-agent"
:state "requested"})
(def revoked-agent-status
{:dns_alt_names ["DNS:BAR"
"DNS:Baz4"
"DNS:foo"
"DNS:revoked-agent"]
:fingerprint "1C:D0:29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95"
:fingerprints {:SHA1 "38:56:67:FF:20:91:0E:85:C4:DF:CA:16:77:60:D2:BB:FB:DF:68:BB"
:SHA256 "1C:D0:29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95"
:SHA512 "1A:E3:12:14:81:50:38:19:3C:C6:42:4B:BB:09:16:0C:B1:8A:3C:EB:8C:64:9C:88:46:C6:7E:35:5E:11:0C:7A:CC:B2:47:A2:EB:57:63:5C:48:68:22:57:62:A1:46:64:B4:56:29:47:A5:46:F4:BD:9B:45:77:19:91:0B:35:39"
:default "1C:D0:29:04:9B:49:F5:ED:AB:E9:85:CC:D9:6F:20:E1:7F:84:06:8A:1D:37:19:ED:EA:24:66:C6:6E:D4:6D:95"}
:name "revoked-agent"
:state "revoked"})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Tests
(deftest crl-endpoint-test
(testing "implementation of the CRL endpoint"
(let [response (handle-get-certificate-revocation-list
{:cacrl (test-pem-file "crl.pem")})]
(is (map? response))
(is (= 200 (:status response)))
(is (= "text/plain" (get-in response [:headers "Content-Type"])))
(is (string? (:body response))))))
(deftest puppet-version-header-test
(testing "Responses contain a X-Puppet-Version header"
(let [version-number "42.42.42"
ring-app (build-ring-handler (testutils/ca-settings cadir) version-number)
;; we can just GET the /CRL endpoint, so that's an easy test here.
request (mock/request :get
"/v1/certificate_revocation_list/mynode")
response (ring-app request)]
(is (= version-number (get-in response [:headers "X-Puppet-Version"]))))))
(deftest handle-put-certificate-request!-test
(let [settings (assoc (testutils/ca-sandbox! cadir)
:allow-duplicate-certs true)
static-csr (ca/path-to-cert-request (str cadir "/requests") "test-agent")]
(logutils/with-test-logging
(testing "when autosign results in true"
(doseq [value [true
(test-autosign-file "ruby-autosign-executable")
(test-autosign-file "autosign-whitelist.conf")]]
(let [settings (assoc settings :autosign value)
csr-stream (io/input-stream static-csr)
expected-path (ca/path-to-cert (:signeddir settings) "test-agent")]
(testing "it signs the CSR, writes the certificate to disk, and
returns a 200 response with empty plaintext body"
(try
(is (false? (fs/exists? expected-path)))
(let [response (handle-put-certificate-request! "test-agent" csr-stream settings)]
(is (true? (fs/exists? expected-path)))
(is (= 200 (:status response)))
(is (= "text/plain" (get-in response [:headers "Content-Type"])))
(is (nil? (:body response))))
(finally
(fs/delete expected-path)))))))
(testing "when autosign results in false"
(doseq [value [false
(test-autosign-file "ruby-autosign-executable-false")
(test-autosign-file "autosign-whitelist.conf")]]
(let [settings (assoc settings :autosign value)
csr-stream (io/input-stream (test-pem-file "foo-agent-csr.pem"))
expected-path (ca/path-to-cert-request (:csrdir settings) "foo-agent")]
(testing "it writes the CSR to disk and returns a
200 response with empty plaintext body"
(try
(is (false? (fs/exists? expected-path)))
(let [response (handle-put-certificate-request! "foo-agent" csr-stream settings)]
(is (true? (fs/exists? expected-path)))
(is (false? (fs/exists? (ca/path-to-cert (:signeddir settings) "foo-agent"))))
(is (= 200 (:status response)))
(is (= "text/plain" (get-in response [:headers "Content-Type"])))
(is (nil? (:body response))))
(finally
(fs/delete expected-path)))))))
(testing "when $allow-duplicate-certs is false and we receive a new CSR,
return a 400 response and error message"
(let [settings (assoc settings :allow-duplicate-certs false)
csr-stream (io/input-stream static-csr)]
;; Put the duplicate in place
(fs/copy static-csr (ca/path-to-cert-request (:csrdir settings) "test-agent"))
(let [response (handle-put-certificate-request! "test-agent" csr-stream settings)]
(is (logged? #"ignoring certificate request" :error))
(is (= 400 (:status response)))
(is (true? (.contains (:body response) "ignoring certificate request"))))))
(testing "when the subject CN on a CSR does not match the hostname specified
in the URL, the response is a 400"
(let [csr-stream (io/input-stream static-csr)
response (handle-put-certificate-request! "NOT-test-agent" csr-stream settings)]
(is (= 400 (:status response)))
(is (re-matches
#"Instance name \"test-agent\" does not match requested key \"NOT-test-agent\""
(:body response)))))
(testing "when the public key on the CSR is bogus, the response is a 400"
(let [csr-with-bad-public-key (test-pem-file "luke.madstop.com-bad-public-key.pem")
csr-stream (io/input-stream csr-with-bad-public-key)
response (handle-put-certificate-request!
"luke.madstop.com" csr-stream settings)]
(is (= 400 (:status response)))
(is (= "CSR contains a public key that does not correspond to the signing key"
(:body response)))))
(testing "when the CSR has disallowed extensions on it, the response is a 400"
(let [csr-with-bad-ext (test-pem-file "meow-bad-extension.pem")
csr-stream (io/input-stream csr-with-bad-ext)
response (handle-put-certificate-request!
"meow" csr-stream settings)]
(is (= 400 (:status response)))
(is (= "Found extensions that are not permitted: 1.9.9.9.9.9.9"
(:body response))))
(let [csr-with-bad-ext (test-pem-file "woof-bad-extensions.pem")
csr-stream (io/input-stream csr-with-bad-ext)
response (handle-put-certificate-request!
"woof" csr-stream settings)]
(is (= 400 (:status response)))
(is (= "Found extensions that are not permitted: 1.9.9.9.9.9.0, 1.9.9.9.9.9.1"
(:body response)))))
(testing "when the CSR subject contains invalid characters, the response is a 400"
;; These test cases are lifted out of the puppet spec tests.
(let [bad-csrs #{{:subject "super/bad"
:csr (test-pem-file "bad-subject-name-1.pem")}
{:subject "not\neven\tkind\rof"
:csr (test-pem-file "bad-subject-name-2.pem")}
{:subject "hidden\b\b\b\b\b\bmessage"
:csr (test-pem-file "bad-subject-name-3.pem")}}]
(doseq [{:keys [subject csr]} bad-csrs]
(let [csr-stream (io/input-stream csr)
response (handle-put-certificate-request!
subject csr-stream settings)]
(is (= 400 (:status response)))
(is (= "Subject contains unprintable or non-ASCII characters"
(:body response)))))))
(testing "no wildcards allowed"
(let [csr-with-wildcard (test-pem-file "bad-subject-name-wildcard.pem")
csr-stream (io/input-stream csr-with-wildcard)
response (handle-put-certificate-request!
"foo*bar" csr-stream settings)]
(is (= 400 (:status response)))
(is (= "Subject contains a wildcard, which is not allowed: foo*bar"
(:body response)))))
(testing "a CSR w/ DNS alt-names gets a specific error response"
(let [csr (io/input-stream (test-pem-file "hostwithaltnames.pem"))
response (handle-put-certificate-request!
"hostwithaltnames" csr settings)]
(is (= 400 (:status response)))
(is (= (:body response)
(str "CSR 'hostwithaltnames' contains subject alternative names "
"(DNS:altname1, DNS:altname2, DNS:altname3), which are disallowed. "
"Use `puppet cert --allow-dns-alt-names sign hostwithaltnames` to sign this request."))))))))
(deftest certificate-status-test
(testing "read requests"
(let [test-app (-> (build-ring-handler (testutils/ca-settings cadir) "42.42.42")
(wrap-with-ssl-client-cert))]
(testing "GET /certificate_status"
(doseq [[subject status] [["localhost" localhost-status]
["test-agent" test-agent-status]
["revoked-agent" revoked-agent-status]]]
(testing subject
(let [response (test-app
{:uri (str "/v1/certificate_status/" subject)
:request-method :get})]
(is (= 200 (:status response)) (str "Error requesting status for " subject))
(is (= status (json/parse-string (:body response) true))))))
(testing "returns a 404 when a non-existent certname is given"
(let [request {:uri "/v1/certificate_status/doesnotexist"
:request-method :get}
response (test-app request)]
(is (= 404 (:status response)))))
(testing "honors 'Accept: pson' header"
(let [request {:uri "/v1/certificate_status/localhost"
:request-method :get
:headers {"accept" "pson"}}
response (test-app request)]
(is (= 200 (:status response))
(ks/pprint-to-string response))
(is (.startsWith (get-in response [:headers "Content-Type"]) "text/pson"))))
(testing "honors 'Accept: text/pson' header"
(let [request {:uri "/v1/certificate_status/localhost"
:request-method :get
:headers {"accept" "text/pson"}}
response (test-app request)]
(is (= 200 (:status response))
(ks/pprint-to-string response))
(is (.startsWith (get-in response [:headers "Content-Type"]) "text/pson"))))
(testing "honors 'Accept: application/json' header"
(let [request {:uri "/v1/certificate_status/localhost"
:request-method :get
:headers {"accept" "application/json"}}
response (test-app request)]
(is (= 200 (:status response))
(ks/pprint-to-string response))
(is (.startsWith (get-in response [:headers "Content-Type"]) "application/json")))))
(testing "GET /certificate_statuses"
(let [response (test-app
{:uri "/v1/certificate_statuses/thisisirrelevant"
:request-method :get})]
(is (= 200 (:status response)))
(is (= #{localhost-status test-agent-status revoked-agent-status}
(set (json/parse-string (:body response) true)))))
(testing "with 'Accept: pson'"
(let [response (test-app
{:uri "/v1/certificate_statuses/thisisirrelevant"
:request-method :get
:headers {"accept" "pson"}})]
(is (= 200 (:status response)))
(is (.startsWith (get-in response [:headers "Content-Type"]) "text/pson"))
(is (= #{localhost-status test-agent-status revoked-agent-status}
(set (json/parse-string (:body response) true))))))
(testing "with 'Accept: text/pson'"
(let [response (test-app
{:uri "/v1/certificate_statuses/thisisirrelevant"
:request-method :get
:headers {"accept" "text/pson"}})]
(is (= 200 (:status response)))
(is (.startsWith (get-in response [:headers "Content-Type"]) "text/pson"))
(is (= #{localhost-status test-agent-status revoked-agent-status}
(set (json/parse-string (:body response) true))))))
(testing "with 'Accept: application/json'"
(let [response (test-app
{:uri "/v1/certificate_statuses/thisisirrelevant"
:request-method :get
:headers {"accept" "application/json"}})]
(is (= 200 (:status response)))
(is (.startsWith (get-in response [:headers "Content-Type"]) "application/json"))
(is (= #{localhost-status test-agent-status revoked-agent-status}
(set (json/parse-string (:body response) true)))))))))
(testing "write requests"
(let [settings (testutils/ca-sandbox! cadir)
test-app (-> (build-ring-handler settings "42.42.42")
(wrap-with-ssl-client-cert))]
(testing "PUT"
(testing "signing a cert"
(let [signed-cert-path (ca/path-to-cert (:signeddir settings) "test-agent")]
(is (false? (fs/exists? signed-cert-path)))
(let [response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :put
:body (body-stream "{\"desired_state\":\"signed\"}")})]
(is (true? (fs/exists? signed-cert-path)))
(is (= 204 (:status response))
(ks/pprint-to-string response)))))
(testing "revoking a cert"
(let [cert (utils/pem->cert (ca/path-to-cert (:signeddir settings) "localhost"))]
(is (false? (utils/revoked? (utils/pem->crl (:cacrl settings)) cert)))
(let [response (test-app
{:uri "/v1/certificate_status/localhost"
:request-method :put
:body (body-stream "{\"desired_state\":\"revoked\"}")})]
(is (true? (utils/revoked? (utils/pem->crl (:cacrl settings)) cert)))
(is (= 204 (:status response))))))
(testing "no body results in a 400"
(let [request {:uri "/v1/certificate_status/test-agent"
:request-method :put}
response (test-app request)]
(is (= 400 (:status response)))
(is (= (:body response) "Empty request body."))))
(testing "a body that isn't JSON results in a 400"
(let [request {:body (body-stream "this is not JSON")
:uri "/v1/certificate_status/test-agent"
:request-method :put}
response (test-app request)]
(is (= 400 (:status response)))
(is (= (:body response) "Request body is not JSON."))))
(testing "invalid cert status results in a 400"
(let [request {:uri "/v1/certificate_status/test-agent"
:request-method :put
:body (body-stream "{\"desired_state\":\"bogus\"}")}
response (test-app request)]
(is (= 400 (:status response)))
(is (= (:body response)
"State bogus invalid; Must specify desired state of 'signed' or 'revoked' for host test-agent."))))
(testing "returns a 404 when a non-existent certname is given"
(let [request {:uri "/v1/certificate_status/doesnotexist"
:request-method :put
:body (body-stream "{\"desired_state\":\"signed\"}")}
response (test-app request)]
(is (= 404 (:status response)))
(is (= "text/plain; charset=UTF-8"
(get-in response [:headers "Content-Type"]))
"Unexpected content type for response")
(is (= "Invalid certificate subject." (:body response)))))
(testing "Additional error handling on PUT requests"
(let [settings (testutils/ca-sandbox! cadir)
test-app (-> (build-ring-handler settings "42.42.42")
(wrap-with-ssl-client-cert))]
(testing "Asking to revoke a cert that hasn't been signed yet is a 409"
(let [request {:uri "/v1/certificate_status/test-agent"
:request-method :put
:body (body-stream "{\"desired_state\":\"revoked\"}")}
response (test-app request)]
(is (= 409 (:status response))
(ks/pprint-to-string response))
(is (= "text/plain; charset=UTF-8"
(get-in response [:headers "Content-Type"]))
"Unexpected content type for response")
(is (= (:body response)
"Cannot revoke certificate for host test-agent without a signed certificate")
(ks/pprint-to-string response))))
(testing "trying to sign a cert that's already signed is a 409"
(let [request {:uri "/v1/certificate_status/localhost"
:request-method :put
:body (body-stream "{\"desired_state\":\"signed\"}")}
response (test-app request)]
(is (= 409 (:status response)))
(is (= "text/plain; charset=UTF-8"
(get-in response [:headers "Content-Type"]))
"Unexpected content type for response")
(is (= (:body response)
"Cannot sign certificate for host localhost without a certificate request"))))
(testing "trying to revoke a cert that's already revoked is a 204"
(let [request {:uri "/v1/certificate_status/revoked-agent"
:request-method :put
:body (body-stream "{\"desired_state\":\"revoked\"}")}
response (test-app request)]
(is (= 204 (:status response))))))))
(testing "DELETE"
(let [csr (ca/path-to-cert-request (:csrdir settings) "test-agent")]
(fs/copy (ca/path-to-cert-request csrdir "test-agent") csr)
(is (true? (fs/exists? csr)))
(is (= 204 (:status (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :delete}))))
(is (false? (fs/exists? csr))))
(let [cert (ca/path-to-cert (:signeddir settings) "revoked-agent")]
(is (true? (fs/exists? cert)))
(is (= 204 (:status (test-app
{:uri "/v1/certificate_status/revoked-agent"
:request-method :delete}))))
(is (false? (fs/exists? cert))))
(testing "returns a 404 when a non-existent certname is given"
(is (= 404 (:status (test-app
{:uri "/v1/certificate_status/doesnotexist"
:request-method :delete}))))))))
(testing "a signing request w/ a 'application/json' content-type succeeds"
(let [settings (testutils/ca-sandbox! cadir)
test-app (-> (build-ring-handler settings "42.42.42")
(wrap-with-ssl-client-cert))
signed-cert-path (ca/path-to-cert (:signeddir settings) "test-agent")]
(is (false? (fs/exists? signed-cert-path)))
(let [response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :put
:headers {"content-type" "application/json"}
:body (body-stream "{\"desired_state\":\"signed\"}")})]
(is (true? (fs/exists? signed-cert-path)))
(is (= 204 (:status response))))))
(testing "a signing request w/ a 'application/json' content-type and charset succeeds"
(let [settings (testutils/ca-sandbox! cadir)
test-app (-> (build-ring-handler settings "42.42.42")
(wrap-with-ssl-client-cert))
signed-cert-path (ca/path-to-cert (:signeddir settings) "test-agent")]
(is (false? (fs/exists? signed-cert-path)))
(let [response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :put
:headers {"content-type"
"application/json; charset=UTF-8"}
:body (body-stream "{\"desired_state\":\"signed\"}")})]
(is (true? (fs/exists? signed-cert-path)))
(is (= 204 (:status response))))))
(testing "a signing request w/ a 'text/pson' content-type succeeds"
(let [settings (testutils/ca-sandbox! cadir)
test-app (-> (build-ring-handler settings "42.42.42")
(wrap-with-ssl-client-cert))
signed-cert-path (ca/path-to-cert (:signeddir settings) "test-agent")]
(is (false? (fs/exists? signed-cert-path)))
(let [response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :put
:headers {"content-type" "text/pson"}
:body (body-stream "{\"desired_state\":\"signed\"}")})]
(is (true? (fs/exists? signed-cert-path)))
(is (= 204 (:status response))))))
(testing "a signing request w/ a 'text/pson' content-type and charset succeeds"
(let [settings (testutils/ca-sandbox! cadir)
test-app (-> (build-ring-handler settings "42.42.42")
(wrap-with-ssl-client-cert))
signed-cert-path (ca/path-to-cert (:signeddir settings) "test-agent")]
(is (false? (fs/exists? signed-cert-path)))
(let [response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :put
:headers {"content-type" "text/pson; charset=UTF-8"}
:body (body-stream "{\"desired_state\":\"signed\"}")})]
(is (true? (fs/exists? signed-cert-path)))
(is (= 204 (:status response))))))
(testing "a signing request w/ a 'pson' content-type succeeds"
(let [settings (testutils/ca-sandbox! cadir)
test-app (-> (build-ring-handler settings "42.42.42")
(wrap-with-ssl-client-cert))
signed-cert-path (ca/path-to-cert (:signeddir settings) "test-agent")]
(is (false? (fs/exists? signed-cert-path)))
(let [response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :put
:headers {"content-type" "pson"}
:body (body-stream "{\"desired_state\":\"signed\"}")})]
(is (true? (fs/exists? signed-cert-path)))
(is (= 204 (:status response))))))
(testing "a signing request w/ a 'pson' content-type and charset succeeds"
(let [settings (testutils/ca-sandbox! cadir)
test-app (-> (build-ring-handler settings "42.42.42")
(wrap-with-ssl-client-cert))
signed-cert-path (ca/path-to-cert (:signeddir settings) "test-agent")]
(is (false? (fs/exists? signed-cert-path)))
(let [response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :put
:headers {"content-type" "pson; charset=UTF-8"}
:body (body-stream "{\"desired_state\":\"signed\"}")})]
(is (true? (fs/exists? signed-cert-path)))
(is (= 204 (:status response))))))
(testing "a signing request w/ a bogus content-type header results in a HTTP 415"
(let [settings (testutils/ca-sandbox! cadir)
test-app (-> (build-ring-handler settings "42.42.42")
(wrap-with-ssl-client-cert))
response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :put
:headers {"content-type" "bogus"}
:body (body-stream "{\"desired_state\":\"signed\"}")})]
(is (= 415 (:status response))
(ks/pprint-to-string response))
(is (= (:body response) "Unsupported media type.")))))
(deftest cert-status-invalid-csrs
(testing "Asking /certificate_status to sign invalid CSRs"
(let [settings (assoc (testutils/ca-settings cadir)
:csrdir (str test-resources-dir "/alternate-csrdir"))
test-app (-> (build-ring-handler settings "42.42.42")
(wrap-with-ssl-client-cert))]
(testing "one example - a CSR with DNS alt-names"
(let [request {:uri "/v1/certificate_status/hostwithaltnames"
:request-method :put
:body (body-stream "{\"desired_state\":\"signed\"}")}
response (test-app request)]
(is (= 409 (:status response))
(ks/pprint-to-string response))
(is (= "text/plain; charset=UTF-8"
(get-in response [:headers "Content-Type"]))
"Unexpected content type for response")
(is (= (:body response)
(str "CSR 'hostwithaltnames' contains subject alternative names "
"(DNS:altname1, DNS:altname2, DNS:altname3), which are disallowed. "
"Use `puppet cert --allow-dns-alt-names sign hostwithaltnames` "
"to sign this request.")))))
(testing "another example - a CSR with an invalid extension"
(let [request {:uri "/v1/certificate_status/meow"
:request-method :put
:body (body-stream "{\"desired_state\":\"signed\"}")}
response (test-app request)]
(is (= 409 (:status response))
(ks/pprint-to-string response))
(is (= "text/plain; charset=UTF-8"
(get-in response [:headers "Content-Type"]))
"Unexpected content type for response")
(is (= (:body response)
"Found extensions that are not permitted: 1.9.9.9.9.9.9")))))))
(deftest cert-status-duplicate-certs
(testing "signing a certificate doesn't depend on $allow-duplicate-certs"
(doseq [bool [false true]]
(testing bool
(let [settings (assoc (testutils/ca-sandbox! cadir)
:allow-duplicate-certs bool)
test-app (-> (build-ring-handler settings "1.2.3.4")
(wrap-with-ssl-client-cert))
signed-path (ca/path-to-cert (:signeddir settings) "test-agent")]
(is (false? (fs/exists? signed-path)))
(let [response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :put
:body (body-stream "{\"desired_state\":\"signed\"}")})]
(is (true? (fs/exists? signed-path)))
(is (= 204 (:status response))
(ks/pprint-to-string response))))))))
(deftest cert-status-access-control
(testing "a request with no certificate is rejected with 403 Forbidden"
(let [test-app (build-ring-handler (testutils/ca-settings cadir) "1.2.3.4")]
(doseq [endpoint ["certificate_status" "certificate_statuses"]]
(testing endpoint
(let [response (test-app
{:uri (str "/v1/" endpoint "/test-agent")
:request-method :get})]
(is (= 403 (:status response)))
(is (= "Forbidden." (:body response))))))))
(testing "a request with a certificate not on the whitelist is rejected"
(let [settings (assoc (testutils/ca-settings cadir)
:access-control {:certificate-status
{:client-whitelist []}})
test-app (build-ring-handler settings "1.2.3.4")]
(doseq [endpoint ["certificate_status" "certificate_statuses"]]
(testing endpoint
(let [response (test-app
{:uri (str "/v1/" endpoint "/test-agent")
:request-method :get
:ssl-client-cert localhost-cert})]
(is (= 403 (:status response)))
(is (= "Forbidden." (:body response))))))))
(testing "a request with a certificate that is on the whitelist is allowed"
(doseq [whitelist [["localhost"] ["foo!" "localhost"]]]
(testing "certificate_status"
(let [settings (assoc (testutils/ca-settings cadir)
:access-control {:certificate-status
{:client-whitelist whitelist}})
test-app (build-ring-handler settings "1.2.3.4")
response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :get
:ssl-client-cert localhost-cert})]
(is (= 200 (:status response)))
(is (= test-agent-status (json/parse-string (:body response) true)))))
(testing "certificate_statuses"
(let [settings (assoc (testutils/ca-settings cadir)
:access-control {:certificate-status
{:client-whitelist whitelist}})
test-app (build-ring-handler settings "1.2.3.4")
response (test-app
{:uri "/v1/certificate_statuses/all"
:request-method :get
:ssl-client-cert localhost-cert})]
(is (= 200 (:status response)))
(is (= #{test-agent-status revoked-agent-status localhost-status}
(set (json/parse-string (:body response) true))))))))
(testing "access control can be disabled"
(let [settings (assoc (testutils/ca-settings cadir)
:access-control {:certificate-status
{:authorization-required false
:client-whitelist []}})
test-app (build-ring-handler settings "1.2.3.4")]
(testing "certificate_status"
(let [response (test-app
{:uri "/v1/certificate_status/test-agent"
:request-method :get})]
(is (= 200 (:status response)))
(is (= test-agent-status (json/parse-string (:body response) true)))))
(testing "certificate_statuses"
(let [response (test-app
{:uri "/v1/certificate_statuses/all"
:request-method :get})]
(is (= 200 (:status response)))
(is (= #{test-agent-status revoked-agent-status localhost-status}
(set (json/parse-string (:body response) true)))))))))
|
[
{
"context": " (db/create! user1)\n bad-email \"random@example.com\"\n bad-password \"wrongpassword\"\n {:k",
"end": 1217,
"score": 0.9999249577522278,
"start": 1199,
"tag": "EMAIL",
"value": "random@example.com"
},
{
"context": "ail \"random@example.com\"\n bad-password \"wrongpassword\"\n {:keys [email password]} user1]\n\n (test",
"end": 1254,
"score": 0.9994706511497498,
"start": 1241,
"tag": "PASSWORD",
"value": "wrongpassword"
},
{
"context": "(is (:email userdata))\n (is (= nil (:password userdata))))))\n",
"end": 1935,
"score": 0.8688887357711792,
"start": 1927,
"tag": "PASSWORD",
"value": "userdata"
}
] | test/clj/villagebook/user/models_test.clj | sathia27/villagebook | 0 | (ns villagebook.user.models-test
(:require [buddy.auth :refer [authenticated?]]
[villagebook.fixtures :refer [setup-once wrap-transaction]]
[villagebook.factory :refer [user1 user2]]
[villagebook.user.db :as db]
[villagebook.user.models :as models]
[clojure.test :refer :all]))
(use-fixtures :once setup-once)
(use-fixtures :each wrap-transaction)
(deftest create-user-test
(testing "Creating a user."
(let [message (models/create! user1)
email (get-in message [:success :email])]
(is email)
(is (not (empty? (db/retrieve-by-email email)))))))
(deftest getting-token-test
(let [user (db/create! user1)
{:keys [email password]} user1]
(testing "Getting a token for user."
(let [message (models/get-token email password)
token (get-in message [:success :token])
;; make dummy request with token for buddy auth
header (str "Token " token)
request {:headers {"authorization" header} :identity {:user email}}]
(is (authenticated? request))))))
(deftest invalid-getting-token-tests
(let [user (db/create! user1)
bad-email "random@example.com"
bad-password "wrongpassword"
{:keys [email password]} user1]
(testing "Getting token with invalid email (does not exist)"
(let [message (models/get-token bad-email bad-password)
error (:error message)]
(is (= error "Email not found"))))
(testing "Getting token with invalid password."
(let [message (models/get-token email bad-password)
error (:error message)]
(is (= error "Invalid password"))))))
(deftest retrieve-user-tests
(testing "Retrieving user by email"
(let [user (db/create! user1)
email (:email user1)
userdata (models/retrieve-by-email email)]
(is (:email userdata))
(is (= nil (:password userdata))))))
| 5790 | (ns villagebook.user.models-test
(:require [buddy.auth :refer [authenticated?]]
[villagebook.fixtures :refer [setup-once wrap-transaction]]
[villagebook.factory :refer [user1 user2]]
[villagebook.user.db :as db]
[villagebook.user.models :as models]
[clojure.test :refer :all]))
(use-fixtures :once setup-once)
(use-fixtures :each wrap-transaction)
(deftest create-user-test
(testing "Creating a user."
(let [message (models/create! user1)
email (get-in message [:success :email])]
(is email)
(is (not (empty? (db/retrieve-by-email email)))))))
(deftest getting-token-test
(let [user (db/create! user1)
{:keys [email password]} user1]
(testing "Getting a token for user."
(let [message (models/get-token email password)
token (get-in message [:success :token])
;; make dummy request with token for buddy auth
header (str "Token " token)
request {:headers {"authorization" header} :identity {:user email}}]
(is (authenticated? request))))))
(deftest invalid-getting-token-tests
(let [user (db/create! user1)
bad-email "<EMAIL>"
bad-password "<PASSWORD>"
{:keys [email password]} user1]
(testing "Getting token with invalid email (does not exist)"
(let [message (models/get-token bad-email bad-password)
error (:error message)]
(is (= error "Email not found"))))
(testing "Getting token with invalid password."
(let [message (models/get-token email bad-password)
error (:error message)]
(is (= error "Invalid password"))))))
(deftest retrieve-user-tests
(testing "Retrieving user by email"
(let [user (db/create! user1)
email (:email user1)
userdata (models/retrieve-by-email email)]
(is (:email userdata))
(is (= nil (:password <PASSWORD>))))))
| true | (ns villagebook.user.models-test
(:require [buddy.auth :refer [authenticated?]]
[villagebook.fixtures :refer [setup-once wrap-transaction]]
[villagebook.factory :refer [user1 user2]]
[villagebook.user.db :as db]
[villagebook.user.models :as models]
[clojure.test :refer :all]))
(use-fixtures :once setup-once)
(use-fixtures :each wrap-transaction)
(deftest create-user-test
(testing "Creating a user."
(let [message (models/create! user1)
email (get-in message [:success :email])]
(is email)
(is (not (empty? (db/retrieve-by-email email)))))))
(deftest getting-token-test
(let [user (db/create! user1)
{:keys [email password]} user1]
(testing "Getting a token for user."
(let [message (models/get-token email password)
token (get-in message [:success :token])
;; make dummy request with token for buddy auth
header (str "Token " token)
request {:headers {"authorization" header} :identity {:user email}}]
(is (authenticated? request))))))
(deftest invalid-getting-token-tests
(let [user (db/create! user1)
bad-email "PI:EMAIL:<EMAIL>END_PI"
bad-password "PI:PASSWORD:<PASSWORD>END_PI"
{:keys [email password]} user1]
(testing "Getting token with invalid email (does not exist)"
(let [message (models/get-token bad-email bad-password)
error (:error message)]
(is (= error "Email not found"))))
(testing "Getting token with invalid password."
(let [message (models/get-token email bad-password)
error (:error message)]
(is (= error "Invalid password"))))))
(deftest retrieve-user-tests
(testing "Retrieving user by email"
(let [user (db/create! user1)
email (:email user1)
userdata (models/retrieve-by-email email)]
(is (:email userdata))
(is (= nil (:password PI:PASSWORD:<PASSWORD>END_PI))))))
|
[
{
"context": "\"\"\n :name \"dat-name\"\n :require",
"end": 1942,
"score": 0.9758626818656921,
"start": 1934,
"tag": "USERNAME",
"value": "dat-name"
},
{
"context": " :placeholder \"**********\"\n :name ",
"end": 2232,
"score": 0.7676670551300049,
"start": 2232,
"tag": "PASSWORD",
"value": ""
}
] | src/zwitscher/views/signin.clj | dak0rn/Zwitscher | 0 | ;; signin.clj - Signin route
(ns zwitscher.views.signin
(:require [hiccup.core :refer [h]]
[ring.util.anti-forgery :refer [anti-forgery-field]]
[hiccup.form :refer [form-to]]
[zwitscher.views.partials.document :refer [document]]
[zwitscher.views.partials.navigation :as nav]))
(defn
render-signin
"Renders the sign in page"
{:added "0.1.0"}
[& {:keys [invalid name-missing password-missing]}]
(document {:title "Sign in to Zwitscher"}
(nav/empty)
[:main.container
[:div.panel.sign-panel
[:div.panel-heading
"Sign in to " [:span.zwitscher "Zwitscher"]
]
(when (or invalid name-missing password-missing)
[:div.panel-block
(when invalid [:div.notification.is-warning
[:a.delete {:href "/signin"} ]
"Your credentials must have been invalid. Please try again."
])
(when name-missing [:div.notification.is-warning
[:a.delete {:href "/signin"} ]
"Please enter your user name"
])
(when password-missing [:div.notification.is-warning
[:a.delete {:href "/signin"} ]
"Please enter your password"
])
])
[:div.panel-block
(form-to ["POST" "/signin/do"]
(anti-forgery-field)
[:label.label "Your username"]
[:div.control
[:input.input {:type "text"
:placeholder ""
:name "dat-name"
:required true}]
]
[:label.label "Your password"]
[:div.control
[:input.input {:type "password"
:placeholder "**********"
:name "dat-pass"
:required true
}]
]
[:div.sign-bar
[:button.button.is-primary "Sign in"]
[:a.button.is-link.mr-15 {:href "/signup"} "Don't have an account yet?"]
]
[:div.is-clearfix])
]
]
]
))
| 79173 | ;; signin.clj - Signin route
(ns zwitscher.views.signin
(:require [hiccup.core :refer [h]]
[ring.util.anti-forgery :refer [anti-forgery-field]]
[hiccup.form :refer [form-to]]
[zwitscher.views.partials.document :refer [document]]
[zwitscher.views.partials.navigation :as nav]))
(defn
render-signin
"Renders the sign in page"
{:added "0.1.0"}
[& {:keys [invalid name-missing password-missing]}]
(document {:title "Sign in to Zwitscher"}
(nav/empty)
[:main.container
[:div.panel.sign-panel
[:div.panel-heading
"Sign in to " [:span.zwitscher "Zwitscher"]
]
(when (or invalid name-missing password-missing)
[:div.panel-block
(when invalid [:div.notification.is-warning
[:a.delete {:href "/signin"} ]
"Your credentials must have been invalid. Please try again."
])
(when name-missing [:div.notification.is-warning
[:a.delete {:href "/signin"} ]
"Please enter your user name"
])
(when password-missing [:div.notification.is-warning
[:a.delete {:href "/signin"} ]
"Please enter your password"
])
])
[:div.panel-block
(form-to ["POST" "/signin/do"]
(anti-forgery-field)
[:label.label "Your username"]
[:div.control
[:input.input {:type "text"
:placeholder ""
:name "dat-name"
:required true}]
]
[:label.label "Your password"]
[:div.control
[:input.input {:type "password"
:placeholder "<PASSWORD>**********"
:name "dat-pass"
:required true
}]
]
[:div.sign-bar
[:button.button.is-primary "Sign in"]
[:a.button.is-link.mr-15 {:href "/signup"} "Don't have an account yet?"]
]
[:div.is-clearfix])
]
]
]
))
| true | ;; signin.clj - Signin route
(ns zwitscher.views.signin
(:require [hiccup.core :refer [h]]
[ring.util.anti-forgery :refer [anti-forgery-field]]
[hiccup.form :refer [form-to]]
[zwitscher.views.partials.document :refer [document]]
[zwitscher.views.partials.navigation :as nav]))
(defn
render-signin
"Renders the sign in page"
{:added "0.1.0"}
[& {:keys [invalid name-missing password-missing]}]
(document {:title "Sign in to Zwitscher"}
(nav/empty)
[:main.container
[:div.panel.sign-panel
[:div.panel-heading
"Sign in to " [:span.zwitscher "Zwitscher"]
]
(when (or invalid name-missing password-missing)
[:div.panel-block
(when invalid [:div.notification.is-warning
[:a.delete {:href "/signin"} ]
"Your credentials must have been invalid. Please try again."
])
(when name-missing [:div.notification.is-warning
[:a.delete {:href "/signin"} ]
"Please enter your user name"
])
(when password-missing [:div.notification.is-warning
[:a.delete {:href "/signin"} ]
"Please enter your password"
])
])
[:div.panel-block
(form-to ["POST" "/signin/do"]
(anti-forgery-field)
[:label.label "Your username"]
[:div.control
[:input.input {:type "text"
:placeholder ""
:name "dat-name"
:required true}]
]
[:label.label "Your password"]
[:div.control
[:input.input {:type "password"
:placeholder "PI:PASSWORD:<PASSWORD>END_PI**********"
:name "dat-pass"
:required true
}]
]
[:div.sign-bar
[:button.button.is-primary "Sign in"]
[:a.button.is-link.mr-15 {:href "/signup"} "Don't have an account yet?"]
]
[:div.is-clearfix])
]
]
]
))
|
[
{
"context": "on %1 %2 :address)}])\n\n(def people [{:id 1 :name \"Tracey Davidson\" :age 43 :address \"5512 Pockrus Page Rd\"}\n ",
"end": 963,
"score": 0.9998613595962524,
"start": 948,
"tag": "NAME",
"value": "Tracey Davidson"
},
{
"context": "5512 Pockrus Page Rd\"}\n {:id 2 :name \"Pierre de Wiles\" :age 41 :address \"358 Fermat's St\"}\n ",
"end": 1048,
"score": 0.9998445510864258,
"start": 1033,
"tag": "NAME",
"value": "Pierre de Wiles"
},
{
"context": "ess \"358 Fermat's St\"}\n {:id 3 :name \"Lydia Weaver\" :age 23 :address \"1251 Fourth St\"}\n ",
"end": 1125,
"score": 0.9998546242713928,
"start": 1113,
"tag": "NAME",
"value": "Lydia Weaver"
},
{
"context": "ress \"1251 Fourth St\"}\n {:id 4 :name \"Willie Reynolds\" :age 26 :address \"2984 Beechcrest Rd\"}\n ",
"end": 1204,
"score": 0.9998608827590942,
"start": 1189,
"tag": "NAME",
"value": "Willie Reynolds"
},
{
"context": " \"2984 Beechcrest Rd\"}\n {:id 5 :name \"Richard Perelman\" :age 51 :address \"2003 Poincaré Ricci Rd\"}\n ",
"end": 1288,
"score": 0.9998531341552734,
"start": 1272,
"tag": "NAME",
"value": "Richard Perelman"
},
{
"context": "03 Poincaré Ricci Rd\"}\n {:id 6 :name \"Srinivasa Ramanujan\" :age 32 :address \"1729 Taxi Cab St\"}\n ",
"end": 1379,
"score": 0.999884843826294,
"start": 1360,
"tag": "NAME",
"value": "Srinivasa Ramanujan"
},
{
"context": "ss \"1729 Taxi Cab St\"}\n {:id 7 :name \"Zoe Cruz\" :age 31 :address \"8593 Pine Rd\"}\n {:",
"end": 1453,
"score": 0.9998620748519897,
"start": 1445,
"tag": "NAME",
"value": "Zoe Cruz"
},
{
"context": "ddress \"8593 Pine Rd\"}\n {:id 8 :name \"Adam Turing\" :age 41 :address \"1936 Automata Lane\"}])\n\n(defn ",
"end": 1526,
"score": 0.999849796295166,
"start": 1515,
"tag": "NAME",
"value": "Adam Turing"
}
] | src/ppl/common.cljs | jdhorwitz/cljs-ppl | 0 | (ns ppl.common)
(def form-style {:label-col {:span 6}
:wrapper-col {:span 13}})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Definitions and functions for the datatable
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def pagination {:show-size-changer true
:page-size-options ["5" "10" "20"]
:show-total #(str "Total: " % " users")})
(defn comparison [data1 data2 field]
(compare (get (js->clj data1 :keywordize-keys true) field)
(get (js->clj data2 :keywordize-keys true) field)))
;; we need to use dataIndex instead of data-index, see README.md
(def columns [{:title "Name" :dataIndex "name" :sorter #(comparison %1 %2 :name)}
{:title "Age" :dataIndex "age" :sorter #(comparison %1 %2 :age)}
{:title "Address" :dataIndex "address" :sorter #(comparison %1 %2 :address)}])
(def people [{:id 1 :name "Tracey Davidson" :age 43 :address "5512 Pockrus Page Rd"}
{:id 2 :name "Pierre de Wiles" :age 41 :address "358 Fermat's St"}
{:id 3 :name "Lydia Weaver" :age 23 :address "1251 Fourth St"}
{:id 4 :name "Willie Reynolds" :age 26 :address "2984 Beechcrest Rd"}
{:id 5 :name "Richard Perelman" :age 51 :address "2003 Poincaré Ricci Rd"}
{:id 6 :name "Srinivasa Ramanujan" :age 32 :address "1729 Taxi Cab St"}
{:id 7 :name "Zoe Cruz" :age 31 :address "8593 Pine Rd"}
{:id 8 :name "Adam Turing" :age 41 :address "1936 Automata Lane"}])
(defn set-locale [country locale-atom]
(let [locale-val (if (= country "zh_CN")
nil country)]
(reset! locale-atom locale-val)))
| 119410 | (ns ppl.common)
(def form-style {:label-col {:span 6}
:wrapper-col {:span 13}})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Definitions and functions for the datatable
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def pagination {:show-size-changer true
:page-size-options ["5" "10" "20"]
:show-total #(str "Total: " % " users")})
(defn comparison [data1 data2 field]
(compare (get (js->clj data1 :keywordize-keys true) field)
(get (js->clj data2 :keywordize-keys true) field)))
;; we need to use dataIndex instead of data-index, see README.md
(def columns [{:title "Name" :dataIndex "name" :sorter #(comparison %1 %2 :name)}
{:title "Age" :dataIndex "age" :sorter #(comparison %1 %2 :age)}
{:title "Address" :dataIndex "address" :sorter #(comparison %1 %2 :address)}])
(def people [{:id 1 :name "<NAME>" :age 43 :address "5512 Pockrus Page Rd"}
{:id 2 :name "<NAME>" :age 41 :address "358 Fermat's St"}
{:id 3 :name "<NAME>" :age 23 :address "1251 Fourth St"}
{:id 4 :name "<NAME>" :age 26 :address "2984 Beechcrest Rd"}
{:id 5 :name "<NAME>" :age 51 :address "2003 Poincaré Ricci Rd"}
{:id 6 :name "<NAME>" :age 32 :address "1729 Taxi Cab St"}
{:id 7 :name "<NAME>" :age 31 :address "8593 Pine Rd"}
{:id 8 :name "<NAME>" :age 41 :address "1936 Automata Lane"}])
(defn set-locale [country locale-atom]
(let [locale-val (if (= country "zh_CN")
nil country)]
(reset! locale-atom locale-val)))
| true | (ns ppl.common)
(def form-style {:label-col {:span 6}
:wrapper-col {:span 13}})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Definitions and functions for the datatable
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def pagination {:show-size-changer true
:page-size-options ["5" "10" "20"]
:show-total #(str "Total: " % " users")})
(defn comparison [data1 data2 field]
(compare (get (js->clj data1 :keywordize-keys true) field)
(get (js->clj data2 :keywordize-keys true) field)))
;; we need to use dataIndex instead of data-index, see README.md
(def columns [{:title "Name" :dataIndex "name" :sorter #(comparison %1 %2 :name)}
{:title "Age" :dataIndex "age" :sorter #(comparison %1 %2 :age)}
{:title "Address" :dataIndex "address" :sorter #(comparison %1 %2 :address)}])
(def people [{:id 1 :name "PI:NAME:<NAME>END_PI" :age 43 :address "5512 Pockrus Page Rd"}
{:id 2 :name "PI:NAME:<NAME>END_PI" :age 41 :address "358 Fermat's St"}
{:id 3 :name "PI:NAME:<NAME>END_PI" :age 23 :address "1251 Fourth St"}
{:id 4 :name "PI:NAME:<NAME>END_PI" :age 26 :address "2984 Beechcrest Rd"}
{:id 5 :name "PI:NAME:<NAME>END_PI" :age 51 :address "2003 Poincaré Ricci Rd"}
{:id 6 :name "PI:NAME:<NAME>END_PI" :age 32 :address "1729 Taxi Cab St"}
{:id 7 :name "PI:NAME:<NAME>END_PI" :age 31 :address "8593 Pine Rd"}
{:id 8 :name "PI:NAME:<NAME>END_PI" :age 41 :address "1936 Automata Lane"}])
(defn set-locale [country locale-atom]
(let [locale-val (if (= country "zh_CN")
nil country)]
(reset! locale-atom locale-val)))
|
[
{
"context": ")\n :tax-id \"012.345.678-90\"\n :name \"Iron Bank S.A.\",\n :expiration 123456789,\n :fine 2.5,",
"end": 729,
"score": 0.9480627775192261,
"start": 716,
"tag": "NAME",
"value": "Iron Bank S.A"
},
{
"context": "tax-id \"20.018.183/0001-80\"\n :description \"Tony Stark's Suit\"\n :amount (:amount preview)\n ",
"end": 1475,
"score": 0.7290557622909546,
"start": 1465,
"tag": "NAME",
"value": "Tony Stark"
}
] | test/starkbank/brcode_payment_test.clj | starkbank/sdk-clojure | 5 | (ns starkbank.brcode-payment-test
(:use [clojure.test])
(:require [starkbank.brcode-payment :as payment]
[starkbank.brcode-payment.log :as log]
[starkbank.invoice :as invoice]
[starkbank.brcode-preview :as preview]
[starkbank.user-test :as user]
[clojure.java.io :as io]
[starkbank.utils.date :as date]
[starkbank.utils.page :as page]))
(deftest create-get-brcode-payments
(testing "create, get, pdf and update brcode payments"
(user/set-test-project)
(def invoices (invoice/create
[{
:amount 40000
:due (date/future-datetime 5)
:tax-id "012.345.678-90"
:name "Iron Bank S.A.",
:expiration 123456789,
:fine 2.5,
:interest 1.3,
:discounts [
{
:percentage 5
:due (date/future-datetime 2)
}
{
:percentage 3
:due (date/future-datetime 4)
}
]
:descriptions [
{
:key "Product X"
:value "big"
}
]
:tags [
"War supply",
"Invoice #1234"
]
}]))
(def invoice (first invoices))
(def preview (first (preview/query {:brcodes [(:brcode invoice)]})))
(def payments (payment/create
[{
:brcode (:brcode invoice)
:tax-id "20.018.183/0001-80"
:description "Tony Stark's Suit"
:amount (:amount preview)
:scheduled (date/future-datetime 3)
:tags ["Stark" "Suit"]
}]))
(payment/get (:id (first payments)))))
(deftest query-pdf-cancel-brcode-payments
(testing "query brcode payments"
(user/set-test-project)
(def payments (take 200 (payment/query {:limit 2 :status "created"})))
(is (= 2 (count payments)))
(def file-name "temp/brcode-payment.pdf")
(io/make-parents file-name)
(io/copy (payment/pdf (:id (first payments))) (io/file file-name)))
(payment/update (:id (first payments)) {:status "canceled"}))
(deftest page-brcode-payment
(testing "page brcode-payment"
(user/set-test-project)
(def get-page (fn [params] (payment/page params)))
(def ids (page/get-ids get-page 2 {:limit 2}))
(is (= 4 (count ids)))))
(deftest query-get-brcode-payment-logs
(testing "query and get brcode payment logs"
(user/set-test-project)
(def payment-logs (log/query {:limit 5}))
(is (= 5 (count payment-logs)))
(def payment-log (log/get (:id (first payment-logs))))
(is (not (nil? (:id payment-log))))
(is (not (nil? (:errors payment-log))))
(is (string? (:created payment-log)))
(is (map? (:payment payment-log)))))
(deftest page-brcode-payment-logs
(testing "page brcode-payment-logs"
(user/set-test-project)
(def get-page (fn [params] (log/page params)))
(def ids (page/get-ids get-page 2 {:limit 2}))
(is (= 4 (count ids)))))
| 32390 | (ns starkbank.brcode-payment-test
(:use [clojure.test])
(:require [starkbank.brcode-payment :as payment]
[starkbank.brcode-payment.log :as log]
[starkbank.invoice :as invoice]
[starkbank.brcode-preview :as preview]
[starkbank.user-test :as user]
[clojure.java.io :as io]
[starkbank.utils.date :as date]
[starkbank.utils.page :as page]))
(deftest create-get-brcode-payments
(testing "create, get, pdf and update brcode payments"
(user/set-test-project)
(def invoices (invoice/create
[{
:amount 40000
:due (date/future-datetime 5)
:tax-id "012.345.678-90"
:name "<NAME>.",
:expiration 123456789,
:fine 2.5,
:interest 1.3,
:discounts [
{
:percentage 5
:due (date/future-datetime 2)
}
{
:percentage 3
:due (date/future-datetime 4)
}
]
:descriptions [
{
:key "Product X"
:value "big"
}
]
:tags [
"War supply",
"Invoice #1234"
]
}]))
(def invoice (first invoices))
(def preview (first (preview/query {:brcodes [(:brcode invoice)]})))
(def payments (payment/create
[{
:brcode (:brcode invoice)
:tax-id "20.018.183/0001-80"
:description "<NAME>'s Suit"
:amount (:amount preview)
:scheduled (date/future-datetime 3)
:tags ["Stark" "Suit"]
}]))
(payment/get (:id (first payments)))))
(deftest query-pdf-cancel-brcode-payments
(testing "query brcode payments"
(user/set-test-project)
(def payments (take 200 (payment/query {:limit 2 :status "created"})))
(is (= 2 (count payments)))
(def file-name "temp/brcode-payment.pdf")
(io/make-parents file-name)
(io/copy (payment/pdf (:id (first payments))) (io/file file-name)))
(payment/update (:id (first payments)) {:status "canceled"}))
(deftest page-brcode-payment
(testing "page brcode-payment"
(user/set-test-project)
(def get-page (fn [params] (payment/page params)))
(def ids (page/get-ids get-page 2 {:limit 2}))
(is (= 4 (count ids)))))
(deftest query-get-brcode-payment-logs
(testing "query and get brcode payment logs"
(user/set-test-project)
(def payment-logs (log/query {:limit 5}))
(is (= 5 (count payment-logs)))
(def payment-log (log/get (:id (first payment-logs))))
(is (not (nil? (:id payment-log))))
(is (not (nil? (:errors payment-log))))
(is (string? (:created payment-log)))
(is (map? (:payment payment-log)))))
(deftest page-brcode-payment-logs
(testing "page brcode-payment-logs"
(user/set-test-project)
(def get-page (fn [params] (log/page params)))
(def ids (page/get-ids get-page 2 {:limit 2}))
(is (= 4 (count ids)))))
| true | (ns starkbank.brcode-payment-test
(:use [clojure.test])
(:require [starkbank.brcode-payment :as payment]
[starkbank.brcode-payment.log :as log]
[starkbank.invoice :as invoice]
[starkbank.brcode-preview :as preview]
[starkbank.user-test :as user]
[clojure.java.io :as io]
[starkbank.utils.date :as date]
[starkbank.utils.page :as page]))
(deftest create-get-brcode-payments
(testing "create, get, pdf and update brcode payments"
(user/set-test-project)
(def invoices (invoice/create
[{
:amount 40000
:due (date/future-datetime 5)
:tax-id "012.345.678-90"
:name "PI:NAME:<NAME>END_PI.",
:expiration 123456789,
:fine 2.5,
:interest 1.3,
:discounts [
{
:percentage 5
:due (date/future-datetime 2)
}
{
:percentage 3
:due (date/future-datetime 4)
}
]
:descriptions [
{
:key "Product X"
:value "big"
}
]
:tags [
"War supply",
"Invoice #1234"
]
}]))
(def invoice (first invoices))
(def preview (first (preview/query {:brcodes [(:brcode invoice)]})))
(def payments (payment/create
[{
:brcode (:brcode invoice)
:tax-id "20.018.183/0001-80"
:description "PI:NAME:<NAME>END_PI's Suit"
:amount (:amount preview)
:scheduled (date/future-datetime 3)
:tags ["Stark" "Suit"]
}]))
(payment/get (:id (first payments)))))
(deftest query-pdf-cancel-brcode-payments
(testing "query brcode payments"
(user/set-test-project)
(def payments (take 200 (payment/query {:limit 2 :status "created"})))
(is (= 2 (count payments)))
(def file-name "temp/brcode-payment.pdf")
(io/make-parents file-name)
(io/copy (payment/pdf (:id (first payments))) (io/file file-name)))
(payment/update (:id (first payments)) {:status "canceled"}))
(deftest page-brcode-payment
(testing "page brcode-payment"
(user/set-test-project)
(def get-page (fn [params] (payment/page params)))
(def ids (page/get-ids get-page 2 {:limit 2}))
(is (= 4 (count ids)))))
(deftest query-get-brcode-payment-logs
(testing "query and get brcode payment logs"
(user/set-test-project)
(def payment-logs (log/query {:limit 5}))
(is (= 5 (count payment-logs)))
(def payment-log (log/get (:id (first payment-logs))))
(is (not (nil? (:id payment-log))))
(is (not (nil? (:errors payment-log))))
(is (string? (:created payment-log)))
(is (map? (:payment payment-log)))))
(deftest page-brcode-payment-logs
(testing "page brcode-payment-logs"
(user/set-test-project)
(def get-page (fn [params] (log/page params)))
(def ids (page/get-ids get-page 2 {:limit 2}))
(is (= 4 (count ids)))))
|
[
{
"context": "45\"}]\n :restaurant/location {:location/addres \"Rua Ribeirão Claro\"\n :location/number 192\n ",
"end": 1760,
"score": 0.9935333728790283,
"start": 1742,
"tag": "NAME",
"value": "Rua Ribeirão Claro"
},
{
"context": " :location/neighborhood \"Vila Olimpia\"\n :location/city",
"end": 1863,
"score": 0.6210634112358093,
"start": 1860,
"tag": "NAME",
"value": "ila"
},
{
"context": " :location/neighborhood \"Vila Olimpia\"\n :location/city 5270\n",
"end": 1869,
"score": 0.6643155217170715,
"start": 1865,
"tag": "NAME",
"value": "limp"
}
] | src/foodship_restaurant/ports/db/data/initial_data.clj | eronalves/foodship-restaurant | 5 | (ns foodship-restaurant.ports.db.data.initial-data)
(defn get-data []
[{:restaurant/id 1
:restaurant/name "Mexicaníssimo"
:restaurant/tags ["mexican"]
:restaurant/preparation-time {:preparation-time/min 45
:preparation-time/max 60}
:restaurant/business-hours [{:business-hours/day-of-week :monday
:business-hours/opening "18:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :tuesday
:business-hours/opening "18:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :wednesday
:business-hours/opening "18:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :thursday
:business-hours/opening "18:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :friday
:business-hours/opening "18:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :saturday
:business-hours/opening "12:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :sunday
:business-hours/opening "12:00"
:business-hours/closing "23:45"}]
:restaurant/location {:location/addres "Rua Ribeirão Claro"
:location/number 192
:location/neighborhood "Vila Olimpia"
:location/city 5270
:location/state 26
:location/country 76
:location/zipcode "04549-050"}
:restaurant/menu [{:menu/title "Tostitacos"
:menu/category :appetizer
:menu/description "Tortilla de milho crocante (taco shell) recheada com proteína de soja refogada com cubinhos de berinjela e abobrinha, servido com alface e com ou sem sour cream."
:menu/ingredients ["farinha de trigo", "carne", "alface"]
:menu/price 25.9
:menu/serves 1}
{:menu/title "Quesadilla de queijo"
:menu/category :principal
:menu/description "Duas tortillas de trigo recheadas com queijo mussarela. Acompanha uma porção pequena de nachos, guacamole e chillibeans."
:menu/ingredients ["farinha de trigo", "queijo"]
:menu/price 22.9
:menu/serves 1}
{:menu/title "Molcajete tradicional"
:menu/category :principal
:menu/description "Cubinhos de alcatra e filé de frango grelhados com cebola, pimentão e queijo granado. Tudo isto é servido em uma pedra vulcânica estupidamente quente. Acompanha seis tortillas de trigo, guacamole e frijoles refritos"
:menu/ingredients ["alcatra", "frangro", "cebola", "pimentão", "queijo granado"]
:menu/price 46.9
:menu/serves 3}]
:restaurant/banking {:banking/agency "xxxx"
:banking/account "xxxx"
:banking/digit 1}}
{:restaurant/id 2
:restaurant/name "Aoyama"
:restaurant/tags ["japanese"]
:restaurant/preparation-time {:preparation-time/min 45
:preparation-time/max 60}
:restaurant/business-hours [{:business-hours/day-of-week :monday
:business-hours/opening "12:00"
:business-hours/closing "20:00"}
{:business-hours/day-of-week :tuesday
:business-hours/opening "12:00"
:business-hours/closing "20:00"}
{:business-hours/day-of-week :wednesday
:business-hours/opening "12:00"
:business-hours/closing "20:00"}
{:business-hours/day-of-week :thursday
:business-hours/opening "12:00"
:business-hours/closing "20:00"}
{:business-hours/day-of-week :friday
:business-hours/opening "12:00"
:business-hours/closing "20:00"}
{:business-hours/day-of-week :saturday
:business-hours/opening "12:00"
:business-hours/closing "23:00"}
{:business-hours/day-of-week :sunday
:business-hours/opening "12:00"
:business-hours/closing "23:00"}]
:restaurant/location {:location/addres "Al. dos Arapanés"
:location/number 532
:location/neighborhood "Moema"
:location/city 5270
:location/state 26
:location/country 76
:location/zipcode "04524-001"}
:restaurant/menu [{:menu/title "Tartar de Salmão"
:menu/category :appetizer
:menu/description "Salmão batido com molho especial Aoyama."
:menu/ingredients ["salmão", "molho"]
:menu/price 39.9
:menu/serves 2}
{:menu/title "Baterá Aoyama"
:menu/category :principal
:menu/description "Salmão, ovas, crispy de batata doce e gergelim."
:menu/ingredients ["salmão", "ovas", "crispy de batata doce", "gergelim"]
:menu/price 50.39
:menu/serves 2}
{:menu/title "Tempurá de Sorvete"
:menu/category :dessert
:menu/description "com caldas de morango, chocolate e maracujá"
:menu/ingredients ["calda de morango", "chocolate", "maracujá"]
:menu/price 39.9
:menu/serves 3}]
:restaurant/banking {:banking/agency "xxxx"
:banking/account "xxxx"
:banking/digit 1}}])
(defn setup [component fn-insert]
(run! #(fn-insert component %) (get-data)))
| 4861 | (ns foodship-restaurant.ports.db.data.initial-data)
(defn get-data []
[{:restaurant/id 1
:restaurant/name "Mexicaníssimo"
:restaurant/tags ["mexican"]
:restaurant/preparation-time {:preparation-time/min 45
:preparation-time/max 60}
:restaurant/business-hours [{:business-hours/day-of-week :monday
:business-hours/opening "18:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :tuesday
:business-hours/opening "18:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :wednesday
:business-hours/opening "18:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :thursday
:business-hours/opening "18:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :friday
:business-hours/opening "18:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :saturday
:business-hours/opening "12:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :sunday
:business-hours/opening "12:00"
:business-hours/closing "23:45"}]
:restaurant/location {:location/addres "<NAME>"
:location/number 192
:location/neighborhood "V<NAME> O<NAME>ia"
:location/city 5270
:location/state 26
:location/country 76
:location/zipcode "04549-050"}
:restaurant/menu [{:menu/title "Tostitacos"
:menu/category :appetizer
:menu/description "Tortilla de milho crocante (taco shell) recheada com proteína de soja refogada com cubinhos de berinjela e abobrinha, servido com alface e com ou sem sour cream."
:menu/ingredients ["farinha de trigo", "carne", "alface"]
:menu/price 25.9
:menu/serves 1}
{:menu/title "Quesadilla de queijo"
:menu/category :principal
:menu/description "Duas tortillas de trigo recheadas com queijo mussarela. Acompanha uma porção pequena de nachos, guacamole e chillibeans."
:menu/ingredients ["farinha de trigo", "queijo"]
:menu/price 22.9
:menu/serves 1}
{:menu/title "Molcajete tradicional"
:menu/category :principal
:menu/description "Cubinhos de alcatra e filé de frango grelhados com cebola, pimentão e queijo granado. Tudo isto é servido em uma pedra vulcânica estupidamente quente. Acompanha seis tortillas de trigo, guacamole e frijoles refritos"
:menu/ingredients ["alcatra", "frangro", "cebola", "pimentão", "queijo granado"]
:menu/price 46.9
:menu/serves 3}]
:restaurant/banking {:banking/agency "xxxx"
:banking/account "xxxx"
:banking/digit 1}}
{:restaurant/id 2
:restaurant/name "Aoyama"
:restaurant/tags ["japanese"]
:restaurant/preparation-time {:preparation-time/min 45
:preparation-time/max 60}
:restaurant/business-hours [{:business-hours/day-of-week :monday
:business-hours/opening "12:00"
:business-hours/closing "20:00"}
{:business-hours/day-of-week :tuesday
:business-hours/opening "12:00"
:business-hours/closing "20:00"}
{:business-hours/day-of-week :wednesday
:business-hours/opening "12:00"
:business-hours/closing "20:00"}
{:business-hours/day-of-week :thursday
:business-hours/opening "12:00"
:business-hours/closing "20:00"}
{:business-hours/day-of-week :friday
:business-hours/opening "12:00"
:business-hours/closing "20:00"}
{:business-hours/day-of-week :saturday
:business-hours/opening "12:00"
:business-hours/closing "23:00"}
{:business-hours/day-of-week :sunday
:business-hours/opening "12:00"
:business-hours/closing "23:00"}]
:restaurant/location {:location/addres "Al. dos Arapanés"
:location/number 532
:location/neighborhood "Moema"
:location/city 5270
:location/state 26
:location/country 76
:location/zipcode "04524-001"}
:restaurant/menu [{:menu/title "Tartar de Salmão"
:menu/category :appetizer
:menu/description "Salmão batido com molho especial Aoyama."
:menu/ingredients ["salmão", "molho"]
:menu/price 39.9
:menu/serves 2}
{:menu/title "Baterá Aoyama"
:menu/category :principal
:menu/description "Salmão, ovas, crispy de batata doce e gergelim."
:menu/ingredients ["salmão", "ovas", "crispy de batata doce", "gergelim"]
:menu/price 50.39
:menu/serves 2}
{:menu/title "Tempurá de Sorvete"
:menu/category :dessert
:menu/description "com caldas de morango, chocolate e maracujá"
:menu/ingredients ["calda de morango", "chocolate", "maracujá"]
:menu/price 39.9
:menu/serves 3}]
:restaurant/banking {:banking/agency "xxxx"
:banking/account "xxxx"
:banking/digit 1}}])
(defn setup [component fn-insert]
(run! #(fn-insert component %) (get-data)))
| true | (ns foodship-restaurant.ports.db.data.initial-data)
(defn get-data []
[{:restaurant/id 1
:restaurant/name "Mexicaníssimo"
:restaurant/tags ["mexican"]
:restaurant/preparation-time {:preparation-time/min 45
:preparation-time/max 60}
:restaurant/business-hours [{:business-hours/day-of-week :monday
:business-hours/opening "18:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :tuesday
:business-hours/opening "18:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :wednesday
:business-hours/opening "18:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :thursday
:business-hours/opening "18:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :friday
:business-hours/opening "18:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :saturday
:business-hours/opening "12:00"
:business-hours/closing "23:45"}
{:business-hours/day-of-week :sunday
:business-hours/opening "12:00"
:business-hours/closing "23:45"}]
:restaurant/location {:location/addres "PI:NAME:<NAME>END_PI"
:location/number 192
:location/neighborhood "VPI:NAME:<NAME>END_PI OPI:NAME:<NAME>END_PIia"
:location/city 5270
:location/state 26
:location/country 76
:location/zipcode "04549-050"}
:restaurant/menu [{:menu/title "Tostitacos"
:menu/category :appetizer
:menu/description "Tortilla de milho crocante (taco shell) recheada com proteína de soja refogada com cubinhos de berinjela e abobrinha, servido com alface e com ou sem sour cream."
:menu/ingredients ["farinha de trigo", "carne", "alface"]
:menu/price 25.9
:menu/serves 1}
{:menu/title "Quesadilla de queijo"
:menu/category :principal
:menu/description "Duas tortillas de trigo recheadas com queijo mussarela. Acompanha uma porção pequena de nachos, guacamole e chillibeans."
:menu/ingredients ["farinha de trigo", "queijo"]
:menu/price 22.9
:menu/serves 1}
{:menu/title "Molcajete tradicional"
:menu/category :principal
:menu/description "Cubinhos de alcatra e filé de frango grelhados com cebola, pimentão e queijo granado. Tudo isto é servido em uma pedra vulcânica estupidamente quente. Acompanha seis tortillas de trigo, guacamole e frijoles refritos"
:menu/ingredients ["alcatra", "frangro", "cebola", "pimentão", "queijo granado"]
:menu/price 46.9
:menu/serves 3}]
:restaurant/banking {:banking/agency "xxxx"
:banking/account "xxxx"
:banking/digit 1}}
{:restaurant/id 2
:restaurant/name "Aoyama"
:restaurant/tags ["japanese"]
:restaurant/preparation-time {:preparation-time/min 45
:preparation-time/max 60}
:restaurant/business-hours [{:business-hours/day-of-week :monday
:business-hours/opening "12:00"
:business-hours/closing "20:00"}
{:business-hours/day-of-week :tuesday
:business-hours/opening "12:00"
:business-hours/closing "20:00"}
{:business-hours/day-of-week :wednesday
:business-hours/opening "12:00"
:business-hours/closing "20:00"}
{:business-hours/day-of-week :thursday
:business-hours/opening "12:00"
:business-hours/closing "20:00"}
{:business-hours/day-of-week :friday
:business-hours/opening "12:00"
:business-hours/closing "20:00"}
{:business-hours/day-of-week :saturday
:business-hours/opening "12:00"
:business-hours/closing "23:00"}
{:business-hours/day-of-week :sunday
:business-hours/opening "12:00"
:business-hours/closing "23:00"}]
:restaurant/location {:location/addres "Al. dos Arapanés"
:location/number 532
:location/neighborhood "Moema"
:location/city 5270
:location/state 26
:location/country 76
:location/zipcode "04524-001"}
:restaurant/menu [{:menu/title "Tartar de Salmão"
:menu/category :appetizer
:menu/description "Salmão batido com molho especial Aoyama."
:menu/ingredients ["salmão", "molho"]
:menu/price 39.9
:menu/serves 2}
{:menu/title "Baterá Aoyama"
:menu/category :principal
:menu/description "Salmão, ovas, crispy de batata doce e gergelim."
:menu/ingredients ["salmão", "ovas", "crispy de batata doce", "gergelim"]
:menu/price 50.39
:menu/serves 2}
{:menu/title "Tempurá de Sorvete"
:menu/category :dessert
:menu/description "com caldas de morango, chocolate e maracujá"
:menu/ingredients ["calda de morango", "chocolate", "maracujá"]
:menu/price 39.9
:menu/serves 3}]
:restaurant/banking {:banking/agency "xxxx"
:banking/account "xxxx"
:banking/digit 1}}])
(defn setup [component fn-insert]
(run! #(fn-insert component %) (get-data)))
|
[
{
"context": "200 :body {[:form/id 42] {:form/id 42 :form/name \"Sam\"}}})))})\n\n(defsc Form [this {:form/keys [name] :a",
"end": 1450,
"score": 0.9667508006095886,
"start": 1447,
"tag": "NAME",
"value": "Sam"
},
{
"context": "tate {:form/id 1\n :form/name \"Sam\"}\n :form-fields #{:form/name}\n :pre-merge ",
"end": 1663,
"score": 0.9767575263977051,
"start": 1660,
"tag": "NAME",
"value": "Sam"
}
] | src/workspaces/com/fulcrologic/fulcro/cards/form_cards.cljs | mruzekw/fulcro | 1,312 | (ns com.fulcrologic.fulcro.cards.form-cards
(:require
[nubank.workspaces.card-types.fulcro3 :as ct.fulcro]
[nubank.workspaces.core :as ws]
[com.wsscode.pathom.connect :as pc]
[com.wsscode.pathom.core :as p]
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.dom :as dom]
[com.fulcrologic.fulcro.networking.mock-server-remote :refer [mock-http-server]]
[com.fulcrologic.fulcro.mutations :as m]
[taoensso.timbre :as log]
[com.fulcrologic.fulcro.algorithms.form-state :as fs]
[com.fulcrologic.fulcro.algorithms.tx-processing :as txn]
[com.fulcrologic.fulcro.data-fetch :as df]
[edn-query-language.core :as eql]))
(defonce remote {:transmit! (fn transmit! [_ {:keys [::txn/ast ::txn/result-handler ::txn/update-handler] :as send-node}]
(let [edn (eql/ast->query ast)
ok-handler (fn [result]
(try
(result-handler (select-keys result #{:transaction :status-code :body :status-text}))
(catch :default e
(log/error e "Result handler failed with an exception."))))]
(ok-handler {:transaction edn :status-code 200 :body {[:form/id 42] {:form/id 42 :form/name "Sam"}}})))})
(defsc Form [this {:form/keys [name] :as props}]
{:query [:form/id :form/name fs/form-config-join]
:ident :form/id
:initial-state {:form/id 1
:form/name "Sam"}
:form-fields #{:form/name}
:pre-merge (fn [{:keys [data-tree]}]
(fs/add-form-config Form data-tree))}
(dom/div
(dom/button {:onClick #(df/load! this [:form/id 42] Form)} "Load!")
(dom/label "Name")
(dom/input {:value name
:onChange #(m/set-string! this :form/name :event %)})))
(ws/defcard form-pre-merge-sample
(ct.fulcro/fulcro-card
{::ct.fulcro/wrap-root? true
::ct.fulcro/root Form
::ct.fulcro/app {:remotes {:remote remote}}}))
| 53389 | (ns com.fulcrologic.fulcro.cards.form-cards
(:require
[nubank.workspaces.card-types.fulcro3 :as ct.fulcro]
[nubank.workspaces.core :as ws]
[com.wsscode.pathom.connect :as pc]
[com.wsscode.pathom.core :as p]
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.dom :as dom]
[com.fulcrologic.fulcro.networking.mock-server-remote :refer [mock-http-server]]
[com.fulcrologic.fulcro.mutations :as m]
[taoensso.timbre :as log]
[com.fulcrologic.fulcro.algorithms.form-state :as fs]
[com.fulcrologic.fulcro.algorithms.tx-processing :as txn]
[com.fulcrologic.fulcro.data-fetch :as df]
[edn-query-language.core :as eql]))
(defonce remote {:transmit! (fn transmit! [_ {:keys [::txn/ast ::txn/result-handler ::txn/update-handler] :as send-node}]
(let [edn (eql/ast->query ast)
ok-handler (fn [result]
(try
(result-handler (select-keys result #{:transaction :status-code :body :status-text}))
(catch :default e
(log/error e "Result handler failed with an exception."))))]
(ok-handler {:transaction edn :status-code 200 :body {[:form/id 42] {:form/id 42 :form/name "<NAME>"}}})))})
(defsc Form [this {:form/keys [name] :as props}]
{:query [:form/id :form/name fs/form-config-join]
:ident :form/id
:initial-state {:form/id 1
:form/name "<NAME>"}
:form-fields #{:form/name}
:pre-merge (fn [{:keys [data-tree]}]
(fs/add-form-config Form data-tree))}
(dom/div
(dom/button {:onClick #(df/load! this [:form/id 42] Form)} "Load!")
(dom/label "Name")
(dom/input {:value name
:onChange #(m/set-string! this :form/name :event %)})))
(ws/defcard form-pre-merge-sample
(ct.fulcro/fulcro-card
{::ct.fulcro/wrap-root? true
::ct.fulcro/root Form
::ct.fulcro/app {:remotes {:remote remote}}}))
| true | (ns com.fulcrologic.fulcro.cards.form-cards
(:require
[nubank.workspaces.card-types.fulcro3 :as ct.fulcro]
[nubank.workspaces.core :as ws]
[com.wsscode.pathom.connect :as pc]
[com.wsscode.pathom.core :as p]
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.dom :as dom]
[com.fulcrologic.fulcro.networking.mock-server-remote :refer [mock-http-server]]
[com.fulcrologic.fulcro.mutations :as m]
[taoensso.timbre :as log]
[com.fulcrologic.fulcro.algorithms.form-state :as fs]
[com.fulcrologic.fulcro.algorithms.tx-processing :as txn]
[com.fulcrologic.fulcro.data-fetch :as df]
[edn-query-language.core :as eql]))
(defonce remote {:transmit! (fn transmit! [_ {:keys [::txn/ast ::txn/result-handler ::txn/update-handler] :as send-node}]
(let [edn (eql/ast->query ast)
ok-handler (fn [result]
(try
(result-handler (select-keys result #{:transaction :status-code :body :status-text}))
(catch :default e
(log/error e "Result handler failed with an exception."))))]
(ok-handler {:transaction edn :status-code 200 :body {[:form/id 42] {:form/id 42 :form/name "PI:NAME:<NAME>END_PI"}}})))})
(defsc Form [this {:form/keys [name] :as props}]
{:query [:form/id :form/name fs/form-config-join]
:ident :form/id
:initial-state {:form/id 1
:form/name "PI:NAME:<NAME>END_PI"}
:form-fields #{:form/name}
:pre-merge (fn [{:keys [data-tree]}]
(fs/add-form-config Form data-tree))}
(dom/div
(dom/button {:onClick #(df/load! this [:form/id 42] Form)} "Load!")
(dom/label "Name")
(dom/input {:value name
:onChange #(m/set-string! this :form/name :event %)})))
(ws/defcard form-pre-merge-sample
(ct.fulcro/fulcro-card
{::ct.fulcro/wrap-root? true
::ct.fulcro/root Form
::ct.fulcro/app {:remotes {:remote remote}}}))
|
[
{
"context": " :user \"myaccount\"\n :password \"secret\"}\n\n metadata-table-ddl (jdbc/create-table-",
"end": 480,
"score": 0.9992572665214539,
"start": 474,
"tag": "PASSWORD",
"value": "secret"
}
] | src/ldtab/init.clj | ontodev/ldtab.clj | 0 | (ns ldtab.init
(:require [clojure.java.jdbc :as jdbc]))
(defn create-database
"Creates an SQLite file with three tables:
1. 'ldtab' with columns: [key, value],
2. 'prefix' with columns: [prefix, base],
3. 'statement' with columns: [assertion, retraction, graph, subject, predicate, object, datatype, annotation]."
[dbname]
(let [db-spec {:dbtype "sqlite"
:dbname (str dbname)
:user "myaccount"
:password "secret"}
metadata-table-ddl (jdbc/create-table-ddl :ldtab
[[:key "TEXT" "PRIMARY KEY"]
[:value "TEXT"]])
prefix-table-ddl (jdbc/create-table-ddl :prefix
[[:prefix "TEXT" "PRIMARY KEY"]
[:base "TEXT" "NOT NULL"]])
statement-table-ddl (jdbc/create-table-ddl :statement
[[:assertion :int "NOT NULL"]
[:retraction :int "NOT NULL DEFAULT 0"]
[:graph "TEXT" "NOT NULL"]
[:subject "TEXT" "NOT NULL"]
[:predicate "TEXT" "NOT NULL"]
[:object "TEXT" "NOT NULL"]
[:datatype "TEXT" "NOT NULL"]
[:annotation "TEXT"]])]
;add tables to database
(jdbc/db-do-commands db-spec metadata-table-ddl)
(jdbc/db-do-commands db-spec prefix-table-ddl)
(jdbc/db-do-commands db-spec statement-table-ddl)
(jdbc/insert! db-spec :ldtab {:key "ldtab version" :value "0.0.1"})
(jdbc/insert! db-spec :ldtab {:key "schema version" :value "0"})))
| 109394 | (ns ldtab.init
(:require [clojure.java.jdbc :as jdbc]))
(defn create-database
"Creates an SQLite file with three tables:
1. 'ldtab' with columns: [key, value],
2. 'prefix' with columns: [prefix, base],
3. 'statement' with columns: [assertion, retraction, graph, subject, predicate, object, datatype, annotation]."
[dbname]
(let [db-spec {:dbtype "sqlite"
:dbname (str dbname)
:user "myaccount"
:password "<PASSWORD>"}
metadata-table-ddl (jdbc/create-table-ddl :ldtab
[[:key "TEXT" "PRIMARY KEY"]
[:value "TEXT"]])
prefix-table-ddl (jdbc/create-table-ddl :prefix
[[:prefix "TEXT" "PRIMARY KEY"]
[:base "TEXT" "NOT NULL"]])
statement-table-ddl (jdbc/create-table-ddl :statement
[[:assertion :int "NOT NULL"]
[:retraction :int "NOT NULL DEFAULT 0"]
[:graph "TEXT" "NOT NULL"]
[:subject "TEXT" "NOT NULL"]
[:predicate "TEXT" "NOT NULL"]
[:object "TEXT" "NOT NULL"]
[:datatype "TEXT" "NOT NULL"]
[:annotation "TEXT"]])]
;add tables to database
(jdbc/db-do-commands db-spec metadata-table-ddl)
(jdbc/db-do-commands db-spec prefix-table-ddl)
(jdbc/db-do-commands db-spec statement-table-ddl)
(jdbc/insert! db-spec :ldtab {:key "ldtab version" :value "0.0.1"})
(jdbc/insert! db-spec :ldtab {:key "schema version" :value "0"})))
| true | (ns ldtab.init
(:require [clojure.java.jdbc :as jdbc]))
(defn create-database
"Creates an SQLite file with three tables:
1. 'ldtab' with columns: [key, value],
2. 'prefix' with columns: [prefix, base],
3. 'statement' with columns: [assertion, retraction, graph, subject, predicate, object, datatype, annotation]."
[dbname]
(let [db-spec {:dbtype "sqlite"
:dbname (str dbname)
:user "myaccount"
:password "PI:PASSWORD:<PASSWORD>END_PI"}
metadata-table-ddl (jdbc/create-table-ddl :ldtab
[[:key "TEXT" "PRIMARY KEY"]
[:value "TEXT"]])
prefix-table-ddl (jdbc/create-table-ddl :prefix
[[:prefix "TEXT" "PRIMARY KEY"]
[:base "TEXT" "NOT NULL"]])
statement-table-ddl (jdbc/create-table-ddl :statement
[[:assertion :int "NOT NULL"]
[:retraction :int "NOT NULL DEFAULT 0"]
[:graph "TEXT" "NOT NULL"]
[:subject "TEXT" "NOT NULL"]
[:predicate "TEXT" "NOT NULL"]
[:object "TEXT" "NOT NULL"]
[:datatype "TEXT" "NOT NULL"]
[:annotation "TEXT"]])]
;add tables to database
(jdbc/db-do-commands db-spec metadata-table-ddl)
(jdbc/db-do-commands db-spec prefix-table-ddl)
(jdbc/db-do-commands db-spec statement-table-ddl)
(jdbc/insert! db-spec :ldtab {:key "ldtab version" :value "0.0.1"})
(jdbc/insert! db-spec :ldtab {:key "schema version" :value "0"})))
|
[
{
"context": " generate different wave forms.\"\n :author \"Karsten Schmidt\"}\n resonate2013.ex03_graph\n (:use [incanter cor",
"end": 204,
"score": 0.9998613595962524,
"start": 189,
"tag": "NAME",
"value": "Karsten Schmidt"
}
] | src/resonate2013/ex03_graph.clj | howthebodyworks/resonate-2013 | 0 | (ns
^{:doc "Brief intro to Incanter and concept of overtones/harmonics.
Displays some graphs of how harmonics are used to
generate different wave forms."
:author "Karsten Schmidt"}
resonate2013.ex03_graph
(:use [incanter core charts]))
(defn simple-plot
"Creates a graph of `f` in the interval `x1` .. `x2`.
Accepts an optional title."
([f x1 x2] (simple-plot f x1 x2 ""))
([f x1 x2 title]
(view (function-plot f x1 x2 :title title))))
(defn plot-harmonics
"Creates a graph of summing oscillator fn `f` over `n` octaves,
in the interval `x1` .. `x2`."
([f n title]
(plot-harmonics f n -10 10 title))
([f n x1 x2 title]
(simple-plot
(fn [x] (apply + (map-indexed f (repeat n x))))
x1 x2 title)))
(defn saw-wave
"Sawtooth uses overtones in each octave with exponentially
decreasing impact."
[i x] (let [i (inc i)] (* (Math/sin (* i x)) (/ 1.0 i))))
(defn sq-wave
"Sawtooth uses overtones in only every 2nd octave with
exponentially decreasing impact."
[i x] (let [i (inc (* i 2))] (* (Math/sin (* i x)) (/ 1.0 i))))
(defn comb-wave
"Like sq-wave, but flips sign for every 2nd harmonic."
[i x]
(let [ii (inc (* i 2))]
(* (Math/sin (* ii x)) (/ (if (odd? i) 1.0 -1.0) ii))))
;; draw pretty pictures
(plot-harmonics saw-wave 20 "sawtooth")
(plot-harmonics sq-wave 20 "square")
(plot-harmonics comb-wave 20 "comb")
;; this graph shows the amplitude of overtones in each octave
(simple-plot #(/ 1.0 %) 1 10 "harmonic falloff") | 99089 | (ns
^{:doc "Brief intro to Incanter and concept of overtones/harmonics.
Displays some graphs of how harmonics are used to
generate different wave forms."
:author "<NAME>"}
resonate2013.ex03_graph
(:use [incanter core charts]))
(defn simple-plot
"Creates a graph of `f` in the interval `x1` .. `x2`.
Accepts an optional title."
([f x1 x2] (simple-plot f x1 x2 ""))
([f x1 x2 title]
(view (function-plot f x1 x2 :title title))))
(defn plot-harmonics
"Creates a graph of summing oscillator fn `f` over `n` octaves,
in the interval `x1` .. `x2`."
([f n title]
(plot-harmonics f n -10 10 title))
([f n x1 x2 title]
(simple-plot
(fn [x] (apply + (map-indexed f (repeat n x))))
x1 x2 title)))
(defn saw-wave
"Sawtooth uses overtones in each octave with exponentially
decreasing impact."
[i x] (let [i (inc i)] (* (Math/sin (* i x)) (/ 1.0 i))))
(defn sq-wave
"Sawtooth uses overtones in only every 2nd octave with
exponentially decreasing impact."
[i x] (let [i (inc (* i 2))] (* (Math/sin (* i x)) (/ 1.0 i))))
(defn comb-wave
"Like sq-wave, but flips sign for every 2nd harmonic."
[i x]
(let [ii (inc (* i 2))]
(* (Math/sin (* ii x)) (/ (if (odd? i) 1.0 -1.0) ii))))
;; draw pretty pictures
(plot-harmonics saw-wave 20 "sawtooth")
(plot-harmonics sq-wave 20 "square")
(plot-harmonics comb-wave 20 "comb")
;; this graph shows the amplitude of overtones in each octave
(simple-plot #(/ 1.0 %) 1 10 "harmonic falloff") | true | (ns
^{:doc "Brief intro to Incanter and concept of overtones/harmonics.
Displays some graphs of how harmonics are used to
generate different wave forms."
:author "PI:NAME:<NAME>END_PI"}
resonate2013.ex03_graph
(:use [incanter core charts]))
(defn simple-plot
"Creates a graph of `f` in the interval `x1` .. `x2`.
Accepts an optional title."
([f x1 x2] (simple-plot f x1 x2 ""))
([f x1 x2 title]
(view (function-plot f x1 x2 :title title))))
(defn plot-harmonics
"Creates a graph of summing oscillator fn `f` over `n` octaves,
in the interval `x1` .. `x2`."
([f n title]
(plot-harmonics f n -10 10 title))
([f n x1 x2 title]
(simple-plot
(fn [x] (apply + (map-indexed f (repeat n x))))
x1 x2 title)))
(defn saw-wave
"Sawtooth uses overtones in each octave with exponentially
decreasing impact."
[i x] (let [i (inc i)] (* (Math/sin (* i x)) (/ 1.0 i))))
(defn sq-wave
"Sawtooth uses overtones in only every 2nd octave with
exponentially decreasing impact."
[i x] (let [i (inc (* i 2))] (* (Math/sin (* i x)) (/ 1.0 i))))
(defn comb-wave
"Like sq-wave, but flips sign for every 2nd harmonic."
[i x]
(let [ii (inc (* i 2))]
(* (Math/sin (* ii x)) (/ (if (odd? i) 1.0 -1.0) ii))))
;; draw pretty pictures
(plot-harmonics saw-wave 20 "sawtooth")
(plot-harmonics sq-wave 20 "square")
(plot-harmonics comb-wave 20 "comb")
;; this graph shows the amplitude of overtones in each octave
(simple-plot #(/ 1.0 %) 1 10 "harmonic falloff") |
[
{
"context": ";; Copyright © 2015-2020 Esko Luontola\n;; This software is released under the Apache Lic",
"end": 38,
"score": 0.9998846054077148,
"start": 25,
"tag": "NAME",
"value": "Esko Luontola"
},
{
"context": " 0 8))\n(def share-id (UUID. 0 9))\n(def share-key \"abc123\")\n\n(def congregation-created\n {:event/type :cong",
"end": 853,
"score": 0.9991968870162964,
"start": 847,
"tag": "KEY",
"value": "abc123"
},
{
"context": "/id cong-id\n :congregation/name \"Cong1 Name\"\n :congregation/permissions {:vi",
"end": 3144,
"score": 0.9615445733070374,
"start": 3134,
"tag": "NAME",
"value": "Cong1 Name"
}
] | test/territory_bro/domain/facade_test.clj | 3breadt/territory-bro | 2 | ;; Copyright © 2015-2020 Esko Luontola
;; This software is released under the Apache License 2.0.
;; The license text is at http://www.apache.org/licenses/LICENSE-2.0
(ns territory-bro.domain.facade-test
(:require [clojure.test :refer :all]
[territory-bro.domain.facade :as facade]
[territory-bro.domain.share :as share]
[territory-bro.domain.testdata :as testdata]
[territory-bro.projections :as projections]
[territory-bro.test.testutil :as testutil])
(:import (java.util UUID)))
(def cong-id (UUID. 0 1))
(def user-id (UUID. 0 2))
(def user-id2 (UUID. 0 3))
(def territory-id (UUID. 0 4))
(def territory-id2 (UUID. 0 5))
(def congregation-boundary-id (UUID. 0 6))
(def region-id (UUID. 0 7))
(def card-minimap-viewport-id (UUID. 0 8))
(def share-id (UUID. 0 9))
(def share-key "abc123")
(def congregation-created
{:event/type :congregation.event/congregation-created
:congregation/id cong-id
:congregation/name "Cong1 Name"
:congregation/schema-name "cong1_schema"})
(def view-congregation-granted
{:event/type :congregation.event/permission-granted
:congregation/id cong-id
:user/id user-id
:permission/id :view-congregation})
(def view-congregation-granted2
(assoc view-congregation-granted
:user/id user-id2))
(def territory-defined
{:event/type :territory.event/territory-defined
:congregation/id cong-id
:territory/id territory-id
:territory/number "123"
:territory/addresses "the addresses"
:territory/region "the region"
:territory/meta {:foo "bar"}
:territory/location testdata/wkt-multi-polygon})
(def territory-defined2
(assoc territory-defined
:territory/id territory-id2
:territory/number "456"))
(def congregation-boundary-defined
{:event/type :congregation-boundary.event/congregation-boundary-defined
:congregation/id cong-id
:congregation-boundary/id congregation-boundary-id
:congregation-boundary/location testdata/wkt-multi-polygon})
(def region-defined
{:event/type :region.event/region-defined
:congregation/id cong-id
:region/id region-id
:region/name "the name"
:region/location testdata/wkt-multi-polygon})
(def card-minimap-viewport-defined
{:event/type :card-minimap-viewport.event/card-minimap-viewport-defined
:congregation/id cong-id
:card-minimap-viewport/id card-minimap-viewport-id
:card-minimap-viewport/location testdata/wkt-polygon})
(def share-created
{:event/type :share.event/share-created
:share/id share-id
:share/key share-key
:share/type :link
:congregation/id cong-id
:territory/id territory-id})
(def test-events
[congregation-created
view-congregation-granted
view-congregation-granted2
territory-defined
territory-defined2
congregation-boundary-defined
region-defined
card-minimap-viewport-defined
share-created])
(defn- apply-events [events]
(testutil/apply-events projections/projection events))
(deftest test-get-congregation
(let [state (apply-events test-events)
expected {:congregation/id cong-id
:congregation/name "Cong1 Name"
:congregation/permissions {:view-congregation true}
:congregation/users [{:user/id user-id}
{:user/id user-id2}]
:congregation/territories [{:territory/id territory-id
:territory/number "123"
:territory/addresses "the addresses"
:territory/region "the region"
:territory/meta {:foo "bar"}
:territory/location testdata/wkt-multi-polygon}
{:territory/id territory-id2
:territory/number "456"
:territory/addresses "the addresses"
:territory/region "the region"
:territory/meta {:foo "bar"}
:territory/location testdata/wkt-multi-polygon}]
:congregation/congregation-boundaries [{:congregation-boundary/id congregation-boundary-id
:congregation-boundary/location testdata/wkt-multi-polygon}]
:congregation/regions [{:region/id region-id
:region/name "the name"
:region/location testdata/wkt-multi-polygon}]
:congregation/card-minimap-viewports [{:card-minimap-viewport/id card-minimap-viewport-id
:card-minimap-viewport/location testdata/wkt-polygon}]}]
(testing "has view permissions"
(is (= expected (facade/get-congregation state cong-id user-id))))
(let [user-id (UUID. 0 0x666)]
(testing "no permissions"
(is (nil? (facade/get-congregation state cong-id user-id))))
(testing "opened a share"
(let [state (share/grant-opened-shares state [share-id] user-id)
expected (assoc expected
:congregation/permissions {}
:congregation/users []
:congregation/territories [{:territory/id territory-id
:territory/number "123"
:territory/addresses "the addresses"
:territory/region "the region"
:territory/meta {:foo "bar"}
:territory/location testdata/wkt-multi-polygon}]
:congregation/congregation-boundaries []
:congregation/regions []
:congregation/card-minimap-viewports [])]
(is (= expected (facade/get-congregation state cong-id user-id))))))))
(deftest test-get-demo-congregation
(let [state (apply-events test-events)
user-id (UUID. 0 0x666)
expected {:congregation/id "demo" ; changed
:congregation/name "Demo Congregation" ; changed
:congregation/permissions {:view-congregation true} ; changed
:congregation/users [] ; changed
:congregation/territories [{:territory/id territory-id
:territory/number "123"
:territory/addresses "the addresses"
:territory/region "the region"
:territory/meta {:foo "bar"}
:territory/location testdata/wkt-multi-polygon}
{:territory/id territory-id2
:territory/number "456"
:territory/addresses "the addresses"
:territory/region "the region"
:territory/meta {:foo "bar"}
:territory/location testdata/wkt-multi-polygon}]
:congregation/congregation-boundaries [{:congregation-boundary/id congregation-boundary-id
:congregation-boundary/location testdata/wkt-multi-polygon}]
:congregation/regions [{:region/id region-id
:region/name "the name"
:region/location testdata/wkt-multi-polygon}]
:congregation/card-minimap-viewports [{:card-minimap-viewport/id card-minimap-viewport-id
:card-minimap-viewport/location testdata/wkt-polygon}]}]
(testing "no demo congregation"
(is (nil? (facade/get-demo-congregation state nil user-id))))
(testing "can see the demo congregation"
(is (= expected (facade/get-demo-congregation state cong-id user-id))))
(testing "cannot see the demo congregation as own congregation"
(is (nil? (facade/get-congregation state cong-id user-id))))))
| 104052 | ;; Copyright © 2015-2020 <NAME>
;; This software is released under the Apache License 2.0.
;; The license text is at http://www.apache.org/licenses/LICENSE-2.0
(ns territory-bro.domain.facade-test
(:require [clojure.test :refer :all]
[territory-bro.domain.facade :as facade]
[territory-bro.domain.share :as share]
[territory-bro.domain.testdata :as testdata]
[territory-bro.projections :as projections]
[territory-bro.test.testutil :as testutil])
(:import (java.util UUID)))
(def cong-id (UUID. 0 1))
(def user-id (UUID. 0 2))
(def user-id2 (UUID. 0 3))
(def territory-id (UUID. 0 4))
(def territory-id2 (UUID. 0 5))
(def congregation-boundary-id (UUID. 0 6))
(def region-id (UUID. 0 7))
(def card-minimap-viewport-id (UUID. 0 8))
(def share-id (UUID. 0 9))
(def share-key "<KEY>")
(def congregation-created
{:event/type :congregation.event/congregation-created
:congregation/id cong-id
:congregation/name "Cong1 Name"
:congregation/schema-name "cong1_schema"})
(def view-congregation-granted
{:event/type :congregation.event/permission-granted
:congregation/id cong-id
:user/id user-id
:permission/id :view-congregation})
(def view-congregation-granted2
(assoc view-congregation-granted
:user/id user-id2))
(def territory-defined
{:event/type :territory.event/territory-defined
:congregation/id cong-id
:territory/id territory-id
:territory/number "123"
:territory/addresses "the addresses"
:territory/region "the region"
:territory/meta {:foo "bar"}
:territory/location testdata/wkt-multi-polygon})
(def territory-defined2
(assoc territory-defined
:territory/id territory-id2
:territory/number "456"))
(def congregation-boundary-defined
{:event/type :congregation-boundary.event/congregation-boundary-defined
:congregation/id cong-id
:congregation-boundary/id congregation-boundary-id
:congregation-boundary/location testdata/wkt-multi-polygon})
(def region-defined
{:event/type :region.event/region-defined
:congregation/id cong-id
:region/id region-id
:region/name "the name"
:region/location testdata/wkt-multi-polygon})
(def card-minimap-viewport-defined
{:event/type :card-minimap-viewport.event/card-minimap-viewport-defined
:congregation/id cong-id
:card-minimap-viewport/id card-minimap-viewport-id
:card-minimap-viewport/location testdata/wkt-polygon})
(def share-created
{:event/type :share.event/share-created
:share/id share-id
:share/key share-key
:share/type :link
:congregation/id cong-id
:territory/id territory-id})
(def test-events
[congregation-created
view-congregation-granted
view-congregation-granted2
territory-defined
territory-defined2
congregation-boundary-defined
region-defined
card-minimap-viewport-defined
share-created])
(defn- apply-events [events]
(testutil/apply-events projections/projection events))
(deftest test-get-congregation
(let [state (apply-events test-events)
expected {:congregation/id cong-id
:congregation/name "<NAME>"
:congregation/permissions {:view-congregation true}
:congregation/users [{:user/id user-id}
{:user/id user-id2}]
:congregation/territories [{:territory/id territory-id
:territory/number "123"
:territory/addresses "the addresses"
:territory/region "the region"
:territory/meta {:foo "bar"}
:territory/location testdata/wkt-multi-polygon}
{:territory/id territory-id2
:territory/number "456"
:territory/addresses "the addresses"
:territory/region "the region"
:territory/meta {:foo "bar"}
:territory/location testdata/wkt-multi-polygon}]
:congregation/congregation-boundaries [{:congregation-boundary/id congregation-boundary-id
:congregation-boundary/location testdata/wkt-multi-polygon}]
:congregation/regions [{:region/id region-id
:region/name "the name"
:region/location testdata/wkt-multi-polygon}]
:congregation/card-minimap-viewports [{:card-minimap-viewport/id card-minimap-viewport-id
:card-minimap-viewport/location testdata/wkt-polygon}]}]
(testing "has view permissions"
(is (= expected (facade/get-congregation state cong-id user-id))))
(let [user-id (UUID. 0 0x666)]
(testing "no permissions"
(is (nil? (facade/get-congregation state cong-id user-id))))
(testing "opened a share"
(let [state (share/grant-opened-shares state [share-id] user-id)
expected (assoc expected
:congregation/permissions {}
:congregation/users []
:congregation/territories [{:territory/id territory-id
:territory/number "123"
:territory/addresses "the addresses"
:territory/region "the region"
:territory/meta {:foo "bar"}
:territory/location testdata/wkt-multi-polygon}]
:congregation/congregation-boundaries []
:congregation/regions []
:congregation/card-minimap-viewports [])]
(is (= expected (facade/get-congregation state cong-id user-id))))))))
(deftest test-get-demo-congregation
(let [state (apply-events test-events)
user-id (UUID. 0 0x666)
expected {:congregation/id "demo" ; changed
:congregation/name "Demo Congregation" ; changed
:congregation/permissions {:view-congregation true} ; changed
:congregation/users [] ; changed
:congregation/territories [{:territory/id territory-id
:territory/number "123"
:territory/addresses "the addresses"
:territory/region "the region"
:territory/meta {:foo "bar"}
:territory/location testdata/wkt-multi-polygon}
{:territory/id territory-id2
:territory/number "456"
:territory/addresses "the addresses"
:territory/region "the region"
:territory/meta {:foo "bar"}
:territory/location testdata/wkt-multi-polygon}]
:congregation/congregation-boundaries [{:congregation-boundary/id congregation-boundary-id
:congregation-boundary/location testdata/wkt-multi-polygon}]
:congregation/regions [{:region/id region-id
:region/name "the name"
:region/location testdata/wkt-multi-polygon}]
:congregation/card-minimap-viewports [{:card-minimap-viewport/id card-minimap-viewport-id
:card-minimap-viewport/location testdata/wkt-polygon}]}]
(testing "no demo congregation"
(is (nil? (facade/get-demo-congregation state nil user-id))))
(testing "can see the demo congregation"
(is (= expected (facade/get-demo-congregation state cong-id user-id))))
(testing "cannot see the demo congregation as own congregation"
(is (nil? (facade/get-congregation state cong-id user-id))))))
| true | ;; Copyright © 2015-2020 PI:NAME:<NAME>END_PI
;; This software is released under the Apache License 2.0.
;; The license text is at http://www.apache.org/licenses/LICENSE-2.0
(ns territory-bro.domain.facade-test
(:require [clojure.test :refer :all]
[territory-bro.domain.facade :as facade]
[territory-bro.domain.share :as share]
[territory-bro.domain.testdata :as testdata]
[territory-bro.projections :as projections]
[territory-bro.test.testutil :as testutil])
(:import (java.util UUID)))
(def cong-id (UUID. 0 1))
(def user-id (UUID. 0 2))
(def user-id2 (UUID. 0 3))
(def territory-id (UUID. 0 4))
(def territory-id2 (UUID. 0 5))
(def congregation-boundary-id (UUID. 0 6))
(def region-id (UUID. 0 7))
(def card-minimap-viewport-id (UUID. 0 8))
(def share-id (UUID. 0 9))
(def share-key "PI:KEY:<KEY>END_PI")
(def congregation-created
{:event/type :congregation.event/congregation-created
:congregation/id cong-id
:congregation/name "Cong1 Name"
:congregation/schema-name "cong1_schema"})
(def view-congregation-granted
{:event/type :congregation.event/permission-granted
:congregation/id cong-id
:user/id user-id
:permission/id :view-congregation})
(def view-congregation-granted2
(assoc view-congregation-granted
:user/id user-id2))
(def territory-defined
{:event/type :territory.event/territory-defined
:congregation/id cong-id
:territory/id territory-id
:territory/number "123"
:territory/addresses "the addresses"
:territory/region "the region"
:territory/meta {:foo "bar"}
:territory/location testdata/wkt-multi-polygon})
(def territory-defined2
(assoc territory-defined
:territory/id territory-id2
:territory/number "456"))
(def congregation-boundary-defined
{:event/type :congregation-boundary.event/congregation-boundary-defined
:congregation/id cong-id
:congregation-boundary/id congregation-boundary-id
:congregation-boundary/location testdata/wkt-multi-polygon})
(def region-defined
{:event/type :region.event/region-defined
:congregation/id cong-id
:region/id region-id
:region/name "the name"
:region/location testdata/wkt-multi-polygon})
(def card-minimap-viewport-defined
{:event/type :card-minimap-viewport.event/card-minimap-viewport-defined
:congregation/id cong-id
:card-minimap-viewport/id card-minimap-viewport-id
:card-minimap-viewport/location testdata/wkt-polygon})
(def share-created
{:event/type :share.event/share-created
:share/id share-id
:share/key share-key
:share/type :link
:congregation/id cong-id
:territory/id territory-id})
(def test-events
[congregation-created
view-congregation-granted
view-congregation-granted2
territory-defined
territory-defined2
congregation-boundary-defined
region-defined
card-minimap-viewport-defined
share-created])
(defn- apply-events [events]
(testutil/apply-events projections/projection events))
(deftest test-get-congregation
(let [state (apply-events test-events)
expected {:congregation/id cong-id
:congregation/name "PI:NAME:<NAME>END_PI"
:congregation/permissions {:view-congregation true}
:congregation/users [{:user/id user-id}
{:user/id user-id2}]
:congregation/territories [{:territory/id territory-id
:territory/number "123"
:territory/addresses "the addresses"
:territory/region "the region"
:territory/meta {:foo "bar"}
:territory/location testdata/wkt-multi-polygon}
{:territory/id territory-id2
:territory/number "456"
:territory/addresses "the addresses"
:territory/region "the region"
:territory/meta {:foo "bar"}
:territory/location testdata/wkt-multi-polygon}]
:congregation/congregation-boundaries [{:congregation-boundary/id congregation-boundary-id
:congregation-boundary/location testdata/wkt-multi-polygon}]
:congregation/regions [{:region/id region-id
:region/name "the name"
:region/location testdata/wkt-multi-polygon}]
:congregation/card-minimap-viewports [{:card-minimap-viewport/id card-minimap-viewport-id
:card-minimap-viewport/location testdata/wkt-polygon}]}]
(testing "has view permissions"
(is (= expected (facade/get-congregation state cong-id user-id))))
(let [user-id (UUID. 0 0x666)]
(testing "no permissions"
(is (nil? (facade/get-congregation state cong-id user-id))))
(testing "opened a share"
(let [state (share/grant-opened-shares state [share-id] user-id)
expected (assoc expected
:congregation/permissions {}
:congregation/users []
:congregation/territories [{:territory/id territory-id
:territory/number "123"
:territory/addresses "the addresses"
:territory/region "the region"
:territory/meta {:foo "bar"}
:territory/location testdata/wkt-multi-polygon}]
:congregation/congregation-boundaries []
:congregation/regions []
:congregation/card-minimap-viewports [])]
(is (= expected (facade/get-congregation state cong-id user-id))))))))
(deftest test-get-demo-congregation
(let [state (apply-events test-events)
user-id (UUID. 0 0x666)
expected {:congregation/id "demo" ; changed
:congregation/name "Demo Congregation" ; changed
:congregation/permissions {:view-congregation true} ; changed
:congregation/users [] ; changed
:congregation/territories [{:territory/id territory-id
:territory/number "123"
:territory/addresses "the addresses"
:territory/region "the region"
:territory/meta {:foo "bar"}
:territory/location testdata/wkt-multi-polygon}
{:territory/id territory-id2
:territory/number "456"
:territory/addresses "the addresses"
:territory/region "the region"
:territory/meta {:foo "bar"}
:territory/location testdata/wkt-multi-polygon}]
:congregation/congregation-boundaries [{:congregation-boundary/id congregation-boundary-id
:congregation-boundary/location testdata/wkt-multi-polygon}]
:congregation/regions [{:region/id region-id
:region/name "the name"
:region/location testdata/wkt-multi-polygon}]
:congregation/card-minimap-viewports [{:card-minimap-viewport/id card-minimap-viewport-id
:card-minimap-viewport/location testdata/wkt-polygon}]}]
(testing "no demo congregation"
(is (nil? (facade/get-demo-congregation state nil user-id))))
(testing "can see the demo congregation"
(is (= expected (facade/get-demo-congregation state cong-id user-id))))
(testing "cannot see the demo congregation as own congregation"
(is (nil? (facade/get-congregation state cong-id user-id))))))
|
[
{
"context": " pip [\"2\" \"3\" \"4\" \"5\" \"6\" \"7\" \"8\" \"9\" \"10\" \"Jack\" \"Queen\" \"King\" \"Ace\"]]\n\t\t\t (Card. pip suit))))",
"end": 437,
"score": 0.5685515999794006,
"start": 433,
"tag": "NAME",
"value": "Jack"
}
] | Task/Playing-cards/Clojure/playing-cards.clj | djgoku/RosettaCodeData | 0 | (defrecord Card [pip suit]
Object
(toString [this] (str pip " of " suit)))
(defprotocol pDeck
(deal [this n])
(shuffle [this])
(newDeck [this])
(print [this]))
(deftype Deck [cards]
pDeck
(deal [this n] [(take n cards) (Deck. (drop n cards))])
(shuffle [this] (Deck. (shuffle cards)))
(newDeck [this] (Deck. (for [suit ["Clubs" "Hearts" "Spades" "Diamonds"]
pip ["2" "3" "4" "5" "6" "7" "8" "9" "10" "Jack" "Queen" "King" "Ace"]]
(Card. pip suit))))
(print [this] (dorun (map (comp println str) cards)) this))
(defn new-deck []
(.newDeck (Deck. nil)))
| 60156 | (defrecord Card [pip suit]
Object
(toString [this] (str pip " of " suit)))
(defprotocol pDeck
(deal [this n])
(shuffle [this])
(newDeck [this])
(print [this]))
(deftype Deck [cards]
pDeck
(deal [this n] [(take n cards) (Deck. (drop n cards))])
(shuffle [this] (Deck. (shuffle cards)))
(newDeck [this] (Deck. (for [suit ["Clubs" "Hearts" "Spades" "Diamonds"]
pip ["2" "3" "4" "5" "6" "7" "8" "9" "10" "<NAME>" "Queen" "King" "Ace"]]
(Card. pip suit))))
(print [this] (dorun (map (comp println str) cards)) this))
(defn new-deck []
(.newDeck (Deck. nil)))
| true | (defrecord Card [pip suit]
Object
(toString [this] (str pip " of " suit)))
(defprotocol pDeck
(deal [this n])
(shuffle [this])
(newDeck [this])
(print [this]))
(deftype Deck [cards]
pDeck
(deal [this n] [(take n cards) (Deck. (drop n cards))])
(shuffle [this] (Deck. (shuffle cards)))
(newDeck [this] (Deck. (for [suit ["Clubs" "Hearts" "Spades" "Diamonds"]
pip ["2" "3" "4" "5" "6" "7" "8" "9" "10" "PI:NAME:<NAME>END_PI" "Queen" "King" "Ace"]]
(Card. pip suit))))
(print [this] (dorun (map (comp println str) cards)) this))
(defn new-deck []
(.newDeck (Deck. nil)))
|
[
{
"context": "(ns ^{:author \"Andrea Richiardi\"\n :doc \"ExtractData Mojo for the resource vi",
"end": 31,
"score": 0.9998748302459717,
"start": 15,
"tag": "NAME",
"value": "Andrea Richiardi"
}
] | src/plugin/rest_resources_viz/extract.clj | elasticpath/rest-resource-viz | 4 | (ns ^{:author "Andrea Richiardi"
:doc "ExtractData Mojo for the resource visualization plugin"}
rest-resources-viz.extract
(:require [classlojure.core :as classlojure]
[clojure.java.io :as io]
[clojure.pprint :as pp]
[clojure.spec.alpha :as s]
[clojure.string :as str]
[resauce.core :as res])
(:import [java.io File InputStream]
[java.nio.file Files Path Paths StandardCopyOption]))
(def ^:private web-assets-dir "web-assets/")
(def ^:private plugin-jar #"rest-viz-maven-plugin-.*\.jar")
(defn relativize
"Return the relative path of file as string"
[^String file-path ^String parent-path]
(str/replace file-path (re-pattern parent-path) ""))
(def web-assets-xf
(filter #(re-find plugin-jar %)))
(defn web-assets-resources
[]
(let [seed (into #{}
web-assets-xf
(res/resource-dir web-assets-dir))]
(loop [rs seed
acc #{}]
(if (seq rs)
(recur (mapcat res/url-dir rs) (into acc rs))
acc))))
;; Java resources are the best, how to know if the resource path is a dir?
;; http://stackoverflow.com/questions/20105554/is-there-a-way-to-tell-if-a-classpath-resource-is-a-file-or-a-directory
(defn directory-resource?
"Check if a resource is a directory"
[cl path]
(let [normalized-path (str path (when-not (= \/ (last path)) "/"))]
(when-let [r (.findResource cl normalized-path)]
(res/directory? r))))
(defn copy-web-assets!
"Copy the web-assets from within our plugin to the output-dir"
[logger ^File output-dir]
(let [cl (.getContextClassLoader (Thread/currentThread))
output-nio-path (some-> output-dir io/file .toURI Paths/get)
parent-path (-> web-assets-dir res/resources first .toExternalForm)]
(if-let [web-assets-paths (seq (web-assets-resources))]
(doseq [path web-assets-paths]
(let [relative-path (relativize path parent-path)
relative-resource-path (str web-assets-dir relative-path)
output-path ^Path (.resolve output-nio-path relative-path)]
(when-not (directory-resource? cl relative-resource-path)
(io/make-parents (.toFile output-path))
(.debug logger (format "Creating %s..." output-path))
(with-open [is ^InputStream (.getResourceAsStream cl relative-resource-path)]
(Files/copy is output-path (into-array StandardCopyOption [StandardCopyOption/REPLACE_EXISTING])))))))))
(def ^:private java-url->str
(map #(.toExternalForm %)))
(s/def :plugin.extractor/target-directory string?)
(s/def :plugin.extractor/pretty-print boolean?)
(s/def :plugin.extractor/data-target-name string?)
(s/def :plugin.extract/opts (s/keys :req-un [:plugin.extractor/target-directory]
:opt-un [:plugin.extractor/pretty-print
:plugin.extractor/data-target-name]))
(defn run-extractor
"Run the extractor."
[maven-session logger opts]
(.debug logger (format "Options: %s" opts))
(s/assert* :plugin.extract/opts opts)
(let [target-dir-file (io/file (:target-directory opts))
local-repo (or (.. maven-session getLocalRepository getBasedir)
(System/getProperty "maven.local-repo"))
classpath-urls (into [] java-url->str
(.. (Thread/currentThread) getContextClassLoader getURLs))
edn-target-file (.getCanonicalPath (io/file target-dir-file (:data-target-name opts)))]
(.debug logger (format "Local m2: %s" local-repo))
(.debug logger (format "Output path: %s" target-dir-file))
(.debug logger (format "Plugin Classpath: %s" (with-out-str (pp/pprint classpath-urls))))
(classlojure/eval-in (classlojure/classlojure classpath-urls)
`(do (require '[rest-resources-viz.extractor])
(try
;; creating the target folder if it does not exist
~(io/make-parents edn-target-file)
;; extracting the data
(rest-resources-viz.extractor/spit-graph-data-edn!
~edn-target-file
{:pretty ~(:pretty-print opts)})
;; copy the web assets
~(copy-web-assets! logger target-dir-file)
(catch Exception ~'e
(throw (ex-info "Cannot extract data, make sure you added the dependencies to your pom.xml."
~opts
~'e))))))))
(comment
(defonce invoker (maven/make-invoker (java.lang.System/getenv "M2_HOME") (java.lang.System/getenv "PWD")))
(def test-pom (-> "pom.xml" io/resource io/file))
(def goals ["rest-viz-maven-plugin:extract"])
(def res (maven/invoke-mojo invoker test-pom goals true)))
| 90267 | (ns ^{:author "<NAME>"
:doc "ExtractData Mojo for the resource visualization plugin"}
rest-resources-viz.extract
(:require [classlojure.core :as classlojure]
[clojure.java.io :as io]
[clojure.pprint :as pp]
[clojure.spec.alpha :as s]
[clojure.string :as str]
[resauce.core :as res])
(:import [java.io File InputStream]
[java.nio.file Files Path Paths StandardCopyOption]))
(def ^:private web-assets-dir "web-assets/")
(def ^:private plugin-jar #"rest-viz-maven-plugin-.*\.jar")
(defn relativize
"Return the relative path of file as string"
[^String file-path ^String parent-path]
(str/replace file-path (re-pattern parent-path) ""))
(def web-assets-xf
(filter #(re-find plugin-jar %)))
(defn web-assets-resources
[]
(let [seed (into #{}
web-assets-xf
(res/resource-dir web-assets-dir))]
(loop [rs seed
acc #{}]
(if (seq rs)
(recur (mapcat res/url-dir rs) (into acc rs))
acc))))
;; Java resources are the best, how to know if the resource path is a dir?
;; http://stackoverflow.com/questions/20105554/is-there-a-way-to-tell-if-a-classpath-resource-is-a-file-or-a-directory
(defn directory-resource?
"Check if a resource is a directory"
[cl path]
(let [normalized-path (str path (when-not (= \/ (last path)) "/"))]
(when-let [r (.findResource cl normalized-path)]
(res/directory? r))))
(defn copy-web-assets!
"Copy the web-assets from within our plugin to the output-dir"
[logger ^File output-dir]
(let [cl (.getContextClassLoader (Thread/currentThread))
output-nio-path (some-> output-dir io/file .toURI Paths/get)
parent-path (-> web-assets-dir res/resources first .toExternalForm)]
(if-let [web-assets-paths (seq (web-assets-resources))]
(doseq [path web-assets-paths]
(let [relative-path (relativize path parent-path)
relative-resource-path (str web-assets-dir relative-path)
output-path ^Path (.resolve output-nio-path relative-path)]
(when-not (directory-resource? cl relative-resource-path)
(io/make-parents (.toFile output-path))
(.debug logger (format "Creating %s..." output-path))
(with-open [is ^InputStream (.getResourceAsStream cl relative-resource-path)]
(Files/copy is output-path (into-array StandardCopyOption [StandardCopyOption/REPLACE_EXISTING])))))))))
(def ^:private java-url->str
(map #(.toExternalForm %)))
(s/def :plugin.extractor/target-directory string?)
(s/def :plugin.extractor/pretty-print boolean?)
(s/def :plugin.extractor/data-target-name string?)
(s/def :plugin.extract/opts (s/keys :req-un [:plugin.extractor/target-directory]
:opt-un [:plugin.extractor/pretty-print
:plugin.extractor/data-target-name]))
(defn run-extractor
"Run the extractor."
[maven-session logger opts]
(.debug logger (format "Options: %s" opts))
(s/assert* :plugin.extract/opts opts)
(let [target-dir-file (io/file (:target-directory opts))
local-repo (or (.. maven-session getLocalRepository getBasedir)
(System/getProperty "maven.local-repo"))
classpath-urls (into [] java-url->str
(.. (Thread/currentThread) getContextClassLoader getURLs))
edn-target-file (.getCanonicalPath (io/file target-dir-file (:data-target-name opts)))]
(.debug logger (format "Local m2: %s" local-repo))
(.debug logger (format "Output path: %s" target-dir-file))
(.debug logger (format "Plugin Classpath: %s" (with-out-str (pp/pprint classpath-urls))))
(classlojure/eval-in (classlojure/classlojure classpath-urls)
`(do (require '[rest-resources-viz.extractor])
(try
;; creating the target folder if it does not exist
~(io/make-parents edn-target-file)
;; extracting the data
(rest-resources-viz.extractor/spit-graph-data-edn!
~edn-target-file
{:pretty ~(:pretty-print opts)})
;; copy the web assets
~(copy-web-assets! logger target-dir-file)
(catch Exception ~'e
(throw (ex-info "Cannot extract data, make sure you added the dependencies to your pom.xml."
~opts
~'e))))))))
(comment
(defonce invoker (maven/make-invoker (java.lang.System/getenv "M2_HOME") (java.lang.System/getenv "PWD")))
(def test-pom (-> "pom.xml" io/resource io/file))
(def goals ["rest-viz-maven-plugin:extract"])
(def res (maven/invoke-mojo invoker test-pom goals true)))
| true | (ns ^{:author "PI:NAME:<NAME>END_PI"
:doc "ExtractData Mojo for the resource visualization plugin"}
rest-resources-viz.extract
(:require [classlojure.core :as classlojure]
[clojure.java.io :as io]
[clojure.pprint :as pp]
[clojure.spec.alpha :as s]
[clojure.string :as str]
[resauce.core :as res])
(:import [java.io File InputStream]
[java.nio.file Files Path Paths StandardCopyOption]))
(def ^:private web-assets-dir "web-assets/")
(def ^:private plugin-jar #"rest-viz-maven-plugin-.*\.jar")
(defn relativize
"Return the relative path of file as string"
[^String file-path ^String parent-path]
(str/replace file-path (re-pattern parent-path) ""))
(def web-assets-xf
(filter #(re-find plugin-jar %)))
(defn web-assets-resources
[]
(let [seed (into #{}
web-assets-xf
(res/resource-dir web-assets-dir))]
(loop [rs seed
acc #{}]
(if (seq rs)
(recur (mapcat res/url-dir rs) (into acc rs))
acc))))
;; Java resources are the best, how to know if the resource path is a dir?
;; http://stackoverflow.com/questions/20105554/is-there-a-way-to-tell-if-a-classpath-resource-is-a-file-or-a-directory
(defn directory-resource?
"Check if a resource is a directory"
[cl path]
(let [normalized-path (str path (when-not (= \/ (last path)) "/"))]
(when-let [r (.findResource cl normalized-path)]
(res/directory? r))))
(defn copy-web-assets!
"Copy the web-assets from within our plugin to the output-dir"
[logger ^File output-dir]
(let [cl (.getContextClassLoader (Thread/currentThread))
output-nio-path (some-> output-dir io/file .toURI Paths/get)
parent-path (-> web-assets-dir res/resources first .toExternalForm)]
(if-let [web-assets-paths (seq (web-assets-resources))]
(doseq [path web-assets-paths]
(let [relative-path (relativize path parent-path)
relative-resource-path (str web-assets-dir relative-path)
output-path ^Path (.resolve output-nio-path relative-path)]
(when-not (directory-resource? cl relative-resource-path)
(io/make-parents (.toFile output-path))
(.debug logger (format "Creating %s..." output-path))
(with-open [is ^InputStream (.getResourceAsStream cl relative-resource-path)]
(Files/copy is output-path (into-array StandardCopyOption [StandardCopyOption/REPLACE_EXISTING])))))))))
(def ^:private java-url->str
(map #(.toExternalForm %)))
(s/def :plugin.extractor/target-directory string?)
(s/def :plugin.extractor/pretty-print boolean?)
(s/def :plugin.extractor/data-target-name string?)
(s/def :plugin.extract/opts (s/keys :req-un [:plugin.extractor/target-directory]
:opt-un [:plugin.extractor/pretty-print
:plugin.extractor/data-target-name]))
(defn run-extractor
"Run the extractor."
[maven-session logger opts]
(.debug logger (format "Options: %s" opts))
(s/assert* :plugin.extract/opts opts)
(let [target-dir-file (io/file (:target-directory opts))
local-repo (or (.. maven-session getLocalRepository getBasedir)
(System/getProperty "maven.local-repo"))
classpath-urls (into [] java-url->str
(.. (Thread/currentThread) getContextClassLoader getURLs))
edn-target-file (.getCanonicalPath (io/file target-dir-file (:data-target-name opts)))]
(.debug logger (format "Local m2: %s" local-repo))
(.debug logger (format "Output path: %s" target-dir-file))
(.debug logger (format "Plugin Classpath: %s" (with-out-str (pp/pprint classpath-urls))))
(classlojure/eval-in (classlojure/classlojure classpath-urls)
`(do (require '[rest-resources-viz.extractor])
(try
;; creating the target folder if it does not exist
~(io/make-parents edn-target-file)
;; extracting the data
(rest-resources-viz.extractor/spit-graph-data-edn!
~edn-target-file
{:pretty ~(:pretty-print opts)})
;; copy the web assets
~(copy-web-assets! logger target-dir-file)
(catch Exception ~'e
(throw (ex-info "Cannot extract data, make sure you added the dependencies to your pom.xml."
~opts
~'e))))))))
(comment
(defonce invoker (maven/make-invoker (java.lang.System/getenv "M2_HOME") (java.lang.System/getenv "PWD")))
(def test-pom (-> "pom.xml" io/resource io/file))
(def goals ["rest-viz-maven-plugin:extract"])
(def res (maven/invoke-mojo invoker test-pom goals true)))
|
[
{
"context": "T=utf8\")\n\n(def cuadrantes-rows\n [{:name \"Rositas\"\n :leader \"Rossy Rutiaga\"\n :leader_em",
"end": 8015,
"score": 0.9996638298034668,
"start": 8008,
"tag": "NAME",
"value": "Rositas"
},
{
"context": "ws\n [{:name \"Rositas\"\n :leader \"Rossy Rutiaga\"\n :leader_email \"rossyrutiaga@rositas.com\"\n ",
"end": 8049,
"score": 0.9999050498008728,
"start": 8036,
"tag": "NAME",
"value": "Rossy Rutiaga"
},
{
"context": " :leader \"Rossy Rutiaga\"\n :leader_email \"rossyrutiaga@rositas.com\"\n :notes \"Cuadrante ciclista con todos ",
"end": 8094,
"score": 0.9999328255653381,
"start": 8070,
"tag": "EMAIL",
"value": "rossyrutiaga@rositas.com"
},
{
"context": "lista.\"\n :status \"T\"}\n {:name \"Azules\"\n :leader \"Ana Villa\"\n :leader_email ",
"end": 8233,
"score": 0.9994230270385742,
"start": 8227,
"tag": "NAME",
"value": "Azules"
},
{
"context": "T\"}\n {:name \"Azules\"\n :leader \"Ana Villa\"\n :leader_email \"anavilla@azules.com\"\n :not",
"end": 8263,
"score": 0.9997732639312744,
"start": 8254,
"tag": "NAME",
"value": "Ana Villa"
},
{
"context": "\n :leader \"Ana Villa\"\n :leader_email \"anavilla@azules.com\"\n :notes \"Cuadrante ciclista con nivele",
"end": 8303,
"score": 0.9999305009841919,
"start": 8284,
"tag": "EMAIL",
"value": "anavilla@azules.com"
},
{
"context": "\"}\n {:name \"Grupo Ciclista La Vid\"\n :leader \"Marco Romero\"\n :leader_email \"mromeropmx@hotmail.com\"\n :",
"end": 8452,
"score": 0.9999006390571594,
"start": 8440,
"tag": "NAME",
"value": "Marco Romero"
},
{
"context": "id\"\n :leader \"Marco Romero\"\n :leader_email \"mromeropmx@hotmail.com\"\n :notes \"Un grupo cristiano con deseos de mej",
"end": 8495,
"score": 0.9999275207519531,
"start": 8473,
"tag": "EMAIL",
"value": "mromeropmx@hotmail.com"
},
{
"context": "tra salud...\"\n :status \"T\"}\n {:name \"Reto Demoledor\"\n :leader \"Reto\"\n :leader_email \"reto",
"end": 8618,
"score": 0.9833822250366211,
"start": 8604,
"tag": "NAME",
"value": "Reto Demoledor"
},
{
"context": ":name \"Reto Demoledor\"\n :leader \"Reto\"\n :leader_email \"retodemoledor@server.com\"\n ",
"end": 8642,
"score": 0.4081888794898987,
"start": 8639,
"tag": "USERNAME",
"value": "Ret"
},
{
"context": "me \"Reto Demoledor\"\n :leader \"Reto\"\n :leader_email \"retodemoledor@server.com\"\n ",
"end": 8643,
"score": 0.663037896156311,
"start": 8642,
"tag": "NAME",
"value": "o"
},
{
"context": "edor\"\n :leader \"Reto\"\n :leader_email \"retodemoledor@server.com\"\n :notes \"Para mas información entra al",
"end": 8688,
"score": 0.9999245405197144,
"start": 8664,
"tag": "EMAIL",
"value": "retodemoledor@server.com"
},
{
"context": "Reto Demoledor\"\n :status \"T\"}\n {:name \"Reto Aerobiker\"\n :leader \"retoaerobiker\"\n :leader_email \"r",
"end": 8809,
"score": 0.9998950958251953,
"start": 8795,
"tag": "NAME",
"value": "Reto Aerobiker"
},
{
"context": " \"T\"}\n {:name \"Reto Aerobiker\"\n :leader \"retoaerobiker\"\n :leader_email \"retoaerobiker@server.com\"\n ",
"end": 8837,
"score": 0.909399151802063,
"start": 8824,
"tag": "USERNAME",
"value": "retoaerobiker"
},
{
"context": "r\"\n :leader \"retoaerobiker\"\n :leader_email \"retoaerobiker@server.com\"\n :notes \"Reto madrugador 5x5 mas detalles en ",
"end": 8882,
"score": 0.9999263286590576,
"start": 8858,
"tag": "EMAIL",
"value": "retoaerobiker@server.com"
},
{
"context": "obikers (FB)\"\n :status \"T\"}\n {:name \"Blanco\"\n :leader \"blancolider\"\n :leader_emai",
"end": 8991,
"score": 0.9995360970497131,
"start": 8985,
"tag": "NAME",
"value": "Blanco"
},
{
"context": "T\"}\n {:name \"Blanco\"\n :leader \"blancolider\"\n :leader_email \"blancolider@server.com\"\n :",
"end": 9023,
"score": 0.9996636509895325,
"start": 9012,
"tag": "USERNAME",
"value": "blancolider"
},
{
"context": " :leader \"blancolider\"\n :leader_email \"blancolider@server.com\"\n :notes \"\"\n :status \"T\"}\n {",
"end": 9066,
"score": 0.9999191761016846,
"start": 9044,
"tag": "EMAIL",
"value": "blancolider@server.com"
},
{
"context": " \"\"\n :status \"T\"}\n {:name \"Bicios@s\"\n :leader \"biciosolider\"\n :lea",
"end": 9132,
"score": 0.6278259754180908,
"start": 9131,
"tag": "USERNAME",
"value": "B"
},
{
"context": " \"\"\n :status \"T\"}\n {:name \"Bicios@s\"\n :leader \"biciosolider\"\n :leader_e",
"end": 9137,
"score": 0.6888633370399475,
"start": 9132,
"tag": "NAME",
"value": "icios"
},
{
"context": "\"\n :status \"T\"}\n {:name \"Bicios@s\"\n :leader \"biciosolider\"\n :leader_em",
"end": 9137,
"score": 0.6105970144271851,
"start": 9137,
"tag": "USERNAME",
"value": ""
},
{
"context": "\n :status \"T\"}\n {:name \"Bicios@s\"\n :leader \"biciosolider\"\n :leader_ema",
"end": 9139,
"score": 0.5811498165130615,
"start": 9138,
"tag": "NAME",
"value": "s"
},
{
"context": "}\n {:name \"Bicios@s\"\n :leader \"biciosolider\"\n :leader_email \"biciosolider@server.com\"\n ",
"end": 9172,
"score": 0.9995704293251038,
"start": 9160,
"tag": "USERNAME",
"value": "biciosolider"
},
{
"context": " :leader \"biciosolider\"\n :leader_email \"biciosolider@server.com\"\n :notes \"\"\n :status \"T\"}\n {",
"end": 9216,
"score": 0.9999193549156189,
"start": 9193,
"tag": "EMAIL",
"value": "biciosolider@server.com"
},
{
"context": " \"\"\n :status \"T\"}\n {:name \"AeroGreens\"\n :leader \"aerogreens\"\n :leader_email",
"end": 9291,
"score": 0.9992771148681641,
"start": 9281,
"tag": "NAME",
"value": "AeroGreens"
},
{
"context": " {:name \"AeroGreens\"\n :leader \"aerogreens\"\n :leader_email \"aerogreens@server.com\"\n :n",
"end": 9322,
"score": 0.9996861219406128,
"start": 9312,
"tag": "USERNAME",
"value": "aerogreens"
},
{
"context": " :leader \"aerogreens\"\n :leader_email \"aerogreens@server.com\"\n :notes \"\"\n :status \"T\"}\n {",
"end": 9364,
"score": 0.9999189376831055,
"start": 9343,
"tag": "EMAIL",
"value": "aerogreens@server.com"
},
{
"context": " \"\"\n :status \"T\"}\n {:name \"Akalambrados\"\n :leader \"Frank\"\n :leader_email \"fra",
"end": 9441,
"score": 0.9991481900215149,
"start": 9429,
"tag": "NAME",
"value": "Akalambrados"
},
{
"context": " {:name \"Akalambrados\"\n :leader \"Frank\"\n :leader_email \"frank@akalambrados.com\"\n :",
"end": 9467,
"score": 0.9972992539405823,
"start": 9462,
"tag": "NAME",
"value": "Frank"
},
{
"context": "dos\"\n :leader \"Frank\"\n :leader_email \"frank@akalambrados.com\"\n :notes \"\"\n :status \"T\"}\n {",
"end": 9510,
"score": 0.9999259114265442,
"start": 9488,
"tag": "EMAIL",
"value": "frank@akalambrados.com"
},
{
"context": " \"\"\n :status \"T\"}\n {:name \"V-Light\"\n :leader \"vlight\"\n :leader_email \"vl",
"end": 9582,
"score": 0.9863083362579346,
"start": 9575,
"tag": "NAME",
"value": "V-Light"
},
{
"context": "\"}\n {:name \"V-Light\"\n :leader \"vlight\"\n :leader_email \"vlight@server.com\"\n :notes",
"end": 9609,
"score": 0.9994785785675049,
"start": 9603,
"tag": "USERNAME",
"value": "vlight"
},
{
"context": "ht\"\n :leader \"vlight\"\n :leader_email \"vlight@server.com\"\n :notes \"\"\n :status \"T\"}\n {",
"end": 9647,
"score": 0.9999099373817444,
"start": 9630,
"tag": "EMAIL",
"value": "vlight@server.com"
},
{
"context": " \"\"\n :status \"T\"}\n {:name \"Aferreitorxs\"\n :leader \"aferreitorxslider\"\n :leade",
"end": 9724,
"score": 0.9987595677375793,
"start": 9712,
"tag": "NAME",
"value": "Aferreitorxs"
},
{
"context": " {:name \"Aferreitorxs\"\n :leader \"aferreitorxslider\"\n :leader_email \"aferreitorxs@server.com\"\n ",
"end": 9762,
"score": 0.9993958473205566,
"start": 9745,
"tag": "USERNAME",
"value": "aferreitorxslider"
},
{
"context": "ader \"aferreitorxslider\"\n :leader_email \"aferreitorxs@server.com\"\n :notes \"\"\n :status \"T\"}\n {",
"end": 9806,
"score": 0.9999150037765503,
"start": 9783,
"tag": "EMAIL",
"value": "aferreitorxs@server.com"
},
{
"context": " \"\"\n :status \"T\"}\n {:name \"Mujeres al Pedal\"\n :leader \"mujeres\"\n :leader_email \"m",
"end": 9887,
"score": 0.9998769760131836,
"start": 9871,
"tag": "NAME",
"value": "Mujeres al Pedal"
},
{
"context": "ame \"Mujeres al Pedal\"\n :leader \"mujeres\"\n :leader_email \"mujeres@server.com\"\n :note",
"end": 9915,
"score": 0.9996691346168518,
"start": 9908,
"tag": "USERNAME",
"value": "mujeres"
},
{
"context": "l\"\n :leader \"mujeres\"\n :leader_email \"mujeres@server.com\"\n :notes \"\"\n :status \"T\"}\n {",
"end": 9954,
"score": 0.9999153017997742,
"start": 9936,
"tag": "EMAIL",
"value": "mujeres@server.com"
},
{
"context": " \"\"\n :status \"T\"}\n {:name \"Raptors\"\n :leader \"raptors\"\n :leader_email \"r",
"end": 10026,
"score": 0.9989621639251709,
"start": 10019,
"tag": "NAME",
"value": "Raptors"
},
{
"context": "\"}\n {:name \"Raptors\"\n :leader \"raptors\"\n :leader_email \"raptors@server.com\"\n :note",
"end": 10054,
"score": 0.9996296763420105,
"start": 10047,
"tag": "USERNAME",
"value": "raptors"
},
{
"context": "s\"\n :leader \"raptors\"\n :leader_email \"raptors@server.com\"\n :notes \"\"\n :status \"T\"}\n {",
"end": 10093,
"score": 0.9999173283576965,
"start": 10075,
"tag": "EMAIL",
"value": "raptors@server.com"
},
{
"context": " \"\"\n :status \"T\"}\n {:name \"Victorianos\"\n :leader \"victorianos\"\n :leader_emai",
"end": 10169,
"score": 0.9991742968559265,
"start": 10158,
"tag": "NAME",
"value": "Victorianos"
},
{
"context": " {:name \"Victorianos\"\n :leader \"victorianos\"\n :leader_email \"victorianos@server.com\"\n :",
"end": 10201,
"score": 0.9995620846748352,
"start": 10190,
"tag": "USERNAME",
"value": "victorianos"
},
{
"context": " :leader \"victorianos\"\n :leader_email \"victorianos@server.com\"\n :notes \"\"\n :status \"T\"}\n {",
"end": 10244,
"score": 0.9999158382415771,
"start": 10222,
"tag": "EMAIL",
"value": "victorianos@server.com"
},
{
"context": " \"\"\n :status \"T\"}\n {:name \"I. V. Cycling (Inter)\"\n :leader \"ivcycling\"\n :leade",
"end": 10322,
"score": 0.999864399433136,
"start": 10309,
"tag": "NAME",
"value": "I. V. Cycling"
},
{
"context": " \"I. V. Cycling (Inter)\"\n :leader \"ivcycling\"\n :leader_email \"ivcycling@server.com\"\n :no",
"end": 10360,
"score": 0.9985302090644836,
"start": 10351,
"tag": "USERNAME",
"value": "ivcycling"
},
{
"context": "\n :leader \"ivcycling\"\n :leader_email \"ivcycling@server.com\"\n :notes \"\"\n :status \"T\"}\n {",
"end": 10401,
"score": 0.999918520450592,
"start": 10381,
"tag": "EMAIL",
"value": "ivcycling@server.com"
},
{
"context": " \"\"\n :status \"T\"}\n {:name \"NONSTOP\"\n :leader \"nonstop\"\n :leader_email \"n",
"end": 10473,
"score": 0.9273796081542969,
"start": 10466,
"tag": "USERNAME",
"value": "NONSTOP"
},
{
"context": "\"}\n {:name \"NONSTOP\"\n :leader \"nonstop\"\n :leader_email \"nonstop@server.com\"\n :note",
"end": 10501,
"score": 0.9984393119812012,
"start": 10494,
"tag": "USERNAME",
"value": "nonstop"
},
{
"context": "P\"\n :leader \"nonstop\"\n :leader_email \"nonstop@server.com\"\n :notes \"\"\n :status \"T\"}])\n\n(",
"end": 10540,
"score": 0.9999146461486816,
"start": 10522,
"tag": "EMAIL",
"value": "nonstop@server.com"
},
{
"context": "a \"20:00:00\"\n :leader \"Hector Lucero\"\n :leader_email \"hectorqlucero@gmail.com\"",
"end": 11061,
"score": 0.999826192855835,
"start": 11048,
"tag": "NAME",
"value": "Hector Lucero"
},
{
"context": " \"Hector Lucero\"\n :leader_email \"hectorqlucero@gmail.com\"\n :cuadrante 1\n :repetir ",
"end": 11110,
"score": 0.9999257326126099,
"start": 11087,
"tag": "EMAIL",
"value": "hectorqlucero@gmail.com"
},
{
"context": "a \"20:00:00\"\n :leader \"Ruth\"\n :leader_email \"hectorqlucero@gmail.com\"",
"end": 11687,
"score": 0.9996427297592163,
"start": 11683,
"tag": "NAME",
"value": "Ruth"
},
{
"context": ":leader \"Ruth\"\n :leader_email \"hectorqlucero@gmail.com\"\n :cuadrante 1\n :repetir ",
"end": 11736,
"score": 0.9999253749847412,
"start": 11713,
"tag": "EMAIL",
"value": "hectorqlucero@gmail.com"
},
{
"context": "a y un tubo de repuesto.\"\n :punto_reunion \"Parque Hidalgo\"\n :nivel \"M\"\n :distancia ",
"end": 12045,
"score": 0.9998841285705566,
"start": 12031,
"tag": "NAME",
"value": "Parque Hidalgo"
},
{
"context": "a \"20:00:00\"\n :leader \"Humberto\"\n :leader_email \"hectorqlucero@gmail.com\"",
"end": 12245,
"score": 0.9998376965522766,
"start": 12237,
"tag": "NAME",
"value": "Humberto"
},
{
"context": "der \"Humberto\"\n :leader_email \"hectorqlucero@gmail.com\"\n :cuadrante 1\n :repetir ",
"end": 12294,
"score": 0.9999260306358337,
"start": 12271,
"tag": "EMAIL",
"value": "hectorqlucero@gmail.com"
},
{
"context": "a y un tubo de repuesto.\"\n :punto_reunion \"Parque Hidalgo\"\n :nivel \"P\"\n :distancia ",
"end": 12607,
"score": 0.9998884201049805,
"start": 12593,
"tag": "NAME",
"value": "Parque Hidalgo"
},
{
"context": "a \"20:00:00\"\n :leader \"Martha Parada\"\n :leader_email \"hectorqlucero@gmail.com\"",
"end": 12813,
"score": 0.9999059438705444,
"start": 12800,
"tag": "NAME",
"value": "Martha Parada"
},
{
"context": " \"Martha Parada\"\n :leader_email \"hectorqlucero@gmail.com\"\n :cuadrante 1\n :repetir ",
"end": 12862,
"score": 0.9999275207519531,
"start": 12839,
"tag": "EMAIL",
"value": "hectorqlucero@gmail.com"
},
{
"context": "a \"08:00:00\"\n :leader_email \"hectorqlucero@gmail.com\"\n :repetir \"F\"\n :anonimo ",
"end": 13566,
"score": 0.99992436170578,
"start": 13543,
"tag": "EMAIL",
"value": "hectorqlucero@gmail.com"
},
{
"context": "a \"20:00:00\"\n :leader \"Melissa Utsler\"\n :leader_email \"hectorqlucero@gmail.com\"",
"end": 14555,
"score": 0.9998967051506042,
"start": 14541,
"tag": "NAME",
"value": "Melissa Utsler"
},
{
"context": " \"Melissa Utsler\"\n :leader_email \"hectorqlucero@gmail.com\"\n :cuadrante 1\n :repetir ",
"end": 14604,
"score": 0.9999247789382935,
"start": 14581,
"tag": "EMAIL",
"value": "hectorqlucero@gmail.com"
},
{
"context": " un tubo de repuesto.\"\n :punto_reunion \"Parque Hidalgo\"\n :nivel \"P\"\n :distancia ",
"end": 14917,
"score": 0.8140131235122681,
"start": 14906,
"tag": "NAME",
"value": "que Hidalgo"
},
{
"context": "a \"20:00:00\"\n :leader \"Chefsito\"\n :leader_email \"hectorqlucero@gmail.com\"",
"end": 15118,
"score": 0.7191879749298096,
"start": 15110,
"tag": "USERNAME",
"value": "Chefsito"
},
{
"context": "der \"Chefsito\"\n :leader_email \"hectorqlucero@gmail.com\"\n :cuadrante 1\n :repetir ",
"end": 15167,
"score": 0.9999274015426636,
"start": 15144,
"tag": "EMAIL",
"value": "hectorqlucero@gmail.com"
},
{
"context": " un tubo de repuesto.\"\n :punto_reunion \"Parque Hidalgo\"\n :nivel \"M\"\n :distancia ",
"end": 15477,
"score": 0.885866105556488,
"start": 15466,
"tag": "NAME",
"value": "que Hidalgo"
},
{
"context": "a \"20:00:00\"\n :leader \"Humberto\"\n :leader_email \"hectorqlucero@gmail.com\"",
"end": 15676,
"score": 0.9947120547294617,
"start": 15668,
"tag": "NAME",
"value": "Humberto"
},
{
"context": "der \"Humberto\"\n :leader_email \"hectorqlucero@gmail.com\"\n :cuadrante 1\n :repetir ",
"end": 15725,
"score": 0.999927282333374,
"start": 15702,
"tag": "EMAIL",
"value": "hectorqlucero@gmail.com"
},
{
"context": "ubo de repuesto.\"\n :punto_reunion \"Parque Hidalgo\"\n :nivel \"A\"\n :distancia ",
"end": 16008,
"score": 0.691580057144165,
"start": 16006,
"tag": "NAME",
"value": "id"
},
{
"context": "a \"20:00:00\"\n :leader \"Oscar Raul\"\n :leader_email \"hectorqlucero@gmail.com\"",
"end": 16215,
"score": 0.9996885657310486,
"start": 16205,
"tag": "NAME",
"value": "Oscar Raul"
},
{
"context": "r \"Oscar Raul\"\n :leader_email \"hectorqlucero@gmail.com\"\n :cuadrante 1\n :repetir ",
"end": 16264,
"score": 0.9999275207519531,
"start": 16241,
"tag": "EMAIL",
"value": "hectorqlucero@gmail.com"
},
{
"context": "a y un tubo de repuesto.\"\n :punto_reunion \"Parque Hidalgo\"\n :nivel \"P\"\n :distancia ",
"end": 16551,
"score": 0.9998005032539368,
"start": 16537,
"tag": "NAME",
"value": "Parque Hidalgo"
},
{
"context": "a \"20:00:00\"\n :leader \"Jose el Pechocho\"\n :leader_email \"hectorqlucero@gmail.com\"",
"end": 16760,
"score": 0.9998771548271179,
"start": 16744,
"tag": "NAME",
"value": "Jose el Pechocho"
},
{
"context": " \"Jose el Pechocho\"\n :leader_email \"hectorqlucero@gmail.com\"\n :cuadrante 1\n :repetir ",
"end": 16809,
"score": 0.9999244213104248,
"start": 16786,
"tag": "EMAIL",
"value": "hectorqlucero@gmail.com"
},
{
"context": " :hora \"08:00:00\"\n :leader \"Martha Parada\"\n :leader_email \"hectorqlucero@gmail.com\"\n ",
"end": 17982,
"score": 0.9999060034751892,
"start": 17969,
"tag": "NAME",
"value": "Martha Parada"
},
{
"context": "leader \"Martha Parada\"\n :leader_email \"hectorqlucero@gmail.com\"\n :repetir \"F\"\n :anonimo \"F\"\n ",
"end": 18027,
"score": 0.9999269843101501,
"start": 18004,
"tag": "EMAIL",
"value": "hectorqlucero@gmail.com"
},
{
"context": "ente al final del evento\"\n :punto_reunion \"Parque Hidalgo\"\n :nivel \"A\"\n :distancia ",
"end": 18479,
"score": 0.999832808971405,
"start": 18465,
"tag": "NAME",
"value": "Parque Hidalgo"
},
{
"context": "a \"06:00:00\"\n :leader \"Rosy Rutiaga\"\n :leader_email \"hectorqlucero@gmail.com\"",
"end": 18646,
"score": 0.9999080896377563,
"start": 18634,
"tag": "NAME",
"value": "Rosy Rutiaga"
},
{
"context": " \"Rosy Rutiaga\"\n :leader_email \"hectorqlucero@gmail.com\"\n :repetir \"F\"\n :anonimo ",
"end": 18695,
"score": 0.9999268651008606,
"start": 18672,
"tag": "EMAIL",
"value": "hectorqlucero@gmail.com"
},
{
"context": " :leader \"\"\n :leader_email \"hectorqlucero@gmail.com\"\n :repetir \"F\"\n :anonimo ",
"end": 19420,
"score": 0.9999293088912964,
"start": 19397,
"tag": "EMAIL",
"value": "hectorqlucero@gmail.com"
},
{
"context": "_link-rows\n [{:rodadas_id \"1\"\n :user \"Hector Lucero\"\n :comentarios \"Alli estare en punto.\"\n :em",
"end": 19555,
"score": 0.9998208284378052,
"start": 19542,
"tag": "NAME",
"value": "Hector Lucero"
},
{
"context": "ntarios \"Alli estare en punto.\"\n :email \"hectorqlucero@gmail.com\"}\n {:rodadas_id \"1\"\n :user \"Martha L",
"end": 19639,
"score": 0.9999282360076904,
"start": 19616,
"tag": "EMAIL",
"value": "hectorqlucero@gmail.com"
},
{
"context": "mail.com\"}\n {:rodadas_id \"1\"\n :user \"Martha Lucero\"\n :comentarios \"Alli estaremos\"\n :email ",
"end": 19694,
"score": 0.9998803734779358,
"start": 19681,
"tag": "NAME",
"value": "Martha Lucero"
},
{
"context": " :user \"Martha Lucero\"\n :comentarios \"Alli estaremos\"\n :email \"marthalucero56@gmail",
"end": 19718,
"score": 0.8128633499145508,
"start": 19714,
"tag": "NAME",
"value": "Alli"
},
{
"context": " :comentarios \"Alli estaremos\"\n :email \"marthalucero56@gmail.com\"}\n {:rodadas_id \"2\"\n :user \"Martha L",
"end": 19772,
"score": 0.9999311566352844,
"start": 19748,
"tag": "EMAIL",
"value": "marthalucero56@gmail.com"
},
{
"context": "mail.com\"}\n {:rodadas_id \"2\"\n :user \"Martha Lucero\"\n :comentarios \"Alli estaremos\"\n :email ",
"end": 19827,
"score": 0.9998661279678345,
"start": 19814,
"tag": "NAME",
"value": "Martha Lucero"
},
{
"context": " :user \"Martha Lucero\"\n :comentarios \"Alli estaremos\"\n :email \"marthalucero56@gmail",
"end": 19851,
"score": 0.7355307340621948,
"start": 19847,
"tag": "NAME",
"value": "Alli"
},
{
"context": " :comentarios \"Alli estaremos\"\n :email \"marthalucero56@gmail.com\"}\n {:rodadas_id \"2\"\n :user \"Hector L",
"end": 19905,
"score": 0.9999322295188904,
"start": 19881,
"tag": "EMAIL",
"value": "marthalucero56@gmail.com"
},
{
"context": "mail.com\"}\n {:rodadas_id \"2\"\n :user \"Hector Lucero\"\n :comentarios \"Alli estaremos\"\n :email ",
"end": 19960,
"score": 0.9998258948326111,
"start": 19947,
"tag": "NAME",
"value": "Hector Lucero"
},
{
"context": " :user \"Hector Lucero\"\n :comentarios \"Alli estaremos\"\n :email \"hectorqlucero@gmai",
"end": 19982,
"score": 0.7288656234741211,
"start": 19980,
"tag": "NAME",
"value": "Al"
},
{
"context": " :comentarios \"Alli estaremos\"\n :email \"hectorqlucero@gmail.com\"}\n {:rodadas_id \"3\"\n :user \"Martha L",
"end": 20037,
"score": 0.9999295473098755,
"start": 20014,
"tag": "EMAIL",
"value": "hectorqlucero@gmail.com"
},
{
"context": "mail.com\"}\n {:rodadas_id \"3\"\n :user \"Martha Lucero\"\n :comentarios \"Alli estaremos\"\n :email ",
"end": 20092,
"score": 0.999878466129303,
"start": 20079,
"tag": "NAME",
"value": "Martha Lucero"
},
{
"context": " :user \"Martha Lucero\"\n :comentarios \"Alli estaremos\"\n :email \"marthalucero56@gmail",
"end": 20116,
"score": 0.7760818004608154,
"start": 20112,
"tag": "NAME",
"value": "Alli"
},
{
"context": " :comentarios \"Alli estaremos\"\n :email \"marthalucero56@gmail.com\"}\n {:rodadas_id \"3\"\n :user \"Hector L",
"end": 20170,
"score": 0.9999318718910217,
"start": 20146,
"tag": "EMAIL",
"value": "marthalucero56@gmail.com"
},
{
"context": "mail.com\"}\n {:rodadas_id \"3\"\n :user \"Hector Lucero\"\n :comentarios \"Alli estaremos\"\n :email ",
"end": 20225,
"score": 0.9998518228530884,
"start": 20212,
"tag": "NAME",
"value": "Hector Lucero"
},
{
"context": " :user \"Hector Lucero\"\n :comentarios \"Alli estaremos\"\n :email \"hectorqlucero@gmail.",
"end": 20249,
"score": 0.851632833480835,
"start": 20245,
"tag": "NAME",
"value": "Alli"
},
{
"context": " :comentarios \"Alli estaremos\"\n :email \"hectorqlucero@gmail.com\"}\n {:rodadas_id \"4\"\n :user \"Martha L",
"end": 20302,
"score": 0.9999301433563232,
"start": 20279,
"tag": "EMAIL",
"value": "hectorqlucero@gmail.com"
},
{
"context": "mail.com\"}\n {:rodadas_id \"4\"\n :user \"Martha Lucero\"\n :comentarios \"Alli estaremos\"\n :email ",
"end": 20357,
"score": 0.999887228012085,
"start": 20344,
"tag": "NAME",
"value": "Martha Lucero"
},
{
"context": " :comentarios \"Alli estaremos\"\n :email \"marthalucero56@gmail.com\"}\n {:rodadas_id \"4\"\n :user \"Hector L",
"end": 20435,
"score": 0.9999317526817322,
"start": 20411,
"tag": "EMAIL",
"value": "marthalucero56@gmail.com"
},
{
"context": "mail.com\"}\n {:rodadas_id \"4\"\n :user \"Hector Lucero\"\n :comentarios \"Alli estaremos\"\n :email ",
"end": 20490,
"score": 0.9998131990432739,
"start": 20477,
"tag": "NAME",
"value": "Hector Lucero"
},
{
"context": " :comentarios \"Alli estaremos\"\n :email \"hectorqlucero@gmail.com\"}\n {:rodadas_id \"8\"\n :user \"Martha L",
"end": 20567,
"score": 0.9999253749847412,
"start": 20544,
"tag": "EMAIL",
"value": "hectorqlucero@gmail.com"
},
{
"context": "mail.com\"}\n {:rodadas_id \"8\"\n :user \"Martha Lucero\"\n :comentarios \"Alli estaremos\"\n :email ",
"end": 20622,
"score": 0.9998655915260315,
"start": 20609,
"tag": "NAME",
"value": "Martha Lucero"
},
{
"context": " :comentarios \"Alli estaremos\"\n :email \"marthalucero56@gmail.com\"}\n {:rodadas_id \"8\"\n :user \"Hector L",
"end": 20700,
"score": 0.9999294281005859,
"start": 20676,
"tag": "EMAIL",
"value": "marthalucero56@gmail.com"
},
{
"context": "mail.com\"}\n {:rodadas_id \"8\"\n :user \"Hector Lucero\"\n :comentarios \"Alli estaremos\"\n :email ",
"end": 20755,
"score": 0.9998627305030823,
"start": 20742,
"tag": "NAME",
"value": "Hector Lucero"
},
{
"context": " :comentarios \"Alli estaremos\"\n :email \"hectorqlucero@gmail.com\"}])\n\n(def user-rows\n [{:lastname \"Lucero\"\n :",
"end": 20832,
"score": 0.9999253749847412,
"start": 20809,
"tag": "EMAIL",
"value": "hectorqlucero@gmail.com"
},
{
"context": "@gmail.com\"}])\n\n(def user-rows\n [{:lastname \"Lucero\"\n :firstname \"Hector\"\n :username \"hectorql",
"end": 20875,
"score": 0.8294893503189087,
"start": 20872,
"tag": "NAME",
"value": "ero"
},
{
"context": " \"Lucero\"\n :firstname \"Hector\"\n :username \"hectorqlucero@gmail.com\"\n :password (crypt/encrypt \"elmo1200\")\n :d",
"end": 20940,
"score": 0.9999262690544128,
"start": 20917,
"tag": "EMAIL",
"value": "hectorqlucero@gmail.com"
},
{
"context": "qlucero@gmail.com\"\n :password (crypt/encrypt \"elmo1200\")\n :dob \"1957-02-07\"\n :email \"hec",
"end": 20981,
"score": 0.9993302226066589,
"start": 20973,
"tag": "PASSWORD",
"value": "elmo1200"
},
{
"context": "200\")\n :dob \"1957-02-07\"\n :email \"hectorqlucero@gmail.com\"\n :level \"S\"\n :active \"T\"}\n {:last",
"end": 21051,
"score": 0.9999231696128845,
"start": 21028,
"tag": "EMAIL",
"value": "hectorqlucero@gmail.com"
},
{
"context": "evel \"S\"\n :active \"T\"}\n {:lastname \"Hernandez\"\n :firstname \"Oscar\"\n :username \"raro",
"end": 21112,
"score": 0.5682543516159058,
"start": 21109,
"tag": "NAME",
"value": "ern"
},
{
"context": "Hernandez\"\n :firstname \"Oscar\"\n :username \"rarome93@gmail.com\"\n :password (crypt/encrypt \"oscarhernandez\")\n",
"end": 21176,
"score": 0.9999254941940308,
"start": 21158,
"tag": "EMAIL",
"value": "rarome93@gmail.com"
},
{
"context": "arome93@gmail.com\"\n :password (crypt/encrypt \"oscarhernandez\")\n :dob \"1975-10-08\"\n :email \"rar",
"end": 21223,
"score": 0.9993345141410828,
"start": 21209,
"tag": "PASSWORD",
"value": "oscarhernandez"
},
{
"context": "dez\")\n :dob \"1975-10-08\"\n :email \"rarome93@gmail.com\"\n :level \"S\"\n :active \"T\"}\n {:last",
"end": 21288,
"score": 0.9999260902404785,
"start": 21270,
"tag": "EMAIL",
"value": "rarome93@gmail.com"
},
{
"context": "level \"S\"\n :active \"T\"}\n {:lastname \"Romero\"\n :firstname \"Marco\"\n :username \"mromeropm",
"end": 21351,
"score": 0.748559296131134,
"start": 21345,
"tag": "NAME",
"value": "Romero"
},
{
"context": " \"Romero\"\n :firstname \"Marco\"\n :username \"mromeropmx@hotmail.com\"\n :password (crypt/encrypt \"marcoromero\")\n ",
"end": 21414,
"score": 0.999920129776001,
"start": 21392,
"tag": "EMAIL",
"value": "mromeropmx@hotmail.com"
},
{
"context": "ropmx@hotmail.com\"\n :password (crypt/encrypt \"marcoromero\")\n :dob \"1975-03-06\"\n :email \"mro",
"end": 21458,
"score": 0.9992771148681641,
"start": 21447,
"tag": "PASSWORD",
"value": "marcoromero"
},
{
"context": "ero\")\n :dob \"1975-03-06\"\n :email \"mromeropmx@hotmail.com\"\n :level \"S\"\n :active \"T\"}\n {:last",
"end": 21527,
"score": 0.9999256134033203,
"start": 21505,
"tag": "EMAIL",
"value": "mromeropmx@hotmail.com"
},
{
"context": "level \"S\"\n :active \"T\"}\n {:lastname \"Lucero\"\n :firstname \"Martha\"\n :username \"marthalu",
"end": 21590,
"score": 0.9811208248138428,
"start": 21584,
"tag": "NAME",
"value": "Lucero"
},
{
"context": " \"Lucero\"\n :firstname \"Martha\"\n :username \"marthalucero56@gmail.com\"\n :dob \"1956-02-23\"\n :email \"mart",
"end": 21656,
"score": 0.9999299645423889,
"start": 21632,
"tag": "EMAIL",
"value": "marthalucero56@gmail.com"
},
{
"context": ".com\"\n :dob \"1956-02-23\"\n :email \"marthalucero56@gmail.com\"\n :password (crypt/encrypt \"preciosa\")\n :l",
"end": 21726,
"score": 0.9999273419380188,
"start": 21702,
"tag": "EMAIL",
"value": "marthalucero56@gmail.com"
},
{
"context": "ucero56@gmail.com\"\n :password (crypt/encrypt \"preciosa\")\n :level \"U\"\n :active \"T\"}])\n\n(def ",
"end": 21767,
"score": 0.9991301894187927,
"start": 21759,
"tag": "PASSWORD",
"value": "preciosa"
}
] | src/cc/models/cdb.clj | hectorqlucero/cc | 3 | (ns cc.models.cdb
(:require [cc.models.crud :refer :all]
[noir.util.crypt :as crypt]))
(def users-sql
"CREATE TABLE users (
id int(11) NOT NULL AUTO_INCREMENT,
lastname varchar(45) DEFAULT NULL,
firstname varchar(45) DEFAULT NULL,
username varchar(45) DEFAULT NULL,
password TEXT DEFAULT NULL,
dob varchar(45) DEFAULT NULL,
cell varchar(45) DEFAULT NULL,
phone varchar(45) DEFAULT NULL,fax varchar(45) DEFAULT NULL,
email varchar(100) DEFAULT NULL,
level char(1) DEFAULT NULL COMMENT 'A=Administrador,U=Usuario,S=Sistema',
active char(1) DEFAULT NULL COMMENT 'T=Active,F=Not active',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8")
(def cuadrantes-sql
"CREATE TABLE cuadrantes (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(100) DEFAULT NULL,
leader varchar(100) DEFAULT NULL,
leader_phone varchar(45) DEFAULT NULL,
leader_cell varchar(45) DEFAULT NULL,
leader_email varchar(100) DEFAULT NULL,
notes TEXT DEFAULT NULL,
status char(1) DEFAULT NULL COMMENT 'T=Active,F=Inactive',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8")
(def rodadas-sql
"CREATE TABLE rodadas (
id int(11) NOT NULL AUTO_INCREMENT,
descripcion_corta varchar(100) DEFAULT NULL,
descripcion varchar(3000) DEFAULT NULL,
punto_reunion varchar(1000) DEFAULT NULL,
nivel char(1) DEFAULT NULL COMMENT 'P=Principiantes,M=Medio,A=Avanzado,T=Todos',
distancia varchar(100) DEFAULT NULL,
velocidad varchar(100) DEFAULT NULL,
fecha date DEFAULT NULL,
hora time DEFAULT NULL,
leader varchar(100) DEFAULT NULL,
leader_email varchar(100) DEFAULT NULL,
cuadrante int(11) DEFAULT NULL,
repetir char(1) DEFAULT NULL COMMENT 'T=Si,F=No',
anonimo char(1) DEFAULT \"F\" COMMENT 'T=Si,F=No',
rodada char(1) DEFAULT \"T\" COMMENT 'T=Si,F=No',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8")
(def rodadas_link-sql
"CREATE TABLE rodadas_link (
id int(11) NOT NULL AUTO_INCREMENT,
rodadas_id int(11) NOT NULL,
user varchar(200) DEFAULT NULL,
comentarios TEXT DEFAULT NULL,
email varchar(100) DEFAULT NULL,
asistir char(1) DEFAULT \"T\" COMMENT 'T=Si,F=No',
PRIMARY KEY (id),
KEY rodadas_id (rodadas_id),
CONSTRAINT rodadas_link_ibfk_1 FOREIGN KEY (rodadas_id) REFERENCES rodadas (id) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8")
(def cartas-sql
"CREATE TABLE `cartas` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`categoria` char(1) DEFAULT NULL COMMENT 'A=Abierta,N=Novatos',
`sexo` char(1) DEFAULT NULL COMMENT 'V=Varonil,F=Femenil',
`bicicleta` char(1) DEFAULT NULL COMMENT 'F=Fija,S=SS,O=Otra',
`no_participacion` varchar(50) DEFAULT NULL,
`nombre` varchar(100) DEFAULT NULL,
`apellido_paterno` varchar(100) DEFAULT NULL,
`apellido_materno` varchar(100) DEFAULT NULL,
`equipo` varchar(100) DEFAULT NULL,
`direccion` varchar(100) DEFAULT NULL,
`pais` varchar(100) DEFAULT NULL,
`ciudad` varchar(100) DEFAULT NULL,
`telefono` varchar(50) DEFAULT NULL,
`celular` varchar(50) DEFAULT NULL,
`email` varchar(100) DEFAULT NULL,
`tutor` varchar(100) DEFAULT NULL,
`dob` varchar(45) DEFAULT NULL,
`creado` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`carreras_id` int(11) unsigned DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=34 DEFAULT CHARSET=utf8")
(def puntos-sql
"CREATE TABLE `puntos` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`cartas_id` int(10) unsigned NOT NULL,
`puntos_p` int(11) DEFAULT NULL,
`puntos_1` int(11) DEFAULT NULL,
`puntos_2` int(11) DEFAULT NULL,
`puntos_3` int(11) DEFAULT NULL,
`creado` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
PRIMARY KEY (`id`),
KEY `f_cartas_id` (`cartas_id`),
CONSTRAINT `puntos_ibfk_1` FOREIGN KEY (`cartas_id`) REFERENCES `cartas` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=435 DEFAULT CHARSET=utf8")
(def categorias-sql
"CREATE TABLE `categorias` (
`id` char(1) NOT NULL,
`descripcion` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8")
(def carreras-sql
"CREATE TABLE `carreras` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`descripcion` varchar(500) DEFAULT NULL,
`fecha` date DEFAULT NULL,
`hora` time DEFAULT NULL,
`puntos_p` int(11) DEFAULT NULL,
`puntos_1` int(11) DEFAULT NULL,
`puntos_2` int(11) DEFAULT NULL,
`puntos_3` int(11) DEFAULT NULL,
`status` char(1) DEFAULT NULL COMMENT 'T=Activo,F=Inactivo',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8")
(def carreras_categorias-sql
"CREATE TABLE `carreras_categorias` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`carreras_id` int(10) unsigned NOT NULL,
`categorias_id` char(1) DEFAULT NULL,
`status` char(1) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=57 DEFAULT CHARSET=utf8")
(def contrareloj-sql
"CREATE TABLE `contrareloj` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`cartas_id` int(11) unsigned NOT NULL,
`carreras_id` int(11) unsigned NOT NULL,
`categorias_id` char(1) NOT NULL,
`empezar` time DEFAULT NULL,
`split1` time DEFAULT NULL,
`split2` time DEFAULT NULL,
`terminar` time DEFAULT NULL,
`penalty` int(11) unsigned DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=291 DEFAULT CHARSET=utf8")
(def taller-sql
"CREATE TABLE `taller` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`nombre` varchar(200) DEFAULT NULL,
`direccion` varchar(200) DEFAULT NULL,
`telefono` varchar(100) NOT NULL,
`horarios` text DEFAULT NULL,
`sitio` varchar(200) DEFAULT NULL,
`direcciones` text DEFAULT NULL,
`historia` text DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8")
(def imdecuf-sql
"CREATE TABLE `imdecuf` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`descripcion_corta` varchar(100) DEFAULT NULL,
`descripcion` text DEFAULT NULL,
`punto_reunion` varchar(1000) DEFAULT NULL,
`nivel` char(1) DEFAULT NULL COMMENT 'P=Principiantes,M=Medio,A=Avanzado,T=Todos',
`distancia` varchar(100) DEFAULT NULL,
`velocidad` varchar(100) DEFAULT NULL,
`fecha` date DEFAULT NULL,
`hora` time DEFAULT NULL,
`leader` varchar(100) DEFAULT NULL,
`leader_email` varchar(100) DEFAULT NULL,
`cuadrante` int(11) DEFAULT NULL,
`repetir` char(1) DEFAULT NULL COMMENT 'T=Si,F=No',
`anonimo` char(1) DEFAULT 'F' COMMENT 'T=Si,F=No',
`rodada` char(1) DEFAULT 'T' COMMENT 'T=Si,F=No',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=80 DEFAULT CHARSET=utf8")
(def cuadrantes-rows
[{:name "Rositas"
:leader "Rossy Rutiaga"
:leader_email "rossyrutiaga@rositas.com"
:notes "Cuadrante ciclista con todos los niveles para el gusto del ciclista."
:status "T"}
{:name "Azules"
:leader "Ana Villa"
:leader_email "anavilla@azules.com"
:notes "Cuadrante ciclista con niveles inter y fast."
:status "T"}
{:name "Grupo Ciclista La Vid"
:leader "Marco Romero"
:leader_email "mromeropmx@hotmail.com"
:notes "Un grupo cristiano con deseos de mejorar nuestra salud..."
:status "T"}
{:name "Reto Demoledor"
:leader "Reto"
:leader_email "retodemoledor@server.com"
:notes "Para mas información entra al grupo Reto Demoledor"
:status "T"}
{:name "Reto Aerobiker"
:leader "retoaerobiker"
:leader_email "retoaerobiker@server.com"
:notes "Reto madrugador 5x5 mas detalles en Aerobikers (FB)"
:status "T"}
{:name "Blanco"
:leader "blancolider"
:leader_email "blancolider@server.com"
:notes ""
:status "T"}
{:name "Bicios@s"
:leader "biciosolider"
:leader_email "biciosolider@server.com"
:notes ""
:status "T"}
{:name "AeroGreens"
:leader "aerogreens"
:leader_email "aerogreens@server.com"
:notes ""
:status "T"}
{:name "Akalambrados"
:leader "Frank"
:leader_email "frank@akalambrados.com"
:notes ""
:status "T"}
{:name "V-Light"
:leader "vlight"
:leader_email "vlight@server.com"
:notes ""
:status "T"}
{:name "Aferreitorxs"
:leader "aferreitorxslider"
:leader_email "aferreitorxs@server.com"
:notes ""
:status "T"}
{:name "Mujeres al Pedal"
:leader "mujeres"
:leader_email "mujeres@server.com"
:notes ""
:status "T"}
{:name "Raptors"
:leader "raptors"
:leader_email "raptors@server.com"
:notes ""
:status "T"}
{:name "Victorianos"
:leader "victorianos"
:leader_email "victorianos@server.com"
:notes ""
:status "T"}
{:name "I. V. Cycling (Inter)"
:leader "ivcycling"
:leader_email "ivcycling@server.com"
:notes ""
:status "T"}
{:name "NONSTOP"
:leader "nonstop"
:leader_email "nonstop@server.com"
:notes ""
:status "T"}])
(def rodadas-rows
[{:descripcion_corta "San Lunes"
:descripcion "Ruta que puede variar por las calles de la ciudad. Se rodaran por lo menos 20 kilometros. No olvidar traer casco, luces, auga y un tubo de repuesto."
:punto_reunion "Parque Hidalgo"
:nivel "P"
:distancia "20/28 Km"
:velocidad "18-25Km/hr"
:fecha "2018-10-08"
:hora "20:00:00"
:leader "Hector Lucero"
:leader_email "hectorqlucero@gmail.com"
:cuadrante 1
:repetir "T"
:anonimo "F"}
{:descripcion_corta "Santa Isabel"
:descripcion "Salimos del Parque Hidalgo hacia la Santa Isabel. Hidratacion en la OXXO que esta en la Lazaro Cardenas. No olividen traer casco, luces, agua y un tubo de repuesto."
:punto_reunion "Parque Hidalgo"
:nivel "T"
:distancia "30 Km"
:velocidad "Lights: 18-25Km/hr Intermedios: 25-35Km/hr"
:fecha "2018-10-09"
:hora "20:00:00"
:leader "Ruth"
:leader_email "hectorqlucero@gmail.com"
:cuadrante 1
:repetir "T"
:anonimo "F"}
{:descripcion_corta "Canalera"
:descripcion "Salimos por el canal de la Independencia a veces hasta el aeropuerto. No olviden traer casco, luces, agua y un tubo de repuesto."
:punto_reunion "Parque Hidalgo"
:nivel "M"
:distancia "30/50Km"
:velocidad "25-35Km/hr"
:fecha "2018-10-08"
:hora "20:00:00"
:leader "Humberto"
:leader_email "hectorqlucero@gmail.com"
:cuadrante 1
:repetir "T"
:anonimo "F"}
{:descripcion_corta "Adorada"
:descripcion "Ruta que puede variar entre el Campestre y el Panteon rumbo al aeropuerto. No olviden traer casco, luces, agua y un tubo de repuesto."
:punto_reunion "Parque Hidalgo"
:nivel "P"
:distancia "20/28 Km"
:velocidad "18-25Km/hr"
:fecha "2018-10-10"
:hora "20:00:00"
:leader "Martha Parada"
:leader_email "hectorqlucero@gmail.com"
:cuadrante 1
:repetir "T"
:anonimo "F"}
{:descripcion_corta "Vida Libre"
:descripcion "5to paseo recreativo Juntos por una VIDA LIBRE de Cancer de MAMA
Viste una prenda rosa y cuelga un liston del mismo color en tu bicicleta.
Rueda, corre, trota camina
Por tu seguridad no olvides tu casco
CIRCUITO PEDESTRES 2 KM
CIRCUITO CICLISTAS 4 KM
Registro: 7:30am. Salida: 8:00am"
:punto_reunion "Oficinas Centrales (Calle Calafia #1115)"
:nivel "T"
:distancia "4 Km"
:velocidad "5-25Km/hr"
:fecha "2018-10-21"
:hora "08:00:00"
:leader_email "hectorqlucero@gmail.com"
:repetir "F"
:anonimo "F"}
{:descripcion_corta "Circuito Obregon"
:descripcion "Hoy toca Circuito Ciclista Obregón los esperamos a las 8:00 PM en el punto de Reunión de Rectoría de la UABC/Biblioteca del Estado. El circuito tiene una longuitud de 3.2 Kilómetros con muy buena iluminado y el formato que se manejara para rodar será de las primeras 9 vueltas serán controladas a 30 kilómetros por hora como máximo y después se comenzara a aumentar la velocidad. Los ciclistas que lleguen más tarde se pueden acoplar al grupo o grupos. Así que a rodar con precaución y llevar sus luces si cuentan con ellas para iluminar esa mancha ciclista por toda la Av. Obregón, A Darle…."
:punto_reunion "Rectoría de la UABC/Biblioteca del Estado"
:nivel "T"
:distancia "20/50 Km"
:velocidad "10-40Km/hr"
:fecha "2018-10-24"
:hora "20:00:00"
:leader "Melissa Utsler"
:leader_email "hectorqlucero@gmail.com"
:cuadrante 1
:repetir "T"
:anonimo "F"}
{:descripcion_corta "Culinaria"
:descripcion "Salimos del parque Hidalgo hacia el panteon que esta rumbo al aeropuerto. No olviden traer casco, luces, agua y un tubo de repuesto."
:punto_reunion "Parque Hidalgo"
:nivel "P"
:distancia "20/28 Km"
:velocidad "18-25Km/hr"
:fecha "2018-10-11"
:hora "20:00:00"
:leader "Chefsito"
:leader_email "hectorqlucero@gmail.com"
:cuadrante 1
:repetir "T"
:anonimo "F"}
{:descripcion_corta "Intermedia"
:descripcion "Salimos del parque Hidalgo hacia el hotel que esta despues del OXXO. No olviden traer casco, luces, agua y un tubo de repuesto."
:punto_reunion "Parque Hidalgo"
:nivel "M"
:distancia "30 Km"
:velocidad "25-35 km/hr"
:fecha "2018-10-11"
:hora "20:00:00"
:leader "Humberto"
:leader_email "hectorqlucero@gmail.com"
:cuadrante 1
:repetir "T"
:anonimo "F"}
{:descripcion_corta "Pedacera"
:descripcion "Salimos del parque Hidalgo hacia el aeropuerto. No olviden traer casco, luces, agua y un tubo de repuesto."
:punto_reunion "Parque Hidalgo"
:nivel "A"
:distancia "50-60 Km"
:velocidad "30-40Km/hr"
:fecha "2018-10-11"
:hora "20:00:00"
:leader "Oscar Raul"
:leader_email "hectorqlucero@gmail.com"
:cuadrante 1
:repetir "T"
:anonimo "F"}
{:descripcion_corta "Familiar"
:descripcion "Salimos del Parque Hidalgo con ruta indefinida. No olviden traer casco, luces, agua y un tubo de repuesto."
:punto_reunion "Parque Hidalgo"
:nivel "P"
:distancia "20/28 Km"
:velocidad "18-25Km/hr"
:fecha "2018-10-12"
:hora "20:00:00"
:leader "Jose el Pechocho"
:leader_email "hectorqlucero@gmail.com"
:cuadrante 1
:repetir "T"
:anonimo "F"}
{:descripcion_corta "Mexicali Rumorosa"
:descripcion "Paseo Ciclista Mexicali-Rumorosa, es el Paseo ciclista mas impresionante en la franja fronteriza entre Mexicali B.C. y Estados Unidos por su vista espectacular natural, donde el participante se deleitara al observar paisajes de magnificas montañas conformadas por un increíble escenario de rocas gigantescas con impresionantes miradores, lo que caracteriza la subida de la carretera a la Rumorosa entre Mexicali y Tecate B.C.
Un Paseo divertido, familiar de sana convivencia para todos los que gustan de nuevos retos.
Una vez en la meta recibiremos a todos los participantes y sus Familia en una Convivencia en la Rumorosa donde además de pasar un rato agradable recibirán su Medalla por participar y se realiza una Rifa de 2 Bicicletas entre los Participantes."
:punto_reunion "Macroplaza del Valle Lázaro Cárdenas 2200 col. El Porvenir, 21220 Mexicali, Baja California."
:nivel "T"
:distancia "75 Km"
:fecha "2018-10-27"
:hora "08:00:00"
:leader "Martha Parada"
:leader_email "hectorqlucero@gmail.com"
:repetir "F"
:anonimo "F"
:velocidad "15-40Km/hr"}
{:descripcion_corta "VI Gran Fondo"
:descripcion "Desafiando tus piernas
VI Gran Fondo
Paseo Mexicali - San Felipe
Distancia: 200 kms de diversión
Ven a disfrutar de este paseo donde pondrás a prueba tus piernas.
Costo: $300 pesos
Contamos con ambulancia, hidrataciones, medalla y el mejor ambiente al final del evento"
:punto_reunion "Parque Hidalgo"
:nivel "A"
:distancia "200 Km"
:fecha "2018-11-10"
:hora "06:00:00"
:leader "Rosy Rutiaga"
:leader_email "hectorqlucero@gmail.com"
:repetir "F"
:anonimo "F"
:velocidad "15-40Km/hr"}
{:descripcion_corta "San Luis al Golfo"
:descripcion "5to paseo anual 360 Cycling Studio.
San Luis - El Golfo, 112 kilometros.
Inscripcion $550 pesos
Barredora
puntos de hidratacion
chip de cronometraje
Camiseta
Comida
Bebida
Medalla de Participacion
Transporte Golfo - San Luis
Informes: (653) 103-1460 * (653) 119-0725"
:punto_reunion "360 Cycling Studio, San Luis R.C."
:nivel "T"
:distancia "120 Km"
:velocidad "15-40Km/hr"
:fecha "2018-11-10"
:hora "07:00:00"
:leader ""
:leader_email "hectorqlucero@gmail.com"
:repetir "F"
:anonimo "F"}])
(def rodadas_link-rows
[{:rodadas_id "1"
:user "Hector Lucero"
:comentarios "Alli estare en punto."
:email "hectorqlucero@gmail.com"}
{:rodadas_id "1"
:user "Martha Lucero"
:comentarios "Alli estaremos"
:email "marthalucero56@gmail.com"}
{:rodadas_id "2"
:user "Martha Lucero"
:comentarios "Alli estaremos"
:email "marthalucero56@gmail.com"}
{:rodadas_id "2"
:user "Hector Lucero"
:comentarios "Alli estaremos"
:email "hectorqlucero@gmail.com"}
{:rodadas_id "3"
:user "Martha Lucero"
:comentarios "Alli estaremos"
:email "marthalucero56@gmail.com"}
{:rodadas_id "3"
:user "Hector Lucero"
:comentarios "Alli estaremos"
:email "hectorqlucero@gmail.com"}
{:rodadas_id "4"
:user "Martha Lucero"
:comentarios "Alli estaremos"
:email "marthalucero56@gmail.com"}
{:rodadas_id "4"
:user "Hector Lucero"
:comentarios "Alli estaremos"
:email "hectorqlucero@gmail.com"}
{:rodadas_id "8"
:user "Martha Lucero"
:comentarios "Alli estaremos"
:email "marthalucero56@gmail.com"}
{:rodadas_id "8"
:user "Hector Lucero"
:comentarios "Alli estaremos"
:email "hectorqlucero@gmail.com"}])
(def user-rows
[{:lastname "Lucero"
:firstname "Hector"
:username "hectorqlucero@gmail.com"
:password (crypt/encrypt "elmo1200")
:dob "1957-02-07"
:email "hectorqlucero@gmail.com"
:level "S"
:active "T"}
{:lastname "Hernandez"
:firstname "Oscar"
:username "rarome93@gmail.com"
:password (crypt/encrypt "oscarhernandez")
:dob "1975-10-08"
:email "rarome93@gmail.com"
:level "S"
:active "T"}
{:lastname "Romero"
:firstname "Marco"
:username "mromeropmx@hotmail.com"
:password (crypt/encrypt "marcoromero")
:dob "1975-03-06"
:email "mromeropmx@hotmail.com"
:level "S"
:active "T"}
{:lastname "Lucero"
:firstname "Martha"
:username "marthalucero56@gmail.com"
:dob "1956-02-23"
:email "marthalucero56@gmail.com"
:password (crypt/encrypt "preciosa")
:level "U"
:active "T"}])
(def categorias-rows
[{:id "A"
:descripcion "Infantil Mixta(hasta 12 años"}
{:id "B"
:descripcion "MTB Mixta Montaña"}
{:id "C"
:descripcion "Juveniles Varonil 13-14"}
{:id "D"
:descripcion "Juveniles Varonil 15-17"}
{:id "E"
:descripcion "Novatos Varonil"}
{:id "F"
:descripcion "Master Varonil 40 y mas"}
{:id "G"
:descripcion "Segunda Fuerza Varonil(Intermedios)"}
{:id "I"
:descripcion "Primera Fuerza Varonil(Avanzados)"}
{:id "J"
:descripcion "Piñon Fijo Varonil y una velicidad(SS)"}
{:id "K"
:descripcion "Femenil Juvenil 15-17"}
{:id "L"
:descripcion "Segunda Fuerza Femenil(Abierta, Novatas)"}
{:id "M"
:descripcion "Primera Fuerza Femenil(Avanzadas)"}
{:id "N"
:descripcion "Piñon Fijo Femenil y una velocidad(SS)"}])
(defn create-database []
"Creates database and a default admin user"
(Query! db users-sql)
(Query! db cuadrantes-sql)
(Query! db rodadas-sql)
(Query! db rodadas_link-sql)
(Query! db cartas-sql)
(Query! db categorias-sql)
(Query! db carreras-sql)
(Query! db puntos-sql)
(Query! db carreras_categorias-sql)
(Query! db contrareloj-sql)
(Query! db taller-sql)
(Query! db imdecuf-sql)
(Insert-multi db :users user-rows)
(Insert-multi db :rodadas rodadas-rows)
(Insert-multi db :rodadas_link rodadas_link-rows)
(Insert-multi db :cuadrantes cuadrantes-rows)
(Insert-multi db :categorias categorias-rows))
(defn reset-database []
"removes existing tables and recreates them"
(Query! db "DROP table IF EXISTS users")
(Query! db "DROP table IF EXISTS cuadrantes")
(Query! db "DROP table IF EXISTS rodadas_link")
(Query! db "DROP table IF EXISTS rodadas")
(Query! db "DROP table IF EXISTS cartas")
(Query! db "DROP table IF EXISTS puntos")
(Query! db "DROP table IF EXISTS categorias")
(Query! db "DROP table IF EXISTS carreras")
(Query! db "DROP table IF EXISTS carreras_categorias")
(Query! db "DROP table IF EXISTS contrareloj")
(Query! db "DROP table IF EXISTS taller")
(Query! db "DROP table IF EXISTS imdecuf")
(Query! db users-sql)
(Query! db cuadrantes-sql)
(Query! db rodadas-sql)
(Query! db rodadas_link-sql)
(Query! db cartas-sql)
(Query! db puntos-sql)
(Query! db categorias-sql)
(Query! db carreras-sql)
(Query! db carreras_categorias-sql)
(Query! db contrareloj-sql)
(Query! db taller-sql)
(Query! db imdecuf-sql)
(Insert-multi db :users user-rows)
(Insert-multi db :cuadrantes cuadrantes-rows)
(Insert-multi db :rodadas rodadas-rows)
(Insert-multi db :rodadas_link rodadas_link-rows)
(Insert-multi db :categorias categorias-rows))
(defn migrate []
"migrate by the seat of my pants"
(Query! db "DROP table IF EXISTS carreras"))
;; This is to create carreras_categorias example
;; (defn create-carreras-categorias []
;; (doseq [item (Query db "SELECT * FROM categorias")]
;; (doseq [sitem (Query db "SELECT * FROM carreras")]
;; (let [carreras_id (str (:id sitem))
;; categorias_id (str (:id item))
;; status "T"
;; id (:id (first (Query db ["SELECT id from carreras_categorias WHERE carreras_id = ? AND categorias_id = ?" carreras_id categorias_id])))
;; postvars {:id (str id)
;; :carreras_id carreras_id
;; :categorias_id categorias_id
;; :status status}]
;; (Save db :carreras_categorias postvars ["id = ?" id])))))
;;(migrate)
| 100308 | (ns cc.models.cdb
(:require [cc.models.crud :refer :all]
[noir.util.crypt :as crypt]))
(def users-sql
"CREATE TABLE users (
id int(11) NOT NULL AUTO_INCREMENT,
lastname varchar(45) DEFAULT NULL,
firstname varchar(45) DEFAULT NULL,
username varchar(45) DEFAULT NULL,
password TEXT DEFAULT NULL,
dob varchar(45) DEFAULT NULL,
cell varchar(45) DEFAULT NULL,
phone varchar(45) DEFAULT NULL,fax varchar(45) DEFAULT NULL,
email varchar(100) DEFAULT NULL,
level char(1) DEFAULT NULL COMMENT 'A=Administrador,U=Usuario,S=Sistema',
active char(1) DEFAULT NULL COMMENT 'T=Active,F=Not active',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8")
(def cuadrantes-sql
"CREATE TABLE cuadrantes (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(100) DEFAULT NULL,
leader varchar(100) DEFAULT NULL,
leader_phone varchar(45) DEFAULT NULL,
leader_cell varchar(45) DEFAULT NULL,
leader_email varchar(100) DEFAULT NULL,
notes TEXT DEFAULT NULL,
status char(1) DEFAULT NULL COMMENT 'T=Active,F=Inactive',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8")
(def rodadas-sql
"CREATE TABLE rodadas (
id int(11) NOT NULL AUTO_INCREMENT,
descripcion_corta varchar(100) DEFAULT NULL,
descripcion varchar(3000) DEFAULT NULL,
punto_reunion varchar(1000) DEFAULT NULL,
nivel char(1) DEFAULT NULL COMMENT 'P=Principiantes,M=Medio,A=Avanzado,T=Todos',
distancia varchar(100) DEFAULT NULL,
velocidad varchar(100) DEFAULT NULL,
fecha date DEFAULT NULL,
hora time DEFAULT NULL,
leader varchar(100) DEFAULT NULL,
leader_email varchar(100) DEFAULT NULL,
cuadrante int(11) DEFAULT NULL,
repetir char(1) DEFAULT NULL COMMENT 'T=Si,F=No',
anonimo char(1) DEFAULT \"F\" COMMENT 'T=Si,F=No',
rodada char(1) DEFAULT \"T\" COMMENT 'T=Si,F=No',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8")
(def rodadas_link-sql
"CREATE TABLE rodadas_link (
id int(11) NOT NULL AUTO_INCREMENT,
rodadas_id int(11) NOT NULL,
user varchar(200) DEFAULT NULL,
comentarios TEXT DEFAULT NULL,
email varchar(100) DEFAULT NULL,
asistir char(1) DEFAULT \"T\" COMMENT 'T=Si,F=No',
PRIMARY KEY (id),
KEY rodadas_id (rodadas_id),
CONSTRAINT rodadas_link_ibfk_1 FOREIGN KEY (rodadas_id) REFERENCES rodadas (id) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8")
(def cartas-sql
"CREATE TABLE `cartas` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`categoria` char(1) DEFAULT NULL COMMENT 'A=Abierta,N=Novatos',
`sexo` char(1) DEFAULT NULL COMMENT 'V=Varonil,F=Femenil',
`bicicleta` char(1) DEFAULT NULL COMMENT 'F=Fija,S=SS,O=Otra',
`no_participacion` varchar(50) DEFAULT NULL,
`nombre` varchar(100) DEFAULT NULL,
`apellido_paterno` varchar(100) DEFAULT NULL,
`apellido_materno` varchar(100) DEFAULT NULL,
`equipo` varchar(100) DEFAULT NULL,
`direccion` varchar(100) DEFAULT NULL,
`pais` varchar(100) DEFAULT NULL,
`ciudad` varchar(100) DEFAULT NULL,
`telefono` varchar(50) DEFAULT NULL,
`celular` varchar(50) DEFAULT NULL,
`email` varchar(100) DEFAULT NULL,
`tutor` varchar(100) DEFAULT NULL,
`dob` varchar(45) DEFAULT NULL,
`creado` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`carreras_id` int(11) unsigned DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=34 DEFAULT CHARSET=utf8")
(def puntos-sql
"CREATE TABLE `puntos` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`cartas_id` int(10) unsigned NOT NULL,
`puntos_p` int(11) DEFAULT NULL,
`puntos_1` int(11) DEFAULT NULL,
`puntos_2` int(11) DEFAULT NULL,
`puntos_3` int(11) DEFAULT NULL,
`creado` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
PRIMARY KEY (`id`),
KEY `f_cartas_id` (`cartas_id`),
CONSTRAINT `puntos_ibfk_1` FOREIGN KEY (`cartas_id`) REFERENCES `cartas` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=435 DEFAULT CHARSET=utf8")
(def categorias-sql
"CREATE TABLE `categorias` (
`id` char(1) NOT NULL,
`descripcion` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8")
(def carreras-sql
"CREATE TABLE `carreras` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`descripcion` varchar(500) DEFAULT NULL,
`fecha` date DEFAULT NULL,
`hora` time DEFAULT NULL,
`puntos_p` int(11) DEFAULT NULL,
`puntos_1` int(11) DEFAULT NULL,
`puntos_2` int(11) DEFAULT NULL,
`puntos_3` int(11) DEFAULT NULL,
`status` char(1) DEFAULT NULL COMMENT 'T=Activo,F=Inactivo',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8")
(def carreras_categorias-sql
"CREATE TABLE `carreras_categorias` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`carreras_id` int(10) unsigned NOT NULL,
`categorias_id` char(1) DEFAULT NULL,
`status` char(1) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=57 DEFAULT CHARSET=utf8")
(def contrareloj-sql
"CREATE TABLE `contrareloj` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`cartas_id` int(11) unsigned NOT NULL,
`carreras_id` int(11) unsigned NOT NULL,
`categorias_id` char(1) NOT NULL,
`empezar` time DEFAULT NULL,
`split1` time DEFAULT NULL,
`split2` time DEFAULT NULL,
`terminar` time DEFAULT NULL,
`penalty` int(11) unsigned DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=291 DEFAULT CHARSET=utf8")
(def taller-sql
"CREATE TABLE `taller` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`nombre` varchar(200) DEFAULT NULL,
`direccion` varchar(200) DEFAULT NULL,
`telefono` varchar(100) NOT NULL,
`horarios` text DEFAULT NULL,
`sitio` varchar(200) DEFAULT NULL,
`direcciones` text DEFAULT NULL,
`historia` text DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8")
(def imdecuf-sql
"CREATE TABLE `imdecuf` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`descripcion_corta` varchar(100) DEFAULT NULL,
`descripcion` text DEFAULT NULL,
`punto_reunion` varchar(1000) DEFAULT NULL,
`nivel` char(1) DEFAULT NULL COMMENT 'P=Principiantes,M=Medio,A=Avanzado,T=Todos',
`distancia` varchar(100) DEFAULT NULL,
`velocidad` varchar(100) DEFAULT NULL,
`fecha` date DEFAULT NULL,
`hora` time DEFAULT NULL,
`leader` varchar(100) DEFAULT NULL,
`leader_email` varchar(100) DEFAULT NULL,
`cuadrante` int(11) DEFAULT NULL,
`repetir` char(1) DEFAULT NULL COMMENT 'T=Si,F=No',
`anonimo` char(1) DEFAULT 'F' COMMENT 'T=Si,F=No',
`rodada` char(1) DEFAULT 'T' COMMENT 'T=Si,F=No',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=80 DEFAULT CHARSET=utf8")
(def cuadrantes-rows
[{:name "<NAME>"
:leader "<NAME>"
:leader_email "<EMAIL>"
:notes "Cuadrante ciclista con todos los niveles para el gusto del ciclista."
:status "T"}
{:name "<NAME>"
:leader "<NAME>"
:leader_email "<EMAIL>"
:notes "Cuadrante ciclista con niveles inter y fast."
:status "T"}
{:name "Grupo Ciclista La Vid"
:leader "<NAME>"
:leader_email "<EMAIL>"
:notes "Un grupo cristiano con deseos de mejorar nuestra salud..."
:status "T"}
{:name "<NAME>"
:leader "Ret<NAME>"
:leader_email "<EMAIL>"
:notes "Para mas información entra al grupo Reto Demoledor"
:status "T"}
{:name "<NAME>"
:leader "retoaerobiker"
:leader_email "<EMAIL>"
:notes "Reto madrugador 5x5 mas detalles en Aerobikers (FB)"
:status "T"}
{:name "<NAME>"
:leader "blancolider"
:leader_email "<EMAIL>"
:notes ""
:status "T"}
{:name "B<NAME>@<NAME>"
:leader "biciosolider"
:leader_email "<EMAIL>"
:notes ""
:status "T"}
{:name "<NAME>"
:leader "aerogreens"
:leader_email "<EMAIL>"
:notes ""
:status "T"}
{:name "<NAME>"
:leader "<NAME>"
:leader_email "<EMAIL>"
:notes ""
:status "T"}
{:name "<NAME>"
:leader "vlight"
:leader_email "<EMAIL>"
:notes ""
:status "T"}
{:name "<NAME>"
:leader "aferreitorxslider"
:leader_email "<EMAIL>"
:notes ""
:status "T"}
{:name "<NAME>"
:leader "mujeres"
:leader_email "<EMAIL>"
:notes ""
:status "T"}
{:name "<NAME>"
:leader "raptors"
:leader_email "<EMAIL>"
:notes ""
:status "T"}
{:name "<NAME>"
:leader "victorianos"
:leader_email "<EMAIL>"
:notes ""
:status "T"}
{:name "<NAME> (Inter)"
:leader "ivcycling"
:leader_email "<EMAIL>"
:notes ""
:status "T"}
{:name "NONSTOP"
:leader "nonstop"
:leader_email "<EMAIL>"
:notes ""
:status "T"}])
(def rodadas-rows
[{:descripcion_corta "San Lunes"
:descripcion "Ruta que puede variar por las calles de la ciudad. Se rodaran por lo menos 20 kilometros. No olvidar traer casco, luces, auga y un tubo de repuesto."
:punto_reunion "Parque Hidalgo"
:nivel "P"
:distancia "20/28 Km"
:velocidad "18-25Km/hr"
:fecha "2018-10-08"
:hora "20:00:00"
:leader "<NAME>"
:leader_email "<EMAIL>"
:cuadrante 1
:repetir "T"
:anonimo "F"}
{:descripcion_corta "Santa Isabel"
:descripcion "Salimos del Parque Hidalgo hacia la Santa Isabel. Hidratacion en la OXXO que esta en la Lazaro Cardenas. No olividen traer casco, luces, agua y un tubo de repuesto."
:punto_reunion "Parque Hidalgo"
:nivel "T"
:distancia "30 Km"
:velocidad "Lights: 18-25Km/hr Intermedios: 25-35Km/hr"
:fecha "2018-10-09"
:hora "20:00:00"
:leader "<NAME>"
:leader_email "<EMAIL>"
:cuadrante 1
:repetir "T"
:anonimo "F"}
{:descripcion_corta "Canalera"
:descripcion "Salimos por el canal de la Independencia a veces hasta el aeropuerto. No olviden traer casco, luces, agua y un tubo de repuesto."
:punto_reunion "<NAME>"
:nivel "M"
:distancia "30/50Km"
:velocidad "25-35Km/hr"
:fecha "2018-10-08"
:hora "20:00:00"
:leader "<NAME>"
:leader_email "<EMAIL>"
:cuadrante 1
:repetir "T"
:anonimo "F"}
{:descripcion_corta "Adorada"
:descripcion "Ruta que puede variar entre el Campestre y el Panteon rumbo al aeropuerto. No olviden traer casco, luces, agua y un tubo de repuesto."
:punto_reunion "<NAME>"
:nivel "P"
:distancia "20/28 Km"
:velocidad "18-25Km/hr"
:fecha "2018-10-10"
:hora "20:00:00"
:leader "<NAME>"
:leader_email "<EMAIL>"
:cuadrante 1
:repetir "T"
:anonimo "F"}
{:descripcion_corta "Vida Libre"
:descripcion "5to paseo recreativo Juntos por una VIDA LIBRE de Cancer de MAMA
Viste una prenda rosa y cuelga un liston del mismo color en tu bicicleta.
Rueda, corre, trota camina
Por tu seguridad no olvides tu casco
CIRCUITO PEDESTRES 2 KM
CIRCUITO CICLISTAS 4 KM
Registro: 7:30am. Salida: 8:00am"
:punto_reunion "Oficinas Centrales (Calle Calafia #1115)"
:nivel "T"
:distancia "4 Km"
:velocidad "5-25Km/hr"
:fecha "2018-10-21"
:hora "08:00:00"
:leader_email "<EMAIL>"
:repetir "F"
:anonimo "F"}
{:descripcion_corta "Circuito Obregon"
:descripcion "Hoy toca Circuito Ciclista Obregón los esperamos a las 8:00 PM en el punto de Reunión de Rectoría de la UABC/Biblioteca del Estado. El circuito tiene una longuitud de 3.2 Kilómetros con muy buena iluminado y el formato que se manejara para rodar será de las primeras 9 vueltas serán controladas a 30 kilómetros por hora como máximo y después se comenzara a aumentar la velocidad. Los ciclistas que lleguen más tarde se pueden acoplar al grupo o grupos. Así que a rodar con precaución y llevar sus luces si cuentan con ellas para iluminar esa mancha ciclista por toda la Av. Obregón, A Darle…."
:punto_reunion "Rectoría de la UABC/Biblioteca del Estado"
:nivel "T"
:distancia "20/50 Km"
:velocidad "10-40Km/hr"
:fecha "2018-10-24"
:hora "20:00:00"
:leader "<NAME>"
:leader_email "<EMAIL>"
:cuadrante 1
:repetir "T"
:anonimo "F"}
{:descripcion_corta "Culinaria"
:descripcion "Salimos del parque Hidalgo hacia el panteon que esta rumbo al aeropuerto. No olviden traer casco, luces, agua y un tubo de repuesto."
:punto_reunion "Par<NAME>"
:nivel "P"
:distancia "20/28 Km"
:velocidad "18-25Km/hr"
:fecha "2018-10-11"
:hora "20:00:00"
:leader "Chefsito"
:leader_email "<EMAIL>"
:cuadrante 1
:repetir "T"
:anonimo "F"}
{:descripcion_corta "Intermedia"
:descripcion "Salimos del parque Hidalgo hacia el hotel que esta despues del OXXO. No olviden traer casco, luces, agua y un tubo de repuesto."
:punto_reunion "Par<NAME>"
:nivel "M"
:distancia "30 Km"
:velocidad "25-35 km/hr"
:fecha "2018-10-11"
:hora "20:00:00"
:leader "<NAME>"
:leader_email "<EMAIL>"
:cuadrante 1
:repetir "T"
:anonimo "F"}
{:descripcion_corta "Pedacera"
:descripcion "Salimos del parque Hidalgo hacia el aeropuerto. No olviden traer casco, luces, agua y un tubo de repuesto."
:punto_reunion "Parque H<NAME>algo"
:nivel "A"
:distancia "50-60 Km"
:velocidad "30-40Km/hr"
:fecha "2018-10-11"
:hora "20:00:00"
:leader "<NAME>"
:leader_email "<EMAIL>"
:cuadrante 1
:repetir "T"
:anonimo "F"}
{:descripcion_corta "Familiar"
:descripcion "Salimos del Parque Hidalgo con ruta indefinida. No olviden traer casco, luces, agua y un tubo de repuesto."
:punto_reunion "<NAME>"
:nivel "P"
:distancia "20/28 Km"
:velocidad "18-25Km/hr"
:fecha "2018-10-12"
:hora "20:00:00"
:leader "<NAME>"
:leader_email "<EMAIL>"
:cuadrante 1
:repetir "T"
:anonimo "F"}
{:descripcion_corta "Mexicali Rumorosa"
:descripcion "Paseo Ciclista Mexicali-Rumorosa, es el Paseo ciclista mas impresionante en la franja fronteriza entre Mexicali B.C. y Estados Unidos por su vista espectacular natural, donde el participante se deleitara al observar paisajes de magnificas montañas conformadas por un increíble escenario de rocas gigantescas con impresionantes miradores, lo que caracteriza la subida de la carretera a la Rumorosa entre Mexicali y Tecate B.C.
Un Paseo divertido, familiar de sana convivencia para todos los que gustan de nuevos retos.
Una vez en la meta recibiremos a todos los participantes y sus Familia en una Convivencia en la Rumorosa donde además de pasar un rato agradable recibirán su Medalla por participar y se realiza una Rifa de 2 Bicicletas entre los Participantes."
:punto_reunion "Macroplaza del Valle Lázaro Cárdenas 2200 col. El Porvenir, 21220 Mexicali, Baja California."
:nivel "T"
:distancia "75 Km"
:fecha "2018-10-27"
:hora "08:00:00"
:leader "<NAME>"
:leader_email "<EMAIL>"
:repetir "F"
:anonimo "F"
:velocidad "15-40Km/hr"}
{:descripcion_corta "VI Gran Fondo"
:descripcion "Desafiando tus piernas
VI Gran Fondo
Paseo Mexicali - San Felipe
Distancia: 200 kms de diversión
Ven a disfrutar de este paseo donde pondrás a prueba tus piernas.
Costo: $300 pesos
Contamos con ambulancia, hidrataciones, medalla y el mejor ambiente al final del evento"
:punto_reunion "<NAME>"
:nivel "A"
:distancia "200 Km"
:fecha "2018-11-10"
:hora "06:00:00"
:leader "<NAME>"
:leader_email "<EMAIL>"
:repetir "F"
:anonimo "F"
:velocidad "15-40Km/hr"}
{:descripcion_corta "San Luis al Golfo"
:descripcion "5to paseo anual 360 Cycling Studio.
San Luis - El Golfo, 112 kilometros.
Inscripcion $550 pesos
Barredora
puntos de hidratacion
chip de cronometraje
Camiseta
Comida
Bebida
Medalla de Participacion
Transporte Golfo - San Luis
Informes: (653) 103-1460 * (653) 119-0725"
:punto_reunion "360 Cycling Studio, San Luis R.C."
:nivel "T"
:distancia "120 Km"
:velocidad "15-40Km/hr"
:fecha "2018-11-10"
:hora "07:00:00"
:leader ""
:leader_email "<EMAIL>"
:repetir "F"
:anonimo "F"}])
(def rodadas_link-rows
[{:rodadas_id "1"
:user "<NAME>"
:comentarios "Alli estare en punto."
:email "<EMAIL>"}
{:rodadas_id "1"
:user "<NAME>"
:comentarios "<NAME> estaremos"
:email "<EMAIL>"}
{:rodadas_id "2"
:user "<NAME>"
:comentarios "<NAME> estaremos"
:email "<EMAIL>"}
{:rodadas_id "2"
:user "<NAME>"
:comentarios "<NAME>li estaremos"
:email "<EMAIL>"}
{:rodadas_id "3"
:user "<NAME>"
:comentarios "<NAME> estaremos"
:email "<EMAIL>"}
{:rodadas_id "3"
:user "<NAME>"
:comentarios "<NAME> estaremos"
:email "<EMAIL>"}
{:rodadas_id "4"
:user "<NAME>"
:comentarios "Alli estaremos"
:email "<EMAIL>"}
{:rodadas_id "4"
:user "<NAME>"
:comentarios "Alli estaremos"
:email "<EMAIL>"}
{:rodadas_id "8"
:user "<NAME>"
:comentarios "Alli estaremos"
:email "<EMAIL>"}
{:rodadas_id "8"
:user "<NAME>"
:comentarios "Alli estaremos"
:email "<EMAIL>"}])
(def user-rows
[{:lastname "Luc<NAME>"
:firstname "Hector"
:username "<EMAIL>"
:password (crypt/encrypt "<PASSWORD>")
:dob "1957-02-07"
:email "<EMAIL>"
:level "S"
:active "T"}
{:lastname "H<NAME>andez"
:firstname "Oscar"
:username "<EMAIL>"
:password (crypt/encrypt "<PASSWORD>")
:dob "1975-10-08"
:email "<EMAIL>"
:level "S"
:active "T"}
{:lastname "<NAME>"
:firstname "Marco"
:username "<EMAIL>"
:password (crypt/encrypt "<PASSWORD>")
:dob "1975-03-06"
:email "<EMAIL>"
:level "S"
:active "T"}
{:lastname "<NAME>"
:firstname "Martha"
:username "<EMAIL>"
:dob "1956-02-23"
:email "<EMAIL>"
:password (crypt/encrypt "<PASSWORD>")
:level "U"
:active "T"}])
(def categorias-rows
[{:id "A"
:descripcion "Infantil Mixta(hasta 12 años"}
{:id "B"
:descripcion "MTB Mixta Montaña"}
{:id "C"
:descripcion "Juveniles Varonil 13-14"}
{:id "D"
:descripcion "Juveniles Varonil 15-17"}
{:id "E"
:descripcion "Novatos Varonil"}
{:id "F"
:descripcion "Master Varonil 40 y mas"}
{:id "G"
:descripcion "Segunda Fuerza Varonil(Intermedios)"}
{:id "I"
:descripcion "Primera Fuerza Varonil(Avanzados)"}
{:id "J"
:descripcion "Piñon Fijo Varonil y una velicidad(SS)"}
{:id "K"
:descripcion "Femenil Juvenil 15-17"}
{:id "L"
:descripcion "Segunda Fuerza Femenil(Abierta, Novatas)"}
{:id "M"
:descripcion "Primera Fuerza Femenil(Avanzadas)"}
{:id "N"
:descripcion "Piñon Fijo Femenil y una velocidad(SS)"}])
(defn create-database []
"Creates database and a default admin user"
(Query! db users-sql)
(Query! db cuadrantes-sql)
(Query! db rodadas-sql)
(Query! db rodadas_link-sql)
(Query! db cartas-sql)
(Query! db categorias-sql)
(Query! db carreras-sql)
(Query! db puntos-sql)
(Query! db carreras_categorias-sql)
(Query! db contrareloj-sql)
(Query! db taller-sql)
(Query! db imdecuf-sql)
(Insert-multi db :users user-rows)
(Insert-multi db :rodadas rodadas-rows)
(Insert-multi db :rodadas_link rodadas_link-rows)
(Insert-multi db :cuadrantes cuadrantes-rows)
(Insert-multi db :categorias categorias-rows))
(defn reset-database []
"removes existing tables and recreates them"
(Query! db "DROP table IF EXISTS users")
(Query! db "DROP table IF EXISTS cuadrantes")
(Query! db "DROP table IF EXISTS rodadas_link")
(Query! db "DROP table IF EXISTS rodadas")
(Query! db "DROP table IF EXISTS cartas")
(Query! db "DROP table IF EXISTS puntos")
(Query! db "DROP table IF EXISTS categorias")
(Query! db "DROP table IF EXISTS carreras")
(Query! db "DROP table IF EXISTS carreras_categorias")
(Query! db "DROP table IF EXISTS contrareloj")
(Query! db "DROP table IF EXISTS taller")
(Query! db "DROP table IF EXISTS imdecuf")
(Query! db users-sql)
(Query! db cuadrantes-sql)
(Query! db rodadas-sql)
(Query! db rodadas_link-sql)
(Query! db cartas-sql)
(Query! db puntos-sql)
(Query! db categorias-sql)
(Query! db carreras-sql)
(Query! db carreras_categorias-sql)
(Query! db contrareloj-sql)
(Query! db taller-sql)
(Query! db imdecuf-sql)
(Insert-multi db :users user-rows)
(Insert-multi db :cuadrantes cuadrantes-rows)
(Insert-multi db :rodadas rodadas-rows)
(Insert-multi db :rodadas_link rodadas_link-rows)
(Insert-multi db :categorias categorias-rows))
(defn migrate []
"migrate by the seat of my pants"
(Query! db "DROP table IF EXISTS carreras"))
;; This is to create carreras_categorias example
;; (defn create-carreras-categorias []
;; (doseq [item (Query db "SELECT * FROM categorias")]
;; (doseq [sitem (Query db "SELECT * FROM carreras")]
;; (let [carreras_id (str (:id sitem))
;; categorias_id (str (:id item))
;; status "T"
;; id (:id (first (Query db ["SELECT id from carreras_categorias WHERE carreras_id = ? AND categorias_id = ?" carreras_id categorias_id])))
;; postvars {:id (str id)
;; :carreras_id carreras_id
;; :categorias_id categorias_id
;; :status status}]
;; (Save db :carreras_categorias postvars ["id = ?" id])))))
;;(migrate)
| true | (ns cc.models.cdb
(:require [cc.models.crud :refer :all]
[noir.util.crypt :as crypt]))
(def users-sql
"CREATE TABLE users (
id int(11) NOT NULL AUTO_INCREMENT,
lastname varchar(45) DEFAULT NULL,
firstname varchar(45) DEFAULT NULL,
username varchar(45) DEFAULT NULL,
password TEXT DEFAULT NULL,
dob varchar(45) DEFAULT NULL,
cell varchar(45) DEFAULT NULL,
phone varchar(45) DEFAULT NULL,fax varchar(45) DEFAULT NULL,
email varchar(100) DEFAULT NULL,
level char(1) DEFAULT NULL COMMENT 'A=Administrador,U=Usuario,S=Sistema',
active char(1) DEFAULT NULL COMMENT 'T=Active,F=Not active',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8")
(def cuadrantes-sql
"CREATE TABLE cuadrantes (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(100) DEFAULT NULL,
leader varchar(100) DEFAULT NULL,
leader_phone varchar(45) DEFAULT NULL,
leader_cell varchar(45) DEFAULT NULL,
leader_email varchar(100) DEFAULT NULL,
notes TEXT DEFAULT NULL,
status char(1) DEFAULT NULL COMMENT 'T=Active,F=Inactive',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8")
(def rodadas-sql
"CREATE TABLE rodadas (
id int(11) NOT NULL AUTO_INCREMENT,
descripcion_corta varchar(100) DEFAULT NULL,
descripcion varchar(3000) DEFAULT NULL,
punto_reunion varchar(1000) DEFAULT NULL,
nivel char(1) DEFAULT NULL COMMENT 'P=Principiantes,M=Medio,A=Avanzado,T=Todos',
distancia varchar(100) DEFAULT NULL,
velocidad varchar(100) DEFAULT NULL,
fecha date DEFAULT NULL,
hora time DEFAULT NULL,
leader varchar(100) DEFAULT NULL,
leader_email varchar(100) DEFAULT NULL,
cuadrante int(11) DEFAULT NULL,
repetir char(1) DEFAULT NULL COMMENT 'T=Si,F=No',
anonimo char(1) DEFAULT \"F\" COMMENT 'T=Si,F=No',
rodada char(1) DEFAULT \"T\" COMMENT 'T=Si,F=No',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8")
(def rodadas_link-sql
"CREATE TABLE rodadas_link (
id int(11) NOT NULL AUTO_INCREMENT,
rodadas_id int(11) NOT NULL,
user varchar(200) DEFAULT NULL,
comentarios TEXT DEFAULT NULL,
email varchar(100) DEFAULT NULL,
asistir char(1) DEFAULT \"T\" COMMENT 'T=Si,F=No',
PRIMARY KEY (id),
KEY rodadas_id (rodadas_id),
CONSTRAINT rodadas_link_ibfk_1 FOREIGN KEY (rodadas_id) REFERENCES rodadas (id) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8")
(def cartas-sql
"CREATE TABLE `cartas` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`categoria` char(1) DEFAULT NULL COMMENT 'A=Abierta,N=Novatos',
`sexo` char(1) DEFAULT NULL COMMENT 'V=Varonil,F=Femenil',
`bicicleta` char(1) DEFAULT NULL COMMENT 'F=Fija,S=SS,O=Otra',
`no_participacion` varchar(50) DEFAULT NULL,
`nombre` varchar(100) DEFAULT NULL,
`apellido_paterno` varchar(100) DEFAULT NULL,
`apellido_materno` varchar(100) DEFAULT NULL,
`equipo` varchar(100) DEFAULT NULL,
`direccion` varchar(100) DEFAULT NULL,
`pais` varchar(100) DEFAULT NULL,
`ciudad` varchar(100) DEFAULT NULL,
`telefono` varchar(50) DEFAULT NULL,
`celular` varchar(50) DEFAULT NULL,
`email` varchar(100) DEFAULT NULL,
`tutor` varchar(100) DEFAULT NULL,
`dob` varchar(45) DEFAULT NULL,
`creado` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`carreras_id` int(11) unsigned DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=34 DEFAULT CHARSET=utf8")
(def puntos-sql
"CREATE TABLE `puntos` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`cartas_id` int(10) unsigned NOT NULL,
`puntos_p` int(11) DEFAULT NULL,
`puntos_1` int(11) DEFAULT NULL,
`puntos_2` int(11) DEFAULT NULL,
`puntos_3` int(11) DEFAULT NULL,
`creado` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
PRIMARY KEY (`id`),
KEY `f_cartas_id` (`cartas_id`),
CONSTRAINT `puntos_ibfk_1` FOREIGN KEY (`cartas_id`) REFERENCES `cartas` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=435 DEFAULT CHARSET=utf8")
(def categorias-sql
"CREATE TABLE `categorias` (
`id` char(1) NOT NULL,
`descripcion` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8")
(def carreras-sql
"CREATE TABLE `carreras` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`descripcion` varchar(500) DEFAULT NULL,
`fecha` date DEFAULT NULL,
`hora` time DEFAULT NULL,
`puntos_p` int(11) DEFAULT NULL,
`puntos_1` int(11) DEFAULT NULL,
`puntos_2` int(11) DEFAULT NULL,
`puntos_3` int(11) DEFAULT NULL,
`status` char(1) DEFAULT NULL COMMENT 'T=Activo,F=Inactivo',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8")
(def carreras_categorias-sql
"CREATE TABLE `carreras_categorias` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`carreras_id` int(10) unsigned NOT NULL,
`categorias_id` char(1) DEFAULT NULL,
`status` char(1) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=57 DEFAULT CHARSET=utf8")
(def contrareloj-sql
"CREATE TABLE `contrareloj` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`cartas_id` int(11) unsigned NOT NULL,
`carreras_id` int(11) unsigned NOT NULL,
`categorias_id` char(1) NOT NULL,
`empezar` time DEFAULT NULL,
`split1` time DEFAULT NULL,
`split2` time DEFAULT NULL,
`terminar` time DEFAULT NULL,
`penalty` int(11) unsigned DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=291 DEFAULT CHARSET=utf8")
(def taller-sql
"CREATE TABLE `taller` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`nombre` varchar(200) DEFAULT NULL,
`direccion` varchar(200) DEFAULT NULL,
`telefono` varchar(100) NOT NULL,
`horarios` text DEFAULT NULL,
`sitio` varchar(200) DEFAULT NULL,
`direcciones` text DEFAULT NULL,
`historia` text DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8")
(def imdecuf-sql
"CREATE TABLE `imdecuf` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`descripcion_corta` varchar(100) DEFAULT NULL,
`descripcion` text DEFAULT NULL,
`punto_reunion` varchar(1000) DEFAULT NULL,
`nivel` char(1) DEFAULT NULL COMMENT 'P=Principiantes,M=Medio,A=Avanzado,T=Todos',
`distancia` varchar(100) DEFAULT NULL,
`velocidad` varchar(100) DEFAULT NULL,
`fecha` date DEFAULT NULL,
`hora` time DEFAULT NULL,
`leader` varchar(100) DEFAULT NULL,
`leader_email` varchar(100) DEFAULT NULL,
`cuadrante` int(11) DEFAULT NULL,
`repetir` char(1) DEFAULT NULL COMMENT 'T=Si,F=No',
`anonimo` char(1) DEFAULT 'F' COMMENT 'T=Si,F=No',
`rodada` char(1) DEFAULT 'T' COMMENT 'T=Si,F=No',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=80 DEFAULT CHARSET=utf8")
(def cuadrantes-rows
[{:name "PI:NAME:<NAME>END_PI"
:leader "PI:NAME:<NAME>END_PI"
:leader_email "PI:EMAIL:<EMAIL>END_PI"
:notes "Cuadrante ciclista con todos los niveles para el gusto del ciclista."
:status "T"}
{:name "PI:NAME:<NAME>END_PI"
:leader "PI:NAME:<NAME>END_PI"
:leader_email "PI:EMAIL:<EMAIL>END_PI"
:notes "Cuadrante ciclista con niveles inter y fast."
:status "T"}
{:name "Grupo Ciclista La Vid"
:leader "PI:NAME:<NAME>END_PI"
:leader_email "PI:EMAIL:<EMAIL>END_PI"
:notes "Un grupo cristiano con deseos de mejorar nuestra salud..."
:status "T"}
{:name "PI:NAME:<NAME>END_PI"
:leader "RetPI:NAME:<NAME>END_PI"
:leader_email "PI:EMAIL:<EMAIL>END_PI"
:notes "Para mas información entra al grupo Reto Demoledor"
:status "T"}
{:name "PI:NAME:<NAME>END_PI"
:leader "retoaerobiker"
:leader_email "PI:EMAIL:<EMAIL>END_PI"
:notes "Reto madrugador 5x5 mas detalles en Aerobikers (FB)"
:status "T"}
{:name "PI:NAME:<NAME>END_PI"
:leader "blancolider"
:leader_email "PI:EMAIL:<EMAIL>END_PI"
:notes ""
:status "T"}
{:name "BPI:NAME:<NAME>END_PI@PI:NAME:<NAME>END_PI"
:leader "biciosolider"
:leader_email "PI:EMAIL:<EMAIL>END_PI"
:notes ""
:status "T"}
{:name "PI:NAME:<NAME>END_PI"
:leader "aerogreens"
:leader_email "PI:EMAIL:<EMAIL>END_PI"
:notes ""
:status "T"}
{:name "PI:NAME:<NAME>END_PI"
:leader "PI:NAME:<NAME>END_PI"
:leader_email "PI:EMAIL:<EMAIL>END_PI"
:notes ""
:status "T"}
{:name "PI:NAME:<NAME>END_PI"
:leader "vlight"
:leader_email "PI:EMAIL:<EMAIL>END_PI"
:notes ""
:status "T"}
{:name "PI:NAME:<NAME>END_PI"
:leader "aferreitorxslider"
:leader_email "PI:EMAIL:<EMAIL>END_PI"
:notes ""
:status "T"}
{:name "PI:NAME:<NAME>END_PI"
:leader "mujeres"
:leader_email "PI:EMAIL:<EMAIL>END_PI"
:notes ""
:status "T"}
{:name "PI:NAME:<NAME>END_PI"
:leader "raptors"
:leader_email "PI:EMAIL:<EMAIL>END_PI"
:notes ""
:status "T"}
{:name "PI:NAME:<NAME>END_PI"
:leader "victorianos"
:leader_email "PI:EMAIL:<EMAIL>END_PI"
:notes ""
:status "T"}
{:name "PI:NAME:<NAME>END_PI (Inter)"
:leader "ivcycling"
:leader_email "PI:EMAIL:<EMAIL>END_PI"
:notes ""
:status "T"}
{:name "NONSTOP"
:leader "nonstop"
:leader_email "PI:EMAIL:<EMAIL>END_PI"
:notes ""
:status "T"}])
(def rodadas-rows
[{:descripcion_corta "San Lunes"
:descripcion "Ruta que puede variar por las calles de la ciudad. Se rodaran por lo menos 20 kilometros. No olvidar traer casco, luces, auga y un tubo de repuesto."
:punto_reunion "Parque Hidalgo"
:nivel "P"
:distancia "20/28 Km"
:velocidad "18-25Km/hr"
:fecha "2018-10-08"
:hora "20:00:00"
:leader "PI:NAME:<NAME>END_PI"
:leader_email "PI:EMAIL:<EMAIL>END_PI"
:cuadrante 1
:repetir "T"
:anonimo "F"}
{:descripcion_corta "Santa Isabel"
:descripcion "Salimos del Parque Hidalgo hacia la Santa Isabel. Hidratacion en la OXXO que esta en la Lazaro Cardenas. No olividen traer casco, luces, agua y un tubo de repuesto."
:punto_reunion "Parque Hidalgo"
:nivel "T"
:distancia "30 Km"
:velocidad "Lights: 18-25Km/hr Intermedios: 25-35Km/hr"
:fecha "2018-10-09"
:hora "20:00:00"
:leader "PI:NAME:<NAME>END_PI"
:leader_email "PI:EMAIL:<EMAIL>END_PI"
:cuadrante 1
:repetir "T"
:anonimo "F"}
{:descripcion_corta "Canalera"
:descripcion "Salimos por el canal de la Independencia a veces hasta el aeropuerto. No olviden traer casco, luces, agua y un tubo de repuesto."
:punto_reunion "PI:NAME:<NAME>END_PI"
:nivel "M"
:distancia "30/50Km"
:velocidad "25-35Km/hr"
:fecha "2018-10-08"
:hora "20:00:00"
:leader "PI:NAME:<NAME>END_PI"
:leader_email "PI:EMAIL:<EMAIL>END_PI"
:cuadrante 1
:repetir "T"
:anonimo "F"}
{:descripcion_corta "Adorada"
:descripcion "Ruta que puede variar entre el Campestre y el Panteon rumbo al aeropuerto. No olviden traer casco, luces, agua y un tubo de repuesto."
:punto_reunion "PI:NAME:<NAME>END_PI"
:nivel "P"
:distancia "20/28 Km"
:velocidad "18-25Km/hr"
:fecha "2018-10-10"
:hora "20:00:00"
:leader "PI:NAME:<NAME>END_PI"
:leader_email "PI:EMAIL:<EMAIL>END_PI"
:cuadrante 1
:repetir "T"
:anonimo "F"}
{:descripcion_corta "Vida Libre"
:descripcion "5to paseo recreativo Juntos por una VIDA LIBRE de Cancer de MAMA
Viste una prenda rosa y cuelga un liston del mismo color en tu bicicleta.
Rueda, corre, trota camina
Por tu seguridad no olvides tu casco
CIRCUITO PEDESTRES 2 KM
CIRCUITO CICLISTAS 4 KM
Registro: 7:30am. Salida: 8:00am"
:punto_reunion "Oficinas Centrales (Calle Calafia #1115)"
:nivel "T"
:distancia "4 Km"
:velocidad "5-25Km/hr"
:fecha "2018-10-21"
:hora "08:00:00"
:leader_email "PI:EMAIL:<EMAIL>END_PI"
:repetir "F"
:anonimo "F"}
{:descripcion_corta "Circuito Obregon"
:descripcion "Hoy toca Circuito Ciclista Obregón los esperamos a las 8:00 PM en el punto de Reunión de Rectoría de la UABC/Biblioteca del Estado. El circuito tiene una longuitud de 3.2 Kilómetros con muy buena iluminado y el formato que se manejara para rodar será de las primeras 9 vueltas serán controladas a 30 kilómetros por hora como máximo y después se comenzara a aumentar la velocidad. Los ciclistas que lleguen más tarde se pueden acoplar al grupo o grupos. Así que a rodar con precaución y llevar sus luces si cuentan con ellas para iluminar esa mancha ciclista por toda la Av. Obregón, A Darle…."
:punto_reunion "Rectoría de la UABC/Biblioteca del Estado"
:nivel "T"
:distancia "20/50 Km"
:velocidad "10-40Km/hr"
:fecha "2018-10-24"
:hora "20:00:00"
:leader "PI:NAME:<NAME>END_PI"
:leader_email "PI:EMAIL:<EMAIL>END_PI"
:cuadrante 1
:repetir "T"
:anonimo "F"}
{:descripcion_corta "Culinaria"
:descripcion "Salimos del parque Hidalgo hacia el panteon que esta rumbo al aeropuerto. No olviden traer casco, luces, agua y un tubo de repuesto."
:punto_reunion "ParPI:NAME:<NAME>END_PI"
:nivel "P"
:distancia "20/28 Km"
:velocidad "18-25Km/hr"
:fecha "2018-10-11"
:hora "20:00:00"
:leader "Chefsito"
:leader_email "PI:EMAIL:<EMAIL>END_PI"
:cuadrante 1
:repetir "T"
:anonimo "F"}
{:descripcion_corta "Intermedia"
:descripcion "Salimos del parque Hidalgo hacia el hotel que esta despues del OXXO. No olviden traer casco, luces, agua y un tubo de repuesto."
:punto_reunion "ParPI:NAME:<NAME>END_PI"
:nivel "M"
:distancia "30 Km"
:velocidad "25-35 km/hr"
:fecha "2018-10-11"
:hora "20:00:00"
:leader "PI:NAME:<NAME>END_PI"
:leader_email "PI:EMAIL:<EMAIL>END_PI"
:cuadrante 1
:repetir "T"
:anonimo "F"}
{:descripcion_corta "Pedacera"
:descripcion "Salimos del parque Hidalgo hacia el aeropuerto. No olviden traer casco, luces, agua y un tubo de repuesto."
:punto_reunion "Parque HPI:NAME:<NAME>END_PIalgo"
:nivel "A"
:distancia "50-60 Km"
:velocidad "30-40Km/hr"
:fecha "2018-10-11"
:hora "20:00:00"
:leader "PI:NAME:<NAME>END_PI"
:leader_email "PI:EMAIL:<EMAIL>END_PI"
:cuadrante 1
:repetir "T"
:anonimo "F"}
{:descripcion_corta "Familiar"
:descripcion "Salimos del Parque Hidalgo con ruta indefinida. No olviden traer casco, luces, agua y un tubo de repuesto."
:punto_reunion "PI:NAME:<NAME>END_PI"
:nivel "P"
:distancia "20/28 Km"
:velocidad "18-25Km/hr"
:fecha "2018-10-12"
:hora "20:00:00"
:leader "PI:NAME:<NAME>END_PI"
:leader_email "PI:EMAIL:<EMAIL>END_PI"
:cuadrante 1
:repetir "T"
:anonimo "F"}
{:descripcion_corta "Mexicali Rumorosa"
:descripcion "Paseo Ciclista Mexicali-Rumorosa, es el Paseo ciclista mas impresionante en la franja fronteriza entre Mexicali B.C. y Estados Unidos por su vista espectacular natural, donde el participante se deleitara al observar paisajes de magnificas montañas conformadas por un increíble escenario de rocas gigantescas con impresionantes miradores, lo que caracteriza la subida de la carretera a la Rumorosa entre Mexicali y Tecate B.C.
Un Paseo divertido, familiar de sana convivencia para todos los que gustan de nuevos retos.
Una vez en la meta recibiremos a todos los participantes y sus Familia en una Convivencia en la Rumorosa donde además de pasar un rato agradable recibirán su Medalla por participar y se realiza una Rifa de 2 Bicicletas entre los Participantes."
:punto_reunion "Macroplaza del Valle Lázaro Cárdenas 2200 col. El Porvenir, 21220 Mexicali, Baja California."
:nivel "T"
:distancia "75 Km"
:fecha "2018-10-27"
:hora "08:00:00"
:leader "PI:NAME:<NAME>END_PI"
:leader_email "PI:EMAIL:<EMAIL>END_PI"
:repetir "F"
:anonimo "F"
:velocidad "15-40Km/hr"}
{:descripcion_corta "VI Gran Fondo"
:descripcion "Desafiando tus piernas
VI Gran Fondo
Paseo Mexicali - San Felipe
Distancia: 200 kms de diversión
Ven a disfrutar de este paseo donde pondrás a prueba tus piernas.
Costo: $300 pesos
Contamos con ambulancia, hidrataciones, medalla y el mejor ambiente al final del evento"
:punto_reunion "PI:NAME:<NAME>END_PI"
:nivel "A"
:distancia "200 Km"
:fecha "2018-11-10"
:hora "06:00:00"
:leader "PI:NAME:<NAME>END_PI"
:leader_email "PI:EMAIL:<EMAIL>END_PI"
:repetir "F"
:anonimo "F"
:velocidad "15-40Km/hr"}
{:descripcion_corta "San Luis al Golfo"
:descripcion "5to paseo anual 360 Cycling Studio.
San Luis - El Golfo, 112 kilometros.
Inscripcion $550 pesos
Barredora
puntos de hidratacion
chip de cronometraje
Camiseta
Comida
Bebida
Medalla de Participacion
Transporte Golfo - San Luis
Informes: (653) 103-1460 * (653) 119-0725"
:punto_reunion "360 Cycling Studio, San Luis R.C."
:nivel "T"
:distancia "120 Km"
:velocidad "15-40Km/hr"
:fecha "2018-11-10"
:hora "07:00:00"
:leader ""
:leader_email "PI:EMAIL:<EMAIL>END_PI"
:repetir "F"
:anonimo "F"}])
(def rodadas_link-rows
[{:rodadas_id "1"
:user "PI:NAME:<NAME>END_PI"
:comentarios "Alli estare en punto."
:email "PI:EMAIL:<EMAIL>END_PI"}
{:rodadas_id "1"
:user "PI:NAME:<NAME>END_PI"
:comentarios "PI:NAME:<NAME>END_PI estaremos"
:email "PI:EMAIL:<EMAIL>END_PI"}
{:rodadas_id "2"
:user "PI:NAME:<NAME>END_PI"
:comentarios "PI:NAME:<NAME>END_PI estaremos"
:email "PI:EMAIL:<EMAIL>END_PI"}
{:rodadas_id "2"
:user "PI:NAME:<NAME>END_PI"
:comentarios "PI:NAME:<NAME>END_PIli estaremos"
:email "PI:EMAIL:<EMAIL>END_PI"}
{:rodadas_id "3"
:user "PI:NAME:<NAME>END_PI"
:comentarios "PI:NAME:<NAME>END_PI estaremos"
:email "PI:EMAIL:<EMAIL>END_PI"}
{:rodadas_id "3"
:user "PI:NAME:<NAME>END_PI"
:comentarios "PI:NAME:<NAME>END_PI estaremos"
:email "PI:EMAIL:<EMAIL>END_PI"}
{:rodadas_id "4"
:user "PI:NAME:<NAME>END_PI"
:comentarios "Alli estaremos"
:email "PI:EMAIL:<EMAIL>END_PI"}
{:rodadas_id "4"
:user "PI:NAME:<NAME>END_PI"
:comentarios "Alli estaremos"
:email "PI:EMAIL:<EMAIL>END_PI"}
{:rodadas_id "8"
:user "PI:NAME:<NAME>END_PI"
:comentarios "Alli estaremos"
:email "PI:EMAIL:<EMAIL>END_PI"}
{:rodadas_id "8"
:user "PI:NAME:<NAME>END_PI"
:comentarios "Alli estaremos"
:email "PI:EMAIL:<EMAIL>END_PI"}])
(def user-rows
[{:lastname "LucPI:NAME:<NAME>END_PI"
:firstname "Hector"
:username "PI:EMAIL:<EMAIL>END_PI"
:password (crypt/encrypt "PI:PASSWORD:<PASSWORD>END_PI")
:dob "1957-02-07"
:email "PI:EMAIL:<EMAIL>END_PI"
:level "S"
:active "T"}
{:lastname "HPI:NAME:<NAME>END_PIandez"
:firstname "Oscar"
:username "PI:EMAIL:<EMAIL>END_PI"
:password (crypt/encrypt "PI:PASSWORD:<PASSWORD>END_PI")
:dob "1975-10-08"
:email "PI:EMAIL:<EMAIL>END_PI"
:level "S"
:active "T"}
{:lastname "PI:NAME:<NAME>END_PI"
:firstname "Marco"
:username "PI:EMAIL:<EMAIL>END_PI"
:password (crypt/encrypt "PI:PASSWORD:<PASSWORD>END_PI")
:dob "1975-03-06"
:email "PI:EMAIL:<EMAIL>END_PI"
:level "S"
:active "T"}
{:lastname "PI:NAME:<NAME>END_PI"
:firstname "Martha"
:username "PI:EMAIL:<EMAIL>END_PI"
:dob "1956-02-23"
:email "PI:EMAIL:<EMAIL>END_PI"
:password (crypt/encrypt "PI:PASSWORD:<PASSWORD>END_PI")
:level "U"
:active "T"}])
(def categorias-rows
[{:id "A"
:descripcion "Infantil Mixta(hasta 12 años"}
{:id "B"
:descripcion "MTB Mixta Montaña"}
{:id "C"
:descripcion "Juveniles Varonil 13-14"}
{:id "D"
:descripcion "Juveniles Varonil 15-17"}
{:id "E"
:descripcion "Novatos Varonil"}
{:id "F"
:descripcion "Master Varonil 40 y mas"}
{:id "G"
:descripcion "Segunda Fuerza Varonil(Intermedios)"}
{:id "I"
:descripcion "Primera Fuerza Varonil(Avanzados)"}
{:id "J"
:descripcion "Piñon Fijo Varonil y una velicidad(SS)"}
{:id "K"
:descripcion "Femenil Juvenil 15-17"}
{:id "L"
:descripcion "Segunda Fuerza Femenil(Abierta, Novatas)"}
{:id "M"
:descripcion "Primera Fuerza Femenil(Avanzadas)"}
{:id "N"
:descripcion "Piñon Fijo Femenil y una velocidad(SS)"}])
(defn create-database []
"Creates database and a default admin user"
(Query! db users-sql)
(Query! db cuadrantes-sql)
(Query! db rodadas-sql)
(Query! db rodadas_link-sql)
(Query! db cartas-sql)
(Query! db categorias-sql)
(Query! db carreras-sql)
(Query! db puntos-sql)
(Query! db carreras_categorias-sql)
(Query! db contrareloj-sql)
(Query! db taller-sql)
(Query! db imdecuf-sql)
(Insert-multi db :users user-rows)
(Insert-multi db :rodadas rodadas-rows)
(Insert-multi db :rodadas_link rodadas_link-rows)
(Insert-multi db :cuadrantes cuadrantes-rows)
(Insert-multi db :categorias categorias-rows))
(defn reset-database []
"removes existing tables and recreates them"
(Query! db "DROP table IF EXISTS users")
(Query! db "DROP table IF EXISTS cuadrantes")
(Query! db "DROP table IF EXISTS rodadas_link")
(Query! db "DROP table IF EXISTS rodadas")
(Query! db "DROP table IF EXISTS cartas")
(Query! db "DROP table IF EXISTS puntos")
(Query! db "DROP table IF EXISTS categorias")
(Query! db "DROP table IF EXISTS carreras")
(Query! db "DROP table IF EXISTS carreras_categorias")
(Query! db "DROP table IF EXISTS contrareloj")
(Query! db "DROP table IF EXISTS taller")
(Query! db "DROP table IF EXISTS imdecuf")
(Query! db users-sql)
(Query! db cuadrantes-sql)
(Query! db rodadas-sql)
(Query! db rodadas_link-sql)
(Query! db cartas-sql)
(Query! db puntos-sql)
(Query! db categorias-sql)
(Query! db carreras-sql)
(Query! db carreras_categorias-sql)
(Query! db contrareloj-sql)
(Query! db taller-sql)
(Query! db imdecuf-sql)
(Insert-multi db :users user-rows)
(Insert-multi db :cuadrantes cuadrantes-rows)
(Insert-multi db :rodadas rodadas-rows)
(Insert-multi db :rodadas_link rodadas_link-rows)
(Insert-multi db :categorias categorias-rows))
(defn migrate []
"migrate by the seat of my pants"
(Query! db "DROP table IF EXISTS carreras"))
;; This is to create carreras_categorias example
;; (defn create-carreras-categorias []
;; (doseq [item (Query db "SELECT * FROM categorias")]
;; (doseq [sitem (Query db "SELECT * FROM carreras")]
;; (let [carreras_id (str (:id sitem))
;; categorias_id (str (:id item))
;; status "T"
;; id (:id (first (Query db ["SELECT id from carreras_categorias WHERE carreras_id = ? AND categorias_id = ?" carreras_id categorias_id])))
;; postvars {:id (str id)
;; :carreras_id carreras_id
;; :categorias_id categorias_id
;; :status status}]
;; (Save db :carreras_categorias postvars ["id = ?" id])))))
;;(migrate)
|
[
{
"context": " good explanation here https://www.ics.uci.edu/~alspaugh/cls/shr/allen.html )\n;; Allen defined 13 basic re",
"end": 861,
"score": 0.5651984810829163,
"start": 855,
"tag": "NAME",
"value": "spaugh"
}
] | explainers/time_count/explainer/c_allens_interval_algebra.clj | hiram-madelaine/time-count | 44 | (ns time-count.explainer.c-allens-interval-algebra
(:require
[time-count.core :refer :all]
[time-count.allens-algebra :refer [relation]]
[time-count.relation-bounded-intervals :refer [map->RelationBoundedInterval ->RelationBound relate-bound-to-ct]]
[time-count.iso8601 :refer [to-iso from-iso t->>]]
[time-count.metajoda]
[midje.sweet :refer :all]))
;; In time-count, all time values are interpreted as intervals.
;; CountableTimes are taken to span period the length of their scale.
;; For example, 2017-12-13 is an interval 1 day long. 2017-12-13T09:15 is an interval 1 minute long.
;; Traditional "before/after" comparison is incomplete, and can result in ambiguous or complex business logic.
;; time-count uses Allen's Interval Algebra to compare intervals.
;; (There is a good explanation here https://www.ics.uci.edu/~alspaugh/cls/shr/allen.html )
;; Allen defined 13 basic relations, which are distinct and exhaustive:
(fact "Thirteen basic relations in Allen's Interval Algebra"
(t->> ["2017" "2017"] (apply relation)) => :equal
(t->> ["2015" "2017"] (apply relation)) => :before
(t->> ["2017" "2015"] (apply relation)) => :after
(t->> ["2016" "2017"] (apply relation)) => :meets
(t->> ["2017" "2016"] (apply relation)) => :met-by
(t->> ["2017-01" "2017"] (apply relation)) => :starts
(t->> ["2017" "2017-01"] (apply relation)) => :started-by
(t->> ["2017-12" "2017"] (apply relation)) => :finishes
(t->> ["2017" "2017-12"] (apply relation)) => :finished-by
(t->> ["2017-02" "2017"] (apply relation)) => :during
(t->> ["2017" "2017-02"] (apply relation)) => :contains
(t->> ["2017-W05" "2017-02"] (apply relation)) => :overlaps
(t->> ["2017-02" "2017-W05"] (apply relation)) => :overlapped-by)
;; Intervals other than those defined as countable times, can be described by their boundaries.
;; The boundary of an interval can be defined in terms of a relation to another interval.
;; In the current implementation of time-count, only :starts and :finishes are supported.
(fact "RelationBoundedIntervals are defined by a combination of Allen's :starts and :finishes relations to other intervals."
(-> {:starts (from-iso "2017") :finishes (from-iso "2019")}
map->RelationBoundedInterval
to-iso)
=> "2017/2019"
(-> {:starts (from-iso "2017-10") :finishes (from-iso "2017-12")}
map->RelationBoundedInterval
to-iso)
=> "2017-10/2017-12"
(-> {:starts (from-iso "2017-10")}
map->RelationBoundedInterval
to-iso)
=> "2017-10/-")
(fact "RelationBoundedIntervals and CountableTimes are compared in the same way."
(relation (from-iso "2017") (from-iso "2019"))
=> :before
(relation (from-iso "2017/2018") (from-iso "2019/2020"))
=> :meets)
(fact "RelationBoundedIntervals and CountableTimes can be compared to each other."
(relation (from-iso "2017/2019") (from-iso "2018"))
=> :contains
(relation (from-iso "2018") (from-iso "2017/2019"))
=> :during)
(facts "About RelationBounds (A RelationBoundedInterval is just a combination of one or two boundaries.)"
(fact "The relation of a single RelationBound with a CountableTime gives a set of possible basic relations (which is, itself, a relation)."
(relate-bound-to-ct
(->RelationBound :finishes (from-iso "2018"))
(from-iso "2017"))
=> #{:overlapped-by :started-by :contains}))
;The basic relations of a RelationBoundedInterval are the intersection of the relations of its two bounds.
(fact "Business rules comparing time are expressed using sets of relations."
(let [contract {:due-date (from-iso "2017-02-15")
:overdue-relation #{:after :met-by} ;This defines what it means to be 'overdue' in relation to the due-date
; ... other contract stuff ...
}
overdue-as-of? #((contract :overdue-relation) (relation % (contract :due-date)))]
(overdue-as-of? (from-iso "2017-02-10T14:30")) => falsey
(overdue-as-of? (from-iso "2017-02-15T20:30")) => falsey
(overdue-as-of? (from-iso "2017-02-15T23:59")) => falsey
(overdue-as-of? (from-iso "2017-02-16T00:00")) => truthy
(overdue-as-of? (from-iso "2017-02-17T10:04")) => truthy)
(let [contract {:active-interval (from-iso "2017-01-01/2017-03-31")
:active-relation #{:starts :during :finishes} ;This defines what it means to be 'active' in relation to the active-interval.
; ... other contract stuff ...
}
active-as-of? #((contract :active-relation) (relation % (contract :active-interval)))]
(active-as-of? (from-iso "2016-12-10T14:30")) => falsey
(active-as-of? (from-iso "2016-12-31T23:59")) => falsey
(active-as-of? (from-iso "2017-02-15T23:59")) => truthy
(active-as-of? (from-iso "2017-03-31T23:59")) => truthy
(active-as-of? (from-iso "2017-04-01T00:00")) => falsey))
| 89098 | (ns time-count.explainer.c-allens-interval-algebra
(:require
[time-count.core :refer :all]
[time-count.allens-algebra :refer [relation]]
[time-count.relation-bounded-intervals :refer [map->RelationBoundedInterval ->RelationBound relate-bound-to-ct]]
[time-count.iso8601 :refer [to-iso from-iso t->>]]
[time-count.metajoda]
[midje.sweet :refer :all]))
;; In time-count, all time values are interpreted as intervals.
;; CountableTimes are taken to span period the length of their scale.
;; For example, 2017-12-13 is an interval 1 day long. 2017-12-13T09:15 is an interval 1 minute long.
;; Traditional "before/after" comparison is incomplete, and can result in ambiguous or complex business logic.
;; time-count uses Allen's Interval Algebra to compare intervals.
;; (There is a good explanation here https://www.ics.uci.edu/~al<NAME>/cls/shr/allen.html )
;; Allen defined 13 basic relations, which are distinct and exhaustive:
(fact "Thirteen basic relations in Allen's Interval Algebra"
(t->> ["2017" "2017"] (apply relation)) => :equal
(t->> ["2015" "2017"] (apply relation)) => :before
(t->> ["2017" "2015"] (apply relation)) => :after
(t->> ["2016" "2017"] (apply relation)) => :meets
(t->> ["2017" "2016"] (apply relation)) => :met-by
(t->> ["2017-01" "2017"] (apply relation)) => :starts
(t->> ["2017" "2017-01"] (apply relation)) => :started-by
(t->> ["2017-12" "2017"] (apply relation)) => :finishes
(t->> ["2017" "2017-12"] (apply relation)) => :finished-by
(t->> ["2017-02" "2017"] (apply relation)) => :during
(t->> ["2017" "2017-02"] (apply relation)) => :contains
(t->> ["2017-W05" "2017-02"] (apply relation)) => :overlaps
(t->> ["2017-02" "2017-W05"] (apply relation)) => :overlapped-by)
;; Intervals other than those defined as countable times, can be described by their boundaries.
;; The boundary of an interval can be defined in terms of a relation to another interval.
;; In the current implementation of time-count, only :starts and :finishes are supported.
(fact "RelationBoundedIntervals are defined by a combination of Allen's :starts and :finishes relations to other intervals."
(-> {:starts (from-iso "2017") :finishes (from-iso "2019")}
map->RelationBoundedInterval
to-iso)
=> "2017/2019"
(-> {:starts (from-iso "2017-10") :finishes (from-iso "2017-12")}
map->RelationBoundedInterval
to-iso)
=> "2017-10/2017-12"
(-> {:starts (from-iso "2017-10")}
map->RelationBoundedInterval
to-iso)
=> "2017-10/-")
(fact "RelationBoundedIntervals and CountableTimes are compared in the same way."
(relation (from-iso "2017") (from-iso "2019"))
=> :before
(relation (from-iso "2017/2018") (from-iso "2019/2020"))
=> :meets)
(fact "RelationBoundedIntervals and CountableTimes can be compared to each other."
(relation (from-iso "2017/2019") (from-iso "2018"))
=> :contains
(relation (from-iso "2018") (from-iso "2017/2019"))
=> :during)
(facts "About RelationBounds (A RelationBoundedInterval is just a combination of one or two boundaries.)"
(fact "The relation of a single RelationBound with a CountableTime gives a set of possible basic relations (which is, itself, a relation)."
(relate-bound-to-ct
(->RelationBound :finishes (from-iso "2018"))
(from-iso "2017"))
=> #{:overlapped-by :started-by :contains}))
;The basic relations of a RelationBoundedInterval are the intersection of the relations of its two bounds.
(fact "Business rules comparing time are expressed using sets of relations."
(let [contract {:due-date (from-iso "2017-02-15")
:overdue-relation #{:after :met-by} ;This defines what it means to be 'overdue' in relation to the due-date
; ... other contract stuff ...
}
overdue-as-of? #((contract :overdue-relation) (relation % (contract :due-date)))]
(overdue-as-of? (from-iso "2017-02-10T14:30")) => falsey
(overdue-as-of? (from-iso "2017-02-15T20:30")) => falsey
(overdue-as-of? (from-iso "2017-02-15T23:59")) => falsey
(overdue-as-of? (from-iso "2017-02-16T00:00")) => truthy
(overdue-as-of? (from-iso "2017-02-17T10:04")) => truthy)
(let [contract {:active-interval (from-iso "2017-01-01/2017-03-31")
:active-relation #{:starts :during :finishes} ;This defines what it means to be 'active' in relation to the active-interval.
; ... other contract stuff ...
}
active-as-of? #((contract :active-relation) (relation % (contract :active-interval)))]
(active-as-of? (from-iso "2016-12-10T14:30")) => falsey
(active-as-of? (from-iso "2016-12-31T23:59")) => falsey
(active-as-of? (from-iso "2017-02-15T23:59")) => truthy
(active-as-of? (from-iso "2017-03-31T23:59")) => truthy
(active-as-of? (from-iso "2017-04-01T00:00")) => falsey))
| true | (ns time-count.explainer.c-allens-interval-algebra
(:require
[time-count.core :refer :all]
[time-count.allens-algebra :refer [relation]]
[time-count.relation-bounded-intervals :refer [map->RelationBoundedInterval ->RelationBound relate-bound-to-ct]]
[time-count.iso8601 :refer [to-iso from-iso t->>]]
[time-count.metajoda]
[midje.sweet :refer :all]))
;; In time-count, all time values are interpreted as intervals.
;; CountableTimes are taken to span period the length of their scale.
;; For example, 2017-12-13 is an interval 1 day long. 2017-12-13T09:15 is an interval 1 minute long.
;; Traditional "before/after" comparison is incomplete, and can result in ambiguous or complex business logic.
;; time-count uses Allen's Interval Algebra to compare intervals.
;; (There is a good explanation here https://www.ics.uci.edu/~alPI:NAME:<NAME>END_PI/cls/shr/allen.html )
;; Allen defined 13 basic relations, which are distinct and exhaustive:
(fact "Thirteen basic relations in Allen's Interval Algebra"
(t->> ["2017" "2017"] (apply relation)) => :equal
(t->> ["2015" "2017"] (apply relation)) => :before
(t->> ["2017" "2015"] (apply relation)) => :after
(t->> ["2016" "2017"] (apply relation)) => :meets
(t->> ["2017" "2016"] (apply relation)) => :met-by
(t->> ["2017-01" "2017"] (apply relation)) => :starts
(t->> ["2017" "2017-01"] (apply relation)) => :started-by
(t->> ["2017-12" "2017"] (apply relation)) => :finishes
(t->> ["2017" "2017-12"] (apply relation)) => :finished-by
(t->> ["2017-02" "2017"] (apply relation)) => :during
(t->> ["2017" "2017-02"] (apply relation)) => :contains
(t->> ["2017-W05" "2017-02"] (apply relation)) => :overlaps
(t->> ["2017-02" "2017-W05"] (apply relation)) => :overlapped-by)
;; Intervals other than those defined as countable times, can be described by their boundaries.
;; The boundary of an interval can be defined in terms of a relation to another interval.
;; In the current implementation of time-count, only :starts and :finishes are supported.
(fact "RelationBoundedIntervals are defined by a combination of Allen's :starts and :finishes relations to other intervals."
(-> {:starts (from-iso "2017") :finishes (from-iso "2019")}
map->RelationBoundedInterval
to-iso)
=> "2017/2019"
(-> {:starts (from-iso "2017-10") :finishes (from-iso "2017-12")}
map->RelationBoundedInterval
to-iso)
=> "2017-10/2017-12"
(-> {:starts (from-iso "2017-10")}
map->RelationBoundedInterval
to-iso)
=> "2017-10/-")
(fact "RelationBoundedIntervals and CountableTimes are compared in the same way."
(relation (from-iso "2017") (from-iso "2019"))
=> :before
(relation (from-iso "2017/2018") (from-iso "2019/2020"))
=> :meets)
(fact "RelationBoundedIntervals and CountableTimes can be compared to each other."
(relation (from-iso "2017/2019") (from-iso "2018"))
=> :contains
(relation (from-iso "2018") (from-iso "2017/2019"))
=> :during)
(facts "About RelationBounds (A RelationBoundedInterval is just a combination of one or two boundaries.)"
(fact "The relation of a single RelationBound with a CountableTime gives a set of possible basic relations (which is, itself, a relation)."
(relate-bound-to-ct
(->RelationBound :finishes (from-iso "2018"))
(from-iso "2017"))
=> #{:overlapped-by :started-by :contains}))
;The basic relations of a RelationBoundedInterval are the intersection of the relations of its two bounds.
(fact "Business rules comparing time are expressed using sets of relations."
(let [contract {:due-date (from-iso "2017-02-15")
:overdue-relation #{:after :met-by} ;This defines what it means to be 'overdue' in relation to the due-date
; ... other contract stuff ...
}
overdue-as-of? #((contract :overdue-relation) (relation % (contract :due-date)))]
(overdue-as-of? (from-iso "2017-02-10T14:30")) => falsey
(overdue-as-of? (from-iso "2017-02-15T20:30")) => falsey
(overdue-as-of? (from-iso "2017-02-15T23:59")) => falsey
(overdue-as-of? (from-iso "2017-02-16T00:00")) => truthy
(overdue-as-of? (from-iso "2017-02-17T10:04")) => truthy)
(let [contract {:active-interval (from-iso "2017-01-01/2017-03-31")
:active-relation #{:starts :during :finishes} ;This defines what it means to be 'active' in relation to the active-interval.
; ... other contract stuff ...
}
active-as-of? #((contract :active-relation) (relation % (contract :active-interval)))]
(active-as-of? (from-iso "2016-12-10T14:30")) => falsey
(active-as-of? (from-iso "2016-12-31T23:59")) => falsey
(active-as-of? (from-iso "2017-02-15T23:59")) => truthy
(active-as-of? (from-iso "2017-03-31T23:59")) => truthy
(active-as-of? (from-iso "2017-04-01T00:00")) => falsey))
|
[
{
"context": "e222591126443015f5f462d9a177186c8701fb45a6ffee0daf1a178fc0f58cd309308fba7e6f011ac38c9cdd4580760f1d4560a84d5ca0355ecbbed2ab715a3350fe0c479050640bd0e77acec90c58c4d3dd0f5cf8d4510e68c8b12e087bd88cad349aafd2ab16b07b0b1b8276091217a44a9fe92fedacffff48092ee693af\\n\")\n\n;;;;; Utils\n;; to create session ids\n(defn uui",
"end": 1831,
"score": 0.7035152316093445,
"start": 1625,
"tag": "KEY",
"value": "1a178fc0f58cd309308fba7e6f011ac38c9cdd4580760f1d4560a84d5ca0355ecbbed2ab715a3350fe0c479050640bd0e77acec90c58c4d3dd0f5cf8d4510e68c8b12e087bd88cad349aafd2ab16b07b0b1b8276091217a44a9fe92fedacffff48092ee693af\\n"
}
] | clj-browserchannel-server/src/net/thegeez/browserchannel.clj | magomimmo/clj-browserchannel | 1 | (ns net.thegeez.browserchannel
"BrowserChannel server implementation in Clojure."
(:require [ring.middleware.params :as params]
[ring.util.codec :as codec]
[clojure.data.json :as json]
[clojure.string :as str]
[net.thegeez.async-adapter :as async-adapter])
(:import [java.util.concurrent ScheduledExecutorService Executors TimeUnit]))
;; @todo: out of order acks and maps
;; @todo use a more specific Exception for failing writes, which
;; indicate closed connection
;; @todo SSL in jetty-async-adapter
;; @todo session-timeout should deduct waiting time for the failed
;; sent heartbeat?
(def default-options
{;; a.example, b.example => ["a","b"]
:host-prefixes []
;; straight from google
:headers {"Content-Type" "text/plain"
"Cache-Control" "no-cache, no-store, max-age=0, must-revalidate"
"Pragma" "no-cache"
"Expires" "Fri, 01 Jan 1990 00:00:00 GMT"
"X-Content-Type-Options" "nosniff"
}
:base "/channel" ;; root for /test and /bind urls
:keep-alive-interval 10 ;; seconds, keep less than session-time-out
:session-timeout-interval 15 ;; seconds
;; after this number of bytes a
;; backchannel will always be closed
:data-threshold (* 10 1024)
})
(def noop-string "[\"noop\"]")
;; almost all special cases are for making this work with IE
(def ie-headers
{"Content-Type" "text/html"})
;; appended to first write to ie to prevent whole page buffering
(def ie-stream-padding "7cca69475363026330a0d99468e88d23ce95e222591126443015f5f462d9a177186c8701fb45a6ffee0daf1a178fc0f58cd309308fba7e6f011ac38c9cdd4580760f1d4560a84d5ca0355ecbbed2ab715a3350fe0c479050640bd0e77acec90c58c4d3dd0f5cf8d4510e68c8b12e087bd88cad349aafd2ab16b07b0b1b8276091217a44a9fe92fedacffff48092ee693af\n")
;;;;; Utils
;; to create session ids
(defn uuid [] (str (java.util.UUID/randomUUID)))
(def scheduler (Executors/newScheduledThreadPool 1))
;; scheduling a task returns a ScheduledFuture, which can be stopped
;; with (.cancel task false) false says not to interrupt running tasks
(defn schedule [f secs]
(.schedule scheduler f secs TimeUnit/SECONDS))
;; json responses are sent as "size-of-response\njson-response"
(defn size-json-str [json]
(let [size (alength (.getBytes json "UTF-8"))]
(str size "\n" json)))
;; make sure the root URI for channels starts with a / for route matching
(defn standard-base [s]
(let [wofirst (if (= \/ (first s))
(apply str (rest s))
s)
wolast (if (= \/ (last wofirst))
(apply str (butlast wofirst))
wofirst)]
(str "/" wolast)))
;; @todo to test file
(assert (= (repeat 4 "/foo")
(map standard-base ["foo" "/foo" "foo/" "/foo"])))
;; type preserving drop upto for queueus
(defn drop-queue [queue id]
(let [head (peek queue)]
(if-not head
queue
(if (< id (first head))
queue
(recur (pop queue) id)))))
(defn transform-url-data [data]
(let [ofs (get data "ofs" "0")
pieces (dissoc data "count" "ofs")]
{:ofs (Long/parseLong ofs)
:maps (->> (for [[k v] pieces]
(let [[_ n k] (re-find #"req(\d+)_(\w+)" k)]
[n {k v}]))
(partition-by first)
(map #(into {} (map second %))))}))
(assert (= {:ofs 0 :maps [{"x" "3" "y" "10"} {"abc" "def"}]}
(transform-url-data {"count" "2"
"ofs" "0"
"req0_x" "3"
"req0_y" "10"
"req1_abc" "def"})))
;; maps are URL Encoded
;;;; URL Encoded data:
;;{ count: '2',
;; ofs: '0',
;; req0_x: '3',
;; req0_y: '10',
;; req1_abc: 'def'
;;}
;;as :form-params in req:
;;{"count" "2"
;; "ofs" "0"
;; "req0_x" "3"
;; "req0_y" "10"
;; "req1_abc" "def"}
;; =>
;;{:ofs 0 :maps [{"x" "3" "y" "10"},{"abc": "def"}]}
(defn get-maps [req]
(let [data (:form-params req)]
(when-not (zero? (count data))
;; number of entries in form-params,
;; not (get "count" (:form-params req))
;; @todo "count" is currently not used to verify the number of
;; parsed maps
(:maps (transform-url-data data)))))
;; rather crude but straight from google
(defn error-response [status-code message]
{:status status-code
:body (str "<html><body><h1>" message "</h1></body></html>")})
;;;;;; end of utils
;;;; listeners
;; @todo clean this up, perhaps store listeners in the session?
;; @todo replace with lamina?
;; sessionId -> :event -> [call back]
;; event: :map | :close
(def listeners-agent (agent {}))
(defn add-listener [session-id event-key f]
(send-off listeners-agent
update-in [session-id event-key] #(conj (or % []) f)))
(defn notify-listeners [session-id event-key & data]
(send-off listeners-agent
(fn [listeners]
(doseq [callback (get-in listeners [session-id event-key])]
(apply callback data))
listeners)))
;; end of listeners
;; Wrapper around writers on continuations
;; the write methods raise an Exception with the wrapped response in closed
;; @todo use a more specific Exception
(defprotocol IResponseWrapper
(write-head [this])
(write [this data])
(write-raw [this data])
(write-end [this]))
;; for writing on backchannel to non-IE clients
(deftype XHRWriter [;; respond calls functions on the continuation
respond
headers]
IResponseWrapper
(write-head [this]
(async-adapter/head respond 200 headers))
(write [this data]
(write-raw this (size-json-str data)))
(write-raw [this data]
(async-adapter/write-chunk respond data))
(write-end [this]
(async-adapter/close respond)))
;; for writing on backchannels to IE clients
(deftype IEWriter [;; respond calls functions on the continuation
respond
headers
;; DOMAIN value from query string
domain
;; first write requires padding,
;; padding-sent is a flag for the first time
^{:volatile-mutable true} write-padding-sent
;; likewise for write raw, used during test phase
^{:volatile-mutable true} write-raw-padding-sent]
IResponseWrapper
(write-head [this]
(async-adapter/head respond 200 (merge headers ie-headers))
(async-adapter/write-chunk respond "<html><body>\n")
(when (seq domain)
(async-adapter/write-chunk respond (str "<script>try{document.domain=\"" (pr-str (json/json-str domain)) "\";}catch(e){}</script>\n"))))
(write [this data]
(async-adapter/write-chunk respond (str "<script>try {parent.m(" (pr-str data) ")} catch(e) {}</script>\n"))
(when-not write-padding-sent
(async-adapter/write-chunk respond ie-stream-padding)
(set! write-padding-sent true)))
(write-raw [this data]
(async-adapter/write-chunk respond (str "<script>try {parent.m(" (pr-str data) ")} catch(e) {}</script>\n"))
(when-not write-raw-padding-sent
(async-adapter/write-chunk respond ie-stream-padding)
(set! write-raw-padding-sent true)))
(write-end [this]
(async-adapter/write-chunk respond "<script>try {parent.d(); }catch (e){}</script>\n")
(async-adapter/close respond)))
;;ArrayBuffer
;;buffer of [[id_lowest data] ... [id_highest data]]
(defprotocol IArrayBuffer
(queue [this string])
(acknowledge-id [this id])
(to-flush [this])
(last-acknowledged-id [this])
(outstanding-bytes [this])
)
(deftype ArrayBuffer [;; id of the last array that is conj'ed, can't
;; always be derived because flush buffer might
;; be empty
array-id
;; needed for session status
last-acknowledged-id
;; array that have been flushed, but not yet
;; acknowledged, does not contain noop messages
to-acknowledge-arrays
;; arrays to be sent out, may contain arrays
;; that were in to-acknowledge-arrays but queued
;; again for resending
to-flush-arrays
]
IArrayBuffer
(queue [this string]
(let [next-array-id (inc array-id)]
(ArrayBuffer. next-array-id
last-acknowledged-id
to-acknowledge-arrays
(conj to-flush-arrays [next-array-id string]))))
;; id may cause the following splits:
;; normal case:
;; ack-arrs <id> flush-arrs
;; client is slow case:
;; ack-arrs <id> ack-arrs flush-arrs
;; after arrays have been requeued:
;; ack-arrs flush-arrs <id> flush-arrs
;; everything before id can be discarded, everything after id
;; becomes new flush-arrs and is resend
(acknowledge-id [this id]
(ArrayBuffer. array-id
id
clojure.lang.PersistentQueue/EMPTY
(into (drop-queue to-acknowledge-arrays id)
(drop-queue to-flush-arrays id))))
;; return [seq-to-flush-array next-array-buffer] or nil if
;; to-flush-arrays is empty
(to-flush [this]
(when-let [to-flush (seq to-flush-arrays)]
[to-flush (ArrayBuffer. array-id
last-acknowledged-id
(into to-acknowledge-arrays
(remove (fn [[id string]]
(= string noop-string))
to-flush))
clojure.lang.PersistentQueue/EMPTY)]))
(last-acknowledged-id [this]
last-acknowledged-id)
;; the sum of all the data that is still to be send
(outstanding-bytes [this]
(reduce + 0 (map (comp count second) to-flush-arrays))))
;; {sessionId -> (agent session)}
(def sessions (atom {}))
;; All methods meant to be fn send to an agent, therefor all need to return a Session
(defprotocol ISession
;; a session spans multiple connections, the connections for the
;; backward channel is the backchannel of a session
(clear-back-channel [this])
(set-back-channel [this
;; respond is a wrapper of the continuation
respond
request])
;; messages sent from server to client are arrays
;; the client acknowledges received arrays when creating a new backwardchannel
(acknowledge-arrays [this array-ids])
(queue-string [this string])
;; heartbeat is a timer to send noop over the backward channel
(clear-heartbeat [this])
(refresh-heartbeat [this])
;; after a backward channel closes the session is kept alive, so
;; the client can reconnect. If there is no reconnect before
;; session-timeout the session is closed
(clear-session-timeout [this])
(refresh-session-timeout [this])
;; try to send data to the client over the backchannel.
;; if there is no backchannel, then nothing happens
(flush-buffer [this])
;; after close this session cannot be reconnected to.
;; removes session for sessions
(close [this message]))
(defrecord BackChannel [;; respond wraps the continuation, which is
;; the actual connection of the backward
;; channel to the client
respond
;; when true use streaming
chunk
;; this is used for diagnostic purposes by the client
bytes-sent])
(defrecord Session [;; must be unique
id
;; {:address
;; :headers
;; :app-version
;; :heartbeat-interval
;; :session-timeout-interval
;; :data-threshold
;;}
details
;; back-channel might be nil, as a session spans
;; multiple connections
back-channel
;; ArrayBuffer
array-buffer
;; ScheduleTask or nil
heartbeat-timeout
;; ScheduleTask or nil
;; when the backchannel is closed from this
;; session, the session is only removes when this
;; timer expires during this time the client can
;; reconnect to its session
session-timeout]
ISession
(clear-back-channel [this]
(try
(when back-channel
(write-end (:respond back-channel)))
(catch Exception e
nil ;; close back channel regardless
))
(-> this
clear-heartbeat
(assoc :back-channel nil)
refresh-session-timeout))
(set-back-channel [this respond req]
(let [bc (BackChannel. respond
;; can we stream responses
;; back?
;; CI is determined client
;; side with /test
(= (get-in req [:query-params "CI"]) "0")
;; no bytes sent yet
0)]
(-> this
clear-back-channel
;; clear-back-channel sets the session-timeout
;; here we know the session is alive and
;; well due to this new backchannel
clear-session-timeout
(assoc :back-channel bc)
refresh-heartbeat
;; try to send any data that was buffered
;; while there was no backchannel
flush-buffer)))
(clear-heartbeat [this]
(when heartbeat-timeout
(.cancel heartbeat-timeout
false ;; do not interrupt running tasks
))
(assoc this :heartbeat-timeout nil))
(refresh-heartbeat [this]
(-> this
clear-heartbeat
(assoc :heartbeat-timeout
;; *agent* not bound when executed later
;; through schedule, therefor passed explicitly
(let [session-agent *agent*]
(schedule (fn []
(send-off session-agent #(-> %
(queue-string noop-string)
flush-buffer)))
(:heartbeat-interval details))))))
(clear-session-timeout [this]
(when session-timeout
(.cancel session-timeout
false ;; do not interrupt running tasks
))
(assoc this :session-timeout nil))
(refresh-session-timeout [this]
(-> this
clear-session-timeout
(assoc :session-timeout
(let [session-agent *agent*]
(schedule (fn []
(send-off session-agent close "Timed out"))
(:session-timeout-interval details))))))
(queue-string [this string]
(update-in this [:array-buffer] queue string))
(acknowledge-arrays [this array-id]
(let [array-id (Long/parseLong array-id)]
(update-in this [:array-buffer] acknowledge-id array-id)))
;; tries to do the actual writing to the client
;; @todo the composition is a bit awkward in this method due to the
;; try catch and if mix
(flush-buffer [this]
(if-not back-channel
this ;; nothing to do when there's no connection
;; only flush unacknowledged arrays
(if-let [[to-flush next-array-buffer] (to-flush array-buffer)]
(try
;; buffer contains [[1 json-str] ...] can't use
;; json-str which will double escape the json
(let [data (str "["
(str/join "," (map (fn [[n d]] (str "[" n "," d "]")) to-flush))
"]")]
;; write throws exception when the connection is closed
(write (:respond back-channel) data))
;; size is an approximation
(let [this (let [size (reduce + 0 (map count (map second to-flush)))]
(-> this
(assoc :array-buffer next-array-buffer)
(update-in [:back-channel :bytes-sent] + size)))
;; clear-back-channel closes the back
;; channel when the channel does not
;; support streaming or when a large
;; amount of data has been sent
this (if (or (not (get-in this [:back-channel :chunk]))
(< (:data-threshold details) (get-in this [:back-channel :bytes-sent])))
(clear-back-channel this)
this)]
;; this sending of data keeps the connection alive
;; make a new heartbeat
(refresh-heartbeat this))
(catch Exception e
;; when write failed
;; non delivered arrays are still in buffer
(clear-back-channel this)
))
this ;; do nothing if buffer is empty
)))
;; closes the session and removes it from sessions
(close [this message]
(-> this
clear-back-channel
clear-session-timeout
;; the heartbeat timeout is cancelled by clear-back-channel
)
(swap! sessions dissoc id)
(notify-listeners id :close message)
nil ;; the agent will no longer wrap a session
))
;; creates a session agent wrapping session data and
;; adds the session to sessions
(defn create-session-agent [req options]
(let [{initial-rid "RID" ;; identifier for forward channel
app-version "CVER" ;; client can specify a custom app-version
old-session-id "OSID"
old-array-id "OAID"} (:query-params req)]
;; when a client specifies and old session id then that old one
;; needs to be removed
(when-let [old-session-agent (@sessions old-session-id)]
(send-off old-session-agent #(-> (if old-array-id
(acknowledge-arrays % old-array-id)
%)
(close "Reconnected"))))
(let [id (uuid)
details {:address (:remote-addr req)
:headers (:headers req)
:app-version app-version
:heartbeat-interval (:keep-alive-interval options)
:session-timeout-interval (:session-timeout-interval options)
:data-threshold (:data-threshold options)}
session (-> (Session. id
details
nil ;; backchannel
(ArrayBuffer.
0 ;; array-id, 0 is never used by the
;; array-buffer, it is used by the
;; first message with the session id
0 ;; last-acknowledged-id
;; to-acknowledge-arrays
clojure.lang.PersistentQueue/EMPTY
;; to-flush-arrays
clojure.lang.PersistentQueue/EMPTY)
nil ;; heartbeat-timeout
nil ;; session-timeout
)
;; this first session-timeout is for the case
;; when the client never connects with a backchannel
refresh-session-timeout)
session-agent (agent session)]
(swap! sessions assoc id session-agent)
(when-let [notify (:on-session options)]
(notify id req))
session-agent)))
(defn session-status [session]
(let [has-back-channel (if (:back-channel session) 1 0)
array-buffer (:array-buffer session)]
[has-back-channel (last-acknowledged-id array-buffer) (outstanding-bytes array-buffer)]))
;; convience function to send data to a session
;; the data will be queued until there is a backchannel to send it
;; over
(defn send-string [session-id string]
(when-let [session-agent (get @sessions session-id)]
(send-off session-agent #(-> %
(queue-string string)
flush-buffer))))
(defn send-map [session-id map]
(send-string session-id (json/json-str map)))
;; wrap the respond function from :reactor with the proper
;; responsewrapper for either IE or other clients
(defn wrap-continuation-writers [handler options]
(fn [req]
(let [res (handler req)]
(if (:async res)
(let [reactor (:reactor res)
type (get-in req [:query-params "TYPE"])]
(assoc res :reactor
(fn [respond]
(reactor (let [headers (assoc (:headers options)
"Transfer-Encoding" "chunked")]
(if (= type "html")
(let [domain (get-in req [:query-params "DOMAIN"])]
;; last two false are the padding
;; sent flags
(IEWriter. respond headers domain false false))
(XHRWriter. respond headers)))))))
res ;; do not touch responses without :async
))))
;; test channel is used to determine which host to connect to
;; and if the connection can support streaming
(defn handle-test-channel [req options]
(if-not (= "8" (get-in req [:query-params "VER"]))
(error-response 400 "Version 8 required")
;; phase 1
;; client requests [random host-prefix or
;; nil,blockedPrefix]
;; blockedPrefix not supported, always nil
(if (= (get-in req [:query-params "MODE"]) "init")
(let [host-prefix (when-let [prefixes (seq (:host-prefixes options))]
(rand-nth prefixes))]
{:status 200
:headers (assoc (:headers options) "X-Accept" "application/json; application/x-www-form-urlencoded")
:body (json/json-str [host-prefix,nil])})
;; else phase 2 for get /test
;; client checks if connection is buffered
;; send 11111, wait 2 seconds, send 2
;; if client gets two chunks, then there is no buffering
;; proxy in the way
{:async :http
:reactor
(fn [respond]
(write-head respond)
(write-raw respond "11111")
(schedule #(do (write-raw respond "2")
(write-end respond))
2))})))
;; POST req client -> server is a forward channel
;; session might be nil, when this is the first POST by client
(defn handle-forward-channel [req session-agent options]
(let [[session-agent is-new-session] (if session-agent
[session-agent false]
[(create-session-agent req options) true])
;; maps contains whatever the messages to the server
maps (get-maps req)]
(if is-new-session
;; first post after a new session is a message with the session
;; details.
;; response is first array sent for this session:
;; [[0,["c", session-id, host-prefix, version (always 8)]]]
;; send as json for XHR and IE
(let [session @session-agent
session-id (:id session)
;; @todo extract the used host-prefix from the request if any
host-prefix nil]
{:status 200
:headers (assoc (:headers options) "Content-Type" "application/javascript")
:body
(size-json-str (json/json-str [[0,["c", session-id, host-prefix, 8]]]))})
;; For existing sessions:
;; Forward sent data by client to listeners
;; reply with
;; [backchannelPresent,lastPostResponseArrayId_,numOutstandingBackchannelBytes]
;; backchannelPresent = 0 for false, 1 for true
;; send as json for XHR and IE
(do
(doseq [map maps]
(notify-listeners (:id @session-agent) :map map))
(let [status (session-status @session-agent)]
{:status 200
:headers (:headers options)
:body (size-json-str (json/json-str status))})))))
;; GET req server->client is a backwardchannel opened by client
(defn handle-backward-channel [req session-agent options]
(let [type (get-in req [:query-params "TYPE"])]
(cond
(#{"xmlhttp" "html"} type)
;; @todo check that query RID is "rpc"
{:async :http
:reactor
(fn [respond]
(write-head respond)
(send-off session-agent set-back-channel respond req))}
(= type "terminate")
;; this is a request made in an img tag
(do ;;end session
(when session-agent
(send-off session-agent close "Disconnected"))
{:status 200
:headers (:headers options)
:body ""}
))))
;; get to /<base>/bind is client->server msg
;; post to /<base>/bind is initiate server->client channel
(defn handle-bind-channel [req options]
(let [SID (get-in req [:query-params "SID"])
;; session-agent might be nil, then it will be created by
;; handle-forward-channel
session-agent (@sessions SID)]
(if (and SID
(not session-agent))
;; SID refers to an already created session, which therefore
;; must exist
(error-response 400 "Unknown SID")
(do
;; client can tell the server which array it has seen
;; up to including AID can be removed from the buffer
(when session-agent
(when-let [AID (get-in req [:query-params "AID"])]
(send-off session-agent acknowledge-arrays AID)))
(condp = (:request-method req)
:post (handle-forward-channel req session-agent options)
:get (handle-backward-channel req session-agent options))))))
;; see default-options for describtion of options
(defn wrap-browserchannel [handler & [options]]
(let [options (merge default-options options)
base (str (:base options))]
(-> (fn [req]
(let [uri (:uri req)
method (:request-method req)]
(cond
(and (.startsWith uri (str base "/test"))
(= method :get))
(handle-test-channel req options)
(.startsWith uri (str base "/bind"))
(handle-bind-channel req options)
:else (handler req))))
(wrap-continuation-writers options)
params/wrap-params
)))
| 88803 | (ns net.thegeez.browserchannel
"BrowserChannel server implementation in Clojure."
(:require [ring.middleware.params :as params]
[ring.util.codec :as codec]
[clojure.data.json :as json]
[clojure.string :as str]
[net.thegeez.async-adapter :as async-adapter])
(:import [java.util.concurrent ScheduledExecutorService Executors TimeUnit]))
;; @todo: out of order acks and maps
;; @todo use a more specific Exception for failing writes, which
;; indicate closed connection
;; @todo SSL in jetty-async-adapter
;; @todo session-timeout should deduct waiting time for the failed
;; sent heartbeat?
(def default-options
{;; a.example, b.example => ["a","b"]
:host-prefixes []
;; straight from google
:headers {"Content-Type" "text/plain"
"Cache-Control" "no-cache, no-store, max-age=0, must-revalidate"
"Pragma" "no-cache"
"Expires" "Fri, 01 Jan 1990 00:00:00 GMT"
"X-Content-Type-Options" "nosniff"
}
:base "/channel" ;; root for /test and /bind urls
:keep-alive-interval 10 ;; seconds, keep less than session-time-out
:session-timeout-interval 15 ;; seconds
;; after this number of bytes a
;; backchannel will always be closed
:data-threshold (* 10 1024)
})
(def noop-string "[\"noop\"]")
;; almost all special cases are for making this work with IE
(def ie-headers
{"Content-Type" "text/html"})
;; appended to first write to ie to prevent whole page buffering
(def ie-stream-padding "7cca69475363026330a0d99468e88d23ce95e222591126443015f5f462d9a177186c8701fb45a6ffee0daf<KEY>")
;;;;; Utils
;; to create session ids
(defn uuid [] (str (java.util.UUID/randomUUID)))
(def scheduler (Executors/newScheduledThreadPool 1))
;; scheduling a task returns a ScheduledFuture, which can be stopped
;; with (.cancel task false) false says not to interrupt running tasks
(defn schedule [f secs]
(.schedule scheduler f secs TimeUnit/SECONDS))
;; json responses are sent as "size-of-response\njson-response"
(defn size-json-str [json]
(let [size (alength (.getBytes json "UTF-8"))]
(str size "\n" json)))
;; make sure the root URI for channels starts with a / for route matching
(defn standard-base [s]
(let [wofirst (if (= \/ (first s))
(apply str (rest s))
s)
wolast (if (= \/ (last wofirst))
(apply str (butlast wofirst))
wofirst)]
(str "/" wolast)))
;; @todo to test file
(assert (= (repeat 4 "/foo")
(map standard-base ["foo" "/foo" "foo/" "/foo"])))
;; type preserving drop upto for queueus
(defn drop-queue [queue id]
(let [head (peek queue)]
(if-not head
queue
(if (< id (first head))
queue
(recur (pop queue) id)))))
(defn transform-url-data [data]
(let [ofs (get data "ofs" "0")
pieces (dissoc data "count" "ofs")]
{:ofs (Long/parseLong ofs)
:maps (->> (for [[k v] pieces]
(let [[_ n k] (re-find #"req(\d+)_(\w+)" k)]
[n {k v}]))
(partition-by first)
(map #(into {} (map second %))))}))
(assert (= {:ofs 0 :maps [{"x" "3" "y" "10"} {"abc" "def"}]}
(transform-url-data {"count" "2"
"ofs" "0"
"req0_x" "3"
"req0_y" "10"
"req1_abc" "def"})))
;; maps are URL Encoded
;;;; URL Encoded data:
;;{ count: '2',
;; ofs: '0',
;; req0_x: '3',
;; req0_y: '10',
;; req1_abc: 'def'
;;}
;;as :form-params in req:
;;{"count" "2"
;; "ofs" "0"
;; "req0_x" "3"
;; "req0_y" "10"
;; "req1_abc" "def"}
;; =>
;;{:ofs 0 :maps [{"x" "3" "y" "10"},{"abc": "def"}]}
(defn get-maps [req]
(let [data (:form-params req)]
(when-not (zero? (count data))
;; number of entries in form-params,
;; not (get "count" (:form-params req))
;; @todo "count" is currently not used to verify the number of
;; parsed maps
(:maps (transform-url-data data)))))
;; rather crude but straight from google
(defn error-response [status-code message]
{:status status-code
:body (str "<html><body><h1>" message "</h1></body></html>")})
;;;;;; end of utils
;;;; listeners
;; @todo clean this up, perhaps store listeners in the session?
;; @todo replace with lamina?
;; sessionId -> :event -> [call back]
;; event: :map | :close
(def listeners-agent (agent {}))
(defn add-listener [session-id event-key f]
(send-off listeners-agent
update-in [session-id event-key] #(conj (or % []) f)))
(defn notify-listeners [session-id event-key & data]
(send-off listeners-agent
(fn [listeners]
(doseq [callback (get-in listeners [session-id event-key])]
(apply callback data))
listeners)))
;; end of listeners
;; Wrapper around writers on continuations
;; the write methods raise an Exception with the wrapped response in closed
;; @todo use a more specific Exception
(defprotocol IResponseWrapper
(write-head [this])
(write [this data])
(write-raw [this data])
(write-end [this]))
;; for writing on backchannel to non-IE clients
(deftype XHRWriter [;; respond calls functions on the continuation
respond
headers]
IResponseWrapper
(write-head [this]
(async-adapter/head respond 200 headers))
(write [this data]
(write-raw this (size-json-str data)))
(write-raw [this data]
(async-adapter/write-chunk respond data))
(write-end [this]
(async-adapter/close respond)))
;; for writing on backchannels to IE clients
(deftype IEWriter [;; respond calls functions on the continuation
respond
headers
;; DOMAIN value from query string
domain
;; first write requires padding,
;; padding-sent is a flag for the first time
^{:volatile-mutable true} write-padding-sent
;; likewise for write raw, used during test phase
^{:volatile-mutable true} write-raw-padding-sent]
IResponseWrapper
(write-head [this]
(async-adapter/head respond 200 (merge headers ie-headers))
(async-adapter/write-chunk respond "<html><body>\n")
(when (seq domain)
(async-adapter/write-chunk respond (str "<script>try{document.domain=\"" (pr-str (json/json-str domain)) "\";}catch(e){}</script>\n"))))
(write [this data]
(async-adapter/write-chunk respond (str "<script>try {parent.m(" (pr-str data) ")} catch(e) {}</script>\n"))
(when-not write-padding-sent
(async-adapter/write-chunk respond ie-stream-padding)
(set! write-padding-sent true)))
(write-raw [this data]
(async-adapter/write-chunk respond (str "<script>try {parent.m(" (pr-str data) ")} catch(e) {}</script>\n"))
(when-not write-raw-padding-sent
(async-adapter/write-chunk respond ie-stream-padding)
(set! write-raw-padding-sent true)))
(write-end [this]
(async-adapter/write-chunk respond "<script>try {parent.d(); }catch (e){}</script>\n")
(async-adapter/close respond)))
;;ArrayBuffer
;;buffer of [[id_lowest data] ... [id_highest data]]
(defprotocol IArrayBuffer
(queue [this string])
(acknowledge-id [this id])
(to-flush [this])
(last-acknowledged-id [this])
(outstanding-bytes [this])
)
(deftype ArrayBuffer [;; id of the last array that is conj'ed, can't
;; always be derived because flush buffer might
;; be empty
array-id
;; needed for session status
last-acknowledged-id
;; array that have been flushed, but not yet
;; acknowledged, does not contain noop messages
to-acknowledge-arrays
;; arrays to be sent out, may contain arrays
;; that were in to-acknowledge-arrays but queued
;; again for resending
to-flush-arrays
]
IArrayBuffer
(queue [this string]
(let [next-array-id (inc array-id)]
(ArrayBuffer. next-array-id
last-acknowledged-id
to-acknowledge-arrays
(conj to-flush-arrays [next-array-id string]))))
;; id may cause the following splits:
;; normal case:
;; ack-arrs <id> flush-arrs
;; client is slow case:
;; ack-arrs <id> ack-arrs flush-arrs
;; after arrays have been requeued:
;; ack-arrs flush-arrs <id> flush-arrs
;; everything before id can be discarded, everything after id
;; becomes new flush-arrs and is resend
(acknowledge-id [this id]
(ArrayBuffer. array-id
id
clojure.lang.PersistentQueue/EMPTY
(into (drop-queue to-acknowledge-arrays id)
(drop-queue to-flush-arrays id))))
;; return [seq-to-flush-array next-array-buffer] or nil if
;; to-flush-arrays is empty
(to-flush [this]
(when-let [to-flush (seq to-flush-arrays)]
[to-flush (ArrayBuffer. array-id
last-acknowledged-id
(into to-acknowledge-arrays
(remove (fn [[id string]]
(= string noop-string))
to-flush))
clojure.lang.PersistentQueue/EMPTY)]))
(last-acknowledged-id [this]
last-acknowledged-id)
;; the sum of all the data that is still to be send
(outstanding-bytes [this]
(reduce + 0 (map (comp count second) to-flush-arrays))))
;; {sessionId -> (agent session)}
(def sessions (atom {}))
;; All methods meant to be fn send to an agent, therefor all need to return a Session
(defprotocol ISession
;; a session spans multiple connections, the connections for the
;; backward channel is the backchannel of a session
(clear-back-channel [this])
(set-back-channel [this
;; respond is a wrapper of the continuation
respond
request])
;; messages sent from server to client are arrays
;; the client acknowledges received arrays when creating a new backwardchannel
(acknowledge-arrays [this array-ids])
(queue-string [this string])
;; heartbeat is a timer to send noop over the backward channel
(clear-heartbeat [this])
(refresh-heartbeat [this])
;; after a backward channel closes the session is kept alive, so
;; the client can reconnect. If there is no reconnect before
;; session-timeout the session is closed
(clear-session-timeout [this])
(refresh-session-timeout [this])
;; try to send data to the client over the backchannel.
;; if there is no backchannel, then nothing happens
(flush-buffer [this])
;; after close this session cannot be reconnected to.
;; removes session for sessions
(close [this message]))
(defrecord BackChannel [;; respond wraps the continuation, which is
;; the actual connection of the backward
;; channel to the client
respond
;; when true use streaming
chunk
;; this is used for diagnostic purposes by the client
bytes-sent])
(defrecord Session [;; must be unique
id
;; {:address
;; :headers
;; :app-version
;; :heartbeat-interval
;; :session-timeout-interval
;; :data-threshold
;;}
details
;; back-channel might be nil, as a session spans
;; multiple connections
back-channel
;; ArrayBuffer
array-buffer
;; ScheduleTask or nil
heartbeat-timeout
;; ScheduleTask or nil
;; when the backchannel is closed from this
;; session, the session is only removes when this
;; timer expires during this time the client can
;; reconnect to its session
session-timeout]
ISession
(clear-back-channel [this]
(try
(when back-channel
(write-end (:respond back-channel)))
(catch Exception e
nil ;; close back channel regardless
))
(-> this
clear-heartbeat
(assoc :back-channel nil)
refresh-session-timeout))
(set-back-channel [this respond req]
(let [bc (BackChannel. respond
;; can we stream responses
;; back?
;; CI is determined client
;; side with /test
(= (get-in req [:query-params "CI"]) "0")
;; no bytes sent yet
0)]
(-> this
clear-back-channel
;; clear-back-channel sets the session-timeout
;; here we know the session is alive and
;; well due to this new backchannel
clear-session-timeout
(assoc :back-channel bc)
refresh-heartbeat
;; try to send any data that was buffered
;; while there was no backchannel
flush-buffer)))
(clear-heartbeat [this]
(when heartbeat-timeout
(.cancel heartbeat-timeout
false ;; do not interrupt running tasks
))
(assoc this :heartbeat-timeout nil))
(refresh-heartbeat [this]
(-> this
clear-heartbeat
(assoc :heartbeat-timeout
;; *agent* not bound when executed later
;; through schedule, therefor passed explicitly
(let [session-agent *agent*]
(schedule (fn []
(send-off session-agent #(-> %
(queue-string noop-string)
flush-buffer)))
(:heartbeat-interval details))))))
(clear-session-timeout [this]
(when session-timeout
(.cancel session-timeout
false ;; do not interrupt running tasks
))
(assoc this :session-timeout nil))
(refresh-session-timeout [this]
(-> this
clear-session-timeout
(assoc :session-timeout
(let [session-agent *agent*]
(schedule (fn []
(send-off session-agent close "Timed out"))
(:session-timeout-interval details))))))
(queue-string [this string]
(update-in this [:array-buffer] queue string))
(acknowledge-arrays [this array-id]
(let [array-id (Long/parseLong array-id)]
(update-in this [:array-buffer] acknowledge-id array-id)))
;; tries to do the actual writing to the client
;; @todo the composition is a bit awkward in this method due to the
;; try catch and if mix
(flush-buffer [this]
(if-not back-channel
this ;; nothing to do when there's no connection
;; only flush unacknowledged arrays
(if-let [[to-flush next-array-buffer] (to-flush array-buffer)]
(try
;; buffer contains [[1 json-str] ...] can't use
;; json-str which will double escape the json
(let [data (str "["
(str/join "," (map (fn [[n d]] (str "[" n "," d "]")) to-flush))
"]")]
;; write throws exception when the connection is closed
(write (:respond back-channel) data))
;; size is an approximation
(let [this (let [size (reduce + 0 (map count (map second to-flush)))]
(-> this
(assoc :array-buffer next-array-buffer)
(update-in [:back-channel :bytes-sent] + size)))
;; clear-back-channel closes the back
;; channel when the channel does not
;; support streaming or when a large
;; amount of data has been sent
this (if (or (not (get-in this [:back-channel :chunk]))
(< (:data-threshold details) (get-in this [:back-channel :bytes-sent])))
(clear-back-channel this)
this)]
;; this sending of data keeps the connection alive
;; make a new heartbeat
(refresh-heartbeat this))
(catch Exception e
;; when write failed
;; non delivered arrays are still in buffer
(clear-back-channel this)
))
this ;; do nothing if buffer is empty
)))
;; closes the session and removes it from sessions
(close [this message]
(-> this
clear-back-channel
clear-session-timeout
;; the heartbeat timeout is cancelled by clear-back-channel
)
(swap! sessions dissoc id)
(notify-listeners id :close message)
nil ;; the agent will no longer wrap a session
))
;; creates a session agent wrapping session data and
;; adds the session to sessions
(defn create-session-agent [req options]
(let [{initial-rid "RID" ;; identifier for forward channel
app-version "CVER" ;; client can specify a custom app-version
old-session-id "OSID"
old-array-id "OAID"} (:query-params req)]
;; when a client specifies and old session id then that old one
;; needs to be removed
(when-let [old-session-agent (@sessions old-session-id)]
(send-off old-session-agent #(-> (if old-array-id
(acknowledge-arrays % old-array-id)
%)
(close "Reconnected"))))
(let [id (uuid)
details {:address (:remote-addr req)
:headers (:headers req)
:app-version app-version
:heartbeat-interval (:keep-alive-interval options)
:session-timeout-interval (:session-timeout-interval options)
:data-threshold (:data-threshold options)}
session (-> (Session. id
details
nil ;; backchannel
(ArrayBuffer.
0 ;; array-id, 0 is never used by the
;; array-buffer, it is used by the
;; first message with the session id
0 ;; last-acknowledged-id
;; to-acknowledge-arrays
clojure.lang.PersistentQueue/EMPTY
;; to-flush-arrays
clojure.lang.PersistentQueue/EMPTY)
nil ;; heartbeat-timeout
nil ;; session-timeout
)
;; this first session-timeout is for the case
;; when the client never connects with a backchannel
refresh-session-timeout)
session-agent (agent session)]
(swap! sessions assoc id session-agent)
(when-let [notify (:on-session options)]
(notify id req))
session-agent)))
(defn session-status [session]
(let [has-back-channel (if (:back-channel session) 1 0)
array-buffer (:array-buffer session)]
[has-back-channel (last-acknowledged-id array-buffer) (outstanding-bytes array-buffer)]))
;; convience function to send data to a session
;; the data will be queued until there is a backchannel to send it
;; over
(defn send-string [session-id string]
(when-let [session-agent (get @sessions session-id)]
(send-off session-agent #(-> %
(queue-string string)
flush-buffer))))
(defn send-map [session-id map]
(send-string session-id (json/json-str map)))
;; wrap the respond function from :reactor with the proper
;; responsewrapper for either IE or other clients
(defn wrap-continuation-writers [handler options]
(fn [req]
(let [res (handler req)]
(if (:async res)
(let [reactor (:reactor res)
type (get-in req [:query-params "TYPE"])]
(assoc res :reactor
(fn [respond]
(reactor (let [headers (assoc (:headers options)
"Transfer-Encoding" "chunked")]
(if (= type "html")
(let [domain (get-in req [:query-params "DOMAIN"])]
;; last two false are the padding
;; sent flags
(IEWriter. respond headers domain false false))
(XHRWriter. respond headers)))))))
res ;; do not touch responses without :async
))))
;; test channel is used to determine which host to connect to
;; and if the connection can support streaming
(defn handle-test-channel [req options]
(if-not (= "8" (get-in req [:query-params "VER"]))
(error-response 400 "Version 8 required")
;; phase 1
;; client requests [random host-prefix or
;; nil,blockedPrefix]
;; blockedPrefix not supported, always nil
(if (= (get-in req [:query-params "MODE"]) "init")
(let [host-prefix (when-let [prefixes (seq (:host-prefixes options))]
(rand-nth prefixes))]
{:status 200
:headers (assoc (:headers options) "X-Accept" "application/json; application/x-www-form-urlencoded")
:body (json/json-str [host-prefix,nil])})
;; else phase 2 for get /test
;; client checks if connection is buffered
;; send 11111, wait 2 seconds, send 2
;; if client gets two chunks, then there is no buffering
;; proxy in the way
{:async :http
:reactor
(fn [respond]
(write-head respond)
(write-raw respond "11111")
(schedule #(do (write-raw respond "2")
(write-end respond))
2))})))
;; POST req client -> server is a forward channel
;; session might be nil, when this is the first POST by client
(defn handle-forward-channel [req session-agent options]
(let [[session-agent is-new-session] (if session-agent
[session-agent false]
[(create-session-agent req options) true])
;; maps contains whatever the messages to the server
maps (get-maps req)]
(if is-new-session
;; first post after a new session is a message with the session
;; details.
;; response is first array sent for this session:
;; [[0,["c", session-id, host-prefix, version (always 8)]]]
;; send as json for XHR and IE
(let [session @session-agent
session-id (:id session)
;; @todo extract the used host-prefix from the request if any
host-prefix nil]
{:status 200
:headers (assoc (:headers options) "Content-Type" "application/javascript")
:body
(size-json-str (json/json-str [[0,["c", session-id, host-prefix, 8]]]))})
;; For existing sessions:
;; Forward sent data by client to listeners
;; reply with
;; [backchannelPresent,lastPostResponseArrayId_,numOutstandingBackchannelBytes]
;; backchannelPresent = 0 for false, 1 for true
;; send as json for XHR and IE
(do
(doseq [map maps]
(notify-listeners (:id @session-agent) :map map))
(let [status (session-status @session-agent)]
{:status 200
:headers (:headers options)
:body (size-json-str (json/json-str status))})))))
;; GET req server->client is a backwardchannel opened by client
(defn handle-backward-channel [req session-agent options]
(let [type (get-in req [:query-params "TYPE"])]
(cond
(#{"xmlhttp" "html"} type)
;; @todo check that query RID is "rpc"
{:async :http
:reactor
(fn [respond]
(write-head respond)
(send-off session-agent set-back-channel respond req))}
(= type "terminate")
;; this is a request made in an img tag
(do ;;end session
(when session-agent
(send-off session-agent close "Disconnected"))
{:status 200
:headers (:headers options)
:body ""}
))))
;; get to /<base>/bind is client->server msg
;; post to /<base>/bind is initiate server->client channel
(defn handle-bind-channel [req options]
(let [SID (get-in req [:query-params "SID"])
;; session-agent might be nil, then it will be created by
;; handle-forward-channel
session-agent (@sessions SID)]
(if (and SID
(not session-agent))
;; SID refers to an already created session, which therefore
;; must exist
(error-response 400 "Unknown SID")
(do
;; client can tell the server which array it has seen
;; up to including AID can be removed from the buffer
(when session-agent
(when-let [AID (get-in req [:query-params "AID"])]
(send-off session-agent acknowledge-arrays AID)))
(condp = (:request-method req)
:post (handle-forward-channel req session-agent options)
:get (handle-backward-channel req session-agent options))))))
;; see default-options for describtion of options
(defn wrap-browserchannel [handler & [options]]
(let [options (merge default-options options)
base (str (:base options))]
(-> (fn [req]
(let [uri (:uri req)
method (:request-method req)]
(cond
(and (.startsWith uri (str base "/test"))
(= method :get))
(handle-test-channel req options)
(.startsWith uri (str base "/bind"))
(handle-bind-channel req options)
:else (handler req))))
(wrap-continuation-writers options)
params/wrap-params
)))
| true | (ns net.thegeez.browserchannel
"BrowserChannel server implementation in Clojure."
(:require [ring.middleware.params :as params]
[ring.util.codec :as codec]
[clojure.data.json :as json]
[clojure.string :as str]
[net.thegeez.async-adapter :as async-adapter])
(:import [java.util.concurrent ScheduledExecutorService Executors TimeUnit]))
;; @todo: out of order acks and maps
;; @todo use a more specific Exception for failing writes, which
;; indicate closed connection
;; @todo SSL in jetty-async-adapter
;; @todo session-timeout should deduct waiting time for the failed
;; sent heartbeat?
(def default-options
{;; a.example, b.example => ["a","b"]
:host-prefixes []
;; straight from google
:headers {"Content-Type" "text/plain"
"Cache-Control" "no-cache, no-store, max-age=0, must-revalidate"
"Pragma" "no-cache"
"Expires" "Fri, 01 Jan 1990 00:00:00 GMT"
"X-Content-Type-Options" "nosniff"
}
:base "/channel" ;; root for /test and /bind urls
:keep-alive-interval 10 ;; seconds, keep less than session-time-out
:session-timeout-interval 15 ;; seconds
;; after this number of bytes a
;; backchannel will always be closed
:data-threshold (* 10 1024)
})
(def noop-string "[\"noop\"]")
;; almost all special cases are for making this work with IE
(def ie-headers
{"Content-Type" "text/html"})
;; appended to first write to ie to prevent whole page buffering
(def ie-stream-padding "7cca69475363026330a0d99468e88d23ce95e222591126443015f5f462d9a177186c8701fb45a6ffee0dafPI:KEY:<KEY>END_PI")
;;;;; Utils
;; to create session ids
(defn uuid [] (str (java.util.UUID/randomUUID)))
(def scheduler (Executors/newScheduledThreadPool 1))
;; scheduling a task returns a ScheduledFuture, which can be stopped
;; with (.cancel task false) false says not to interrupt running tasks
(defn schedule [f secs]
(.schedule scheduler f secs TimeUnit/SECONDS))
;; json responses are sent as "size-of-response\njson-response"
(defn size-json-str [json]
(let [size (alength (.getBytes json "UTF-8"))]
(str size "\n" json)))
;; make sure the root URI for channels starts with a / for route matching
(defn standard-base [s]
(let [wofirst (if (= \/ (first s))
(apply str (rest s))
s)
wolast (if (= \/ (last wofirst))
(apply str (butlast wofirst))
wofirst)]
(str "/" wolast)))
;; @todo to test file
(assert (= (repeat 4 "/foo")
(map standard-base ["foo" "/foo" "foo/" "/foo"])))
;; type preserving drop upto for queueus
(defn drop-queue [queue id]
(let [head (peek queue)]
(if-not head
queue
(if (< id (first head))
queue
(recur (pop queue) id)))))
(defn transform-url-data [data]
(let [ofs (get data "ofs" "0")
pieces (dissoc data "count" "ofs")]
{:ofs (Long/parseLong ofs)
:maps (->> (for [[k v] pieces]
(let [[_ n k] (re-find #"req(\d+)_(\w+)" k)]
[n {k v}]))
(partition-by first)
(map #(into {} (map second %))))}))
(assert (= {:ofs 0 :maps [{"x" "3" "y" "10"} {"abc" "def"}]}
(transform-url-data {"count" "2"
"ofs" "0"
"req0_x" "3"
"req0_y" "10"
"req1_abc" "def"})))
;; maps are URL Encoded
;;;; URL Encoded data:
;;{ count: '2',
;; ofs: '0',
;; req0_x: '3',
;; req0_y: '10',
;; req1_abc: 'def'
;;}
;;as :form-params in req:
;;{"count" "2"
;; "ofs" "0"
;; "req0_x" "3"
;; "req0_y" "10"
;; "req1_abc" "def"}
;; =>
;;{:ofs 0 :maps [{"x" "3" "y" "10"},{"abc": "def"}]}
(defn get-maps [req]
(let [data (:form-params req)]
(when-not (zero? (count data))
;; number of entries in form-params,
;; not (get "count" (:form-params req))
;; @todo "count" is currently not used to verify the number of
;; parsed maps
(:maps (transform-url-data data)))))
;; rather crude but straight from google
(defn error-response [status-code message]
{:status status-code
:body (str "<html><body><h1>" message "</h1></body></html>")})
;;;;;; end of utils
;;;; listeners
;; @todo clean this up, perhaps store listeners in the session?
;; @todo replace with lamina?
;; sessionId -> :event -> [call back]
;; event: :map | :close
(def listeners-agent (agent {}))
(defn add-listener [session-id event-key f]
(send-off listeners-agent
update-in [session-id event-key] #(conj (or % []) f)))
(defn notify-listeners [session-id event-key & data]
(send-off listeners-agent
(fn [listeners]
(doseq [callback (get-in listeners [session-id event-key])]
(apply callback data))
listeners)))
;; end of listeners
;; Wrapper around writers on continuations
;; the write methods raise an Exception with the wrapped response in closed
;; @todo use a more specific Exception
(defprotocol IResponseWrapper
(write-head [this])
(write [this data])
(write-raw [this data])
(write-end [this]))
;; for writing on backchannel to non-IE clients
(deftype XHRWriter [;; respond calls functions on the continuation
respond
headers]
IResponseWrapper
(write-head [this]
(async-adapter/head respond 200 headers))
(write [this data]
(write-raw this (size-json-str data)))
(write-raw [this data]
(async-adapter/write-chunk respond data))
(write-end [this]
(async-adapter/close respond)))
;; for writing on backchannels to IE clients
(deftype IEWriter [;; respond calls functions on the continuation
respond
headers
;; DOMAIN value from query string
domain
;; first write requires padding,
;; padding-sent is a flag for the first time
^{:volatile-mutable true} write-padding-sent
;; likewise for write raw, used during test phase
^{:volatile-mutable true} write-raw-padding-sent]
IResponseWrapper
(write-head [this]
(async-adapter/head respond 200 (merge headers ie-headers))
(async-adapter/write-chunk respond "<html><body>\n")
(when (seq domain)
(async-adapter/write-chunk respond (str "<script>try{document.domain=\"" (pr-str (json/json-str domain)) "\";}catch(e){}</script>\n"))))
(write [this data]
(async-adapter/write-chunk respond (str "<script>try {parent.m(" (pr-str data) ")} catch(e) {}</script>\n"))
(when-not write-padding-sent
(async-adapter/write-chunk respond ie-stream-padding)
(set! write-padding-sent true)))
(write-raw [this data]
(async-adapter/write-chunk respond (str "<script>try {parent.m(" (pr-str data) ")} catch(e) {}</script>\n"))
(when-not write-raw-padding-sent
(async-adapter/write-chunk respond ie-stream-padding)
(set! write-raw-padding-sent true)))
(write-end [this]
(async-adapter/write-chunk respond "<script>try {parent.d(); }catch (e){}</script>\n")
(async-adapter/close respond)))
;;ArrayBuffer
;;buffer of [[id_lowest data] ... [id_highest data]]
(defprotocol IArrayBuffer
(queue [this string])
(acknowledge-id [this id])
(to-flush [this])
(last-acknowledged-id [this])
(outstanding-bytes [this])
)
(deftype ArrayBuffer [;; id of the last array that is conj'ed, can't
;; always be derived because flush buffer might
;; be empty
array-id
;; needed for session status
last-acknowledged-id
;; array that have been flushed, but not yet
;; acknowledged, does not contain noop messages
to-acknowledge-arrays
;; arrays to be sent out, may contain arrays
;; that were in to-acknowledge-arrays but queued
;; again for resending
to-flush-arrays
]
IArrayBuffer
(queue [this string]
(let [next-array-id (inc array-id)]
(ArrayBuffer. next-array-id
last-acknowledged-id
to-acknowledge-arrays
(conj to-flush-arrays [next-array-id string]))))
;; id may cause the following splits:
;; normal case:
;; ack-arrs <id> flush-arrs
;; client is slow case:
;; ack-arrs <id> ack-arrs flush-arrs
;; after arrays have been requeued:
;; ack-arrs flush-arrs <id> flush-arrs
;; everything before id can be discarded, everything after id
;; becomes new flush-arrs and is resend
(acknowledge-id [this id]
(ArrayBuffer. array-id
id
clojure.lang.PersistentQueue/EMPTY
(into (drop-queue to-acknowledge-arrays id)
(drop-queue to-flush-arrays id))))
;; return [seq-to-flush-array next-array-buffer] or nil if
;; to-flush-arrays is empty
(to-flush [this]
(when-let [to-flush (seq to-flush-arrays)]
[to-flush (ArrayBuffer. array-id
last-acknowledged-id
(into to-acknowledge-arrays
(remove (fn [[id string]]
(= string noop-string))
to-flush))
clojure.lang.PersistentQueue/EMPTY)]))
(last-acknowledged-id [this]
last-acknowledged-id)
;; the sum of all the data that is still to be send
(outstanding-bytes [this]
(reduce + 0 (map (comp count second) to-flush-arrays))))
;; {sessionId -> (agent session)}
(def sessions (atom {}))
;; All methods meant to be fn send to an agent, therefor all need to return a Session
(defprotocol ISession
;; a session spans multiple connections, the connections for the
;; backward channel is the backchannel of a session
(clear-back-channel [this])
(set-back-channel [this
;; respond is a wrapper of the continuation
respond
request])
;; messages sent from server to client are arrays
;; the client acknowledges received arrays when creating a new backwardchannel
(acknowledge-arrays [this array-ids])
(queue-string [this string])
;; heartbeat is a timer to send noop over the backward channel
(clear-heartbeat [this])
(refresh-heartbeat [this])
;; after a backward channel closes the session is kept alive, so
;; the client can reconnect. If there is no reconnect before
;; session-timeout the session is closed
(clear-session-timeout [this])
(refresh-session-timeout [this])
;; try to send data to the client over the backchannel.
;; if there is no backchannel, then nothing happens
(flush-buffer [this])
;; after close this session cannot be reconnected to.
;; removes session for sessions
(close [this message]))
(defrecord BackChannel [;; respond wraps the continuation, which is
;; the actual connection of the backward
;; channel to the client
respond
;; when true use streaming
chunk
;; this is used for diagnostic purposes by the client
bytes-sent])
(defrecord Session [;; must be unique
id
;; {:address
;; :headers
;; :app-version
;; :heartbeat-interval
;; :session-timeout-interval
;; :data-threshold
;;}
details
;; back-channel might be nil, as a session spans
;; multiple connections
back-channel
;; ArrayBuffer
array-buffer
;; ScheduleTask or nil
heartbeat-timeout
;; ScheduleTask or nil
;; when the backchannel is closed from this
;; session, the session is only removes when this
;; timer expires during this time the client can
;; reconnect to its session
session-timeout]
ISession
(clear-back-channel [this]
(try
(when back-channel
(write-end (:respond back-channel)))
(catch Exception e
nil ;; close back channel regardless
))
(-> this
clear-heartbeat
(assoc :back-channel nil)
refresh-session-timeout))
(set-back-channel [this respond req]
(let [bc (BackChannel. respond
;; can we stream responses
;; back?
;; CI is determined client
;; side with /test
(= (get-in req [:query-params "CI"]) "0")
;; no bytes sent yet
0)]
(-> this
clear-back-channel
;; clear-back-channel sets the session-timeout
;; here we know the session is alive and
;; well due to this new backchannel
clear-session-timeout
(assoc :back-channel bc)
refresh-heartbeat
;; try to send any data that was buffered
;; while there was no backchannel
flush-buffer)))
(clear-heartbeat [this]
(when heartbeat-timeout
(.cancel heartbeat-timeout
false ;; do not interrupt running tasks
))
(assoc this :heartbeat-timeout nil))
(refresh-heartbeat [this]
(-> this
clear-heartbeat
(assoc :heartbeat-timeout
;; *agent* not bound when executed later
;; through schedule, therefor passed explicitly
(let [session-agent *agent*]
(schedule (fn []
(send-off session-agent #(-> %
(queue-string noop-string)
flush-buffer)))
(:heartbeat-interval details))))))
(clear-session-timeout [this]
(when session-timeout
(.cancel session-timeout
false ;; do not interrupt running tasks
))
(assoc this :session-timeout nil))
(refresh-session-timeout [this]
(-> this
clear-session-timeout
(assoc :session-timeout
(let [session-agent *agent*]
(schedule (fn []
(send-off session-agent close "Timed out"))
(:session-timeout-interval details))))))
(queue-string [this string]
(update-in this [:array-buffer] queue string))
(acknowledge-arrays [this array-id]
(let [array-id (Long/parseLong array-id)]
(update-in this [:array-buffer] acknowledge-id array-id)))
;; tries to do the actual writing to the client
;; @todo the composition is a bit awkward in this method due to the
;; try catch and if mix
(flush-buffer [this]
(if-not back-channel
this ;; nothing to do when there's no connection
;; only flush unacknowledged arrays
(if-let [[to-flush next-array-buffer] (to-flush array-buffer)]
(try
;; buffer contains [[1 json-str] ...] can't use
;; json-str which will double escape the json
(let [data (str "["
(str/join "," (map (fn [[n d]] (str "[" n "," d "]")) to-flush))
"]")]
;; write throws exception when the connection is closed
(write (:respond back-channel) data))
;; size is an approximation
(let [this (let [size (reduce + 0 (map count (map second to-flush)))]
(-> this
(assoc :array-buffer next-array-buffer)
(update-in [:back-channel :bytes-sent] + size)))
;; clear-back-channel closes the back
;; channel when the channel does not
;; support streaming or when a large
;; amount of data has been sent
this (if (or (not (get-in this [:back-channel :chunk]))
(< (:data-threshold details) (get-in this [:back-channel :bytes-sent])))
(clear-back-channel this)
this)]
;; this sending of data keeps the connection alive
;; make a new heartbeat
(refresh-heartbeat this))
(catch Exception e
;; when write failed
;; non delivered arrays are still in buffer
(clear-back-channel this)
))
this ;; do nothing if buffer is empty
)))
;; closes the session and removes it from sessions
(close [this message]
(-> this
clear-back-channel
clear-session-timeout
;; the heartbeat timeout is cancelled by clear-back-channel
)
(swap! sessions dissoc id)
(notify-listeners id :close message)
nil ;; the agent will no longer wrap a session
))
;; creates a session agent wrapping session data and
;; adds the session to sessions
(defn create-session-agent [req options]
(let [{initial-rid "RID" ;; identifier for forward channel
app-version "CVER" ;; client can specify a custom app-version
old-session-id "OSID"
old-array-id "OAID"} (:query-params req)]
;; when a client specifies and old session id then that old one
;; needs to be removed
(when-let [old-session-agent (@sessions old-session-id)]
(send-off old-session-agent #(-> (if old-array-id
(acknowledge-arrays % old-array-id)
%)
(close "Reconnected"))))
(let [id (uuid)
details {:address (:remote-addr req)
:headers (:headers req)
:app-version app-version
:heartbeat-interval (:keep-alive-interval options)
:session-timeout-interval (:session-timeout-interval options)
:data-threshold (:data-threshold options)}
session (-> (Session. id
details
nil ;; backchannel
(ArrayBuffer.
0 ;; array-id, 0 is never used by the
;; array-buffer, it is used by the
;; first message with the session id
0 ;; last-acknowledged-id
;; to-acknowledge-arrays
clojure.lang.PersistentQueue/EMPTY
;; to-flush-arrays
clojure.lang.PersistentQueue/EMPTY)
nil ;; heartbeat-timeout
nil ;; session-timeout
)
;; this first session-timeout is for the case
;; when the client never connects with a backchannel
refresh-session-timeout)
session-agent (agent session)]
(swap! sessions assoc id session-agent)
(when-let [notify (:on-session options)]
(notify id req))
session-agent)))
(defn session-status [session]
(let [has-back-channel (if (:back-channel session) 1 0)
array-buffer (:array-buffer session)]
[has-back-channel (last-acknowledged-id array-buffer) (outstanding-bytes array-buffer)]))
;; convience function to send data to a session
;; the data will be queued until there is a backchannel to send it
;; over
(defn send-string [session-id string]
(when-let [session-agent (get @sessions session-id)]
(send-off session-agent #(-> %
(queue-string string)
flush-buffer))))
(defn send-map [session-id map]
(send-string session-id (json/json-str map)))
;; wrap the respond function from :reactor with the proper
;; responsewrapper for either IE or other clients
(defn wrap-continuation-writers [handler options]
(fn [req]
(let [res (handler req)]
(if (:async res)
(let [reactor (:reactor res)
type (get-in req [:query-params "TYPE"])]
(assoc res :reactor
(fn [respond]
(reactor (let [headers (assoc (:headers options)
"Transfer-Encoding" "chunked")]
(if (= type "html")
(let [domain (get-in req [:query-params "DOMAIN"])]
;; last two false are the padding
;; sent flags
(IEWriter. respond headers domain false false))
(XHRWriter. respond headers)))))))
res ;; do not touch responses without :async
))))
;; test channel is used to determine which host to connect to
;; and if the connection can support streaming
(defn handle-test-channel [req options]
(if-not (= "8" (get-in req [:query-params "VER"]))
(error-response 400 "Version 8 required")
;; phase 1
;; client requests [random host-prefix or
;; nil,blockedPrefix]
;; blockedPrefix not supported, always nil
(if (= (get-in req [:query-params "MODE"]) "init")
(let [host-prefix (when-let [prefixes (seq (:host-prefixes options))]
(rand-nth prefixes))]
{:status 200
:headers (assoc (:headers options) "X-Accept" "application/json; application/x-www-form-urlencoded")
:body (json/json-str [host-prefix,nil])})
;; else phase 2 for get /test
;; client checks if connection is buffered
;; send 11111, wait 2 seconds, send 2
;; if client gets two chunks, then there is no buffering
;; proxy in the way
{:async :http
:reactor
(fn [respond]
(write-head respond)
(write-raw respond "11111")
(schedule #(do (write-raw respond "2")
(write-end respond))
2))})))
;; POST req client -> server is a forward channel
;; session might be nil, when this is the first POST by client
(defn handle-forward-channel [req session-agent options]
(let [[session-agent is-new-session] (if session-agent
[session-agent false]
[(create-session-agent req options) true])
;; maps contains whatever the messages to the server
maps (get-maps req)]
(if is-new-session
;; first post after a new session is a message with the session
;; details.
;; response is first array sent for this session:
;; [[0,["c", session-id, host-prefix, version (always 8)]]]
;; send as json for XHR and IE
(let [session @session-agent
session-id (:id session)
;; @todo extract the used host-prefix from the request if any
host-prefix nil]
{:status 200
:headers (assoc (:headers options) "Content-Type" "application/javascript")
:body
(size-json-str (json/json-str [[0,["c", session-id, host-prefix, 8]]]))})
;; For existing sessions:
;; Forward sent data by client to listeners
;; reply with
;; [backchannelPresent,lastPostResponseArrayId_,numOutstandingBackchannelBytes]
;; backchannelPresent = 0 for false, 1 for true
;; send as json for XHR and IE
(do
(doseq [map maps]
(notify-listeners (:id @session-agent) :map map))
(let [status (session-status @session-agent)]
{:status 200
:headers (:headers options)
:body (size-json-str (json/json-str status))})))))
;; GET req server->client is a backwardchannel opened by client
(defn handle-backward-channel [req session-agent options]
(let [type (get-in req [:query-params "TYPE"])]
(cond
(#{"xmlhttp" "html"} type)
;; @todo check that query RID is "rpc"
{:async :http
:reactor
(fn [respond]
(write-head respond)
(send-off session-agent set-back-channel respond req))}
(= type "terminate")
;; this is a request made in an img tag
(do ;;end session
(when session-agent
(send-off session-agent close "Disconnected"))
{:status 200
:headers (:headers options)
:body ""}
))))
;; get to /<base>/bind is client->server msg
;; post to /<base>/bind is initiate server->client channel
(defn handle-bind-channel [req options]
(let [SID (get-in req [:query-params "SID"])
;; session-agent might be nil, then it will be created by
;; handle-forward-channel
session-agent (@sessions SID)]
(if (and SID
(not session-agent))
;; SID refers to an already created session, which therefore
;; must exist
(error-response 400 "Unknown SID")
(do
;; client can tell the server which array it has seen
;; up to including AID can be removed from the buffer
(when session-agent
(when-let [AID (get-in req [:query-params "AID"])]
(send-off session-agent acknowledge-arrays AID)))
(condp = (:request-method req)
:post (handle-forward-channel req session-agent options)
:get (handle-backward-channel req session-agent options))))))
;; see default-options for describtion of options
(defn wrap-browserchannel [handler & [options]]
(let [options (merge default-options options)
base (str (:base options))]
(-> (fn [req]
(let [uri (:uri req)
method (:request-method req)]
(cond
(and (.startsWith uri (str base "/test"))
(= method :get))
(handle-test-channel req options)
(.startsWith uri (str base "/bind"))
(handle-bind-channel req options)
:else (handler req))))
(wrap-continuation-writers options)
params/wrap-params
)))
|
[
{
"context": "mote-type :hornetq-wildfly,\n :username \"testuser\", :password \"testuser\"})\n\n(use-fixtures :once\n (",
"end": 1160,
"score": 0.9994636178016663,
"start": 1152,
"tag": "USERNAME",
"value": "testuser"
},
{
"context": "dfly,\n :username \"testuser\", :password \"testuser\"})\n\n(use-fixtures :once\n (compose-fixtures\n (",
"end": 1182,
"score": 0.9991600513458252,
"start": 1174,
"tag": "PASSWORD",
"value": "testuser"
}
] | integration-tests/test-clustering/integs/cluster_test.clj | kfowler/immutant | 0 | ;; Copyright 2008-2014 Red Hat, Inc, and individual contributors.
;;
;; This is free software; you can redistribute it and/or modify it
;; under the terms of the GNU Lesser General Public License as
;; published by the Free Software Foundation; either version 2.1 of
;; the License, or (at your option) any later version.
;;
;; This software is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this software; if not, write to the Free
;; Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
;; 02110-1301 USA, or see the FSF site: http://www.fsf.org.
(ns integs.cluster-test
(:require [fntest.core :refer :all]
[clojure.test :refer :all]
[integs.cluster-help :refer (get-as-data stop start http-port mark)]
[immutant.messaging :as msg]))
(def opts {:host "localhost", :remote-type :hornetq-wildfly,
:username "testuser", :password "testuser"})
(use-fixtures :once
(compose-fixtures
(partial with-jboss #{:isolated :offset :domain})
(with-deployment "ROOT.war" "." :profiles [:cluster :dev :test])))
(defmacro marktest [t & body]
`(deftest ~t
(let [v# (-> ~t var meta :name)]
(mark "START" v#)
~@body
(mark "FINISH" v#))))
(marktest bouncing-basic-web
(is (-> (get-as-data "/cache" "server-one") :count number?))
(is (-> (get-as-data "/cache" "server-two") :count number?))
(stop "server-one")
(is (thrown? java.net.ConnectException (get-as-data "/cache" "server-one")))
(start "server-one")
(is (-> (get-as-data "/cache" "server-one") :count number? )))
(marktest session-replication
(is (= 0 (get-as-data "/counter" "server-one")))
(is (= 1 (get-as-data "/counter" "server-two")))
(is (= 2 (get-as-data "/counter" "server-one")))
(stop "server-one")
(is (= 3 (get-as-data "/counter" "server-two")))
(start "server-one")
(is (= 4 (get-as-data "/counter" "server-one"))))
(marktest failover
(let [responses (atom [])
host1 (with-open [c (msg/context (assoc opts :port (http-port "server-one")))]
(deref (msg/request (msg/queue "/queue/cache" :context c) :whatever)
60000 nil))
host2 (-> #{"server-one" "server-two"} (disj host1) first)
response (fn [s] (get-as-data "/cache" s))]
(mark (swap! responses conj (response host1)))
(stop host1)
(mark (swap! responses conj (response host2)))
(is (= host2 (:node (last @responses))))
(start host1)
(mark (swap! responses conj (response host2)))
(is (= host2 (:node (last @responses))))
(stop host2)
(mark (swap! responses conj (response host1)))
(is (= host1 (:node (last @responses))))
(start host2)
;; assert the job and distributed cache kept the count ascending
;; across restarts
(is (apply < (map :count @responses)))))
(marktest publish-here-receive-there
(with-open [ctx1 (msg/context (assoc opts :port (http-port "server-one")))
ctx2 (msg/context (assoc opts :port (http-port "server-two")))]
(let [q1 (msg/queue "/queue/cluster" :context ctx1)
q2 (msg/queue "/queue/cluster" :context ctx2)
received (atom #{})
p (promise)
c 100]
(msg/listen q2 (fn [m]
(mark "GOT:" m)
(swap! received conj m)
(when (= c (count @received))
(deliver p :done))))
(dotimes [i c]
(msg/publish q1 i))
(deref p 60000 nil)
(is (= (set (range c)) @received)))))
| 85713 | ;; Copyright 2008-2014 Red Hat, Inc, and individual contributors.
;;
;; This is free software; you can redistribute it and/or modify it
;; under the terms of the GNU Lesser General Public License as
;; published by the Free Software Foundation; either version 2.1 of
;; the License, or (at your option) any later version.
;;
;; This software is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this software; if not, write to the Free
;; Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
;; 02110-1301 USA, or see the FSF site: http://www.fsf.org.
(ns integs.cluster-test
(:require [fntest.core :refer :all]
[clojure.test :refer :all]
[integs.cluster-help :refer (get-as-data stop start http-port mark)]
[immutant.messaging :as msg]))
(def opts {:host "localhost", :remote-type :hornetq-wildfly,
:username "testuser", :password "<PASSWORD>"})
(use-fixtures :once
(compose-fixtures
(partial with-jboss #{:isolated :offset :domain})
(with-deployment "ROOT.war" "." :profiles [:cluster :dev :test])))
(defmacro marktest [t & body]
`(deftest ~t
(let [v# (-> ~t var meta :name)]
(mark "START" v#)
~@body
(mark "FINISH" v#))))
(marktest bouncing-basic-web
(is (-> (get-as-data "/cache" "server-one") :count number?))
(is (-> (get-as-data "/cache" "server-two") :count number?))
(stop "server-one")
(is (thrown? java.net.ConnectException (get-as-data "/cache" "server-one")))
(start "server-one")
(is (-> (get-as-data "/cache" "server-one") :count number? )))
(marktest session-replication
(is (= 0 (get-as-data "/counter" "server-one")))
(is (= 1 (get-as-data "/counter" "server-two")))
(is (= 2 (get-as-data "/counter" "server-one")))
(stop "server-one")
(is (= 3 (get-as-data "/counter" "server-two")))
(start "server-one")
(is (= 4 (get-as-data "/counter" "server-one"))))
(marktest failover
(let [responses (atom [])
host1 (with-open [c (msg/context (assoc opts :port (http-port "server-one")))]
(deref (msg/request (msg/queue "/queue/cache" :context c) :whatever)
60000 nil))
host2 (-> #{"server-one" "server-two"} (disj host1) first)
response (fn [s] (get-as-data "/cache" s))]
(mark (swap! responses conj (response host1)))
(stop host1)
(mark (swap! responses conj (response host2)))
(is (= host2 (:node (last @responses))))
(start host1)
(mark (swap! responses conj (response host2)))
(is (= host2 (:node (last @responses))))
(stop host2)
(mark (swap! responses conj (response host1)))
(is (= host1 (:node (last @responses))))
(start host2)
;; assert the job and distributed cache kept the count ascending
;; across restarts
(is (apply < (map :count @responses)))))
(marktest publish-here-receive-there
(with-open [ctx1 (msg/context (assoc opts :port (http-port "server-one")))
ctx2 (msg/context (assoc opts :port (http-port "server-two")))]
(let [q1 (msg/queue "/queue/cluster" :context ctx1)
q2 (msg/queue "/queue/cluster" :context ctx2)
received (atom #{})
p (promise)
c 100]
(msg/listen q2 (fn [m]
(mark "GOT:" m)
(swap! received conj m)
(when (= c (count @received))
(deliver p :done))))
(dotimes [i c]
(msg/publish q1 i))
(deref p 60000 nil)
(is (= (set (range c)) @received)))))
| true | ;; Copyright 2008-2014 Red Hat, Inc, and individual contributors.
;;
;; This is free software; you can redistribute it and/or modify it
;; under the terms of the GNU Lesser General Public License as
;; published by the Free Software Foundation; either version 2.1 of
;; the License, or (at your option) any later version.
;;
;; This software is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this software; if not, write to the Free
;; Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
;; 02110-1301 USA, or see the FSF site: http://www.fsf.org.
(ns integs.cluster-test
(:require [fntest.core :refer :all]
[clojure.test :refer :all]
[integs.cluster-help :refer (get-as-data stop start http-port mark)]
[immutant.messaging :as msg]))
(def opts {:host "localhost", :remote-type :hornetq-wildfly,
:username "testuser", :password "PI:PASSWORD:<PASSWORD>END_PI"})
(use-fixtures :once
(compose-fixtures
(partial with-jboss #{:isolated :offset :domain})
(with-deployment "ROOT.war" "." :profiles [:cluster :dev :test])))
(defmacro marktest [t & body]
`(deftest ~t
(let [v# (-> ~t var meta :name)]
(mark "START" v#)
~@body
(mark "FINISH" v#))))
(marktest bouncing-basic-web
(is (-> (get-as-data "/cache" "server-one") :count number?))
(is (-> (get-as-data "/cache" "server-two") :count number?))
(stop "server-one")
(is (thrown? java.net.ConnectException (get-as-data "/cache" "server-one")))
(start "server-one")
(is (-> (get-as-data "/cache" "server-one") :count number? )))
(marktest session-replication
(is (= 0 (get-as-data "/counter" "server-one")))
(is (= 1 (get-as-data "/counter" "server-two")))
(is (= 2 (get-as-data "/counter" "server-one")))
(stop "server-one")
(is (= 3 (get-as-data "/counter" "server-two")))
(start "server-one")
(is (= 4 (get-as-data "/counter" "server-one"))))
(marktest failover
(let [responses (atom [])
host1 (with-open [c (msg/context (assoc opts :port (http-port "server-one")))]
(deref (msg/request (msg/queue "/queue/cache" :context c) :whatever)
60000 nil))
host2 (-> #{"server-one" "server-two"} (disj host1) first)
response (fn [s] (get-as-data "/cache" s))]
(mark (swap! responses conj (response host1)))
(stop host1)
(mark (swap! responses conj (response host2)))
(is (= host2 (:node (last @responses))))
(start host1)
(mark (swap! responses conj (response host2)))
(is (= host2 (:node (last @responses))))
(stop host2)
(mark (swap! responses conj (response host1)))
(is (= host1 (:node (last @responses))))
(start host2)
;; assert the job and distributed cache kept the count ascending
;; across restarts
(is (apply < (map :count @responses)))))
(marktest publish-here-receive-there
(with-open [ctx1 (msg/context (assoc opts :port (http-port "server-one")))
ctx2 (msg/context (assoc opts :port (http-port "server-two")))]
(let [q1 (msg/queue "/queue/cluster" :context ctx1)
q2 (msg/queue "/queue/cluster" :context ctx2)
received (atom #{})
p (promise)
c 100]
(msg/listen q2 (fn [m]
(mark "GOT:" m)
(swap! received conj m)
(when (= c (count @received))
(deliver p :done))))
(dotimes [i c]
(msg/publish q1 i))
(deref p 60000 nil)
(is (= (set (range c)) @received)))))
|
[
{
"context": ";;; Copyright 2019 Mitchell Kember. Subject to the MIT License.\n\n(ns twenty48.game\n ",
"end": 34,
"score": 0.9998916387557983,
"start": 19,
"tag": "NAME",
"value": "Mitchell Kember"
}
] | src/twenty48/game.clj | mk12/twenty48 | 0 | ;;; Copyright 2019 Mitchell Kember. Subject to the MIT License.
(ns twenty48.game
"Defines the game screen, where all the fun happens."
(:require [clojure.string :refer [upper-case]]
[clojure.math.numeric-tower :as math]
[seesaw.action :as a]
[seesaw.bind :as b]
[seesaw.color :as color]
[seesaw.core :as s]
[seesaw.font :as f]
[seesaw.keymap :as k]
[seesaw.mig :as m]
[twenty48.common :as c]
[twenty48.grid :as r]
[twenty48.ui :as ui]))
;;;;; Forward declarations
(declare game-over-view)
;;;;; Grid
(defn make-grid
"Creates a new empty grid according to the option values."
[options]
(r/empty-grid (:grid-size options)))
(defn new-block-number
"Returns a random new number to be added to the grid."
[options]
(let [p (/ (:probability options) 100.0)
max-exponent (:largest-new options)]
(loop [exponent 1]
(if (or (= exponent max-exponent) (< (rand) p))
(math/expt 2 exponent)
(recur (inc exponent))))))
(defn insert-blocks
"Inserts new blocks into the grid according to the options."
[grid options]
(r/insert-blocks
grid
(take (:at-a-time options)
(repeatedly #(new-block-number options)))))
;;;;; Game state
(def animation-delay 20)
(def animation-increment 0.2)
(defn initial-game-state
"Returns the initial game state."
[options]
{:grid (insert-blocks (make-grid options) options)
:dirs #{:left :right :up :down}})
(defn start-game
"Starts a new game."
[sys state canvas]
(reset! state (initial-game-state (:options @sys)))
(s/repaint! canvas))
(defn update-state
"Updates the given state by moving the grid in the direction dir and adding a
new block. Returns the new state Switches to the game-over screen when the
grid is full and no more moves are possible."
[state sys dir]
(let [options (:options @sys)
old-grid (:grid state)
[post-slide-grid combined] (r/slide-grid old-grid dir)
grid (insert-blocks post-slide-grid options)
dirs (set (r/available-slide-directions grid))]
(if (empty? dirs)
(do (ui/show-view! sys (game-over-view sys (:score grid)))
(initial-game-state options))
{:grid grid
:dirs dirs
:old-grid old-grid
:combined combined
:animation {:phase :slide, :t 0.0}})))
(defn step-animation
"Advances the animation state. Returns nil when the animation is finished."
[animation]
(when-let [{phase :phase t :t} animation]
(if (< t 1)
{:phase phase :t (c/clamp (+ t animation-increment) 0 1)}
(case phase
:slide {:phase :appear, :t 0.0}
nil))))
;;;;; 2048 canvas
(def cell-gap 10)
(def cell-corner-radius 15)
(defn cell-dimension
"Calculates the size of a cell along one dimension when there are to be n
cells evenly spaced by cell-gap in a canvas with size canvas-dim, with gaps
between the border and edge cells as well."
[canvas-dim n]
(/ (- canvas-dim
(* (inc n) cell-gap))
n))
(defn block-color-bg
"Returns the background color to use for the given block value."
[value]
(-> {0 "#cdc1b5"
2 "#eee4da"
4 "#ede0c8"
8 "#f2b179"
16 "#f59563"
32 "#f67c5f"
64 "#f65e3b"
128 "#edcf72"
256 "#edcc61"
512 "#edc850"
1024 "#edc53f"
2048 "#edc22e"}
(get value "#3c3a32")
color/color))
(defn block-color-fg
"Returns the foreground color to use for the given block value."
[value]
(color/color (if (<= value 4) "#776e65" "#f9f6f2")))
(defn block-font-size
"Returns the font size for the given block value."
[grid-side value]
(* (condp >= value
64 55
512 45
2048 35
30)
(/ 4.0 grid-side)))
(defn draw-centred-text
"Draws text centred at the given coordinates."
[^java.awt.Graphics2D g text x y]
(let [metrics (.getFontMetrics g)
x' (c/round (- x (/ (.stringWidth metrics text) 2)))
y' (c/round (+ (- y (/ (.getHeight metrics) 2))
(.getAscent metrics)))]
(.drawString g text x' y')))
(defn draw-round-rect-centred
"Draws a rounded rectangle centred at the given coordinates."
[^java.awt.Graphics2D g x y w h]
(.fillRoundRect g (- x (/ w 2)) (- y (/ h 2)) w h
cell-corner-radius cell-corner-radius))
(defn interpolate-blocks
"Linearly interpolate block positions between two grids."
[t old-blocks new-blocks combined]
(let [all-blocks (concat new-blocks combined)
id-map (zipmap (map :id all-blocks) all-blocks)]
(map
(fn [block]
(let [[x1 y1] (:pos block)
[x2 y2] (:pos (get id-map (:id block)))]
(assoc block :pos [(c/interpolate t x1 x2)
(c/interpolate t y1 y2)])))
old-blocks)))
(defn paint-canvas
"Paints the grid in the canvas c with graphics context g."
[state c ^java.awt.Graphics2D g]
(let [grid (:grid state)
animation (:animation state)
side (:side grid)
cell-w (cell-dimension (s/width c) side)
cell-h (cell-dimension (s/height c) side)
mult-x (+ cell-w cell-gap)
mult-y (+ cell-h cell-gap)
x-pos (fn [x] (+ cell-gap (/ cell-w 2) (* x mult-x)))
y-pos (fn [y] (+ cell-gap (/ cell-h 2) (* y mult-y)))
draw-block (fn [g x y m]
(draw-round-rect-centred
g (x-pos x) (y-pos y) (* m cell-w) (* m cell-h)))
block-set (if (= (:phase animation) :slide)
(interpolate-blocks (:t animation)
(:blocks (:old-grid state))
(:blocks grid)
(:combined state))
(:blocks grid))
block-size-mult (if-not (= (:phase animation) :appear)
(constantly 1)
(let [appear-ids
(set (map :merged-into (:combined state)))]
(fn [block]
(if-not (appear-ids (:id block))
1
(- 1.25 (math/expt (- (:t animation) 0.5) 2))))))]
(.setFont g (f/font :name :sans-serif :style :bold))
(.setColor g (block-color-bg 0))
(doseq [x (range side)
y (range side)]
(draw-block g x y 1))
(doseq [block block-set]
(let [value (:value block)
[x y] (:pos block)]
(doto g
(.setColor (block-color-bg value))
(draw-block x y (block-size-mult block))
(.setColor (block-color-fg value))
(.setFont
(.. g getFont (deriveFont (float (block-font-size side value)))))
(draw-centred-text (str value) (x-pos x) (y-pos y)))))))
(defn make-canvas
"Creates the main canvas given the state atom."
[state]
(s/canvas :background "#bbada0"
:paint #(paint-canvas @state %1 %2)))
;;;;; Binding and mapping
(defn bind-val-to-property
"Binds the value associated with the key k in the source map atom to the
property p of the target widget."
[source k target p]
(b/bind source
(b/transform k)
(b/property target p)))
(defn perform-slide
"Action for when the user presses an arrow key to make the next move. Updates
the game state and starts an animation timer."
[sys state canvas dir]
(when ((:dirs @state) dir)
(let [handler (fn [event]
(swap! state update :animation step-animation)
(s/repaint! canvas)
(when-not (:animation @state)
(.. event getSource stop)))
timer (javax.swing.Timer. 0 (a/action :handler handler))]
(swap! state (fn [s]
(when-let [t (:timer s)] (.stop t))
(-> s (update-state sys dir) (assoc :timer timer))))
(doto timer (.setDelay animation-delay) .start))))
(defn map-arrow-keys
"Maps the arrow keys in the panel so that they update the grid atom and
repaint the canvas."
[sys state panel canvas]
(doseq [dir [:left :right :up :down]]
(k/map-key
panel
(upper-case (name dir))
(fn [_] (perform-slide sys state canvas dir))
:scope :descendants)))
;;;;; Game view
(defn game-panel
"Helper function for making the game panel."
[sys state score-label canvas]
(m/mig-panel
:id :game
:constraints ["fill"
"[fill,grow]"
"[c,nogrid]10[fill,grow]"]
:items [[(ui/image "logo" "png") "ax l"]
[:fill-h "w 3"]
[:fill-h "growx"]
[score-label]
[:fill-h "growx"]
[(ui/button "New Game" (fn [_] (start-game sys state canvas))) "ax r"]
[(ui/nav-button sys :options "Options") "ax r, wrap"]
[canvas "hmin 100"]]
:focusable? true
:listen [:component-resized
(fn [_] (s/repaint! canvas))]))
(defn game-view
"Creates the game view, which contains a few UI elements and the 2048 grid."
[sys]
(let [state (atom (initial-game-state (:options @sys)))
score-label (ui/label 0 40)
canvas (make-canvas state)
panel (game-panel sys state score-label canvas)]
(bind-val-to-property state (comp :score :grid) score-label :text)
(map-arrow-keys sys state panel canvas)
panel))
;;;;; Game over view
(defn game-over-view
"Create the game-over view, which displays the score and allows the user to
begin a new game."
[sys score]
(m/mig-panel
:id :game-over
:constraints ["wrap 1, fill"
"[c]"
"push[]50[]50[]push"]
:items [[(ui/label "Game Over" 40)]
[(ui/label score 60)]
[(ui/nav-button sys :game "Try Again")]]))
| 48368 | ;;; Copyright 2019 <NAME>. Subject to the MIT License.
(ns twenty48.game
"Defines the game screen, where all the fun happens."
(:require [clojure.string :refer [upper-case]]
[clojure.math.numeric-tower :as math]
[seesaw.action :as a]
[seesaw.bind :as b]
[seesaw.color :as color]
[seesaw.core :as s]
[seesaw.font :as f]
[seesaw.keymap :as k]
[seesaw.mig :as m]
[twenty48.common :as c]
[twenty48.grid :as r]
[twenty48.ui :as ui]))
;;;;; Forward declarations
(declare game-over-view)
;;;;; Grid
(defn make-grid
"Creates a new empty grid according to the option values."
[options]
(r/empty-grid (:grid-size options)))
(defn new-block-number
"Returns a random new number to be added to the grid."
[options]
(let [p (/ (:probability options) 100.0)
max-exponent (:largest-new options)]
(loop [exponent 1]
(if (or (= exponent max-exponent) (< (rand) p))
(math/expt 2 exponent)
(recur (inc exponent))))))
(defn insert-blocks
"Inserts new blocks into the grid according to the options."
[grid options]
(r/insert-blocks
grid
(take (:at-a-time options)
(repeatedly #(new-block-number options)))))
;;;;; Game state
(def animation-delay 20)
(def animation-increment 0.2)
(defn initial-game-state
"Returns the initial game state."
[options]
{:grid (insert-blocks (make-grid options) options)
:dirs #{:left :right :up :down}})
(defn start-game
"Starts a new game."
[sys state canvas]
(reset! state (initial-game-state (:options @sys)))
(s/repaint! canvas))
(defn update-state
"Updates the given state by moving the grid in the direction dir and adding a
new block. Returns the new state Switches to the game-over screen when the
grid is full and no more moves are possible."
[state sys dir]
(let [options (:options @sys)
old-grid (:grid state)
[post-slide-grid combined] (r/slide-grid old-grid dir)
grid (insert-blocks post-slide-grid options)
dirs (set (r/available-slide-directions grid))]
(if (empty? dirs)
(do (ui/show-view! sys (game-over-view sys (:score grid)))
(initial-game-state options))
{:grid grid
:dirs dirs
:old-grid old-grid
:combined combined
:animation {:phase :slide, :t 0.0}})))
(defn step-animation
"Advances the animation state. Returns nil when the animation is finished."
[animation]
(when-let [{phase :phase t :t} animation]
(if (< t 1)
{:phase phase :t (c/clamp (+ t animation-increment) 0 1)}
(case phase
:slide {:phase :appear, :t 0.0}
nil))))
;;;;; 2048 canvas
(def cell-gap 10)
(def cell-corner-radius 15)
(defn cell-dimension
"Calculates the size of a cell along one dimension when there are to be n
cells evenly spaced by cell-gap in a canvas with size canvas-dim, with gaps
between the border and edge cells as well."
[canvas-dim n]
(/ (- canvas-dim
(* (inc n) cell-gap))
n))
(defn block-color-bg
"Returns the background color to use for the given block value."
[value]
(-> {0 "#cdc1b5"
2 "#eee4da"
4 "#ede0c8"
8 "#f2b179"
16 "#f59563"
32 "#f67c5f"
64 "#f65e3b"
128 "#edcf72"
256 "#edcc61"
512 "#edc850"
1024 "#edc53f"
2048 "#edc22e"}
(get value "#3c3a32")
color/color))
(defn block-color-fg
"Returns the foreground color to use for the given block value."
[value]
(color/color (if (<= value 4) "#776e65" "#f9f6f2")))
(defn block-font-size
"Returns the font size for the given block value."
[grid-side value]
(* (condp >= value
64 55
512 45
2048 35
30)
(/ 4.0 grid-side)))
(defn draw-centred-text
"Draws text centred at the given coordinates."
[^java.awt.Graphics2D g text x y]
(let [metrics (.getFontMetrics g)
x' (c/round (- x (/ (.stringWidth metrics text) 2)))
y' (c/round (+ (- y (/ (.getHeight metrics) 2))
(.getAscent metrics)))]
(.drawString g text x' y')))
(defn draw-round-rect-centred
"Draws a rounded rectangle centred at the given coordinates."
[^java.awt.Graphics2D g x y w h]
(.fillRoundRect g (- x (/ w 2)) (- y (/ h 2)) w h
cell-corner-radius cell-corner-radius))
(defn interpolate-blocks
"Linearly interpolate block positions between two grids."
[t old-blocks new-blocks combined]
(let [all-blocks (concat new-blocks combined)
id-map (zipmap (map :id all-blocks) all-blocks)]
(map
(fn [block]
(let [[x1 y1] (:pos block)
[x2 y2] (:pos (get id-map (:id block)))]
(assoc block :pos [(c/interpolate t x1 x2)
(c/interpolate t y1 y2)])))
old-blocks)))
(defn paint-canvas
"Paints the grid in the canvas c with graphics context g."
[state c ^java.awt.Graphics2D g]
(let [grid (:grid state)
animation (:animation state)
side (:side grid)
cell-w (cell-dimension (s/width c) side)
cell-h (cell-dimension (s/height c) side)
mult-x (+ cell-w cell-gap)
mult-y (+ cell-h cell-gap)
x-pos (fn [x] (+ cell-gap (/ cell-w 2) (* x mult-x)))
y-pos (fn [y] (+ cell-gap (/ cell-h 2) (* y mult-y)))
draw-block (fn [g x y m]
(draw-round-rect-centred
g (x-pos x) (y-pos y) (* m cell-w) (* m cell-h)))
block-set (if (= (:phase animation) :slide)
(interpolate-blocks (:t animation)
(:blocks (:old-grid state))
(:blocks grid)
(:combined state))
(:blocks grid))
block-size-mult (if-not (= (:phase animation) :appear)
(constantly 1)
(let [appear-ids
(set (map :merged-into (:combined state)))]
(fn [block]
(if-not (appear-ids (:id block))
1
(- 1.25 (math/expt (- (:t animation) 0.5) 2))))))]
(.setFont g (f/font :name :sans-serif :style :bold))
(.setColor g (block-color-bg 0))
(doseq [x (range side)
y (range side)]
(draw-block g x y 1))
(doseq [block block-set]
(let [value (:value block)
[x y] (:pos block)]
(doto g
(.setColor (block-color-bg value))
(draw-block x y (block-size-mult block))
(.setColor (block-color-fg value))
(.setFont
(.. g getFont (deriveFont (float (block-font-size side value)))))
(draw-centred-text (str value) (x-pos x) (y-pos y)))))))
(defn make-canvas
"Creates the main canvas given the state atom."
[state]
(s/canvas :background "#bbada0"
:paint #(paint-canvas @state %1 %2)))
;;;;; Binding and mapping
(defn bind-val-to-property
"Binds the value associated with the key k in the source map atom to the
property p of the target widget."
[source k target p]
(b/bind source
(b/transform k)
(b/property target p)))
(defn perform-slide
"Action for when the user presses an arrow key to make the next move. Updates
the game state and starts an animation timer."
[sys state canvas dir]
(when ((:dirs @state) dir)
(let [handler (fn [event]
(swap! state update :animation step-animation)
(s/repaint! canvas)
(when-not (:animation @state)
(.. event getSource stop)))
timer (javax.swing.Timer. 0 (a/action :handler handler))]
(swap! state (fn [s]
(when-let [t (:timer s)] (.stop t))
(-> s (update-state sys dir) (assoc :timer timer))))
(doto timer (.setDelay animation-delay) .start))))
(defn map-arrow-keys
"Maps the arrow keys in the panel so that they update the grid atom and
repaint the canvas."
[sys state panel canvas]
(doseq [dir [:left :right :up :down]]
(k/map-key
panel
(upper-case (name dir))
(fn [_] (perform-slide sys state canvas dir))
:scope :descendants)))
;;;;; Game view
(defn game-panel
"Helper function for making the game panel."
[sys state score-label canvas]
(m/mig-panel
:id :game
:constraints ["fill"
"[fill,grow]"
"[c,nogrid]10[fill,grow]"]
:items [[(ui/image "logo" "png") "ax l"]
[:fill-h "w 3"]
[:fill-h "growx"]
[score-label]
[:fill-h "growx"]
[(ui/button "New Game" (fn [_] (start-game sys state canvas))) "ax r"]
[(ui/nav-button sys :options "Options") "ax r, wrap"]
[canvas "hmin 100"]]
:focusable? true
:listen [:component-resized
(fn [_] (s/repaint! canvas))]))
(defn game-view
"Creates the game view, which contains a few UI elements and the 2048 grid."
[sys]
(let [state (atom (initial-game-state (:options @sys)))
score-label (ui/label 0 40)
canvas (make-canvas state)
panel (game-panel sys state score-label canvas)]
(bind-val-to-property state (comp :score :grid) score-label :text)
(map-arrow-keys sys state panel canvas)
panel))
;;;;; Game over view
(defn game-over-view
"Create the game-over view, which displays the score and allows the user to
begin a new game."
[sys score]
(m/mig-panel
:id :game-over
:constraints ["wrap 1, fill"
"[c]"
"push[]50[]50[]push"]
:items [[(ui/label "Game Over" 40)]
[(ui/label score 60)]
[(ui/nav-button sys :game "Try Again")]]))
| true | ;;; Copyright 2019 PI:NAME:<NAME>END_PI. Subject to the MIT License.
(ns twenty48.game
"Defines the game screen, where all the fun happens."
(:require [clojure.string :refer [upper-case]]
[clojure.math.numeric-tower :as math]
[seesaw.action :as a]
[seesaw.bind :as b]
[seesaw.color :as color]
[seesaw.core :as s]
[seesaw.font :as f]
[seesaw.keymap :as k]
[seesaw.mig :as m]
[twenty48.common :as c]
[twenty48.grid :as r]
[twenty48.ui :as ui]))
;;;;; Forward declarations
(declare game-over-view)
;;;;; Grid
(defn make-grid
"Creates a new empty grid according to the option values."
[options]
(r/empty-grid (:grid-size options)))
(defn new-block-number
"Returns a random new number to be added to the grid."
[options]
(let [p (/ (:probability options) 100.0)
max-exponent (:largest-new options)]
(loop [exponent 1]
(if (or (= exponent max-exponent) (< (rand) p))
(math/expt 2 exponent)
(recur (inc exponent))))))
(defn insert-blocks
"Inserts new blocks into the grid according to the options."
[grid options]
(r/insert-blocks
grid
(take (:at-a-time options)
(repeatedly #(new-block-number options)))))
;;;;; Game state
(def animation-delay 20)
(def animation-increment 0.2)
(defn initial-game-state
"Returns the initial game state."
[options]
{:grid (insert-blocks (make-grid options) options)
:dirs #{:left :right :up :down}})
(defn start-game
"Starts a new game."
[sys state canvas]
(reset! state (initial-game-state (:options @sys)))
(s/repaint! canvas))
(defn update-state
"Updates the given state by moving the grid in the direction dir and adding a
new block. Returns the new state Switches to the game-over screen when the
grid is full and no more moves are possible."
[state sys dir]
(let [options (:options @sys)
old-grid (:grid state)
[post-slide-grid combined] (r/slide-grid old-grid dir)
grid (insert-blocks post-slide-grid options)
dirs (set (r/available-slide-directions grid))]
(if (empty? dirs)
(do (ui/show-view! sys (game-over-view sys (:score grid)))
(initial-game-state options))
{:grid grid
:dirs dirs
:old-grid old-grid
:combined combined
:animation {:phase :slide, :t 0.0}})))
(defn step-animation
"Advances the animation state. Returns nil when the animation is finished."
[animation]
(when-let [{phase :phase t :t} animation]
(if (< t 1)
{:phase phase :t (c/clamp (+ t animation-increment) 0 1)}
(case phase
:slide {:phase :appear, :t 0.0}
nil))))
;;;;; 2048 canvas
(def cell-gap 10)
(def cell-corner-radius 15)
(defn cell-dimension
"Calculates the size of a cell along one dimension when there are to be n
cells evenly spaced by cell-gap in a canvas with size canvas-dim, with gaps
between the border and edge cells as well."
[canvas-dim n]
(/ (- canvas-dim
(* (inc n) cell-gap))
n))
(defn block-color-bg
"Returns the background color to use for the given block value."
[value]
(-> {0 "#cdc1b5"
2 "#eee4da"
4 "#ede0c8"
8 "#f2b179"
16 "#f59563"
32 "#f67c5f"
64 "#f65e3b"
128 "#edcf72"
256 "#edcc61"
512 "#edc850"
1024 "#edc53f"
2048 "#edc22e"}
(get value "#3c3a32")
color/color))
(defn block-color-fg
"Returns the foreground color to use for the given block value."
[value]
(color/color (if (<= value 4) "#776e65" "#f9f6f2")))
(defn block-font-size
"Returns the font size for the given block value."
[grid-side value]
(* (condp >= value
64 55
512 45
2048 35
30)
(/ 4.0 grid-side)))
(defn draw-centred-text
"Draws text centred at the given coordinates."
[^java.awt.Graphics2D g text x y]
(let [metrics (.getFontMetrics g)
x' (c/round (- x (/ (.stringWidth metrics text) 2)))
y' (c/round (+ (- y (/ (.getHeight metrics) 2))
(.getAscent metrics)))]
(.drawString g text x' y')))
(defn draw-round-rect-centred
"Draws a rounded rectangle centred at the given coordinates."
[^java.awt.Graphics2D g x y w h]
(.fillRoundRect g (- x (/ w 2)) (- y (/ h 2)) w h
cell-corner-radius cell-corner-radius))
(defn interpolate-blocks
"Linearly interpolate block positions between two grids."
[t old-blocks new-blocks combined]
(let [all-blocks (concat new-blocks combined)
id-map (zipmap (map :id all-blocks) all-blocks)]
(map
(fn [block]
(let [[x1 y1] (:pos block)
[x2 y2] (:pos (get id-map (:id block)))]
(assoc block :pos [(c/interpolate t x1 x2)
(c/interpolate t y1 y2)])))
old-blocks)))
(defn paint-canvas
"Paints the grid in the canvas c with graphics context g."
[state c ^java.awt.Graphics2D g]
(let [grid (:grid state)
animation (:animation state)
side (:side grid)
cell-w (cell-dimension (s/width c) side)
cell-h (cell-dimension (s/height c) side)
mult-x (+ cell-w cell-gap)
mult-y (+ cell-h cell-gap)
x-pos (fn [x] (+ cell-gap (/ cell-w 2) (* x mult-x)))
y-pos (fn [y] (+ cell-gap (/ cell-h 2) (* y mult-y)))
draw-block (fn [g x y m]
(draw-round-rect-centred
g (x-pos x) (y-pos y) (* m cell-w) (* m cell-h)))
block-set (if (= (:phase animation) :slide)
(interpolate-blocks (:t animation)
(:blocks (:old-grid state))
(:blocks grid)
(:combined state))
(:blocks grid))
block-size-mult (if-not (= (:phase animation) :appear)
(constantly 1)
(let [appear-ids
(set (map :merged-into (:combined state)))]
(fn [block]
(if-not (appear-ids (:id block))
1
(- 1.25 (math/expt (- (:t animation) 0.5) 2))))))]
(.setFont g (f/font :name :sans-serif :style :bold))
(.setColor g (block-color-bg 0))
(doseq [x (range side)
y (range side)]
(draw-block g x y 1))
(doseq [block block-set]
(let [value (:value block)
[x y] (:pos block)]
(doto g
(.setColor (block-color-bg value))
(draw-block x y (block-size-mult block))
(.setColor (block-color-fg value))
(.setFont
(.. g getFont (deriveFont (float (block-font-size side value)))))
(draw-centred-text (str value) (x-pos x) (y-pos y)))))))
(defn make-canvas
"Creates the main canvas given the state atom."
[state]
(s/canvas :background "#bbada0"
:paint #(paint-canvas @state %1 %2)))
;;;;; Binding and mapping
(defn bind-val-to-property
"Binds the value associated with the key k in the source map atom to the
property p of the target widget."
[source k target p]
(b/bind source
(b/transform k)
(b/property target p)))
(defn perform-slide
"Action for when the user presses an arrow key to make the next move. Updates
the game state and starts an animation timer."
[sys state canvas dir]
(when ((:dirs @state) dir)
(let [handler (fn [event]
(swap! state update :animation step-animation)
(s/repaint! canvas)
(when-not (:animation @state)
(.. event getSource stop)))
timer (javax.swing.Timer. 0 (a/action :handler handler))]
(swap! state (fn [s]
(when-let [t (:timer s)] (.stop t))
(-> s (update-state sys dir) (assoc :timer timer))))
(doto timer (.setDelay animation-delay) .start))))
(defn map-arrow-keys
"Maps the arrow keys in the panel so that they update the grid atom and
repaint the canvas."
[sys state panel canvas]
(doseq [dir [:left :right :up :down]]
(k/map-key
panel
(upper-case (name dir))
(fn [_] (perform-slide sys state canvas dir))
:scope :descendants)))
;;;;; Game view
(defn game-panel
"Helper function for making the game panel."
[sys state score-label canvas]
(m/mig-panel
:id :game
:constraints ["fill"
"[fill,grow]"
"[c,nogrid]10[fill,grow]"]
:items [[(ui/image "logo" "png") "ax l"]
[:fill-h "w 3"]
[:fill-h "growx"]
[score-label]
[:fill-h "growx"]
[(ui/button "New Game" (fn [_] (start-game sys state canvas))) "ax r"]
[(ui/nav-button sys :options "Options") "ax r, wrap"]
[canvas "hmin 100"]]
:focusable? true
:listen [:component-resized
(fn [_] (s/repaint! canvas))]))
(defn game-view
"Creates the game view, which contains a few UI elements and the 2048 grid."
[sys]
(let [state (atom (initial-game-state (:options @sys)))
score-label (ui/label 0 40)
canvas (make-canvas state)
panel (game-panel sys state score-label canvas)]
(bind-val-to-property state (comp :score :grid) score-label :text)
(map-arrow-keys sys state panel canvas)
panel))
;;;;; Game over view
(defn game-over-view
"Create the game-over view, which displays the score and allows the user to
begin a new game."
[sys score]
(m/mig-panel
:id :game-over
:constraints ["wrap 1, fill"
"[c]"
"push[]50[]50[]push"]
:items [[(ui/label "Game Over" 40)]
[(ui/label score 60)]
[(ui/nav-button sys :game "Try Again")]]))
|
[
{
"context": ";; Based on the Nature of Code\n;; by Daniel Shiffman\n;; http://natureofcode.com\n;;\n(ns videotest.flock",
"end": 52,
"score": 0.9998210072517395,
"start": 37,
"tag": "NAME",
"value": "Daniel Shiffman"
}
] | BigGiantProjectWhichNeedsToBeDecomposed/src/videotest/flock_tune/behavior.clj | PasDeChocolat/QuilCV | 3 | ;; Based on the Nature of Code
;; by Daniel Shiffman
;; http://natureofcode.com
;;
(ns videotest.flock-tune.behavior
(:require
[videotest.flock-tune.native-vector :as fvec]))
(defn dist-vehicle [loc vehicles]
(mapv (fn [v]
(let [d (fvec/distance (:location v) loc)]
[d v]))
vehicles))
(defn apply-force [vehicle f-vector]
(update-in vehicle [:acceleration] #(fvec/+ % f-vector)))
(defn between-0 [upper-d d]
(and (> d 0.0)
(< d upper-d)))
(defn align-vec
"General alignment with things with a velocity. Assumes that
inputs are already filtered (for distance)."
[max-force max-speed others thing]
(if (seq others)
(let [sum-vec (doall
(reduce (fn [avg-v v]
(fvec/+ avg-v v))
(fvec/fvec 0 0) others))]
(-> sum-vec
(fvec// (count others))
(fvec/normalize)
(fvec/* max-speed)
(fvec/- thing)
(fvec/limit max-force)))
(fvec/fvec 0 0)))
(defn align
"Returns the alignment force for nearby vehicles, an average
velocity of sorts. This force must be applied."
[neighbor-dist all vehicle]
(let [{:keys [location max-force max-speed velocity]} vehicle
all-vel (doall
(->> all
(dist-vehicle location)
(filter (fn [[d _]] (between-0 neighbor-dist d)))
(map (fn [[_ v]] (:velocity v)))))]
(align-vec max-force max-speed all-vel velocity)))
(defn glom
"Returns the cohesive force, which must be applied."
[glom-dist all vehicle]
(let [{:keys [location max-force max-speed velocity]} vehicle
dist-veh (doall
(->> all
(dist-vehicle location)
(filter (fn [[d _]] (between-0 glom-dist d)))))
num-vehicles (count dist-veh)]
(if (< 0 num-vehicles)
(let [sum-loc (doall
(reduce (fn [sum [d v]]
(fvec/+ sum (:location v)))
(fvec/fvec 0 0) dist-veh))]
(-> sum-loc
(fvec/- location)
(fvec/normalize)
(fvec/* max-speed)
(fvec/- velocity)
(fvec/limit max-force)))
(fvec/fvec 0.0 0.0))))
(defn seek
"Returns the seek force, which must be applied."
[target vehicle]
(let [{:keys [location max-force max-speed velocity]} vehicle]
(-> (fvec/- target location)
(fvec/normalize)
(fvec/* max-speed)
(fvec/- velocity)
(fvec/limit max-force))))
(defn separate
"Returns separation force, based on neighbor distance and desired
separation distance. Force must be applied to a vehicles accel."
[sep-dist all vehicle]
(let [{:keys [location max-force max-speed velocity]} vehicle
dist-veh (doall
(->> all
(dist-vehicle location)
(filter (fn [[d _]] (between-0 sep-dist d)))))
num-vehicles (count dist-veh)]
(if (< 0 num-vehicles)
(let [sum-dir (doall
(reduce (fn [avg-dir [d v]]
(let [diff (-> (fvec/- location (:location v))
(fvec/normalize)
(fvec// d))]
(fvec/+ avg-dir diff)))
(fvec/fvec 0 0) dist-veh))]
(-> sum-dir
(fvec/normalize)
(fvec/set-mag max-speed)
(fvec/- velocity)
(fvec/limit max-force)))
(fvec/fvec 0.0 0.0))))
(defn borders
[edge-x edge-y vehicle-r vehicle]
"Assumes multiple path segments (at least two)."
(let [{:keys [location]} vehicle
[x y] (fvec/x-y location)]
(cond->
vehicle
(> x (+ edge-x vehicle-r))
(assoc-in [:location]
(fvec/fvec (- 0 vehicle-r) y))
(< x (- 0 vehicle-r))
(assoc-in [:location]
(fvec/fvec (+ edge-x vehicle-r) y))
(> y (+ edge-y vehicle-r))
(assoc-in [:location]
(fvec/fvec x (- 0 vehicle-r)))
(< y (- 0 vehicle-r))
(assoc-in [:location]
(fvec/fvec x (+ edge-y vehicle-r))))))
(defn move-vehicle [vehicle]
(let [v (fvec/+ (:velocity vehicle) (:acceleration vehicle))
v (fvec/limit v (:max-speed vehicle))
loc (fvec/+ v (:location vehicle))]
(-> vehicle
(assoc-in [:velocity] v)
(assoc-in [:location] loc)
(assoc-in [:acceleration] (fvec/fvec 0 0)))))
| 101571 | ;; Based on the Nature of Code
;; by <NAME>
;; http://natureofcode.com
;;
(ns videotest.flock-tune.behavior
(:require
[videotest.flock-tune.native-vector :as fvec]))
(defn dist-vehicle [loc vehicles]
(mapv (fn [v]
(let [d (fvec/distance (:location v) loc)]
[d v]))
vehicles))
(defn apply-force [vehicle f-vector]
(update-in vehicle [:acceleration] #(fvec/+ % f-vector)))
(defn between-0 [upper-d d]
(and (> d 0.0)
(< d upper-d)))
(defn align-vec
"General alignment with things with a velocity. Assumes that
inputs are already filtered (for distance)."
[max-force max-speed others thing]
(if (seq others)
(let [sum-vec (doall
(reduce (fn [avg-v v]
(fvec/+ avg-v v))
(fvec/fvec 0 0) others))]
(-> sum-vec
(fvec// (count others))
(fvec/normalize)
(fvec/* max-speed)
(fvec/- thing)
(fvec/limit max-force)))
(fvec/fvec 0 0)))
(defn align
"Returns the alignment force for nearby vehicles, an average
velocity of sorts. This force must be applied."
[neighbor-dist all vehicle]
(let [{:keys [location max-force max-speed velocity]} vehicle
all-vel (doall
(->> all
(dist-vehicle location)
(filter (fn [[d _]] (between-0 neighbor-dist d)))
(map (fn [[_ v]] (:velocity v)))))]
(align-vec max-force max-speed all-vel velocity)))
(defn glom
"Returns the cohesive force, which must be applied."
[glom-dist all vehicle]
(let [{:keys [location max-force max-speed velocity]} vehicle
dist-veh (doall
(->> all
(dist-vehicle location)
(filter (fn [[d _]] (between-0 glom-dist d)))))
num-vehicles (count dist-veh)]
(if (< 0 num-vehicles)
(let [sum-loc (doall
(reduce (fn [sum [d v]]
(fvec/+ sum (:location v)))
(fvec/fvec 0 0) dist-veh))]
(-> sum-loc
(fvec/- location)
(fvec/normalize)
(fvec/* max-speed)
(fvec/- velocity)
(fvec/limit max-force)))
(fvec/fvec 0.0 0.0))))
(defn seek
"Returns the seek force, which must be applied."
[target vehicle]
(let [{:keys [location max-force max-speed velocity]} vehicle]
(-> (fvec/- target location)
(fvec/normalize)
(fvec/* max-speed)
(fvec/- velocity)
(fvec/limit max-force))))
(defn separate
"Returns separation force, based on neighbor distance and desired
separation distance. Force must be applied to a vehicles accel."
[sep-dist all vehicle]
(let [{:keys [location max-force max-speed velocity]} vehicle
dist-veh (doall
(->> all
(dist-vehicle location)
(filter (fn [[d _]] (between-0 sep-dist d)))))
num-vehicles (count dist-veh)]
(if (< 0 num-vehicles)
(let [sum-dir (doall
(reduce (fn [avg-dir [d v]]
(let [diff (-> (fvec/- location (:location v))
(fvec/normalize)
(fvec// d))]
(fvec/+ avg-dir diff)))
(fvec/fvec 0 0) dist-veh))]
(-> sum-dir
(fvec/normalize)
(fvec/set-mag max-speed)
(fvec/- velocity)
(fvec/limit max-force)))
(fvec/fvec 0.0 0.0))))
(defn borders
[edge-x edge-y vehicle-r vehicle]
"Assumes multiple path segments (at least two)."
(let [{:keys [location]} vehicle
[x y] (fvec/x-y location)]
(cond->
vehicle
(> x (+ edge-x vehicle-r))
(assoc-in [:location]
(fvec/fvec (- 0 vehicle-r) y))
(< x (- 0 vehicle-r))
(assoc-in [:location]
(fvec/fvec (+ edge-x vehicle-r) y))
(> y (+ edge-y vehicle-r))
(assoc-in [:location]
(fvec/fvec x (- 0 vehicle-r)))
(< y (- 0 vehicle-r))
(assoc-in [:location]
(fvec/fvec x (+ edge-y vehicle-r))))))
(defn move-vehicle [vehicle]
(let [v (fvec/+ (:velocity vehicle) (:acceleration vehicle))
v (fvec/limit v (:max-speed vehicle))
loc (fvec/+ v (:location vehicle))]
(-> vehicle
(assoc-in [:velocity] v)
(assoc-in [:location] loc)
(assoc-in [:acceleration] (fvec/fvec 0 0)))))
| true | ;; Based on the Nature of Code
;; by PI:NAME:<NAME>END_PI
;; http://natureofcode.com
;;
(ns videotest.flock-tune.behavior
(:require
[videotest.flock-tune.native-vector :as fvec]))
(defn dist-vehicle [loc vehicles]
(mapv (fn [v]
(let [d (fvec/distance (:location v) loc)]
[d v]))
vehicles))
(defn apply-force [vehicle f-vector]
(update-in vehicle [:acceleration] #(fvec/+ % f-vector)))
(defn between-0 [upper-d d]
(and (> d 0.0)
(< d upper-d)))
(defn align-vec
"General alignment with things with a velocity. Assumes that
inputs are already filtered (for distance)."
[max-force max-speed others thing]
(if (seq others)
(let [sum-vec (doall
(reduce (fn [avg-v v]
(fvec/+ avg-v v))
(fvec/fvec 0 0) others))]
(-> sum-vec
(fvec// (count others))
(fvec/normalize)
(fvec/* max-speed)
(fvec/- thing)
(fvec/limit max-force)))
(fvec/fvec 0 0)))
(defn align
"Returns the alignment force for nearby vehicles, an average
velocity of sorts. This force must be applied."
[neighbor-dist all vehicle]
(let [{:keys [location max-force max-speed velocity]} vehicle
all-vel (doall
(->> all
(dist-vehicle location)
(filter (fn [[d _]] (between-0 neighbor-dist d)))
(map (fn [[_ v]] (:velocity v)))))]
(align-vec max-force max-speed all-vel velocity)))
(defn glom
"Returns the cohesive force, which must be applied."
[glom-dist all vehicle]
(let [{:keys [location max-force max-speed velocity]} vehicle
dist-veh (doall
(->> all
(dist-vehicle location)
(filter (fn [[d _]] (between-0 glom-dist d)))))
num-vehicles (count dist-veh)]
(if (< 0 num-vehicles)
(let [sum-loc (doall
(reduce (fn [sum [d v]]
(fvec/+ sum (:location v)))
(fvec/fvec 0 0) dist-veh))]
(-> sum-loc
(fvec/- location)
(fvec/normalize)
(fvec/* max-speed)
(fvec/- velocity)
(fvec/limit max-force)))
(fvec/fvec 0.0 0.0))))
(defn seek
"Returns the seek force, which must be applied."
[target vehicle]
(let [{:keys [location max-force max-speed velocity]} vehicle]
(-> (fvec/- target location)
(fvec/normalize)
(fvec/* max-speed)
(fvec/- velocity)
(fvec/limit max-force))))
(defn separate
"Returns separation force, based on neighbor distance and desired
separation distance. Force must be applied to a vehicles accel."
[sep-dist all vehicle]
(let [{:keys [location max-force max-speed velocity]} vehicle
dist-veh (doall
(->> all
(dist-vehicle location)
(filter (fn [[d _]] (between-0 sep-dist d)))))
num-vehicles (count dist-veh)]
(if (< 0 num-vehicles)
(let [sum-dir (doall
(reduce (fn [avg-dir [d v]]
(let [diff (-> (fvec/- location (:location v))
(fvec/normalize)
(fvec// d))]
(fvec/+ avg-dir diff)))
(fvec/fvec 0 0) dist-veh))]
(-> sum-dir
(fvec/normalize)
(fvec/set-mag max-speed)
(fvec/- velocity)
(fvec/limit max-force)))
(fvec/fvec 0.0 0.0))))
(defn borders
[edge-x edge-y vehicle-r vehicle]
"Assumes multiple path segments (at least two)."
(let [{:keys [location]} vehicle
[x y] (fvec/x-y location)]
(cond->
vehicle
(> x (+ edge-x vehicle-r))
(assoc-in [:location]
(fvec/fvec (- 0 vehicle-r) y))
(< x (- 0 vehicle-r))
(assoc-in [:location]
(fvec/fvec (+ edge-x vehicle-r) y))
(> y (+ edge-y vehicle-r))
(assoc-in [:location]
(fvec/fvec x (- 0 vehicle-r)))
(< y (- 0 vehicle-r))
(assoc-in [:location]
(fvec/fvec x (+ edge-y vehicle-r))))))
(defn move-vehicle [vehicle]
(let [v (fvec/+ (:velocity vehicle) (:acceleration vehicle))
v (fvec/limit v (:max-speed vehicle))
loc (fvec/+ v (:location vehicle))]
(-> vehicle
(assoc-in [:velocity] v)
(assoc-in [:location] loc)
(assoc-in [:acceleration] (fvec/fvec 0 0)))))
|
[
{
"context": ";;; Copyright (C) 2012 Christian Pohlmann\n;;;\n;;; Licensed under The MIT License (see LICEN",
"end": 41,
"score": 0.9995748400688171,
"start": 23,
"tag": "NAME",
"value": "Christian Pohlmann"
}
] | src/runver/ltl.clj | christianpohlmann/runver | 0 | ;;; Copyright (C) 2012 Christian Pohlmann
;;;
;;; Licensed under The MIT License (see LICENSE)
(ns runver.ltl
(:use [matchure :only [cond-match]])
(:gen-class))
(def operators
^{:doc "Symbols representing LTL operators are mapped to their respective
precedence."}
{ '-> 1 'or 1 'and 2 'U 3 'R 3 'WX 3 'X 3 'G 3 'F 3 'not 4})
(def arity
{ '-> 2 'or 2 'and 2 'U 2 'R 2 'WX 1 'X 1 'G 1 'F 1 'not 1})
(defn is-operator? [x]
(some #{x} (keys operators)))
(def is-operand? (comp not is-operator?))
(def precedence operators)
(defn infix-to-postfix
"Converts an LTL expression given in usual infix syntax to postfix syntax
(RPN). This function implements Dijkstra's shunting-yard algorithm."
[expr]
(loop [expr expr
stack []
out []]
(cond (not (coll? expr))
expr
(empty? expr)
(concat out (reverse stack))
(coll? (first expr))
(recur (rest expr) stack (concat out (infix-to-postfix
(first expr))))
(is-operand? (first expr))
(recur (rest expr) stack (conj out (first expr)))
(empty? stack)
(recur (rest expr) (conj stack (first expr)) out)
(> (precedence (peek stack)) (precedence (first expr)))
(recur expr (pop stack) (conj out (peek stack)))
:else
(recur (rest expr) (conj stack (first expr)) out))))
(defn peek-n
"Returns the first n items from the given stack."
[stack n]
(loop [n n
vals []
stack stack]
(if (= n 0) (reverse vals)
(recur (dec n) (conj vals (peek stack)) (pop stack)))))
(defn pop-n
"Returns the given stack with the first n items removed."
[stack n]
(loop [n n
stack stack]
(if (= n 0) stack
(recur (dec n) (pop stack)))))
(defn postfix-to-prefix
"Converts an LTL expression given in RPN into prefix notation by performing
a 'pseudo evaluation'."
[expr]
(loop [expr expr
stack []]
(cond (not (coll? expr))
expr
(empty? expr)
(peek stack)
(is-operator? (first expr))
(recur (rest expr)
(conj (pop-n stack (arity (first expr)))
(conj (peek-n stack (arity (first expr)))
(first expr))))
:else
(recur (rest expr) (conj stack (first expr))))))
(def infix-to-prefix (comp postfix-to-prefix infix-to-postfix))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Defining the LTL truth domain, i.e. constants, order (which is ;;;;
;;;; linear), meet/join operations and the dual elements ;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def top 'top)
(def bot 'bot)
(def ? '?) ;; LTL3-specific value
(def p_top 'p_top) ;; LTL4-specific value
(def p_bot 'p_bot) ;; LTL4-specific value
(defn ltl-boolean? [x]
(some #{x} [bot top ? p_top p_bot]))
(defn final-value?
"Returns true if the given argument is a final value. A final value
is either top or bottom."
[x]
(or (= x top) (= x bot)))
(let [ltl3-order { top 3 ? 2 bot 1 }
ltl4-order { top 3 p_top 2 p_bot 2 bot 1 }]
(defn ltl-meet [arg1 arg2 env]
(if (= (:logic env) 'ltl3)
(min-key ltl3-order arg1 arg2) ; ltl3
(if (or (= [arg1 arg2] [p_top p_bot]) ; ltl4
(= [arg1 arg2] [p_bot p_top]))
bot
(min-key ltl4-order arg1 arg2))))
(defn ltl-join [arg1 arg2 env]
(if (= (:logic env) 'ltl3)
(min-key ltl3-order arg1 arg2)
(if (or (= [arg1 arg2] [p_top p_bot])
(= [arg1 arg2] [p_bot p_top]))
top
(max-key ltl4-order arg1 arg2)))))
(def ltl-dual {top bot
bot top
? ?
p_top p_bot
p_bot p_top})
(defn simplify
"Simplifies a given LTL formula according to some rules."
;;; TODO: Use syntax-quote instead of manual calls to list etc.
[phi]
(letfn [(simplify-once [phi]
(if (not (coll? phi))
phi
(let [[fst phi1 phi2] phi]
(cond (= fst 'and)
(cond
;; rule: A1
(= phi1 bot) bot
;; rule: A2
(= phi2 bot) bot
;; rule: A3
(= phi1 top) (recur phi2)
;; rule: A4
(= phi2 top) (recur phi1)
;; rule A5
:else
(list 'and
(simplify-once phi1)
(simplify-once phi2)))
(= fst 'or)
(cond
;; rule: O1
(= phi1 bot) (recur phi2)
;; rule: O2
(= phi2 bot) (recur phi1)
;; rule: O3
(= phi1 top) top
;; rule: O4
(= phi2 top) top
;; rule O5
:else
(list 'or
(simplify-once phi1)
(simplify-once phi2)))
(= fst 'not)
(cond
;; rule: N1
(= phi1 top) bot
;; rule: N2
(= phi1 bot) top
;; rules: N3, N4
(and (coll? phi1) (or (= (first phi1) 'and)
(= (first phi1) 'or)))
(let [[op psi1 psi2] phi1]
(simplify-once
(list ({'or 'and 'and 'or} op)
(list 'not (simplify-once psi1))
(list 'not (simplify-once psi2)))))
;; rule: N5
(and (coll? phi1) (= (first phi1) 'not))
(recur (second phi1))
;; rule: N6
:else
(list 'not (simplify-once phi1)))
;; rule: U1
(= fst 'U)
(list 'U
(simplify-once phi1)
(simplify-once phi2))
:else
phi))))]
;; There are formulae which cannot be fully simplified in a single
;; iteration using the above rules (e.g. (and (not bot) phi1) will
;; result in (and top phi1)). Therefore simplify-once is applied
;; iteratively until the formula doesn't change in one iteration
;; (i.e. can't be simplified further)
(loop [prev-formula phi]
(let [simp-formula (simplify-once prev-formula)]
(if (not= prev-formula simp-formula)
(recur simp-formula)
simp-formula)))))
(defstruct monitor-result :value :formula)
(defmacro result [value formula]
`(struct monitor-result ~value ~formula))
(defn simplify-result
"Simplifies the formula of a result object and returns the updated
rseult, i.e. leaving the value field unchanged."
[{value :value formula :formula}]
(struct monitor-result value (simplify formula)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; LTL evaluation functions ;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; All evaluation functions have an env-parameter which is currently only
;;; used to signal whether LTL3 or LTL4 is used, but it could be used for
;;; other options as well.
(declare ltl-eval)
(defn ltl-ap [input ap]
(if (some #{ap} input) (result top top) (result bot bot)))
(defn ltl-not [input phi env]
(let [ev-phi (ltl-eval input phi env)]
(result (ltl-dual (:value ev-phi))
`(~'not ~(:formula ev-phi)))))
(defn ltl-next [input phi env]
(if (= (:logic env) 'ltl4)
(result p_bot phi) ; ltl4
(result ? phi))) ; ltl3
(defn ltl-weaknext [input phi env]
(ltl-eval input `(~'not (~'X (~'not ~phi))) env))
;; (if (= (:logic env) 'ltl4)
;; (result p_top phi) ; ltl4
;; (result ? phi))) ; ltl3
(defn ltl-until [input phi1 phi2 env]
(let [new-formula `(~'or ~phi2 (~'and ~phi1 (~'X (~'U ~phi1 ~phi2))))]
(ltl-eval input new-formula env)))
(defn ltl-release [input phi1 phi2 env]
(ltl-eval input `(~'not (~'U (~'not ~phi1) (~'not ~phi2))) env))
(defn ltl-globally [input phi env]
(ltl-eval input `(~'R ~bot ~phi) env))
(defn ltl-finally [input phi env]
(ltl-eval input `(~'U ~top ~phi) env))
(defn ltl-and [input phi1 phi2 env]
(let [ev-phi1 (ltl-eval input phi1 env)]
(if (= (:value ev-phi1) top)
(ltl-eval input phi2 env)
(let [ev-phi2 (ltl-eval input phi2 env)
meet (ltl-meet (:value ev-phi1) (:value ev-phi2) env)]
(cond (final-value? meet) (result meet meet)
:else (result meet (list 'and (:formula ev-phi1)
(:formula ev-phi2))))))))
;; in order to improve performance it might be better to implement
;; ltl-or and ltl-impl independently and not in terms of other functions
(defn ltl-or [input phi1 phi2 env]
(ltl-eval input `(~'not (~'and (~'not ~phi1) (~'not ~phi2))) env))
(defn ltl-impl [input phi1 phi2 env]
(ltl-eval input `(~'or (~'not ~phi1) ~phi2) env))
(defn ltl-boolean [input val]
(result val val))
(defn ltl-evaluator
"Online-evaluation of infinite traces *without* automata. This function
returns a closure acting as monitor which can be called with the
continuation of the trace (which may be non-finite). When the given
formula can be fully evaluated, either top or bot is returned, otherwise
? is returned (i.e. in cases like p and X phi)."
[formula logic]
(let [formula (atom (infix-to-prefix formula))]
(fn [& input]
(let [res (ltl-eval input @formula {:logic logic})
s-res (simplify-result res)] ; simplified result
(compare-and-set! formula @formula (:formula s-res))
s-res))))
(defn ltl-eval [input phi env]
(cond (coll? phi)
(let [[op phi1 phi2] phi]
(cond (= op 'and) (ltl-and input phi1 phi2 env)
(= op' or) (ltl-or input phi1 phi2 env)
(= op '->) (ltl-impl input phi1 phi2 env)
(= op 'not) (ltl-not input phi1 env)
(= op 'WX) (ltl-weaknext input phi1 env)
(= op 'X) (ltl-next input phi1 env)
(= op 'U) (ltl-until input phi1 phi2 env)
(= op 'R) (ltl-release input phi1 phi2 env)
(= op 'G) (ltl-globally input phi1 env)
(= op 'F) (ltl-finally input phi1 env)
:else_ (throw (Exception.
(format "Unsupported operation: %s"
(first phi))))))
(ltl-boolean? phi)
(ltl-boolean input phi)
:else
(ltl-ap input phi)))
| 13924 | ;;; Copyright (C) 2012 <NAME>
;;;
;;; Licensed under The MIT License (see LICENSE)
(ns runver.ltl
(:use [matchure :only [cond-match]])
(:gen-class))
(def operators
^{:doc "Symbols representing LTL operators are mapped to their respective
precedence."}
{ '-> 1 'or 1 'and 2 'U 3 'R 3 'WX 3 'X 3 'G 3 'F 3 'not 4})
(def arity
{ '-> 2 'or 2 'and 2 'U 2 'R 2 'WX 1 'X 1 'G 1 'F 1 'not 1})
(defn is-operator? [x]
(some #{x} (keys operators)))
(def is-operand? (comp not is-operator?))
(def precedence operators)
(defn infix-to-postfix
"Converts an LTL expression given in usual infix syntax to postfix syntax
(RPN). This function implements Dijkstra's shunting-yard algorithm."
[expr]
(loop [expr expr
stack []
out []]
(cond (not (coll? expr))
expr
(empty? expr)
(concat out (reverse stack))
(coll? (first expr))
(recur (rest expr) stack (concat out (infix-to-postfix
(first expr))))
(is-operand? (first expr))
(recur (rest expr) stack (conj out (first expr)))
(empty? stack)
(recur (rest expr) (conj stack (first expr)) out)
(> (precedence (peek stack)) (precedence (first expr)))
(recur expr (pop stack) (conj out (peek stack)))
:else
(recur (rest expr) (conj stack (first expr)) out))))
(defn peek-n
"Returns the first n items from the given stack."
[stack n]
(loop [n n
vals []
stack stack]
(if (= n 0) (reverse vals)
(recur (dec n) (conj vals (peek stack)) (pop stack)))))
(defn pop-n
"Returns the given stack with the first n items removed."
[stack n]
(loop [n n
stack stack]
(if (= n 0) stack
(recur (dec n) (pop stack)))))
(defn postfix-to-prefix
"Converts an LTL expression given in RPN into prefix notation by performing
a 'pseudo evaluation'."
[expr]
(loop [expr expr
stack []]
(cond (not (coll? expr))
expr
(empty? expr)
(peek stack)
(is-operator? (first expr))
(recur (rest expr)
(conj (pop-n stack (arity (first expr)))
(conj (peek-n stack (arity (first expr)))
(first expr))))
:else
(recur (rest expr) (conj stack (first expr))))))
(def infix-to-prefix (comp postfix-to-prefix infix-to-postfix))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Defining the LTL truth domain, i.e. constants, order (which is ;;;;
;;;; linear), meet/join operations and the dual elements ;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def top 'top)
(def bot 'bot)
(def ? '?) ;; LTL3-specific value
(def p_top 'p_top) ;; LTL4-specific value
(def p_bot 'p_bot) ;; LTL4-specific value
(defn ltl-boolean? [x]
(some #{x} [bot top ? p_top p_bot]))
(defn final-value?
"Returns true if the given argument is a final value. A final value
is either top or bottom."
[x]
(or (= x top) (= x bot)))
(let [ltl3-order { top 3 ? 2 bot 1 }
ltl4-order { top 3 p_top 2 p_bot 2 bot 1 }]
(defn ltl-meet [arg1 arg2 env]
(if (= (:logic env) 'ltl3)
(min-key ltl3-order arg1 arg2) ; ltl3
(if (or (= [arg1 arg2] [p_top p_bot]) ; ltl4
(= [arg1 arg2] [p_bot p_top]))
bot
(min-key ltl4-order arg1 arg2))))
(defn ltl-join [arg1 arg2 env]
(if (= (:logic env) 'ltl3)
(min-key ltl3-order arg1 arg2)
(if (or (= [arg1 arg2] [p_top p_bot])
(= [arg1 arg2] [p_bot p_top]))
top
(max-key ltl4-order arg1 arg2)))))
(def ltl-dual {top bot
bot top
? ?
p_top p_bot
p_bot p_top})
(defn simplify
"Simplifies a given LTL formula according to some rules."
;;; TODO: Use syntax-quote instead of manual calls to list etc.
[phi]
(letfn [(simplify-once [phi]
(if (not (coll? phi))
phi
(let [[fst phi1 phi2] phi]
(cond (= fst 'and)
(cond
;; rule: A1
(= phi1 bot) bot
;; rule: A2
(= phi2 bot) bot
;; rule: A3
(= phi1 top) (recur phi2)
;; rule: A4
(= phi2 top) (recur phi1)
;; rule A5
:else
(list 'and
(simplify-once phi1)
(simplify-once phi2)))
(= fst 'or)
(cond
;; rule: O1
(= phi1 bot) (recur phi2)
;; rule: O2
(= phi2 bot) (recur phi1)
;; rule: O3
(= phi1 top) top
;; rule: O4
(= phi2 top) top
;; rule O5
:else
(list 'or
(simplify-once phi1)
(simplify-once phi2)))
(= fst 'not)
(cond
;; rule: N1
(= phi1 top) bot
;; rule: N2
(= phi1 bot) top
;; rules: N3, N4
(and (coll? phi1) (or (= (first phi1) 'and)
(= (first phi1) 'or)))
(let [[op psi1 psi2] phi1]
(simplify-once
(list ({'or 'and 'and 'or} op)
(list 'not (simplify-once psi1))
(list 'not (simplify-once psi2)))))
;; rule: N5
(and (coll? phi1) (= (first phi1) 'not))
(recur (second phi1))
;; rule: N6
:else
(list 'not (simplify-once phi1)))
;; rule: U1
(= fst 'U)
(list 'U
(simplify-once phi1)
(simplify-once phi2))
:else
phi))))]
;; There are formulae which cannot be fully simplified in a single
;; iteration using the above rules (e.g. (and (not bot) phi1) will
;; result in (and top phi1)). Therefore simplify-once is applied
;; iteratively until the formula doesn't change in one iteration
;; (i.e. can't be simplified further)
(loop [prev-formula phi]
(let [simp-formula (simplify-once prev-formula)]
(if (not= prev-formula simp-formula)
(recur simp-formula)
simp-formula)))))
(defstruct monitor-result :value :formula)
(defmacro result [value formula]
`(struct monitor-result ~value ~formula))
(defn simplify-result
"Simplifies the formula of a result object and returns the updated
rseult, i.e. leaving the value field unchanged."
[{value :value formula :formula}]
(struct monitor-result value (simplify formula)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; LTL evaluation functions ;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; All evaluation functions have an env-parameter which is currently only
;;; used to signal whether LTL3 or LTL4 is used, but it could be used for
;;; other options as well.
(declare ltl-eval)
(defn ltl-ap [input ap]
(if (some #{ap} input) (result top top) (result bot bot)))
(defn ltl-not [input phi env]
(let [ev-phi (ltl-eval input phi env)]
(result (ltl-dual (:value ev-phi))
`(~'not ~(:formula ev-phi)))))
(defn ltl-next [input phi env]
(if (= (:logic env) 'ltl4)
(result p_bot phi) ; ltl4
(result ? phi))) ; ltl3
(defn ltl-weaknext [input phi env]
(ltl-eval input `(~'not (~'X (~'not ~phi))) env))
;; (if (= (:logic env) 'ltl4)
;; (result p_top phi) ; ltl4
;; (result ? phi))) ; ltl3
(defn ltl-until [input phi1 phi2 env]
(let [new-formula `(~'or ~phi2 (~'and ~phi1 (~'X (~'U ~phi1 ~phi2))))]
(ltl-eval input new-formula env)))
(defn ltl-release [input phi1 phi2 env]
(ltl-eval input `(~'not (~'U (~'not ~phi1) (~'not ~phi2))) env))
(defn ltl-globally [input phi env]
(ltl-eval input `(~'R ~bot ~phi) env))
(defn ltl-finally [input phi env]
(ltl-eval input `(~'U ~top ~phi) env))
(defn ltl-and [input phi1 phi2 env]
(let [ev-phi1 (ltl-eval input phi1 env)]
(if (= (:value ev-phi1) top)
(ltl-eval input phi2 env)
(let [ev-phi2 (ltl-eval input phi2 env)
meet (ltl-meet (:value ev-phi1) (:value ev-phi2) env)]
(cond (final-value? meet) (result meet meet)
:else (result meet (list 'and (:formula ev-phi1)
(:formula ev-phi2))))))))
;; in order to improve performance it might be better to implement
;; ltl-or and ltl-impl independently and not in terms of other functions
(defn ltl-or [input phi1 phi2 env]
(ltl-eval input `(~'not (~'and (~'not ~phi1) (~'not ~phi2))) env))
(defn ltl-impl [input phi1 phi2 env]
(ltl-eval input `(~'or (~'not ~phi1) ~phi2) env))
(defn ltl-boolean [input val]
(result val val))
(defn ltl-evaluator
"Online-evaluation of infinite traces *without* automata. This function
returns a closure acting as monitor which can be called with the
continuation of the trace (which may be non-finite). When the given
formula can be fully evaluated, either top or bot is returned, otherwise
? is returned (i.e. in cases like p and X phi)."
[formula logic]
(let [formula (atom (infix-to-prefix formula))]
(fn [& input]
(let [res (ltl-eval input @formula {:logic logic})
s-res (simplify-result res)] ; simplified result
(compare-and-set! formula @formula (:formula s-res))
s-res))))
(defn ltl-eval [input phi env]
(cond (coll? phi)
(let [[op phi1 phi2] phi]
(cond (= op 'and) (ltl-and input phi1 phi2 env)
(= op' or) (ltl-or input phi1 phi2 env)
(= op '->) (ltl-impl input phi1 phi2 env)
(= op 'not) (ltl-not input phi1 env)
(= op 'WX) (ltl-weaknext input phi1 env)
(= op 'X) (ltl-next input phi1 env)
(= op 'U) (ltl-until input phi1 phi2 env)
(= op 'R) (ltl-release input phi1 phi2 env)
(= op 'G) (ltl-globally input phi1 env)
(= op 'F) (ltl-finally input phi1 env)
:else_ (throw (Exception.
(format "Unsupported operation: %s"
(first phi))))))
(ltl-boolean? phi)
(ltl-boolean input phi)
:else
(ltl-ap input phi)))
| true | ;;; Copyright (C) 2012 PI:NAME:<NAME>END_PI
;;;
;;; Licensed under The MIT License (see LICENSE)
(ns runver.ltl
(:use [matchure :only [cond-match]])
(:gen-class))
(def operators
^{:doc "Symbols representing LTL operators are mapped to their respective
precedence."}
{ '-> 1 'or 1 'and 2 'U 3 'R 3 'WX 3 'X 3 'G 3 'F 3 'not 4})
(def arity
{ '-> 2 'or 2 'and 2 'U 2 'R 2 'WX 1 'X 1 'G 1 'F 1 'not 1})
(defn is-operator? [x]
(some #{x} (keys operators)))
(def is-operand? (comp not is-operator?))
(def precedence operators)
(defn infix-to-postfix
"Converts an LTL expression given in usual infix syntax to postfix syntax
(RPN). This function implements Dijkstra's shunting-yard algorithm."
[expr]
(loop [expr expr
stack []
out []]
(cond (not (coll? expr))
expr
(empty? expr)
(concat out (reverse stack))
(coll? (first expr))
(recur (rest expr) stack (concat out (infix-to-postfix
(first expr))))
(is-operand? (first expr))
(recur (rest expr) stack (conj out (first expr)))
(empty? stack)
(recur (rest expr) (conj stack (first expr)) out)
(> (precedence (peek stack)) (precedence (first expr)))
(recur expr (pop stack) (conj out (peek stack)))
:else
(recur (rest expr) (conj stack (first expr)) out))))
(defn peek-n
"Returns the first n items from the given stack."
[stack n]
(loop [n n
vals []
stack stack]
(if (= n 0) (reverse vals)
(recur (dec n) (conj vals (peek stack)) (pop stack)))))
(defn pop-n
"Returns the given stack with the first n items removed."
[stack n]
(loop [n n
stack stack]
(if (= n 0) stack
(recur (dec n) (pop stack)))))
(defn postfix-to-prefix
"Converts an LTL expression given in RPN into prefix notation by performing
a 'pseudo evaluation'."
[expr]
(loop [expr expr
stack []]
(cond (not (coll? expr))
expr
(empty? expr)
(peek stack)
(is-operator? (first expr))
(recur (rest expr)
(conj (pop-n stack (arity (first expr)))
(conj (peek-n stack (arity (first expr)))
(first expr))))
:else
(recur (rest expr) (conj stack (first expr))))))
(def infix-to-prefix (comp postfix-to-prefix infix-to-postfix))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Defining the LTL truth domain, i.e. constants, order (which is ;;;;
;;;; linear), meet/join operations and the dual elements ;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def top 'top)
(def bot 'bot)
(def ? '?) ;; LTL3-specific value
(def p_top 'p_top) ;; LTL4-specific value
(def p_bot 'p_bot) ;; LTL4-specific value
(defn ltl-boolean? [x]
(some #{x} [bot top ? p_top p_bot]))
(defn final-value?
"Returns true if the given argument is a final value. A final value
is either top or bottom."
[x]
(or (= x top) (= x bot)))
(let [ltl3-order { top 3 ? 2 bot 1 }
ltl4-order { top 3 p_top 2 p_bot 2 bot 1 }]
(defn ltl-meet [arg1 arg2 env]
(if (= (:logic env) 'ltl3)
(min-key ltl3-order arg1 arg2) ; ltl3
(if (or (= [arg1 arg2] [p_top p_bot]) ; ltl4
(= [arg1 arg2] [p_bot p_top]))
bot
(min-key ltl4-order arg1 arg2))))
(defn ltl-join [arg1 arg2 env]
(if (= (:logic env) 'ltl3)
(min-key ltl3-order arg1 arg2)
(if (or (= [arg1 arg2] [p_top p_bot])
(= [arg1 arg2] [p_bot p_top]))
top
(max-key ltl4-order arg1 arg2)))))
(def ltl-dual {top bot
bot top
? ?
p_top p_bot
p_bot p_top})
(defn simplify
"Simplifies a given LTL formula according to some rules."
;;; TODO: Use syntax-quote instead of manual calls to list etc.
[phi]
(letfn [(simplify-once [phi]
(if (not (coll? phi))
phi
(let [[fst phi1 phi2] phi]
(cond (= fst 'and)
(cond
;; rule: A1
(= phi1 bot) bot
;; rule: A2
(= phi2 bot) bot
;; rule: A3
(= phi1 top) (recur phi2)
;; rule: A4
(= phi2 top) (recur phi1)
;; rule A5
:else
(list 'and
(simplify-once phi1)
(simplify-once phi2)))
(= fst 'or)
(cond
;; rule: O1
(= phi1 bot) (recur phi2)
;; rule: O2
(= phi2 bot) (recur phi1)
;; rule: O3
(= phi1 top) top
;; rule: O4
(= phi2 top) top
;; rule O5
:else
(list 'or
(simplify-once phi1)
(simplify-once phi2)))
(= fst 'not)
(cond
;; rule: N1
(= phi1 top) bot
;; rule: N2
(= phi1 bot) top
;; rules: N3, N4
(and (coll? phi1) (or (= (first phi1) 'and)
(= (first phi1) 'or)))
(let [[op psi1 psi2] phi1]
(simplify-once
(list ({'or 'and 'and 'or} op)
(list 'not (simplify-once psi1))
(list 'not (simplify-once psi2)))))
;; rule: N5
(and (coll? phi1) (= (first phi1) 'not))
(recur (second phi1))
;; rule: N6
:else
(list 'not (simplify-once phi1)))
;; rule: U1
(= fst 'U)
(list 'U
(simplify-once phi1)
(simplify-once phi2))
:else
phi))))]
;; There are formulae which cannot be fully simplified in a single
;; iteration using the above rules (e.g. (and (not bot) phi1) will
;; result in (and top phi1)). Therefore simplify-once is applied
;; iteratively until the formula doesn't change in one iteration
;; (i.e. can't be simplified further)
(loop [prev-formula phi]
(let [simp-formula (simplify-once prev-formula)]
(if (not= prev-formula simp-formula)
(recur simp-formula)
simp-formula)))))
(defstruct monitor-result :value :formula)
(defmacro result [value formula]
`(struct monitor-result ~value ~formula))
(defn simplify-result
"Simplifies the formula of a result object and returns the updated
rseult, i.e. leaving the value field unchanged."
[{value :value formula :formula}]
(struct monitor-result value (simplify formula)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; LTL evaluation functions ;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; All evaluation functions have an env-parameter which is currently only
;;; used to signal whether LTL3 or LTL4 is used, but it could be used for
;;; other options as well.
(declare ltl-eval)
(defn ltl-ap [input ap]
(if (some #{ap} input) (result top top) (result bot bot)))
(defn ltl-not [input phi env]
(let [ev-phi (ltl-eval input phi env)]
(result (ltl-dual (:value ev-phi))
`(~'not ~(:formula ev-phi)))))
(defn ltl-next [input phi env]
(if (= (:logic env) 'ltl4)
(result p_bot phi) ; ltl4
(result ? phi))) ; ltl3
(defn ltl-weaknext [input phi env]
(ltl-eval input `(~'not (~'X (~'not ~phi))) env))
;; (if (= (:logic env) 'ltl4)
;; (result p_top phi) ; ltl4
;; (result ? phi))) ; ltl3
(defn ltl-until [input phi1 phi2 env]
(let [new-formula `(~'or ~phi2 (~'and ~phi1 (~'X (~'U ~phi1 ~phi2))))]
(ltl-eval input new-formula env)))
(defn ltl-release [input phi1 phi2 env]
(ltl-eval input `(~'not (~'U (~'not ~phi1) (~'not ~phi2))) env))
(defn ltl-globally [input phi env]
(ltl-eval input `(~'R ~bot ~phi) env))
(defn ltl-finally [input phi env]
(ltl-eval input `(~'U ~top ~phi) env))
(defn ltl-and [input phi1 phi2 env]
(let [ev-phi1 (ltl-eval input phi1 env)]
(if (= (:value ev-phi1) top)
(ltl-eval input phi2 env)
(let [ev-phi2 (ltl-eval input phi2 env)
meet (ltl-meet (:value ev-phi1) (:value ev-phi2) env)]
(cond (final-value? meet) (result meet meet)
:else (result meet (list 'and (:formula ev-phi1)
(:formula ev-phi2))))))))
;; in order to improve performance it might be better to implement
;; ltl-or and ltl-impl independently and not in terms of other functions
(defn ltl-or [input phi1 phi2 env]
(ltl-eval input `(~'not (~'and (~'not ~phi1) (~'not ~phi2))) env))
(defn ltl-impl [input phi1 phi2 env]
(ltl-eval input `(~'or (~'not ~phi1) ~phi2) env))
(defn ltl-boolean [input val]
(result val val))
(defn ltl-evaluator
"Online-evaluation of infinite traces *without* automata. This function
returns a closure acting as monitor which can be called with the
continuation of the trace (which may be non-finite). When the given
formula can be fully evaluated, either top or bot is returned, otherwise
? is returned (i.e. in cases like p and X phi)."
[formula logic]
(let [formula (atom (infix-to-prefix formula))]
(fn [& input]
(let [res (ltl-eval input @formula {:logic logic})
s-res (simplify-result res)] ; simplified result
(compare-and-set! formula @formula (:formula s-res))
s-res))))
(defn ltl-eval [input phi env]
(cond (coll? phi)
(let [[op phi1 phi2] phi]
(cond (= op 'and) (ltl-and input phi1 phi2 env)
(= op' or) (ltl-or input phi1 phi2 env)
(= op '->) (ltl-impl input phi1 phi2 env)
(= op 'not) (ltl-not input phi1 env)
(= op 'WX) (ltl-weaknext input phi1 env)
(= op 'X) (ltl-next input phi1 env)
(= op 'U) (ltl-until input phi1 phi2 env)
(= op 'R) (ltl-release input phi1 phi2 env)
(= op 'G) (ltl-globally input phi1 env)
(= op 'F) (ltl-finally input phi1 env)
:else_ (throw (Exception.
(format "Unsupported operation: %s"
(first phi))))))
(ltl-boolean? phi)
(ltl-boolean input phi)
:else
(ltl-ap input phi)))
|
[
{
"context": "y-queue)}]\n (dosync\n (chega-em! hospital \"guilherme\")\n (chega-em! hospital \"maria\")\n (chega",
"end": 908,
"score": 0.9531846046447754,
"start": 899,
"tag": "NAME",
"value": "guilherme"
},
{
"context": " hospital \"guilherme\")\n (chega-em! hospital \"maria\")\n (chega-em! hospital \"lucia\")\n (chega",
"end": 943,
"score": 0.9995756149291992,
"start": 938,
"tag": "NAME",
"value": "maria"
},
{
"context": "-em! hospital \"maria\")\n (chega-em! hospital \"lucia\")\n (chega-em! hospital \"daniela\")\n (che",
"end": 978,
"score": 0.9996561408042908,
"start": 973,
"tag": "NAME",
"value": "lucia"
},
{
"context": "-em! hospital \"lucia\")\n (chega-em! hospital \"daniela\")\n (chega-em! hospital \"ana\")\n ; (c",
"end": 1015,
"score": 0.9995735883712769,
"start": 1008,
"tag": "NAME",
"value": "daniela"
},
{
"context": "m! hospital \"daniela\")\n (chega-em! hospital \"ana\")\n ; (chega-em! hospital \"paulo\")\n ",
"end": 1048,
"score": 0.9710190892219543,
"start": 1045,
"tag": "NAME",
"value": "ana"
},
{
"context": " hospital \"ana\")\n ; (chega-em! hospital \"paulo\")\n )\n (pprint hospital)))\n\n;(simula-um-di",
"end": 1089,
"score": 0.8757238388061523,
"start": 1084,
"tag": "NAME",
"value": "paulo"
}
] | curso3/src/hospital/aula6.clj | Caporiccii/Clojure-Class | 0 | (ns hospital.aula6
(:use [clojure.pprint])
(:require [hospital.model :as h.model]))
(defn cabe-na-fila? [fila]
(-> fila
count
(< 5)))
(defn chega-em [fila pessoa]
(if (cabe-na-fila? fila)
(conj fila pessoa)
(throw (ex-info "Fila tá foda parceiro" {:tentando-adicionar pessoa}))))
(defn chega-em!
"troca de referencia via ref-set"
[hospital pessoa]
(let [fila (get hospital :espera)]
(ref-set fila (chega-em @fila pessoa))))
(defn chega-em!
"troca de referencia via"
[hospital pessoa]
(let [fila (get hospital :espera)]
(alter fila chega-em pessoa)))
(defn simula-um-dia []
(let [hospital {:espera (ref h.model/empty-queue)
:laboratorio1 (ref h.model/empty-queue)
:laboratorio2 (ref h.model/empty-queue)
:laboratorio3 (ref h.model/empty-queue)}]
(dosync
(chega-em! hospital "guilherme")
(chega-em! hospital "maria")
(chega-em! hospital "lucia")
(chega-em! hospital "daniela")
(chega-em! hospital "ana")
; (chega-em! hospital "paulo")
)
(pprint hospital)))
;(simula-um-dia)
(defn chega-em-async! [hospital pessoa]
(future
(Thread/sleep (rand 5000))
(dosync
(println "Tentando codigo sincronizado" pessoa)
(chega-em! hospital pessoa))))
(defn simula-um-dia-async []
(let [hospital {:espera (ref h.model/empty-queue)
:laboratorio1 (ref h.model/empty-queue)
:laboratorio2 (ref h.model/empty-queue)
:laboratorio3 (ref h.model/empty-queue)}]
(dotimes [pessoa 10]
(chega-em-async! hospital pessoa))
(future
(Thread/sleep 8000)
(pprint hospital))))
;(simula-um-dia-async)
(defn simula-um-dia-async []
(let [hospital {:espera (ref h.model/empty-queue)
:laboratorio1 (ref h.model/empty-queue)
:laboratorio2 (ref h.model/empty-queue)
:laboratorio3 (ref h.model/empty-queue)}
futures (mapv #(chega-em-async! hospital %) (range 10))]
(future
(dotimes [n 4]
(Thread/sleep 2000)
(pprint hospital)
(pprint futures)))
))
(defn simula-um-dia-async []
(let [hospital {:espera (ref h.model/empty-queue)
:laboratorio1 (ref h.model/empty-queue)
:laboratorio2 (ref h.model/empty-queue)
:laboratorio3 (ref h.model/empty-queue)}]
;global só pra olhar as exceptions no repl
(def futures (mapv #(chega-em-async! hospital %) (range 10)))
(future
(dotimes [n 4]
(Thread/sleep 2000)
(pprint hospital)
(pprint futures)))
))
(simula-um-dia-async)
;(println (future 15))
;(println (future ((Thread/sleep 1000) 15))) | 4381 | (ns hospital.aula6
(:use [clojure.pprint])
(:require [hospital.model :as h.model]))
(defn cabe-na-fila? [fila]
(-> fila
count
(< 5)))
(defn chega-em [fila pessoa]
(if (cabe-na-fila? fila)
(conj fila pessoa)
(throw (ex-info "Fila tá foda parceiro" {:tentando-adicionar pessoa}))))
(defn chega-em!
"troca de referencia via ref-set"
[hospital pessoa]
(let [fila (get hospital :espera)]
(ref-set fila (chega-em @fila pessoa))))
(defn chega-em!
"troca de referencia via"
[hospital pessoa]
(let [fila (get hospital :espera)]
(alter fila chega-em pessoa)))
(defn simula-um-dia []
(let [hospital {:espera (ref h.model/empty-queue)
:laboratorio1 (ref h.model/empty-queue)
:laboratorio2 (ref h.model/empty-queue)
:laboratorio3 (ref h.model/empty-queue)}]
(dosync
(chega-em! hospital "<NAME>")
(chega-em! hospital "<NAME>")
(chega-em! hospital "<NAME>")
(chega-em! hospital "<NAME>")
(chega-em! hospital "<NAME>")
; (chega-em! hospital "<NAME>")
)
(pprint hospital)))
;(simula-um-dia)
(defn chega-em-async! [hospital pessoa]
(future
(Thread/sleep (rand 5000))
(dosync
(println "Tentando codigo sincronizado" pessoa)
(chega-em! hospital pessoa))))
(defn simula-um-dia-async []
(let [hospital {:espera (ref h.model/empty-queue)
:laboratorio1 (ref h.model/empty-queue)
:laboratorio2 (ref h.model/empty-queue)
:laboratorio3 (ref h.model/empty-queue)}]
(dotimes [pessoa 10]
(chega-em-async! hospital pessoa))
(future
(Thread/sleep 8000)
(pprint hospital))))
;(simula-um-dia-async)
(defn simula-um-dia-async []
(let [hospital {:espera (ref h.model/empty-queue)
:laboratorio1 (ref h.model/empty-queue)
:laboratorio2 (ref h.model/empty-queue)
:laboratorio3 (ref h.model/empty-queue)}
futures (mapv #(chega-em-async! hospital %) (range 10))]
(future
(dotimes [n 4]
(Thread/sleep 2000)
(pprint hospital)
(pprint futures)))
))
(defn simula-um-dia-async []
(let [hospital {:espera (ref h.model/empty-queue)
:laboratorio1 (ref h.model/empty-queue)
:laboratorio2 (ref h.model/empty-queue)
:laboratorio3 (ref h.model/empty-queue)}]
;global só pra olhar as exceptions no repl
(def futures (mapv #(chega-em-async! hospital %) (range 10)))
(future
(dotimes [n 4]
(Thread/sleep 2000)
(pprint hospital)
(pprint futures)))
))
(simula-um-dia-async)
;(println (future 15))
;(println (future ((Thread/sleep 1000) 15))) | true | (ns hospital.aula6
(:use [clojure.pprint])
(:require [hospital.model :as h.model]))
(defn cabe-na-fila? [fila]
(-> fila
count
(< 5)))
(defn chega-em [fila pessoa]
(if (cabe-na-fila? fila)
(conj fila pessoa)
(throw (ex-info "Fila tá foda parceiro" {:tentando-adicionar pessoa}))))
(defn chega-em!
"troca de referencia via ref-set"
[hospital pessoa]
(let [fila (get hospital :espera)]
(ref-set fila (chega-em @fila pessoa))))
(defn chega-em!
"troca de referencia via"
[hospital pessoa]
(let [fila (get hospital :espera)]
(alter fila chega-em pessoa)))
(defn simula-um-dia []
(let [hospital {:espera (ref h.model/empty-queue)
:laboratorio1 (ref h.model/empty-queue)
:laboratorio2 (ref h.model/empty-queue)
:laboratorio3 (ref h.model/empty-queue)}]
(dosync
(chega-em! hospital "PI:NAME:<NAME>END_PI")
(chega-em! hospital "PI:NAME:<NAME>END_PI")
(chega-em! hospital "PI:NAME:<NAME>END_PI")
(chega-em! hospital "PI:NAME:<NAME>END_PI")
(chega-em! hospital "PI:NAME:<NAME>END_PI")
; (chega-em! hospital "PI:NAME:<NAME>END_PI")
)
(pprint hospital)))
;(simula-um-dia)
(defn chega-em-async! [hospital pessoa]
(future
(Thread/sleep (rand 5000))
(dosync
(println "Tentando codigo sincronizado" pessoa)
(chega-em! hospital pessoa))))
(defn simula-um-dia-async []
(let [hospital {:espera (ref h.model/empty-queue)
:laboratorio1 (ref h.model/empty-queue)
:laboratorio2 (ref h.model/empty-queue)
:laboratorio3 (ref h.model/empty-queue)}]
(dotimes [pessoa 10]
(chega-em-async! hospital pessoa))
(future
(Thread/sleep 8000)
(pprint hospital))))
;(simula-um-dia-async)
(defn simula-um-dia-async []
(let [hospital {:espera (ref h.model/empty-queue)
:laboratorio1 (ref h.model/empty-queue)
:laboratorio2 (ref h.model/empty-queue)
:laboratorio3 (ref h.model/empty-queue)}
futures (mapv #(chega-em-async! hospital %) (range 10))]
(future
(dotimes [n 4]
(Thread/sleep 2000)
(pprint hospital)
(pprint futures)))
))
(defn simula-um-dia-async []
(let [hospital {:espera (ref h.model/empty-queue)
:laboratorio1 (ref h.model/empty-queue)
:laboratorio2 (ref h.model/empty-queue)
:laboratorio3 (ref h.model/empty-queue)}]
;global só pra olhar as exceptions no repl
(def futures (mapv #(chega-em-async! hospital %) (range 10)))
(future
(dotimes [n 4]
(Thread/sleep 2000)
(pprint hospital)
(pprint futures)))
))
(simula-um-dia-async)
;(println (future 15))
;(println (future ((Thread/sleep 1000) 15))) |
[
{
"context": "nds this to the REPL\n(foo \"Somebody else\")\n\n(foo \"Felix\")\n\n(defn average\n \"I am a documentatio string he",
"end": 212,
"score": 0.9996911287307739,
"start": 207,
"tag": "NAME",
"value": "Felix"
}
] | backups/clojure-backup/playground/src/playground/core.clj | roskenet/Playground | 0 | (ns playground.core)
(defn foo
"I don't do a whole lot."
[x]
(println "Hello this is", x))
;Alt+Shift+L loads this file into the REPL
;Alt+Shift+P sends this to the REPL
(foo "Somebody else")
(foo "Felix")
(defn average
"I am a documentatio string here!"
[numbers]
(/ (apply + numbers) (count numbers)))
| 32307 | (ns playground.core)
(defn foo
"I don't do a whole lot."
[x]
(println "Hello this is", x))
;Alt+Shift+L loads this file into the REPL
;Alt+Shift+P sends this to the REPL
(foo "Somebody else")
(foo "<NAME>")
(defn average
"I am a documentatio string here!"
[numbers]
(/ (apply + numbers) (count numbers)))
| true | (ns playground.core)
(defn foo
"I don't do a whole lot."
[x]
(println "Hello this is", x))
;Alt+Shift+L loads this file into the REPL
;Alt+Shift+P sends this to the REPL
(foo "Somebody else")
(foo "PI:NAME:<NAME>END_PI")
(defn average
"I am a documentatio string here!"
[numbers]
(/ (apply + numbers) (count numbers)))
|
[
{
"context": " (first (:deck (get-runner))))))\n (is (= \"Corroder\" (:title (second (:deck (get-runner))))))\n ",
"end": 9885,
"score": 0.510136604309082,
"start": 9883,
"tag": "NAME",
"value": "ro"
},
{
"context": "le (second (:deck (get-runner))))))\n (is (= \"Patron\" (:title (second (rest (:deck (get-runner)))))))\n",
"end": 9951,
"score": 0.8514282703399658,
"start": 9945,
"tag": "NAME",
"value": "Patron"
},
{
"context": "2 (count (:discard (get-runner)))))\n (is (= \"Corroder\" (:title (first (:deck (get-runner)))))))))\n\n(",
"end": 10268,
"score": 0.6233339309692383,
"start": 10263,
"tag": "NAME",
"value": "Corro"
},
{
"context": " (new-game (default-corp [(qty \"Shiro\" 1) (qty \"Caprice Nisei\" 1)\n (qty \"Quandary\" ",
"end": 28030,
"score": 0.9898483157157898,
"start": 28017,
"tag": "NAME",
"value": "Caprice Nisei"
},
{
"context": "rice Nisei\" 1)\n (qty \"Quandary\" 1) (qty \"Jackson Howard\" 1)])\n (def",
"end": 28078,
"score": 0.7382550239562988,
"start": 28070,
"tag": "NAME",
"value": "Quandary"
},
{
"context": " (qty \"Quandary\" 1) (qty \"Jackson Howard\" 1)])\n (default-runner [(qty \"R&D In",
"end": 28103,
"score": 0.9996566772460938,
"start": 28089,
"tag": "NAME",
"value": "Jackson Howard"
},
{
"context": "p shiro 0)\n (prompt-choice :corp (find-card \"Caprice Nisei\" (:deck (get-corp))))\n (prompt-choice :corp ",
"end": 28533,
"score": 0.9993278384208679,
"start": 28520,
"tag": "NAME",
"value": "Caprice Nisei"
},
{
"context": "corp))))\n (prompt-choice :corp (find-card \"Quandary\" (:deck (get-corp))))\n (prompt-choice :corp ",
"end": 28603,
"score": 0.6633484363555908,
"start": 28597,
"tag": "NAME",
"value": "andary"
},
{
"context": "t-corp))))\n (prompt-choice :corp (find-card \"Jackson Howard\" (:deck (get-corp))))\n ;; try starting over\n",
"end": 28679,
"score": 0.9994970560073853,
"start": 28665,
"tag": "NAME",
"value": "Jackson Howard"
},
{
"context": "art over\")\n (prompt-choice :corp (find-card \"Jackson Howard\" (:deck (get-corp))))\n (prompt-choice :corp ",
"end": 28823,
"score": 0.9998278021812439,
"start": 28809,
"tag": "NAME",
"value": "Jackson Howard"
},
{
"context": "t-corp))))\n (prompt-choice :corp (find-card \"Quandary\" (:deck (get-corp))))\n (prompt-choice :corp ",
"end": 28893,
"score": 0.9963898062705994,
"start": 28885,
"tag": "NAME",
"value": "Quandary"
},
{
"context": "t-corp))))\n (prompt-choice :corp (find-card \"Caprice Nisei\" (:deck (get-corp)))) ;this is the top card of R&",
"end": 28968,
"score": 0.9998589754104614,
"start": 28955,
"tag": "NAME",
"value": "Caprice Nisei"
},
{
"context": "\n (prompt-choice :corp \"Done\")\n (is (= \"Caprice Nisei\" (:title (first (:deck (get-corp))))))\n (is ",
"end": 29082,
"score": 0.9998694658279419,
"start": 29069,
"tag": "NAME",
"value": "Caprice Nisei"
},
{
"context": "title (first (:deck (get-corp))))))\n (is (= \"Quandary\" (:title (second (:deck (get-corp))))))\n (is",
"end": 29144,
"score": 0.9997802376747131,
"start": 29136,
"tag": "NAME",
"value": "Quandary"
},
{
"context": "itle (second (:deck (get-corp))))))\n (is (= \"Jackson Howard\" (:title (second (rest (:deck (get-corp)))))))\n ",
"end": 29213,
"score": 0.9998227953910828,
"start": 29199,
"tag": "NAME",
"value": "Jackson Howard"
}
] | src/clj/test/cards/ice.clj | erbridge/netrunner | 0 | (ns test.cards.ice
(:require [game.core :as core]
[game.utils :refer :all]
[test.core :refer :all]
[test.utils :refer :all]
[test.macros :refer :all]
[clojure.test :refer :all]))
(deftest end-the-run
;; Since all ETR ice share a common ability, we only need one test
(do-game
(new-game (default-corp [(qty "Ice Wall" 3) (qty "Hedge Fund" 3) (qty "Restructure" 2)])
(default-runner))
(play-from-hand state :corp "Ice Wall" "HQ")
(take-credits state :corp 2)
(run-on state "HQ")
(is (= [:hq] (get-in @state [:run :server])))
(let [iwall (get-ice state :hq 0)]
(core/rez state :corp iwall)
(card-subroutine state :corp iwall 0)
(is (not (:run @state)) "Run is ended")
(is (get-in @state [:runner :register :unsuccessful-run]) "Run was unsuccessful"))))
(deftest archangel
;; Archangel - accessing from R&D does not cause run to hang.
(do-game
(new-game (default-corp [(qty "Archangel" 1) (qty "Hedge Fund" 1)])
(default-runner [(qty "Bank Job" 1)]))
(starting-hand state :corp ["Hedge Fund"])
(take-credits state :corp)
(play-from-hand state :runner "Bank Job")
(run-empty-server state :rd)
(prompt-choice :corp "Yes")
(prompt-choice :runner "Yes")
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(prompt-select :corp (get-resource state 0))
(prompt-choice :runner "OK")
(is (not (:run @state)) "Run ended")))
(deftest architect-untrashable
;; Architect is untrashable while installed and rezzed, but trashable if derezzed or from HQ
(do-game
(new-game (default-corp [(qty "Architect" 3)])
(default-runner))
(play-from-hand state :corp "Architect" "HQ")
(let [architect (get-ice state :hq 0)]
(core/rez state :corp architect)
(core/trash state :corp (refresh architect))
(is (not= nil (get-ice state :hq 0)) "Architect was trashed, but should be untrashable")
(core/derez state :corp (refresh architect))
(core/trash state :corp (refresh architect))
(is (= nil (get-ice state :hq 0)) "Architect was not trashed, but should be trashable")
(core/trash state :corp (get-in @state [:corp :hand 0]))
(is (= (get-in @state [:corp :discard 0 :title]) "Architect"))
(is (= (get-in @state [:corp :discard 1 :title]) "Architect")))))
(deftest asteroid-belt
;; Asteroid Belt - Space ICE rez cost reduced by 3 credits per advancement
(do-game
(new-game (default-corp [(qty "Asteroid Belt" 1)])
(default-runner))
(core/gain state :corp :credit 5)
(play-from-hand state :corp "Asteroid Belt" "HQ")
(let [ab (get-ice state :hq 0)]
(core/advance state :corp {:card (refresh ab)})
(core/advance state :corp {:card (refresh ab)})
(is (= 8 (:credit (get-corp))))
(is (= 2 (:advance-counter (refresh ab))))
(core/rez state :corp (refresh ab))
(is (= 5 (:credit (get-corp))) "Paid 3 credits to rez; 2 advancments on Asteroid Belt"))))
(deftest bandwidth
;; Bandwidth - Give the Runner 1 tag; remove 1 tag if the run is successful
(do-game
(new-game (default-corp [(qty "Bandwidth" 1)])
(default-runner))
(play-from-hand state :corp "Bandwidth" "Archives")
(let [bw (get-ice state :archives 0)]
(take-credits state :corp)
(run-on state "Archives")
(core/rez state :corp bw)
(card-subroutine state :corp bw 0)
(is (= 1 (:tag (get-runner))) "Runner took 1 tag")
(run-successful state)
(is (= 0 (:tag (get-runner))) "Run successful; Runner lost 1 tag")
(run-on state "Archives")
(card-subroutine state :corp bw 0)
(is (= 1 (:tag (get-runner))) "Runner took 1 tag")
(run-jack-out state)
(is (= 1 (:tag (get-runner))) "Run unsuccessful; Runner kept 1 tag"))))
(deftest bullfrog
;; Bullfrog - Win psi to move to outermost position of another server and continue run there
(do-game
(new-game (default-corp [(qty "Bullfrog" 1) (qty "Pup" 2)])
(default-runner))
(play-from-hand state :corp "Bullfrog" "HQ")
(play-from-hand state :corp "Pup" "R&D")
(play-from-hand state :corp "Pup" "R&D")
(take-credits state :corp)
(run-on state :hq)
(let [frog (get-ice state :hq 0)]
(core/rez state :corp frog)
(is (= :hq (first (get-in @state [:run :server]))))
(card-subroutine state :corp frog 0)
(prompt-choice :corp "0 [Credits]")
(prompt-choice :runner "1 [Credits]")
(prompt-choice :corp "R&D")
(is (= :rd (first (get-in @state [:run :server]))) "Run redirected to R&D")
(is (= 2 (get-in @state [:run :position])) "Passed Bullfrog")
(is (= "Bullfrog" (:title (get-ice state :rd 2))) "Bullfrog at outermost position of R&D"))))
(deftest cell-portal
;; Cell Portal - Bounce Runner to outermost position and derez itself
(do-game
(new-game (default-corp [(qty "Cell Portal" 1) (qty "Paper Wall" 2)])
(default-runner))
(core/gain state :corp :credit 5)
(play-from-hand state :corp "Cell Portal" "HQ")
(play-from-hand state :corp "Paper Wall" "HQ")
(play-from-hand state :corp "Paper Wall" "HQ")
(take-credits state :corp)
(run-on state :hq)
(run-continue state)
(run-continue state)
(is (= 1 (get-in @state [:run :position])))
(let [cp (get-ice state :hq 0)]
(core/rez state :corp cp)
(card-subroutine state :corp cp 0)
(is (= 3 (get-in @state [:run :position])) "Run back at outermost position")
(is (not (get-in (refresh cp) [:rezzed])) "Cell Portal derezzed"))))
(deftest chimera
;; Chimera - Gains chosen subtype
(do-game
(new-game (default-corp [(qty "Chimera" 1)])
(default-runner))
(play-from-hand state :corp "Chimera" "HQ")
(let [ch (get-ice state :hq 0)]
(core/rez state :corp ch)
(prompt-choice :corp "Barrier")
(is (core/has-subtype? (refresh ch) "Barrier") "Chimera has barrier")
(take-credits state :corp)
(is (not (core/has-subtype? (refresh ch) "Barrier")) "Chimera does not have barrier"))))
(deftest cortex-lock
;; Cortex Lock - Do net damage equal to Runner's unused memory
(do-game
(new-game (default-corp [(qty "Cortex Lock" 1)])
(default-runner [(qty "Corroder" 2) (qty "Sure Gamble" 3)]))
(play-from-hand state :corp "Cortex Lock" "HQ")
(take-credits state :corp)
(let [cort (get-ice state :hq 0)]
(play-from-hand state :runner "Corroder")
(is (= 3 (:memory (get-runner))))
(run-on state "HQ")
(core/rez state :corp cort)
(card-subroutine state :corp cort 0)
(is (= 3 (count (:discard (get-runner)))) "Runner suffered 3 net damage"))))
(deftest crick
;; Crick - Strength boost when protecting Archives; installs a card from Archives
(do-game
(new-game (default-corp [(qty "Crick" 2) (qty "Ice Wall" 1)])
(default-runner))
(play-from-hand state :corp "Crick" "HQ")
(play-from-hand state :corp "Crick" "Archives")
(core/move state :corp (find-card "Ice Wall" (:hand (get-corp))) :discard)
(take-credits state :corp)
(let [cr1 (get-ice state :hq 0)
cr2 (get-ice state :archives 0)]
(core/rez state :corp cr1)
(core/rez state :corp cr2)
(is (= 3 (:current-strength (refresh cr1))) "Normal strength over HQ")
(is (= 6 (:current-strength (refresh cr2))) "+3 strength over Archives")
(card-subroutine state :corp cr2 0)
(prompt-select :corp (find-card "Ice Wall" (:discard (get-corp))))
(prompt-choice :corp "HQ")
(is (= 3 (:credit (get-corp))) "Paid 1 credit to install as 2nd ICE over HQ"))))
(deftest curtain-wall
;; Curtain Wall - Strength boost when outermost ICE
(do-game
(new-game (default-corp [(qty "Curtain Wall" 1) (qty "Paper Wall" 1)])
(default-runner))
(core/gain state :corp :credit 10)
(play-from-hand state :corp "Curtain Wall" "HQ")
(let [curt (get-ice state :hq 0)]
(core/rez state :corp curt)
(is (= 10 (:current-strength (refresh curt)))
"Curtain Wall has +4 strength as outermost ICE")
(play-from-hand state :corp "Paper Wall" "HQ")
(let [paper (get-ice state :hq 1)]
(core/rez state :corp paper)
(is (= 6 (:current-strength (refresh curt))) "Curtain Wall back to default 6 strength")))))
(deftest data-hound
;; Data Hound - Full test
(do-game
(new-game (default-corp [(qty "Data Hound" 1)])
(default-runner [(qty "Sure Gamble" 2) (qty "Desperado" 1)
(qty "Corroder" 1) (qty "Patron" 1)]))
(starting-hand state :runner ["Sure Gamble"]) ;move all other cards to stack
(play-from-hand state :corp "Data Hound" "HQ")
(take-credits state :corp)
(let [dh (get-ice state :hq 0)]
(run-on state "HQ")
(core/rez state :corp dh)
(card-subroutine state :corp dh 0)
(prompt-choice :corp 2)
(prompt-choice :runner 0)
;; trash 1 card and rearrange the other 3
(prompt-choice :corp (find-card "Desperado" (:deck (get-runner))))
(is (= 1 (count (:discard (get-runner)))))
(prompt-choice :corp (find-card "Sure Gamble" (:deck (get-runner))))
(prompt-choice :corp (find-card "Corroder" (:deck (get-runner))))
(prompt-choice :corp (find-card "Patron" (:deck (get-runner))))
;; try starting over
(prompt-choice :corp "Start over")
(prompt-choice :corp (find-card "Patron" (:deck (get-runner))))
(prompt-choice :corp (find-card "Corroder" (:deck (get-runner))))
(prompt-choice :corp (find-card "Sure Gamble" (:deck (get-runner)))) ;this is the top card on stack
(prompt-choice :corp "Done")
(is (= "Sure Gamble" (:title (first (:deck (get-runner))))))
(is (= "Corroder" (:title (second (:deck (get-runner))))))
(is (= "Patron" (:title (second (rest (:deck (get-runner)))))))
(run-jack-out state)
(run-on state "HQ")
(card-subroutine state :corp dh 0)
(prompt-choice :corp 0)
(prompt-choice :runner 1)
;; trash the only card automatically
(is (= 2 (count (:discard (get-runner)))))
(is (= "Corroder" (:title (first (:deck (get-runner)))))))))
(deftest draco
;; Dracō - Pay credits when rezzed to increase strength; trace to give 1 tag and end the run
(do-game
(new-game (default-corp [(qty "Dracō" 1)])
(default-runner))
(play-from-hand state :corp "Dracō" "HQ")
(take-credits state :corp)
(let [drac (get-ice state :hq 0)]
(run-on state "HQ")
(core/rez state :corp drac)
(prompt-choice :corp 4)
(is (= 4 (get-counters (refresh drac) :power)) "Dracō has 4 power counters")
(is (= 4 (:current-strength (refresh drac))) "Dracō is 4 strength")
(card-subroutine state :corp drac 0)
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (= 1 (:tag (get-runner))) "Runner took 1 tag")
(is (nil? (get-in @state [:run])) "Run was ended"))))
(deftest enigma
;; Enigma - Force Runner to lose 1 click if able
(do-game
(new-game (default-corp [(qty "Enigma" 1)])
(default-runner))
(play-from-hand state :corp "Enigma" "HQ")
(take-credits state :corp)
(let [enig (get-ice state :hq 0)]
(run-on state "HQ")
(is (= 3 (:click (get-runner))))
(core/rez state :corp enig)
(card-subroutine state :corp enig 0)
(is (= 2 (:click (get-runner))) "Runner lost 1 click"))))
(deftest excalibur
;; Excalibur - Prevent Runner from making another run this turn
(do-game
(new-game (default-corp [(qty "Excalibur" 1)])
(default-runner [(qty "Stimhack" 1)]))
(play-from-hand state :corp "Excalibur" "HQ")
(take-credits state :corp)
(let [excal (get-ice state :hq 0)]
(run-on state "HQ")
(core/rez state :corp excal)
(card-subroutine state :corp excal 0)
(run-jack-out state)
(run-on state "R&D")
(is (not (:run @state)) "No run initiated")
(is (= 3 (:click (get-runner))))
(play-from-hand state :runner "Stimhack")
(is (not (:run @state)) "No run initiated")
(is (= 3 (:click (get-runner))))
(is (empty? (:discard (get-runner))) "Card not played from Grip"))))
(deftest fenris
;; Fenris - Illicit ICE give Corp 1 bad publicity when rezzed
(do-game
(new-game (default-corp [(qty "Fenris" 1)])
(default-runner))
(play-from-hand state :corp "Fenris" "HQ")
(take-credits state :corp)
(let [fen (get-ice state :hq 0)]
(run-on state "HQ")
(core/rez state :corp fen)
(is (= 1 (:bad-publicity (get-corp))) "Gained 1 bad pub")
(card-subroutine state :corp fen 0)
(is (= 1 (:brain-damage (get-runner))) "Runner took 1 brain damage")
(is (= 1 (count (:discard (get-runner)))))
(is (= 4 (core/hand-size state :runner))))))
(deftest flare
;; Flare - Trash 1 program, do 2 unpreventable meat damage, and end the run
(do-game
(new-game (default-corp [(qty "Flare" 1)])
(default-runner [(qty "Plascrete Carapace" 1) (qty "Clone Chip" 1) (qty "Cache" 3)]))
(play-from-hand state :corp "Flare" "HQ")
(core/gain state :corp :credit 2)
(take-credits state :corp)
(play-from-hand state :runner "Plascrete Carapace")
(play-from-hand state :runner "Clone Chip")
(let [flare (get-ice state :hq 0)
cc (get-hardware state 1)]
(run-on state :hq)
(core/rez state :corp flare)
(card-subroutine state :corp flare 0)
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(prompt-select :corp cc)
(is (= 1 (count (get-in @state [:runner :rig :hardware]))) "Clone Chip trashed")
(is (empty? (:prompt (get-runner))) "Plascrete didn't try peventing meat damage")
(is (= 1 (count (:hand (get-runner)))))
(is (= 3 (count (:discard (get-runner)))) "Clone Chip plus 2 cards lost from damage in discard")
(is (not (:run @state)) "Run ended"))))
(deftest gemini-kicker
;; Gemini - Successfully trace to do 1 net damage; do 1 net damage if trace strength is 5 or more regardless of success
(do-game
(new-game (default-corp [(qty "Gemini" 1) (qty "Hedge Fund" 2)])
(default-runner [(qty "Sure Gamble" 3) (qty "Dirty Laundry" 2)]))
(play-from-hand state :corp "Gemini" "HQ")
(play-from-hand state :corp "Hedge Fund")
(play-from-hand state :corp "Hedge Fund")
(take-credits state :corp)
(let [gem (get-ice state :hq 0)]
(run-on state "HQ")
(core/rez state :corp gem)
(card-subroutine state :corp gem 0)
(prompt-choice :corp 3) ; boost to trace strength 5
(prompt-choice :runner 0)
(is (= 2 (count (:discard (get-runner)))) "Did 2 net damage")
(card-subroutine state :corp gem 0)
(prompt-choice :corp 3) ; boost to trace strength 5
(prompt-choice :runner 5) ; match trace
(is (= 3 (count (:discard (get-runner)))) "Did only 1 net damage for having trace strength 5 or more"))))
(deftest gemini-chronos-protocol
;; Gemini - Interaction with Chronos Protocol and kicker
(do-game
(new-game (make-deck "Chronos Protocol: Selective Mind-mapping" [(qty "Gemini" 1) (qty "Hedge Fund" 2)])
(default-runner [(qty "Sure Gamble" 1) (qty "Dirty Laundry" 2)]))
(play-from-hand state :corp "Gemini" "HQ")
(play-from-hand state :corp "Hedge Fund")
(play-from-hand state :corp "Hedge Fund")
(take-credits state :corp)
(let [gem (get-ice state :hq 0)]
(run-on state "HQ")
(core/rez state :corp gem)
(card-subroutine state :corp gem 0)
(prompt-choice :corp 3) ; boost to trace strength 5
(prompt-choice :runner 0)
(prompt-choice :corp "Yes")
(prompt-choice :corp (find-card "Sure Gamble" (:hand (get-runner))))
(is (= 2 (count (:discard (get-runner)))) "Did 2 net damage"))))
(deftest iq
;; IQ - Rez cost and strength equal to cards in HQ
(do-game
(new-game (default-corp [(qty "IQ" 3) (qty "Hedge Fund" 3)])
(default-runner))
(play-from-hand state :corp "Hedge Fund")
(play-from-hand state :corp "IQ" "R&D")
(let [iq1 (get-ice state :rd 0)]
(core/rez state :corp iq1)
(is (and (= 4 (count (:hand (get-corp))))
(= 4 (:current-strength (refresh iq1)))
(= 5 (:credit (get-corp)))) "4 cards in HQ: paid 4 to rez, has 4 strength")
(play-from-hand state :corp "IQ" "HQ")
(let [iq2 (get-ice state :hq 0)]
(core/rez state :corp iq2)
(is (and (= 3 (count (:hand (get-corp))))
(= 3 (:current-strength (refresh iq1)))
(= 3 (:current-strength (refresh iq2)))
(= 2 (:credit (get-corp)))) "3 cards in HQ: paid 3 to rez, both have 3 strength")))))
(deftest lockdown
;; Lockdown - Prevent Runner from drawing cards for the rest of the turn
(do-game
(new-game (default-corp [(qty "Lockdown" 1)])
(default-runner [(qty "Diesel" 2) (qty "Sure Gamble" 3)]))
(play-from-hand state :corp "Lockdown" "R&D")
(take-credits state :corp)
(core/move state :runner (find-card "Sure Gamble" (:hand (get-runner))) :deck)
(core/move state :runner (find-card "Sure Gamble" (:hand (get-runner))) :deck)
(core/move state :runner (find-card "Sure Gamble" (:hand (get-runner))) :deck)
(let [lock (get-ice state :rd 0)]
(run-on state "R&D")
(core/rez state :corp lock)
(card-subroutine state :corp lock 0)
(run-successful state)
(play-from-hand state :runner "Diesel")
(is (= 1 (count (:hand (get-runner)))) "No cards drawn")
(take-credits state :runner)
(take-credits state :corp)
(play-from-hand state :runner "Diesel")
(is (= 3 (count (:hand (get-runner))))
"New turn ends prevention; remaining 3 cards drawn from Stack"))))
(deftest lotus-field-unlowerable
;; Lotus Field strength cannot be lowered
(do-game
(new-game (default-corp [(qty "Lotus Field" 1) (qty "Lag Time" 1)])
(default-runner [(qty "Ice Carver" 1) (qty "Parasite" 1)]))
(play-from-hand state :corp "Lotus Field" "Archives")
(take-credits state :corp 2)
(let [lotus (get-ice state :archives 0)]
(core/rez state :corp lotus)
(play-from-hand state :runner "Ice Carver")
(run-on state "Archives")
(is (= 4 (:current-strength (refresh lotus))) "Lotus Field strength unchanged")
(run-jack-out state)
(play-from-hand state :runner "Parasite")
(prompt-select :runner lotus)
(is (= 1 (count (:hosted (refresh lotus)))) "Parasite hosted on Lotus Field")
(take-credits state :runner 1)
(take-credits state :corp)
(is (= 1 (core/get-virus-counters state :runner (first (:hosted (refresh lotus)))))
"Parasite has 1 virus counter")
(is (= 4 (:current-strength (refresh lotus))) "Lotus Field strength unchanged")
(take-credits state :runner)
(play-from-hand state :corp "Lag Time")
(is (= 5 (:current-strength (refresh lotus))) "Lotus Field strength increased")
(take-credits state :corp 2)
(is (= 5 (:current-strength (refresh lotus))) "Lotus Field strength increased"))))
(deftest mausolus
;; Mausolus - 3 adv tokens change the subroutines
(do-game
(new-game (default-corp [(qty "Mausolus" 1)])
(default-runner [(qty "NetChip" 5)]))
(play-from-hand state :corp "Mausolus" "HQ")
(let [mau (get-ice state :hq 0)]
(core/rez state :corp mau)
(take-credits state :corp)
(run-on state :hq)
(is (= 3 (:credit (get-corp))) "corp starts encounter with 3 crs")
(is (= 0 (count (:discard (get-runner)))) "runner starts encounter with no cards in heap")
(is (= 0 (:tag (get-runner))) "runner starts encounter with 0 tags")
(card-subroutine state :corp mau 0)
(card-subroutine state :corp mau 1)
(card-subroutine state :corp mau 2)
(is (= 4 (:credit (get-corp))) "corp gains 1 cr from mausolus")
(is (= 1 (count (:discard (get-runner)))) "corp does 1 net damage")
(is (= 1 (:tag (get-runner))) "corp gives 1 tag")
(run-jack-out state)
(take-credits state :runner)
(core/advance state :corp {:card (refresh mau)})
(core/advance state :corp {:card (refresh mau)})
(core/advance state :corp {:card (refresh mau)})
(run-on state :hq)
(is (= 1 (:credit (get-corp))) "corp starts encounter with 1 crs")
(is (= 1 (count (:discard (get-runner)))) "runner starts encounter with 1 card in heap")
(is (= 1 (:tag (get-runner))) "runner starts encounter with 1 tags")
(card-subroutine state :corp mau 0)
(card-subroutine state :corp mau 1)
(card-subroutine state :corp mau 2)
(is (= 4 (:credit (get-corp))) "corp gains 3 cr")
(is (= 4 (count (:discard (get-runner)))) "corp does 3 net damage")
(is (= 2 (:tag (get-runner))) "corp gives 1 tag")
(is (not (:run @state)) "Run is ended")
(is (get-in @state [:runner :register :unsuccessful-run]) "Run was unsuccessful"))))
(deftest minelayer
;; Minelayer - Install a piece of ICE in outermost position of Minelayer's server at no cost
(do-game
(new-game (default-corp [(qty "Minelayer" 1) (qty "Fire Wall" 1)])
(default-runner))
(play-from-hand state :corp "Minelayer" "HQ")
(take-credits state :corp)
(run-on state :hq)
(core/rez state :corp (get-ice state :hq 0))
(is (= 6 (:credit (get-corp))))
(card-subroutine state :corp (get-ice state :hq 0) 0)
(prompt-select :corp (find-card "Fire Wall" (:hand (get-corp))))
(is (= 2 (count (get-in @state [:corp :servers :hq :ices]))) "2 ICE protecting HQ")
(is (= 6 (:credit (get-corp))) "Didn't pay 1 credit to install as second ICE")))
(deftest morph-ice-subtype-changing
;; Morph ice gain and lose subtypes from normal advancements and placed advancements
(do-game
(new-game (default-corp [(qty "Wendigo" 1)
(qty "Shipment from SanSan" 1)
(qty "Superior Cyberwalls" 1)])
(default-runner))
(core/gain state :corp :click 2)
(play-from-hand state :corp "Superior Cyberwalls" "New remote")
(let [sc (get-content state :remote1 0)]
(score-agenda state :corp sc)
(play-from-hand state :corp "Wendigo" "HQ")
(let [wend (get-ice state :hq 0)]
(core/rez state :corp wend)
(is (= 4 (:current-strength (refresh wend))) "Wendigo at normal 4 strength")
(core/advance state :corp {:card (refresh wend)})
(is (= true (has? (refresh wend) :subtype "Barrier")) "Wendigo gained Barrier")
(is (= false (has? (refresh wend) :subtype "Code Gate")) "Wendigo lost Code Gate")
(is (= 5 (:current-strength (refresh wend))) "Wendigo boosted to 5 strength by scored Superior Cyberwalls")
(play-from-hand state :corp "Shipment from SanSan")
(prompt-choice :corp "1")
(prompt-select :corp wend)
(is (= false (has? (refresh wend) :subtype "Barrier")) "Wendigo lost Barrier")
(is (= true (has? (refresh wend) :subtype "Code Gate")) "Wendigo gained Code Gate")
(is (= 4 (:current-strength (refresh wend))) "Wendigo returned to normal 4 strength")))))
(deftest mother-goddess
;; Mother Goddess - Gains other ice subtypes
(do-game
(new-game (default-corp [(qty "Mother Goddess" 1) (qty "NEXT Bronze" 1)])
(default-runner))
(core/gain state :corp :credit 1)
(play-from-hand state :corp "Mother Goddess" "HQ")
(play-from-hand state :corp "NEXT Bronze" "R&D")
(let [mg (get-ice state :hq 0)
nb (get-ice state :rd 0)]
(core/rez state :corp mg)
(is (core/has-subtype? (refresh mg) "Mythic") "Mother Goddess has mythic")
(is (not (core/has-subtype? (refresh mg) "Code Gate")) "Mother Goddess does not have code gate")
(is (not (core/has-subtype? (refresh mg) "NEXT")) "Mother Goddess does not have NEXT")
(core/rez state :corp nb)
(is (core/has-subtype? (refresh mg) "Mythic") "Mother Goddess has mythic")
(is (core/has-subtype? (refresh mg) "Code Gate") "Mother Goddess has code gate")
(is (core/has-subtype? (refresh mg) "NEXT") "Mother Goddess has NEXT"))))
(deftest next-bronze
;; NEXT Bronze - Add 1 strength for every rezzed NEXT ice
(do-game
(new-game (default-corp [(qty "NEXT Bronze" 2) (qty "NEXT Silver" 1)])
(default-runner))
(core/gain state :corp :credit 2)
(play-from-hand state :corp "NEXT Bronze" "HQ")
(play-from-hand state :corp "NEXT Bronze" "R&D")
(play-from-hand state :corp "NEXT Silver" "Archives")
(let [nb1 (get-ice state :hq 0)
nb2 (get-ice state :rd 0)
ns1 (get-ice state :archives 0)]
(core/rez state :corp nb1)
(is (= 1 (:current-strength (refresh nb1)))
"NEXT Bronze at 1 strength: 1 rezzed NEXT ice")
(core/rez state :corp nb2)
(is (= 2 (:current-strength (refresh nb1)))
"NEXT Bronze at 2 strength: 2 rezzed NEXT ice")
(is (= 2 (:current-strength (refresh nb2)))
"NEXT Bronze at 2 strength: 2 rezzed NEXT ice")
(core/rez state :corp ns1)
(is (= 3 (:current-strength (refresh nb1)))
"NEXT Bronze at 3 strength: 3 rezzed NEXT ice")
(is (= 3 (:current-strength (refresh nb2)))
"NEXT Bronze at 3 strength: 3 rezzed NEXT ice"))))
(deftest resistor
;; Resistor - Strength equal to Runner tags, lose strength when Runner removes a tag
(do-game
(new-game (default-corp [(qty "Resistor" 1)])
(default-runner))
(play-from-hand state :corp "Resistor" "HQ")
(let [resistor (get-ice state :hq 0)]
(core/rez state :corp resistor)
(is (= 0 (:current-strength (refresh resistor))) "No Runner tags; 0 strength")
(core/tag-runner state :runner 2)
(is (= 2 (:tag (get-runner))))
(is (= 2 (:current-strength (refresh resistor))) "2 Runner tags; 2 strength")
(take-credits state :corp)
(core/remove-tag state :runner 1)
(is (= 1 (:current-strength (refresh resistor))) "Runner removed 1 tag; down to 1 strength"))))
(deftest searchlight
;; Searchlight - Trace bace equal to advancement counters
(do-game
(new-game (default-corp [(qty "Searchlight" 1)])
(default-runner))
(play-from-hand state :corp "Searchlight" "HQ")
(let [searchlight (get-ice state :hq 0)]
(core/rez state :corp searchlight)
(card-subroutine state :corp (refresh searchlight) 0)
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (= 0 (:tag (get-runner))) "Trace failed with 0 advancements")
(core/advance state :corp {:card (refresh searchlight)})
(card-subroutine state :corp (refresh searchlight) 0)
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (= 1 (:tag (get-runner))) "Trace succeeds with 0 advancements"))))
(deftest sherlock
;; Sherlock 1.0 - Trace to add an installed program to the top of Runner's Stack
(do-game
(new-game (default-corp [(qty "Sherlock 1.0" 1)])
(default-runner [(qty "Gordian Blade" 3) (qty "Sure Gamble" 3)]))
(play-from-hand state :corp "Sherlock 1.0" "HQ")
(take-credits state :corp)
(play-from-hand state :runner "Gordian Blade")
(run-on state :hq)
(core/rez state :corp (get-ice state :hq 0))
(card-subroutine state :corp (get-ice state :hq 0) 0)
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(prompt-select :corp (get-in @state [:runner :rig :program 0]))
(is (empty? (get-in @state [:runner :rig :program])) "Gordian uninstalled")
(is (= "Gordian Blade" (:title (first (:deck (get-runner))))) "Gordian on top of Stack")))
(deftest shiro
;; Shiro - Full test
(do-game
(new-game (default-corp [(qty "Shiro" 1) (qty "Caprice Nisei" 1)
(qty "Quandary" 1) (qty "Jackson Howard" 1)])
(default-runner [(qty "R&D Interface" 1)]))
(starting-hand state :corp ["Shiro"])
(play-from-hand state :corp "Shiro" "HQ")
(take-credits state :corp)
(play-from-hand state :runner "R&D Interface")
(let [shiro (get-ice state :hq 0)]
(run-on state :hq)
(core/rez state :corp shiro)
(card-subroutine state :corp shiro 0)
(prompt-choice :corp (find-card "Caprice Nisei" (:deck (get-corp))))
(prompt-choice :corp (find-card "Quandary" (:deck (get-corp))))
(prompt-choice :corp (find-card "Jackson Howard" (:deck (get-corp))))
;; try starting over
(prompt-choice :corp "Start over")
(prompt-choice :corp (find-card "Jackson Howard" (:deck (get-corp))))
(prompt-choice :corp (find-card "Quandary" (:deck (get-corp))))
(prompt-choice :corp (find-card "Caprice Nisei" (:deck (get-corp)))) ;this is the top card of R&D
(prompt-choice :corp "Done")
(is (= "Caprice Nisei" (:title (first (:deck (get-corp))))))
(is (= "Quandary" (:title (second (:deck (get-corp))))))
(is (= "Jackson Howard" (:title (second (rest (:deck (get-corp)))))))
(card-subroutine state :corp shiro 1)
(is (= (:cid (first (:deck (get-corp))))
(:cid (:card (first (:prompt (get-runner)))))) "Access the top card of R&D")
(prompt-choice :runner "No")
(is (= (:cid (second (:deck (get-corp))))
(:cid (:card (first (:prompt (get-runner)))))) "Access another card due to R&D Interface"))))
(deftest snowflake
;; Snowflake - Win a psi game to end the run
(do-game
(new-game (default-corp [(qty "Snowflake" 1)])
(default-runner))
(play-from-hand state :corp "Snowflake" "HQ")
(take-credits state :corp)
(run-on state :hq)
(let [sf (get-ice state :hq 0)]
(core/rez state :corp sf)
(card-subroutine state :corp sf 0)
(prompt-choice :corp "0 [Credits]")
(prompt-choice :runner "0 [Credits]")
(is (:run @state) "Runner won psi, run continues")
(card-subroutine state :corp sf 0)
(prompt-choice :corp "0 [Credits]")
(prompt-choice :runner "1 [Credits]")
(is (not (:run @state)) "Run ended"))))
(deftest special-offer-trash-ice-during-run
;; Special Offer trashes itself and updates the run position
(do-game
(new-game (default-corp [(qty "Ice Wall" 1) (qty "Special Offer" 1)])
(default-runner))
(play-from-hand state :corp "Ice Wall" "HQ")
(play-from-hand state :corp "Special Offer" "HQ")
(take-credits state :corp 1)
(run-on state "HQ")
(is (= 2 (:position (get-in @state [:run]))) "Initial position approaching Special Offer")
(let [special (get-ice state :hq 1)]
(core/rez state :corp special)
(is (= 4 (:credit (get-corp))))
(card-subroutine state :corp special 0)
(is (= 9 (:credit (get-corp))) "Special Offer paid 5 credits")
(is (= 1 (:position (get-in @state [:run])))
"Run position updated; now approaching Ice Wall"))))
(deftest tmi
;; TMI ICE test
(do-game
(new-game (default-corp [(qty "TMI" 3)])
(default-runner))
(play-from-hand state :corp "TMI" "HQ")
(let [tmi (get-ice state :hq 0)]
(core/rez state :corp tmi)
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (get-in (refresh tmi) [:rezzed])))))
(deftest tmi-derez
;; TMI ICE trace derez
(do-game
(new-game (default-corp [(qty "TMI" 3)])
(make-deck "Sunny Lebeau: Security Specialist" [(qty "Blackmail" 3)]))
(play-from-hand state :corp "TMI" "HQ")
(let [tmi (get-ice state :hq 0)]
(core/rez state :corp tmi)
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (not (get-in (refresh tmi) [:rezzed]))))))
(deftest turing-positional-strength
;; Turing - Strength boosted when protecting a remote server
(do-game
(new-game (default-corp [(qty "Turing" 2) (qty "Hedge Fund" 1)])
(default-runner))
(play-from-hand state :corp "Hedge Fund")
(play-from-hand state :corp "Turing" "HQ")
(play-from-hand state :corp "Turing" "New remote")
(let [t1 (get-ice state :hq 0)
t2 (get-ice state :remote1 0)]
(core/rez state :corp t1)
(is (= 2 (:current-strength (refresh t1)))
"Turing default 2 strength over a central server")
(core/rez state :corp t2)
(is (= 5 (:current-strength (refresh t2)))
"Turing increased to 5 strength over a remote server"))))
(deftest wraparound
;; Wraparound - Strength boosted when no fracter is installed
(do-game
(new-game (default-corp [(qty "Wraparound" 1)])
(default-runner [(qty "Corroder" 1)]))
(play-from-hand state :corp "Wraparound" "HQ")
(let [wrap (get-ice state :hq 0)]
(core/rez state :corp wrap)
(is (= 7 (:current-strength (refresh wrap)))
"Wraparound +7 strength with no fracter in play")
(take-credits state :corp)
(play-from-hand state :runner "Corroder")
(is (= 0 (:current-strength (refresh wrap)))
"Wraparound 0 strength after Corroder installed"))))
| 43158 | (ns test.cards.ice
(:require [game.core :as core]
[game.utils :refer :all]
[test.core :refer :all]
[test.utils :refer :all]
[test.macros :refer :all]
[clojure.test :refer :all]))
(deftest end-the-run
;; Since all ETR ice share a common ability, we only need one test
(do-game
(new-game (default-corp [(qty "Ice Wall" 3) (qty "Hedge Fund" 3) (qty "Restructure" 2)])
(default-runner))
(play-from-hand state :corp "Ice Wall" "HQ")
(take-credits state :corp 2)
(run-on state "HQ")
(is (= [:hq] (get-in @state [:run :server])))
(let [iwall (get-ice state :hq 0)]
(core/rez state :corp iwall)
(card-subroutine state :corp iwall 0)
(is (not (:run @state)) "Run is ended")
(is (get-in @state [:runner :register :unsuccessful-run]) "Run was unsuccessful"))))
(deftest archangel
;; Archangel - accessing from R&D does not cause run to hang.
(do-game
(new-game (default-corp [(qty "Archangel" 1) (qty "Hedge Fund" 1)])
(default-runner [(qty "Bank Job" 1)]))
(starting-hand state :corp ["Hedge Fund"])
(take-credits state :corp)
(play-from-hand state :runner "Bank Job")
(run-empty-server state :rd)
(prompt-choice :corp "Yes")
(prompt-choice :runner "Yes")
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(prompt-select :corp (get-resource state 0))
(prompt-choice :runner "OK")
(is (not (:run @state)) "Run ended")))
(deftest architect-untrashable
;; Architect is untrashable while installed and rezzed, but trashable if derezzed or from HQ
(do-game
(new-game (default-corp [(qty "Architect" 3)])
(default-runner))
(play-from-hand state :corp "Architect" "HQ")
(let [architect (get-ice state :hq 0)]
(core/rez state :corp architect)
(core/trash state :corp (refresh architect))
(is (not= nil (get-ice state :hq 0)) "Architect was trashed, but should be untrashable")
(core/derez state :corp (refresh architect))
(core/trash state :corp (refresh architect))
(is (= nil (get-ice state :hq 0)) "Architect was not trashed, but should be trashable")
(core/trash state :corp (get-in @state [:corp :hand 0]))
(is (= (get-in @state [:corp :discard 0 :title]) "Architect"))
(is (= (get-in @state [:corp :discard 1 :title]) "Architect")))))
(deftest asteroid-belt
;; Asteroid Belt - Space ICE rez cost reduced by 3 credits per advancement
(do-game
(new-game (default-corp [(qty "Asteroid Belt" 1)])
(default-runner))
(core/gain state :corp :credit 5)
(play-from-hand state :corp "Asteroid Belt" "HQ")
(let [ab (get-ice state :hq 0)]
(core/advance state :corp {:card (refresh ab)})
(core/advance state :corp {:card (refresh ab)})
(is (= 8 (:credit (get-corp))))
(is (= 2 (:advance-counter (refresh ab))))
(core/rez state :corp (refresh ab))
(is (= 5 (:credit (get-corp))) "Paid 3 credits to rez; 2 advancments on Asteroid Belt"))))
(deftest bandwidth
;; Bandwidth - Give the Runner 1 tag; remove 1 tag if the run is successful
(do-game
(new-game (default-corp [(qty "Bandwidth" 1)])
(default-runner))
(play-from-hand state :corp "Bandwidth" "Archives")
(let [bw (get-ice state :archives 0)]
(take-credits state :corp)
(run-on state "Archives")
(core/rez state :corp bw)
(card-subroutine state :corp bw 0)
(is (= 1 (:tag (get-runner))) "Runner took 1 tag")
(run-successful state)
(is (= 0 (:tag (get-runner))) "Run successful; Runner lost 1 tag")
(run-on state "Archives")
(card-subroutine state :corp bw 0)
(is (= 1 (:tag (get-runner))) "Runner took 1 tag")
(run-jack-out state)
(is (= 1 (:tag (get-runner))) "Run unsuccessful; Runner kept 1 tag"))))
(deftest bullfrog
;; Bullfrog - Win psi to move to outermost position of another server and continue run there
(do-game
(new-game (default-corp [(qty "Bullfrog" 1) (qty "Pup" 2)])
(default-runner))
(play-from-hand state :corp "Bullfrog" "HQ")
(play-from-hand state :corp "Pup" "R&D")
(play-from-hand state :corp "Pup" "R&D")
(take-credits state :corp)
(run-on state :hq)
(let [frog (get-ice state :hq 0)]
(core/rez state :corp frog)
(is (= :hq (first (get-in @state [:run :server]))))
(card-subroutine state :corp frog 0)
(prompt-choice :corp "0 [Credits]")
(prompt-choice :runner "1 [Credits]")
(prompt-choice :corp "R&D")
(is (= :rd (first (get-in @state [:run :server]))) "Run redirected to R&D")
(is (= 2 (get-in @state [:run :position])) "Passed Bullfrog")
(is (= "Bullfrog" (:title (get-ice state :rd 2))) "Bullfrog at outermost position of R&D"))))
(deftest cell-portal
;; Cell Portal - Bounce Runner to outermost position and derez itself
(do-game
(new-game (default-corp [(qty "Cell Portal" 1) (qty "Paper Wall" 2)])
(default-runner))
(core/gain state :corp :credit 5)
(play-from-hand state :corp "Cell Portal" "HQ")
(play-from-hand state :corp "Paper Wall" "HQ")
(play-from-hand state :corp "Paper Wall" "HQ")
(take-credits state :corp)
(run-on state :hq)
(run-continue state)
(run-continue state)
(is (= 1 (get-in @state [:run :position])))
(let [cp (get-ice state :hq 0)]
(core/rez state :corp cp)
(card-subroutine state :corp cp 0)
(is (= 3 (get-in @state [:run :position])) "Run back at outermost position")
(is (not (get-in (refresh cp) [:rezzed])) "Cell Portal derezzed"))))
(deftest chimera
;; Chimera - Gains chosen subtype
(do-game
(new-game (default-corp [(qty "Chimera" 1)])
(default-runner))
(play-from-hand state :corp "Chimera" "HQ")
(let [ch (get-ice state :hq 0)]
(core/rez state :corp ch)
(prompt-choice :corp "Barrier")
(is (core/has-subtype? (refresh ch) "Barrier") "Chimera has barrier")
(take-credits state :corp)
(is (not (core/has-subtype? (refresh ch) "Barrier")) "Chimera does not have barrier"))))
(deftest cortex-lock
;; Cortex Lock - Do net damage equal to Runner's unused memory
(do-game
(new-game (default-corp [(qty "Cortex Lock" 1)])
(default-runner [(qty "Corroder" 2) (qty "Sure Gamble" 3)]))
(play-from-hand state :corp "Cortex Lock" "HQ")
(take-credits state :corp)
(let [cort (get-ice state :hq 0)]
(play-from-hand state :runner "Corroder")
(is (= 3 (:memory (get-runner))))
(run-on state "HQ")
(core/rez state :corp cort)
(card-subroutine state :corp cort 0)
(is (= 3 (count (:discard (get-runner)))) "Runner suffered 3 net damage"))))
(deftest crick
;; Crick - Strength boost when protecting Archives; installs a card from Archives
(do-game
(new-game (default-corp [(qty "Crick" 2) (qty "Ice Wall" 1)])
(default-runner))
(play-from-hand state :corp "Crick" "HQ")
(play-from-hand state :corp "Crick" "Archives")
(core/move state :corp (find-card "Ice Wall" (:hand (get-corp))) :discard)
(take-credits state :corp)
(let [cr1 (get-ice state :hq 0)
cr2 (get-ice state :archives 0)]
(core/rez state :corp cr1)
(core/rez state :corp cr2)
(is (= 3 (:current-strength (refresh cr1))) "Normal strength over HQ")
(is (= 6 (:current-strength (refresh cr2))) "+3 strength over Archives")
(card-subroutine state :corp cr2 0)
(prompt-select :corp (find-card "Ice Wall" (:discard (get-corp))))
(prompt-choice :corp "HQ")
(is (= 3 (:credit (get-corp))) "Paid 1 credit to install as 2nd ICE over HQ"))))
(deftest curtain-wall
;; Curtain Wall - Strength boost when outermost ICE
(do-game
(new-game (default-corp [(qty "Curtain Wall" 1) (qty "Paper Wall" 1)])
(default-runner))
(core/gain state :corp :credit 10)
(play-from-hand state :corp "Curtain Wall" "HQ")
(let [curt (get-ice state :hq 0)]
(core/rez state :corp curt)
(is (= 10 (:current-strength (refresh curt)))
"Curtain Wall has +4 strength as outermost ICE")
(play-from-hand state :corp "Paper Wall" "HQ")
(let [paper (get-ice state :hq 1)]
(core/rez state :corp paper)
(is (= 6 (:current-strength (refresh curt))) "Curtain Wall back to default 6 strength")))))
(deftest data-hound
;; Data Hound - Full test
(do-game
(new-game (default-corp [(qty "Data Hound" 1)])
(default-runner [(qty "Sure Gamble" 2) (qty "Desperado" 1)
(qty "Corroder" 1) (qty "Patron" 1)]))
(starting-hand state :runner ["Sure Gamble"]) ;move all other cards to stack
(play-from-hand state :corp "Data Hound" "HQ")
(take-credits state :corp)
(let [dh (get-ice state :hq 0)]
(run-on state "HQ")
(core/rez state :corp dh)
(card-subroutine state :corp dh 0)
(prompt-choice :corp 2)
(prompt-choice :runner 0)
;; trash 1 card and rearrange the other 3
(prompt-choice :corp (find-card "Desperado" (:deck (get-runner))))
(is (= 1 (count (:discard (get-runner)))))
(prompt-choice :corp (find-card "Sure Gamble" (:deck (get-runner))))
(prompt-choice :corp (find-card "Corroder" (:deck (get-runner))))
(prompt-choice :corp (find-card "Patron" (:deck (get-runner))))
;; try starting over
(prompt-choice :corp "Start over")
(prompt-choice :corp (find-card "Patron" (:deck (get-runner))))
(prompt-choice :corp (find-card "Corroder" (:deck (get-runner))))
(prompt-choice :corp (find-card "Sure Gamble" (:deck (get-runner)))) ;this is the top card on stack
(prompt-choice :corp "Done")
(is (= "Sure Gamble" (:title (first (:deck (get-runner))))))
(is (= "Cor<NAME>der" (:title (second (:deck (get-runner))))))
(is (= "<NAME>" (:title (second (rest (:deck (get-runner)))))))
(run-jack-out state)
(run-on state "HQ")
(card-subroutine state :corp dh 0)
(prompt-choice :corp 0)
(prompt-choice :runner 1)
;; trash the only card automatically
(is (= 2 (count (:discard (get-runner)))))
(is (= "<NAME>der" (:title (first (:deck (get-runner)))))))))
(deftest draco
;; Dracō - Pay credits when rezzed to increase strength; trace to give 1 tag and end the run
(do-game
(new-game (default-corp [(qty "Dracō" 1)])
(default-runner))
(play-from-hand state :corp "Dracō" "HQ")
(take-credits state :corp)
(let [drac (get-ice state :hq 0)]
(run-on state "HQ")
(core/rez state :corp drac)
(prompt-choice :corp 4)
(is (= 4 (get-counters (refresh drac) :power)) "Dracō has 4 power counters")
(is (= 4 (:current-strength (refresh drac))) "Dracō is 4 strength")
(card-subroutine state :corp drac 0)
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (= 1 (:tag (get-runner))) "Runner took 1 tag")
(is (nil? (get-in @state [:run])) "Run was ended"))))
(deftest enigma
;; Enigma - Force Runner to lose 1 click if able
(do-game
(new-game (default-corp [(qty "Enigma" 1)])
(default-runner))
(play-from-hand state :corp "Enigma" "HQ")
(take-credits state :corp)
(let [enig (get-ice state :hq 0)]
(run-on state "HQ")
(is (= 3 (:click (get-runner))))
(core/rez state :corp enig)
(card-subroutine state :corp enig 0)
(is (= 2 (:click (get-runner))) "Runner lost 1 click"))))
(deftest excalibur
;; Excalibur - Prevent Runner from making another run this turn
(do-game
(new-game (default-corp [(qty "Excalibur" 1)])
(default-runner [(qty "Stimhack" 1)]))
(play-from-hand state :corp "Excalibur" "HQ")
(take-credits state :corp)
(let [excal (get-ice state :hq 0)]
(run-on state "HQ")
(core/rez state :corp excal)
(card-subroutine state :corp excal 0)
(run-jack-out state)
(run-on state "R&D")
(is (not (:run @state)) "No run initiated")
(is (= 3 (:click (get-runner))))
(play-from-hand state :runner "Stimhack")
(is (not (:run @state)) "No run initiated")
(is (= 3 (:click (get-runner))))
(is (empty? (:discard (get-runner))) "Card not played from Grip"))))
(deftest fenris
;; Fenris - Illicit ICE give Corp 1 bad publicity when rezzed
(do-game
(new-game (default-corp [(qty "Fenris" 1)])
(default-runner))
(play-from-hand state :corp "Fenris" "HQ")
(take-credits state :corp)
(let [fen (get-ice state :hq 0)]
(run-on state "HQ")
(core/rez state :corp fen)
(is (= 1 (:bad-publicity (get-corp))) "Gained 1 bad pub")
(card-subroutine state :corp fen 0)
(is (= 1 (:brain-damage (get-runner))) "Runner took 1 brain damage")
(is (= 1 (count (:discard (get-runner)))))
(is (= 4 (core/hand-size state :runner))))))
(deftest flare
;; Flare - Trash 1 program, do 2 unpreventable meat damage, and end the run
(do-game
(new-game (default-corp [(qty "Flare" 1)])
(default-runner [(qty "Plascrete Carapace" 1) (qty "Clone Chip" 1) (qty "Cache" 3)]))
(play-from-hand state :corp "Flare" "HQ")
(core/gain state :corp :credit 2)
(take-credits state :corp)
(play-from-hand state :runner "Plascrete Carapace")
(play-from-hand state :runner "Clone Chip")
(let [flare (get-ice state :hq 0)
cc (get-hardware state 1)]
(run-on state :hq)
(core/rez state :corp flare)
(card-subroutine state :corp flare 0)
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(prompt-select :corp cc)
(is (= 1 (count (get-in @state [:runner :rig :hardware]))) "Clone Chip trashed")
(is (empty? (:prompt (get-runner))) "Plascrete didn't try peventing meat damage")
(is (= 1 (count (:hand (get-runner)))))
(is (= 3 (count (:discard (get-runner)))) "Clone Chip plus 2 cards lost from damage in discard")
(is (not (:run @state)) "Run ended"))))
(deftest gemini-kicker
;; Gemini - Successfully trace to do 1 net damage; do 1 net damage if trace strength is 5 or more regardless of success
(do-game
(new-game (default-corp [(qty "Gemini" 1) (qty "Hedge Fund" 2)])
(default-runner [(qty "Sure Gamble" 3) (qty "Dirty Laundry" 2)]))
(play-from-hand state :corp "Gemini" "HQ")
(play-from-hand state :corp "Hedge Fund")
(play-from-hand state :corp "Hedge Fund")
(take-credits state :corp)
(let [gem (get-ice state :hq 0)]
(run-on state "HQ")
(core/rez state :corp gem)
(card-subroutine state :corp gem 0)
(prompt-choice :corp 3) ; boost to trace strength 5
(prompt-choice :runner 0)
(is (= 2 (count (:discard (get-runner)))) "Did 2 net damage")
(card-subroutine state :corp gem 0)
(prompt-choice :corp 3) ; boost to trace strength 5
(prompt-choice :runner 5) ; match trace
(is (= 3 (count (:discard (get-runner)))) "Did only 1 net damage for having trace strength 5 or more"))))
(deftest gemini-chronos-protocol
;; Gemini - Interaction with Chronos Protocol and kicker
(do-game
(new-game (make-deck "Chronos Protocol: Selective Mind-mapping" [(qty "Gemini" 1) (qty "Hedge Fund" 2)])
(default-runner [(qty "Sure Gamble" 1) (qty "Dirty Laundry" 2)]))
(play-from-hand state :corp "Gemini" "HQ")
(play-from-hand state :corp "Hedge Fund")
(play-from-hand state :corp "Hedge Fund")
(take-credits state :corp)
(let [gem (get-ice state :hq 0)]
(run-on state "HQ")
(core/rez state :corp gem)
(card-subroutine state :corp gem 0)
(prompt-choice :corp 3) ; boost to trace strength 5
(prompt-choice :runner 0)
(prompt-choice :corp "Yes")
(prompt-choice :corp (find-card "Sure Gamble" (:hand (get-runner))))
(is (= 2 (count (:discard (get-runner)))) "Did 2 net damage"))))
(deftest iq
;; IQ - Rez cost and strength equal to cards in HQ
(do-game
(new-game (default-corp [(qty "IQ" 3) (qty "Hedge Fund" 3)])
(default-runner))
(play-from-hand state :corp "Hedge Fund")
(play-from-hand state :corp "IQ" "R&D")
(let [iq1 (get-ice state :rd 0)]
(core/rez state :corp iq1)
(is (and (= 4 (count (:hand (get-corp))))
(= 4 (:current-strength (refresh iq1)))
(= 5 (:credit (get-corp)))) "4 cards in HQ: paid 4 to rez, has 4 strength")
(play-from-hand state :corp "IQ" "HQ")
(let [iq2 (get-ice state :hq 0)]
(core/rez state :corp iq2)
(is (and (= 3 (count (:hand (get-corp))))
(= 3 (:current-strength (refresh iq1)))
(= 3 (:current-strength (refresh iq2)))
(= 2 (:credit (get-corp)))) "3 cards in HQ: paid 3 to rez, both have 3 strength")))))
(deftest lockdown
;; Lockdown - Prevent Runner from drawing cards for the rest of the turn
(do-game
(new-game (default-corp [(qty "Lockdown" 1)])
(default-runner [(qty "Diesel" 2) (qty "Sure Gamble" 3)]))
(play-from-hand state :corp "Lockdown" "R&D")
(take-credits state :corp)
(core/move state :runner (find-card "Sure Gamble" (:hand (get-runner))) :deck)
(core/move state :runner (find-card "Sure Gamble" (:hand (get-runner))) :deck)
(core/move state :runner (find-card "Sure Gamble" (:hand (get-runner))) :deck)
(let [lock (get-ice state :rd 0)]
(run-on state "R&D")
(core/rez state :corp lock)
(card-subroutine state :corp lock 0)
(run-successful state)
(play-from-hand state :runner "Diesel")
(is (= 1 (count (:hand (get-runner)))) "No cards drawn")
(take-credits state :runner)
(take-credits state :corp)
(play-from-hand state :runner "Diesel")
(is (= 3 (count (:hand (get-runner))))
"New turn ends prevention; remaining 3 cards drawn from Stack"))))
(deftest lotus-field-unlowerable
;; Lotus Field strength cannot be lowered
(do-game
(new-game (default-corp [(qty "Lotus Field" 1) (qty "Lag Time" 1)])
(default-runner [(qty "Ice Carver" 1) (qty "Parasite" 1)]))
(play-from-hand state :corp "Lotus Field" "Archives")
(take-credits state :corp 2)
(let [lotus (get-ice state :archives 0)]
(core/rez state :corp lotus)
(play-from-hand state :runner "Ice Carver")
(run-on state "Archives")
(is (= 4 (:current-strength (refresh lotus))) "Lotus Field strength unchanged")
(run-jack-out state)
(play-from-hand state :runner "Parasite")
(prompt-select :runner lotus)
(is (= 1 (count (:hosted (refresh lotus)))) "Parasite hosted on Lotus Field")
(take-credits state :runner 1)
(take-credits state :corp)
(is (= 1 (core/get-virus-counters state :runner (first (:hosted (refresh lotus)))))
"Parasite has 1 virus counter")
(is (= 4 (:current-strength (refresh lotus))) "Lotus Field strength unchanged")
(take-credits state :runner)
(play-from-hand state :corp "Lag Time")
(is (= 5 (:current-strength (refresh lotus))) "Lotus Field strength increased")
(take-credits state :corp 2)
(is (= 5 (:current-strength (refresh lotus))) "Lotus Field strength increased"))))
(deftest mausolus
;; Mausolus - 3 adv tokens change the subroutines
(do-game
(new-game (default-corp [(qty "Mausolus" 1)])
(default-runner [(qty "NetChip" 5)]))
(play-from-hand state :corp "Mausolus" "HQ")
(let [mau (get-ice state :hq 0)]
(core/rez state :corp mau)
(take-credits state :corp)
(run-on state :hq)
(is (= 3 (:credit (get-corp))) "corp starts encounter with 3 crs")
(is (= 0 (count (:discard (get-runner)))) "runner starts encounter with no cards in heap")
(is (= 0 (:tag (get-runner))) "runner starts encounter with 0 tags")
(card-subroutine state :corp mau 0)
(card-subroutine state :corp mau 1)
(card-subroutine state :corp mau 2)
(is (= 4 (:credit (get-corp))) "corp gains 1 cr from mausolus")
(is (= 1 (count (:discard (get-runner)))) "corp does 1 net damage")
(is (= 1 (:tag (get-runner))) "corp gives 1 tag")
(run-jack-out state)
(take-credits state :runner)
(core/advance state :corp {:card (refresh mau)})
(core/advance state :corp {:card (refresh mau)})
(core/advance state :corp {:card (refresh mau)})
(run-on state :hq)
(is (= 1 (:credit (get-corp))) "corp starts encounter with 1 crs")
(is (= 1 (count (:discard (get-runner)))) "runner starts encounter with 1 card in heap")
(is (= 1 (:tag (get-runner))) "runner starts encounter with 1 tags")
(card-subroutine state :corp mau 0)
(card-subroutine state :corp mau 1)
(card-subroutine state :corp mau 2)
(is (= 4 (:credit (get-corp))) "corp gains 3 cr")
(is (= 4 (count (:discard (get-runner)))) "corp does 3 net damage")
(is (= 2 (:tag (get-runner))) "corp gives 1 tag")
(is (not (:run @state)) "Run is ended")
(is (get-in @state [:runner :register :unsuccessful-run]) "Run was unsuccessful"))))
(deftest minelayer
;; Minelayer - Install a piece of ICE in outermost position of Minelayer's server at no cost
(do-game
(new-game (default-corp [(qty "Minelayer" 1) (qty "Fire Wall" 1)])
(default-runner))
(play-from-hand state :corp "Minelayer" "HQ")
(take-credits state :corp)
(run-on state :hq)
(core/rez state :corp (get-ice state :hq 0))
(is (= 6 (:credit (get-corp))))
(card-subroutine state :corp (get-ice state :hq 0) 0)
(prompt-select :corp (find-card "Fire Wall" (:hand (get-corp))))
(is (= 2 (count (get-in @state [:corp :servers :hq :ices]))) "2 ICE protecting HQ")
(is (= 6 (:credit (get-corp))) "Didn't pay 1 credit to install as second ICE")))
(deftest morph-ice-subtype-changing
;; Morph ice gain and lose subtypes from normal advancements and placed advancements
(do-game
(new-game (default-corp [(qty "Wendigo" 1)
(qty "Shipment from SanSan" 1)
(qty "Superior Cyberwalls" 1)])
(default-runner))
(core/gain state :corp :click 2)
(play-from-hand state :corp "Superior Cyberwalls" "New remote")
(let [sc (get-content state :remote1 0)]
(score-agenda state :corp sc)
(play-from-hand state :corp "Wendigo" "HQ")
(let [wend (get-ice state :hq 0)]
(core/rez state :corp wend)
(is (= 4 (:current-strength (refresh wend))) "Wendigo at normal 4 strength")
(core/advance state :corp {:card (refresh wend)})
(is (= true (has? (refresh wend) :subtype "Barrier")) "Wendigo gained Barrier")
(is (= false (has? (refresh wend) :subtype "Code Gate")) "Wendigo lost Code Gate")
(is (= 5 (:current-strength (refresh wend))) "Wendigo boosted to 5 strength by scored Superior Cyberwalls")
(play-from-hand state :corp "Shipment from SanSan")
(prompt-choice :corp "1")
(prompt-select :corp wend)
(is (= false (has? (refresh wend) :subtype "Barrier")) "Wendigo lost Barrier")
(is (= true (has? (refresh wend) :subtype "Code Gate")) "Wendigo gained Code Gate")
(is (= 4 (:current-strength (refresh wend))) "Wendigo returned to normal 4 strength")))))
(deftest mother-goddess
;; Mother Goddess - Gains other ice subtypes
(do-game
(new-game (default-corp [(qty "Mother Goddess" 1) (qty "NEXT Bronze" 1)])
(default-runner))
(core/gain state :corp :credit 1)
(play-from-hand state :corp "Mother Goddess" "HQ")
(play-from-hand state :corp "NEXT Bronze" "R&D")
(let [mg (get-ice state :hq 0)
nb (get-ice state :rd 0)]
(core/rez state :corp mg)
(is (core/has-subtype? (refresh mg) "Mythic") "Mother Goddess has mythic")
(is (not (core/has-subtype? (refresh mg) "Code Gate")) "Mother Goddess does not have code gate")
(is (not (core/has-subtype? (refresh mg) "NEXT")) "Mother Goddess does not have NEXT")
(core/rez state :corp nb)
(is (core/has-subtype? (refresh mg) "Mythic") "Mother Goddess has mythic")
(is (core/has-subtype? (refresh mg) "Code Gate") "Mother Goddess has code gate")
(is (core/has-subtype? (refresh mg) "NEXT") "Mother Goddess has NEXT"))))
(deftest next-bronze
;; NEXT Bronze - Add 1 strength for every rezzed NEXT ice
(do-game
(new-game (default-corp [(qty "NEXT Bronze" 2) (qty "NEXT Silver" 1)])
(default-runner))
(core/gain state :corp :credit 2)
(play-from-hand state :corp "NEXT Bronze" "HQ")
(play-from-hand state :corp "NEXT Bronze" "R&D")
(play-from-hand state :corp "NEXT Silver" "Archives")
(let [nb1 (get-ice state :hq 0)
nb2 (get-ice state :rd 0)
ns1 (get-ice state :archives 0)]
(core/rez state :corp nb1)
(is (= 1 (:current-strength (refresh nb1)))
"NEXT Bronze at 1 strength: 1 rezzed NEXT ice")
(core/rez state :corp nb2)
(is (= 2 (:current-strength (refresh nb1)))
"NEXT Bronze at 2 strength: 2 rezzed NEXT ice")
(is (= 2 (:current-strength (refresh nb2)))
"NEXT Bronze at 2 strength: 2 rezzed NEXT ice")
(core/rez state :corp ns1)
(is (= 3 (:current-strength (refresh nb1)))
"NEXT Bronze at 3 strength: 3 rezzed NEXT ice")
(is (= 3 (:current-strength (refresh nb2)))
"NEXT Bronze at 3 strength: 3 rezzed NEXT ice"))))
(deftest resistor
;; Resistor - Strength equal to Runner tags, lose strength when Runner removes a tag
(do-game
(new-game (default-corp [(qty "Resistor" 1)])
(default-runner))
(play-from-hand state :corp "Resistor" "HQ")
(let [resistor (get-ice state :hq 0)]
(core/rez state :corp resistor)
(is (= 0 (:current-strength (refresh resistor))) "No Runner tags; 0 strength")
(core/tag-runner state :runner 2)
(is (= 2 (:tag (get-runner))))
(is (= 2 (:current-strength (refresh resistor))) "2 Runner tags; 2 strength")
(take-credits state :corp)
(core/remove-tag state :runner 1)
(is (= 1 (:current-strength (refresh resistor))) "Runner removed 1 tag; down to 1 strength"))))
(deftest searchlight
;; Searchlight - Trace bace equal to advancement counters
(do-game
(new-game (default-corp [(qty "Searchlight" 1)])
(default-runner))
(play-from-hand state :corp "Searchlight" "HQ")
(let [searchlight (get-ice state :hq 0)]
(core/rez state :corp searchlight)
(card-subroutine state :corp (refresh searchlight) 0)
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (= 0 (:tag (get-runner))) "Trace failed with 0 advancements")
(core/advance state :corp {:card (refresh searchlight)})
(card-subroutine state :corp (refresh searchlight) 0)
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (= 1 (:tag (get-runner))) "Trace succeeds with 0 advancements"))))
(deftest sherlock
;; Sherlock 1.0 - Trace to add an installed program to the top of Runner's Stack
(do-game
(new-game (default-corp [(qty "Sherlock 1.0" 1)])
(default-runner [(qty "Gordian Blade" 3) (qty "Sure Gamble" 3)]))
(play-from-hand state :corp "Sherlock 1.0" "HQ")
(take-credits state :corp)
(play-from-hand state :runner "Gordian Blade")
(run-on state :hq)
(core/rez state :corp (get-ice state :hq 0))
(card-subroutine state :corp (get-ice state :hq 0) 0)
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(prompt-select :corp (get-in @state [:runner :rig :program 0]))
(is (empty? (get-in @state [:runner :rig :program])) "Gordian uninstalled")
(is (= "Gordian Blade" (:title (first (:deck (get-runner))))) "Gordian on top of Stack")))
(deftest shiro
;; Shiro - Full test
(do-game
(new-game (default-corp [(qty "Shiro" 1) (qty "<NAME>" 1)
(qty "<NAME>" 1) (qty "<NAME>" 1)])
(default-runner [(qty "R&D Interface" 1)]))
(starting-hand state :corp ["Shiro"])
(play-from-hand state :corp "Shiro" "HQ")
(take-credits state :corp)
(play-from-hand state :runner "R&D Interface")
(let [shiro (get-ice state :hq 0)]
(run-on state :hq)
(core/rez state :corp shiro)
(card-subroutine state :corp shiro 0)
(prompt-choice :corp (find-card "<NAME>" (:deck (get-corp))))
(prompt-choice :corp (find-card "Qu<NAME>" (:deck (get-corp))))
(prompt-choice :corp (find-card "<NAME>" (:deck (get-corp))))
;; try starting over
(prompt-choice :corp "Start over")
(prompt-choice :corp (find-card "<NAME>" (:deck (get-corp))))
(prompt-choice :corp (find-card "<NAME>" (:deck (get-corp))))
(prompt-choice :corp (find-card "<NAME>" (:deck (get-corp)))) ;this is the top card of R&D
(prompt-choice :corp "Done")
(is (= "<NAME>" (:title (first (:deck (get-corp))))))
(is (= "<NAME>" (:title (second (:deck (get-corp))))))
(is (= "<NAME>" (:title (second (rest (:deck (get-corp)))))))
(card-subroutine state :corp shiro 1)
(is (= (:cid (first (:deck (get-corp))))
(:cid (:card (first (:prompt (get-runner)))))) "Access the top card of R&D")
(prompt-choice :runner "No")
(is (= (:cid (second (:deck (get-corp))))
(:cid (:card (first (:prompt (get-runner)))))) "Access another card due to R&D Interface"))))
(deftest snowflake
;; Snowflake - Win a psi game to end the run
(do-game
(new-game (default-corp [(qty "Snowflake" 1)])
(default-runner))
(play-from-hand state :corp "Snowflake" "HQ")
(take-credits state :corp)
(run-on state :hq)
(let [sf (get-ice state :hq 0)]
(core/rez state :corp sf)
(card-subroutine state :corp sf 0)
(prompt-choice :corp "0 [Credits]")
(prompt-choice :runner "0 [Credits]")
(is (:run @state) "Runner won psi, run continues")
(card-subroutine state :corp sf 0)
(prompt-choice :corp "0 [Credits]")
(prompt-choice :runner "1 [Credits]")
(is (not (:run @state)) "Run ended"))))
(deftest special-offer-trash-ice-during-run
;; Special Offer trashes itself and updates the run position
(do-game
(new-game (default-corp [(qty "Ice Wall" 1) (qty "Special Offer" 1)])
(default-runner))
(play-from-hand state :corp "Ice Wall" "HQ")
(play-from-hand state :corp "Special Offer" "HQ")
(take-credits state :corp 1)
(run-on state "HQ")
(is (= 2 (:position (get-in @state [:run]))) "Initial position approaching Special Offer")
(let [special (get-ice state :hq 1)]
(core/rez state :corp special)
(is (= 4 (:credit (get-corp))))
(card-subroutine state :corp special 0)
(is (= 9 (:credit (get-corp))) "Special Offer paid 5 credits")
(is (= 1 (:position (get-in @state [:run])))
"Run position updated; now approaching Ice Wall"))))
(deftest tmi
;; TMI ICE test
(do-game
(new-game (default-corp [(qty "TMI" 3)])
(default-runner))
(play-from-hand state :corp "TMI" "HQ")
(let [tmi (get-ice state :hq 0)]
(core/rez state :corp tmi)
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (get-in (refresh tmi) [:rezzed])))))
(deftest tmi-derez
;; TMI ICE trace derez
(do-game
(new-game (default-corp [(qty "TMI" 3)])
(make-deck "Sunny Lebeau: Security Specialist" [(qty "Blackmail" 3)]))
(play-from-hand state :corp "TMI" "HQ")
(let [tmi (get-ice state :hq 0)]
(core/rez state :corp tmi)
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (not (get-in (refresh tmi) [:rezzed]))))))
(deftest turing-positional-strength
;; Turing - Strength boosted when protecting a remote server
(do-game
(new-game (default-corp [(qty "Turing" 2) (qty "Hedge Fund" 1)])
(default-runner))
(play-from-hand state :corp "Hedge Fund")
(play-from-hand state :corp "Turing" "HQ")
(play-from-hand state :corp "Turing" "New remote")
(let [t1 (get-ice state :hq 0)
t2 (get-ice state :remote1 0)]
(core/rez state :corp t1)
(is (= 2 (:current-strength (refresh t1)))
"Turing default 2 strength over a central server")
(core/rez state :corp t2)
(is (= 5 (:current-strength (refresh t2)))
"Turing increased to 5 strength over a remote server"))))
(deftest wraparound
;; Wraparound - Strength boosted when no fracter is installed
(do-game
(new-game (default-corp [(qty "Wraparound" 1)])
(default-runner [(qty "Corroder" 1)]))
(play-from-hand state :corp "Wraparound" "HQ")
(let [wrap (get-ice state :hq 0)]
(core/rez state :corp wrap)
(is (= 7 (:current-strength (refresh wrap)))
"Wraparound +7 strength with no fracter in play")
(take-credits state :corp)
(play-from-hand state :runner "Corroder")
(is (= 0 (:current-strength (refresh wrap)))
"Wraparound 0 strength after Corroder installed"))))
| true | (ns test.cards.ice
(:require [game.core :as core]
[game.utils :refer :all]
[test.core :refer :all]
[test.utils :refer :all]
[test.macros :refer :all]
[clojure.test :refer :all]))
(deftest end-the-run
;; Since all ETR ice share a common ability, we only need one test
(do-game
(new-game (default-corp [(qty "Ice Wall" 3) (qty "Hedge Fund" 3) (qty "Restructure" 2)])
(default-runner))
(play-from-hand state :corp "Ice Wall" "HQ")
(take-credits state :corp 2)
(run-on state "HQ")
(is (= [:hq] (get-in @state [:run :server])))
(let [iwall (get-ice state :hq 0)]
(core/rez state :corp iwall)
(card-subroutine state :corp iwall 0)
(is (not (:run @state)) "Run is ended")
(is (get-in @state [:runner :register :unsuccessful-run]) "Run was unsuccessful"))))
(deftest archangel
;; Archangel - accessing from R&D does not cause run to hang.
(do-game
(new-game (default-corp [(qty "Archangel" 1) (qty "Hedge Fund" 1)])
(default-runner [(qty "Bank Job" 1)]))
(starting-hand state :corp ["Hedge Fund"])
(take-credits state :corp)
(play-from-hand state :runner "Bank Job")
(run-empty-server state :rd)
(prompt-choice :corp "Yes")
(prompt-choice :runner "Yes")
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(prompt-select :corp (get-resource state 0))
(prompt-choice :runner "OK")
(is (not (:run @state)) "Run ended")))
(deftest architect-untrashable
;; Architect is untrashable while installed and rezzed, but trashable if derezzed or from HQ
(do-game
(new-game (default-corp [(qty "Architect" 3)])
(default-runner))
(play-from-hand state :corp "Architect" "HQ")
(let [architect (get-ice state :hq 0)]
(core/rez state :corp architect)
(core/trash state :corp (refresh architect))
(is (not= nil (get-ice state :hq 0)) "Architect was trashed, but should be untrashable")
(core/derez state :corp (refresh architect))
(core/trash state :corp (refresh architect))
(is (= nil (get-ice state :hq 0)) "Architect was not trashed, but should be trashable")
(core/trash state :corp (get-in @state [:corp :hand 0]))
(is (= (get-in @state [:corp :discard 0 :title]) "Architect"))
(is (= (get-in @state [:corp :discard 1 :title]) "Architect")))))
(deftest asteroid-belt
;; Asteroid Belt - Space ICE rez cost reduced by 3 credits per advancement
(do-game
(new-game (default-corp [(qty "Asteroid Belt" 1)])
(default-runner))
(core/gain state :corp :credit 5)
(play-from-hand state :corp "Asteroid Belt" "HQ")
(let [ab (get-ice state :hq 0)]
(core/advance state :corp {:card (refresh ab)})
(core/advance state :corp {:card (refresh ab)})
(is (= 8 (:credit (get-corp))))
(is (= 2 (:advance-counter (refresh ab))))
(core/rez state :corp (refresh ab))
(is (= 5 (:credit (get-corp))) "Paid 3 credits to rez; 2 advancments on Asteroid Belt"))))
(deftest bandwidth
;; Bandwidth - Give the Runner 1 tag; remove 1 tag if the run is successful
(do-game
(new-game (default-corp [(qty "Bandwidth" 1)])
(default-runner))
(play-from-hand state :corp "Bandwidth" "Archives")
(let [bw (get-ice state :archives 0)]
(take-credits state :corp)
(run-on state "Archives")
(core/rez state :corp bw)
(card-subroutine state :corp bw 0)
(is (= 1 (:tag (get-runner))) "Runner took 1 tag")
(run-successful state)
(is (= 0 (:tag (get-runner))) "Run successful; Runner lost 1 tag")
(run-on state "Archives")
(card-subroutine state :corp bw 0)
(is (= 1 (:tag (get-runner))) "Runner took 1 tag")
(run-jack-out state)
(is (= 1 (:tag (get-runner))) "Run unsuccessful; Runner kept 1 tag"))))
(deftest bullfrog
;; Bullfrog - Win psi to move to outermost position of another server and continue run there
(do-game
(new-game (default-corp [(qty "Bullfrog" 1) (qty "Pup" 2)])
(default-runner))
(play-from-hand state :corp "Bullfrog" "HQ")
(play-from-hand state :corp "Pup" "R&D")
(play-from-hand state :corp "Pup" "R&D")
(take-credits state :corp)
(run-on state :hq)
(let [frog (get-ice state :hq 0)]
(core/rez state :corp frog)
(is (= :hq (first (get-in @state [:run :server]))))
(card-subroutine state :corp frog 0)
(prompt-choice :corp "0 [Credits]")
(prompt-choice :runner "1 [Credits]")
(prompt-choice :corp "R&D")
(is (= :rd (first (get-in @state [:run :server]))) "Run redirected to R&D")
(is (= 2 (get-in @state [:run :position])) "Passed Bullfrog")
(is (= "Bullfrog" (:title (get-ice state :rd 2))) "Bullfrog at outermost position of R&D"))))
(deftest cell-portal
;; Cell Portal - Bounce Runner to outermost position and derez itself
(do-game
(new-game (default-corp [(qty "Cell Portal" 1) (qty "Paper Wall" 2)])
(default-runner))
(core/gain state :corp :credit 5)
(play-from-hand state :corp "Cell Portal" "HQ")
(play-from-hand state :corp "Paper Wall" "HQ")
(play-from-hand state :corp "Paper Wall" "HQ")
(take-credits state :corp)
(run-on state :hq)
(run-continue state)
(run-continue state)
(is (= 1 (get-in @state [:run :position])))
(let [cp (get-ice state :hq 0)]
(core/rez state :corp cp)
(card-subroutine state :corp cp 0)
(is (= 3 (get-in @state [:run :position])) "Run back at outermost position")
(is (not (get-in (refresh cp) [:rezzed])) "Cell Portal derezzed"))))
(deftest chimera
;; Chimera - Gains chosen subtype
(do-game
(new-game (default-corp [(qty "Chimera" 1)])
(default-runner))
(play-from-hand state :corp "Chimera" "HQ")
(let [ch (get-ice state :hq 0)]
(core/rez state :corp ch)
(prompt-choice :corp "Barrier")
(is (core/has-subtype? (refresh ch) "Barrier") "Chimera has barrier")
(take-credits state :corp)
(is (not (core/has-subtype? (refresh ch) "Barrier")) "Chimera does not have barrier"))))
(deftest cortex-lock
;; Cortex Lock - Do net damage equal to Runner's unused memory
(do-game
(new-game (default-corp [(qty "Cortex Lock" 1)])
(default-runner [(qty "Corroder" 2) (qty "Sure Gamble" 3)]))
(play-from-hand state :corp "Cortex Lock" "HQ")
(take-credits state :corp)
(let [cort (get-ice state :hq 0)]
(play-from-hand state :runner "Corroder")
(is (= 3 (:memory (get-runner))))
(run-on state "HQ")
(core/rez state :corp cort)
(card-subroutine state :corp cort 0)
(is (= 3 (count (:discard (get-runner)))) "Runner suffered 3 net damage"))))
(deftest crick
;; Crick - Strength boost when protecting Archives; installs a card from Archives
(do-game
(new-game (default-corp [(qty "Crick" 2) (qty "Ice Wall" 1)])
(default-runner))
(play-from-hand state :corp "Crick" "HQ")
(play-from-hand state :corp "Crick" "Archives")
(core/move state :corp (find-card "Ice Wall" (:hand (get-corp))) :discard)
(take-credits state :corp)
(let [cr1 (get-ice state :hq 0)
cr2 (get-ice state :archives 0)]
(core/rez state :corp cr1)
(core/rez state :corp cr2)
(is (= 3 (:current-strength (refresh cr1))) "Normal strength over HQ")
(is (= 6 (:current-strength (refresh cr2))) "+3 strength over Archives")
(card-subroutine state :corp cr2 0)
(prompt-select :corp (find-card "Ice Wall" (:discard (get-corp))))
(prompt-choice :corp "HQ")
(is (= 3 (:credit (get-corp))) "Paid 1 credit to install as 2nd ICE over HQ"))))
(deftest curtain-wall
;; Curtain Wall - Strength boost when outermost ICE
(do-game
(new-game (default-corp [(qty "Curtain Wall" 1) (qty "Paper Wall" 1)])
(default-runner))
(core/gain state :corp :credit 10)
(play-from-hand state :corp "Curtain Wall" "HQ")
(let [curt (get-ice state :hq 0)]
(core/rez state :corp curt)
(is (= 10 (:current-strength (refresh curt)))
"Curtain Wall has +4 strength as outermost ICE")
(play-from-hand state :corp "Paper Wall" "HQ")
(let [paper (get-ice state :hq 1)]
(core/rez state :corp paper)
(is (= 6 (:current-strength (refresh curt))) "Curtain Wall back to default 6 strength")))))
(deftest data-hound
;; Data Hound - Full test
(do-game
(new-game (default-corp [(qty "Data Hound" 1)])
(default-runner [(qty "Sure Gamble" 2) (qty "Desperado" 1)
(qty "Corroder" 1) (qty "Patron" 1)]))
(starting-hand state :runner ["Sure Gamble"]) ;move all other cards to stack
(play-from-hand state :corp "Data Hound" "HQ")
(take-credits state :corp)
(let [dh (get-ice state :hq 0)]
(run-on state "HQ")
(core/rez state :corp dh)
(card-subroutine state :corp dh 0)
(prompt-choice :corp 2)
(prompt-choice :runner 0)
;; trash 1 card and rearrange the other 3
(prompt-choice :corp (find-card "Desperado" (:deck (get-runner))))
(is (= 1 (count (:discard (get-runner)))))
(prompt-choice :corp (find-card "Sure Gamble" (:deck (get-runner))))
(prompt-choice :corp (find-card "Corroder" (:deck (get-runner))))
(prompt-choice :corp (find-card "Patron" (:deck (get-runner))))
;; try starting over
(prompt-choice :corp "Start over")
(prompt-choice :corp (find-card "Patron" (:deck (get-runner))))
(prompt-choice :corp (find-card "Corroder" (:deck (get-runner))))
(prompt-choice :corp (find-card "Sure Gamble" (:deck (get-runner)))) ;this is the top card on stack
(prompt-choice :corp "Done")
(is (= "Sure Gamble" (:title (first (:deck (get-runner))))))
(is (= "CorPI:NAME:<NAME>END_PIder" (:title (second (:deck (get-runner))))))
(is (= "PI:NAME:<NAME>END_PI" (:title (second (rest (:deck (get-runner)))))))
(run-jack-out state)
(run-on state "HQ")
(card-subroutine state :corp dh 0)
(prompt-choice :corp 0)
(prompt-choice :runner 1)
;; trash the only card automatically
(is (= 2 (count (:discard (get-runner)))))
(is (= "PI:NAME:<NAME>END_PIder" (:title (first (:deck (get-runner)))))))))
(deftest draco
;; Dracō - Pay credits when rezzed to increase strength; trace to give 1 tag and end the run
(do-game
(new-game (default-corp [(qty "Dracō" 1)])
(default-runner))
(play-from-hand state :corp "Dracō" "HQ")
(take-credits state :corp)
(let [drac (get-ice state :hq 0)]
(run-on state "HQ")
(core/rez state :corp drac)
(prompt-choice :corp 4)
(is (= 4 (get-counters (refresh drac) :power)) "Dracō has 4 power counters")
(is (= 4 (:current-strength (refresh drac))) "Dracō is 4 strength")
(card-subroutine state :corp drac 0)
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (= 1 (:tag (get-runner))) "Runner took 1 tag")
(is (nil? (get-in @state [:run])) "Run was ended"))))
(deftest enigma
;; Enigma - Force Runner to lose 1 click if able
(do-game
(new-game (default-corp [(qty "Enigma" 1)])
(default-runner))
(play-from-hand state :corp "Enigma" "HQ")
(take-credits state :corp)
(let [enig (get-ice state :hq 0)]
(run-on state "HQ")
(is (= 3 (:click (get-runner))))
(core/rez state :corp enig)
(card-subroutine state :corp enig 0)
(is (= 2 (:click (get-runner))) "Runner lost 1 click"))))
(deftest excalibur
;; Excalibur - Prevent Runner from making another run this turn
(do-game
(new-game (default-corp [(qty "Excalibur" 1)])
(default-runner [(qty "Stimhack" 1)]))
(play-from-hand state :corp "Excalibur" "HQ")
(take-credits state :corp)
(let [excal (get-ice state :hq 0)]
(run-on state "HQ")
(core/rez state :corp excal)
(card-subroutine state :corp excal 0)
(run-jack-out state)
(run-on state "R&D")
(is (not (:run @state)) "No run initiated")
(is (= 3 (:click (get-runner))))
(play-from-hand state :runner "Stimhack")
(is (not (:run @state)) "No run initiated")
(is (= 3 (:click (get-runner))))
(is (empty? (:discard (get-runner))) "Card not played from Grip"))))
(deftest fenris
;; Fenris - Illicit ICE give Corp 1 bad publicity when rezzed
(do-game
(new-game (default-corp [(qty "Fenris" 1)])
(default-runner))
(play-from-hand state :corp "Fenris" "HQ")
(take-credits state :corp)
(let [fen (get-ice state :hq 0)]
(run-on state "HQ")
(core/rez state :corp fen)
(is (= 1 (:bad-publicity (get-corp))) "Gained 1 bad pub")
(card-subroutine state :corp fen 0)
(is (= 1 (:brain-damage (get-runner))) "Runner took 1 brain damage")
(is (= 1 (count (:discard (get-runner)))))
(is (= 4 (core/hand-size state :runner))))))
(deftest flare
;; Flare - Trash 1 program, do 2 unpreventable meat damage, and end the run
(do-game
(new-game (default-corp [(qty "Flare" 1)])
(default-runner [(qty "Plascrete Carapace" 1) (qty "Clone Chip" 1) (qty "Cache" 3)]))
(play-from-hand state :corp "Flare" "HQ")
(core/gain state :corp :credit 2)
(take-credits state :corp)
(play-from-hand state :runner "Plascrete Carapace")
(play-from-hand state :runner "Clone Chip")
(let [flare (get-ice state :hq 0)
cc (get-hardware state 1)]
(run-on state :hq)
(core/rez state :corp flare)
(card-subroutine state :corp flare 0)
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(prompt-select :corp cc)
(is (= 1 (count (get-in @state [:runner :rig :hardware]))) "Clone Chip trashed")
(is (empty? (:prompt (get-runner))) "Plascrete didn't try peventing meat damage")
(is (= 1 (count (:hand (get-runner)))))
(is (= 3 (count (:discard (get-runner)))) "Clone Chip plus 2 cards lost from damage in discard")
(is (not (:run @state)) "Run ended"))))
(deftest gemini-kicker
;; Gemini - Successfully trace to do 1 net damage; do 1 net damage if trace strength is 5 or more regardless of success
(do-game
(new-game (default-corp [(qty "Gemini" 1) (qty "Hedge Fund" 2)])
(default-runner [(qty "Sure Gamble" 3) (qty "Dirty Laundry" 2)]))
(play-from-hand state :corp "Gemini" "HQ")
(play-from-hand state :corp "Hedge Fund")
(play-from-hand state :corp "Hedge Fund")
(take-credits state :corp)
(let [gem (get-ice state :hq 0)]
(run-on state "HQ")
(core/rez state :corp gem)
(card-subroutine state :corp gem 0)
(prompt-choice :corp 3) ; boost to trace strength 5
(prompt-choice :runner 0)
(is (= 2 (count (:discard (get-runner)))) "Did 2 net damage")
(card-subroutine state :corp gem 0)
(prompt-choice :corp 3) ; boost to trace strength 5
(prompt-choice :runner 5) ; match trace
(is (= 3 (count (:discard (get-runner)))) "Did only 1 net damage for having trace strength 5 or more"))))
(deftest gemini-chronos-protocol
;; Gemini - Interaction with Chronos Protocol and kicker
(do-game
(new-game (make-deck "Chronos Protocol: Selective Mind-mapping" [(qty "Gemini" 1) (qty "Hedge Fund" 2)])
(default-runner [(qty "Sure Gamble" 1) (qty "Dirty Laundry" 2)]))
(play-from-hand state :corp "Gemini" "HQ")
(play-from-hand state :corp "Hedge Fund")
(play-from-hand state :corp "Hedge Fund")
(take-credits state :corp)
(let [gem (get-ice state :hq 0)]
(run-on state "HQ")
(core/rez state :corp gem)
(card-subroutine state :corp gem 0)
(prompt-choice :corp 3) ; boost to trace strength 5
(prompt-choice :runner 0)
(prompt-choice :corp "Yes")
(prompt-choice :corp (find-card "Sure Gamble" (:hand (get-runner))))
(is (= 2 (count (:discard (get-runner)))) "Did 2 net damage"))))
(deftest iq
;; IQ - Rez cost and strength equal to cards in HQ
(do-game
(new-game (default-corp [(qty "IQ" 3) (qty "Hedge Fund" 3)])
(default-runner))
(play-from-hand state :corp "Hedge Fund")
(play-from-hand state :corp "IQ" "R&D")
(let [iq1 (get-ice state :rd 0)]
(core/rez state :corp iq1)
(is (and (= 4 (count (:hand (get-corp))))
(= 4 (:current-strength (refresh iq1)))
(= 5 (:credit (get-corp)))) "4 cards in HQ: paid 4 to rez, has 4 strength")
(play-from-hand state :corp "IQ" "HQ")
(let [iq2 (get-ice state :hq 0)]
(core/rez state :corp iq2)
(is (and (= 3 (count (:hand (get-corp))))
(= 3 (:current-strength (refresh iq1)))
(= 3 (:current-strength (refresh iq2)))
(= 2 (:credit (get-corp)))) "3 cards in HQ: paid 3 to rez, both have 3 strength")))))
(deftest lockdown
;; Lockdown - Prevent Runner from drawing cards for the rest of the turn
(do-game
(new-game (default-corp [(qty "Lockdown" 1)])
(default-runner [(qty "Diesel" 2) (qty "Sure Gamble" 3)]))
(play-from-hand state :corp "Lockdown" "R&D")
(take-credits state :corp)
(core/move state :runner (find-card "Sure Gamble" (:hand (get-runner))) :deck)
(core/move state :runner (find-card "Sure Gamble" (:hand (get-runner))) :deck)
(core/move state :runner (find-card "Sure Gamble" (:hand (get-runner))) :deck)
(let [lock (get-ice state :rd 0)]
(run-on state "R&D")
(core/rez state :corp lock)
(card-subroutine state :corp lock 0)
(run-successful state)
(play-from-hand state :runner "Diesel")
(is (= 1 (count (:hand (get-runner)))) "No cards drawn")
(take-credits state :runner)
(take-credits state :corp)
(play-from-hand state :runner "Diesel")
(is (= 3 (count (:hand (get-runner))))
"New turn ends prevention; remaining 3 cards drawn from Stack"))))
(deftest lotus-field-unlowerable
;; Lotus Field strength cannot be lowered
(do-game
(new-game (default-corp [(qty "Lotus Field" 1) (qty "Lag Time" 1)])
(default-runner [(qty "Ice Carver" 1) (qty "Parasite" 1)]))
(play-from-hand state :corp "Lotus Field" "Archives")
(take-credits state :corp 2)
(let [lotus (get-ice state :archives 0)]
(core/rez state :corp lotus)
(play-from-hand state :runner "Ice Carver")
(run-on state "Archives")
(is (= 4 (:current-strength (refresh lotus))) "Lotus Field strength unchanged")
(run-jack-out state)
(play-from-hand state :runner "Parasite")
(prompt-select :runner lotus)
(is (= 1 (count (:hosted (refresh lotus)))) "Parasite hosted on Lotus Field")
(take-credits state :runner 1)
(take-credits state :corp)
(is (= 1 (core/get-virus-counters state :runner (first (:hosted (refresh lotus)))))
"Parasite has 1 virus counter")
(is (= 4 (:current-strength (refresh lotus))) "Lotus Field strength unchanged")
(take-credits state :runner)
(play-from-hand state :corp "Lag Time")
(is (= 5 (:current-strength (refresh lotus))) "Lotus Field strength increased")
(take-credits state :corp 2)
(is (= 5 (:current-strength (refresh lotus))) "Lotus Field strength increased"))))
(deftest mausolus
;; Mausolus - 3 adv tokens change the subroutines
(do-game
(new-game (default-corp [(qty "Mausolus" 1)])
(default-runner [(qty "NetChip" 5)]))
(play-from-hand state :corp "Mausolus" "HQ")
(let [mau (get-ice state :hq 0)]
(core/rez state :corp mau)
(take-credits state :corp)
(run-on state :hq)
(is (= 3 (:credit (get-corp))) "corp starts encounter with 3 crs")
(is (= 0 (count (:discard (get-runner)))) "runner starts encounter with no cards in heap")
(is (= 0 (:tag (get-runner))) "runner starts encounter with 0 tags")
(card-subroutine state :corp mau 0)
(card-subroutine state :corp mau 1)
(card-subroutine state :corp mau 2)
(is (= 4 (:credit (get-corp))) "corp gains 1 cr from mausolus")
(is (= 1 (count (:discard (get-runner)))) "corp does 1 net damage")
(is (= 1 (:tag (get-runner))) "corp gives 1 tag")
(run-jack-out state)
(take-credits state :runner)
(core/advance state :corp {:card (refresh mau)})
(core/advance state :corp {:card (refresh mau)})
(core/advance state :corp {:card (refresh mau)})
(run-on state :hq)
(is (= 1 (:credit (get-corp))) "corp starts encounter with 1 crs")
(is (= 1 (count (:discard (get-runner)))) "runner starts encounter with 1 card in heap")
(is (= 1 (:tag (get-runner))) "runner starts encounter with 1 tags")
(card-subroutine state :corp mau 0)
(card-subroutine state :corp mau 1)
(card-subroutine state :corp mau 2)
(is (= 4 (:credit (get-corp))) "corp gains 3 cr")
(is (= 4 (count (:discard (get-runner)))) "corp does 3 net damage")
(is (= 2 (:tag (get-runner))) "corp gives 1 tag")
(is (not (:run @state)) "Run is ended")
(is (get-in @state [:runner :register :unsuccessful-run]) "Run was unsuccessful"))))
(deftest minelayer
;; Minelayer - Install a piece of ICE in outermost position of Minelayer's server at no cost
(do-game
(new-game (default-corp [(qty "Minelayer" 1) (qty "Fire Wall" 1)])
(default-runner))
(play-from-hand state :corp "Minelayer" "HQ")
(take-credits state :corp)
(run-on state :hq)
(core/rez state :corp (get-ice state :hq 0))
(is (= 6 (:credit (get-corp))))
(card-subroutine state :corp (get-ice state :hq 0) 0)
(prompt-select :corp (find-card "Fire Wall" (:hand (get-corp))))
(is (= 2 (count (get-in @state [:corp :servers :hq :ices]))) "2 ICE protecting HQ")
(is (= 6 (:credit (get-corp))) "Didn't pay 1 credit to install as second ICE")))
(deftest morph-ice-subtype-changing
;; Morph ice gain and lose subtypes from normal advancements and placed advancements
(do-game
(new-game (default-corp [(qty "Wendigo" 1)
(qty "Shipment from SanSan" 1)
(qty "Superior Cyberwalls" 1)])
(default-runner))
(core/gain state :corp :click 2)
(play-from-hand state :corp "Superior Cyberwalls" "New remote")
(let [sc (get-content state :remote1 0)]
(score-agenda state :corp sc)
(play-from-hand state :corp "Wendigo" "HQ")
(let [wend (get-ice state :hq 0)]
(core/rez state :corp wend)
(is (= 4 (:current-strength (refresh wend))) "Wendigo at normal 4 strength")
(core/advance state :corp {:card (refresh wend)})
(is (= true (has? (refresh wend) :subtype "Barrier")) "Wendigo gained Barrier")
(is (= false (has? (refresh wend) :subtype "Code Gate")) "Wendigo lost Code Gate")
(is (= 5 (:current-strength (refresh wend))) "Wendigo boosted to 5 strength by scored Superior Cyberwalls")
(play-from-hand state :corp "Shipment from SanSan")
(prompt-choice :corp "1")
(prompt-select :corp wend)
(is (= false (has? (refresh wend) :subtype "Barrier")) "Wendigo lost Barrier")
(is (= true (has? (refresh wend) :subtype "Code Gate")) "Wendigo gained Code Gate")
(is (= 4 (:current-strength (refresh wend))) "Wendigo returned to normal 4 strength")))))
(deftest mother-goddess
;; Mother Goddess - Gains other ice subtypes
(do-game
(new-game (default-corp [(qty "Mother Goddess" 1) (qty "NEXT Bronze" 1)])
(default-runner))
(core/gain state :corp :credit 1)
(play-from-hand state :corp "Mother Goddess" "HQ")
(play-from-hand state :corp "NEXT Bronze" "R&D")
(let [mg (get-ice state :hq 0)
nb (get-ice state :rd 0)]
(core/rez state :corp mg)
(is (core/has-subtype? (refresh mg) "Mythic") "Mother Goddess has mythic")
(is (not (core/has-subtype? (refresh mg) "Code Gate")) "Mother Goddess does not have code gate")
(is (not (core/has-subtype? (refresh mg) "NEXT")) "Mother Goddess does not have NEXT")
(core/rez state :corp nb)
(is (core/has-subtype? (refresh mg) "Mythic") "Mother Goddess has mythic")
(is (core/has-subtype? (refresh mg) "Code Gate") "Mother Goddess has code gate")
(is (core/has-subtype? (refresh mg) "NEXT") "Mother Goddess has NEXT"))))
(deftest next-bronze
;; NEXT Bronze - Add 1 strength for every rezzed NEXT ice
(do-game
(new-game (default-corp [(qty "NEXT Bronze" 2) (qty "NEXT Silver" 1)])
(default-runner))
(core/gain state :corp :credit 2)
(play-from-hand state :corp "NEXT Bronze" "HQ")
(play-from-hand state :corp "NEXT Bronze" "R&D")
(play-from-hand state :corp "NEXT Silver" "Archives")
(let [nb1 (get-ice state :hq 0)
nb2 (get-ice state :rd 0)
ns1 (get-ice state :archives 0)]
(core/rez state :corp nb1)
(is (= 1 (:current-strength (refresh nb1)))
"NEXT Bronze at 1 strength: 1 rezzed NEXT ice")
(core/rez state :corp nb2)
(is (= 2 (:current-strength (refresh nb1)))
"NEXT Bronze at 2 strength: 2 rezzed NEXT ice")
(is (= 2 (:current-strength (refresh nb2)))
"NEXT Bronze at 2 strength: 2 rezzed NEXT ice")
(core/rez state :corp ns1)
(is (= 3 (:current-strength (refresh nb1)))
"NEXT Bronze at 3 strength: 3 rezzed NEXT ice")
(is (= 3 (:current-strength (refresh nb2)))
"NEXT Bronze at 3 strength: 3 rezzed NEXT ice"))))
(deftest resistor
;; Resistor - Strength equal to Runner tags, lose strength when Runner removes a tag
(do-game
(new-game (default-corp [(qty "Resistor" 1)])
(default-runner))
(play-from-hand state :corp "Resistor" "HQ")
(let [resistor (get-ice state :hq 0)]
(core/rez state :corp resistor)
(is (= 0 (:current-strength (refresh resistor))) "No Runner tags; 0 strength")
(core/tag-runner state :runner 2)
(is (= 2 (:tag (get-runner))))
(is (= 2 (:current-strength (refresh resistor))) "2 Runner tags; 2 strength")
(take-credits state :corp)
(core/remove-tag state :runner 1)
(is (= 1 (:current-strength (refresh resistor))) "Runner removed 1 tag; down to 1 strength"))))
(deftest searchlight
;; Searchlight - Trace bace equal to advancement counters
(do-game
(new-game (default-corp [(qty "Searchlight" 1)])
(default-runner))
(play-from-hand state :corp "Searchlight" "HQ")
(let [searchlight (get-ice state :hq 0)]
(core/rez state :corp searchlight)
(card-subroutine state :corp (refresh searchlight) 0)
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (= 0 (:tag (get-runner))) "Trace failed with 0 advancements")
(core/advance state :corp {:card (refresh searchlight)})
(card-subroutine state :corp (refresh searchlight) 0)
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (= 1 (:tag (get-runner))) "Trace succeeds with 0 advancements"))))
(deftest sherlock
;; Sherlock 1.0 - Trace to add an installed program to the top of Runner's Stack
(do-game
(new-game (default-corp [(qty "Sherlock 1.0" 1)])
(default-runner [(qty "Gordian Blade" 3) (qty "Sure Gamble" 3)]))
(play-from-hand state :corp "Sherlock 1.0" "HQ")
(take-credits state :corp)
(play-from-hand state :runner "Gordian Blade")
(run-on state :hq)
(core/rez state :corp (get-ice state :hq 0))
(card-subroutine state :corp (get-ice state :hq 0) 0)
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(prompt-select :corp (get-in @state [:runner :rig :program 0]))
(is (empty? (get-in @state [:runner :rig :program])) "Gordian uninstalled")
(is (= "Gordian Blade" (:title (first (:deck (get-runner))))) "Gordian on top of Stack")))
(deftest shiro
;; Shiro - Full test
(do-game
(new-game (default-corp [(qty "Shiro" 1) (qty "PI:NAME:<NAME>END_PI" 1)
(qty "PI:NAME:<NAME>END_PI" 1) (qty "PI:NAME:<NAME>END_PI" 1)])
(default-runner [(qty "R&D Interface" 1)]))
(starting-hand state :corp ["Shiro"])
(play-from-hand state :corp "Shiro" "HQ")
(take-credits state :corp)
(play-from-hand state :runner "R&D Interface")
(let [shiro (get-ice state :hq 0)]
(run-on state :hq)
(core/rez state :corp shiro)
(card-subroutine state :corp shiro 0)
(prompt-choice :corp (find-card "PI:NAME:<NAME>END_PI" (:deck (get-corp))))
(prompt-choice :corp (find-card "QuPI:NAME:<NAME>END_PI" (:deck (get-corp))))
(prompt-choice :corp (find-card "PI:NAME:<NAME>END_PI" (:deck (get-corp))))
;; try starting over
(prompt-choice :corp "Start over")
(prompt-choice :corp (find-card "PI:NAME:<NAME>END_PI" (:deck (get-corp))))
(prompt-choice :corp (find-card "PI:NAME:<NAME>END_PI" (:deck (get-corp))))
(prompt-choice :corp (find-card "PI:NAME:<NAME>END_PI" (:deck (get-corp)))) ;this is the top card of R&D
(prompt-choice :corp "Done")
(is (= "PI:NAME:<NAME>END_PI" (:title (first (:deck (get-corp))))))
(is (= "PI:NAME:<NAME>END_PI" (:title (second (:deck (get-corp))))))
(is (= "PI:NAME:<NAME>END_PI" (:title (second (rest (:deck (get-corp)))))))
(card-subroutine state :corp shiro 1)
(is (= (:cid (first (:deck (get-corp))))
(:cid (:card (first (:prompt (get-runner)))))) "Access the top card of R&D")
(prompt-choice :runner "No")
(is (= (:cid (second (:deck (get-corp))))
(:cid (:card (first (:prompt (get-runner)))))) "Access another card due to R&D Interface"))))
(deftest snowflake
;; Snowflake - Win a psi game to end the run
(do-game
(new-game (default-corp [(qty "Snowflake" 1)])
(default-runner))
(play-from-hand state :corp "Snowflake" "HQ")
(take-credits state :corp)
(run-on state :hq)
(let [sf (get-ice state :hq 0)]
(core/rez state :corp sf)
(card-subroutine state :corp sf 0)
(prompt-choice :corp "0 [Credits]")
(prompt-choice :runner "0 [Credits]")
(is (:run @state) "Runner won psi, run continues")
(card-subroutine state :corp sf 0)
(prompt-choice :corp "0 [Credits]")
(prompt-choice :runner "1 [Credits]")
(is (not (:run @state)) "Run ended"))))
(deftest special-offer-trash-ice-during-run
;; Special Offer trashes itself and updates the run position
(do-game
(new-game (default-corp [(qty "Ice Wall" 1) (qty "Special Offer" 1)])
(default-runner))
(play-from-hand state :corp "Ice Wall" "HQ")
(play-from-hand state :corp "Special Offer" "HQ")
(take-credits state :corp 1)
(run-on state "HQ")
(is (= 2 (:position (get-in @state [:run]))) "Initial position approaching Special Offer")
(let [special (get-ice state :hq 1)]
(core/rez state :corp special)
(is (= 4 (:credit (get-corp))))
(card-subroutine state :corp special 0)
(is (= 9 (:credit (get-corp))) "Special Offer paid 5 credits")
(is (= 1 (:position (get-in @state [:run])))
"Run position updated; now approaching Ice Wall"))))
(deftest tmi
;; TMI ICE test
(do-game
(new-game (default-corp [(qty "TMI" 3)])
(default-runner))
(play-from-hand state :corp "TMI" "HQ")
(let [tmi (get-ice state :hq 0)]
(core/rez state :corp tmi)
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (get-in (refresh tmi) [:rezzed])))))
(deftest tmi-derez
;; TMI ICE trace derez
(do-game
(new-game (default-corp [(qty "TMI" 3)])
(make-deck "Sunny Lebeau: Security Specialist" [(qty "Blackmail" 3)]))
(play-from-hand state :corp "TMI" "HQ")
(let [tmi (get-ice state :hq 0)]
(core/rez state :corp tmi)
(prompt-choice :corp 0)
(prompt-choice :runner 0)
(is (not (get-in (refresh tmi) [:rezzed]))))))
(deftest turing-positional-strength
;; Turing - Strength boosted when protecting a remote server
(do-game
(new-game (default-corp [(qty "Turing" 2) (qty "Hedge Fund" 1)])
(default-runner))
(play-from-hand state :corp "Hedge Fund")
(play-from-hand state :corp "Turing" "HQ")
(play-from-hand state :corp "Turing" "New remote")
(let [t1 (get-ice state :hq 0)
t2 (get-ice state :remote1 0)]
(core/rez state :corp t1)
(is (= 2 (:current-strength (refresh t1)))
"Turing default 2 strength over a central server")
(core/rez state :corp t2)
(is (= 5 (:current-strength (refresh t2)))
"Turing increased to 5 strength over a remote server"))))
(deftest wraparound
;; Wraparound - Strength boosted when no fracter is installed
(do-game
(new-game (default-corp [(qty "Wraparound" 1)])
(default-runner [(qty "Corroder" 1)]))
(play-from-hand state :corp "Wraparound" "HQ")
(let [wrap (get-ice state :hq 0)]
(core/rez state :corp wrap)
(is (= 7 (:current-strength (refresh wrap)))
"Wraparound +7 strength with no fracter in play")
(take-credits state :corp)
(play-from-hand state :runner "Corroder")
(is (= 0 (:current-strength (refresh wrap)))
"Wraparound 0 strength after Corroder installed"))))
|
[
{
"context": "(apply build-identity-table\n [\"Username\" username]\n [\"Link Expiration\" [:div {:style {:fl",
"end": 2726,
"score": 0.9820464253425598,
"start": 2718,
"tag": "USERNAME",
"value": "username"
},
{
"context": "expire-time (.now js/Date))\n username (:username fence-status)]\n [:div {}\n [:h4 {} di",
"end": 6350,
"score": 0.587714433670044,
"start": 6342,
"tag": "USERNAME",
"value": "username"
},
{
"context": " (build-identity-table\n [\"Username\" username]\n [\"Link Expiration\" [:div {}\n ",
"end": 6826,
"score": 0.6210898160934448,
"start": 6818,
"tag": "USERNAME",
"value": "username"
},
{
"context": "fc- Form\n {:get-field-keys\n (fn []\n (list :firstName :lastName :title :contactEmail :institute :instit",
"end": 9824,
"score": 0.5715492963790894,
"start": 9815,
"tag": "NAME",
"value": "firstName"
},
{
"context": "{:get-field-keys\n (fn []\n (list :firstName :lastName :title :contactEmail :institute :institutionalPro",
"end": 9834,
"score": 0.8910702466964722,
"start": 9826,
"tag": "NAME",
"value": "lastName"
},
{
"context": " (this :render-field :firstName \"First Name\")\n (this :render-field :last",
"end": 10573,
"score": 0.9449538588523865,
"start": 10563,
"tag": "NAME",
"value": "First Name"
},
{
"context": " (this :render-field :lastName \"Last Name\"))\n (this :render-field :title \"Title\"",
"end": 10638,
"score": 0.9397143721580505,
"start": 10629,
"tag": "NAME",
"value": "Last Name"
}
] | src/cljs/main/broadfcui/page/profile.cljs | ssyms/firecloud-ui | 26 | (ns broadfcui.page.profile
(:require
[dmohs.react :as react]
[clojure.string :as string]
[broadfcui.common :as common]
[broadfcui.common.components :as components]
[broadfcui.common.flex-utils :as flex]
[broadfcui.common.icons :as icons]
[broadfcui.common.links :as links]
[broadfcui.common.input :as input]
[broadfcui.common.style :as style]
[broadfcui.components.buttons :as buttons]
[broadfcui.components.foundation-dropdown :as dropdown]
[broadfcui.components.spinner :refer [spinner]]
[broadfcui.config :as config]
[broadfcui.endpoints :as endpoints]
[broadfcui.nav :as nav]
[broadfcui.utils :as utils]
[broadfcui.utils.user :as user]
))
(defn build-identity-table [& pairs]
[:table {:style {:borderSpacing "0 1rem" :marginTop "-1rem"}}
[:tbody {}
(map (fn [[k v]]
[:tr {}
[:td {:style {:width "12rem" :verticalAlign "top"}} k ":"]
[:td {} v]])
pairs)]])
(defn get-nih-link-href []
(str (get @config/config "shibbolethUrlRoot")
"/link-nih-account?redirect-url="
(js/encodeURIComponent
(let [loc (.-location js/window)]
(str (.-protocol loc) "//" (.-host loc) "/#profile/nih-username-token={token}")))))
(defn get-url-search-param [param-name]
(.get (js/URLSearchParams. js/window.location.search) param-name))
(defn auth-url-link [href text provider]
(if href
(links/create-external {:href href :target "_self" :data-test-id provider :class "provider-link"} text)
(spinner {:ref "pending-spinner"} "Getting link information...")))
(react/defc- NihLink
{:render
(fn [{:keys [state]}]
(let [status (:nih-status @state)
username (:linkedNihUsername status)
expire-time (* (:linkExpireTime status) 1000)
expired? (< expire-time (.now js/Date))
expiring-soon? (< expire-time (utils/_24-hours-from-now-ms))
datasets (:datasetPermissions status)]
[:div {}
[:h4 {} "NIH Account"
(dropdown/render-info-box
{:text
(str "Linking with eRA Commons will allow FireCloud to automatically determine if you can access "
"controlled datasets hosted in FireCloud (ex. TCGA) based on your valid dbGaP applications.")})]
(cond
(:error-message @state) (style/create-server-error-message (:error-message @state))
(:pending-nih-username-token @state)
(spinner {:ref "pending-spinner"} "Linking NIH account...")
(nil? username)
(links/create-external {:href (get-nih-link-href)} "Log-In to NIH to link your account")
:else
(apply build-identity-table
["Username" username]
["Link Expiration" [:div {:style {:flex "0 0 auto"}}
(if expired?
[:span {:style {:color "red"}} "Expired"]
[:span {:style {:color (when expiring-soon? "red")}} (common/format-date expire-time)])
[:div {}
(links/create-external {:href (get-nih-link-href)} "Log-In to NIH to re-link your account")]]]
(map
(fn [whitelist]
[(str (:name whitelist) " Authorization") [:div {:style {:flex "0 0 auto"}}
(if (:authorized whitelist)
[:span {:style {:color (:state-success style/colors)}} "Authorized"]
[:span {:style {:color (:text-light style/colors)}}
"Not Authorized"
(dropdown/render-info-box
{:text
[:div {}
"Your account was linked, but you are not authorized to view this controlled dataset. Please go "
(links/create-external {:href "https://dbgap.ncbi.nlm.nih.gov/aa/wga.cgi?page=login"} "here")
" to check your credentials."]})])]])
datasets)))]))
:component-did-mount
(fn [{:keys [this props state after-update]}]
(let [{:keys [nih-token]} props]
(if-not (nil? nih-token)
(do
(swap! state assoc :pending-nih-username-token nih-token)
(after-update #(this :link-nih-account nih-token))
;; Navigate to the parent (this page without the token), but replace the location so
;; the back button doesn't take the user back to the token.
(.replace (.-location js/window) (nav/get-link :profile)))
(this :load-nih-status))))
:component-did-update
(fn [{:keys [refs]}]
(when (@refs "pending-spinner")
(common/scroll-to-center (react/find-dom-node (@refs "pending-spinner")))))
:load-nih-status
(fn [{:keys [state]}]
(endpoints/profile-get-nih-status
(fn [{:keys [success? status-code status-text get-parsed-response]}]
(cond
success? (swap! state assoc :nih-status (get-parsed-response))
(= status-code 404) (swap! state assoc :nih-status :none)
:else
(swap! state assoc :error-message status-text)))))
:link-nih-account
(fn [{:keys [state]} token]
(endpoints/profile-link-nih-account
token
(fn [{:keys [success? get-parsed-response]}]
(if success?
(do (swap! state dissoc :pending-nih-username-token :nih-status)
(swap! state assoc :nih-status (get-parsed-response)))
(swap! state assoc :error-message "Failed to link NIH account")))))})
(react/defc- FenceLink
{:render
(fn [{:keys [props state]}]
(let [{:keys [fence-status error-message pending-fence-token auth-url]} @state
{:keys [display-name provider]} props
date-issued (.getTime (js/Date. (:issued_at fence-status)))
expire-time (utils/_30-days-from-date-ms date-issued)
expired? (< expire-time (.now js/Date))
username (:username fence-status)]
[:div {}
[:h4 {} display-name]
(cond
error-message
(style/create-server-error-message error-message)
pending-fence-token
(spinner {:ref "pending-spinner"} "Linking Framework Services account...")
(nil? username)
(auth-url-link auth-url "Log-In to Framework Services to link your account" provider)
:else
(build-identity-table
["Username" username]
["Link Expiration" [:div {}
(if expired?
[:span {:style {:color "red"}} "Expired"]
[:span {:style {:color (:state-success style/colors)}} (common/format-date expire-time)])
[:div {}
(auth-url-link auth-url "Log-In to Framework Services to re-link your account" provider)]]]))]))
:component-did-mount
(fn [{:keys [this props locals state after-update]}]
(let [fence-token (get-url-search-param "code")
base64-oauth-state (get-url-search-param "state")
oauth-state (when (not-empty base64-oauth-state) (utils/decode-base64-json base64-oauth-state))]
(if (and (= (:provider props) (:provider oauth-state)) (not-empty fence-token))
(do
(swap! state assoc :pending-fence-token fence-token)
(after-update #(this :link-fence-account fence-token))
;; Navigate to the parent (this page without the token), but replace the location so
;; the back button doesn't take the user back to the token.
(js/window.history.replaceState #{} "" (str "/#" (nav/get-path :profile))))))
(this :load-fence-status)
(this :get-auth-url))
:component-did-update
(fn [{:keys [refs]}]
(when (@refs "pending-spinner")
(common/scroll-to-center (react/find-dom-node (@refs "pending-spinner")))))
:load-fence-status
(fn [{:keys [props state]}]
(endpoints/profile-get-fence-status
(:provider props)
(fn [{:keys [success? status-code status-text get-parsed-response]}]
(cond
success? (swap! state assoc :fence-status (get-parsed-response))
(= status-code 404) (swap! state assoc :fence-status :none)
:else
(swap! state assoc :error-message status-text)))))
:get-auth-url
(fn [{:keys [props state]}]
(endpoints/get-provider-auth-url
(:provider props)
(fn [{:keys [success? status-code status-text get-parsed-response]}]
(cond
success? (swap! state assoc :auth-url (:url (get-parsed-response)))
(= status-code 404) (swap! state assoc :fence-status "Failed to retrieve Fence link")
:else
(swap! state assoc :error-message status-text)))))
:link-fence-account
(fn [{:keys [props state]} token]
(endpoints/profile-link-fence-account
(:provider props)
token
(js/encodeURIComponent
(let [loc js/window.location]
(str (.-protocol loc) "//" (.-host loc) "/#fence-callback")))
(fn [{:keys [success? get-parsed-response]}]
(if success?
(do (swap! state dissoc :pending-fence-token :fence-status)
(swap! state assoc :fence-status (get-parsed-response)))
(swap! state assoc :error-message "Failed to link Framework Services account")))))})
(react/defc- Form
{:get-field-keys
(fn []
(list :firstName :lastName :title :contactEmail :institute :institutionalProgram :programLocationCity
:programLocationState :programLocationCountry :pi))
:get-values
(fn [{:keys [state]}]
(reduce-kv (fn [r k v] (assoc r k (string/trim v))) {} (merge @user/profile (:values @state))))
:validation-errors
(fn [{:keys [refs this]}]
(apply input/validate refs (map name (this :get-field-keys))))
:render
(fn [{:keys [this props state]}]
(cond (:error-message @state) (style/create-server-error-message (:error-message @state))
@user/profile
[:div {}
[:h3 {:style {:marginBottom "0.5rem"}} "User Info"]
(flex/box {}
(this :render-field :firstName "First Name")
(this :render-field :lastName "Last Name"))
(this :render-field :title "Title")
(this :render-field :contactEmail "Contact Email for Notifications (if different)" :optional :email)
(flex/box {}
(this :render-field :institute "Institute")
(this :render-field :institutionalProgram "Institutional Program"))
(when-not (:new-registration? props)
[:div {:style {:clear "both" :margin "0.5em 0"}}
[:div {:style {:marginTop "0.5em" :fontSize "88%"}}
"Proxy Group"
(dropdown/render-info-box
{:text
[:div {} "For more information about proxy groups, see the "
(links/create-external {:href "https://software.broadinstitute.org/firecloud/documentation/article?id=11185"} "user guide") "."]})]
[:div {:data-test-id "proxyGroupEmail"
:style {:fontSize "88%" :padding "0.5em"}} (:userProxyGroupEmail @state)]])
(common/clear-both)
[:h3 {:style {:marginBottom "0.5rem"}} "Program Info"]
(style/create-form-label "Non-Profit Status")
(flex/box {:style {:fontSize "88%"}}
(this :render-radio-field :nonProfitStatus "Profit")
(this :render-radio-field :nonProfitStatus "Non-Profit"))
(this :render-field :pi "Principal Investigator/Program Lead")
(flex/box {}
(this :render-field :programLocationCity "City")
(this :render-field :programLocationState "State/Province")
(this :render-field :programLocationCountry "Country"))]
:else (spinner "Loading User Profile...")))
:render-radio-field
(fn [{:keys [state]} key value]
[:label {:style {:margin "0 1em 0.5em 0" :padding "0.5em 0"}}
[:input {:type "radio" :value value :name key
:checked (= value (get-in @state [:values key] (@user/profile key)))
:onChange #(swap! state assoc-in [:values key] value)}]
value])
:render-field
(fn [{:keys [state]} key label & flags]
(let [flag-set (set flags)
required? (not (flag-set :optional))
email? (flag-set :email)]
[:div {:style {:margin "0.5em 1em 0.5em 0"}}
[:label {}
(style/create-form-label label)
[input/TextField {:style {:width 200}
:data-test-id key
:defaultValue (@user/profile key)
:ref (name key)
:placeholder (when email? (user/get-email))
:predicates [(when required? (input/nonempty label))
(when email? (input/valid-email-or-empty label))]
:onChange #(swap! state assoc-in [:values key] (-> % .-target .-value))}]]]))
:component-will-mount
(fn [{:keys [state]}]
(when-not @user/profile
(user/reload-profile
(fn [{:keys [success? status-text]}]
(if success?
(swap! state assoc :loaded-profile? true)
(swap! state assoc :error-message status-text)))))
(endpoints/call-ajax-orch
{:endpoint (endpoints/proxy-group (user/get-email))
:on-done (fn [{:keys [success? get-parsed-response status-code raw-response]}]
(swap! state assoc :userProxyGroupEmail (if success?
(get-parsed-response)
(style/create-inline-error-message (str status-code ": " raw-response)))))}))})
(react/defc- Page
{:render
(fn [{:keys [this props state]}]
(let [new? (:new-registration? props)
update? (:update-registration? props)]
[:div {:style {:minHeight 300 :maxWidth 1250 :paddingTop "1.5rem" :margin "auto"}}
[:h2 {} (cond new? "New User Registration"
update? "Update Registration"
:else "Profile")]
[:div {:style {:display "flex"}}
[:div {:style {:width "50%"}}
[Form (merge {:ref "form"}
(select-keys props [:new-registration? :nih-token :fence-token]))]]
[:div {:style {:width "50%"}}
(when-not (:new-registration? props)
[:div {:style {:padding "1rem" :borderRadius 5 :backgroundColor (:background-light style/colors)}}
[:h3 {} "Identity & External Servers"]
[NihLink (select-keys props [:nih-token])]
[FenceLink {:provider "fence"
:display-name "DCP Framework Services by University of Chicago"}]
[FenceLink {:provider "dcf-fence"
:display-name "DCF Framework Services by University of Chicago"}]])]]
[:div {:style {:marginTop "2em"}}
(when (:server-error @state)
[:div {:style {:marginBottom "1em"}}
[components/ErrorViewer {:error (:server-error @state)}]])
(when (:validation-errors @state)
[:div {:style {:marginBottom "1em"}}
(style/create-flexbox
{}
[:span {:style {:paddingRight "1ex"}}
(icons/render-icon {:style {:color (:state-exception style/colors)}}
:warning)]
"Validation Errors:")
[:ul {}
(common/mapwrap :li (:validation-errors @state))]])
(cond
(:done? @state)
[:div {:style {:color (:state-success style/colors)}} "Profile saved!"]
(:in-progress? @state)
(spinner "Saving...")
:else
[buttons/Button {:text (if new? "Register" "Save Profile")
:onClick #(this :save)}])]]))
:save
(fn [{:keys [props state refs]}]
(utils/multi-swap! state (dissoc :server-error :validation-errors)
(assoc :in-progress? true))
(let [values ((@refs "form") :get-values)
validation-errors ((@refs "form") :validation-errors)]
(cond
(nil? validation-errors)
(endpoints/profile-set
values
(fn [{:keys [success? get-parsed-response]}]
(swap! state (fn [s]
(let [new-state (dissoc s :in-progress? :validation-errors)]
(if-not success?
(assoc new-state :server-error (get-parsed-response false))
(let [on-done (or (:on-done props) #(swap! state dissoc :done?))]
(js/setTimeout on-done 2000)
(user/reload-profile)
(assoc new-state :done? true))))))))
:else
(utils/multi-swap! state (dissoc :in-progress? :done?)
(assoc :validation-errors validation-errors)))))})
(defn render [props]
(react/create-element Page props))
(defn add-nav-paths []
(nav/defpath
:profile
{:component Page
:regex #"profile(?:/nih-username-token=([^\s/&]+))?"
;; account-linking redirects should not carry over between FC and Terra. Worst case, end user is redirected to Terra UI
;; and must re-initiate account linking.
:terra-redirect #(str "profile")
:make-props (fn [nih-token] (utils/restructure nih-token))
:make-path (fn [] "profile")})
(nav/defredirect
{:regex #"fence-callback"
:make-path (fn [] "profile")}))
| 71202 | (ns broadfcui.page.profile
(:require
[dmohs.react :as react]
[clojure.string :as string]
[broadfcui.common :as common]
[broadfcui.common.components :as components]
[broadfcui.common.flex-utils :as flex]
[broadfcui.common.icons :as icons]
[broadfcui.common.links :as links]
[broadfcui.common.input :as input]
[broadfcui.common.style :as style]
[broadfcui.components.buttons :as buttons]
[broadfcui.components.foundation-dropdown :as dropdown]
[broadfcui.components.spinner :refer [spinner]]
[broadfcui.config :as config]
[broadfcui.endpoints :as endpoints]
[broadfcui.nav :as nav]
[broadfcui.utils :as utils]
[broadfcui.utils.user :as user]
))
(defn build-identity-table [& pairs]
[:table {:style {:borderSpacing "0 1rem" :marginTop "-1rem"}}
[:tbody {}
(map (fn [[k v]]
[:tr {}
[:td {:style {:width "12rem" :verticalAlign "top"}} k ":"]
[:td {} v]])
pairs)]])
(defn get-nih-link-href []
(str (get @config/config "shibbolethUrlRoot")
"/link-nih-account?redirect-url="
(js/encodeURIComponent
(let [loc (.-location js/window)]
(str (.-protocol loc) "//" (.-host loc) "/#profile/nih-username-token={token}")))))
(defn get-url-search-param [param-name]
(.get (js/URLSearchParams. js/window.location.search) param-name))
(defn auth-url-link [href text provider]
(if href
(links/create-external {:href href :target "_self" :data-test-id provider :class "provider-link"} text)
(spinner {:ref "pending-spinner"} "Getting link information...")))
(react/defc- NihLink
{:render
(fn [{:keys [state]}]
(let [status (:nih-status @state)
username (:linkedNihUsername status)
expire-time (* (:linkExpireTime status) 1000)
expired? (< expire-time (.now js/Date))
expiring-soon? (< expire-time (utils/_24-hours-from-now-ms))
datasets (:datasetPermissions status)]
[:div {}
[:h4 {} "NIH Account"
(dropdown/render-info-box
{:text
(str "Linking with eRA Commons will allow FireCloud to automatically determine if you can access "
"controlled datasets hosted in FireCloud (ex. TCGA) based on your valid dbGaP applications.")})]
(cond
(:error-message @state) (style/create-server-error-message (:error-message @state))
(:pending-nih-username-token @state)
(spinner {:ref "pending-spinner"} "Linking NIH account...")
(nil? username)
(links/create-external {:href (get-nih-link-href)} "Log-In to NIH to link your account")
:else
(apply build-identity-table
["Username" username]
["Link Expiration" [:div {:style {:flex "0 0 auto"}}
(if expired?
[:span {:style {:color "red"}} "Expired"]
[:span {:style {:color (when expiring-soon? "red")}} (common/format-date expire-time)])
[:div {}
(links/create-external {:href (get-nih-link-href)} "Log-In to NIH to re-link your account")]]]
(map
(fn [whitelist]
[(str (:name whitelist) " Authorization") [:div {:style {:flex "0 0 auto"}}
(if (:authorized whitelist)
[:span {:style {:color (:state-success style/colors)}} "Authorized"]
[:span {:style {:color (:text-light style/colors)}}
"Not Authorized"
(dropdown/render-info-box
{:text
[:div {}
"Your account was linked, but you are not authorized to view this controlled dataset. Please go "
(links/create-external {:href "https://dbgap.ncbi.nlm.nih.gov/aa/wga.cgi?page=login"} "here")
" to check your credentials."]})])]])
datasets)))]))
:component-did-mount
(fn [{:keys [this props state after-update]}]
(let [{:keys [nih-token]} props]
(if-not (nil? nih-token)
(do
(swap! state assoc :pending-nih-username-token nih-token)
(after-update #(this :link-nih-account nih-token))
;; Navigate to the parent (this page without the token), but replace the location so
;; the back button doesn't take the user back to the token.
(.replace (.-location js/window) (nav/get-link :profile)))
(this :load-nih-status))))
:component-did-update
(fn [{:keys [refs]}]
(when (@refs "pending-spinner")
(common/scroll-to-center (react/find-dom-node (@refs "pending-spinner")))))
:load-nih-status
(fn [{:keys [state]}]
(endpoints/profile-get-nih-status
(fn [{:keys [success? status-code status-text get-parsed-response]}]
(cond
success? (swap! state assoc :nih-status (get-parsed-response))
(= status-code 404) (swap! state assoc :nih-status :none)
:else
(swap! state assoc :error-message status-text)))))
:link-nih-account
(fn [{:keys [state]} token]
(endpoints/profile-link-nih-account
token
(fn [{:keys [success? get-parsed-response]}]
(if success?
(do (swap! state dissoc :pending-nih-username-token :nih-status)
(swap! state assoc :nih-status (get-parsed-response)))
(swap! state assoc :error-message "Failed to link NIH account")))))})
(react/defc- FenceLink
{:render
(fn [{:keys [props state]}]
(let [{:keys [fence-status error-message pending-fence-token auth-url]} @state
{:keys [display-name provider]} props
date-issued (.getTime (js/Date. (:issued_at fence-status)))
expire-time (utils/_30-days-from-date-ms date-issued)
expired? (< expire-time (.now js/Date))
username (:username fence-status)]
[:div {}
[:h4 {} display-name]
(cond
error-message
(style/create-server-error-message error-message)
pending-fence-token
(spinner {:ref "pending-spinner"} "Linking Framework Services account...")
(nil? username)
(auth-url-link auth-url "Log-In to Framework Services to link your account" provider)
:else
(build-identity-table
["Username" username]
["Link Expiration" [:div {}
(if expired?
[:span {:style {:color "red"}} "Expired"]
[:span {:style {:color (:state-success style/colors)}} (common/format-date expire-time)])
[:div {}
(auth-url-link auth-url "Log-In to Framework Services to re-link your account" provider)]]]))]))
:component-did-mount
(fn [{:keys [this props locals state after-update]}]
(let [fence-token (get-url-search-param "code")
base64-oauth-state (get-url-search-param "state")
oauth-state (when (not-empty base64-oauth-state) (utils/decode-base64-json base64-oauth-state))]
(if (and (= (:provider props) (:provider oauth-state)) (not-empty fence-token))
(do
(swap! state assoc :pending-fence-token fence-token)
(after-update #(this :link-fence-account fence-token))
;; Navigate to the parent (this page without the token), but replace the location so
;; the back button doesn't take the user back to the token.
(js/window.history.replaceState #{} "" (str "/#" (nav/get-path :profile))))))
(this :load-fence-status)
(this :get-auth-url))
:component-did-update
(fn [{:keys [refs]}]
(when (@refs "pending-spinner")
(common/scroll-to-center (react/find-dom-node (@refs "pending-spinner")))))
:load-fence-status
(fn [{:keys [props state]}]
(endpoints/profile-get-fence-status
(:provider props)
(fn [{:keys [success? status-code status-text get-parsed-response]}]
(cond
success? (swap! state assoc :fence-status (get-parsed-response))
(= status-code 404) (swap! state assoc :fence-status :none)
:else
(swap! state assoc :error-message status-text)))))
:get-auth-url
(fn [{:keys [props state]}]
(endpoints/get-provider-auth-url
(:provider props)
(fn [{:keys [success? status-code status-text get-parsed-response]}]
(cond
success? (swap! state assoc :auth-url (:url (get-parsed-response)))
(= status-code 404) (swap! state assoc :fence-status "Failed to retrieve Fence link")
:else
(swap! state assoc :error-message status-text)))))
:link-fence-account
(fn [{:keys [props state]} token]
(endpoints/profile-link-fence-account
(:provider props)
token
(js/encodeURIComponent
(let [loc js/window.location]
(str (.-protocol loc) "//" (.-host loc) "/#fence-callback")))
(fn [{:keys [success? get-parsed-response]}]
(if success?
(do (swap! state dissoc :pending-fence-token :fence-status)
(swap! state assoc :fence-status (get-parsed-response)))
(swap! state assoc :error-message "Failed to link Framework Services account")))))})
(react/defc- Form
{:get-field-keys
(fn []
(list :<NAME> :<NAME> :title :contactEmail :institute :institutionalProgram :programLocationCity
:programLocationState :programLocationCountry :pi))
:get-values
(fn [{:keys [state]}]
(reduce-kv (fn [r k v] (assoc r k (string/trim v))) {} (merge @user/profile (:values @state))))
:validation-errors
(fn [{:keys [refs this]}]
(apply input/validate refs (map name (this :get-field-keys))))
:render
(fn [{:keys [this props state]}]
(cond (:error-message @state) (style/create-server-error-message (:error-message @state))
@user/profile
[:div {}
[:h3 {:style {:marginBottom "0.5rem"}} "User Info"]
(flex/box {}
(this :render-field :firstName "<NAME>")
(this :render-field :lastName "<NAME>"))
(this :render-field :title "Title")
(this :render-field :contactEmail "Contact Email for Notifications (if different)" :optional :email)
(flex/box {}
(this :render-field :institute "Institute")
(this :render-field :institutionalProgram "Institutional Program"))
(when-not (:new-registration? props)
[:div {:style {:clear "both" :margin "0.5em 0"}}
[:div {:style {:marginTop "0.5em" :fontSize "88%"}}
"Proxy Group"
(dropdown/render-info-box
{:text
[:div {} "For more information about proxy groups, see the "
(links/create-external {:href "https://software.broadinstitute.org/firecloud/documentation/article?id=11185"} "user guide") "."]})]
[:div {:data-test-id "proxyGroupEmail"
:style {:fontSize "88%" :padding "0.5em"}} (:userProxyGroupEmail @state)]])
(common/clear-both)
[:h3 {:style {:marginBottom "0.5rem"}} "Program Info"]
(style/create-form-label "Non-Profit Status")
(flex/box {:style {:fontSize "88%"}}
(this :render-radio-field :nonProfitStatus "Profit")
(this :render-radio-field :nonProfitStatus "Non-Profit"))
(this :render-field :pi "Principal Investigator/Program Lead")
(flex/box {}
(this :render-field :programLocationCity "City")
(this :render-field :programLocationState "State/Province")
(this :render-field :programLocationCountry "Country"))]
:else (spinner "Loading User Profile...")))
:render-radio-field
(fn [{:keys [state]} key value]
[:label {:style {:margin "0 1em 0.5em 0" :padding "0.5em 0"}}
[:input {:type "radio" :value value :name key
:checked (= value (get-in @state [:values key] (@user/profile key)))
:onChange #(swap! state assoc-in [:values key] value)}]
value])
:render-field
(fn [{:keys [state]} key label & flags]
(let [flag-set (set flags)
required? (not (flag-set :optional))
email? (flag-set :email)]
[:div {:style {:margin "0.5em 1em 0.5em 0"}}
[:label {}
(style/create-form-label label)
[input/TextField {:style {:width 200}
:data-test-id key
:defaultValue (@user/profile key)
:ref (name key)
:placeholder (when email? (user/get-email))
:predicates [(when required? (input/nonempty label))
(when email? (input/valid-email-or-empty label))]
:onChange #(swap! state assoc-in [:values key] (-> % .-target .-value))}]]]))
:component-will-mount
(fn [{:keys [state]}]
(when-not @user/profile
(user/reload-profile
(fn [{:keys [success? status-text]}]
(if success?
(swap! state assoc :loaded-profile? true)
(swap! state assoc :error-message status-text)))))
(endpoints/call-ajax-orch
{:endpoint (endpoints/proxy-group (user/get-email))
:on-done (fn [{:keys [success? get-parsed-response status-code raw-response]}]
(swap! state assoc :userProxyGroupEmail (if success?
(get-parsed-response)
(style/create-inline-error-message (str status-code ": " raw-response)))))}))})
(react/defc- Page
{:render
(fn [{:keys [this props state]}]
(let [new? (:new-registration? props)
update? (:update-registration? props)]
[:div {:style {:minHeight 300 :maxWidth 1250 :paddingTop "1.5rem" :margin "auto"}}
[:h2 {} (cond new? "New User Registration"
update? "Update Registration"
:else "Profile")]
[:div {:style {:display "flex"}}
[:div {:style {:width "50%"}}
[Form (merge {:ref "form"}
(select-keys props [:new-registration? :nih-token :fence-token]))]]
[:div {:style {:width "50%"}}
(when-not (:new-registration? props)
[:div {:style {:padding "1rem" :borderRadius 5 :backgroundColor (:background-light style/colors)}}
[:h3 {} "Identity & External Servers"]
[NihLink (select-keys props [:nih-token])]
[FenceLink {:provider "fence"
:display-name "DCP Framework Services by University of Chicago"}]
[FenceLink {:provider "dcf-fence"
:display-name "DCF Framework Services by University of Chicago"}]])]]
[:div {:style {:marginTop "2em"}}
(when (:server-error @state)
[:div {:style {:marginBottom "1em"}}
[components/ErrorViewer {:error (:server-error @state)}]])
(when (:validation-errors @state)
[:div {:style {:marginBottom "1em"}}
(style/create-flexbox
{}
[:span {:style {:paddingRight "1ex"}}
(icons/render-icon {:style {:color (:state-exception style/colors)}}
:warning)]
"Validation Errors:")
[:ul {}
(common/mapwrap :li (:validation-errors @state))]])
(cond
(:done? @state)
[:div {:style {:color (:state-success style/colors)}} "Profile saved!"]
(:in-progress? @state)
(spinner "Saving...")
:else
[buttons/Button {:text (if new? "Register" "Save Profile")
:onClick #(this :save)}])]]))
:save
(fn [{:keys [props state refs]}]
(utils/multi-swap! state (dissoc :server-error :validation-errors)
(assoc :in-progress? true))
(let [values ((@refs "form") :get-values)
validation-errors ((@refs "form") :validation-errors)]
(cond
(nil? validation-errors)
(endpoints/profile-set
values
(fn [{:keys [success? get-parsed-response]}]
(swap! state (fn [s]
(let [new-state (dissoc s :in-progress? :validation-errors)]
(if-not success?
(assoc new-state :server-error (get-parsed-response false))
(let [on-done (or (:on-done props) #(swap! state dissoc :done?))]
(js/setTimeout on-done 2000)
(user/reload-profile)
(assoc new-state :done? true))))))))
:else
(utils/multi-swap! state (dissoc :in-progress? :done?)
(assoc :validation-errors validation-errors)))))})
(defn render [props]
(react/create-element Page props))
(defn add-nav-paths []
(nav/defpath
:profile
{:component Page
:regex #"profile(?:/nih-username-token=([^\s/&]+))?"
;; account-linking redirects should not carry over between FC and Terra. Worst case, end user is redirected to Terra UI
;; and must re-initiate account linking.
:terra-redirect #(str "profile")
:make-props (fn [nih-token] (utils/restructure nih-token))
:make-path (fn [] "profile")})
(nav/defredirect
{:regex #"fence-callback"
:make-path (fn [] "profile")}))
| true | (ns broadfcui.page.profile
(:require
[dmohs.react :as react]
[clojure.string :as string]
[broadfcui.common :as common]
[broadfcui.common.components :as components]
[broadfcui.common.flex-utils :as flex]
[broadfcui.common.icons :as icons]
[broadfcui.common.links :as links]
[broadfcui.common.input :as input]
[broadfcui.common.style :as style]
[broadfcui.components.buttons :as buttons]
[broadfcui.components.foundation-dropdown :as dropdown]
[broadfcui.components.spinner :refer [spinner]]
[broadfcui.config :as config]
[broadfcui.endpoints :as endpoints]
[broadfcui.nav :as nav]
[broadfcui.utils :as utils]
[broadfcui.utils.user :as user]
))
(defn build-identity-table [& pairs]
[:table {:style {:borderSpacing "0 1rem" :marginTop "-1rem"}}
[:tbody {}
(map (fn [[k v]]
[:tr {}
[:td {:style {:width "12rem" :verticalAlign "top"}} k ":"]
[:td {} v]])
pairs)]])
(defn get-nih-link-href []
(str (get @config/config "shibbolethUrlRoot")
"/link-nih-account?redirect-url="
(js/encodeURIComponent
(let [loc (.-location js/window)]
(str (.-protocol loc) "//" (.-host loc) "/#profile/nih-username-token={token}")))))
(defn get-url-search-param [param-name]
(.get (js/URLSearchParams. js/window.location.search) param-name))
(defn auth-url-link [href text provider]
(if href
(links/create-external {:href href :target "_self" :data-test-id provider :class "provider-link"} text)
(spinner {:ref "pending-spinner"} "Getting link information...")))
(react/defc- NihLink
{:render
(fn [{:keys [state]}]
(let [status (:nih-status @state)
username (:linkedNihUsername status)
expire-time (* (:linkExpireTime status) 1000)
expired? (< expire-time (.now js/Date))
expiring-soon? (< expire-time (utils/_24-hours-from-now-ms))
datasets (:datasetPermissions status)]
[:div {}
[:h4 {} "NIH Account"
(dropdown/render-info-box
{:text
(str "Linking with eRA Commons will allow FireCloud to automatically determine if you can access "
"controlled datasets hosted in FireCloud (ex. TCGA) based on your valid dbGaP applications.")})]
(cond
(:error-message @state) (style/create-server-error-message (:error-message @state))
(:pending-nih-username-token @state)
(spinner {:ref "pending-spinner"} "Linking NIH account...")
(nil? username)
(links/create-external {:href (get-nih-link-href)} "Log-In to NIH to link your account")
:else
(apply build-identity-table
["Username" username]
["Link Expiration" [:div {:style {:flex "0 0 auto"}}
(if expired?
[:span {:style {:color "red"}} "Expired"]
[:span {:style {:color (when expiring-soon? "red")}} (common/format-date expire-time)])
[:div {}
(links/create-external {:href (get-nih-link-href)} "Log-In to NIH to re-link your account")]]]
(map
(fn [whitelist]
[(str (:name whitelist) " Authorization") [:div {:style {:flex "0 0 auto"}}
(if (:authorized whitelist)
[:span {:style {:color (:state-success style/colors)}} "Authorized"]
[:span {:style {:color (:text-light style/colors)}}
"Not Authorized"
(dropdown/render-info-box
{:text
[:div {}
"Your account was linked, but you are not authorized to view this controlled dataset. Please go "
(links/create-external {:href "https://dbgap.ncbi.nlm.nih.gov/aa/wga.cgi?page=login"} "here")
" to check your credentials."]})])]])
datasets)))]))
:component-did-mount
(fn [{:keys [this props state after-update]}]
(let [{:keys [nih-token]} props]
(if-not (nil? nih-token)
(do
(swap! state assoc :pending-nih-username-token nih-token)
(after-update #(this :link-nih-account nih-token))
;; Navigate to the parent (this page without the token), but replace the location so
;; the back button doesn't take the user back to the token.
(.replace (.-location js/window) (nav/get-link :profile)))
(this :load-nih-status))))
:component-did-update
(fn [{:keys [refs]}]
(when (@refs "pending-spinner")
(common/scroll-to-center (react/find-dom-node (@refs "pending-spinner")))))
:load-nih-status
(fn [{:keys [state]}]
(endpoints/profile-get-nih-status
(fn [{:keys [success? status-code status-text get-parsed-response]}]
(cond
success? (swap! state assoc :nih-status (get-parsed-response))
(= status-code 404) (swap! state assoc :nih-status :none)
:else
(swap! state assoc :error-message status-text)))))
:link-nih-account
(fn [{:keys [state]} token]
(endpoints/profile-link-nih-account
token
(fn [{:keys [success? get-parsed-response]}]
(if success?
(do (swap! state dissoc :pending-nih-username-token :nih-status)
(swap! state assoc :nih-status (get-parsed-response)))
(swap! state assoc :error-message "Failed to link NIH account")))))})
(react/defc- FenceLink
{:render
(fn [{:keys [props state]}]
(let [{:keys [fence-status error-message pending-fence-token auth-url]} @state
{:keys [display-name provider]} props
date-issued (.getTime (js/Date. (:issued_at fence-status)))
expire-time (utils/_30-days-from-date-ms date-issued)
expired? (< expire-time (.now js/Date))
username (:username fence-status)]
[:div {}
[:h4 {} display-name]
(cond
error-message
(style/create-server-error-message error-message)
pending-fence-token
(spinner {:ref "pending-spinner"} "Linking Framework Services account...")
(nil? username)
(auth-url-link auth-url "Log-In to Framework Services to link your account" provider)
:else
(build-identity-table
["Username" username]
["Link Expiration" [:div {}
(if expired?
[:span {:style {:color "red"}} "Expired"]
[:span {:style {:color (:state-success style/colors)}} (common/format-date expire-time)])
[:div {}
(auth-url-link auth-url "Log-In to Framework Services to re-link your account" provider)]]]))]))
:component-did-mount
(fn [{:keys [this props locals state after-update]}]
(let [fence-token (get-url-search-param "code")
base64-oauth-state (get-url-search-param "state")
oauth-state (when (not-empty base64-oauth-state) (utils/decode-base64-json base64-oauth-state))]
(if (and (= (:provider props) (:provider oauth-state)) (not-empty fence-token))
(do
(swap! state assoc :pending-fence-token fence-token)
(after-update #(this :link-fence-account fence-token))
;; Navigate to the parent (this page without the token), but replace the location so
;; the back button doesn't take the user back to the token.
(js/window.history.replaceState #{} "" (str "/#" (nav/get-path :profile))))))
(this :load-fence-status)
(this :get-auth-url))
:component-did-update
(fn [{:keys [refs]}]
(when (@refs "pending-spinner")
(common/scroll-to-center (react/find-dom-node (@refs "pending-spinner")))))
:load-fence-status
(fn [{:keys [props state]}]
(endpoints/profile-get-fence-status
(:provider props)
(fn [{:keys [success? status-code status-text get-parsed-response]}]
(cond
success? (swap! state assoc :fence-status (get-parsed-response))
(= status-code 404) (swap! state assoc :fence-status :none)
:else
(swap! state assoc :error-message status-text)))))
:get-auth-url
(fn [{:keys [props state]}]
(endpoints/get-provider-auth-url
(:provider props)
(fn [{:keys [success? status-code status-text get-parsed-response]}]
(cond
success? (swap! state assoc :auth-url (:url (get-parsed-response)))
(= status-code 404) (swap! state assoc :fence-status "Failed to retrieve Fence link")
:else
(swap! state assoc :error-message status-text)))))
:link-fence-account
(fn [{:keys [props state]} token]
(endpoints/profile-link-fence-account
(:provider props)
token
(js/encodeURIComponent
(let [loc js/window.location]
(str (.-protocol loc) "//" (.-host loc) "/#fence-callback")))
(fn [{:keys [success? get-parsed-response]}]
(if success?
(do (swap! state dissoc :pending-fence-token :fence-status)
(swap! state assoc :fence-status (get-parsed-response)))
(swap! state assoc :error-message "Failed to link Framework Services account")))))})
(react/defc- Form
{:get-field-keys
(fn []
(list :PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI :title :contactEmail :institute :institutionalProgram :programLocationCity
:programLocationState :programLocationCountry :pi))
:get-values
(fn [{:keys [state]}]
(reduce-kv (fn [r k v] (assoc r k (string/trim v))) {} (merge @user/profile (:values @state))))
:validation-errors
(fn [{:keys [refs this]}]
(apply input/validate refs (map name (this :get-field-keys))))
:render
(fn [{:keys [this props state]}]
(cond (:error-message @state) (style/create-server-error-message (:error-message @state))
@user/profile
[:div {}
[:h3 {:style {:marginBottom "0.5rem"}} "User Info"]
(flex/box {}
(this :render-field :firstName "PI:NAME:<NAME>END_PI")
(this :render-field :lastName "PI:NAME:<NAME>END_PI"))
(this :render-field :title "Title")
(this :render-field :contactEmail "Contact Email for Notifications (if different)" :optional :email)
(flex/box {}
(this :render-field :institute "Institute")
(this :render-field :institutionalProgram "Institutional Program"))
(when-not (:new-registration? props)
[:div {:style {:clear "both" :margin "0.5em 0"}}
[:div {:style {:marginTop "0.5em" :fontSize "88%"}}
"Proxy Group"
(dropdown/render-info-box
{:text
[:div {} "For more information about proxy groups, see the "
(links/create-external {:href "https://software.broadinstitute.org/firecloud/documentation/article?id=11185"} "user guide") "."]})]
[:div {:data-test-id "proxyGroupEmail"
:style {:fontSize "88%" :padding "0.5em"}} (:userProxyGroupEmail @state)]])
(common/clear-both)
[:h3 {:style {:marginBottom "0.5rem"}} "Program Info"]
(style/create-form-label "Non-Profit Status")
(flex/box {:style {:fontSize "88%"}}
(this :render-radio-field :nonProfitStatus "Profit")
(this :render-radio-field :nonProfitStatus "Non-Profit"))
(this :render-field :pi "Principal Investigator/Program Lead")
(flex/box {}
(this :render-field :programLocationCity "City")
(this :render-field :programLocationState "State/Province")
(this :render-field :programLocationCountry "Country"))]
:else (spinner "Loading User Profile...")))
:render-radio-field
(fn [{:keys [state]} key value]
[:label {:style {:margin "0 1em 0.5em 0" :padding "0.5em 0"}}
[:input {:type "radio" :value value :name key
:checked (= value (get-in @state [:values key] (@user/profile key)))
:onChange #(swap! state assoc-in [:values key] value)}]
value])
:render-field
(fn [{:keys [state]} key label & flags]
(let [flag-set (set flags)
required? (not (flag-set :optional))
email? (flag-set :email)]
[:div {:style {:margin "0.5em 1em 0.5em 0"}}
[:label {}
(style/create-form-label label)
[input/TextField {:style {:width 200}
:data-test-id key
:defaultValue (@user/profile key)
:ref (name key)
:placeholder (when email? (user/get-email))
:predicates [(when required? (input/nonempty label))
(when email? (input/valid-email-or-empty label))]
:onChange #(swap! state assoc-in [:values key] (-> % .-target .-value))}]]]))
:component-will-mount
(fn [{:keys [state]}]
(when-not @user/profile
(user/reload-profile
(fn [{:keys [success? status-text]}]
(if success?
(swap! state assoc :loaded-profile? true)
(swap! state assoc :error-message status-text)))))
(endpoints/call-ajax-orch
{:endpoint (endpoints/proxy-group (user/get-email))
:on-done (fn [{:keys [success? get-parsed-response status-code raw-response]}]
(swap! state assoc :userProxyGroupEmail (if success?
(get-parsed-response)
(style/create-inline-error-message (str status-code ": " raw-response)))))}))})
(react/defc- Page
{:render
(fn [{:keys [this props state]}]
(let [new? (:new-registration? props)
update? (:update-registration? props)]
[:div {:style {:minHeight 300 :maxWidth 1250 :paddingTop "1.5rem" :margin "auto"}}
[:h2 {} (cond new? "New User Registration"
update? "Update Registration"
:else "Profile")]
[:div {:style {:display "flex"}}
[:div {:style {:width "50%"}}
[Form (merge {:ref "form"}
(select-keys props [:new-registration? :nih-token :fence-token]))]]
[:div {:style {:width "50%"}}
(when-not (:new-registration? props)
[:div {:style {:padding "1rem" :borderRadius 5 :backgroundColor (:background-light style/colors)}}
[:h3 {} "Identity & External Servers"]
[NihLink (select-keys props [:nih-token])]
[FenceLink {:provider "fence"
:display-name "DCP Framework Services by University of Chicago"}]
[FenceLink {:provider "dcf-fence"
:display-name "DCF Framework Services by University of Chicago"}]])]]
[:div {:style {:marginTop "2em"}}
(when (:server-error @state)
[:div {:style {:marginBottom "1em"}}
[components/ErrorViewer {:error (:server-error @state)}]])
(when (:validation-errors @state)
[:div {:style {:marginBottom "1em"}}
(style/create-flexbox
{}
[:span {:style {:paddingRight "1ex"}}
(icons/render-icon {:style {:color (:state-exception style/colors)}}
:warning)]
"Validation Errors:")
[:ul {}
(common/mapwrap :li (:validation-errors @state))]])
(cond
(:done? @state)
[:div {:style {:color (:state-success style/colors)}} "Profile saved!"]
(:in-progress? @state)
(spinner "Saving...")
:else
[buttons/Button {:text (if new? "Register" "Save Profile")
:onClick #(this :save)}])]]))
:save
(fn [{:keys [props state refs]}]
(utils/multi-swap! state (dissoc :server-error :validation-errors)
(assoc :in-progress? true))
(let [values ((@refs "form") :get-values)
validation-errors ((@refs "form") :validation-errors)]
(cond
(nil? validation-errors)
(endpoints/profile-set
values
(fn [{:keys [success? get-parsed-response]}]
(swap! state (fn [s]
(let [new-state (dissoc s :in-progress? :validation-errors)]
(if-not success?
(assoc new-state :server-error (get-parsed-response false))
(let [on-done (or (:on-done props) #(swap! state dissoc :done?))]
(js/setTimeout on-done 2000)
(user/reload-profile)
(assoc new-state :done? true))))))))
:else
(utils/multi-swap! state (dissoc :in-progress? :done?)
(assoc :validation-errors validation-errors)))))})
(defn render [props]
(react/create-element Page props))
(defn add-nav-paths []
(nav/defpath
:profile
{:component Page
:regex #"profile(?:/nih-username-token=([^\s/&]+))?"
;; account-linking redirects should not carry over between FC and Terra. Worst case, end user is redirected to Terra UI
;; and must re-initiate account linking.
:terra-redirect #(str "profile")
:make-props (fn [nih-token] (utils/restructure nih-token))
:make-path (fn [] "profile")})
(nav/defredirect
{:regex #"fence-callback"
:make-path (fn [] "profile")}))
|
[
{
"context": "-------------------------------\n;;\n;;\n;; Author: PLIQUE Guillaume (Yomguithereal)\n;; Version: 0.1\n;;\n(ns clj-fuzz",
"end": 222,
"score": 0.999854326248169,
"start": 206,
"tag": "NAME",
"value": "PLIQUE Guillaume"
},
{
"context": "------------\n;;\n;;\n;; Author: PLIQUE Guillaume (Yomguithereal)\n;; Version: 0.1\n;;\n(ns clj-fuzzy.dice-test\n (",
"end": 237,
"score": 0.9992555975914001,
"start": 224,
"tag": "USERNAME",
"value": "Yomguithereal"
}
] | test/clj_fuzzy/dice_test.clj | sooheon/clj-fuzzy | 222 | ;; -------------------------------------------------------------------
;; clj-fuzzy Sorensen Dice Coefficient Tests
;; -------------------------------------------------------------------
;;
;;
;; Author: PLIQUE Guillaume (Yomguithereal)
;; Version: 0.1
;;
(ns clj-fuzzy.dice-test
(:require [clojure.test :refer :all]
[clj-fuzzy.dice :refer :all]))
(deftest coefficient-test
(is (= 1.0 (coefficient "healed" "healed")))
(is (= 0.8 (coefficient "healed" "sealed")))
(is (= 0.5454545454545454 (coefficient "healed" "healthy")))
(is (= 0.4444444444444444 (coefficient "healed" "heard")))
(is (= 0.4 (coefficient "healed" "herded")))
(is (= 0.25 (coefficient "healed" "help")))
(is (= 0.0 (coefficient "healed" "sold")))
(is (= 1.0 (coefficient "tomato" "tomato")))
(is (= 0.0 (coefficient "h" "help")))
(is (= 1.0 (coefficient "h" "h")))
(is (= 1.0 (coefficient "" "")))
(is (= 0.0 (coefficient "h" "g")))
(is (= 1.0 (coefficient "bar" "baz" :n 0)))
(is (= 0.6666666666666666 (coefficient "bar" "baz" :n 1)))
(is (= 0.5 (coefficient "bar" "baz" :n 2)))
(is (= 0.0 (coefficient "bar" "baz" :n 3))))
| 36902 | ;; -------------------------------------------------------------------
;; clj-fuzzy Sorensen Dice Coefficient Tests
;; -------------------------------------------------------------------
;;
;;
;; Author: <NAME> (Yomguithereal)
;; Version: 0.1
;;
(ns clj-fuzzy.dice-test
(:require [clojure.test :refer :all]
[clj-fuzzy.dice :refer :all]))
(deftest coefficient-test
(is (= 1.0 (coefficient "healed" "healed")))
(is (= 0.8 (coefficient "healed" "sealed")))
(is (= 0.5454545454545454 (coefficient "healed" "healthy")))
(is (= 0.4444444444444444 (coefficient "healed" "heard")))
(is (= 0.4 (coefficient "healed" "herded")))
(is (= 0.25 (coefficient "healed" "help")))
(is (= 0.0 (coefficient "healed" "sold")))
(is (= 1.0 (coefficient "tomato" "tomato")))
(is (= 0.0 (coefficient "h" "help")))
(is (= 1.0 (coefficient "h" "h")))
(is (= 1.0 (coefficient "" "")))
(is (= 0.0 (coefficient "h" "g")))
(is (= 1.0 (coefficient "bar" "baz" :n 0)))
(is (= 0.6666666666666666 (coefficient "bar" "baz" :n 1)))
(is (= 0.5 (coefficient "bar" "baz" :n 2)))
(is (= 0.0 (coefficient "bar" "baz" :n 3))))
| true | ;; -------------------------------------------------------------------
;; clj-fuzzy Sorensen Dice Coefficient Tests
;; -------------------------------------------------------------------
;;
;;
;; Author: PI:NAME:<NAME>END_PI (Yomguithereal)
;; Version: 0.1
;;
(ns clj-fuzzy.dice-test
(:require [clojure.test :refer :all]
[clj-fuzzy.dice :refer :all]))
(deftest coefficient-test
(is (= 1.0 (coefficient "healed" "healed")))
(is (= 0.8 (coefficient "healed" "sealed")))
(is (= 0.5454545454545454 (coefficient "healed" "healthy")))
(is (= 0.4444444444444444 (coefficient "healed" "heard")))
(is (= 0.4 (coefficient "healed" "herded")))
(is (= 0.25 (coefficient "healed" "help")))
(is (= 0.0 (coefficient "healed" "sold")))
(is (= 1.0 (coefficient "tomato" "tomato")))
(is (= 0.0 (coefficient "h" "help")))
(is (= 1.0 (coefficient "h" "h")))
(is (= 1.0 (coefficient "" "")))
(is (= 0.0 (coefficient "h" "g")))
(is (= 1.0 (coefficient "bar" "baz" :n 0)))
(is (= 0.6666666666666666 (coefficient "bar" "baz" :n 1)))
(is (= 0.5 (coefficient "bar" "baz" :n 2)))
(is (= 0.0 (coefficient "bar" "baz" :n 3))))
|
[
{
"context": "ettings\n (value [env params]\n [{:id 1 :value \"Gorgon\"}\n {:id 2 :value \"Thraser\"}\n {:id 3 :valu",
"end": 506,
"score": 0.8227741718292236,
"start": 500,
"tag": "NAME",
"value": "Gorgon"
},
{
"context": "\n [{:id 1 :value \"Gorgon\"}\n {:id 2 :value \"Thraser\"}\n {:id 3 :value \"Under\"}]))\n",
"end": 531,
"score": 0.5372723340988159,
"start": 529,
"tag": "NAME",
"value": "Th"
}
] | src/demos/recipes/tabbed_interface_server.clj | weirp/fulcrodev | 0 | (ns recipes.tabbed-interface-server
(:require [om.next.server :as om]
[om.next.impl.parser :as op]
[fulcro.server :refer [defquery-root defquery-entity defmutation server-mutate]]
[taoensso.timbre :as timbre]
[fulcro.easy-server :as core]))
; This is the only thing we wrote for the server...just return some value so we can
; see it really talked to the server for this query.
(defquery-root :all-settings
(value [env params]
[{:id 1 :value "Gorgon"}
{:id 2 :value "Thraser"}
{:id 3 :value "Under"}]))
| 80807 | (ns recipes.tabbed-interface-server
(:require [om.next.server :as om]
[om.next.impl.parser :as op]
[fulcro.server :refer [defquery-root defquery-entity defmutation server-mutate]]
[taoensso.timbre :as timbre]
[fulcro.easy-server :as core]))
; This is the only thing we wrote for the server...just return some value so we can
; see it really talked to the server for this query.
(defquery-root :all-settings
(value [env params]
[{:id 1 :value "<NAME>"}
{:id 2 :value "<NAME>raser"}
{:id 3 :value "Under"}]))
| true | (ns recipes.tabbed-interface-server
(:require [om.next.server :as om]
[om.next.impl.parser :as op]
[fulcro.server :refer [defquery-root defquery-entity defmutation server-mutate]]
[taoensso.timbre :as timbre]
[fulcro.easy-server :as core]))
; This is the only thing we wrote for the server...just return some value so we can
; see it really talked to the server for this query.
(defquery-root :all-settings
(value [env params]
[{:id 1 :value "PI:NAME:<NAME>END_PI"}
{:id 2 :value "PI:NAME:<NAME>END_PIraser"}
{:id 3 :value "Under"}]))
|
[
{
"context": "tion-method)\n :email email\n :password new-password}})\n (auth-password/identifier->user-id email))\n\n",
"end": 1500,
"score": 0.9792216420173645,
"start": 1488,
"tag": "PASSWORD",
"value": "new-password"
}
] | code/src/sixsq/nuvla/server/resources/callback_join_group.clj | nuvla/server | 6 | (ns sixsq.nuvla.server.resources.callback-join-group
"
Allow invited user to join a group. The process creating this callback sends the
action link to the email address to be verified. When the execute link is
visited, the email identifier is marked as validated.
"
(:require
[sixsq.nuvla.auth.password :as auth-password]
[sixsq.nuvla.auth.utils :as auth]
[sixsq.nuvla.server.resources.callback :as callback]
[sixsq.nuvla.server.resources.callback.utils :as utils]
[sixsq.nuvla.server.resources.common.crud :as crud]
[sixsq.nuvla.server.resources.common.std-crud :as std-crud]
[sixsq.nuvla.server.resources.common.utils :as u]
[sixsq.nuvla.server.resources.credential-hashed-password :as hashed-password]
[sixsq.nuvla.server.resources.user-template :as p]
[sixsq.nuvla.server.resources.user-template-minimum :as user-minimum]
[sixsq.nuvla.server.resources.user.utils :as user-utils]
[sixsq.nuvla.server.util.response :as r]))
(def ^:const action-name "join-group")
(def create-callback (partial callback/create action-name))
(defn create-user
[email new-password]
(when-not (hashed-password/acceptable-password? new-password)
(throw (r/ex-response hashed-password/acceptable-password-msg 400)))
(std-crud/add-if-absent
(str user-utils/resource-url " '" email "'") user-utils/resource-url
{:template
{:href (str p/resource-type "/" user-minimum/registration-method)
:email email
:password new-password}})
(auth-password/identifier->user-id email))
(defn add-user-to-group
[group-id user-id]
(let [{:keys [users]} (crud/retrieve-by-id-as-admin group-id)
{:keys [status body]} (crud/edit
{:params {:uuid (u/id->uuid group-id)
:resource-name (u/id->resource-type group-id)}
:nuvla/authn auth/internal-identity
:body {:users (-> users (conj user-id) distinct vec)}})]
(if (= 200 status)
body
(let [msg (str (format "adding %s to %s failed:" user-id group-id)
status (:message body))]
(throw (r/ex-bad-request msg))))))
(defmethod callback/execute action-name
[{callback-id :id
{existing-user-id :user-id
email :email
redirect-url :redirect-url} :data
{group-id :href} :target-resource :as _callback-resource}
{{:keys [new-password]} :body :as _request}]
(try
(let [user-id (or existing-user-id
(auth-password/identifier->user-id email) ;; in case user created an account in meantime
(create-user email new-password))
msg (format "'%s' successfully joined '%s'" user-id group-id)]
(add-user-to-group group-id user-id)
(utils/callback-succeeded! callback-id)
(if (and existing-user-id redirect-url)
(r/map-response msg 303 callback-id redirect-url)
(r/map-response msg 200)))
(catch Exception e
(utils/callback-failed! callback-id)
(or (ex-data e) (throw e)))))
| 63957 | (ns sixsq.nuvla.server.resources.callback-join-group
"
Allow invited user to join a group. The process creating this callback sends the
action link to the email address to be verified. When the execute link is
visited, the email identifier is marked as validated.
"
(:require
[sixsq.nuvla.auth.password :as auth-password]
[sixsq.nuvla.auth.utils :as auth]
[sixsq.nuvla.server.resources.callback :as callback]
[sixsq.nuvla.server.resources.callback.utils :as utils]
[sixsq.nuvla.server.resources.common.crud :as crud]
[sixsq.nuvla.server.resources.common.std-crud :as std-crud]
[sixsq.nuvla.server.resources.common.utils :as u]
[sixsq.nuvla.server.resources.credential-hashed-password :as hashed-password]
[sixsq.nuvla.server.resources.user-template :as p]
[sixsq.nuvla.server.resources.user-template-minimum :as user-minimum]
[sixsq.nuvla.server.resources.user.utils :as user-utils]
[sixsq.nuvla.server.util.response :as r]))
(def ^:const action-name "join-group")
(def create-callback (partial callback/create action-name))
(defn create-user
[email new-password]
(when-not (hashed-password/acceptable-password? new-password)
(throw (r/ex-response hashed-password/acceptable-password-msg 400)))
(std-crud/add-if-absent
(str user-utils/resource-url " '" email "'") user-utils/resource-url
{:template
{:href (str p/resource-type "/" user-minimum/registration-method)
:email email
:password <PASSWORD>}})
(auth-password/identifier->user-id email))
(defn add-user-to-group
[group-id user-id]
(let [{:keys [users]} (crud/retrieve-by-id-as-admin group-id)
{:keys [status body]} (crud/edit
{:params {:uuid (u/id->uuid group-id)
:resource-name (u/id->resource-type group-id)}
:nuvla/authn auth/internal-identity
:body {:users (-> users (conj user-id) distinct vec)}})]
(if (= 200 status)
body
(let [msg (str (format "adding %s to %s failed:" user-id group-id)
status (:message body))]
(throw (r/ex-bad-request msg))))))
(defmethod callback/execute action-name
[{callback-id :id
{existing-user-id :user-id
email :email
redirect-url :redirect-url} :data
{group-id :href} :target-resource :as _callback-resource}
{{:keys [new-password]} :body :as _request}]
(try
(let [user-id (or existing-user-id
(auth-password/identifier->user-id email) ;; in case user created an account in meantime
(create-user email new-password))
msg (format "'%s' successfully joined '%s'" user-id group-id)]
(add-user-to-group group-id user-id)
(utils/callback-succeeded! callback-id)
(if (and existing-user-id redirect-url)
(r/map-response msg 303 callback-id redirect-url)
(r/map-response msg 200)))
(catch Exception e
(utils/callback-failed! callback-id)
(or (ex-data e) (throw e)))))
| true | (ns sixsq.nuvla.server.resources.callback-join-group
"
Allow invited user to join a group. The process creating this callback sends the
action link to the email address to be verified. When the execute link is
visited, the email identifier is marked as validated.
"
(:require
[sixsq.nuvla.auth.password :as auth-password]
[sixsq.nuvla.auth.utils :as auth]
[sixsq.nuvla.server.resources.callback :as callback]
[sixsq.nuvla.server.resources.callback.utils :as utils]
[sixsq.nuvla.server.resources.common.crud :as crud]
[sixsq.nuvla.server.resources.common.std-crud :as std-crud]
[sixsq.nuvla.server.resources.common.utils :as u]
[sixsq.nuvla.server.resources.credential-hashed-password :as hashed-password]
[sixsq.nuvla.server.resources.user-template :as p]
[sixsq.nuvla.server.resources.user-template-minimum :as user-minimum]
[sixsq.nuvla.server.resources.user.utils :as user-utils]
[sixsq.nuvla.server.util.response :as r]))
(def ^:const action-name "join-group")
(def create-callback (partial callback/create action-name))
(defn create-user
[email new-password]
(when-not (hashed-password/acceptable-password? new-password)
(throw (r/ex-response hashed-password/acceptable-password-msg 400)))
(std-crud/add-if-absent
(str user-utils/resource-url " '" email "'") user-utils/resource-url
{:template
{:href (str p/resource-type "/" user-minimum/registration-method)
:email email
:password PI:PASSWORD:<PASSWORD>END_PI}})
(auth-password/identifier->user-id email))
(defn add-user-to-group
[group-id user-id]
(let [{:keys [users]} (crud/retrieve-by-id-as-admin group-id)
{:keys [status body]} (crud/edit
{:params {:uuid (u/id->uuid group-id)
:resource-name (u/id->resource-type group-id)}
:nuvla/authn auth/internal-identity
:body {:users (-> users (conj user-id) distinct vec)}})]
(if (= 200 status)
body
(let [msg (str (format "adding %s to %s failed:" user-id group-id)
status (:message body))]
(throw (r/ex-bad-request msg))))))
(defmethod callback/execute action-name
[{callback-id :id
{existing-user-id :user-id
email :email
redirect-url :redirect-url} :data
{group-id :href} :target-resource :as _callback-resource}
{{:keys [new-password]} :body :as _request}]
(try
(let [user-id (or existing-user-id
(auth-password/identifier->user-id email) ;; in case user created an account in meantime
(create-user email new-password))
msg (format "'%s' successfully joined '%s'" user-id group-id)]
(add-user-to-group group-id user-id)
(utils/callback-succeeded! callback-id)
(if (and existing-user-id redirect-url)
(r/map-response msg 303 callback-id redirect-url)
(r/map-response msg 200)))
(catch Exception e
(utils/callback-failed! callback-id)
(or (ex-data e) (throw e)))))
|
[
{
"context": "e\"\n :key-password \"keykey\"\n :client-auth :wa",
"end": 2295,
"score": 0.9945390224456787,
"start": 2289,
"tag": "PASSWORD",
"value": "keykey"
},
{
"context": "e\"\n :key-password \"keykey\"\n :client-auth :wa",
"end": 3096,
"score": 0.9938839673995972,
"start": 3090,
"tag": "PASSWORD",
"value": "keykey"
}
] | test/clj_http/test/conn_mgr_test.clj | thegeez/clj-http | 0 | (ns clj-http.test.conn-mgr-test
(:require [clj-http.conn-mgr :as conn-mgr]
[clj-http.core :as core]
[clj-http.test.core-test :refer [run-server]]
[clojure.test :refer :all]
[ring.adapter.jetty :as ring])
(:import (java.security KeyStore)
(org.apache.http.impl.conn BasicHttpClientConnectionManager)
(org.apache.http.conn.ssl SSLConnectionSocketFactory
DefaultHostnameVerifier
NoopHostnameVerifier
TrustStrategy)))
(def client-ks "test-resources/client-keystore")
(def client-ks-pass "keykey")
(def secure-request {:request-method :get :uri "/"
:server-port 18084 :scheme :https
:keystore client-ks :keystore-pass client-ks-pass
:trust-store client-ks :trust-store-pass client-ks-pass
:server-name "localhost" :insecure? true})
(defn secure-handler [req]
(if (nil? (:ssl-client-cert req))
{:status 403}
{:status 200}))
(deftest load-keystore
(let [ks (conn-mgr/get-keystore "test-resources/keystore" nil "keykey")]
(is (instance? KeyStore ks))
(is (> (.size ks) 0))))
(deftest use-existing-keystore
(let [ks (conn-mgr/get-keystore "test-resources/keystore" nil "keykey")
ks (conn-mgr/get-keystore ks)]
(is (instance? KeyStore ks))
(is (> (.size ks) 0))))
(deftest load-keystore-with-nil-pass
(let [ks (conn-mgr/get-keystore "test-resources/keystore" nil nil)]
(is (instance? KeyStore ks))))
(deftest keystore-scheme-factory
(let [sr (conn-mgr/get-keystore-scheme-registry
{:keystore client-ks :keystore-pass client-ks-pass
:trust-store client-ks :trust-store-pass client-ks-pass})
socket-factory (.lookup sr "https")]
(is (instance? SSLConnectionSocketFactory socket-factory))))
(deftest ^:integration ssl-client-cert-get
(let [server (ring/run-jetty secure-handler
{:port 18083 :ssl-port 18084
:ssl? true
:join? false
:keystore "test-resources/keystore"
:key-password "keykey"
:client-auth :want})]
(try
(let [resp (core/request {:request-method :get :uri "/get"
:server-port 18084 :scheme :https
:insecure? true :server-name "localhost"})]
(is (= 403 (:status resp))))
(let [resp (core/request secure-request)]
(is (= 200 (:status resp))))
(finally
(.stop server)))))
(deftest ^:integration ssl-client-cert-get-async
(let [server (ring/run-jetty secure-handler
{:port 18083 :ssl-port 18084
:ssl? true
:join? false
:keystore "test-resources/keystore"
:key-password "keykey"
:client-auth :want})]
(try
(let [resp (promise)
exception (promise)
_ (core/request {:request-method :get :uri "/get"
:server-port 18084 :scheme :https
:insecure? true :server-name "localhost"
:async? true} resp exception)]
(is (= 403 (:status @resp))))
(let [resp (promise)
exception (promise)
_ (core/request (assoc secure-request :async? true) resp exception)]
(is (= 200 (:status @resp))))
(finally
(.stop server)))))
(deftest ^:integration t-closed-conn-mgr-for-as-stream
(run-server)
(let [shutdown? (atom false)
cm (proxy [BasicHttpClientConnectionManager] []
(shutdown []
(reset! shutdown? true)))]
(try
(core/request {:request-method :get :uri "/timeout"
:server-port 18080 :scheme :http
:server-name "localhost"
;; timeouts forces an exception being thrown
:socket-timeout 1
:conn-timeout 1
:connection-manager cm
:as :stream})
(is false "request should have thrown an exception")
(catch Exception e))
(is @shutdown? "Connection manager has been shutdown")))
(deftest ^:integration t-closed-conn-mgr-for-empty-body
(run-server)
(let [shutdown? (atom false)
cm (proxy [BasicHttpClientConnectionManager] []
(shutdown []
(reset! shutdown? true)))
response (core/request {:request-method :get :uri "/unmodified-resource"
:server-port 18080 :scheme :http
:server-name "localhost"
:connection-manager cm})]
(is (nil? (:body response)) "response shouldn't have body")
(is (= 304 (:status response)))
(is @shutdown? "connection manager should be shutdown")))
| 57445 | (ns clj-http.test.conn-mgr-test
(:require [clj-http.conn-mgr :as conn-mgr]
[clj-http.core :as core]
[clj-http.test.core-test :refer [run-server]]
[clojure.test :refer :all]
[ring.adapter.jetty :as ring])
(:import (java.security KeyStore)
(org.apache.http.impl.conn BasicHttpClientConnectionManager)
(org.apache.http.conn.ssl SSLConnectionSocketFactory
DefaultHostnameVerifier
NoopHostnameVerifier
TrustStrategy)))
(def client-ks "test-resources/client-keystore")
(def client-ks-pass "keykey")
(def secure-request {:request-method :get :uri "/"
:server-port 18084 :scheme :https
:keystore client-ks :keystore-pass client-ks-pass
:trust-store client-ks :trust-store-pass client-ks-pass
:server-name "localhost" :insecure? true})
(defn secure-handler [req]
(if (nil? (:ssl-client-cert req))
{:status 403}
{:status 200}))
(deftest load-keystore
(let [ks (conn-mgr/get-keystore "test-resources/keystore" nil "keykey")]
(is (instance? KeyStore ks))
(is (> (.size ks) 0))))
(deftest use-existing-keystore
(let [ks (conn-mgr/get-keystore "test-resources/keystore" nil "keykey")
ks (conn-mgr/get-keystore ks)]
(is (instance? KeyStore ks))
(is (> (.size ks) 0))))
(deftest load-keystore-with-nil-pass
(let [ks (conn-mgr/get-keystore "test-resources/keystore" nil nil)]
(is (instance? KeyStore ks))))
(deftest keystore-scheme-factory
(let [sr (conn-mgr/get-keystore-scheme-registry
{:keystore client-ks :keystore-pass client-ks-pass
:trust-store client-ks :trust-store-pass client-ks-pass})
socket-factory (.lookup sr "https")]
(is (instance? SSLConnectionSocketFactory socket-factory))))
(deftest ^:integration ssl-client-cert-get
(let [server (ring/run-jetty secure-handler
{:port 18083 :ssl-port 18084
:ssl? true
:join? false
:keystore "test-resources/keystore"
:key-password "<PASSWORD>"
:client-auth :want})]
(try
(let [resp (core/request {:request-method :get :uri "/get"
:server-port 18084 :scheme :https
:insecure? true :server-name "localhost"})]
(is (= 403 (:status resp))))
(let [resp (core/request secure-request)]
(is (= 200 (:status resp))))
(finally
(.stop server)))))
(deftest ^:integration ssl-client-cert-get-async
(let [server (ring/run-jetty secure-handler
{:port 18083 :ssl-port 18084
:ssl? true
:join? false
:keystore "test-resources/keystore"
:key-password "<PASSWORD>"
:client-auth :want})]
(try
(let [resp (promise)
exception (promise)
_ (core/request {:request-method :get :uri "/get"
:server-port 18084 :scheme :https
:insecure? true :server-name "localhost"
:async? true} resp exception)]
(is (= 403 (:status @resp))))
(let [resp (promise)
exception (promise)
_ (core/request (assoc secure-request :async? true) resp exception)]
(is (= 200 (:status @resp))))
(finally
(.stop server)))))
(deftest ^:integration t-closed-conn-mgr-for-as-stream
(run-server)
(let [shutdown? (atom false)
cm (proxy [BasicHttpClientConnectionManager] []
(shutdown []
(reset! shutdown? true)))]
(try
(core/request {:request-method :get :uri "/timeout"
:server-port 18080 :scheme :http
:server-name "localhost"
;; timeouts forces an exception being thrown
:socket-timeout 1
:conn-timeout 1
:connection-manager cm
:as :stream})
(is false "request should have thrown an exception")
(catch Exception e))
(is @shutdown? "Connection manager has been shutdown")))
(deftest ^:integration t-closed-conn-mgr-for-empty-body
(run-server)
(let [shutdown? (atom false)
cm (proxy [BasicHttpClientConnectionManager] []
(shutdown []
(reset! shutdown? true)))
response (core/request {:request-method :get :uri "/unmodified-resource"
:server-port 18080 :scheme :http
:server-name "localhost"
:connection-manager cm})]
(is (nil? (:body response)) "response shouldn't have body")
(is (= 304 (:status response)))
(is @shutdown? "connection manager should be shutdown")))
| true | (ns clj-http.test.conn-mgr-test
(:require [clj-http.conn-mgr :as conn-mgr]
[clj-http.core :as core]
[clj-http.test.core-test :refer [run-server]]
[clojure.test :refer :all]
[ring.adapter.jetty :as ring])
(:import (java.security KeyStore)
(org.apache.http.impl.conn BasicHttpClientConnectionManager)
(org.apache.http.conn.ssl SSLConnectionSocketFactory
DefaultHostnameVerifier
NoopHostnameVerifier
TrustStrategy)))
(def client-ks "test-resources/client-keystore")
(def client-ks-pass "keykey")
(def secure-request {:request-method :get :uri "/"
:server-port 18084 :scheme :https
:keystore client-ks :keystore-pass client-ks-pass
:trust-store client-ks :trust-store-pass client-ks-pass
:server-name "localhost" :insecure? true})
(defn secure-handler [req]
(if (nil? (:ssl-client-cert req))
{:status 403}
{:status 200}))
(deftest load-keystore
(let [ks (conn-mgr/get-keystore "test-resources/keystore" nil "keykey")]
(is (instance? KeyStore ks))
(is (> (.size ks) 0))))
(deftest use-existing-keystore
(let [ks (conn-mgr/get-keystore "test-resources/keystore" nil "keykey")
ks (conn-mgr/get-keystore ks)]
(is (instance? KeyStore ks))
(is (> (.size ks) 0))))
(deftest load-keystore-with-nil-pass
(let [ks (conn-mgr/get-keystore "test-resources/keystore" nil nil)]
(is (instance? KeyStore ks))))
(deftest keystore-scheme-factory
(let [sr (conn-mgr/get-keystore-scheme-registry
{:keystore client-ks :keystore-pass client-ks-pass
:trust-store client-ks :trust-store-pass client-ks-pass})
socket-factory (.lookup sr "https")]
(is (instance? SSLConnectionSocketFactory socket-factory))))
(deftest ^:integration ssl-client-cert-get
(let [server (ring/run-jetty secure-handler
{:port 18083 :ssl-port 18084
:ssl? true
:join? false
:keystore "test-resources/keystore"
:key-password "PI:PASSWORD:<PASSWORD>END_PI"
:client-auth :want})]
(try
(let [resp (core/request {:request-method :get :uri "/get"
:server-port 18084 :scheme :https
:insecure? true :server-name "localhost"})]
(is (= 403 (:status resp))))
(let [resp (core/request secure-request)]
(is (= 200 (:status resp))))
(finally
(.stop server)))))
(deftest ^:integration ssl-client-cert-get-async
(let [server (ring/run-jetty secure-handler
{:port 18083 :ssl-port 18084
:ssl? true
:join? false
:keystore "test-resources/keystore"
:key-password "PI:PASSWORD:<PASSWORD>END_PI"
:client-auth :want})]
(try
(let [resp (promise)
exception (promise)
_ (core/request {:request-method :get :uri "/get"
:server-port 18084 :scheme :https
:insecure? true :server-name "localhost"
:async? true} resp exception)]
(is (= 403 (:status @resp))))
(let [resp (promise)
exception (promise)
_ (core/request (assoc secure-request :async? true) resp exception)]
(is (= 200 (:status @resp))))
(finally
(.stop server)))))
(deftest ^:integration t-closed-conn-mgr-for-as-stream
(run-server)
(let [shutdown? (atom false)
cm (proxy [BasicHttpClientConnectionManager] []
(shutdown []
(reset! shutdown? true)))]
(try
(core/request {:request-method :get :uri "/timeout"
:server-port 18080 :scheme :http
:server-name "localhost"
;; timeouts forces an exception being thrown
:socket-timeout 1
:conn-timeout 1
:connection-manager cm
:as :stream})
(is false "request should have thrown an exception")
(catch Exception e))
(is @shutdown? "Connection manager has been shutdown")))
(deftest ^:integration t-closed-conn-mgr-for-empty-body
(run-server)
(let [shutdown? (atom false)
cm (proxy [BasicHttpClientConnectionManager] []
(shutdown []
(reset! shutdown? true)))
response (core/request {:request-method :get :uri "/unmodified-resource"
:server-port 18080 :scheme :http
:server-name "localhost"
:connection-manager cm})]
(is (nil? (:body response)) "response shouldn't have body")
(is (= 304 (:status response)))
(is @shutdown? "connection manager should be shutdown")))
|
[
{
"context": "odified from potemkin, v0.4.3 (https://github.com/ztellman/potemkin), MIT licnensed, Copyright Zachary Tellm",
"end": 73,
"score": 0.9985941052436829,
"start": 65,
"tag": "USERNAME",
"value": "ztellman"
},
{
"context": "b.com/ztellman/potemkin), MIT licnensed, Copyright Zachary Tellman\n\n(ns ^:no-doc from.potemkin.template\n (:require\n",
"end": 125,
"score": 0.9998801946640015,
"start": 110,
"tag": "NAME",
"value": "Zachary Tellman"
}
] | web/src/from/potemkin/template.clj | Elknar/immutant | 275 | ;; Copied and modified from potemkin, v0.4.3 (https://github.com/ztellman/potemkin), MIT licnensed, Copyright Zachary Tellman
(ns ^:no-doc from.potemkin.template
(:require
[clojure.set :as s]
[from.riddley.walk :as r]
[from.riddley.compiler :as c]))
(defn- validate-body [externs args body]
(let [valid? (atom true)
externs (set externs)
args (set args)
check? (s/union externs args)]
(when-not (empty? (s/intersection externs args))
(throw
(IllegalArgumentException.
"No overlap allowed between extern and argument names")))
(r/walk-exprs
symbol?
(fn [s]
(when (and (check? s) (->> (c/locals) keys (filter #(= s %)) first meta ::valid not))
(throw
(IllegalArgumentException.
(str \' s \' " is shadowed by local lexical binding"))))
(when-not (get (c/locals) s)
(throw
(IllegalArgumentException.
(str \' s \' " is undefined, must be explicitly defined as an extern."))))
s)
`(let [~@(mapcat
(fn [x]
[(with-meta x {::valid true}) nil])
(concat
externs
args))]
~body))
true))
(defn- unquote? [x]
(and (seq? x) (= 'clojure.core/unquote (first x))))
(defn- splice? [x]
(and (seq? x) (= 'clojure.core/unquote-splicing (first x))))
(defn validate-externs [name externs]
(doseq [e externs]
(when-not (contains? (c/locals) e)
(throw
(IllegalArgumentException.
(str "template "
\' name \'
" expects extern "
\' e \'
" to be defined within local scope."))))))
(defmacro deftemplate [name externs args & body]
(let [body `(do ~@body)]
(validate-body externs args body)
(let [arg? (set args)
pred (fn [x] (or (seq? x) (vector? x) (symbol? x)))]
(list 'defmacro name args
(list 'validate-externs (list 'quote name) (list 'quote (set externs)))
(r/walk-exprs
pred
(fn this [x]
(if (or (seq? x) (vector? x))
(let [splicing? (some splice? x)
terms (map
(fn [t]
(cond
(unquote? t) (second t)
(splice? t) t
:else (r/walk-exprs pred this t)))
x)
x' (if (some splice? x)
(list* 'concat (map #(if (splice? %) (second %) [%]) terms))
(list* 'list terms))]
(if (vector? x)
(vec x')
x'))
(cond
(arg? x)
x
(arg? (-> x meta :tag))
(list 'quote
(list 'with-meta x
(list 'assoc
(list 'meta x)
{:tag (-> x meta :tag)})))
:else
(list 'quote x))))
body)))))
| 56960 | ;; Copied and modified from potemkin, v0.4.3 (https://github.com/ztellman/potemkin), MIT licnensed, Copyright <NAME>
(ns ^:no-doc from.potemkin.template
(:require
[clojure.set :as s]
[from.riddley.walk :as r]
[from.riddley.compiler :as c]))
(defn- validate-body [externs args body]
(let [valid? (atom true)
externs (set externs)
args (set args)
check? (s/union externs args)]
(when-not (empty? (s/intersection externs args))
(throw
(IllegalArgumentException.
"No overlap allowed between extern and argument names")))
(r/walk-exprs
symbol?
(fn [s]
(when (and (check? s) (->> (c/locals) keys (filter #(= s %)) first meta ::valid not))
(throw
(IllegalArgumentException.
(str \' s \' " is shadowed by local lexical binding"))))
(when-not (get (c/locals) s)
(throw
(IllegalArgumentException.
(str \' s \' " is undefined, must be explicitly defined as an extern."))))
s)
`(let [~@(mapcat
(fn [x]
[(with-meta x {::valid true}) nil])
(concat
externs
args))]
~body))
true))
(defn- unquote? [x]
(and (seq? x) (= 'clojure.core/unquote (first x))))
(defn- splice? [x]
(and (seq? x) (= 'clojure.core/unquote-splicing (first x))))
(defn validate-externs [name externs]
(doseq [e externs]
(when-not (contains? (c/locals) e)
(throw
(IllegalArgumentException.
(str "template "
\' name \'
" expects extern "
\' e \'
" to be defined within local scope."))))))
(defmacro deftemplate [name externs args & body]
(let [body `(do ~@body)]
(validate-body externs args body)
(let [arg? (set args)
pred (fn [x] (or (seq? x) (vector? x) (symbol? x)))]
(list 'defmacro name args
(list 'validate-externs (list 'quote name) (list 'quote (set externs)))
(r/walk-exprs
pred
(fn this [x]
(if (or (seq? x) (vector? x))
(let [splicing? (some splice? x)
terms (map
(fn [t]
(cond
(unquote? t) (second t)
(splice? t) t
:else (r/walk-exprs pred this t)))
x)
x' (if (some splice? x)
(list* 'concat (map #(if (splice? %) (second %) [%]) terms))
(list* 'list terms))]
(if (vector? x)
(vec x')
x'))
(cond
(arg? x)
x
(arg? (-> x meta :tag))
(list 'quote
(list 'with-meta x
(list 'assoc
(list 'meta x)
{:tag (-> x meta :tag)})))
:else
(list 'quote x))))
body)))))
| true | ;; Copied and modified from potemkin, v0.4.3 (https://github.com/ztellman/potemkin), MIT licnensed, Copyright PI:NAME:<NAME>END_PI
(ns ^:no-doc from.potemkin.template
(:require
[clojure.set :as s]
[from.riddley.walk :as r]
[from.riddley.compiler :as c]))
(defn- validate-body [externs args body]
(let [valid? (atom true)
externs (set externs)
args (set args)
check? (s/union externs args)]
(when-not (empty? (s/intersection externs args))
(throw
(IllegalArgumentException.
"No overlap allowed between extern and argument names")))
(r/walk-exprs
symbol?
(fn [s]
(when (and (check? s) (->> (c/locals) keys (filter #(= s %)) first meta ::valid not))
(throw
(IllegalArgumentException.
(str \' s \' " is shadowed by local lexical binding"))))
(when-not (get (c/locals) s)
(throw
(IllegalArgumentException.
(str \' s \' " is undefined, must be explicitly defined as an extern."))))
s)
`(let [~@(mapcat
(fn [x]
[(with-meta x {::valid true}) nil])
(concat
externs
args))]
~body))
true))
(defn- unquote? [x]
(and (seq? x) (= 'clojure.core/unquote (first x))))
(defn- splice? [x]
(and (seq? x) (= 'clojure.core/unquote-splicing (first x))))
(defn validate-externs [name externs]
(doseq [e externs]
(when-not (contains? (c/locals) e)
(throw
(IllegalArgumentException.
(str "template "
\' name \'
" expects extern "
\' e \'
" to be defined within local scope."))))))
(defmacro deftemplate [name externs args & body]
(let [body `(do ~@body)]
(validate-body externs args body)
(let [arg? (set args)
pred (fn [x] (or (seq? x) (vector? x) (symbol? x)))]
(list 'defmacro name args
(list 'validate-externs (list 'quote name) (list 'quote (set externs)))
(r/walk-exprs
pred
(fn this [x]
(if (or (seq? x) (vector? x))
(let [splicing? (some splice? x)
terms (map
(fn [t]
(cond
(unquote? t) (second t)
(splice? t) t
:else (r/walk-exprs pred this t)))
x)
x' (if (some splice? x)
(list* 'concat (map #(if (splice? %) (second %) [%]) terms))
(list* 'list terms))]
(if (vector? x)
(vec x')
x'))
(cond
(arg? x)
x
(arg? (-> x meta :tag))
(list 'quote
(list 'with-meta x
(list 'assoc
(list 'meta x)
{:tag (-> x meta :tag)})))
:else
(list 'quote x))))
body)))))
|
[
{
"context": "'t always match 1:1).\n\n (full-name->username \\\"Cam Saul\\\") ;-> \\\"cam\\\"\"\n [full-name]\n {:pre [(string? f",
"end": 2810,
"score": 0.999468982219696,
"start": 2802,
"tag": "NAME",
"value": "Cam Saul"
}
] | src/closed_issues_bot/slack.clj | metabase/slack-recently-closed-issues-bot | 0 | (ns closed-issues-bot.slack
(:require [cheshire.core :as json]
[clj-http.client :as http]
[closed-issues-bot.config :as config]))
(def ^:private ^String api-base-url "https://slack.com/api")
(defn- request-headers []
{"Accept" "application/json; charset=utf-8"
"Content-Type" "application/json; charset=utf-8"
;; See https://api.slack.com/authentication/oauth-v2#using
"Authorization" (format "Bearer %s" (config/slack-oauth-token))})
(defn- default-request-options []
{:headers (request-headers)
:conn-timeout 10000
:socket-timeout 10000})
(defn- handle-response [response]
(let [response-body (-> response
:body
(json/parse-string true))]
(when-not (:ok response-body)
(throw (ex-info (format "Slack API responded with error %s" (pr-str (:error response-body)))
{:response response-body})))
response-body))
(defn- http-request [f endpoint & [request-body]]
(let [url (str api-base-url "/" (name endpoint))
request (merge
(default-request-options)
(when request-body
{:body (json/generate-string request-body)}))]
(try
(handle-response (f url request))
(catch Throwable e
(throw (ex-info (ex-message e)
{:url url, :request-body request-body}
e))))))
(defn- GET [endpoint]
(http-request http/get endpoint))
(defn- POST [endpoint request-body]
(http-request http/post endpoint request-body))
;; see https://api.slack.com/methods/chat.postMessage
(defn post-chat-message!
"Calls Slack API `chat.postMessage` endpoint and posts a message to a channel."
[channel-id blocks]
(POST "chat.postMessage"
{:channel channel-id
:username (config/slack-bot-name)
:icon_emoji (config/slack-bot-emoji)
:blocks blocks}))
(defn- users-list []
(:members (GET "users.list")))
(def ^:private full-name->username*
(delay
(into {} (for [user (users-list)
:when (seq (:real_name user))]
[(:real_name user) (:name user)]))))
(defn- levenshtein-distance ^Integer [^CharSequence s1 ^CharSequence s2]
(try
(.apply (org.apache.commons.text.similarity.LevenshteinDistance/getDefaultInstance) s1 s2)
(catch Throwable e
(throw (ex-info (str "Error calculating Levenshtein distance: " (ex-message e))
{:s1 s1, :s2 s2}
e)))))
(defn full-name->username
"Given someone's IRL full name, find the Slack username with the same full name. Uses Levenshtein distance to find the
closest match (people's GH and Slack usernames don't always match 1:1).
(full-name->username \"Cam Saul\") ;-> \"cam\""
[full-name]
{:pre [(string? full-name)]}
(let [[[_ username]] (sort-by first
(fn [s1 s2]
(compare
(levenshtein-distance full-name s1)
(levenshtein-distance full-name s2)))
@full-name->username*)]
username))
| 53106 | (ns closed-issues-bot.slack
(:require [cheshire.core :as json]
[clj-http.client :as http]
[closed-issues-bot.config :as config]))
(def ^:private ^String api-base-url "https://slack.com/api")
(defn- request-headers []
{"Accept" "application/json; charset=utf-8"
"Content-Type" "application/json; charset=utf-8"
;; See https://api.slack.com/authentication/oauth-v2#using
"Authorization" (format "Bearer %s" (config/slack-oauth-token))})
(defn- default-request-options []
{:headers (request-headers)
:conn-timeout 10000
:socket-timeout 10000})
(defn- handle-response [response]
(let [response-body (-> response
:body
(json/parse-string true))]
(when-not (:ok response-body)
(throw (ex-info (format "Slack API responded with error %s" (pr-str (:error response-body)))
{:response response-body})))
response-body))
(defn- http-request [f endpoint & [request-body]]
(let [url (str api-base-url "/" (name endpoint))
request (merge
(default-request-options)
(when request-body
{:body (json/generate-string request-body)}))]
(try
(handle-response (f url request))
(catch Throwable e
(throw (ex-info (ex-message e)
{:url url, :request-body request-body}
e))))))
(defn- GET [endpoint]
(http-request http/get endpoint))
(defn- POST [endpoint request-body]
(http-request http/post endpoint request-body))
;; see https://api.slack.com/methods/chat.postMessage
(defn post-chat-message!
"Calls Slack API `chat.postMessage` endpoint and posts a message to a channel."
[channel-id blocks]
(POST "chat.postMessage"
{:channel channel-id
:username (config/slack-bot-name)
:icon_emoji (config/slack-bot-emoji)
:blocks blocks}))
(defn- users-list []
(:members (GET "users.list")))
(def ^:private full-name->username*
(delay
(into {} (for [user (users-list)
:when (seq (:real_name user))]
[(:real_name user) (:name user)]))))
(defn- levenshtein-distance ^Integer [^CharSequence s1 ^CharSequence s2]
(try
(.apply (org.apache.commons.text.similarity.LevenshteinDistance/getDefaultInstance) s1 s2)
(catch Throwable e
(throw (ex-info (str "Error calculating Levenshtein distance: " (ex-message e))
{:s1 s1, :s2 s2}
e)))))
(defn full-name->username
"Given someone's IRL full name, find the Slack username with the same full name. Uses Levenshtein distance to find the
closest match (people's GH and Slack usernames don't always match 1:1).
(full-name->username \"<NAME>\") ;-> \"cam\""
[full-name]
{:pre [(string? full-name)]}
(let [[[_ username]] (sort-by first
(fn [s1 s2]
(compare
(levenshtein-distance full-name s1)
(levenshtein-distance full-name s2)))
@full-name->username*)]
username))
| true | (ns closed-issues-bot.slack
(:require [cheshire.core :as json]
[clj-http.client :as http]
[closed-issues-bot.config :as config]))
(def ^:private ^String api-base-url "https://slack.com/api")
(defn- request-headers []
{"Accept" "application/json; charset=utf-8"
"Content-Type" "application/json; charset=utf-8"
;; See https://api.slack.com/authentication/oauth-v2#using
"Authorization" (format "Bearer %s" (config/slack-oauth-token))})
(defn- default-request-options []
{:headers (request-headers)
:conn-timeout 10000
:socket-timeout 10000})
(defn- handle-response [response]
(let [response-body (-> response
:body
(json/parse-string true))]
(when-not (:ok response-body)
(throw (ex-info (format "Slack API responded with error %s" (pr-str (:error response-body)))
{:response response-body})))
response-body))
(defn- http-request [f endpoint & [request-body]]
(let [url (str api-base-url "/" (name endpoint))
request (merge
(default-request-options)
(when request-body
{:body (json/generate-string request-body)}))]
(try
(handle-response (f url request))
(catch Throwable e
(throw (ex-info (ex-message e)
{:url url, :request-body request-body}
e))))))
(defn- GET [endpoint]
(http-request http/get endpoint))
(defn- POST [endpoint request-body]
(http-request http/post endpoint request-body))
;; see https://api.slack.com/methods/chat.postMessage
(defn post-chat-message!
"Calls Slack API `chat.postMessage` endpoint and posts a message to a channel."
[channel-id blocks]
(POST "chat.postMessage"
{:channel channel-id
:username (config/slack-bot-name)
:icon_emoji (config/slack-bot-emoji)
:blocks blocks}))
(defn- users-list []
(:members (GET "users.list")))
(def ^:private full-name->username*
(delay
(into {} (for [user (users-list)
:when (seq (:real_name user))]
[(:real_name user) (:name user)]))))
(defn- levenshtein-distance ^Integer [^CharSequence s1 ^CharSequence s2]
(try
(.apply (org.apache.commons.text.similarity.LevenshteinDistance/getDefaultInstance) s1 s2)
(catch Throwable e
(throw (ex-info (str "Error calculating Levenshtein distance: " (ex-message e))
{:s1 s1, :s2 s2}
e)))))
(defn full-name->username
"Given someone's IRL full name, find the Slack username with the same full name. Uses Levenshtein distance to find the
closest match (people's GH and Slack usernames don't always match 1:1).
(full-name->username \"PI:NAME:<NAME>END_PI\") ;-> \"cam\""
[full-name]
{:pre [(string? full-name)]}
(let [[[_ username]] (sort-by first
(fn [s1 s2]
(compare
(levenshtein-distance full-name s1)
(levenshtein-distance full-name s2)))
@full-name->username*)]
username))
|
[
{
"context": "bric messaging broker\"\n :url \"https://github.com/puppetlabs/pcp-broker\"\n :license {:name \"Apache License, Ve",
"end": 174,
"score": 0.915447473526001,
"start": 164,
"tag": "USERNAME",
"value": "puppetlabs"
},
{
"context": "\n :password :env/nexus_jenkins_password\n ",
"end": 2153,
"score": 0.8590044975280762,
"start": 2150,
"tag": "PASSWORD",
"value": "env"
},
{
"context": " :password :env/nexus_jenkins_password\n :sign-relea",
"end": 2176,
"score": 0.6493285298347473,
"start": 2168,
"tag": "PASSWORD",
"value": "password"
}
] | project.clj | donoghuc/pcp-broker | 0 | (def http-async-client-version "1.3.0")
(defproject puppetlabs/pcp-broker "1.5.7-SNAPSHOT"
:description "PCP fabric messaging broker"
:url "https://github.com/puppetlabs/pcp-broker"
:license {:name "Apache License, Version 2.0"
:url "http://www.apache.org/licenses/LICENSE-2.0.html"}
:min-lein-version "2.7.1"
;; Abort when version ranges or version conflicts are detected in
;; dependencies. Also supports :warn to simply emit warnings.
;; requires lein 2.2.0+.
:pedantic? :abort
:parent-project {:coords [puppetlabs/clj-parent "4.4.1"]
:inherit [:managed-dependencies]}
:dependencies [[org.clojure/clojure]
[org.clojure/tools.logging]
[puppetlabs/kitchensink]
[puppetlabs/trapperkeeper]
[puppetlabs/trapperkeeper-authorization]
[puppetlabs/trapperkeeper-metrics]
[puppetlabs/trapperkeeper-webserver-jetty9]
[puppetlabs/trapperkeeper-status]
[puppetlabs/trapperkeeper-filesystem-watcher]
[puppetlabs/structured-logging]
[puppetlabs/ssl-utils]
[metrics-clojure]
;; try+/throw+
[slingshot]
[puppetlabs/pcp-client "1.3.1"]
[puppetlabs/i18n]]
:plugins [[lein-parent "0.3.7"]
[puppetlabs/lein-ezbake "1.9.0"]
[puppetlabs/i18n "0.8.0"]
[lein-release "1.0.5" :exclusions [org.clojure/clojure]]]
:lein-release {:scm :git
:deploy-via :lein-deploy}
:deploy-repositories [["releases" {:url "https://clojars.org/repo"
:username :env/clojars_jenkins_username
:password :env/clojars_jenkins_password
:sign-releases false}]
["snapshots" {:url "https://artifactory.delivery.puppetlabs.net/artifactory/clojure-snapshots__local/"
:username :env/nexus_jenkins_username
:password :env/nexus_jenkins_password
:sign-releases false}]]
:test-paths ["test/unit" "test/integration" "test/utils" "test-resources"]
:lein-ezbake {:config-dir "ezbake/config"
:vars {:docker {:ports [8140]}}}
:profiles {:dev {:source-paths ["dev"]
:dependencies [[http.async.client ~http-async-client-version]
[puppetlabs/trapperkeeper :classifier "test" :scope "test"]
[puppetlabs/kitchensink :classifier "test" :scope "test"]
[org.bouncycastle/bcpkix-jdk15on]
[org.clojure/tools.namespace]
[org.clojure/tools.nrepl]]
:plugins [[lein-cloverage "1.0.6" :excludes [org.clojure/clojure org.clojure/tools.cli]]]}
:dev-schema-validation [:dev
{:injections [(do
(require 'schema.core)
(schema.core/set-fn-validation! true))]}]
:test-base {:source-paths ["test/utils" "test-resources"]
:dependencies [[http.async.client ~http-async-client-version]
[puppetlabs/trapperkeeper :classifier "test" :scope "test"]
[puppetlabs/kitchensink :classifier "test" :scope "test"]
[org.bouncycastle/bcpkix-jdk15on]]
:test-paths ^:replace ["test/unit" "test/integration"]}
:test-schema-validation [:test-base
{:injections [(do
(require 'schema.core)
(schema.core/set-fn-validation! true))]}]
:uberjar {:aot [puppetlabs.pcp.broker.service
puppetlabs.trapperkeeper.services.authorization.authorization-service
puppetlabs.trapperkeeper.services.metrics.metrics-service
puppetlabs.trapperkeeper.services.scheduler.scheduler-service
puppetlabs.trapperkeeper.services.status.status-service
puppetlabs.trapperkeeper.services.webrouting.webrouting-service
puppetlabs.trapperkeeper.services.webserver.jetty9-service]}
:unit [:test-base
{:test-paths ^:replace ["test/unit"]}]
:integration [:test-base
{:test-paths ^:replace ["test/integration"]}]
:cljfmt {:plugins [[lein-cljfmt "0.5.7" :exclusions [org.clojure/clojure]]
[lein-parent "0.3.4"]]
:parent-project {:path "../pl-clojure-style/project.clj"
:inherit [:cljfmt]}}
:internal-mirrors {:mirrors [["releases" {:name "internal-releases"
:url "https://artifactory.delivery.puppetlabs.net/artifactory/clojure-releases__local/"}]
["central" {:name "internal-central-mirror"
:url "https://artifactory.delivery.puppetlabs.net/artifactory/maven/" }]
["clojars" {:name "internal-clojars-mirror"
:url "https://artifactory.delivery.puppetlabs.net/artifactory/maven/" }]
["snapshots" {:name "internal-snapshots"
:url "https://artifactory.delivery.puppetlabs.net/artifactory/clojure-snapshots__local/" }]]}
:internal-integration [:integration :internal-mirrors]}
:repl-options {:init-ns user}
;; Enable occasionally to check we have no interop hotspots that need better type hinting
; :global-vars {*warn-on-reflection* true}
:aliases {"tk" ["trampoline" "run" "--config" "test-resources/conf.d"]
;; runs trapperkeeper with schema validations enabled
"tkv" ["with-profile" "dev-schema-validation" "tk"]
"certs" ["trampoline" "run" "-m" "puppetlabs.pcp.testutils.certs" "--config" "test-resources/conf.d" "--"]
;; cljfmt requires pl-clojure-style's root dir as per above profile;
;; run with 'check' then 'fix' with args (refer to the project docs)
"cljfmt" ["with-profile" "+cljfmt" "cljfmt"]
"coverage" ["cloverage" "-e" "puppetlabs.puppetdb.*" "-e" "user"]
"test-all" ["with-profile" "test-base:test-schema-validation" "test"]}
:main puppetlabs.trapperkeeper.main)
| 81004 | (def http-async-client-version "1.3.0")
(defproject puppetlabs/pcp-broker "1.5.7-SNAPSHOT"
:description "PCP fabric messaging broker"
:url "https://github.com/puppetlabs/pcp-broker"
:license {:name "Apache License, Version 2.0"
:url "http://www.apache.org/licenses/LICENSE-2.0.html"}
:min-lein-version "2.7.1"
;; Abort when version ranges or version conflicts are detected in
;; dependencies. Also supports :warn to simply emit warnings.
;; requires lein 2.2.0+.
:pedantic? :abort
:parent-project {:coords [puppetlabs/clj-parent "4.4.1"]
:inherit [:managed-dependencies]}
:dependencies [[org.clojure/clojure]
[org.clojure/tools.logging]
[puppetlabs/kitchensink]
[puppetlabs/trapperkeeper]
[puppetlabs/trapperkeeper-authorization]
[puppetlabs/trapperkeeper-metrics]
[puppetlabs/trapperkeeper-webserver-jetty9]
[puppetlabs/trapperkeeper-status]
[puppetlabs/trapperkeeper-filesystem-watcher]
[puppetlabs/structured-logging]
[puppetlabs/ssl-utils]
[metrics-clojure]
;; try+/throw+
[slingshot]
[puppetlabs/pcp-client "1.3.1"]
[puppetlabs/i18n]]
:plugins [[lein-parent "0.3.7"]
[puppetlabs/lein-ezbake "1.9.0"]
[puppetlabs/i18n "0.8.0"]
[lein-release "1.0.5" :exclusions [org.clojure/clojure]]]
:lein-release {:scm :git
:deploy-via :lein-deploy}
:deploy-repositories [["releases" {:url "https://clojars.org/repo"
:username :env/clojars_jenkins_username
:password :env/clojars_jenkins_password
:sign-releases false}]
["snapshots" {:url "https://artifactory.delivery.puppetlabs.net/artifactory/clojure-snapshots__local/"
:username :env/nexus_jenkins_username
:password :<PASSWORD>/nexus_jenkins_<PASSWORD>
:sign-releases false}]]
:test-paths ["test/unit" "test/integration" "test/utils" "test-resources"]
:lein-ezbake {:config-dir "ezbake/config"
:vars {:docker {:ports [8140]}}}
:profiles {:dev {:source-paths ["dev"]
:dependencies [[http.async.client ~http-async-client-version]
[puppetlabs/trapperkeeper :classifier "test" :scope "test"]
[puppetlabs/kitchensink :classifier "test" :scope "test"]
[org.bouncycastle/bcpkix-jdk15on]
[org.clojure/tools.namespace]
[org.clojure/tools.nrepl]]
:plugins [[lein-cloverage "1.0.6" :excludes [org.clojure/clojure org.clojure/tools.cli]]]}
:dev-schema-validation [:dev
{:injections [(do
(require 'schema.core)
(schema.core/set-fn-validation! true))]}]
:test-base {:source-paths ["test/utils" "test-resources"]
:dependencies [[http.async.client ~http-async-client-version]
[puppetlabs/trapperkeeper :classifier "test" :scope "test"]
[puppetlabs/kitchensink :classifier "test" :scope "test"]
[org.bouncycastle/bcpkix-jdk15on]]
:test-paths ^:replace ["test/unit" "test/integration"]}
:test-schema-validation [:test-base
{:injections [(do
(require 'schema.core)
(schema.core/set-fn-validation! true))]}]
:uberjar {:aot [puppetlabs.pcp.broker.service
puppetlabs.trapperkeeper.services.authorization.authorization-service
puppetlabs.trapperkeeper.services.metrics.metrics-service
puppetlabs.trapperkeeper.services.scheduler.scheduler-service
puppetlabs.trapperkeeper.services.status.status-service
puppetlabs.trapperkeeper.services.webrouting.webrouting-service
puppetlabs.trapperkeeper.services.webserver.jetty9-service]}
:unit [:test-base
{:test-paths ^:replace ["test/unit"]}]
:integration [:test-base
{:test-paths ^:replace ["test/integration"]}]
:cljfmt {:plugins [[lein-cljfmt "0.5.7" :exclusions [org.clojure/clojure]]
[lein-parent "0.3.4"]]
:parent-project {:path "../pl-clojure-style/project.clj"
:inherit [:cljfmt]}}
:internal-mirrors {:mirrors [["releases" {:name "internal-releases"
:url "https://artifactory.delivery.puppetlabs.net/artifactory/clojure-releases__local/"}]
["central" {:name "internal-central-mirror"
:url "https://artifactory.delivery.puppetlabs.net/artifactory/maven/" }]
["clojars" {:name "internal-clojars-mirror"
:url "https://artifactory.delivery.puppetlabs.net/artifactory/maven/" }]
["snapshots" {:name "internal-snapshots"
:url "https://artifactory.delivery.puppetlabs.net/artifactory/clojure-snapshots__local/" }]]}
:internal-integration [:integration :internal-mirrors]}
:repl-options {:init-ns user}
;; Enable occasionally to check we have no interop hotspots that need better type hinting
; :global-vars {*warn-on-reflection* true}
:aliases {"tk" ["trampoline" "run" "--config" "test-resources/conf.d"]
;; runs trapperkeeper with schema validations enabled
"tkv" ["with-profile" "dev-schema-validation" "tk"]
"certs" ["trampoline" "run" "-m" "puppetlabs.pcp.testutils.certs" "--config" "test-resources/conf.d" "--"]
;; cljfmt requires pl-clojure-style's root dir as per above profile;
;; run with 'check' then 'fix' with args (refer to the project docs)
"cljfmt" ["with-profile" "+cljfmt" "cljfmt"]
"coverage" ["cloverage" "-e" "puppetlabs.puppetdb.*" "-e" "user"]
"test-all" ["with-profile" "test-base:test-schema-validation" "test"]}
:main puppetlabs.trapperkeeper.main)
| true | (def http-async-client-version "1.3.0")
(defproject puppetlabs/pcp-broker "1.5.7-SNAPSHOT"
:description "PCP fabric messaging broker"
:url "https://github.com/puppetlabs/pcp-broker"
:license {:name "Apache License, Version 2.0"
:url "http://www.apache.org/licenses/LICENSE-2.0.html"}
:min-lein-version "2.7.1"
;; Abort when version ranges or version conflicts are detected in
;; dependencies. Also supports :warn to simply emit warnings.
;; requires lein 2.2.0+.
:pedantic? :abort
:parent-project {:coords [puppetlabs/clj-parent "4.4.1"]
:inherit [:managed-dependencies]}
:dependencies [[org.clojure/clojure]
[org.clojure/tools.logging]
[puppetlabs/kitchensink]
[puppetlabs/trapperkeeper]
[puppetlabs/trapperkeeper-authorization]
[puppetlabs/trapperkeeper-metrics]
[puppetlabs/trapperkeeper-webserver-jetty9]
[puppetlabs/trapperkeeper-status]
[puppetlabs/trapperkeeper-filesystem-watcher]
[puppetlabs/structured-logging]
[puppetlabs/ssl-utils]
[metrics-clojure]
;; try+/throw+
[slingshot]
[puppetlabs/pcp-client "1.3.1"]
[puppetlabs/i18n]]
:plugins [[lein-parent "0.3.7"]
[puppetlabs/lein-ezbake "1.9.0"]
[puppetlabs/i18n "0.8.0"]
[lein-release "1.0.5" :exclusions [org.clojure/clojure]]]
:lein-release {:scm :git
:deploy-via :lein-deploy}
:deploy-repositories [["releases" {:url "https://clojars.org/repo"
:username :env/clojars_jenkins_username
:password :env/clojars_jenkins_password
:sign-releases false}]
["snapshots" {:url "https://artifactory.delivery.puppetlabs.net/artifactory/clojure-snapshots__local/"
:username :env/nexus_jenkins_username
:password :PI:PASSWORD:<PASSWORD>END_PI/nexus_jenkins_PI:PASSWORD:<PASSWORD>END_PI
:sign-releases false}]]
:test-paths ["test/unit" "test/integration" "test/utils" "test-resources"]
:lein-ezbake {:config-dir "ezbake/config"
:vars {:docker {:ports [8140]}}}
:profiles {:dev {:source-paths ["dev"]
:dependencies [[http.async.client ~http-async-client-version]
[puppetlabs/trapperkeeper :classifier "test" :scope "test"]
[puppetlabs/kitchensink :classifier "test" :scope "test"]
[org.bouncycastle/bcpkix-jdk15on]
[org.clojure/tools.namespace]
[org.clojure/tools.nrepl]]
:plugins [[lein-cloverage "1.0.6" :excludes [org.clojure/clojure org.clojure/tools.cli]]]}
:dev-schema-validation [:dev
{:injections [(do
(require 'schema.core)
(schema.core/set-fn-validation! true))]}]
:test-base {:source-paths ["test/utils" "test-resources"]
:dependencies [[http.async.client ~http-async-client-version]
[puppetlabs/trapperkeeper :classifier "test" :scope "test"]
[puppetlabs/kitchensink :classifier "test" :scope "test"]
[org.bouncycastle/bcpkix-jdk15on]]
:test-paths ^:replace ["test/unit" "test/integration"]}
:test-schema-validation [:test-base
{:injections [(do
(require 'schema.core)
(schema.core/set-fn-validation! true))]}]
:uberjar {:aot [puppetlabs.pcp.broker.service
puppetlabs.trapperkeeper.services.authorization.authorization-service
puppetlabs.trapperkeeper.services.metrics.metrics-service
puppetlabs.trapperkeeper.services.scheduler.scheduler-service
puppetlabs.trapperkeeper.services.status.status-service
puppetlabs.trapperkeeper.services.webrouting.webrouting-service
puppetlabs.trapperkeeper.services.webserver.jetty9-service]}
:unit [:test-base
{:test-paths ^:replace ["test/unit"]}]
:integration [:test-base
{:test-paths ^:replace ["test/integration"]}]
:cljfmt {:plugins [[lein-cljfmt "0.5.7" :exclusions [org.clojure/clojure]]
[lein-parent "0.3.4"]]
:parent-project {:path "../pl-clojure-style/project.clj"
:inherit [:cljfmt]}}
:internal-mirrors {:mirrors [["releases" {:name "internal-releases"
:url "https://artifactory.delivery.puppetlabs.net/artifactory/clojure-releases__local/"}]
["central" {:name "internal-central-mirror"
:url "https://artifactory.delivery.puppetlabs.net/artifactory/maven/" }]
["clojars" {:name "internal-clojars-mirror"
:url "https://artifactory.delivery.puppetlabs.net/artifactory/maven/" }]
["snapshots" {:name "internal-snapshots"
:url "https://artifactory.delivery.puppetlabs.net/artifactory/clojure-snapshots__local/" }]]}
:internal-integration [:integration :internal-mirrors]}
:repl-options {:init-ns user}
;; Enable occasionally to check we have no interop hotspots that need better type hinting
; :global-vars {*warn-on-reflection* true}
:aliases {"tk" ["trampoline" "run" "--config" "test-resources/conf.d"]
;; runs trapperkeeper with schema validations enabled
"tkv" ["with-profile" "dev-schema-validation" "tk"]
"certs" ["trampoline" "run" "-m" "puppetlabs.pcp.testutils.certs" "--config" "test-resources/conf.d" "--"]
;; cljfmt requires pl-clojure-style's root dir as per above profile;
;; run with 'check' then 'fix' with args (refer to the project docs)
"cljfmt" ["with-profile" "+cljfmt" "cljfmt"]
"coverage" ["cloverage" "-e" "puppetlabs.puppetdb.*" "-e" "user"]
"test-all" ["with-profile" "test-base:test-schema-validation" "test"]}
:main puppetlabs.trapperkeeper.main)
|
[
{
"context": "https://adventofcode.com/2020/day/16\n;; author: Vitor SRG (vitorssrg@gmail.com)\n;; date: 2021-01-10\n;;",
"end": 230,
"score": 0.9998912811279297,
"start": 221,
"tag": "NAME",
"value": "Vitor SRG"
},
{
"context": "ntofcode.com/2020/day/16\n;; author: Vitor SRG (vitorssrg@gmail.com)\n;; date: 2021-01-10\n;; execution: $ bash ./",
"end": 251,
"score": 0.9999294281005859,
"start": 232,
"tag": "EMAIL",
"value": "vitorssrg@gmail.com"
}
] | aoc2020/d16/main.clj | vitorsrg/advent-of-code | 0 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; domain: Advent of Code 2020
;; challenge: Day 16: Ticket Translation
;; url: https://adventofcode.com/2020/day/16
;; author: Vitor SRG (vitorssrg@gmail.com)
;; date: 2021-01-10
;; execution: $ bash ./aoc2020/run.sh d16 < [INPUT_FILE]
;; example:
;; $ bash ./aoc2020/run.sh d16 < ./aoc2020/d16/input.txt
;; part 1 23044
;; part 2 3765150732757
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns d16.main)
(defn transpose [coll] (apply mapv vector coll))
(defn product-colls
[colls]
"https://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists#Clojure"
(if (empty? colls)
'(())
(for [more (product-colls (rest colls)) x (first colls)] (cons x more))))
(defn parse-data
[data-raw]
(let [[_ fields-raw own-ticket-raw nearby-tickets-raw]
(re-matches #"(?s)^(.*?)\n\n.*?\n(.*?)\n\n.*?\n(.*?)\n$" data-raw)
fields (->> fields-raw
(clojure.string/split-lines)
(map #(re-matches #"^(.*?): (\d+)-(\d+) or (\d+)-(\d+)$" %))
(map rest)
(mapv (fn [[name & values]]
{:name name,
:constraint (mapv #(Integer/parseInt %) values)})))
own-ticket (->> own-ticket-raw
(#(clojure.string/split % #","))
(mapv #(Integer/parseInt %)))
nearby-tickets (->> nearby-tickets-raw
(clojure.string/split-lines)
(map #(clojure.string/split % #","))
(mapv (fn [ticket]
(mapv #(Integer/parseInt %) ticket))))]
{:fields fields, ;
:own-ticket own-ticket,
:nearby-tickets nearby-tickets}))
(defn field-validate
[constraint value]
(or (<= (nth constraint 0) value (nth constraint 1))
(<= (nth constraint 2) value (nth constraint 3))))
(defn problem--create
[fields cols-valid-fields]
{:fields-names fields, :cols-valid-fields cols-valid-fields})
(defn problem--make-initial-state
[problem]
{:index 0,
:available-fields (set (:fields-names problem)),
:fields-order [],
:used-fields #{}})
(defn problem--state-actions
[problem state]
(clojure.set/difference (nth (:cols-valid-fields problem) (:index state))
(:used-fields state)))
(defn problem--is-final-state?
[problem state]
(= (:index state) (count (:fields-names problem))))
(defn problem--next-state
[problem state action]
(let [{index :index,
available-fields :available-fields,
fields-order :fields-order,
used-fields :used-fields}
state]
{:index (inc index),
:available-fields (disj available-fields action),
:fields-order (conj fields-order action),
:used-fields (conj used-fields action)}))
(defn problem--simulate-greedy
[problem state]
(if (problem--is-final-state? problem state)
[[state nil]]
(first (for [action (problem--state-actions problem state)
:let [next-state (problem--next-state problem state action)
result (problem--simulate-greedy problem next-state)]
:when (some? result)]
(lazy-seq (cons [state action] result))))))
(defn -main
[& args]
(let [data (->> *in*
(slurp)
(parse-data))
nearby-tickets-matches
(->> (for [i (->> data
(:nearby-tickets)
(count)
(range))]
(for [j (->> data
(:fields)
(count)
(range))
:let [value (get-in (:nearby-tickets data) [i j])]]
(->> data
(:fields)
(filter #(field-validate (:constraint %) value))
(map :name)
(set))))
(map vec)
(vec))]
;; part 1
(let [not-valid-values
(for [i (->> data
(:nearby-tickets)
(count)
(range))
j (->> data
(:fields)
(count)
(range))
:let [value (get-in (:nearby-tickets data) [i j])
matches (get-in nearby-tickets-matches [i j])]
:when (= (count matches) 0)]
value)]
(println "part 1" (apply + not-valid-values)))
;; part 2
(let [valid-nearby-tickets
(vec (for [i (->> data
(:nearby-tickets)
(count)
(range))
:let [ticket (nth nearby-tickets-matches i)]
:when (->> ticket
(map (fn [matches] (> (count matches) 0)))
(every? true?)
(true?))]
ticket))
cols-valid-fields (->> valid-nearby-tickets
(transpose)
(mapv #(apply clojure.set/intersection %)))
problem (problem--create (:fields data) cols-valid-fields)
initial-state (problem--make-initial-state problem)
problem-solution (->> initial-state
(problem--simulate-greedy problem)
(vec))
fields-order (->> problem-solution
(count)
(dec)
(nth problem-solution)
(first)
(:fields-order)
(vec))]
(println "part 2"
(->> data
(:own-ticket)
(map vector fields-order)
(filter #(some? (re-matches #"^departure.*" (first %))))
(map second)
(apply *))))))
| 31546 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; domain: Advent of Code 2020
;; challenge: Day 16: Ticket Translation
;; url: https://adventofcode.com/2020/day/16
;; author: <NAME> (<EMAIL>)
;; date: 2021-01-10
;; execution: $ bash ./aoc2020/run.sh d16 < [INPUT_FILE]
;; example:
;; $ bash ./aoc2020/run.sh d16 < ./aoc2020/d16/input.txt
;; part 1 23044
;; part 2 3765150732757
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns d16.main)
(defn transpose [coll] (apply mapv vector coll))
(defn product-colls
[colls]
"https://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists#Clojure"
(if (empty? colls)
'(())
(for [more (product-colls (rest colls)) x (first colls)] (cons x more))))
(defn parse-data
[data-raw]
(let [[_ fields-raw own-ticket-raw nearby-tickets-raw]
(re-matches #"(?s)^(.*?)\n\n.*?\n(.*?)\n\n.*?\n(.*?)\n$" data-raw)
fields (->> fields-raw
(clojure.string/split-lines)
(map #(re-matches #"^(.*?): (\d+)-(\d+) or (\d+)-(\d+)$" %))
(map rest)
(mapv (fn [[name & values]]
{:name name,
:constraint (mapv #(Integer/parseInt %) values)})))
own-ticket (->> own-ticket-raw
(#(clojure.string/split % #","))
(mapv #(Integer/parseInt %)))
nearby-tickets (->> nearby-tickets-raw
(clojure.string/split-lines)
(map #(clojure.string/split % #","))
(mapv (fn [ticket]
(mapv #(Integer/parseInt %) ticket))))]
{:fields fields, ;
:own-ticket own-ticket,
:nearby-tickets nearby-tickets}))
(defn field-validate
[constraint value]
(or (<= (nth constraint 0) value (nth constraint 1))
(<= (nth constraint 2) value (nth constraint 3))))
(defn problem--create
[fields cols-valid-fields]
{:fields-names fields, :cols-valid-fields cols-valid-fields})
(defn problem--make-initial-state
[problem]
{:index 0,
:available-fields (set (:fields-names problem)),
:fields-order [],
:used-fields #{}})
(defn problem--state-actions
[problem state]
(clojure.set/difference (nth (:cols-valid-fields problem) (:index state))
(:used-fields state)))
(defn problem--is-final-state?
[problem state]
(= (:index state) (count (:fields-names problem))))
(defn problem--next-state
[problem state action]
(let [{index :index,
available-fields :available-fields,
fields-order :fields-order,
used-fields :used-fields}
state]
{:index (inc index),
:available-fields (disj available-fields action),
:fields-order (conj fields-order action),
:used-fields (conj used-fields action)}))
(defn problem--simulate-greedy
[problem state]
(if (problem--is-final-state? problem state)
[[state nil]]
(first (for [action (problem--state-actions problem state)
:let [next-state (problem--next-state problem state action)
result (problem--simulate-greedy problem next-state)]
:when (some? result)]
(lazy-seq (cons [state action] result))))))
(defn -main
[& args]
(let [data (->> *in*
(slurp)
(parse-data))
nearby-tickets-matches
(->> (for [i (->> data
(:nearby-tickets)
(count)
(range))]
(for [j (->> data
(:fields)
(count)
(range))
:let [value (get-in (:nearby-tickets data) [i j])]]
(->> data
(:fields)
(filter #(field-validate (:constraint %) value))
(map :name)
(set))))
(map vec)
(vec))]
;; part 1
(let [not-valid-values
(for [i (->> data
(:nearby-tickets)
(count)
(range))
j (->> data
(:fields)
(count)
(range))
:let [value (get-in (:nearby-tickets data) [i j])
matches (get-in nearby-tickets-matches [i j])]
:when (= (count matches) 0)]
value)]
(println "part 1" (apply + not-valid-values)))
;; part 2
(let [valid-nearby-tickets
(vec (for [i (->> data
(:nearby-tickets)
(count)
(range))
:let [ticket (nth nearby-tickets-matches i)]
:when (->> ticket
(map (fn [matches] (> (count matches) 0)))
(every? true?)
(true?))]
ticket))
cols-valid-fields (->> valid-nearby-tickets
(transpose)
(mapv #(apply clojure.set/intersection %)))
problem (problem--create (:fields data) cols-valid-fields)
initial-state (problem--make-initial-state problem)
problem-solution (->> initial-state
(problem--simulate-greedy problem)
(vec))
fields-order (->> problem-solution
(count)
(dec)
(nth problem-solution)
(first)
(:fields-order)
(vec))]
(println "part 2"
(->> data
(:own-ticket)
(map vector fields-order)
(filter #(some? (re-matches #"^departure.*" (first %))))
(map second)
(apply *))))))
| true | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; domain: Advent of Code 2020
;; challenge: Day 16: Ticket Translation
;; url: https://adventofcode.com/2020/day/16
;; author: PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
;; date: 2021-01-10
;; execution: $ bash ./aoc2020/run.sh d16 < [INPUT_FILE]
;; example:
;; $ bash ./aoc2020/run.sh d16 < ./aoc2020/d16/input.txt
;; part 1 23044
;; part 2 3765150732757
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns d16.main)
(defn transpose [coll] (apply mapv vector coll))
(defn product-colls
[colls]
"https://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists#Clojure"
(if (empty? colls)
'(())
(for [more (product-colls (rest colls)) x (first colls)] (cons x more))))
(defn parse-data
[data-raw]
(let [[_ fields-raw own-ticket-raw nearby-tickets-raw]
(re-matches #"(?s)^(.*?)\n\n.*?\n(.*?)\n\n.*?\n(.*?)\n$" data-raw)
fields (->> fields-raw
(clojure.string/split-lines)
(map #(re-matches #"^(.*?): (\d+)-(\d+) or (\d+)-(\d+)$" %))
(map rest)
(mapv (fn [[name & values]]
{:name name,
:constraint (mapv #(Integer/parseInt %) values)})))
own-ticket (->> own-ticket-raw
(#(clojure.string/split % #","))
(mapv #(Integer/parseInt %)))
nearby-tickets (->> nearby-tickets-raw
(clojure.string/split-lines)
(map #(clojure.string/split % #","))
(mapv (fn [ticket]
(mapv #(Integer/parseInt %) ticket))))]
{:fields fields, ;
:own-ticket own-ticket,
:nearby-tickets nearby-tickets}))
(defn field-validate
[constraint value]
(or (<= (nth constraint 0) value (nth constraint 1))
(<= (nth constraint 2) value (nth constraint 3))))
(defn problem--create
[fields cols-valid-fields]
{:fields-names fields, :cols-valid-fields cols-valid-fields})
(defn problem--make-initial-state
[problem]
{:index 0,
:available-fields (set (:fields-names problem)),
:fields-order [],
:used-fields #{}})
(defn problem--state-actions
[problem state]
(clojure.set/difference (nth (:cols-valid-fields problem) (:index state))
(:used-fields state)))
(defn problem--is-final-state?
[problem state]
(= (:index state) (count (:fields-names problem))))
(defn problem--next-state
[problem state action]
(let [{index :index,
available-fields :available-fields,
fields-order :fields-order,
used-fields :used-fields}
state]
{:index (inc index),
:available-fields (disj available-fields action),
:fields-order (conj fields-order action),
:used-fields (conj used-fields action)}))
(defn problem--simulate-greedy
[problem state]
(if (problem--is-final-state? problem state)
[[state nil]]
(first (for [action (problem--state-actions problem state)
:let [next-state (problem--next-state problem state action)
result (problem--simulate-greedy problem next-state)]
:when (some? result)]
(lazy-seq (cons [state action] result))))))
(defn -main
[& args]
(let [data (->> *in*
(slurp)
(parse-data))
nearby-tickets-matches
(->> (for [i (->> data
(:nearby-tickets)
(count)
(range))]
(for [j (->> data
(:fields)
(count)
(range))
:let [value (get-in (:nearby-tickets data) [i j])]]
(->> data
(:fields)
(filter #(field-validate (:constraint %) value))
(map :name)
(set))))
(map vec)
(vec))]
;; part 1
(let [not-valid-values
(for [i (->> data
(:nearby-tickets)
(count)
(range))
j (->> data
(:fields)
(count)
(range))
:let [value (get-in (:nearby-tickets data) [i j])
matches (get-in nearby-tickets-matches [i j])]
:when (= (count matches) 0)]
value)]
(println "part 1" (apply + not-valid-values)))
;; part 2
(let [valid-nearby-tickets
(vec (for [i (->> data
(:nearby-tickets)
(count)
(range))
:let [ticket (nth nearby-tickets-matches i)]
:when (->> ticket
(map (fn [matches] (> (count matches) 0)))
(every? true?)
(true?))]
ticket))
cols-valid-fields (->> valid-nearby-tickets
(transpose)
(mapv #(apply clojure.set/intersection %)))
problem (problem--create (:fields data) cols-valid-fields)
initial-state (problem--make-initial-state problem)
problem-solution (->> initial-state
(problem--simulate-greedy problem)
(vec))
fields-order (->> problem-solution
(count)
(dec)
(nth problem-solution)
(first)
(:fields-order)
(vec))]
(println "part 2"
(->> data
(:own-ticket)
(map vector fields-order)
(filter #(some? (re-matches #"^departure.*" (first %))))
(map second)
(apply *))))))
|
[
{
"context": " tests for utility functions\n;;\n;; Copyright 2012, F.M. de Waard & Vixu.com <fmw@vixu.com>.\n;;\n;; Licensed under t",
"end": 92,
"score": 0.9998603463172913,
"start": 79,
"tag": "NAME",
"value": "F.M. de Waard"
},
{
"context": "s\n;;\n;; Copyright 2012, F.M. de Waard & Vixu.com <fmw@vixu.com>.\n;;\n;; Licensed under the Apache License, Versio",
"end": 117,
"score": 0.9999343752861023,
"start": 105,
"tag": "EMAIL",
"value": "fmw@vixu.com"
}
] | test/alida/test/util.clj | fmw/alida | 6 | ;; test/alida/test/util.clj: tests for utility functions
;;
;; Copyright 2012, F.M. de Waard & Vixu.com <fmw@vixu.com>.
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns alida.test.util
(:use [clojure.test]
[alida.util] :reload)
(:require [clj-time.core :as time-core]))
(deftest test-make-timestamp
(is (re-matches
#"^[\d]{4}-[\d]{2}-[\d]{2}T[\d]{2}:[\d]{2}:[\d]{2}\.[\d]{1,4}Z"
(make-timestamp))))
(deftest test-rfc3339-to-jodatime
(let [datetime-obj (rfc3339-to-jodatime "2011-11-04T09:16:52.253Z"
"Europe/Amsterdam")]
(is (= (time-core/month datetime-obj) 11))
(is (= (time-core/day datetime-obj) 4))
(is (= (time-core/year datetime-obj) 2011))
(is (= (time-core/hour datetime-obj) 10))
(is (= (time-core/minute datetime-obj) 16))
(is (= (time-core/sec datetime-obj) 52))
(is (= (time-core/milli datetime-obj) 253)))
(is (= (rfc3339-to-jodatime nil "GMT") nil)))
(deftest test-rfc3339-to-long
(is (= (rfc3339-to-long "2011-11-04T09:16:52.253Z")
1320398212253))
(is (= (rfc3339-to-long "2012-01-12T15:40:07+01:00")
1326379207000))
(is (= (rfc3339-to-long nil) nil))
(is (= (rfc3339-to-long 10) nil)))
(deftest test-get-absolute-uri
(are [base-uri link expected-uri]
(= (get-absolute-uri base-uri link) expected-uri)
"http://www.dummyhealthfoodstore.com/"
"/products/whisky.html"
"http://www.dummyhealthfoodstore.com/products/whisky.html"
"http://www.dummyhealthfoodstore.com/products/whisky.html"
"../brora.html"
"http://www.dummyhealthfoodstore.com/brora.html"
"http://www.dummyhealthfoodstore.com/"
"/brora.html#fragment"
"http://www.dummyhealthfoodstore.com/brora.html"
"http://www.dummyhealthfoodstore.com:8080/"
"/brora.html"
"http://www.dummyhealthfoodstore.com:8080/brora.html"))
(deftest test-get-uri-segments
(is (= (get-uri-segments "http://www.dummyhealthfoodstore.com/brora.html")
{:scheme "http://"
:host "www.dummyhealthfoodstore.com"
:path "/brora.html"}))) | 118460 | ;; test/alida/test/util.clj: tests for utility functions
;;
;; Copyright 2012, <NAME> & Vixu.com <<EMAIL>>.
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns alida.test.util
(:use [clojure.test]
[alida.util] :reload)
(:require [clj-time.core :as time-core]))
(deftest test-make-timestamp
(is (re-matches
#"^[\d]{4}-[\d]{2}-[\d]{2}T[\d]{2}:[\d]{2}:[\d]{2}\.[\d]{1,4}Z"
(make-timestamp))))
(deftest test-rfc3339-to-jodatime
(let [datetime-obj (rfc3339-to-jodatime "2011-11-04T09:16:52.253Z"
"Europe/Amsterdam")]
(is (= (time-core/month datetime-obj) 11))
(is (= (time-core/day datetime-obj) 4))
(is (= (time-core/year datetime-obj) 2011))
(is (= (time-core/hour datetime-obj) 10))
(is (= (time-core/minute datetime-obj) 16))
(is (= (time-core/sec datetime-obj) 52))
(is (= (time-core/milli datetime-obj) 253)))
(is (= (rfc3339-to-jodatime nil "GMT") nil)))
(deftest test-rfc3339-to-long
(is (= (rfc3339-to-long "2011-11-04T09:16:52.253Z")
1320398212253))
(is (= (rfc3339-to-long "2012-01-12T15:40:07+01:00")
1326379207000))
(is (= (rfc3339-to-long nil) nil))
(is (= (rfc3339-to-long 10) nil)))
(deftest test-get-absolute-uri
(are [base-uri link expected-uri]
(= (get-absolute-uri base-uri link) expected-uri)
"http://www.dummyhealthfoodstore.com/"
"/products/whisky.html"
"http://www.dummyhealthfoodstore.com/products/whisky.html"
"http://www.dummyhealthfoodstore.com/products/whisky.html"
"../brora.html"
"http://www.dummyhealthfoodstore.com/brora.html"
"http://www.dummyhealthfoodstore.com/"
"/brora.html#fragment"
"http://www.dummyhealthfoodstore.com/brora.html"
"http://www.dummyhealthfoodstore.com:8080/"
"/brora.html"
"http://www.dummyhealthfoodstore.com:8080/brora.html"))
(deftest test-get-uri-segments
(is (= (get-uri-segments "http://www.dummyhealthfoodstore.com/brora.html")
{:scheme "http://"
:host "www.dummyhealthfoodstore.com"
:path "/brora.html"}))) | true | ;; test/alida/test/util.clj: tests for utility functions
;;
;; Copyright 2012, PI:NAME:<NAME>END_PI & Vixu.com <PI:EMAIL:<EMAIL>END_PI>.
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns alida.test.util
(:use [clojure.test]
[alida.util] :reload)
(:require [clj-time.core :as time-core]))
(deftest test-make-timestamp
(is (re-matches
#"^[\d]{4}-[\d]{2}-[\d]{2}T[\d]{2}:[\d]{2}:[\d]{2}\.[\d]{1,4}Z"
(make-timestamp))))
(deftest test-rfc3339-to-jodatime
(let [datetime-obj (rfc3339-to-jodatime "2011-11-04T09:16:52.253Z"
"Europe/Amsterdam")]
(is (= (time-core/month datetime-obj) 11))
(is (= (time-core/day datetime-obj) 4))
(is (= (time-core/year datetime-obj) 2011))
(is (= (time-core/hour datetime-obj) 10))
(is (= (time-core/minute datetime-obj) 16))
(is (= (time-core/sec datetime-obj) 52))
(is (= (time-core/milli datetime-obj) 253)))
(is (= (rfc3339-to-jodatime nil "GMT") nil)))
(deftest test-rfc3339-to-long
(is (= (rfc3339-to-long "2011-11-04T09:16:52.253Z")
1320398212253))
(is (= (rfc3339-to-long "2012-01-12T15:40:07+01:00")
1326379207000))
(is (= (rfc3339-to-long nil) nil))
(is (= (rfc3339-to-long 10) nil)))
(deftest test-get-absolute-uri
(are [base-uri link expected-uri]
(= (get-absolute-uri base-uri link) expected-uri)
"http://www.dummyhealthfoodstore.com/"
"/products/whisky.html"
"http://www.dummyhealthfoodstore.com/products/whisky.html"
"http://www.dummyhealthfoodstore.com/products/whisky.html"
"../brora.html"
"http://www.dummyhealthfoodstore.com/brora.html"
"http://www.dummyhealthfoodstore.com/"
"/brora.html#fragment"
"http://www.dummyhealthfoodstore.com/brora.html"
"http://www.dummyhealthfoodstore.com:8080/"
"/brora.html"
"http://www.dummyhealthfoodstore.com:8080/brora.html"))
(deftest test-get-uri-segments
(is (= (get-uri-segments "http://www.dummyhealthfoodstore.com/brora.html")
{:scheme "http://"
:host "www.dummyhealthfoodstore.com"
:path "/brora.html"}))) |
[
{
"context": ", animation, and simulations\"\n ;; (Adrian Dobre and Dev Ramtal)\n (let [v-ball (get",
"end": 12398,
"score": 0.9998849630355835,
"start": 12386,
"tag": "NAME",
"value": "Adrian Dobre"
},
{
"context": " simulations\"\n ;; (Adrian Dobre and Dev Ramtal)\n (let [v-ball (get ball :velocity",
"end": 12413,
"score": 0.9998646378517151,
"start": 12403,
"tag": "NAME",
"value": "Dev Ramtal"
}
] | src/cljs/dev/reus/rondo/model.cljs | reus/rondo | 0 | (ns dev.reus.rondo.model
(:require [dev.reus.rondo.math :as math :refer [dot-product magnitude normalize
add subtract add-scaled distance angle
rotate scale-by projection para project
proj distance-circles circles-overlap?]]
[dev.reus.rondo.gamedata :as gamedata]))
(defn find-color [team]
"Determine the shirt-color of a player. Use a team keyword."
(loop [i 0]
(if-let [t (get gamedata/teams i)]
(if (= (:id t) team)
(:color t)
(recur (inc i)))
[0 0 0])))
(defn init-player [idx player]
"Initialize player vector. Adds different game related
properties to each player hashmap."
(let [team (:team player)
color (find-color team)
[r g b] (map #(* 256 %) color)
color-str (str "rgb(" r "," g "," b ")")]
(assoc player
:goal {:status :idle}
:index idx
:color color
:color-str color-str)))
(defn init-players []
"Initialize player data to be used in gameloop."
(mapv init-player (range) gamedata/players))
(defn init-teams []
"Initialize team data to be used in gameloop."
gamedata/teams)
(defn compute-integrals
([player acc-dir dt]
(compute-integrals player acc-dir 0 dt))
([{[vx vy] :velocity pos :pos dir :direction :as player} acc-dir turn dt]
(let [magn (magnitude [vx vy])
new-acc (mapv + (map #(* 100 %) acc-dir) (map #(* -0.3 magn %) [vx vy]) (map * (map #(* turn %) [-1 1]) [vy vx]))
new-vel (mapv + [vx vy] (map #(* dt %) new-acc))
new-pos (mapv + pos (map #(* dt %) new-vel))
new-dir (if (< magn 7)
(rotate dir (* 0.03 turn))
(normalize new-vel))]
(assoc player :acceleration new-acc :velocity new-vel :pos new-pos :prev-pos pos :direction new-dir))))
(defn set-direction [{vel :velocity :as player}]
(assoc player :direction (normalize vel)))
(defn get-player-update-fn [state]
(fn [{acc :acceleration vel :velocity pos :pos dir :direction :as player}]
(let [dt (* 0.001 (:frame-time state))
goal (:goal player)]
(case (:status goal)
:human-controlled (let [run (:run goal)
acc-dir (map #(* run %) (:acc-dir goal))
turn (* run (:turn goal))]
(if (zero? turn)
(compute-integrals player acc-dir dt)
(if (= acc-dir [0 0])
(compute-integrals player acc-dir turn dt)
(compute-integrals player acc-dir turn dt))))
:move-direction (let [acc-dir (:direction goal)]
(-> player
(compute-integrals acc-dir dt)))
:move-destination (let [dest (:destination goal)
run (:run goal)
dest-vector (subtract dest pos)
norm (map #(* run %)(normalize dest-vector))
new-player (-> player
(compute-integrals norm dt))
vec-new-player-to-dest (subtract dest (:pos new-player))]
(if (> (dot-product dest-vector vec-new-player-to-dest) 10) ;check if destination has been (almost) reached
new-player
(assoc player :goal {:status :decelerate})))
:decelerate (let [vel (:velocity player)
magn (magnitude vel)]
(if (> magn 5)
(compute-integrals player [0 0] dt)
(assoc player :acceleration [0 0] :velocity [0 0] :goal {:status :idle})))
:approach-ball (let [ball (:ball state)
ball-state (:state ball)]
(if (= :moving ball-state)
(let [pos-ball (:pos ball)
dir-ball (normalize (:velocity ball))
pos-player (:pos player)
vec-ball-to-player (subtract pos-player pos-ball)
pr (proj dir-ball vec-ball-to-player)]
(println pos-ball)
(println dir-ball)
(println pos-player)
(println vec-ball-to-player)
(println pr)
(assoc player :goal {:status :move-destination
:destination (add pos-ball pr)
:run 3}))
player))
:set-idle (assoc player :goal {:status :idle} :acceleration [0 0] :velocity [0 0])
player))))
(defn update-players [{players :players :as state}]
(let [update-fn (get-player-update-fn state)]
(assoc state :players (mapv update-fn players))))
(defn position-ball-with-player [{pos :pos dir :direction}]
(mapv + pos (map #(* % (+ (:player-radius gamedata/settings)
(:ball-radius gamedata/settings)
(:distance-to-ball gamedata/settings))) dir)))
(defn update-ball [{ball :ball :as state}]
(if-let [p (:player ball)]
(case (:state ball)
(:with-player
:shooting) (let [player (get-in state [:players p])
new-pos (position-ball-with-player player)]
(assoc-in state [:ball :pos] new-pos))
:shot-initiated (let [player (get-in state [:players p])
new-pos (position-ball-with-player player)
t (:time state)
new-ball (assoc ball :shot-start-time t :pos new-pos)]
(assoc state :ball new-ball))
:release-shot (let [player (get-in state [:players p])
pos (:pos player)
dir (:direction player)
t (:time state)
shot-start-time (:shot-start-time ball)
ke (* (- t shot-start-time) 100)
vmag (.sqrt js/Math (* ke 2))
vel (map #(* % vmag) dir)
new-pos (position-ball-with-player player)]
(assoc state :ball {:state :moving
:player nil
:velocity vel
:ke ke
:pos new-pos
:shot-start-time nil})))
(case (:state ball)
:moving (let [ke (:ke ball)]
(if (> ke 1)
(let [vmag (.sqrt js/Math (* ke 2))
vel (:velocity ball)
new-vel (map #(* % vmag) (normalize vel))
dt (* 0.001 (:frame-time state))
pos (:pos ball)
new-position (mapv + pos (map #(* dt %) new-vel))]
(assoc state :ball {:state :moving
:pos new-position
:velocity new-vel
:ke (- ke (* 1 vmag vmag dt))
:player nil
:shot-start-time nil}))
(assoc state :ball {:state :still
:pos (:pos ball)
:velocity [0 0]
:ke 0
:player nil
:shot-start-time nil})))
:still state)))
(defn reset-position [state i]
(let [player (get-in state [:players i])
pos (get-in gamedata/players [i :pos])
dir (get-in gamedata/players [i :direction])
reset (assoc player :pos pos :acceleration [0 0] :velocity [0 0] :direction dir :goal {:status :idle})
new-state (assoc-in state [:players i] reset)]
new-state))
(defn random-position [state i]
(let [player (get-in state [:players i])
[min-x min-y] [(:player-radius gamedata/settings) (:player-radius gamedata/settings)]
[max-x max-y] (map #(- % (:player-radius gamedata/settings))
(:pitch-size gamedata/settings))
new-pos [(+ min-x (int (* max-x (.random js/Math))))
(+ min-y (int (* max-y (.random js/Math))))]
new-player (assoc player :pos new-pos :acceleration [0 0] :velocity [0 0] :goal {:status :idle})
new-state (assoc-in state [:players i] new-player)]
new-state))
(defn point-in-player? [[x y] player]
"Determine whether the point (x,y) is part of a player's body."
(let [player-radius (:player-radius gamedata/settings)
ab [(* 2 player-radius) 0]
bc [0 (* 2 player-radius)]
[x-player y-player] (:pos player)
pa [(- x-player player-radius) (- y-player player-radius)]
pb [(+ x-player player-radius) (- y-player player-radius)]
am (map - [x y] pa)
bm (map - [x y] pb)]
(and (<= 0 (dot-product ab am))
(<= (dot-product ab am) (dot-product ab ab))
(<= 0 (dot-product bc bm))
(<= (dot-product bc bm) (dot-product bc bc)))))
(defn point-in-players? [[x y] players]
"Given a vector of players, determine whether the point (x,y)
is part of a player's body."
(loop [i 0]
(if-let [player (get players i)]
(if (point-in-player? [x y] player)
i
(recur (inc i))))))
(defn player-player-collisions [{players :players :as state}]
(let [r (:player-radius gamedata/settings)
ps (mapv #(select-keys % [:pos :index]) players)
positions (for [p ps :let [i (:index p)]]
[p (mapv :pos (filter #(not= (:index %) i) ps))])]
(loop [ps positions new-players []]
(if-let [x (first ps)]
(let [collisions (map #(circles-overlap? (get (first x) :pos) r % r) (last x))]
(let [index (get (first x) :index)
player (get players index)]
(if (some identity collisions)
(recur (rest ps) (conj new-players (assoc player :goal {:status :idle}
:pos (or (get player :prev-pos)
(get player :pos)))))
(recur (rest ps) (conj new-players player)))))
(assoc state :players new-players)))))
(defn player-ball-collisions [{players :players ball :ball :as state}]
(let [ball-pos (get ball :pos)
ball-radius (get gamedata/settings :ball-radius)
player-radius (get gamedata/settings :player-radius)]
(loop [i 0 collisions []]
(if-let [p (get players i)]
(if (circles-overlap? (get p :pos) player-radius ball-pos ball-radius)
(recur (inc i) (conj collisions (get p :index)))
(recur (inc i) collisions))
(case (count collisions)
0 state
1 (let [index (first collisions)
player (get-in state [:players index])
pos-player (:pos player)
vector-player-ball (map - ball-pos pos-player)
norm-vector-player-ball (normalize vector-player-ball)
dir (:direction player)
angle (angle dir norm-vector-player-ball)]
(if (< angle (get gamedata/settings :max-angle-pickup-ball))
(assoc state :ball {:state :with-player
:player index
:ke 0 ;; kinetic energy
:velocity nil
:pos (position-ball-with-player player)
:shot-start-time nil})
;; ball bounces on player, calculate new velocity
;; based on method described in book
;; "Physics for javascript games, animation, and simulations"
;; (Adrian Dobre and Dev Ramtal)
(let [v-ball (get ball :velocity)
v-player (get player :velocity)
normal-velo-ball (project v-ball vector-player-ball)
normal-velo-player (project v-player vector-player-ball)
tangent-velo-ball (subtract v-ball normal-velo-ball)
L (- (+ ball-radius player-radius) (magnitude vector-player-ball))
vrel (magnitude (subtract normal-velo-ball normal-velo-player))
ball-pos-impact (add-scaled ball-pos normal-velo-ball (/ (* -1 L) vrel))
u1 (projection normal-velo-ball vector-player-ball)
u2 (projection normal-velo-player vector-player-ball)
v1 (+ (* -1 u1) (* 2 u2)) ;assuming the weight of the ball is much smaller then the player
normal-velo-1 (para vector-player-ball v1)
new-v-ball (add normal-velo-1 tangent-velo-ball)]
(assoc state :ball {:state :moving
:player nil
:ke (* (get ball :ke) ;; lose kinetic energy
(get gamedata/settings :factor-ke-loss-on-collision))
:velocity new-v-ball
:pos ball-pos-impact
:shot-start-time nil}))))
2 (do
(println 2)
state)
state)))))
(defn check-ball [{ball :ball :as state}]
(let [[x y] (get ball :pos)]
(if (or (js/isNaN x) (js/isNaN y))
(do
(println state)
(assoc-in state [:ball :pos] [10 10]))
state)))
| 59878 | (ns dev.reus.rondo.model
(:require [dev.reus.rondo.math :as math :refer [dot-product magnitude normalize
add subtract add-scaled distance angle
rotate scale-by projection para project
proj distance-circles circles-overlap?]]
[dev.reus.rondo.gamedata :as gamedata]))
(defn find-color [team]
"Determine the shirt-color of a player. Use a team keyword."
(loop [i 0]
(if-let [t (get gamedata/teams i)]
(if (= (:id t) team)
(:color t)
(recur (inc i)))
[0 0 0])))
(defn init-player [idx player]
"Initialize player vector. Adds different game related
properties to each player hashmap."
(let [team (:team player)
color (find-color team)
[r g b] (map #(* 256 %) color)
color-str (str "rgb(" r "," g "," b ")")]
(assoc player
:goal {:status :idle}
:index idx
:color color
:color-str color-str)))
(defn init-players []
"Initialize player data to be used in gameloop."
(mapv init-player (range) gamedata/players))
(defn init-teams []
"Initialize team data to be used in gameloop."
gamedata/teams)
(defn compute-integrals
([player acc-dir dt]
(compute-integrals player acc-dir 0 dt))
([{[vx vy] :velocity pos :pos dir :direction :as player} acc-dir turn dt]
(let [magn (magnitude [vx vy])
new-acc (mapv + (map #(* 100 %) acc-dir) (map #(* -0.3 magn %) [vx vy]) (map * (map #(* turn %) [-1 1]) [vy vx]))
new-vel (mapv + [vx vy] (map #(* dt %) new-acc))
new-pos (mapv + pos (map #(* dt %) new-vel))
new-dir (if (< magn 7)
(rotate dir (* 0.03 turn))
(normalize new-vel))]
(assoc player :acceleration new-acc :velocity new-vel :pos new-pos :prev-pos pos :direction new-dir))))
(defn set-direction [{vel :velocity :as player}]
(assoc player :direction (normalize vel)))
(defn get-player-update-fn [state]
(fn [{acc :acceleration vel :velocity pos :pos dir :direction :as player}]
(let [dt (* 0.001 (:frame-time state))
goal (:goal player)]
(case (:status goal)
:human-controlled (let [run (:run goal)
acc-dir (map #(* run %) (:acc-dir goal))
turn (* run (:turn goal))]
(if (zero? turn)
(compute-integrals player acc-dir dt)
(if (= acc-dir [0 0])
(compute-integrals player acc-dir turn dt)
(compute-integrals player acc-dir turn dt))))
:move-direction (let [acc-dir (:direction goal)]
(-> player
(compute-integrals acc-dir dt)))
:move-destination (let [dest (:destination goal)
run (:run goal)
dest-vector (subtract dest pos)
norm (map #(* run %)(normalize dest-vector))
new-player (-> player
(compute-integrals norm dt))
vec-new-player-to-dest (subtract dest (:pos new-player))]
(if (> (dot-product dest-vector vec-new-player-to-dest) 10) ;check if destination has been (almost) reached
new-player
(assoc player :goal {:status :decelerate})))
:decelerate (let [vel (:velocity player)
magn (magnitude vel)]
(if (> magn 5)
(compute-integrals player [0 0] dt)
(assoc player :acceleration [0 0] :velocity [0 0] :goal {:status :idle})))
:approach-ball (let [ball (:ball state)
ball-state (:state ball)]
(if (= :moving ball-state)
(let [pos-ball (:pos ball)
dir-ball (normalize (:velocity ball))
pos-player (:pos player)
vec-ball-to-player (subtract pos-player pos-ball)
pr (proj dir-ball vec-ball-to-player)]
(println pos-ball)
(println dir-ball)
(println pos-player)
(println vec-ball-to-player)
(println pr)
(assoc player :goal {:status :move-destination
:destination (add pos-ball pr)
:run 3}))
player))
:set-idle (assoc player :goal {:status :idle} :acceleration [0 0] :velocity [0 0])
player))))
(defn update-players [{players :players :as state}]
(let [update-fn (get-player-update-fn state)]
(assoc state :players (mapv update-fn players))))
(defn position-ball-with-player [{pos :pos dir :direction}]
(mapv + pos (map #(* % (+ (:player-radius gamedata/settings)
(:ball-radius gamedata/settings)
(:distance-to-ball gamedata/settings))) dir)))
(defn update-ball [{ball :ball :as state}]
(if-let [p (:player ball)]
(case (:state ball)
(:with-player
:shooting) (let [player (get-in state [:players p])
new-pos (position-ball-with-player player)]
(assoc-in state [:ball :pos] new-pos))
:shot-initiated (let [player (get-in state [:players p])
new-pos (position-ball-with-player player)
t (:time state)
new-ball (assoc ball :shot-start-time t :pos new-pos)]
(assoc state :ball new-ball))
:release-shot (let [player (get-in state [:players p])
pos (:pos player)
dir (:direction player)
t (:time state)
shot-start-time (:shot-start-time ball)
ke (* (- t shot-start-time) 100)
vmag (.sqrt js/Math (* ke 2))
vel (map #(* % vmag) dir)
new-pos (position-ball-with-player player)]
(assoc state :ball {:state :moving
:player nil
:velocity vel
:ke ke
:pos new-pos
:shot-start-time nil})))
(case (:state ball)
:moving (let [ke (:ke ball)]
(if (> ke 1)
(let [vmag (.sqrt js/Math (* ke 2))
vel (:velocity ball)
new-vel (map #(* % vmag) (normalize vel))
dt (* 0.001 (:frame-time state))
pos (:pos ball)
new-position (mapv + pos (map #(* dt %) new-vel))]
(assoc state :ball {:state :moving
:pos new-position
:velocity new-vel
:ke (- ke (* 1 vmag vmag dt))
:player nil
:shot-start-time nil}))
(assoc state :ball {:state :still
:pos (:pos ball)
:velocity [0 0]
:ke 0
:player nil
:shot-start-time nil})))
:still state)))
(defn reset-position [state i]
(let [player (get-in state [:players i])
pos (get-in gamedata/players [i :pos])
dir (get-in gamedata/players [i :direction])
reset (assoc player :pos pos :acceleration [0 0] :velocity [0 0] :direction dir :goal {:status :idle})
new-state (assoc-in state [:players i] reset)]
new-state))
(defn random-position [state i]
(let [player (get-in state [:players i])
[min-x min-y] [(:player-radius gamedata/settings) (:player-radius gamedata/settings)]
[max-x max-y] (map #(- % (:player-radius gamedata/settings))
(:pitch-size gamedata/settings))
new-pos [(+ min-x (int (* max-x (.random js/Math))))
(+ min-y (int (* max-y (.random js/Math))))]
new-player (assoc player :pos new-pos :acceleration [0 0] :velocity [0 0] :goal {:status :idle})
new-state (assoc-in state [:players i] new-player)]
new-state))
(defn point-in-player? [[x y] player]
"Determine whether the point (x,y) is part of a player's body."
(let [player-radius (:player-radius gamedata/settings)
ab [(* 2 player-radius) 0]
bc [0 (* 2 player-radius)]
[x-player y-player] (:pos player)
pa [(- x-player player-radius) (- y-player player-radius)]
pb [(+ x-player player-radius) (- y-player player-radius)]
am (map - [x y] pa)
bm (map - [x y] pb)]
(and (<= 0 (dot-product ab am))
(<= (dot-product ab am) (dot-product ab ab))
(<= 0 (dot-product bc bm))
(<= (dot-product bc bm) (dot-product bc bc)))))
(defn point-in-players? [[x y] players]
"Given a vector of players, determine whether the point (x,y)
is part of a player's body."
(loop [i 0]
(if-let [player (get players i)]
(if (point-in-player? [x y] player)
i
(recur (inc i))))))
(defn player-player-collisions [{players :players :as state}]
(let [r (:player-radius gamedata/settings)
ps (mapv #(select-keys % [:pos :index]) players)
positions (for [p ps :let [i (:index p)]]
[p (mapv :pos (filter #(not= (:index %) i) ps))])]
(loop [ps positions new-players []]
(if-let [x (first ps)]
(let [collisions (map #(circles-overlap? (get (first x) :pos) r % r) (last x))]
(let [index (get (first x) :index)
player (get players index)]
(if (some identity collisions)
(recur (rest ps) (conj new-players (assoc player :goal {:status :idle}
:pos (or (get player :prev-pos)
(get player :pos)))))
(recur (rest ps) (conj new-players player)))))
(assoc state :players new-players)))))
(defn player-ball-collisions [{players :players ball :ball :as state}]
(let [ball-pos (get ball :pos)
ball-radius (get gamedata/settings :ball-radius)
player-radius (get gamedata/settings :player-radius)]
(loop [i 0 collisions []]
(if-let [p (get players i)]
(if (circles-overlap? (get p :pos) player-radius ball-pos ball-radius)
(recur (inc i) (conj collisions (get p :index)))
(recur (inc i) collisions))
(case (count collisions)
0 state
1 (let [index (first collisions)
player (get-in state [:players index])
pos-player (:pos player)
vector-player-ball (map - ball-pos pos-player)
norm-vector-player-ball (normalize vector-player-ball)
dir (:direction player)
angle (angle dir norm-vector-player-ball)]
(if (< angle (get gamedata/settings :max-angle-pickup-ball))
(assoc state :ball {:state :with-player
:player index
:ke 0 ;; kinetic energy
:velocity nil
:pos (position-ball-with-player player)
:shot-start-time nil})
;; ball bounces on player, calculate new velocity
;; based on method described in book
;; "Physics for javascript games, animation, and simulations"
;; (<NAME> and <NAME>)
(let [v-ball (get ball :velocity)
v-player (get player :velocity)
normal-velo-ball (project v-ball vector-player-ball)
normal-velo-player (project v-player vector-player-ball)
tangent-velo-ball (subtract v-ball normal-velo-ball)
L (- (+ ball-radius player-radius) (magnitude vector-player-ball))
vrel (magnitude (subtract normal-velo-ball normal-velo-player))
ball-pos-impact (add-scaled ball-pos normal-velo-ball (/ (* -1 L) vrel))
u1 (projection normal-velo-ball vector-player-ball)
u2 (projection normal-velo-player vector-player-ball)
v1 (+ (* -1 u1) (* 2 u2)) ;assuming the weight of the ball is much smaller then the player
normal-velo-1 (para vector-player-ball v1)
new-v-ball (add normal-velo-1 tangent-velo-ball)]
(assoc state :ball {:state :moving
:player nil
:ke (* (get ball :ke) ;; lose kinetic energy
(get gamedata/settings :factor-ke-loss-on-collision))
:velocity new-v-ball
:pos ball-pos-impact
:shot-start-time nil}))))
2 (do
(println 2)
state)
state)))))
(defn check-ball [{ball :ball :as state}]
(let [[x y] (get ball :pos)]
(if (or (js/isNaN x) (js/isNaN y))
(do
(println state)
(assoc-in state [:ball :pos] [10 10]))
state)))
| true | (ns dev.reus.rondo.model
(:require [dev.reus.rondo.math :as math :refer [dot-product magnitude normalize
add subtract add-scaled distance angle
rotate scale-by projection para project
proj distance-circles circles-overlap?]]
[dev.reus.rondo.gamedata :as gamedata]))
(defn find-color [team]
"Determine the shirt-color of a player. Use a team keyword."
(loop [i 0]
(if-let [t (get gamedata/teams i)]
(if (= (:id t) team)
(:color t)
(recur (inc i)))
[0 0 0])))
(defn init-player [idx player]
"Initialize player vector. Adds different game related
properties to each player hashmap."
(let [team (:team player)
color (find-color team)
[r g b] (map #(* 256 %) color)
color-str (str "rgb(" r "," g "," b ")")]
(assoc player
:goal {:status :idle}
:index idx
:color color
:color-str color-str)))
(defn init-players []
"Initialize player data to be used in gameloop."
(mapv init-player (range) gamedata/players))
(defn init-teams []
"Initialize team data to be used in gameloop."
gamedata/teams)
(defn compute-integrals
([player acc-dir dt]
(compute-integrals player acc-dir 0 dt))
([{[vx vy] :velocity pos :pos dir :direction :as player} acc-dir turn dt]
(let [magn (magnitude [vx vy])
new-acc (mapv + (map #(* 100 %) acc-dir) (map #(* -0.3 magn %) [vx vy]) (map * (map #(* turn %) [-1 1]) [vy vx]))
new-vel (mapv + [vx vy] (map #(* dt %) new-acc))
new-pos (mapv + pos (map #(* dt %) new-vel))
new-dir (if (< magn 7)
(rotate dir (* 0.03 turn))
(normalize new-vel))]
(assoc player :acceleration new-acc :velocity new-vel :pos new-pos :prev-pos pos :direction new-dir))))
(defn set-direction [{vel :velocity :as player}]
(assoc player :direction (normalize vel)))
(defn get-player-update-fn [state]
(fn [{acc :acceleration vel :velocity pos :pos dir :direction :as player}]
(let [dt (* 0.001 (:frame-time state))
goal (:goal player)]
(case (:status goal)
:human-controlled (let [run (:run goal)
acc-dir (map #(* run %) (:acc-dir goal))
turn (* run (:turn goal))]
(if (zero? turn)
(compute-integrals player acc-dir dt)
(if (= acc-dir [0 0])
(compute-integrals player acc-dir turn dt)
(compute-integrals player acc-dir turn dt))))
:move-direction (let [acc-dir (:direction goal)]
(-> player
(compute-integrals acc-dir dt)))
:move-destination (let [dest (:destination goal)
run (:run goal)
dest-vector (subtract dest pos)
norm (map #(* run %)(normalize dest-vector))
new-player (-> player
(compute-integrals norm dt))
vec-new-player-to-dest (subtract dest (:pos new-player))]
(if (> (dot-product dest-vector vec-new-player-to-dest) 10) ;check if destination has been (almost) reached
new-player
(assoc player :goal {:status :decelerate})))
:decelerate (let [vel (:velocity player)
magn (magnitude vel)]
(if (> magn 5)
(compute-integrals player [0 0] dt)
(assoc player :acceleration [0 0] :velocity [0 0] :goal {:status :idle})))
:approach-ball (let [ball (:ball state)
ball-state (:state ball)]
(if (= :moving ball-state)
(let [pos-ball (:pos ball)
dir-ball (normalize (:velocity ball))
pos-player (:pos player)
vec-ball-to-player (subtract pos-player pos-ball)
pr (proj dir-ball vec-ball-to-player)]
(println pos-ball)
(println dir-ball)
(println pos-player)
(println vec-ball-to-player)
(println pr)
(assoc player :goal {:status :move-destination
:destination (add pos-ball pr)
:run 3}))
player))
:set-idle (assoc player :goal {:status :idle} :acceleration [0 0] :velocity [0 0])
player))))
(defn update-players [{players :players :as state}]
(let [update-fn (get-player-update-fn state)]
(assoc state :players (mapv update-fn players))))
(defn position-ball-with-player [{pos :pos dir :direction}]
(mapv + pos (map #(* % (+ (:player-radius gamedata/settings)
(:ball-radius gamedata/settings)
(:distance-to-ball gamedata/settings))) dir)))
(defn update-ball [{ball :ball :as state}]
(if-let [p (:player ball)]
(case (:state ball)
(:with-player
:shooting) (let [player (get-in state [:players p])
new-pos (position-ball-with-player player)]
(assoc-in state [:ball :pos] new-pos))
:shot-initiated (let [player (get-in state [:players p])
new-pos (position-ball-with-player player)
t (:time state)
new-ball (assoc ball :shot-start-time t :pos new-pos)]
(assoc state :ball new-ball))
:release-shot (let [player (get-in state [:players p])
pos (:pos player)
dir (:direction player)
t (:time state)
shot-start-time (:shot-start-time ball)
ke (* (- t shot-start-time) 100)
vmag (.sqrt js/Math (* ke 2))
vel (map #(* % vmag) dir)
new-pos (position-ball-with-player player)]
(assoc state :ball {:state :moving
:player nil
:velocity vel
:ke ke
:pos new-pos
:shot-start-time nil})))
(case (:state ball)
:moving (let [ke (:ke ball)]
(if (> ke 1)
(let [vmag (.sqrt js/Math (* ke 2))
vel (:velocity ball)
new-vel (map #(* % vmag) (normalize vel))
dt (* 0.001 (:frame-time state))
pos (:pos ball)
new-position (mapv + pos (map #(* dt %) new-vel))]
(assoc state :ball {:state :moving
:pos new-position
:velocity new-vel
:ke (- ke (* 1 vmag vmag dt))
:player nil
:shot-start-time nil}))
(assoc state :ball {:state :still
:pos (:pos ball)
:velocity [0 0]
:ke 0
:player nil
:shot-start-time nil})))
:still state)))
(defn reset-position [state i]
(let [player (get-in state [:players i])
pos (get-in gamedata/players [i :pos])
dir (get-in gamedata/players [i :direction])
reset (assoc player :pos pos :acceleration [0 0] :velocity [0 0] :direction dir :goal {:status :idle})
new-state (assoc-in state [:players i] reset)]
new-state))
(defn random-position [state i]
(let [player (get-in state [:players i])
[min-x min-y] [(:player-radius gamedata/settings) (:player-radius gamedata/settings)]
[max-x max-y] (map #(- % (:player-radius gamedata/settings))
(:pitch-size gamedata/settings))
new-pos [(+ min-x (int (* max-x (.random js/Math))))
(+ min-y (int (* max-y (.random js/Math))))]
new-player (assoc player :pos new-pos :acceleration [0 0] :velocity [0 0] :goal {:status :idle})
new-state (assoc-in state [:players i] new-player)]
new-state))
(defn point-in-player? [[x y] player]
"Determine whether the point (x,y) is part of a player's body."
(let [player-radius (:player-radius gamedata/settings)
ab [(* 2 player-radius) 0]
bc [0 (* 2 player-radius)]
[x-player y-player] (:pos player)
pa [(- x-player player-radius) (- y-player player-radius)]
pb [(+ x-player player-radius) (- y-player player-radius)]
am (map - [x y] pa)
bm (map - [x y] pb)]
(and (<= 0 (dot-product ab am))
(<= (dot-product ab am) (dot-product ab ab))
(<= 0 (dot-product bc bm))
(<= (dot-product bc bm) (dot-product bc bc)))))
(defn point-in-players? [[x y] players]
"Given a vector of players, determine whether the point (x,y)
is part of a player's body."
(loop [i 0]
(if-let [player (get players i)]
(if (point-in-player? [x y] player)
i
(recur (inc i))))))
(defn player-player-collisions [{players :players :as state}]
(let [r (:player-radius gamedata/settings)
ps (mapv #(select-keys % [:pos :index]) players)
positions (for [p ps :let [i (:index p)]]
[p (mapv :pos (filter #(not= (:index %) i) ps))])]
(loop [ps positions new-players []]
(if-let [x (first ps)]
(let [collisions (map #(circles-overlap? (get (first x) :pos) r % r) (last x))]
(let [index (get (first x) :index)
player (get players index)]
(if (some identity collisions)
(recur (rest ps) (conj new-players (assoc player :goal {:status :idle}
:pos (or (get player :prev-pos)
(get player :pos)))))
(recur (rest ps) (conj new-players player)))))
(assoc state :players new-players)))))
(defn player-ball-collisions [{players :players ball :ball :as state}]
(let [ball-pos (get ball :pos)
ball-radius (get gamedata/settings :ball-radius)
player-radius (get gamedata/settings :player-radius)]
(loop [i 0 collisions []]
(if-let [p (get players i)]
(if (circles-overlap? (get p :pos) player-radius ball-pos ball-radius)
(recur (inc i) (conj collisions (get p :index)))
(recur (inc i) collisions))
(case (count collisions)
0 state
1 (let [index (first collisions)
player (get-in state [:players index])
pos-player (:pos player)
vector-player-ball (map - ball-pos pos-player)
norm-vector-player-ball (normalize vector-player-ball)
dir (:direction player)
angle (angle dir norm-vector-player-ball)]
(if (< angle (get gamedata/settings :max-angle-pickup-ball))
(assoc state :ball {:state :with-player
:player index
:ke 0 ;; kinetic energy
:velocity nil
:pos (position-ball-with-player player)
:shot-start-time nil})
;; ball bounces on player, calculate new velocity
;; based on method described in book
;; "Physics for javascript games, animation, and simulations"
;; (PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI)
(let [v-ball (get ball :velocity)
v-player (get player :velocity)
normal-velo-ball (project v-ball vector-player-ball)
normal-velo-player (project v-player vector-player-ball)
tangent-velo-ball (subtract v-ball normal-velo-ball)
L (- (+ ball-radius player-radius) (magnitude vector-player-ball))
vrel (magnitude (subtract normal-velo-ball normal-velo-player))
ball-pos-impact (add-scaled ball-pos normal-velo-ball (/ (* -1 L) vrel))
u1 (projection normal-velo-ball vector-player-ball)
u2 (projection normal-velo-player vector-player-ball)
v1 (+ (* -1 u1) (* 2 u2)) ;assuming the weight of the ball is much smaller then the player
normal-velo-1 (para vector-player-ball v1)
new-v-ball (add normal-velo-1 tangent-velo-ball)]
(assoc state :ball {:state :moving
:player nil
:ke (* (get ball :ke) ;; lose kinetic energy
(get gamedata/settings :factor-ke-loss-on-collision))
:velocity new-v-ball
:pos ball-pos-impact
:shot-start-time nil}))))
2 (do
(println 2)
state)
state)))))
(defn check-ball [{ball :ball :as state}]
(let [[x y] (get ball :pos)]
(if (or (js/isNaN x) (js/isNaN y))
(do
(println state)
(assoc-in state [:ball :pos] [10 10]))
state)))
|
[
{
"context": "stroke hover-stroke})})))\n\n(def school-colors\n {\"Peruskoulut\"\n {:name \"Peruskoulut\" :color \"#C17B0D\"}\n \"Pe",
"end": 12907,
"score": 0.7839919328689575,
"start": 12896,
"tag": "NAME",
"value": "Peruskoulut"
},
{
"context": ")\n\n(def school-colors\n {\"Peruskoulut\"\n {:name \"Peruskoulut\" :color \"#C17B0D\"}\n \"Peruskouluasteen erityisko",
"end": 12931,
"score": 0.9958053827285767,
"start": 12920,
"tag": "NAME",
"value": "Peruskoulut"
},
{
"context": "\"}\n \"Peruskouluasteen erityiskoulut\"\n {:name \"Peruskouluasteen erityiskoulut\" :color \"#C2923E\"}\n \"Lukiot\"\n {:name \"Lukio",
"end": 13026,
"score": 0.7284058928489685,
"start": 12998,
"tag": "NAME",
"value": "Peruskouluasteen erityiskoul"
},
{
"context": "kouluasteen erityiskoulut\" :color \"#C2923E\"}\n \"Lukiot\"\n {:name \"Lukiot\" :color \"#4A69C2\"}\n \"Perus- ",
"end": 13058,
"score": 0.8246338963508606,
"start": 13053,
"tag": "NAME",
"value": "ukiot"
},
{
"context": "skoulut\" :color \"#C2923E\"}\n \"Lukiot\"\n {:name \"Lukiot\" :color \"#4A69C2\"}\n \"Perus- ja lukioasteen koul",
"end": 13077,
"score": 0.9820793271064758,
"start": 13071,
"tag": "NAME",
"value": "Lukiot"
},
{
"context": "\"Lukiot\"\n {:name \"Lukiot\" :color \"#4A69C2\"}\n \"Perus- ja lukioasteen koulut\"\n {:name \"Perus- ja lu",
"end": 13104,
"score": 0.5135404467582703,
"start": 13101,
"tag": "NAME",
"value": "Per"
},
{
"context": "C2\"}\n \"Perus- ja lukioasteen koulut\"\n {:name \"Perus- ja lukioasteen koulut\" :color \"#0D3BC1\"}\n \"Var",
"end": 13147,
"score": 0.8703435659408569,
"start": 13142,
"tag": "NAME",
"value": "Perus"
},
{
"context": "kioasteen koulut\"\n {:name \"Perus- ja lukioasteen koulut\" :color \"#0D3BC1\"}\n \"Varhaiskasvatusyksikkö\"\n",
"end": 13168,
"score": 0.8491523861885071,
"start": 13164,
"tag": "NAME",
"value": "koul"
},
{
"context": "kioasteen koulut\" :color \"#0D3BC1\"}\n \"Varhaiskasvatusyksikkö\"\n {:name \"Varhaiskasvatusyksikkö\" :c",
"end": 13205,
"score": 0.5384266972541809,
"start": 13204,
"tag": "NAME",
"value": "v"
},
{
"context": "een koulut\" :color \"#0D3BC1\"}\n \"Varhaiskasvatusyksikkö\"\n {:name \"Varhaiskasvatusyksikkö\" :color \"#",
"end": 13212,
"score": 0.5995771884918213,
"start": 13210,
"tag": "NAME",
"value": "ks"
},
{
"context": "\"#0D3BC1\"}\n \"Varhaiskasvatusyksikkö\"\n {:name \"Varhaiskasvatusyksikkö\" :color \"#ff40ff\"}})\n\n(defn school-style [f resol",
"end": 13251,
"score": 0.9920601844787598,
"start": 13229,
"tag": "NAME",
"value": "Varhaiskasvatusyksikkö"
}
] | webapp/src/cljs/lipas/ui/map/styles.cljs | lipas-liikuntapaikat/lipas | 49 | (ns lipas.ui.map.styles
(:require
["ol" :as ol]
[goog.color :as gcolor]
[goog.color.alpha :as gcolora]
[lipas.ui.mui :as mui]
[lipas.ui.svg :as svg]
[lipas.data.styles :as styles]))
(defn ->marker-style [opts]
(ol/style.Style.
#js{:image
(ol/style.Icon.
#js{:src (str "data:image/svg+xml;charset=utf-8,"
(-> opts
svg/->marker-str
js/encodeURIComponent))
:anchor #js[0.5 0.85]
:offset #js[0 0]})}))
(defn ->school-style [opts]
(ol/style.Style.
#js{:image
(ol/style.Icon.
#js{:src (str "data:image/svg+xml;charset=utf-8,"
(-> opts
svg/->school-str
js/encodeURIComponent))
:anchor #js[0.0 0.0]
:offset #js[0 0]})}))
(def blue-marker-style (->marker-style {}))
(def red-marker-style (->marker-style {:color mui/secondary}))
(def default-stroke (ol/style.Stroke. #js{:color "#3399CC" :width 3}))
(def default-fill (ol/style.Fill. #js{:color "rgba(255,255,0,0.4)"}))
(def hover-stroke (ol/style.Stroke. #js{:color "rgba(255,0,0,0.4)" :width 3.5}))
(def hover-fill (ol/style.Fill. #js{:color "rgba(255,0,0,0.4)"}))
;; Draw circles to all LineString and Polygon vertices
(def vertices-style
(ol/style.Style.
#js{:image
(ol/style.Circle.
#js{:radius 5
:stroke (ol/style.Stroke.
#js{:color mui/primary})
:fill (ol/style.Fill.
#js{:color mui/secondary2})})
:geometry
(fn [f]
(let [geom-type (-> f .getGeometry .getType)
coords (case geom-type
"Polygon" (-> f
.getGeometry
.getCoordinates
js->clj
(as-> $ (mapcat identity $))
clj->js)
"LineString" (-> f .getGeometry .getCoordinates)
nil)]
(when coords
(ol/geom.MultiPoint. coords))))}))
(def edit-style
(ol/style.Style.
#js{:stroke
(ol/style.Stroke.
#js{:width 3 :color "blue"})
:fill default-fill
:image
(ol/style.Circle.
#js{:radius 7
:fill (ol/style.Fill. #js{:color "rgba(255,255,0,0.85)"})
:stroke default-stroke})}))
(def invalid-style
(ol/style.Style.
#js{:stroke
(ol/style.Stroke.
#js{:width 3
:color "red"})
:fill default-fill
:image
(ol/style.Circle.
#js{:radius 5
:fill default-fill
:stroke default-stroke})}))
(def default-style
(ol/style.Style.
#js{:stroke default-stroke
:fill default-fill
:image
(ol/style.Circle.
#js{:radius 5
:fill default-fill
:stroke default-stroke})}))
(def hover-style
(ol/style.Style.
#js{:stroke hover-stroke
:fill default-fill
:image
(ol/style.Circle.
#js{:radius 7
:fill default-fill
:stroke hover-stroke})}))
(def editing-hover-style
(ol/style.Style.
#js{:stroke hover-stroke
:fill (ol/style.Fill. #js{:color "rgba(255,255,0,0.2)"})
:image
(ol/style.Circle.
#js{:radius 7
:fill default-fill
:stroke hover-stroke})}))
(def hover-styles #js[hover-style blue-marker-style])
(defn ->rgba [hex alpha]
(when (and hex alpha)
(let [rgb (gcolor/hexToRgb hex)
rgba (doto rgb (.push alpha))]
(gcolora/rgbaArrayToRgbaStyle rgba))))
(defn ->symbol-style
[m & {hover? :hover selected? :selected planned? :planned planning? :planning}]
(let [fill-alpha (case (:shape m)
"polygon" (if hover? 0.3 0.2)
0.85)
fill-color (-> m :fill :color (->rgba fill-alpha))
fill (ol/style.Fill. #js{:color fill-color})
stroke-alpha (case (:shape m)
"polygon" 0.6
0.9)
stroke-width (-> m :stroke :width)
stroke-hover-width (* 2 stroke-width)
stroke-color (-> m :stroke :color (->rgba stroke-alpha))
stroke-black (ol/style.Stroke. #js{:color "#00000" :width 1})
stroke-planned (ol/style.Stroke.
#js{:color "#3b3b3b"
:lineDash #js[2 20]
; :lineDashOffset 1
:width (if (#{"polygon" "linestring"} (:shape m))
10
5)})
stroke-planning (ol/style.Stroke.
#js{:color "#ee00ee"
:lineDash #js[2 20]
; :lineDashOffset 1
:width (if (#{"polygon" "linestring"} (:shape m))
10
5)})
stroke (ol/style.Stroke.
#js{:color stroke-color
:lineDash (when (or selected? hover?)
#js[2 8])
:width (if (or selected? hover?)
stroke-hover-width
stroke-width)})
on-top? (or selected? hover?)
style (ol/style.Style.
#js{:stroke stroke
:fill fill
:zIndex (condp = (:shape m)
"polygon" (if on-top? 100 99)
"linestring" (if on-top? 200 199)
(if on-top? 300 299))
:image
(when-not (#{"polygon" "linestring"} (:shape m))
(ol/style.Circle.
#js{:radius (cond
hover? 8
planning? 7
planned? 7
:else 7)
:fill fill
:stroke
(cond
planning? (ol/style.Stroke.
#js{:color "#ee00ee"
:width 3
:lineDash #js [2 5]})
planned? (ol/style.Stroke.
#js{:color "black"
:width 3
:lineDash #js [2 5]})
hover? hover-stroke
:else stroke-black)}))})
planned-stroke (ol/style.Style.
#js{:stroke stroke-planned})
planning-stroke (ol/style.Style.
#js{:stroke stroke-planning})]
(if (and selected? (:shape m))
#js[style blue-marker-style]
(cond
planning? #js[style planning-stroke]
planned? #js[style planned-stroke]
:else #js[style]))))
(def styleset styles/adapted-temp-symbols)
(def symbols
(reduce (fn [m [k v]] (assoc m k (->symbol-style v))) {} styleset))
(def hover-symbols
(reduce (fn [m [k v]] (assoc m k (->symbol-style v :hover true))) {} styleset))
(def selected-symbols
(reduce (fn [m [k v]] (assoc m k (->symbol-style v :selected true))) {} styleset))
(def planned-symbols
(reduce (fn [m [k v]] (assoc m k (->symbol-style v :planned true))) {} styleset))
(def planning-symbols
(reduce (fn [m [k v]] (assoc m k (->symbol-style v :planning true))) {} styleset))
(defn shift-likely-overlapping!
[type-code style resolution f]
(when (#{4402 4440} type-code)
(let [delta (* resolution 4)
copy (-> f .getGeometry .clone)]
(doto style
(.setGeometry (doto copy
(.translate delta delta)))))))
(defn feature-style [f resolution]
(let [type-code (.get f "type-code")
status (.get f "status")
style (condp = status
"planning" (get planning-symbols type-code)
"planned" (get planned-symbols type-code)
(get symbols type-code))]
(shift-likely-overlapping! type-code (first style) resolution f)
style))
(defn feature-style-hover [f resolution]
(let [type-code (.get f "type-code")
style (get hover-symbols type-code)]
(shift-likely-overlapping! type-code (first style) resolution f)
style))
(defn feature-style-selected [f resolution]
(let [type-code (.get f "type-code")
style (get selected-symbols type-code)]
(shift-likely-overlapping! type-code (first style) resolution f)
style))
;; Color scheme from Tilastokeskus
;; http://www.stat.fi/org/avoindata/paikkatietoaineistot/vaestoruutuaineisto_1km.html
(def population-colors
["rgba(255,237,169,0.5)"
"rgba(255,206,123,0.5)"
"rgba(247,149,72,0.5)"
"rgba(243,112,67,0.5)"
"rgba(237,26,59,0.5)"
"rgba(139,66,102,0.5)"])
(defn make-population-styles
([] (make-population-styles false "LawnGreen"))
([hover? stroke-color]
(->> population-colors
(map-indexed
(fn [idx color]
[idx (ol/style.Style.
#js{:stroke (if hover?
(ol/style.Stroke. #js{:color stroke-color :width 5})
(ol/style.Stroke. #js{:color "black" :width 2}))
:fill (ol/style.Fill. #js{:color color})})]))
(into {}))))
(def population-styles
(make-population-styles))
(def population-hover-styles
(make-population-styles :hover "LawnGreen"))
(def population-zone1
(make-population-styles :hover "#008000"))
(def population-zone2
(make-population-styles :hover "#2db92d"))
(def population-zone3
(make-population-styles :hover "#73e600"))
(defn population-style
[f _resolution]
(let [n (.get f "vaesto")]
(condp > n
5 (population-styles 0)
20 (population-styles 1)
50 (population-styles 2)
500 (population-styles 3)
5000 (population-styles 4)
(population-styles 5))))
(defn population-hover-style
[f _resolution]
(let [n (.get f "vaesto")]
(condp > n
5 (population-hover-styles 0)
20 (population-hover-styles 1)
50 (population-hover-styles 2)
500 (population-hover-styles 3)
5000 (population-hover-styles 4)
(population-styles 5))))
(defn population-zone1-fn
[f _resolution]
(let [n (.get f "vaesto")]
(condp > n
5 (population-zone1 0)
20 (population-zone1 1)
50 (population-zone1 2)
500 (population-zone1 3)
5000 (population-zone1 4)
(population-zone1 5))))
(defn population-zone2-fn
[f _resolution]
(let [n (.get f "vaesto")]
(condp > n
5 (population-zone2 0)
20 (population-zone2 1)
50 (population-zone2 2)
500 (population-zone2 3)
5000 (population-zone2 4)
(population-zone2 5))))
(defn population-zone3-fn
[f _resolution]
(let [n (.get f "vaesto")]
(condp > n
5 (population-zone3 0)
20 (population-zone3 1)
50 (population-zone3 2)
500 (population-zone3 3)
5000 (population-zone3 4)
(population-zone3 5))))
(defn population-style2
[f _resolution]
(let [n (.get f "vaesto")
color (.get f "color")]
(ol/style.Style.
#js{:stroke
(ol/style.Stroke.
#js{:width 3 :color color})
:fill (ol/style.Fill. #js{:color color})
:image
(ol/style.Circle.
#js{:radius (min 7 (* 0.01 (js/Math.abs n)))
:fill (ol/style.Fill. #js{:color color})
:stroke (ol/style.Stroke. #js{:color color :width 3})})})))
(defn population-hover-style2
[f _resolution]
(let [n (.get f "vaesto")]
(ol/style.Style.
#js{:stroke
(ol/style.Stroke.
#js{:width 3 :color "blue"})
:fill default-fill
:image
(ol/style.Circle.
#js{:radius (min 10 (* 0.1 (js/Math.abs n)))
:fill (ol/style.Fill. #js{:color "rgba(255,255,0,0.85)"})
:stroke hover-stroke})})))
(def school-colors
{"Peruskoulut"
{:name "Peruskoulut" :color "#C17B0D"}
"Peruskouluasteen erityiskoulut"
{:name "Peruskouluasteen erityiskoulut" :color "#C2923E"}
"Lukiot"
{:name "Lukiot" :color "#4A69C2"}
"Perus- ja lukioasteen koulut"
{:name "Perus- ja lukioasteen koulut" :color "#0D3BC1"}
"Varhaiskasvatusyksikkö"
{:name "Varhaiskasvatusyksikkö" :color "#ff40ff"}})
(defn school-style [f resolution]
(let [color (:color (get school-colors (.get f "type")))]
(->school-style {:color color :width 24 :height 24})))
(defn school-hover-style [f resolution]
(let [color (:color (get school-colors (.get f "type")))]
(->school-style {:color color :width 24 :height 24 :hover? true})))
| 119760 | (ns lipas.ui.map.styles
(:require
["ol" :as ol]
[goog.color :as gcolor]
[goog.color.alpha :as gcolora]
[lipas.ui.mui :as mui]
[lipas.ui.svg :as svg]
[lipas.data.styles :as styles]))
(defn ->marker-style [opts]
(ol/style.Style.
#js{:image
(ol/style.Icon.
#js{:src (str "data:image/svg+xml;charset=utf-8,"
(-> opts
svg/->marker-str
js/encodeURIComponent))
:anchor #js[0.5 0.85]
:offset #js[0 0]})}))
(defn ->school-style [opts]
(ol/style.Style.
#js{:image
(ol/style.Icon.
#js{:src (str "data:image/svg+xml;charset=utf-8,"
(-> opts
svg/->school-str
js/encodeURIComponent))
:anchor #js[0.0 0.0]
:offset #js[0 0]})}))
(def blue-marker-style (->marker-style {}))
(def red-marker-style (->marker-style {:color mui/secondary}))
(def default-stroke (ol/style.Stroke. #js{:color "#3399CC" :width 3}))
(def default-fill (ol/style.Fill. #js{:color "rgba(255,255,0,0.4)"}))
(def hover-stroke (ol/style.Stroke. #js{:color "rgba(255,0,0,0.4)" :width 3.5}))
(def hover-fill (ol/style.Fill. #js{:color "rgba(255,0,0,0.4)"}))
;; Draw circles to all LineString and Polygon vertices
(def vertices-style
(ol/style.Style.
#js{:image
(ol/style.Circle.
#js{:radius 5
:stroke (ol/style.Stroke.
#js{:color mui/primary})
:fill (ol/style.Fill.
#js{:color mui/secondary2})})
:geometry
(fn [f]
(let [geom-type (-> f .getGeometry .getType)
coords (case geom-type
"Polygon" (-> f
.getGeometry
.getCoordinates
js->clj
(as-> $ (mapcat identity $))
clj->js)
"LineString" (-> f .getGeometry .getCoordinates)
nil)]
(when coords
(ol/geom.MultiPoint. coords))))}))
(def edit-style
(ol/style.Style.
#js{:stroke
(ol/style.Stroke.
#js{:width 3 :color "blue"})
:fill default-fill
:image
(ol/style.Circle.
#js{:radius 7
:fill (ol/style.Fill. #js{:color "rgba(255,255,0,0.85)"})
:stroke default-stroke})}))
(def invalid-style
(ol/style.Style.
#js{:stroke
(ol/style.Stroke.
#js{:width 3
:color "red"})
:fill default-fill
:image
(ol/style.Circle.
#js{:radius 5
:fill default-fill
:stroke default-stroke})}))
(def default-style
(ol/style.Style.
#js{:stroke default-stroke
:fill default-fill
:image
(ol/style.Circle.
#js{:radius 5
:fill default-fill
:stroke default-stroke})}))
(def hover-style
(ol/style.Style.
#js{:stroke hover-stroke
:fill default-fill
:image
(ol/style.Circle.
#js{:radius 7
:fill default-fill
:stroke hover-stroke})}))
(def editing-hover-style
(ol/style.Style.
#js{:stroke hover-stroke
:fill (ol/style.Fill. #js{:color "rgba(255,255,0,0.2)"})
:image
(ol/style.Circle.
#js{:radius 7
:fill default-fill
:stroke hover-stroke})}))
(def hover-styles #js[hover-style blue-marker-style])
(defn ->rgba [hex alpha]
(when (and hex alpha)
(let [rgb (gcolor/hexToRgb hex)
rgba (doto rgb (.push alpha))]
(gcolora/rgbaArrayToRgbaStyle rgba))))
(defn ->symbol-style
[m & {hover? :hover selected? :selected planned? :planned planning? :planning}]
(let [fill-alpha (case (:shape m)
"polygon" (if hover? 0.3 0.2)
0.85)
fill-color (-> m :fill :color (->rgba fill-alpha))
fill (ol/style.Fill. #js{:color fill-color})
stroke-alpha (case (:shape m)
"polygon" 0.6
0.9)
stroke-width (-> m :stroke :width)
stroke-hover-width (* 2 stroke-width)
stroke-color (-> m :stroke :color (->rgba stroke-alpha))
stroke-black (ol/style.Stroke. #js{:color "#00000" :width 1})
stroke-planned (ol/style.Stroke.
#js{:color "#3b3b3b"
:lineDash #js[2 20]
; :lineDashOffset 1
:width (if (#{"polygon" "linestring"} (:shape m))
10
5)})
stroke-planning (ol/style.Stroke.
#js{:color "#ee00ee"
:lineDash #js[2 20]
; :lineDashOffset 1
:width (if (#{"polygon" "linestring"} (:shape m))
10
5)})
stroke (ol/style.Stroke.
#js{:color stroke-color
:lineDash (when (or selected? hover?)
#js[2 8])
:width (if (or selected? hover?)
stroke-hover-width
stroke-width)})
on-top? (or selected? hover?)
style (ol/style.Style.
#js{:stroke stroke
:fill fill
:zIndex (condp = (:shape m)
"polygon" (if on-top? 100 99)
"linestring" (if on-top? 200 199)
(if on-top? 300 299))
:image
(when-not (#{"polygon" "linestring"} (:shape m))
(ol/style.Circle.
#js{:radius (cond
hover? 8
planning? 7
planned? 7
:else 7)
:fill fill
:stroke
(cond
planning? (ol/style.Stroke.
#js{:color "#ee00ee"
:width 3
:lineDash #js [2 5]})
planned? (ol/style.Stroke.
#js{:color "black"
:width 3
:lineDash #js [2 5]})
hover? hover-stroke
:else stroke-black)}))})
planned-stroke (ol/style.Style.
#js{:stroke stroke-planned})
planning-stroke (ol/style.Style.
#js{:stroke stroke-planning})]
(if (and selected? (:shape m))
#js[style blue-marker-style]
(cond
planning? #js[style planning-stroke]
planned? #js[style planned-stroke]
:else #js[style]))))
(def styleset styles/adapted-temp-symbols)
(def symbols
(reduce (fn [m [k v]] (assoc m k (->symbol-style v))) {} styleset))
(def hover-symbols
(reduce (fn [m [k v]] (assoc m k (->symbol-style v :hover true))) {} styleset))
(def selected-symbols
(reduce (fn [m [k v]] (assoc m k (->symbol-style v :selected true))) {} styleset))
(def planned-symbols
(reduce (fn [m [k v]] (assoc m k (->symbol-style v :planned true))) {} styleset))
(def planning-symbols
(reduce (fn [m [k v]] (assoc m k (->symbol-style v :planning true))) {} styleset))
(defn shift-likely-overlapping!
[type-code style resolution f]
(when (#{4402 4440} type-code)
(let [delta (* resolution 4)
copy (-> f .getGeometry .clone)]
(doto style
(.setGeometry (doto copy
(.translate delta delta)))))))
(defn feature-style [f resolution]
(let [type-code (.get f "type-code")
status (.get f "status")
style (condp = status
"planning" (get planning-symbols type-code)
"planned" (get planned-symbols type-code)
(get symbols type-code))]
(shift-likely-overlapping! type-code (first style) resolution f)
style))
(defn feature-style-hover [f resolution]
(let [type-code (.get f "type-code")
style (get hover-symbols type-code)]
(shift-likely-overlapping! type-code (first style) resolution f)
style))
(defn feature-style-selected [f resolution]
(let [type-code (.get f "type-code")
style (get selected-symbols type-code)]
(shift-likely-overlapping! type-code (first style) resolution f)
style))
;; Color scheme from Tilastokeskus
;; http://www.stat.fi/org/avoindata/paikkatietoaineistot/vaestoruutuaineisto_1km.html
(def population-colors
["rgba(255,237,169,0.5)"
"rgba(255,206,123,0.5)"
"rgba(247,149,72,0.5)"
"rgba(243,112,67,0.5)"
"rgba(237,26,59,0.5)"
"rgba(139,66,102,0.5)"])
(defn make-population-styles
([] (make-population-styles false "LawnGreen"))
([hover? stroke-color]
(->> population-colors
(map-indexed
(fn [idx color]
[idx (ol/style.Style.
#js{:stroke (if hover?
(ol/style.Stroke. #js{:color stroke-color :width 5})
(ol/style.Stroke. #js{:color "black" :width 2}))
:fill (ol/style.Fill. #js{:color color})})]))
(into {}))))
(def population-styles
(make-population-styles))
(def population-hover-styles
(make-population-styles :hover "LawnGreen"))
(def population-zone1
(make-population-styles :hover "#008000"))
(def population-zone2
(make-population-styles :hover "#2db92d"))
(def population-zone3
(make-population-styles :hover "#73e600"))
(defn population-style
[f _resolution]
(let [n (.get f "vaesto")]
(condp > n
5 (population-styles 0)
20 (population-styles 1)
50 (population-styles 2)
500 (population-styles 3)
5000 (population-styles 4)
(population-styles 5))))
(defn population-hover-style
[f _resolution]
(let [n (.get f "vaesto")]
(condp > n
5 (population-hover-styles 0)
20 (population-hover-styles 1)
50 (population-hover-styles 2)
500 (population-hover-styles 3)
5000 (population-hover-styles 4)
(population-styles 5))))
(defn population-zone1-fn
[f _resolution]
(let [n (.get f "vaesto")]
(condp > n
5 (population-zone1 0)
20 (population-zone1 1)
50 (population-zone1 2)
500 (population-zone1 3)
5000 (population-zone1 4)
(population-zone1 5))))
(defn population-zone2-fn
[f _resolution]
(let [n (.get f "vaesto")]
(condp > n
5 (population-zone2 0)
20 (population-zone2 1)
50 (population-zone2 2)
500 (population-zone2 3)
5000 (population-zone2 4)
(population-zone2 5))))
(defn population-zone3-fn
[f _resolution]
(let [n (.get f "vaesto")]
(condp > n
5 (population-zone3 0)
20 (population-zone3 1)
50 (population-zone3 2)
500 (population-zone3 3)
5000 (population-zone3 4)
(population-zone3 5))))
(defn population-style2
[f _resolution]
(let [n (.get f "vaesto")
color (.get f "color")]
(ol/style.Style.
#js{:stroke
(ol/style.Stroke.
#js{:width 3 :color color})
:fill (ol/style.Fill. #js{:color color})
:image
(ol/style.Circle.
#js{:radius (min 7 (* 0.01 (js/Math.abs n)))
:fill (ol/style.Fill. #js{:color color})
:stroke (ol/style.Stroke. #js{:color color :width 3})})})))
(defn population-hover-style2
[f _resolution]
(let [n (.get f "vaesto")]
(ol/style.Style.
#js{:stroke
(ol/style.Stroke.
#js{:width 3 :color "blue"})
:fill default-fill
:image
(ol/style.Circle.
#js{:radius (min 10 (* 0.1 (js/Math.abs n)))
:fill (ol/style.Fill. #js{:color "rgba(255,255,0,0.85)"})
:stroke hover-stroke})})))
(def school-colors
{"<NAME>"
{:name "<NAME>" :color "#C17B0D"}
"Peruskouluasteen erityiskoulut"
{:name "<NAME>ut" :color "#C2923E"}
"L<NAME>"
{:name "<NAME>" :color "#4A69C2"}
"<NAME>us- ja lukioasteen koulut"
{:name "<NAME>- ja lukioasteen <NAME>ut" :color "#0D3BC1"}
"Varhaiskas<NAME>atusy<NAME>ikkö"
{:name "<NAME>" :color "#ff40ff"}})
(defn school-style [f resolution]
(let [color (:color (get school-colors (.get f "type")))]
(->school-style {:color color :width 24 :height 24})))
(defn school-hover-style [f resolution]
(let [color (:color (get school-colors (.get f "type")))]
(->school-style {:color color :width 24 :height 24 :hover? true})))
| true | (ns lipas.ui.map.styles
(:require
["ol" :as ol]
[goog.color :as gcolor]
[goog.color.alpha :as gcolora]
[lipas.ui.mui :as mui]
[lipas.ui.svg :as svg]
[lipas.data.styles :as styles]))
(defn ->marker-style [opts]
(ol/style.Style.
#js{:image
(ol/style.Icon.
#js{:src (str "data:image/svg+xml;charset=utf-8,"
(-> opts
svg/->marker-str
js/encodeURIComponent))
:anchor #js[0.5 0.85]
:offset #js[0 0]})}))
(defn ->school-style [opts]
(ol/style.Style.
#js{:image
(ol/style.Icon.
#js{:src (str "data:image/svg+xml;charset=utf-8,"
(-> opts
svg/->school-str
js/encodeURIComponent))
:anchor #js[0.0 0.0]
:offset #js[0 0]})}))
(def blue-marker-style (->marker-style {}))
(def red-marker-style (->marker-style {:color mui/secondary}))
(def default-stroke (ol/style.Stroke. #js{:color "#3399CC" :width 3}))
(def default-fill (ol/style.Fill. #js{:color "rgba(255,255,0,0.4)"}))
(def hover-stroke (ol/style.Stroke. #js{:color "rgba(255,0,0,0.4)" :width 3.5}))
(def hover-fill (ol/style.Fill. #js{:color "rgba(255,0,0,0.4)"}))
;; Draw circles to all LineString and Polygon vertices
(def vertices-style
(ol/style.Style.
#js{:image
(ol/style.Circle.
#js{:radius 5
:stroke (ol/style.Stroke.
#js{:color mui/primary})
:fill (ol/style.Fill.
#js{:color mui/secondary2})})
:geometry
(fn [f]
(let [geom-type (-> f .getGeometry .getType)
coords (case geom-type
"Polygon" (-> f
.getGeometry
.getCoordinates
js->clj
(as-> $ (mapcat identity $))
clj->js)
"LineString" (-> f .getGeometry .getCoordinates)
nil)]
(when coords
(ol/geom.MultiPoint. coords))))}))
(def edit-style
(ol/style.Style.
#js{:stroke
(ol/style.Stroke.
#js{:width 3 :color "blue"})
:fill default-fill
:image
(ol/style.Circle.
#js{:radius 7
:fill (ol/style.Fill. #js{:color "rgba(255,255,0,0.85)"})
:stroke default-stroke})}))
(def invalid-style
(ol/style.Style.
#js{:stroke
(ol/style.Stroke.
#js{:width 3
:color "red"})
:fill default-fill
:image
(ol/style.Circle.
#js{:radius 5
:fill default-fill
:stroke default-stroke})}))
(def default-style
(ol/style.Style.
#js{:stroke default-stroke
:fill default-fill
:image
(ol/style.Circle.
#js{:radius 5
:fill default-fill
:stroke default-stroke})}))
(def hover-style
(ol/style.Style.
#js{:stroke hover-stroke
:fill default-fill
:image
(ol/style.Circle.
#js{:radius 7
:fill default-fill
:stroke hover-stroke})}))
(def editing-hover-style
(ol/style.Style.
#js{:stroke hover-stroke
:fill (ol/style.Fill. #js{:color "rgba(255,255,0,0.2)"})
:image
(ol/style.Circle.
#js{:radius 7
:fill default-fill
:stroke hover-stroke})}))
(def hover-styles #js[hover-style blue-marker-style])
(defn ->rgba [hex alpha]
(when (and hex alpha)
(let [rgb (gcolor/hexToRgb hex)
rgba (doto rgb (.push alpha))]
(gcolora/rgbaArrayToRgbaStyle rgba))))
(defn ->symbol-style
[m & {hover? :hover selected? :selected planned? :planned planning? :planning}]
(let [fill-alpha (case (:shape m)
"polygon" (if hover? 0.3 0.2)
0.85)
fill-color (-> m :fill :color (->rgba fill-alpha))
fill (ol/style.Fill. #js{:color fill-color})
stroke-alpha (case (:shape m)
"polygon" 0.6
0.9)
stroke-width (-> m :stroke :width)
stroke-hover-width (* 2 stroke-width)
stroke-color (-> m :stroke :color (->rgba stroke-alpha))
stroke-black (ol/style.Stroke. #js{:color "#00000" :width 1})
stroke-planned (ol/style.Stroke.
#js{:color "#3b3b3b"
:lineDash #js[2 20]
; :lineDashOffset 1
:width (if (#{"polygon" "linestring"} (:shape m))
10
5)})
stroke-planning (ol/style.Stroke.
#js{:color "#ee00ee"
:lineDash #js[2 20]
; :lineDashOffset 1
:width (if (#{"polygon" "linestring"} (:shape m))
10
5)})
stroke (ol/style.Stroke.
#js{:color stroke-color
:lineDash (when (or selected? hover?)
#js[2 8])
:width (if (or selected? hover?)
stroke-hover-width
stroke-width)})
on-top? (or selected? hover?)
style (ol/style.Style.
#js{:stroke stroke
:fill fill
:zIndex (condp = (:shape m)
"polygon" (if on-top? 100 99)
"linestring" (if on-top? 200 199)
(if on-top? 300 299))
:image
(when-not (#{"polygon" "linestring"} (:shape m))
(ol/style.Circle.
#js{:radius (cond
hover? 8
planning? 7
planned? 7
:else 7)
:fill fill
:stroke
(cond
planning? (ol/style.Stroke.
#js{:color "#ee00ee"
:width 3
:lineDash #js [2 5]})
planned? (ol/style.Stroke.
#js{:color "black"
:width 3
:lineDash #js [2 5]})
hover? hover-stroke
:else stroke-black)}))})
planned-stroke (ol/style.Style.
#js{:stroke stroke-planned})
planning-stroke (ol/style.Style.
#js{:stroke stroke-planning})]
(if (and selected? (:shape m))
#js[style blue-marker-style]
(cond
planning? #js[style planning-stroke]
planned? #js[style planned-stroke]
:else #js[style]))))
(def styleset styles/adapted-temp-symbols)
(def symbols
(reduce (fn [m [k v]] (assoc m k (->symbol-style v))) {} styleset))
(def hover-symbols
(reduce (fn [m [k v]] (assoc m k (->symbol-style v :hover true))) {} styleset))
(def selected-symbols
(reduce (fn [m [k v]] (assoc m k (->symbol-style v :selected true))) {} styleset))
(def planned-symbols
(reduce (fn [m [k v]] (assoc m k (->symbol-style v :planned true))) {} styleset))
(def planning-symbols
(reduce (fn [m [k v]] (assoc m k (->symbol-style v :planning true))) {} styleset))
(defn shift-likely-overlapping!
[type-code style resolution f]
(when (#{4402 4440} type-code)
(let [delta (* resolution 4)
copy (-> f .getGeometry .clone)]
(doto style
(.setGeometry (doto copy
(.translate delta delta)))))))
(defn feature-style [f resolution]
(let [type-code (.get f "type-code")
status (.get f "status")
style (condp = status
"planning" (get planning-symbols type-code)
"planned" (get planned-symbols type-code)
(get symbols type-code))]
(shift-likely-overlapping! type-code (first style) resolution f)
style))
(defn feature-style-hover [f resolution]
(let [type-code (.get f "type-code")
style (get hover-symbols type-code)]
(shift-likely-overlapping! type-code (first style) resolution f)
style))
(defn feature-style-selected [f resolution]
(let [type-code (.get f "type-code")
style (get selected-symbols type-code)]
(shift-likely-overlapping! type-code (first style) resolution f)
style))
;; Color scheme from Tilastokeskus
;; http://www.stat.fi/org/avoindata/paikkatietoaineistot/vaestoruutuaineisto_1km.html
(def population-colors
["rgba(255,237,169,0.5)"
"rgba(255,206,123,0.5)"
"rgba(247,149,72,0.5)"
"rgba(243,112,67,0.5)"
"rgba(237,26,59,0.5)"
"rgba(139,66,102,0.5)"])
(defn make-population-styles
([] (make-population-styles false "LawnGreen"))
([hover? stroke-color]
(->> population-colors
(map-indexed
(fn [idx color]
[idx (ol/style.Style.
#js{:stroke (if hover?
(ol/style.Stroke. #js{:color stroke-color :width 5})
(ol/style.Stroke. #js{:color "black" :width 2}))
:fill (ol/style.Fill. #js{:color color})})]))
(into {}))))
(def population-styles
(make-population-styles))
(def population-hover-styles
(make-population-styles :hover "LawnGreen"))
(def population-zone1
(make-population-styles :hover "#008000"))
(def population-zone2
(make-population-styles :hover "#2db92d"))
(def population-zone3
(make-population-styles :hover "#73e600"))
(defn population-style
[f _resolution]
(let [n (.get f "vaesto")]
(condp > n
5 (population-styles 0)
20 (population-styles 1)
50 (population-styles 2)
500 (population-styles 3)
5000 (population-styles 4)
(population-styles 5))))
(defn population-hover-style
[f _resolution]
(let [n (.get f "vaesto")]
(condp > n
5 (population-hover-styles 0)
20 (population-hover-styles 1)
50 (population-hover-styles 2)
500 (population-hover-styles 3)
5000 (population-hover-styles 4)
(population-styles 5))))
(defn population-zone1-fn
[f _resolution]
(let [n (.get f "vaesto")]
(condp > n
5 (population-zone1 0)
20 (population-zone1 1)
50 (population-zone1 2)
500 (population-zone1 3)
5000 (population-zone1 4)
(population-zone1 5))))
(defn population-zone2-fn
[f _resolution]
(let [n (.get f "vaesto")]
(condp > n
5 (population-zone2 0)
20 (population-zone2 1)
50 (population-zone2 2)
500 (population-zone2 3)
5000 (population-zone2 4)
(population-zone2 5))))
(defn population-zone3-fn
[f _resolution]
(let [n (.get f "vaesto")]
(condp > n
5 (population-zone3 0)
20 (population-zone3 1)
50 (population-zone3 2)
500 (population-zone3 3)
5000 (population-zone3 4)
(population-zone3 5))))
(defn population-style2
[f _resolution]
(let [n (.get f "vaesto")
color (.get f "color")]
(ol/style.Style.
#js{:stroke
(ol/style.Stroke.
#js{:width 3 :color color})
:fill (ol/style.Fill. #js{:color color})
:image
(ol/style.Circle.
#js{:radius (min 7 (* 0.01 (js/Math.abs n)))
:fill (ol/style.Fill. #js{:color color})
:stroke (ol/style.Stroke. #js{:color color :width 3})})})))
(defn population-hover-style2
[f _resolution]
(let [n (.get f "vaesto")]
(ol/style.Style.
#js{:stroke
(ol/style.Stroke.
#js{:width 3 :color "blue"})
:fill default-fill
:image
(ol/style.Circle.
#js{:radius (min 10 (* 0.1 (js/Math.abs n)))
:fill (ol/style.Fill. #js{:color "rgba(255,255,0,0.85)"})
:stroke hover-stroke})})))
(def school-colors
{"PI:NAME:<NAME>END_PI"
{:name "PI:NAME:<NAME>END_PI" :color "#C17B0D"}
"Peruskouluasteen erityiskoulut"
{:name "PI:NAME:<NAME>END_PIut" :color "#C2923E"}
"LPI:NAME:<NAME>END_PI"
{:name "PI:NAME:<NAME>END_PI" :color "#4A69C2"}
"PI:NAME:<NAME>END_PIus- ja lukioasteen koulut"
{:name "PI:NAME:<NAME>END_PI- ja lukioasteen PI:NAME:<NAME>END_PIut" :color "#0D3BC1"}
"VarhaiskasPI:NAME:<NAME>END_PIatusyPI:NAME:<NAME>END_PIikkö"
{:name "PI:NAME:<NAME>END_PI" :color "#ff40ff"}})
(defn school-style [f resolution]
(let [color (:color (get school-colors (.get f "type")))]
(->school-style {:color color :width 24 :height 24})))
(defn school-hover-style [f resolution]
(let [color (:color (get school-colors (.get f "type")))]
(->school-style {:color color :width 24 :height 24 :hover? true})))
|
[
{
"context": ".clj:1:7266)\n:key1\n;;=> :key1\n(def person {:name \"John McCarthy\" :country \"USA\"})\n;;=> #'chapter01.primitives/per",
"end": 1729,
"score": 0.999717116355896,
"start": 1716,
"tag": "NAME",
"value": "John McCarthy"
}
] | Chapter 01 Code/chapter01/src/chapter01/primitives.clj | PacktPublishing/Clojure-Programming-Cookbook | 14 | (ns chapter01.primitives)
(+ 1 2)
;;=> 3
(+ 1 2 3)
;;=> 6
(+ 1.2 3.5)
;;=> 4.7
(- 3 2)
;;=> 1
(- 1 2 3)
;;=> -4
(- 1)
;;=> -1
(* 5 2)
;;=> 10
(* 1 2 3 4 5)
;;=> 120
(/ 10 5)
;;=> 2
(/ 10 3)
;;=> 10/3
(float (/ 10 3))
;;=> 3.3333333
(double (/ 10 3))
;;=> 3.333333333333333
(quot 10 3)
;;=> 3
(rem 10 3)
;;=> 1
(bigdec (/ 10 2))
;;=> 5M
(bigdec (/ 10 3))
;; ArithmeticException Non-terminating decimal expansion; no exact representable decimal result. ;; java.math.BigDecimal.divide (BigDecimal.java:1690)
(= (bigint 10) 10N)
;;=> true
"Hello world ! "
;;=> "Hello world ! "
(str "Hello " "world !" " Clojure")
;;=> "Hello world ! Clojure"
(.length "Hello world !")
;;=> 13
(clojure.string/blank? " ")
;;=> true
(clojure.string/trim " Hello ")
;;=> "Hello"
(clojure.string/upper-case "clojure")
;;=> "CLOJURE"
(clojure.string/capitalize "clojure")
;;=> "Clojure"
(clojure.string/lower-case "REPL")
;;=> "repl"
\a
;;=> \a
(int \a)
;;=> 97
(char 97)
;;=> \a
(seq "Hello world!")
;;=> (\H \e \l \l \o \space \w \o \r \l \d \!)
(str \C \l \o \j \u \r \e)
;;=> "Clojure"
true
;;=> true
false
;;=> false
(= 1 1)
;;=> true
(= 1 2)
;;=> false
(= "Hello" "Hello")
;;=> true
(= "Hello" "hello")
;;=> false
(not true)
;;=> false
(not false)
;;=> true
(not= 1 2)
;;=> true
(not true)
;;=> false
(true? (= 1 1))
;;=> true
(false? (= 1 1))
;;=> false
(if nil true false)
;;=> false
(seq [])
;;=> nil
(get {:a 1 :b 2} :c)
;;=> nil
(def pi 3.14159265359)
;;=> #'chapter01.primitives/pi
pi
;;=> 3.14159265359
pi-not-bind
;;=> CompilerException java.lang.RuntimeException: Unable to resolve symbol:
;; pi-not-bind in this context, compiling:(/tmp/form-init1426260352520034213.clj:1:7266)
:key1
;;=> :key1
(def person {:name "John McCarthy" :country "USA"})
;;=> #'chapter01.primitives/person
(class 1)
;;=> java.lang.Long
(class 1.0)
;;=> java.lang.Double
(class (float 1.0))
;;=> java.lang.Float
(class 5.5M)
;;=> java.math.BigDecimal
(class 1N)
;;=> clojure.lang.BigInt
(class (/ 10 3))
;;=> clojure.lang.Ratio
(class "Hello world ! ")
;;=> java.lang.String
(class \a)
;;=> java.lang.Character
(class true)
;;=> java.lang.Boolean
(class false)
;;=> java.lang.Boolean
(class :key)
;;=> clojure.lang.Keyword
(class (quote a))
;;=> clojure.lang.Symbol
(class nil)
;;=> nil
0xff
;;=> 255
0400
;;=> 256
2r11111
;;=> 31
16rff
;;=> 255
8r11000
;;=> 4608
7r111
;;=>57
\u0031\u0032\u0061\u0062
;;=> \1
;;=> \2
;;=> \a
;;=> \b
+
;;=> #function[clojure.core/+]
(quote pi-not-bind)
;;=> pi-not-bind
(require '[clojure.math.numeric-tower :as math])
(math/expt 2 10)
;;=> 1024
(math/sqrt 10)
;;=> 3.1622776601683795
| 89889 | (ns chapter01.primitives)
(+ 1 2)
;;=> 3
(+ 1 2 3)
;;=> 6
(+ 1.2 3.5)
;;=> 4.7
(- 3 2)
;;=> 1
(- 1 2 3)
;;=> -4
(- 1)
;;=> -1
(* 5 2)
;;=> 10
(* 1 2 3 4 5)
;;=> 120
(/ 10 5)
;;=> 2
(/ 10 3)
;;=> 10/3
(float (/ 10 3))
;;=> 3.3333333
(double (/ 10 3))
;;=> 3.333333333333333
(quot 10 3)
;;=> 3
(rem 10 3)
;;=> 1
(bigdec (/ 10 2))
;;=> 5M
(bigdec (/ 10 3))
;; ArithmeticException Non-terminating decimal expansion; no exact representable decimal result. ;; java.math.BigDecimal.divide (BigDecimal.java:1690)
(= (bigint 10) 10N)
;;=> true
"Hello world ! "
;;=> "Hello world ! "
(str "Hello " "world !" " Clojure")
;;=> "Hello world ! Clojure"
(.length "Hello world !")
;;=> 13
(clojure.string/blank? " ")
;;=> true
(clojure.string/trim " Hello ")
;;=> "Hello"
(clojure.string/upper-case "clojure")
;;=> "CLOJURE"
(clojure.string/capitalize "clojure")
;;=> "Clojure"
(clojure.string/lower-case "REPL")
;;=> "repl"
\a
;;=> \a
(int \a)
;;=> 97
(char 97)
;;=> \a
(seq "Hello world!")
;;=> (\H \e \l \l \o \space \w \o \r \l \d \!)
(str \C \l \o \j \u \r \e)
;;=> "Clojure"
true
;;=> true
false
;;=> false
(= 1 1)
;;=> true
(= 1 2)
;;=> false
(= "Hello" "Hello")
;;=> true
(= "Hello" "hello")
;;=> false
(not true)
;;=> false
(not false)
;;=> true
(not= 1 2)
;;=> true
(not true)
;;=> false
(true? (= 1 1))
;;=> true
(false? (= 1 1))
;;=> false
(if nil true false)
;;=> false
(seq [])
;;=> nil
(get {:a 1 :b 2} :c)
;;=> nil
(def pi 3.14159265359)
;;=> #'chapter01.primitives/pi
pi
;;=> 3.14159265359
pi-not-bind
;;=> CompilerException java.lang.RuntimeException: Unable to resolve symbol:
;; pi-not-bind in this context, compiling:(/tmp/form-init1426260352520034213.clj:1:7266)
:key1
;;=> :key1
(def person {:name "<NAME>" :country "USA"})
;;=> #'chapter01.primitives/person
(class 1)
;;=> java.lang.Long
(class 1.0)
;;=> java.lang.Double
(class (float 1.0))
;;=> java.lang.Float
(class 5.5M)
;;=> java.math.BigDecimal
(class 1N)
;;=> clojure.lang.BigInt
(class (/ 10 3))
;;=> clojure.lang.Ratio
(class "Hello world ! ")
;;=> java.lang.String
(class \a)
;;=> java.lang.Character
(class true)
;;=> java.lang.Boolean
(class false)
;;=> java.lang.Boolean
(class :key)
;;=> clojure.lang.Keyword
(class (quote a))
;;=> clojure.lang.Symbol
(class nil)
;;=> nil
0xff
;;=> 255
0400
;;=> 256
2r11111
;;=> 31
16rff
;;=> 255
8r11000
;;=> 4608
7r111
;;=>57
\u0031\u0032\u0061\u0062
;;=> \1
;;=> \2
;;=> \a
;;=> \b
+
;;=> #function[clojure.core/+]
(quote pi-not-bind)
;;=> pi-not-bind
(require '[clojure.math.numeric-tower :as math])
(math/expt 2 10)
;;=> 1024
(math/sqrt 10)
;;=> 3.1622776601683795
| true | (ns chapter01.primitives)
(+ 1 2)
;;=> 3
(+ 1 2 3)
;;=> 6
(+ 1.2 3.5)
;;=> 4.7
(- 3 2)
;;=> 1
(- 1 2 3)
;;=> -4
(- 1)
;;=> -1
(* 5 2)
;;=> 10
(* 1 2 3 4 5)
;;=> 120
(/ 10 5)
;;=> 2
(/ 10 3)
;;=> 10/3
(float (/ 10 3))
;;=> 3.3333333
(double (/ 10 3))
;;=> 3.333333333333333
(quot 10 3)
;;=> 3
(rem 10 3)
;;=> 1
(bigdec (/ 10 2))
;;=> 5M
(bigdec (/ 10 3))
;; ArithmeticException Non-terminating decimal expansion; no exact representable decimal result. ;; java.math.BigDecimal.divide (BigDecimal.java:1690)
(= (bigint 10) 10N)
;;=> true
"Hello world ! "
;;=> "Hello world ! "
(str "Hello " "world !" " Clojure")
;;=> "Hello world ! Clojure"
(.length "Hello world !")
;;=> 13
(clojure.string/blank? " ")
;;=> true
(clojure.string/trim " Hello ")
;;=> "Hello"
(clojure.string/upper-case "clojure")
;;=> "CLOJURE"
(clojure.string/capitalize "clojure")
;;=> "Clojure"
(clojure.string/lower-case "REPL")
;;=> "repl"
\a
;;=> \a
(int \a)
;;=> 97
(char 97)
;;=> \a
(seq "Hello world!")
;;=> (\H \e \l \l \o \space \w \o \r \l \d \!)
(str \C \l \o \j \u \r \e)
;;=> "Clojure"
true
;;=> true
false
;;=> false
(= 1 1)
;;=> true
(= 1 2)
;;=> false
(= "Hello" "Hello")
;;=> true
(= "Hello" "hello")
;;=> false
(not true)
;;=> false
(not false)
;;=> true
(not= 1 2)
;;=> true
(not true)
;;=> false
(true? (= 1 1))
;;=> true
(false? (= 1 1))
;;=> false
(if nil true false)
;;=> false
(seq [])
;;=> nil
(get {:a 1 :b 2} :c)
;;=> nil
(def pi 3.14159265359)
;;=> #'chapter01.primitives/pi
pi
;;=> 3.14159265359
pi-not-bind
;;=> CompilerException java.lang.RuntimeException: Unable to resolve symbol:
;; pi-not-bind in this context, compiling:(/tmp/form-init1426260352520034213.clj:1:7266)
:key1
;;=> :key1
(def person {:name "PI:NAME:<NAME>END_PI" :country "USA"})
;;=> #'chapter01.primitives/person
(class 1)
;;=> java.lang.Long
(class 1.0)
;;=> java.lang.Double
(class (float 1.0))
;;=> java.lang.Float
(class 5.5M)
;;=> java.math.BigDecimal
(class 1N)
;;=> clojure.lang.BigInt
(class (/ 10 3))
;;=> clojure.lang.Ratio
(class "Hello world ! ")
;;=> java.lang.String
(class \a)
;;=> java.lang.Character
(class true)
;;=> java.lang.Boolean
(class false)
;;=> java.lang.Boolean
(class :key)
;;=> clojure.lang.Keyword
(class (quote a))
;;=> clojure.lang.Symbol
(class nil)
;;=> nil
0xff
;;=> 255
0400
;;=> 256
2r11111
;;=> 31
16rff
;;=> 255
8r11000
;;=> 4608
7r111
;;=>57
\u0031\u0032\u0061\u0062
;;=> \1
;;=> \2
;;=> \a
;;=> \b
+
;;=> #function[clojure.core/+]
(quote pi-not-bind)
;;=> pi-not-bind
(require '[clojure.math.numeric-tower :as math])
(math/expt 2 10)
;;=> 1024
(math/sqrt 10)
;;=> 3.1622776601683795
|
[
{
"context": " (atom\n {:people\n [{:type :student :first \"Ben\" :last \"Bitdiddle\" :email \"benb@mit.edu\"}\n {",
"end": 441,
"score": 0.9998046159744263,
"start": 438,
"tag": "NAME",
"value": "Ben"
},
{
"context": ":people\n [{:type :student :first \"Ben\" :last \"Bitdiddle\" :email \"benb@mit.edu\"}\n {:type :student :fi",
"end": 459,
"score": 0.9973325133323669,
"start": 450,
"tag": "NAME",
"value": "Bitdiddle"
},
{
"context": "e :student :first \"Ben\" :last \"Bitdiddle\" :email \"benb@mit.edu\"}\n {:type :student :first \"Alyssa\" :middle-i",
"end": 481,
"score": 0.999925434589386,
"start": 469,
"tag": "EMAIL",
"value": "benb@mit.edu"
},
{
"context": "ail \"benb@mit.edu\"}\n {:type :student :first \"Alyssa\" :middle-initial \"P\" :last \"Hacker\"\n :email",
"end": 520,
"score": 0.9996724128723145,
"start": 514,
"tag": "NAME",
"value": "Alyssa"
},
{
"context": " {:type :student :first \"Alyssa\" :middle-initial \"P\" :last \"Hacker\"\n :email \"aphacker@mit.edu\"}",
"end": 540,
"score": 0.9946993589401245,
"start": 539,
"tag": "NAME",
"value": "P"
},
{
"context": "tudent :first \"Alyssa\" :middle-initial \"P\" :last \"Hacker\"\n :email \"aphacker@mit.edu\"}\n {:type :",
"end": 555,
"score": 0.9251565933227539,
"start": 549,
"tag": "NAME",
"value": "Hacker"
},
{
"context": ":middle-initial \"P\" :last \"Hacker\"\n :email \"aphacker@mit.edu\"}\n {:type :professor :first \"Gerald\" :middle",
"end": 588,
"score": 0.9999215006828308,
"start": 572,
"tag": "EMAIL",
"value": "aphacker@mit.edu"
},
{
"context": "phacker@mit.edu\"}\n {:type :professor :first \"Gerald\" :middle \"Jay\" :last \"Sussman\"\n :email \"met",
"end": 629,
"score": 0.9996660351753235,
"start": 623,
"tag": "NAME",
"value": "Gerald"
},
{
"context": "\n {:type :professor :first \"Gerald\" :middle \"Jay\" :last \"Sussman\"\n :email \"metacirc@mit.edu\"",
"end": 643,
"score": 0.9958124756813049,
"start": 640,
"tag": "NAME",
"value": "Jay"
},
{
"context": "e :professor :first \"Gerald\" :middle \"Jay\" :last \"Sussman\"\n :email \"metacirc@mit.edu\" :classes [:6001",
"end": 659,
"score": 0.9992353320121765,
"start": 652,
"tag": "NAME",
"value": "Sussman"
},
{
"context": "ald\" :middle \"Jay\" :last \"Sussman\"\n :email \"metacirc@mit.edu\" :classes [:6001 :6946]}\n {:type :student :f",
"end": 692,
"score": 0.9999221563339233,
"start": 676,
"tag": "EMAIL",
"value": "metacirc@mit.edu"
},
{
"context": "sses [:6001 :6946]}\n {:type :student :first \"Eva\" :middle \"Lu\" :last \"Ator\" :email \"eval@mit.edu\"}",
"end": 751,
"score": 0.999639630317688,
"start": 748,
"tag": "NAME",
"value": "Eva"
},
{
"context": "946]}\n {:type :student :first \"Eva\" :middle \"Lu\" :last \"Ator\" :email \"eval@mit.edu\"}\n {:type",
"end": 764,
"score": 0.9964454770088196,
"start": 762,
"tag": "NAME",
"value": "Lu"
},
{
"context": " {:type :student :first \"Eva\" :middle \"Lu\" :last \"Ator\" :email \"eval@mit.edu\"}\n {:type :student :fi",
"end": 777,
"score": 0.9992465972900391,
"start": 773,
"tag": "NAME",
"value": "Ator"
},
{
"context": "nt :first \"Eva\" :middle \"Lu\" :last \"Ator\" :email \"eval@mit.edu\"}\n {:type :student :first \"Louis\" :last \"Rea",
"end": 799,
"score": 0.9999168515205383,
"start": 787,
"tag": "EMAIL",
"value": "eval@mit.edu"
},
{
"context": "ail \"eval@mit.edu\"}\n {:type :student :first \"Louis\" :last \"Reasoner\" :email \"prolog@mit.edu\"}\n ",
"end": 837,
"score": 0.9995830059051514,
"start": 832,
"tag": "NAME",
"value": "Louis"
},
{
"context": "edu\"}\n {:type :student :first \"Louis\" :last \"Reasoner\" :email \"prolog@mit.edu\"}\n {:type :professor",
"end": 854,
"score": 0.9740262031555176,
"start": 846,
"tag": "NAME",
"value": "Reasoner"
},
{
"context": " :student :first \"Louis\" :last \"Reasoner\" :email \"prolog@mit.edu\"}\n {:type :professor :first \"Hal\" :last \"Abe",
"end": 878,
"score": 0.9999160170555115,
"start": 864,
"tag": "EMAIL",
"value": "prolog@mit.edu"
},
{
"context": "\"prolog@mit.edu\"}\n {:type :professor :first \"Hal\" :last \"Abelson\" :email \"evalapply@mit.edu\"\n ",
"end": 916,
"score": 0.9997814297676086,
"start": 913,
"tag": "NAME",
"value": "Hal"
},
{
"context": "edu\"}\n {:type :professor :first \"Hal\" :last \"Abelson\" :email \"evalapply@mit.edu\"\n :classes [:600",
"end": 932,
"score": 0.9995691776275635,
"start": 925,
"tag": "NAME",
"value": "Abelson"
},
{
"context": "e :professor :first \"Hal\" :last \"Abelson\" :email \"evalapply@mit.edu\"\n :classes [:6001]}]\n :classes\n {:6",
"end": 959,
"score": 0.9999210238456726,
"start": 942,
"tag": "EMAIL",
"value": "evalapply@mit.edu"
}
] | src/om_basic/core.cljs | imaximix/om-tutorials | 0 | (ns ^:figwheel-always om-basic.core
(:require [om.core :as om :include-macros true]
[om.dom :as dom :include-macros true]
[clojure.string :as string]))
(enable-console-print!)
(extend-type string
ICloneable
(-clone [s] (js/String. s)))
(extend-type js/String
ICloneable
(-clone [s] (js/String. s))
om/IValue
(-value [s] (str s)))
(def app-state
(atom
{:people
[{:type :student :first "Ben" :last "Bitdiddle" :email "benb@mit.edu"}
{:type :student :first "Alyssa" :middle-initial "P" :last "Hacker"
:email "aphacker@mit.edu"}
{:type :professor :first "Gerald" :middle "Jay" :last "Sussman"
:email "metacirc@mit.edu" :classes [:6001 :6946]}
{:type :student :first "Eva" :middle "Lu" :last "Ator" :email "eval@mit.edu"}
{:type :student :first "Louis" :last "Reasoner" :email "prolog@mit.edu"}
{:type :professor :first "Hal" :last "Abelson" :email "evalapply@mit.edu"
:classes [:6001]}]
:classes
{:6001 "The Structure and Interpretation of Computer Programs"
:6946 "The Structure and Interpretation of Classical Mechanics"
:1806 "Linear Algebra"}}))
(defn display [show]
(if show
#js {}
#js {:display "none"}))
(defn handle-change [e text owner]
(om/transact! text (fn [_] (.. e -target -value))))
(defn commit-change [text owner]
(om/set-state! owner :editing false))
(defn middle-name [{:keys [middle middle-initial]}]
(cond
middle (str " " middle)
middle-initial (str " " middle-initial ".")))
(defn display-name [{:keys [first last] :as contact}]
(str last ", " first (middle-name contact)))
(defn student-view [student owner]
(reify
om/IRender
(render [_]
(dom/li nil (display-name student)))))
(defn editable [text owner]
(reify
om/IInitState
(init-state [_]
{:editing false})
om/IRenderState
(render-state [_ {:keys [editing]}]
(dom/li nil
(dom/span #js {:style (display (not editing))} (om/value text))
(dom/input
#js {:style (display editing)
:value (om/value text)
:onChange #(handle-change % text owner)
:onKeyDown #(when (= (.-key %) "Enter")
(commit-change text owner))
:onBlur (fn [e] (commit-change text owner))})
(dom/button
#js {:style (display (not editing))
:onClick #(om/set-state! owner :editing true)}
"Edit")))))
(defn professor-view [professor owner]
(reify
om/IRender
(render [_]
(dom/li nil
(dom/div nil (display-name professor))
(dom/label nil "Classes")
(apply dom/ul nil
(om/build-all editable (:classes professor)))))))
(defmulti entry-view (fn [person _] (:type person)))
(defmethod entry-view :student
[person owner] (student-view person owner))
(defmethod entry-view :professor
[person owner] (professor-view person owner))
(defn people
[data]
(->> data
:people
(mapv (fn [x]
(if (:classes x)
(update-in x [:classes]
(fn [cs] (mapv (:classes data) cs)))
x)))))
(defn registry-view [data owner]
(reify
om/IRender
(render [_]
(dom/div nil
(dom/h2 nil "Registry")
(apply dom/ul nil
(om/build-all entry-view (people data)))))))
(defn classes-view [data owner]
(reify
om/IRender
(render [_]
(dom/div #js {:id "classes"}
(dom/h2 nil "Classes")
(apply dom/ul nil
(om/build-all editable (vals (:classes data))))))))
(om/root registry-view app-state
{:target (. js/document (getElementById "registry"))})
(om/root classes-view app-state
{:target (. js/document (getElementById "classes"))})
(defn on-js-reload []
;; optionally touch your app-state to force rerendering depending on
;; your application
;; (swap! app-state update-in [:__figwheel_counter] inc)
)
| 14343 | (ns ^:figwheel-always om-basic.core
(:require [om.core :as om :include-macros true]
[om.dom :as dom :include-macros true]
[clojure.string :as string]))
(enable-console-print!)
(extend-type string
ICloneable
(-clone [s] (js/String. s)))
(extend-type js/String
ICloneable
(-clone [s] (js/String. s))
om/IValue
(-value [s] (str s)))
(def app-state
(atom
{:people
[{:type :student :first "<NAME>" :last "<NAME>" :email "<EMAIL>"}
{:type :student :first "<NAME>" :middle-initial "<NAME>" :last "<NAME>"
:email "<EMAIL>"}
{:type :professor :first "<NAME>" :middle "<NAME>" :last "<NAME>"
:email "<EMAIL>" :classes [:6001 :6946]}
{:type :student :first "<NAME>" :middle "<NAME>" :last "<NAME>" :email "<EMAIL>"}
{:type :student :first "<NAME>" :last "<NAME>" :email "<EMAIL>"}
{:type :professor :first "<NAME>" :last "<NAME>" :email "<EMAIL>"
:classes [:6001]}]
:classes
{:6001 "The Structure and Interpretation of Computer Programs"
:6946 "The Structure and Interpretation of Classical Mechanics"
:1806 "Linear Algebra"}}))
(defn display [show]
(if show
#js {}
#js {:display "none"}))
(defn handle-change [e text owner]
(om/transact! text (fn [_] (.. e -target -value))))
(defn commit-change [text owner]
(om/set-state! owner :editing false))
(defn middle-name [{:keys [middle middle-initial]}]
(cond
middle (str " " middle)
middle-initial (str " " middle-initial ".")))
(defn display-name [{:keys [first last] :as contact}]
(str last ", " first (middle-name contact)))
(defn student-view [student owner]
(reify
om/IRender
(render [_]
(dom/li nil (display-name student)))))
(defn editable [text owner]
(reify
om/IInitState
(init-state [_]
{:editing false})
om/IRenderState
(render-state [_ {:keys [editing]}]
(dom/li nil
(dom/span #js {:style (display (not editing))} (om/value text))
(dom/input
#js {:style (display editing)
:value (om/value text)
:onChange #(handle-change % text owner)
:onKeyDown #(when (= (.-key %) "Enter")
(commit-change text owner))
:onBlur (fn [e] (commit-change text owner))})
(dom/button
#js {:style (display (not editing))
:onClick #(om/set-state! owner :editing true)}
"Edit")))))
(defn professor-view [professor owner]
(reify
om/IRender
(render [_]
(dom/li nil
(dom/div nil (display-name professor))
(dom/label nil "Classes")
(apply dom/ul nil
(om/build-all editable (:classes professor)))))))
(defmulti entry-view (fn [person _] (:type person)))
(defmethod entry-view :student
[person owner] (student-view person owner))
(defmethod entry-view :professor
[person owner] (professor-view person owner))
(defn people
[data]
(->> data
:people
(mapv (fn [x]
(if (:classes x)
(update-in x [:classes]
(fn [cs] (mapv (:classes data) cs)))
x)))))
(defn registry-view [data owner]
(reify
om/IRender
(render [_]
(dom/div nil
(dom/h2 nil "Registry")
(apply dom/ul nil
(om/build-all entry-view (people data)))))))
(defn classes-view [data owner]
(reify
om/IRender
(render [_]
(dom/div #js {:id "classes"}
(dom/h2 nil "Classes")
(apply dom/ul nil
(om/build-all editable (vals (:classes data))))))))
(om/root registry-view app-state
{:target (. js/document (getElementById "registry"))})
(om/root classes-view app-state
{:target (. js/document (getElementById "classes"))})
(defn on-js-reload []
;; optionally touch your app-state to force rerendering depending on
;; your application
;; (swap! app-state update-in [:__figwheel_counter] inc)
)
| true | (ns ^:figwheel-always om-basic.core
(:require [om.core :as om :include-macros true]
[om.dom :as dom :include-macros true]
[clojure.string :as string]))
(enable-console-print!)
(extend-type string
ICloneable
(-clone [s] (js/String. s)))
(extend-type js/String
ICloneable
(-clone [s] (js/String. s))
om/IValue
(-value [s] (str s)))
(def app-state
(atom
{:people
[{:type :student :first "PI:NAME:<NAME>END_PI" :last "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"}
{:type :student :first "PI:NAME:<NAME>END_PI" :middle-initial "PI:NAME:<NAME>END_PI" :last "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"}
{:type :professor :first "PI:NAME:<NAME>END_PI" :middle "PI:NAME:<NAME>END_PI" :last "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI" :classes [:6001 :6946]}
{:type :student :first "PI:NAME:<NAME>END_PI" :middle "PI:NAME:<NAME>END_PI" :last "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"}
{:type :student :first "PI:NAME:<NAME>END_PI" :last "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"}
{:type :professor :first "PI:NAME:<NAME>END_PI" :last "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"
:classes [:6001]}]
:classes
{:6001 "The Structure and Interpretation of Computer Programs"
:6946 "The Structure and Interpretation of Classical Mechanics"
:1806 "Linear Algebra"}}))
(defn display [show]
(if show
#js {}
#js {:display "none"}))
(defn handle-change [e text owner]
(om/transact! text (fn [_] (.. e -target -value))))
(defn commit-change [text owner]
(om/set-state! owner :editing false))
(defn middle-name [{:keys [middle middle-initial]}]
(cond
middle (str " " middle)
middle-initial (str " " middle-initial ".")))
(defn display-name [{:keys [first last] :as contact}]
(str last ", " first (middle-name contact)))
(defn student-view [student owner]
(reify
om/IRender
(render [_]
(dom/li nil (display-name student)))))
(defn editable [text owner]
(reify
om/IInitState
(init-state [_]
{:editing false})
om/IRenderState
(render-state [_ {:keys [editing]}]
(dom/li nil
(dom/span #js {:style (display (not editing))} (om/value text))
(dom/input
#js {:style (display editing)
:value (om/value text)
:onChange #(handle-change % text owner)
:onKeyDown #(when (= (.-key %) "Enter")
(commit-change text owner))
:onBlur (fn [e] (commit-change text owner))})
(dom/button
#js {:style (display (not editing))
:onClick #(om/set-state! owner :editing true)}
"Edit")))))
(defn professor-view [professor owner]
(reify
om/IRender
(render [_]
(dom/li nil
(dom/div nil (display-name professor))
(dom/label nil "Classes")
(apply dom/ul nil
(om/build-all editable (:classes professor)))))))
(defmulti entry-view (fn [person _] (:type person)))
(defmethod entry-view :student
[person owner] (student-view person owner))
(defmethod entry-view :professor
[person owner] (professor-view person owner))
(defn people
[data]
(->> data
:people
(mapv (fn [x]
(if (:classes x)
(update-in x [:classes]
(fn [cs] (mapv (:classes data) cs)))
x)))))
(defn registry-view [data owner]
(reify
om/IRender
(render [_]
(dom/div nil
(dom/h2 nil "Registry")
(apply dom/ul nil
(om/build-all entry-view (people data)))))))
(defn classes-view [data owner]
(reify
om/IRender
(render [_]
(dom/div #js {:id "classes"}
(dom/h2 nil "Classes")
(apply dom/ul nil
(om/build-all editable (vals (:classes data))))))))
(om/root registry-view app-state
{:target (. js/document (getElementById "registry"))})
(om/root classes-view app-state
{:target (. js/document (getElementById "classes"))})
(defn on-js-reload []
;; optionally touch your app-state to force rerendering depending on
;; your application
;; (swap! app-state update-in [:__figwheel_counter] inc)
)
|
[
{
"context": ";;Copyright (c) 2017 Rafik Naccache <rafik@fekr.tech>\n;;Distributed under the MIT Lic",
"end": 35,
"score": 0.9998638033866882,
"start": 21,
"tag": "NAME",
"value": "Rafik Naccache"
},
{
"context": ";;Copyright (c) 2017 Rafik Naccache <rafik@fekr.tech>\n;;Distributed under the MIT License\n(ns postagga",
"end": 52,
"score": 0.9999323487281799,
"start": 37,
"tag": "EMAIL",
"value": "rafik@fekr.tech"
}
] | test/postagga/tagger_test.cljc | jffrydsr/postagga | 93 | ;;Copyright (c) 2017 Rafik Naccache <rafik@fekr.tech>
;;Distributed under the MIT License
(ns postagga.tagger-test
(:require [clojure.test :refer :all]
[postagga.tagger :refer :all]))
(def sample-model
{:states #{"P" "V" "N" "D"},
:transitions {["P" "V"] 0.3333333, ["P" "P"] 0.3333333, ["P" "N"] 0.3333334, ["V" "D"] 0.5, ["V" "P"] 0.5, ["D" "N"] 1.0 ["N" "N"] 1.0},
:emissions
{["P" "Je"] 0.3333333,
["P" "Te"] 0.3333333,
["P" "Ma"] 0.3333334,
["V" "Mange"] 0.3333333,
["V" "Tue"] 0.3333333,
["V" "Montre"] 0.3333334,
["N" "Pomme"] 0.3333333,
["N" "Mouche"] 0.3333333,
["N" "Montre"] 0.3333334,
["D" "Une"] 1.0},
:init-probs {"P" 1.0}})
(deftest viterbi-test
(testing "viterbi")
(is (= ["P" "V" "D" "N"] (viterbi sample-model ["Je" "Mange" "Une" "Pomme"])))
(is (= ["P" "P" "V" "P" "N"] (viterbi sample-model ["Je" "Te" "Montre" "Ma" "Montre"]))))
(def sample-db-trie {"h" {:nb 1, :next {"e" {:nb 1, :next {"l" {:nb 1, :next {"l" {:nb 1, :next {"o" {:nb 1, :next {"a" {:nb 1 :end true}}}}}}}}}}}})
(deftest patch-w-entity-test
(testing "patch-w-entity")
(is (= [] (patch-w-entity 0.5 [] {} [] nil)))
(is (= ["N"] (patch-w-entity 0.0 ["hello"] {} ["N"] "NPP")))
(is (= ["NPP"] (patch-w-entity 0.5 ["hello"] sample-db-trie ["N"] "NPP")))
(is (= ["N"] (patch-w-entity 1.0 ["hello"] sample-db-trie ["N"] "NPP")))
(is (= ["N" "NPP"] (patch-w-entity 0.5 ["world" "hello"] sample-db-trie ["N" "N"] "NPP"))))
| 11951 | ;;Copyright (c) 2017 <NAME> <<EMAIL>>
;;Distributed under the MIT License
(ns postagga.tagger-test
(:require [clojure.test :refer :all]
[postagga.tagger :refer :all]))
(def sample-model
{:states #{"P" "V" "N" "D"},
:transitions {["P" "V"] 0.3333333, ["P" "P"] 0.3333333, ["P" "N"] 0.3333334, ["V" "D"] 0.5, ["V" "P"] 0.5, ["D" "N"] 1.0 ["N" "N"] 1.0},
:emissions
{["P" "Je"] 0.3333333,
["P" "Te"] 0.3333333,
["P" "Ma"] 0.3333334,
["V" "Mange"] 0.3333333,
["V" "Tue"] 0.3333333,
["V" "Montre"] 0.3333334,
["N" "Pomme"] 0.3333333,
["N" "Mouche"] 0.3333333,
["N" "Montre"] 0.3333334,
["D" "Une"] 1.0},
:init-probs {"P" 1.0}})
(deftest viterbi-test
(testing "viterbi")
(is (= ["P" "V" "D" "N"] (viterbi sample-model ["Je" "Mange" "Une" "Pomme"])))
(is (= ["P" "P" "V" "P" "N"] (viterbi sample-model ["Je" "Te" "Montre" "Ma" "Montre"]))))
(def sample-db-trie {"h" {:nb 1, :next {"e" {:nb 1, :next {"l" {:nb 1, :next {"l" {:nb 1, :next {"o" {:nb 1, :next {"a" {:nb 1 :end true}}}}}}}}}}}})
(deftest patch-w-entity-test
(testing "patch-w-entity")
(is (= [] (patch-w-entity 0.5 [] {} [] nil)))
(is (= ["N"] (patch-w-entity 0.0 ["hello"] {} ["N"] "NPP")))
(is (= ["NPP"] (patch-w-entity 0.5 ["hello"] sample-db-trie ["N"] "NPP")))
(is (= ["N"] (patch-w-entity 1.0 ["hello"] sample-db-trie ["N"] "NPP")))
(is (= ["N" "NPP"] (patch-w-entity 0.5 ["world" "hello"] sample-db-trie ["N" "N"] "NPP"))))
| true | ;;Copyright (c) 2017 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;;Distributed under the MIT License
(ns postagga.tagger-test
(:require [clojure.test :refer :all]
[postagga.tagger :refer :all]))
(def sample-model
{:states #{"P" "V" "N" "D"},
:transitions {["P" "V"] 0.3333333, ["P" "P"] 0.3333333, ["P" "N"] 0.3333334, ["V" "D"] 0.5, ["V" "P"] 0.5, ["D" "N"] 1.0 ["N" "N"] 1.0},
:emissions
{["P" "Je"] 0.3333333,
["P" "Te"] 0.3333333,
["P" "Ma"] 0.3333334,
["V" "Mange"] 0.3333333,
["V" "Tue"] 0.3333333,
["V" "Montre"] 0.3333334,
["N" "Pomme"] 0.3333333,
["N" "Mouche"] 0.3333333,
["N" "Montre"] 0.3333334,
["D" "Une"] 1.0},
:init-probs {"P" 1.0}})
(deftest viterbi-test
(testing "viterbi")
(is (= ["P" "V" "D" "N"] (viterbi sample-model ["Je" "Mange" "Une" "Pomme"])))
(is (= ["P" "P" "V" "P" "N"] (viterbi sample-model ["Je" "Te" "Montre" "Ma" "Montre"]))))
(def sample-db-trie {"h" {:nb 1, :next {"e" {:nb 1, :next {"l" {:nb 1, :next {"l" {:nb 1, :next {"o" {:nb 1, :next {"a" {:nb 1 :end true}}}}}}}}}}}})
(deftest patch-w-entity-test
(testing "patch-w-entity")
(is (= [] (patch-w-entity 0.5 [] {} [] nil)))
(is (= ["N"] (patch-w-entity 0.0 ["hello"] {} ["N"] "NPP")))
(is (= ["NPP"] (patch-w-entity 0.5 ["hello"] sample-db-trie ["N"] "NPP")))
(is (= ["N"] (patch-w-entity 1.0 ["hello"] sample-db-trie ["N"] "NPP")))
(is (= ["N" "NPP"] (patch-w-entity 0.5 ["world" "hello"] sample-db-trie ["N" "N"] "NPP"))))
|
[
{
"context": "c)))))\n\n(def foaf-data\n [[[:box/id \"zk\"] \"name\" \"Zack\" false]\n [[:box/id \"cindy\"] \"name\" \"Cindy\" fals",
"end": 2164,
"score": 0.9996160864830017,
"start": 2160,
"tag": "NAME",
"value": "Zack"
},
{
"context": "name\" \"Zack\" false]\n [[:box/id \"cindy\"] \"name\" \"Cindy\" false]\n [[:box/id \"zk\"] \"friend\" [:box/id \"cin",
"end": 2208,
"score": 0.9992416501045227,
"start": 2203,
"tag": "NAME",
"value": "Cindy"
},
{
"context": "\n(def movies-db\n [[[:box/id -100] \"person/name\" \"James Cameron\" nil nil]\n [[:box/id -100] \"person/born\" -48530",
"end": 3345,
"score": 0.9998868107795715,
"start": 3332,
"tag": "NAME",
"value": "James Cameron"
},
{
"context": "800000 nil nil]\n [[:box/id -101] \"person/name\" \"Arnold Schwarzenegger\" nil nil]\n [[:box/id -101] \"person/born\" -70770",
"end": 3467,
"score": 0.9998865127563477,
"start": 3446,
"tag": "NAME",
"value": "Arnold Schwarzenegger"
},
{
"context": "400000 nil nil]\n [[:box/id -102] \"person/name\" \"Linda Hamilton\" nil nil]\n [[:box/id -102] \"person/born\" -41860",
"end": 3582,
"score": 0.9998828768730164,
"start": 3568,
"tag": "NAME",
"value": "Linda Hamilton"
},
{
"context": "000000 nil nil]\n [[:box/id -103] \"person/name\" \"Michael Biehn\" nil nil]\n [[:box/id -103] \"person/born\" -42353",
"end": 3696,
"score": 0.9998772144317627,
"start": 3683,
"tag": "NAME",
"value": "Michael Biehn"
},
{
"context": "800000 nil nil]\n [[:box/id -104] \"person/name\" \"Ted Kotcheff\" nil nil]\n [[:box/id -104] \"person/born\" -12224",
"end": 3809,
"score": 0.9998809695243835,
"start": 3797,
"tag": "NAME",
"value": "Ted Kotcheff"
},
{
"context": "600000 nil nil]\n [[:box/id -105] \"person/name\" \"Sylvester Stallone\" nil nil]\n [[:box/id -105] \"person/born\" -74131",
"end": 3929,
"score": 0.9998841881752014,
"start": 3911,
"tag": "NAME",
"value": "Sylvester Stallone"
},
{
"context": "000000 nil nil]\n [[:box/id -106] \"person/name\" \"Richard Crenna\" nil nil]\n [[:box/id -106] \"person/born\" -13597",
"end": 4044,
"score": 0.9998663067817688,
"start": 4030,
"tag": "NAME",
"value": "Richard Crenna"
},
{
"context": "600000 nil nil]\n [[:box/id -107] \"person/name\" \"Brian Dennehy\" nil nil]\n [[:box/id -107] \"person/born\" -99351",
"end": 4216,
"score": 0.9998942613601685,
"start": 4203,
"tag": "NAME",
"value": "Brian Dennehy"
},
{
"context": "600000 nil nil]\n [[:box/id -108] \"person/name\" \"John McTiernan\" nil nil]\n [[:box/id -108] \"person/born\" -59901",
"end": 4331,
"score": 0.9998898506164551,
"start": 4317,
"tag": "NAME",
"value": "John McTiernan"
},
{
"context": "200000 nil nil]\n [[:box/id -109] \"person/name\" \"Elpidia Carrillo\" nil nil]\n [[:box/id -109] \"person/born\" -26438",
"end": 4448,
"score": 0.9998766779899597,
"start": 4432,
"tag": "NAME",
"value": "Elpidia Carrillo"
},
{
"context": "000000 nil nil]\n [[:box/id -110] \"person/name\" \"Carl Weathers\" nil nil]\n [[:box/id -110] \"person/born\" -69318",
"end": 4562,
"score": 0.9998480677604675,
"start": 4549,
"tag": "NAME",
"value": "Carl Weathers"
},
{
"context": "200000 nil nil]\n [[:box/id -111] \"person/name\" \"Richard Donner\" nil nil]\n [[:box/id -111] \"person/born\" -12525",
"end": 4677,
"score": 0.9998428821563721,
"start": 4663,
"tag": "NAME",
"value": "Richard Donner"
},
{
"context": "800000 nil nil]\n [[:box/id -112] \"person/name\" \"Mel Gibson\" nil nil]\n [[:box/id -112] \"person/born\" -44167",
"end": 4789,
"score": 0.999858021736145,
"start": 4779,
"tag": "NAME",
"value": "Mel Gibson"
},
{
"context": "800000 nil nil]\n [[:box/id -113] \"person/name\" \"Danny Glover\" nil nil]\n [[:box/id -113] \"person/born\" -73992",
"end": 4902,
"score": 0.9998620748519897,
"start": 4890,
"tag": "NAME",
"value": "Danny Glover"
},
{
"context": "600000 nil nil]\n [[:box/id -114] \"person/name\" \"Gary Busey\" nil nil]\n [[:box/id -114] \"person/born\" -80239",
"end": 5013,
"score": 0.9998506307601929,
"start": 5003,
"tag": "NAME",
"value": "Gary Busey"
},
{
"context": "800000 nil nil]\n [[:box/id -115] \"person/name\" \"Paul Verhoeven\" nil nil]\n [[:box/id -115] \"person/born\" -99273",
"end": 5128,
"score": 0.9998706579208374,
"start": 5114,
"tag": "NAME",
"value": "Paul Verhoeven"
},
{
"context": "000000 nil nil]\n [[:box/id -116] \"person/name\" \"Peter Weller\" nil nil]\n [[:box/id -116] \"person/born\" -71081",
"end": 5241,
"score": 0.9998663663864136,
"start": 5229,
"tag": "NAME",
"value": "Peter Weller"
},
{
"context": "800000 nil nil]\n [[:box/id -117] \"person/name\" \"Nancy Allen\" nil nil]\n [[:box/id -117] \"person/born\" -61611",
"end": 5353,
"score": 0.9998688697814941,
"start": 5342,
"tag": "NAME",
"value": "Nancy Allen"
},
{
"context": "400000 nil nil]\n [[:box/id -118] \"person/name\" \"Ronny Cox\" nil nil]\n [[:box/id -118] \"person/born\" -99230",
"end": 5463,
"score": 0.9998773336410522,
"start": 5454,
"tag": "NAME",
"value": "Ronny Cox"
},
{
"context": "000000 nil nil]\n [[:box/id -119] \"person/name\" \"Mark L. Lester\" nil nil]\n [[:box/id -119] \"person/born\" -72895",
"end": 5578,
"score": 0.99986732006073,
"start": 5564,
"tag": "NAME",
"value": "Mark L. Lester"
},
{
"context": "800000 nil nil]\n [[:box/id -120] \"person/name\" \"Rae Dawn Chong\" nil nil]\n [[:box/id -120] \"person/born\" -27898",
"end": 5693,
"score": 0.9998658299446106,
"start": 5679,
"tag": "NAME",
"value": "Rae Dawn Chong"
},
{
"context": "600000 nil nil]\n [[:box/id -121] \"person/name\" \"Alyssa Milano\" nil nil]\n [[:box/id -121] \"person/born\" 935712",
"end": 5807,
"score": 0.9998698234558105,
"start": 5794,
"tag": "NAME",
"value": "Alyssa Milano"
},
{
"context": "200000 nil nil]\n [[:box/id -122] \"person/name\" \"Bruce Willis\" nil nil]\n [[:box/id -122] \"person/born\" -46673",
"end": 5918,
"score": 0.9998766183853149,
"start": 5906,
"tag": "NAME",
"value": "Bruce Willis"
},
{
"context": "800000 nil nil]\n [[:box/id -123] \"person/name\" \"Alan Rickman\" nil nil]\n [[:box/id -123] \"person/born\" -75297",
"end": 6031,
"score": 0.9998470544815063,
"start": 6019,
"tag": "NAME",
"value": "Alan Rickman"
},
{
"context": "000000 nil nil]\n [[:box/id -124] \"person/name\" \"Alexander Godunov\" nil nil]\n [[:box/id -124] \"person/born\" -63408",
"end": 6149,
"score": 0.999843418598175,
"start": 6132,
"tag": "NAME",
"value": "Alexander Godunov"
},
{
"context": "200000 nil nil]\n [[:box/id -125] \"person/name\" \"Robert Patrick\" nil nil]\n [[:box/id -125] \"person/born\" -35208",
"end": 6320,
"score": 0.9998407363891602,
"start": 6306,
"tag": "NAME",
"value": "Robert Patrick"
},
{
"context": "000000 nil nil]\n [[:box/id -126] \"person/name\" \"Edward Furlong\" nil nil]\n [[:box/id -126] \"person/born\" 239328",
"end": 6435,
"score": 0.999859631061554,
"start": 6421,
"tag": "NAME",
"value": "Edward Furlong"
},
{
"context": "000000 nil nil]\n [[:box/id -127] \"person/name\" \"Jonathan Mostow\" nil nil]\n [[:box/id -127] \"person/born\" -25539",
"end": 6550,
"score": 0.9998437166213989,
"start": 6535,
"tag": "NAME",
"value": "Jonathan Mostow"
},
{
"context": "400000 nil nil]\n [[:box/id -128] \"person/name\" \"Nick Stahl\" nil nil]\n [[:box/id -128] \"person/born\" 313200",
"end": 6661,
"score": 0.9998452067375183,
"start": 6651,
"tag": "NAME",
"value": "Nick Stahl"
},
{
"context": "000000 nil nil]\n [[:box/id -129] \"person/name\" \"Claire Danes\" nil nil]\n [[:box/id -129] \"person/born\" 292723",
"end": 6773,
"score": 0.9998500347137451,
"start": 6761,
"tag": "NAME",
"value": "Claire Danes"
},
{
"context": "200000 nil nil]\n [[:box/id -130] \"person/name\" \"George P. Cosmatos\" nil nil]\n [[:box/id -130] \"person/born\" -91488",
"end": 6891,
"score": 0.9998592734336853,
"start": 6873,
"tag": "NAME",
"value": "George P. Cosmatos"
},
{
"context": "800000 nil nil]\n [[:box/id -131] \"person/name\" \"Charles Napier\" nil nil]\n [[:box/id -131] \"person/born\" -10641",
"end": 7063,
"score": 0.999841034412384,
"start": 7049,
"tag": "NAME",
"value": "Charles Napier"
},
{
"context": "800000 nil nil]\n [[:box/id -132] \"person/name\" \"Peter MacDonald\" nil nil]\n [[:box/id -133] \"person/name\" \"Marc ",
"end": 7237,
"score": 0.999867856502533,
"start": 7222,
"tag": "NAME",
"value": "Peter MacDonald"
},
{
"context": "onald\" nil nil]\n [[:box/id -133] \"person/name\" \"Marc de Jonge\" nil nil]\n [[:box/id -133] \"person/born\" -65871",
"end": 7295,
"score": 0.9998809099197388,
"start": 7282,
"tag": "NAME",
"value": "Marc de Jonge"
},
{
"context": "200000 nil nil]\n [[:box/id -134] \"person/name\" \"Stephen Hopkins\" nil nil]\n [[:box/id -135] \"person/name\" \"Ruben",
"end": 7467,
"score": 0.9998704791069031,
"start": 7452,
"tag": "NAME",
"value": "Stephen Hopkins"
},
{
"context": "pkins\" nil nil]\n [[:box/id -135] \"person/name\" \"Ruben Blades\" nil nil]\n [[:box/id -135] \"person/born\" -67728",
"end": 7524,
"score": 0.999862551689148,
"start": 7512,
"tag": "NAME",
"value": "Ruben Blades"
},
{
"context": "600000 nil nil]\n [[:box/id -136] \"person/name\" \"Joe Pesci\" nil nil]\n [[:box/id -136] \"person/born\" -84870",
"end": 7634,
"score": 0.9998477101325989,
"start": 7625,
"tag": "NAME",
"value": "Joe Pesci"
},
{
"context": "200000 nil nil]\n [[:box/id -137] \"person/name\" \"Ridley Scott\" nil nil]\n [[:box/id -137] \"person/born\" -10126",
"end": 7747,
"score": 0.9998568296432495,
"start": 7735,
"tag": "NAME",
"value": "Ridley Scott"
},
{
"context": "000000 nil nil]\n [[:box/id -138] \"person/name\" \"Tom Skerritt\" nil nil]\n [[:box/id -138] \"person/born\" -11472",
"end": 7861,
"score": 0.999859094619751,
"start": 7849,
"tag": "NAME",
"value": "Tom Skerritt"
},
{
"context": "200000 nil nil]\n [[:box/id -139] \"person/name\" \"Sigourney Weaver\" nil nil]\n [[:box/id -139] \"person/born\" -63849",
"end": 7979,
"score": 0.999872088432312,
"start": 7963,
"tag": "NAME",
"value": "Sigourney Weaver"
},
{
"context": "000000 nil nil]\n [[:box/id -140] \"person/name\" \"Veronica Cartwright\" nil nil]\n [[:box/id -140] \"person/born\" -65327",
"end": 8099,
"score": 0.9998496174812317,
"start": 8080,
"tag": "NAME",
"value": "Veronica Cartwright"
},
{
"context": "400000 nil nil]\n [[:box/id -141] \"person/name\" \"Carrie Henn\" nil nil]\n [[:box/id -142] \"person/name\" \"Georg",
"end": 8211,
"score": 0.9998529553413391,
"start": 8200,
"tag": "NAME",
"value": "Carrie Henn"
},
{
"context": " Henn\" nil nil]\n [[:box/id -142] \"person/name\" \"George Miller\" nil nil]\n [[:box/id -142] \"person/born\" -78364",
"end": 8269,
"score": 0.9998459815979004,
"start": 8256,
"tag": "NAME",
"value": "George Miller"
},
{
"context": "000000 nil nil]\n [[:box/id -143] \"person/name\" \"Steve Bisley\" nil nil]\n [[:box/id -143] \"person/born\" -56859",
"end": 8382,
"score": 0.9998500943183899,
"start": 8370,
"tag": "NAME",
"value": "Steve Bisley"
},
{
"context": "400000 nil nil]\n [[:box/id -144] \"person/name\" \"Joanne Samuel\" nil nil]\n [[:box/id -145] \"person/name\" \"Micha",
"end": 8496,
"score": 0.9998458027839661,
"start": 8483,
"tag": "NAME",
"value": "Joanne Samuel"
},
{
"context": "amuel\" nil nil]\n [[:box/id -145] \"person/name\" \"Michael Preston\" nil nil]\n [[:box/id -145] \"person/born\" -99835",
"end": 8556,
"score": 0.9998384118080139,
"start": 8541,
"tag": "NAME",
"value": "Michael Preston"
},
{
"context": "000000 nil nil]\n [[:box/id -146] \"person/name\" \"Bruce Spence\" nil nil]\n [[:box/id -146] \"person/born\" -76654",
"end": 8669,
"score": 0.9998525381088257,
"start": 8657,
"tag": "NAME",
"value": "Bruce Spence"
},
{
"context": "800000 nil nil]\n [[:box/id -147] \"person/name\" \"George Ogilvie\" nil nil]\n [[:box/id -147] \"person/born\" -12253",
"end": 8784,
"score": 0.999844491481781,
"start": 8770,
"tag": "NAME",
"value": "George Ogilvie"
},
{
"context": "800000 nil nil]\n [[:box/id -148] \"person/name\" \"Tina Turner\" nil nil]\n [[:box/id -148] \"person/born\" -94988",
"end": 8897,
"score": 0.9998289942741394,
"start": 8886,
"tag": "NAME",
"value": "Tina Turner"
},
{
"context": "600000 nil nil]\n [[:box/id -149] \"person/name\" \"Sophie Marceau\" nil nil]\n [[:box/id -149] \"person/born\" -98582",
"end": 9012,
"score": 0.999841034412384,
"start": 8998,
"tag": "NAME",
"value": "Sophie Marceau"
},
{
"context": "uel was written with an eye to having\\n John McTiernan direct. Schwarzenegger wasn't interested in rep",
"end": 11435,
"score": 0.5994497537612915,
"start": 11432,
"tag": "NAME",
"value": "ern"
},
{
"context": "ith an eye to having\\n John McTiernan direct. Schwarzenegger wasn't interested in reprising\\n the role. The s",
"end": 11460,
"score": 0.9625827670097351,
"start": 11449,
"tag": "NAME",
"value": "warzenegger"
},
{
"context": "h a new central character,\\n eventually played by Bruce Willis, and became Die Hard\"\n nil\n nil]\n [[:box/",
"end": 11600,
"score": 0.9998757243156433,
"start": 11588,
"tag": "NAME",
"value": "Bruce Willis"
},
{
"context": "-210] true nil]\n [[:box/id -210] \"movie/title\" \"Rambo III\" nil nil]\n [[:box/id -210] \"movie/year\" 1",
"end": 13267,
"score": 0.8382777571678162,
"start": 13264,
"tag": "NAME",
"value": "Ram"
},
{
"context": "103] true true]\n [[:box/id -216] \"movie/title\" \"Mad Max\" nil nil]\n [[:box/id -216] \"movie/year\" 1979 ni",
"end": 15405,
"score": 0.9345204830169678,
"start": 15398,
"tag": "NAME",
"value": "Mad Max"
},
{
"context": " :where\n [?e :name \"Zack\"]\n [?e :friend ?e2]\n ",
"end": 17484,
"score": 0.9996576309204102,
"start": 17480,
"tag": "NAME",
"value": "Zack"
},
{
"context": " entity succeeded\"]]))\n\n(def dq-basic-datoms\n [[\"sally\" \"age\" 21]\n [\"fred\" \"age\" 42]\n [\"ethel\" \"age\"",
"end": 17875,
"score": 0.9914035797119141,
"start": 17870,
"tag": "NAME",
"value": "sally"
},
{
"context": "\n\n(def dq-basic-datoms\n [[\"sally\" \"age\" 21]\n [\"fred\" \"age\" 42]\n [\"ethel\" \"age\" 42]\n [\"fred\" \"like",
"end": 17896,
"score": 0.9992821216583252,
"start": 17892,
"tag": "NAME",
"value": "fred"
},
{
"context": "]\n [\"fred\" \"age\" 42]\n [\"ethel\" \"age\" 42]\n [\"fred\" \"likes\" \"pizza\"]\n [\"sally\" \"likes\" \"opera\"]\n ",
"end": 17939,
"score": 0.9986468553543091,
"start": 17935,
"tag": "NAME",
"value": "fred"
},
{
"context": "ethel\" \"age\" 42]\n [\"fred\" \"likes\" \"pizza\"]\n [\"sally\" \"likes\" \"opera\"]\n [\"ethel\" \"likes\" \"sushi\"]\n ",
"end": 17968,
"score": 0.9972677230834961,
"start": 17963,
"tag": "NAME",
"value": "sally"
},
{
"context": "likes\" \"pizza\"]\n [\"sally\" \"likes\" \"opera\"]\n [\"ethel\" \"likes\" \"sushi\"]\n [\"sally\" \"name\" \"Sally\"]\n ",
"end": 17997,
"score": 0.7358638048171997,
"start": 17992,
"tag": "NAME",
"value": "ethel"
},
{
"context": "likes\" \"opera\"]\n [\"ethel\" \"likes\" \"sushi\"]\n [\"sally\" \"name\" \"Sally\"]\n [\"fred\" \"name\" \"Fred\"]\n [\"e",
"end": 18026,
"score": 0.9968700408935547,
"start": 18021,
"tag": "NAME",
"value": "sally"
},
{
"context": "\n [\"ethel\" \"likes\" \"sushi\"]\n [\"sally\" \"name\" \"Sally\"]\n [\"fred\" \"name\" \"Fred\"]\n [\"ethel\" \"name\" \"E",
"end": 18041,
"score": 0.9996980428695679,
"start": 18036,
"tag": "NAME",
"value": "Sally"
},
{
"context": "\"likes\" \"sushi\"]\n [\"sally\" \"name\" \"Sally\"]\n [\"fred\" \"name\" \"Fred\"]\n [\"ethel\" \"name\" \"Ethel\"]])\n\n(<",
"end": 18053,
"score": 0.9995933771133423,
"start": 18049,
"tag": "NAME",
"value": "fred"
},
{
"context": "\"]\n [\"sally\" \"name\" \"Sally\"]\n [\"fred\" \"name\" \"Fred\"]\n [\"ethel\" \"name\" \"Ethel\"]])\n\n(<deftest test-q",
"end": 18067,
"score": 0.999793529510498,
"start": 18063,
"tag": "NAME",
"value": "Fred"
},
{
"context": "y\" \"name\" \"Sally\"]\n [\"fred\" \"name\" \"Fred\"]\n [\"ethel\" \"name\" \"Ethel\"]])\n\n(<deftest test-query-basic []",
"end": 18080,
"score": 0.9951532483100891,
"start": 18075,
"tag": "NAME",
"value": "ethel"
},
{
"context": "y\"]\n [\"fred\" \"name\" \"Fred\"]\n [\"ethel\" \"name\" \"Ethel\"]])\n\n(<deftest test-query-basic []\n (let [expect",
"end": 18095,
"score": 0.999717652797699,
"start": 18090,
"tag": "NAME",
"value": "Ethel"
},
{
"context": "st test-query-basic []\n (let [expect [[[:box/id \"fred\"]]\n [[:box/id \"ethel\"]]]\n a",
"end": 18162,
"score": 0.9981669187545776,
"start": 18158,
"tag": "NAME",
"value": "fred"
},
{
"context": "ct [[[:box/id \"fred\"]]\n [[:box/id \"ethel\"]]]\n actual (<! (bq/<query\n ",
"end": 18198,
"score": 0.8909575343132019,
"start": 18193,
"tag": "NAME",
"value": "ethel"
},
{
"context": "t-query-unification []\n (let [expect [[[:box/id \"fred\"] \"pizza\"] [[:box/id \"ethel\"] \"sushi\"]]\n a",
"end": 18541,
"score": 0.9997426271438599,
"start": 18537,
"tag": "NAME",
"value": "fred"
},
{
"context": "? (<test-conn dq-basic-datoms))\n expect [[\"Fred\" 42] [\"Ethel\" 42] [\"Sally\" 21]]\n actual (<",
"end": 19373,
"score": 0.9998447895050049,
"start": 19369,
"tag": "NAME",
"value": "Fred"
},
{
"context": "n dq-basic-datoms))\n expect [[\"Fred\" 42] [\"Ethel\" 42] [\"Sally\" 21]]\n actual (<! (bq/<query\n",
"end": 19386,
"score": 0.9996858239173889,
"start": 19381,
"tag": "NAME",
"value": "Ethel"
},
{
"context": "toms))\n expect [[\"Fred\" 42] [\"Ethel\" 42] [\"Sally\" 21]]\n actual (<! (bq/<query\n ",
"end": 19399,
"score": 0.9997092485427856,
"start": 19394,
"tag": "NAME",
"value": "Sally"
},
{
"context": "dq-basic-datoms))\n expect (vec (reverse [[\"Fred\" 42] [\"Ethel\" 42] [\"Sally\" 21]]))\n actual ",
"end": 19926,
"score": 0.9998412728309631,
"start": 19922,
"tag": "NAME",
"value": "Fred"
},
{
"context": "oms))\n expect (vec (reverse [[\"Fred\" 42] [\"Ethel\" 42] [\"Sally\" 21]]))\n actual (<! (bq/<quer",
"end": 19939,
"score": 0.9997890591621399,
"start": 19934,
"tag": "NAME",
"value": "Ethel"
},
{
"context": " expect (vec (reverse [[\"Fred\" 42] [\"Ethel\" 42] [\"Sally\" 21]]))\n actual (<! (bq/<query\n ",
"end": 19952,
"score": 0.9997694492340088,
"start": 19947,
"tag": "NAME",
"value": "Sally"
},
{
"context": "(<test-conn movies-db))\n expect [[\"Veronica Cartwright\"] [\"Tom Skerritt\"] [\"Tina Turner\"]]\n actua",
"end": 20477,
"score": 0.9945115447044373,
"start": 20467,
"tag": "NAME",
"value": "Cartwright"
},
{
"context": "es-db))\n expect [[\"Veronica Cartwright\"] [\"Tom Skerritt\"] [\"Tina Turner\"]]\n actual (<! (bq/<query\n",
"end": 20494,
"score": 0.9998617172241211,
"start": 20482,
"tag": "NAME",
"value": "Tom Skerritt"
},
{
"context": "xpect [[\"Veronica Cartwright\"] [\"Tom Skerritt\"] [\"Tina Turner\"]]\n actual (<! (bq/<query\n ",
"end": 20510,
"score": 0.9998559951782227,
"start": 20499,
"tag": "NAME",
"value": "Tina Turner"
},
{
"context": "? (<test-conn dq-basic-datoms))\n expect [[\"Fred\" 42] [\"Ethel\" 42]]\n actual (<! (bq/<query\n",
"end": 22536,
"score": 0.9998104572296143,
"start": 22532,
"tag": "NAME",
"value": "Fred"
},
{
"context": "n dq-basic-datoms))\n expect [[\"Fred\" 42] [\"Ethel\" 42]]\n actual (<! (bq/<query\n ",
"end": 22549,
"score": 0.9995632171630859,
"start": 22544,
"tag": "NAME",
"value": "Ethel"
},
{
"context": "? (<test-conn dq-basic-datoms))\n expect [[\"Ethel\" 42] [\"Sally\" 21]]\n actual (<! (bq/<query\n",
"end": 23092,
"score": 0.9995551109313965,
"start": 23087,
"tag": "NAME",
"value": "Ethel"
},
{
"context": " dq-basic-datoms))\n expect [[\"Ethel\" 42] [\"Sally\" 21]]\n actual (<! (bq/<query\n ",
"end": 23105,
"score": 0.9997744560241699,
"start": 23100,
"tag": "NAME",
"value": "Sally"
},
{
"context": "basic-queries-ch-1-2 []\n (go\n (let [expect [[\"Alan Rickman\"]\n [\"Alexander Godunov\"]\n ",
"end": 28679,
"score": 0.9998979568481445,
"start": 28667,
"tag": "NAME",
"value": "Alan Rickman"
},
{
"context": "let [expect [[\"Alan Rickman\"]\n [\"Alexander Godunov\"]\n [\"Alyssa Milano\"]\n ",
"end": 28719,
"score": 0.9998965263366699,
"start": 28702,
"tag": "NAME",
"value": "Alexander Godunov"
},
{
"context": " [\"Alexander Godunov\"]\n [\"Alyssa Milano\"]\n [\"Arnold Schwarzenegger\"]\n ",
"end": 28755,
"score": 0.9998968839645386,
"start": 28742,
"tag": "NAME",
"value": "Alyssa Milano"
},
{
"context": " [\"Alyssa Milano\"]\n [\"Arnold Schwarzenegger\"]\n [\"Brian Dennehy\"]\n ",
"end": 28799,
"score": 0.9999009966850281,
"start": 28778,
"tag": "NAME",
"value": "Arnold Schwarzenegger"
},
{
"context": " [\"Arnold Schwarzenegger\"]\n [\"Brian Dennehy\"]\n [\"Bruce Spence\"]\n ",
"end": 28835,
"score": 0.9999040365219116,
"start": 28822,
"tag": "NAME",
"value": "Brian Dennehy"
},
{
"context": " [\"Brian Dennehy\"]\n [\"Bruce Spence\"]\n [\"Bruce Willis\"]\n ",
"end": 28870,
"score": 0.9998979568481445,
"start": 28858,
"tag": "NAME",
"value": "Bruce Spence"
},
{
"context": " [\"Bruce Spence\"]\n [\"Bruce Willis\"]\n [\"Carl Weathers\"]\n ",
"end": 28905,
"score": 0.9998939633369446,
"start": 28893,
"tag": "NAME",
"value": "Bruce Willis"
},
{
"context": " [\"Bruce Willis\"]\n [\"Carl Weathers\"]\n [\"Carrie Henn\"]\n ",
"end": 28941,
"score": 0.9998986721038818,
"start": 28928,
"tag": "NAME",
"value": "Carl Weathers"
},
{
"context": " [\"Carl Weathers\"]\n [\"Carrie Henn\"]\n [\"Charles Napier\"]\n ",
"end": 28975,
"score": 0.9999011754989624,
"start": 28964,
"tag": "NAME",
"value": "Carrie Henn"
},
{
"context": " [\"Carrie Henn\"]\n [\"Charles Napier\"]\n [\"Claire Danes\"]\n ",
"end": 29012,
"score": 0.9998947381973267,
"start": 28998,
"tag": "NAME",
"value": "Charles Napier"
},
{
"context": " [\"Charles Napier\"]\n [\"Claire Danes\"]\n [\"Danny Glover\"]\n ",
"end": 29047,
"score": 0.9998832941055298,
"start": 29035,
"tag": "NAME",
"value": "Claire Danes"
},
{
"context": " [\"Claire Danes\"]\n [\"Danny Glover\"]\n [\"Edward Furlong\"]\n ",
"end": 29082,
"score": 0.9998976588249207,
"start": 29070,
"tag": "NAME",
"value": "Danny Glover"
},
{
"context": " [\"Danny Glover\"]\n [\"Edward Furlong\"]\n [\"Elpidia Carrillo\"]\n ",
"end": 29119,
"score": 0.9998983144760132,
"start": 29105,
"tag": "NAME",
"value": "Edward Furlong"
},
{
"context": " [\"Edward Furlong\"]\n [\"Elpidia Carrillo\"]\n [\"Gary Busey\"]\n ",
"end": 29158,
"score": 0.9998911619186401,
"start": 29142,
"tag": "NAME",
"value": "Elpidia Carrillo"
},
{
"context": " [\"Elpidia Carrillo\"]\n [\"Gary Busey\"]\n [\"George Miller\"]\n ",
"end": 29191,
"score": 0.9998871684074402,
"start": 29181,
"tag": "NAME",
"value": "Gary Busey"
},
{
"context": " [\"Gary Busey\"]\n [\"George Miller\"]\n [\"George Ogilvie\"]\n ",
"end": 29227,
"score": 0.9998856782913208,
"start": 29214,
"tag": "NAME",
"value": "George Miller"
},
{
"context": " [\"George Miller\"]\n [\"George Ogilvie\"]\n [\"George P. Cosmatos\"]\n ",
"end": 29264,
"score": 0.9998960494995117,
"start": 29250,
"tag": "NAME",
"value": "George Ogilvie"
},
{
"context": " [\"George Ogilvie\"]\n [\"George P. Cosmatos\"]\n [\"James Cameron\"]\n ",
"end": 29305,
"score": 0.9998807311058044,
"start": 29287,
"tag": "NAME",
"value": "George P. Cosmatos"
},
{
"context": " [\"George P. Cosmatos\"]\n [\"James Cameron\"]\n [\"Joanne Samuel\"]\n ",
"end": 29341,
"score": 0.9998771548271179,
"start": 29328,
"tag": "NAME",
"value": "James Cameron"
},
{
"context": " [\"James Cameron\"]\n [\"Joanne Samuel\"]\n [\"Joe Pesci\"]\n ",
"end": 29377,
"score": 0.9998853802680969,
"start": 29364,
"tag": "NAME",
"value": "Joanne Samuel"
},
{
"context": " [\"Joanne Samuel\"]\n [\"Joe Pesci\"]\n [\"John McTiernan\"]\n ",
"end": 29409,
"score": 0.9998771548271179,
"start": 29400,
"tag": "NAME",
"value": "Joe Pesci"
},
{
"context": " [\"Joe Pesci\"]\n [\"John McTiernan\"]\n [\"Jonathan Mostow\"]\n ",
"end": 29446,
"score": 0.999879002571106,
"start": 29432,
"tag": "NAME",
"value": "John McTiernan"
},
{
"context": " [\"John McTiernan\"]\n [\"Jonathan Mostow\"]\n [\"Linda Hamilton\"]\n ",
"end": 29484,
"score": 0.9998692870140076,
"start": 29469,
"tag": "NAME",
"value": "Jonathan Mostow"
},
{
"context": " [\"Jonathan Mostow\"]\n [\"Linda Hamilton\"]\n [\"Marc de Jonge\"]\n ",
"end": 29521,
"score": 0.9998943209648132,
"start": 29507,
"tag": "NAME",
"value": "Linda Hamilton"
},
{
"context": " [\"Linda Hamilton\"]\n [\"Marc de Jonge\"]\n [\"Mark L. Lester\"]\n ",
"end": 29557,
"score": 0.9998924136161804,
"start": 29544,
"tag": "NAME",
"value": "Marc de Jonge"
},
{
"context": " [\"Marc de Jonge\"]\n [\"Mark L. Lester\"]\n [\"Mel Gibson\"]\n ",
"end": 29594,
"score": 0.9998804330825806,
"start": 29580,
"tag": "NAME",
"value": "Mark L. Lester"
},
{
"context": " [\"Mark L. Lester\"]\n [\"Mel Gibson\"]\n [\"Michael Biehn\"]\n ",
"end": 29627,
"score": 0.9998730421066284,
"start": 29617,
"tag": "NAME",
"value": "Mel Gibson"
},
{
"context": " [\"Mel Gibson\"]\n [\"Michael Biehn\"]\n [\"Michael Preston\"]\n ",
"end": 29663,
"score": 0.9998939037322998,
"start": 29650,
"tag": "NAME",
"value": "Michael Biehn"
},
{
"context": " [\"Michael Biehn\"]\n [\"Michael Preston\"]\n [\"Nancy Allen\"]\n ",
"end": 29701,
"score": 0.9998891949653625,
"start": 29686,
"tag": "NAME",
"value": "Michael Preston"
},
{
"context": " [\"Michael Preston\"]\n [\"Nancy Allen\"]\n [\"Nick Stahl\"]\n ",
"end": 29735,
"score": 0.9998626708984375,
"start": 29724,
"tag": "NAME",
"value": "Nancy Allen"
},
{
"context": " [\"Nancy Allen\"]\n [\"Nick Stahl\"]\n [\"Paul Verhoeven\"]\n ",
"end": 29768,
"score": 0.9998819828033447,
"start": 29758,
"tag": "NAME",
"value": "Nick Stahl"
},
{
"context": " [\"Nick Stahl\"]\n [\"Paul Verhoeven\"]\n [\"Peter MacDonald\"]\n ",
"end": 29805,
"score": 0.9998992681503296,
"start": 29791,
"tag": "NAME",
"value": "Paul Verhoeven"
},
{
"context": " [\"Paul Verhoeven\"]\n [\"Peter MacDonald\"]\n [\"Peter Weller\"]\n ",
"end": 29843,
"score": 0.9998803734779358,
"start": 29828,
"tag": "NAME",
"value": "Peter MacDonald"
},
{
"context": " [\"Peter MacDonald\"]\n [\"Peter Weller\"]\n [\"Rae Dawn Chong\"]\n ",
"end": 29878,
"score": 0.9998687505722046,
"start": 29866,
"tag": "NAME",
"value": "Peter Weller"
},
{
"context": " [\"Peter Weller\"]\n [\"Rae Dawn Chong\"]\n [\"Richard Crenna\"]\n ",
"end": 29915,
"score": 0.9998980164527893,
"start": 29901,
"tag": "NAME",
"value": "Rae Dawn Chong"
},
{
"context": " [\"Rae Dawn Chong\"]\n [\"Richard Crenna\"]\n [\"Richard Donner\"]\n ",
"end": 29952,
"score": 0.9998893737792969,
"start": 29938,
"tag": "NAME",
"value": "Richard Crenna"
},
{
"context": " [\"Richard Crenna\"]\n [\"Richard Donner\"]\n [\"Ridley Scott\"]\n ",
"end": 29989,
"score": 0.9998883008956909,
"start": 29975,
"tag": "NAME",
"value": "Richard Donner"
},
{
"context": " [\"Richard Donner\"]\n [\"Ridley Scott\"]\n [\"Robert Patrick\"]\n ",
"end": 30024,
"score": 0.999894917011261,
"start": 30012,
"tag": "NAME",
"value": "Ridley Scott"
},
{
"context": " [\"Ridley Scott\"]\n [\"Robert Patrick\"]\n [\"Ronny Cox\"]\n ",
"end": 30061,
"score": 0.9998847842216492,
"start": 30047,
"tag": "NAME",
"value": "Robert Patrick"
},
{
"context": " [\"Robert Patrick\"]\n [\"Ronny Cox\"]\n [\"Ruben Blades\"]\n ",
"end": 30093,
"score": 0.9999016523361206,
"start": 30084,
"tag": "NAME",
"value": "Ronny Cox"
},
{
"context": " [\"Ronny Cox\"]\n [\"Ruben Blades\"]\n [\"Sigourney Weaver\"]\n ",
"end": 30128,
"score": 0.9998969435691833,
"start": 30116,
"tag": "NAME",
"value": "Ruben Blades"
},
{
"context": " [\"Ruben Blades\"]\n [\"Sigourney Weaver\"]\n [\"Sophie Marceau\"]\n ",
"end": 30167,
"score": 0.9998770952224731,
"start": 30151,
"tag": "NAME",
"value": "Sigourney Weaver"
},
{
"context": " [\"Sigourney Weaver\"]\n [\"Sophie Marceau\"]\n [\"Stephen Hopkins\"]\n ",
"end": 30204,
"score": 0.9999005198478699,
"start": 30190,
"tag": "NAME",
"value": "Sophie Marceau"
},
{
"context": " [\"Sophie Marceau\"]\n [\"Stephen Hopkins\"]\n [\"Steve Bisley\"]\n ",
"end": 30242,
"score": 0.9999005198478699,
"start": 30227,
"tag": "NAME",
"value": "Stephen Hopkins"
},
{
"context": " [\"Stephen Hopkins\"]\n [\"Steve Bisley\"]\n [\"Sylvester Stallone\"]\n ",
"end": 30277,
"score": 0.9998847246170044,
"start": 30265,
"tag": "NAME",
"value": "Steve Bisley"
},
{
"context": " [\"Steve Bisley\"]\n [\"Sylvester Stallone\"]\n [\"Ted Kotcheff\"]\n ",
"end": 30318,
"score": 0.9998978972434998,
"start": 30300,
"tag": "NAME",
"value": "Sylvester Stallone"
},
{
"context": " [\"Sylvester Stallone\"]\n [\"Ted Kotcheff\"]\n [\"Tina Turner\"] \n ",
"end": 30353,
"score": 0.9999003410339355,
"start": 30341,
"tag": "NAME",
"value": "Ted Kotcheff"
},
{
"context": " [\"Ted Kotcheff\"]\n [\"Tina Turner\"] \n [\"Tom Skerritt\"] \n ",
"end": 30387,
"score": 0.9998877048492432,
"start": 30376,
"tag": "NAME",
"value": "Tina Turner"
},
{
"context": " [\"Tina Turner\"] \n [\"Tom Skerritt\"] \n [\"Veronica Cartwright\"]]\n ",
"end": 30423,
"score": 0.9998931288719177,
"start": 30411,
"tag": "NAME",
"value": "Tom Skerritt"
},
{
"context": " [\"Tom Skerritt\"] \n [\"Veronica Cartwright\"]]\n actual (<! (bq/<query\n ",
"end": 30466,
"score": 0.9998905062675476,
"start": 30447,
"tag": "NAME",
"value": "Veronica Cartwright"
},
{
"context": " (<! (<test-conn movies-db))))\n [[\"Paul Verhoeven\"]])]]))\n\n(deftest test-dpat-ch-2-3 []\n (go\n (",
"end": 32005,
"score": 0.999897837638855,
"start": 31991,
"tag": "NAME",
"value": "Paul Verhoeven"
},
{
"context": "est test-dpat-ch-2-3 []\n (go\n (let [expect [[\"James Cameron\"]\n [\"John McTiernan\"] \n ",
"end": 32083,
"score": 0.9998878836631775,
"start": 32070,
"tag": "NAME",
"value": "James Cameron"
},
{
"context": "et [expect [[\"James Cameron\"]\n [\"John McTiernan\"] \n [\"Jonathan Mostow\"]\n ",
"end": 32120,
"score": 0.9998937845230103,
"start": 32106,
"tag": "NAME",
"value": "John McTiernan"
},
{
"context": " [\"John McTiernan\"] \n [\"Jonathan Mostow\"]\n [\"Mark L. Lester\"]]\n ",
"end": 32159,
"score": 0.9998955726623535,
"start": 32144,
"tag": "NAME",
"value": "Jonathan Mostow"
},
{
"context": " [\"Jonathan Mostow\"]\n [\"Mark L. Lester\"]]\n actual (<! (bq/<query\n ",
"end": 32196,
"score": 0.9998949766159058,
"start": 32182,
"tag": "NAME",
"value": "Mark L. Lester"
},
{
"context": ":where\n [?p :person/name \"Arnold Schwarzenegger\"]\n [?m :movie/cast ?p]\n ",
"end": 32365,
"score": 0.9999017715454102,
"start": 32344,
"tag": "NAME",
"value": "Arnold Schwarzenegger"
},
{
"context": "))\n 1988))\n [[\"Die Hard\"] [\"Rambo III\"]])]]))\n\n(deftest test-param-queries-ch-3-1 []\n ",
"end": 33066,
"score": 0.6129194498062134,
"start": 33057,
"tag": "NAME",
"value": "Rambo III"
},
{
"context": " #_debug-explain)\n \"Michael Biehn\"\n \"James Cameron\"))]\n ",
"end": 34352,
"score": 0.9998376965522766,
"start": 34339,
"tag": "NAME",
"value": "Michael Biehn"
},
{
"context": " \"Michael Biehn\"\n \"James Cameron\"))]\n #_(<! (<dump-conn conn))\n [[(= exp",
"end": 34391,
"score": 0.9998741745948792,
"start": 34378,
"tag": "NAME",
"value": "James Cameron"
},
{
"context": " (reverse\n [[\"Alexander Godunov\"]\n [\"Alan Rickman\"] \n ",
"end": 35274,
"score": 0.9998830556869507,
"start": 35257,
"tag": "NAME",
"value": "Alexander Godunov"
},
{
"context": " [[\"Alexander Godunov\"]\n [\"Alan Rickman\"] \n [\"Bruce Willis\"] \n ",
"end": 35313,
"score": 0.9998747110366821,
"start": 35301,
"tag": "NAME",
"value": "Alan Rickman"
},
{
"context": " [\"Alan Rickman\"] \n [\"Bruce Willis\"] \n [\"John McTiernan\"]]))\n ",
"end": 35353,
"score": 0.9998915791511536,
"start": 35341,
"tag": "NAME",
"value": "Bruce Willis"
},
{
"context": " [\"Bruce Willis\"] \n [\"John McTiernan\"]]))\n actual (<! (bq/<query\n ",
"end": 35395,
"score": 0.9999030828475952,
"start": 35381,
"tag": "NAME",
"value": "John McTiernan"
},
{
"context": ":where\n [?d :person/name \"Danny Glover\"]\n [?d :person/born ?b1]\n",
"end": 36711,
"score": 0.9998843669891357,
"start": 36699,
"tag": "NAME",
"value": "Danny Glover"
},
{
"context": " #_debug-explain)))\n expect [[\"Alan Rickman\"]\n [\"Brian Dennehy\"]\n ",
"end": 37101,
"score": 0.9998611211776733,
"start": 37089,
"tag": "NAME",
"value": "Alan Rickman"
},
{
"context": " expect [[\"Alan Rickman\"]\n [\"Brian Dennehy\"]\n [\"Bruce Spence\"]\n ",
"end": 37137,
"score": 0.9998914003372192,
"start": 37124,
"tag": "NAME",
"value": "Brian Dennehy"
},
{
"context": " [\"Brian Dennehy\"]\n [\"Bruce Spence\"]\n [\"Charles Napier\"]\n ",
"end": 37172,
"score": 0.9998858571052551,
"start": 37160,
"tag": "NAME",
"value": "Bruce Spence"
},
{
"context": " [\"Bruce Spence\"]\n [\"Charles Napier\"]\n [\"Gary Busey\"]\n ",
"end": 37209,
"score": 0.9998871088027954,
"start": 37195,
"tag": "NAME",
"value": "Charles Napier"
},
{
"context": " [\"Charles Napier\"]\n [\"Gary Busey\"]\n [\"Joe Pesci\"]\n ",
"end": 37242,
"score": 0.9988219141960144,
"start": 37232,
"tag": "NAME",
"value": "Gary Busey"
},
{
"context": " [\"Gary Busey\"]\n [\"Joe Pesci\"]\n [\"Michael Preston\"]\n ",
"end": 37274,
"score": 0.9998728632926941,
"start": 37265,
"tag": "NAME",
"value": "Joe Pesci"
},
{
"context": " [\"Joe Pesci\"]\n [\"Michael Preston\"]\n [\"Richard Crenna\"]\n ",
"end": 37312,
"score": 0.9998734593391418,
"start": 37297,
"tag": "NAME",
"value": "Michael Preston"
},
{
"context": " [\"Michael Preston\"]\n [\"Richard Crenna\"]\n [\"Ronny Cox\"]\n ",
"end": 37349,
"score": 0.9998642206192017,
"start": 37335,
"tag": "NAME",
"value": "Richard Crenna"
},
{
"context": " [\"Richard Crenna\"]\n [\"Ronny Cox\"]\n [\"Sylvester Stallone\"] \n ",
"end": 37381,
"score": 0.9998847842216492,
"start": 37372,
"tag": "NAME",
"value": "Ronny Cox"
},
{
"context": " [\"Ronny Cox\"]\n [\"Sylvester Stallone\"] \n [\"Tina Turner\"] \n ",
"end": 37422,
"score": 0.9998850226402283,
"start": 37404,
"tag": "NAME",
"value": "Sylvester Stallone"
},
{
"context": " [\"Sylvester Stallone\"] \n [\"Tina Turner\"] \n [\"Tom Skerritt\"]]]\n [[(",
"end": 37457,
"score": 0.9998785257339478,
"start": 37446,
"tag": "NAME",
"value": "Tina Turner"
},
{
"context": " [\"Tina Turner\"] \n [\"Tom Skerritt\"]]]\n [[(= expect actual)\n nil\n ",
"end": 37493,
"score": 0.9998663663864136,
"start": 37481,
"tag": "NAME",
"value": "Tom Skerritt"
},
{
"context": " :box/updated-ts 1000,\n :box/text \"hithere\",\n :box/ref {:box/id \"two\"},\n :bo",
"end": 43619,
"score": 0.5988724231719971,
"start": 43613,
"tag": "NAME",
"value": "ithere"
},
{
"context": " :box/updated-ts 1000,\n :box/text \"hithere\",\n :box/ref {:box/id \"two\"},\n ",
"end": 44141,
"score": 0.5169618129730225,
"start": 44138,
"tag": "NAME",
"value": "ith"
},
{
"context": " :box/updated-ts 1000,\n :box/text \"hithere\",\n :box/ref\n {:box/id \"two\",\n",
"end": 45593,
"score": 0.9581419825553894,
"start": 45586,
"tag": "NAME",
"value": "hithere"
},
{
"context": " :box/updated-ts 1000,\n :box/text \"hithere\",\n :box/ref {:box/id \"two\"},\n :bo",
"end": 46299,
"score": 0.9646292328834534,
"start": 46292,
"tag": "NAME",
"value": "hithere"
}
] | src/cljs-node/rx/node/box2/tests.cljs | zk/rx-lib | 0 | (ns rx.node.box2.tests
(:require [rx.kitchen-sink :as ks]
[rx.box2 :as bq]
[rx.box2.sql :as bsql]
#_[rx.box2.reagent :as br]
[rx.node.sqlite2 :as sql]
[rx.test :as test
:refer-macros [deftest
<deftest]]
[rx.anom :as anom
:refer-macros [<defn <? gol]]
[datascript.query :as dsq]
[datascript.query-v3 :as dsqv3]
[clojure.core.async :as async
:refer [go <!]]))
(def debug-explain
{::bsql/debug-explain-query? true})
(def test-schema {:box/schema
{:box/attrs
[{:box/attr :box/id
:box/ident? true
:box/value-type :box/string}
{:box/attr :box/ref
:box/ref? true
:box/cardinality :box/cardinality-one}
{:box/attr :box/refs
:box/ref? true
:box/cardinality :box/cardinality-many}
{:box/attr :box/updated-ts
:box/index? true
:box/value-type :box/long}
{:box/attr :box/created-ts
:box/index? true
:box/value-type :box/long}]}})
(<defn <test-conn [& [datoms]]
(let [db (<! (sql/<open-db {:name ":memory:"}))]
(anom/throw-if-anom
(<! (sql/<exec db [(bq/create-datoms-sql)])))
(anom/throw-if-anom
(<! (sql/<batch-exec db (bq/create-indexes-sql-vecs))))
(when datoms
(anom/throw-if-anom
(<! (sql/<batch-exec db (bq/insert-datoms-sqls datoms)))))
(merge
{::bsql/db db
::bsql/<exec sql/<exec
::bsql/<batch-exec sql/<batch-exec}
test-schema)))
(defn <dump-conn [{:keys [::bsql/db
::bsql/<exec]}]
(go
(ks/pp
(<! (<exec db ["select * from datoms"])))))
(defn <run-sql [{:keys [::bsql/db
::bsql/<exec]}
sql-vec]
(go
(ks/spy
"RUN SQL"
(<! (<exec db sql-vec)))))
(def foaf-data
[[[:box/id "zk"] "name" "Zack" false]
[[:box/id "cindy"] "name" "Cindy" false]
[[:box/id "zk"] "friend" [:box/id "cindy"] true true]])
(def refs-datoms
[[[:box/id "one"] :box/id "one"]
[[:box/id "one"] :box/created-ts 1000]
[[:box/id "one"] :box/updated-ts 1000]
[[:box/id "one"] :box/text "hithere"]
[[:box/id "one"] :box/ref [:box/id "two"] true]
[[:box/id "two"] :box/id "two"]
[[:box/id "two"] :box/updated-ts 2000]
[[:box/id "two"] :box/created-ts 2000]
[[:box/id "three"] :box/id "three"]
[[:box/id "three"] :box/created-ts 3000]
[[:box/id "three"] :box/updated-ts 3000]
[[:box/id "four"] :box/id "four"]
[[:box/id "four"] :box/created-ts 4000]
[[:box/id "four"] :box/updated-ts 4000]
[[:box/id "one"] :box/refs [:box/id "three"] true true]
[[:box/id "one"] :box/refs [:box/id "four"] true true]
[[:box/id "five"] :box/id "five"]
[[:box/id "five"] :box/created-ts 5000]
[[:box/id "two"] :box/refs [:box/id "five"] true true]
[[:box/id "six"] :box/id "six"]
[[:box/id "six"] :box/bool? true]
[[:box/id "seven"] :box/id "seven"]
[[:box/id "seven"] :box/bool? false]])
(def movies-db
[[[:box/id -100] "person/name" "James Cameron" nil nil]
[[:box/id -100] "person/born" -485308800000 nil nil]
[[:box/id -101] "person/name" "Arnold Schwarzenegger" nil nil]
[[:box/id -101] "person/born" -707702400000 nil nil]
[[:box/id -102] "person/name" "Linda Hamilton" nil nil]
[[:box/id -102] "person/born" -418608000000 nil nil]
[[:box/id -103] "person/name" "Michael Biehn" nil nil]
[[:box/id -103] "person/born" -423532800000 nil nil]
[[:box/id -104] "person/name" "Ted Kotcheff" nil nil]
[[:box/id -104] "person/born" -1222473600000 nil nil]
[[:box/id -105] "person/name" "Sylvester Stallone" nil nil]
[[:box/id -105] "person/born" -741312000000 nil nil]
[[:box/id -106] "person/name" "Richard Crenna" nil nil]
[[:box/id -106] "person/born" -1359763200000 nil nil]
[[:box/id -106] "person/death" 1042761600000 nil nil]
[[:box/id -107] "person/name" "Brian Dennehy" nil nil]
[[:box/id -107] "person/born" -993513600000 nil nil]
[[:box/id -108] "person/name" "John McTiernan" nil nil]
[[:box/id -108] "person/born" -599011200000 nil nil]
[[:box/id -109] "person/name" "Elpidia Carrillo" nil nil]
[[:box/id -109] "person/born" -264384000000 nil nil]
[[:box/id -110] "person/name" "Carl Weathers" nil nil]
[[:box/id -110] "person/born" -693187200000 nil nil]
[[:box/id -111] "person/name" "Richard Donner" nil nil]
[[:box/id -111] "person/born" -1252540800000 nil nil]
[[:box/id -112] "person/name" "Mel Gibson" nil nil]
[[:box/id -112] "person/born" -441676800000 nil nil]
[[:box/id -113] "person/name" "Danny Glover" nil nil]
[[:box/id -113] "person/born" -739929600000 nil nil]
[[:box/id -114] "person/name" "Gary Busey" nil nil]
[[:box/id -114] "person/born" -802396800000 nil nil]
[[:box/id -115] "person/name" "Paul Verhoeven" nil nil]
[[:box/id -115] "person/born" -992736000000 nil nil]
[[:box/id -116] "person/name" "Peter Weller" nil nil]
[[:box/id -116] "person/born" -710812800000 nil nil]
[[:box/id -117] "person/name" "Nancy Allen" nil nil]
[[:box/id -117] "person/born" -616118400000 nil nil]
[[:box/id -118] "person/name" "Ronny Cox" nil nil]
[[:box/id -118] "person/born" -992304000000 nil nil]
[[:box/id -119] "person/name" "Mark L. Lester" nil nil]
[[:box/id -119] "person/born" -728956800000 nil nil]
[[:box/id -120] "person/name" "Rae Dawn Chong" nil nil]
[[:box/id -120] "person/born" -278985600000 nil nil]
[[:box/id -121] "person/name" "Alyssa Milano" nil nil]
[[:box/id -121] "person/born" 93571200000 nil nil]
[[:box/id -122] "person/name" "Bruce Willis" nil nil]
[[:box/id -122] "person/born" -466732800000 nil nil]
[[:box/id -123] "person/name" "Alan Rickman" nil nil]
[[:box/id -123] "person/born" -752976000000 nil nil]
[[:box/id -124] "person/name" "Alexander Godunov" nil nil]
[[:box/id -124] "person/born" -634089600000 nil nil]
[[:box/id -124] "person/death" 800755200000 nil nil]
[[:box/id -125] "person/name" "Robert Patrick" nil nil]
[[:box/id -125] "person/born" -352080000000 nil nil]
[[:box/id -126] "person/name" "Edward Furlong" nil nil]
[[:box/id -126] "person/born" 239328000000 nil nil]
[[:box/id -127] "person/name" "Jonathan Mostow" nil nil]
[[:box/id -127] "person/born" -255398400000 nil nil]
[[:box/id -128] "person/name" "Nick Stahl" nil nil]
[[:box/id -128] "person/born" 313200000000 nil nil]
[[:box/id -129] "person/name" "Claire Danes" nil nil]
[[:box/id -129] "person/born" 292723200000 nil nil]
[[:box/id -130] "person/name" "George P. Cosmatos" nil nil]
[[:box/id -130] "person/born" -914889600000 nil nil]
[[:box/id -130] "person/death" 1113868800000 nil nil]
[[:box/id -131] "person/name" "Charles Napier" nil nil]
[[:box/id -131] "person/born" -1064188800000 nil nil]
[[:box/id -131] "person/death" 1317772800000 nil nil]
[[:box/id -132] "person/name" "Peter MacDonald" nil nil]
[[:box/id -133] "person/name" "Marc de Jonge" nil nil]
[[:box/id -133] "person/born" -658713600000 nil nil]
[[:box/id -133] "person/death" 834019200000 nil nil]
[[:box/id -134] "person/name" "Stephen Hopkins" nil nil]
[[:box/id -135] "person/name" "Ruben Blades" nil nil]
[[:box/id -135] "person/born" -677289600000 nil nil]
[[:box/id -136] "person/name" "Joe Pesci" nil nil]
[[:box/id -136] "person/born" -848707200000 nil nil]
[[:box/id -137] "person/name" "Ridley Scott" nil nil]
[[:box/id -137] "person/born" -1012608000000 nil nil]
[[:box/id -138] "person/name" "Tom Skerritt" nil nil]
[[:box/id -138] "person/born" -1147219200000 nil nil]
[[:box/id -139] "person/name" "Sigourney Weaver" nil nil]
[[:box/id -139] "person/born" -638496000000 nil nil]
[[:box/id -140] "person/name" "Veronica Cartwright" nil nil]
[[:box/id -140] "person/born" -653270400000 nil nil]
[[:box/id -141] "person/name" "Carrie Henn" nil nil]
[[:box/id -142] "person/name" "George Miller" nil nil]
[[:box/id -142] "person/born" -783648000000 nil nil]
[[:box/id -143] "person/name" "Steve Bisley" nil nil]
[[:box/id -143] "person/born" -568598400000 nil nil]
[[:box/id -144] "person/name" "Joanne Samuel" nil nil]
[[:box/id -145] "person/name" "Michael Preston" nil nil]
[[:box/id -145] "person/born" -998352000000 nil nil]
[[:box/id -146] "person/name" "Bruce Spence" nil nil]
[[:box/id -146] "person/born" -766540800000 nil nil]
[[:box/id -147] "person/name" "George Ogilvie" nil nil]
[[:box/id -147] "person/born" -1225324800000 nil nil]
[[:box/id -148] "person/name" "Tina Turner" nil nil]
[[:box/id -148] "person/born" -949881600000 nil nil]
[[:box/id -149] "person/name" "Sophie Marceau" nil nil]
[[:box/id -149] "person/born" -98582400000 nil nil]
[[:box/id -200] "movie/title" "The Terminator" nil nil]
[[:box/id -200] "movie/year" 1984 nil nil]
[[:box/id -200] "movie/director" [:box/id -100] true nil]
[[:box/id -200] "movie/cast" [:box/id -101] true true]
[[:box/id -200] "movie/cast" [:box/id -102] true true]
[[:box/id -200] "movie/cast" [:box/id -103] true true]
[[:box/id -200] "movie/sequel" [:box/id -207] true nil]
[[:box/id -201] "movie/title" "First Blood" nil nil]
[[:box/id -201] "movie/year" 1982 nil nil]
[[:box/id -201] "movie/director" [:box/id -104] true nil]
[[:box/id -201] "movie/cast" [:box/id -105] true true]
[[:box/id -201] "movie/cast" [:box/id -106] true true]
[[:box/id -201] "movie/cast" [:box/id -107] true true]
[[:box/id -201] "movie/sequel" [:box/id -209] true nil]
[[:box/id -202] "movie/title" "Predator" nil nil]
[[:box/id -202] "movie/year" 1987 nil nil]
[[:box/id -202] "movie/director" [:box/id -108] true nil]
[[:box/id -202] "movie/cast" [:box/id -101] true true]
[[:box/id -202] "movie/cast" [:box/id -109] true true]
[[:box/id -202] "movie/cast" [:box/id -110] true true]
[[:box/id -202] "movie/sequel" [:box/id -211] true nil]
[[:box/id -203] "movie/title" "Lethal Weapon" nil nil]
[[:box/id -203] "movie/year" 1987 nil nil]
[[:box/id -203] "movie/director" [:box/id -111] true nil]
[[:box/id -203] "movie/cast" [:box/id -112] true true]
[[:box/id -203] "movie/cast" [:box/id -113] true true]
[[:box/id -203] "movie/cast" [:box/id -114] true true]
[[:box/id -203] "movie/sequel" [:box/id -212] true nil]
[[:box/id -204] "movie/title" "RoboCop" nil nil]
[[:box/id -204] "movie/year" 1987 nil nil]
[[:box/id -204] "movie/director" [:box/id -115] true nil]
[[:box/id -204] "movie/cast" [:box/id -116] true true]
[[:box/id -204] "movie/cast" [:box/id -117] true true]
[[:box/id -204] "movie/cast" [:box/id -118] true true]
[[:box/id -205] "movie/title" "Commando" nil nil]
[[:box/id -205] "movie/year" 1985 nil nil]
[[:box/id -205] "movie/director" [:box/id -119] true nil]
[[:box/id -205] "movie/cast" [:box/id -101] true true]
[[:box/id -205] "movie/cast" [:box/id -120] true true]
[[:box/id -205] "movie/cast" [:box/id -121] true true]
[[:box/id -205]
"trivia"
"In 1986, a sequel was written with an eye to having\n John McTiernan direct. Schwarzenegger wasn't interested in reprising\n the role. The script was then reworked with a new central character,\n eventually played by Bruce Willis, and became Die Hard"
nil
nil]
[[:box/id -206] "movie/title" "Die Hard" nil nil]
[[:box/id -206] "movie/year" 1988 nil nil]
[[:box/id -206] "movie/director" [:box/id -108] true nil]
[[:box/id -206] "movie/cast" [:box/id -122] true true]
[[:box/id -206] "movie/cast" [:box/id -123] true true]
[[:box/id -206] "movie/cast" [:box/id -124] true true]
[[:box/id -207] "movie/title" "Terminator 2: Judgment Day" nil nil]
[[:box/id -207] "movie/year" 1991 nil nil]
[[:box/id -207] "movie/director" [:box/id -100] true nil]
[[:box/id -207] "movie/cast" [:box/id -101] true true]
[[:box/id -207] "movie/cast" [:box/id -102] true true]
[[:box/id -207] "movie/cast" [:box/id -125] true true]
[[:box/id -207] "movie/cast" [:box/id -126] true true]
[[:box/id -207] "movie/sequel" [:box/id -208] true nil]
[[:box/id -208]
"movie/title"
"Terminator 3: Rise of the Machines"
nil
nil]
[[:box/id -208] "movie/year" 2003 nil nil]
[[:box/id -208] "movie/director" [:box/id -127] true nil]
[[:box/id -208] "movie/cast" [:box/id -101] true true]
[[:box/id -208] "movie/cast" [:box/id -128] true true]
[[:box/id -208] "movie/cast" [:box/id -129] true true]
[[:box/id -209] "movie/title" "Rambo: First Blood Part II" nil nil]
[[:box/id -209] "movie/year" 1985 nil nil]
[[:box/id -209] "movie/director" [:box/id -130] true nil]
[[:box/id -209] "movie/cast" [:box/id -105] true true]
[[:box/id -209] "movie/cast" [:box/id -106] true true]
[[:box/id -209] "movie/cast" [:box/id -131] true true]
[[:box/id -209] "movie/sequel" [:box/id -210] true nil]
[[:box/id -210] "movie/title" "Rambo III" nil nil]
[[:box/id -210] "movie/year" 1988 nil nil]
[[:box/id -210] "movie/director" [:box/id -132] true nil]
[[:box/id -210] "movie/cast" [:box/id -105] true true]
[[:box/id -210] "movie/cast" [:box/id -106] true true]
[[:box/id -210] "movie/cast" [:box/id -133] true true]
[[:box/id -211] "movie/title" "Predator 2" nil nil]
[[:box/id -211] "movie/year" 1990 nil nil]
[[:box/id -211] "movie/director" [:box/id -134] true nil]
[[:box/id -211] "movie/cast" [:box/id -113] true true]
[[:box/id -211] "movie/cast" [:box/id -114] true true]
[[:box/id -211] "movie/cast" [:box/id -135] true true]
[[:box/id -212] "movie/title" "Lethal Weapon 2" nil nil]
[[:box/id -212] "movie/year" 1989 nil nil]
[[:box/id -212] "movie/director" [:box/id -111] true nil]
[[:box/id -212] "movie/cast" [:box/id -112] true true]
[[:box/id -212] "movie/cast" [:box/id -113] true true]
[[:box/id -212] "movie/cast" [:box/id -136] true true]
[[:box/id -212] "movie/sequel" [:box/id -213] true nil]
[[:box/id -213] "movie/title" "Lethal Weapon 3" nil nil]
[[:box/id -213] "movie/year" 1992 nil nil]
[[:box/id -213] "movie/director" [:box/id -111] true nil]
[[:box/id -213] "movie/cast" [:box/id -112] true true]
[[:box/id -213] "movie/cast" [:box/id -113] true true]
[[:box/id -213] "movie/cast" [:box/id -136] true true]
[[:box/id -214] "movie/title" "Alien" nil nil]
[[:box/id -214] "movie/year" 1979 nil nil]
[[:box/id -214] "movie/director" [:box/id -137] true nil]
[[:box/id -214] "movie/cast" [:box/id -138] true true]
[[:box/id -214] "movie/cast" [:box/id -139] true true]
[[:box/id -214] "movie/cast" [:box/id -140] true true]
[[:box/id -214] "movie/sequel" [:box/id -215] true nil]
[[:box/id -215] "movie/title" "Aliens" nil nil]
[[:box/id -215] "movie/year" 1986 nil nil]
[[:box/id -215] "movie/director" [:box/id -100] true nil]
[[:box/id -215] "movie/cast" [:box/id -139] true true]
[[:box/id -215] "movie/cast" [:box/id -141] true true]
[[:box/id -215] "movie/cast" [:box/id -103] true true]
[[:box/id -216] "movie/title" "Mad Max" nil nil]
[[:box/id -216] "movie/year" 1979 nil nil]
[[:box/id -216] "movie/director" [:box/id -142] true nil]
[[:box/id -216] "movie/cast" [:box/id -112] true true]
[[:box/id -216] "movie/cast" [:box/id -143] true true]
[[:box/id -216] "movie/cast" [:box/id -144] true true]
[[:box/id -216] "movie/sequel" [:box/id -217] true nil]
[[:box/id -217] "movie/title" "Mad Max 2" nil nil]
[[:box/id -217] "movie/year" 1981 nil nil]
[[:box/id -217] "movie/director" [:box/id -142] true nil]
[[:box/id -217] "movie/cast" [:box/id -112] true true]
[[:box/id -217] "movie/cast" [:box/id -145] true true]
[[:box/id -217] "movie/cast" [:box/id -146] true true]
[[:box/id -217] "movie/sequel" [:box/id -218] true nil]
[[:box/id -218] "movie/title" "Mad Max Beyond Thunderdome" nil nil]
[[:box/id -218] "movie/year" 1985 nil nil]
[[:box/id -218] "movie/director" [:box/id -142] true true]
[[:box/id -218] "movie/director" [:box/id -147] true true]
[[:box/id -218] "movie/cast" [:box/id -112] true true]
[[:box/id -218] "movie/cast" [:box/id -148] true true]
[[:box/id -219] "movie/title" "Braveheart" nil nil]
[[:box/id -219] "movie/year" 1995 nil nil]
[[:box/id -219] "movie/director" [:box/id -112] true true]
[[:box/id -219] "movie/cast" [:box/id -112] true true]
[[:box/id -219] "movie/cast" [:box/id -149] true true]])
(<deftest test-query-entity []
(let [conn (<? (<test-conn foaf-data))
expect ["Cindy"]
actual (<! (bq/<query
'[:find [?name ...]
:in $ ?e
:where
[?e :friend ?e2]
[?e2 :name ?name]]
conn
{:box/id "zk"}))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-foaf []
(let [conn (<? (<test-conn foaf-data))
expect ["Cindy"]
actual (<! (bq/<query
'[:find [?name ...]
:where
[?e :name "Zack"]
[?e :friend ?e2]
[?e2 :name ?name]]
conn))
ent (<! (bq/<pull
conn
'[*]
[:box/id "zk"]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]
[(not (nil? ent))
"Pull entity succeeded"]]))
(def dq-basic-datoms
[["sally" "age" 21]
["fred" "age" 42]
["ethel" "age" 42]
["fred" "likes" "pizza"]
["sally" "likes" "opera"]
["ethel" "likes" "sushi"]
["sally" "name" "Sally"]
["fred" "name" "Fred"]
["ethel" "name" "Ethel"]])
(<deftest test-query-basic []
(let [expect [[[:box/id "fred"]]
[[:box/id "ethel"]]]
actual (<! (bq/<query
'[:find ?e
:where
[?e :age 42]]
(<! (<test-conn dq-basic-datoms))))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-unification []
(let [expect [[[:box/id "fred"] "pizza"] [[:box/id "ethel"] "sushi"]]
actual (<! (bq/<query
'[:find ?e ?x
:where [?e :age 42]
[?e :likes ?x]]
(<! (<test-conn dq-basic-datoms))))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-blanks []
(let [expect [["opera"] ["pizza"] ["sushi"]]
actual (<! (bq/<query
'[:find ?x
:where [_ :likes ?x]]
(merge
#_debug-explain
(<! (<test-conn dq-basic-datoms)))))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-sort-desc []
(let [conn (<? (<test-conn dq-basic-datoms))
expect [["Fred" 42] ["Ethel" 42] ["Sally" 21]]
actual (<! (bq/<query
{:dq '[:find [?name ?age]
:where
[?e :age ?age]
[?e :name ?name]]
:sort '[[?age :desc]
[?name :desc]]}
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-sort-asc []
(let [conn (<? (<test-conn dq-basic-datoms))
expect (vec (reverse [["Fred" 42] ["Ethel" 42] ["Sally" 21]]))
actual (<! (bq/<query
{:dq '[:find [?name ?age]
:where
[?e :age ?age]
[?e :name ?name]]
:sort '[[?age :asc]
[?name :asc]]}
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-sort-string []
(let [conn (<? (<test-conn movies-db))
expect [["Veronica Cartwright"] ["Tom Skerritt"] ["Tina Turner"]]
actual (<! (bq/<query
{:dq '[:find [?name]
:where
[_ :person/name ?name]]
:sort '[[?name :desc]]
:limit 3}
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(comment
(test/<run-var-repl #'test-query-sort-string)
)
(<deftest test-query-sort-pull-wrapped []
(let [conn (<? (<test-conn))
_ (<! (bq/<transact
conn
[{:box/id "one"
:box/created-ts 1}
{:box/id "two"
:box/created-ts 2}]))
expect [[{:box/id "two", :box/created-ts 2}]
[{:box/id "one", :box/created-ts 1}]]
actual (<! (bq/<query
{:dq '[:find (pull ?e [*])
:where
[?e :box/id]
[?e :box/created-ts ?ts]]
:sort '[[?ts :desc]]}
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-sort-pull-unwrapped []
(let [conn (<? (<test-conn))
_ (<! (bq/<transact
conn
[{:box/id "one"
:box/created-ts 1}
{:box/id "two"
:box/created-ts 2}]))
expect [{:box/id "two"
:box/created-ts 2}
{:box/id "one"
:box/created-ts 1}]
actual (<! (bq/<query
{:dq '[:find [(pull ?e [*]) ...]
:where
[?e :box/id]
[?e :box/created-ts ?ts]]
:sort '[[?ts :desc]]}
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-limit []
(let [conn (<? (<test-conn dq-basic-datoms))
expect [["Fred" 42] ["Ethel" 42]]
actual (<! (bq/<query
{:dq '[:find [?name ?age]
:where
[?e :age ?age]
[?e :name ?name]]
:sort '[[?age :desc]
[?name :desc]]
:limit 2}
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-offset []
(let [conn (<? (<test-conn dq-basic-datoms))
expect [["Ethel" 42] ["Sally" 21]]
actual (<! (bq/<query
{:dq '[:find [?name ?age]
:where
[?e :age ?age]
[?e :name ?name]]
:sort '[[?age :desc]
[?name :desc]]
:offset 1}
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-parent-ref []
(let [conn (<? (<test-conn refs-datoms))
expect [[[:box/id "four"]] [[:box/id "three"]]]
actual (<! (bq/<query
{:dq '[:find ?e
:in $ ?p
:where
[?e :box/updated-ts]
[?p :box/refs ?e]]}
conn
{:box/id "one"}))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-missing-attr []
(let [conn (<? (<test-conn refs-datoms))
expect [[[:box/id "one"]]
[[:box/id "seven"]]
[[:box/id "six"]]
[[:box/id "two"]]]
actual (<! (bq/<query
{:dq '[:find ?e
:where
[?e]
(not
[_ :box/refs ?e])]}
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-order-by []
(let [conn (<? (<test-conn refs-datoms))
expect [[[:box/id "two"]]
[[:box/id "one"]]]
actual (<! (bq/<query
{:dq '[:find ?e
:where
[?e]
#_[?e :box/created-ts]
(not
[_ :box/refs ?e])
[?e :box/created-ts ?ts]]
:sort '[[?ts :desc]]
}
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(defn rq []
(gol
(bq/<sql
(<? (<test-conn refs-datoms))
["SELECT DISTINCT c0.ENTITY AS \"?e\" FROM datoms AS c0
LEFT JOIN datoms AS c1 ON c0.ENTITY=c1.VALUE
--EXCEPT
--SELECT DISTINCT c0.ENTITY AS \"?e\" FROM datoms AS c0
--INNER JOIN datoms AS c1 ON c0.ENTITY=c1.VALUE
--WHERE c1.ATTR=?"
#_"box/refs"]
)))
(comment
(test/<run-var-repl #'test-query-order-by)
(rq)
)
(deftest test-edn-ch-0 []
(go
(let [expect [["Alien"]
["Aliens"]
["Braveheart"]
["Commando"]
["Die Hard"]
["First Blood"]
["Lethal Weapon"]
["Lethal Weapon 2"]
["Lethal Weapon 3"]
["Mad Max"]
["Mad Max 2"]
["Mad Max Beyond Thunderdome"]
["Predator"]
["Predator 2"]
["Rambo III"]
["Rambo: First Blood Part II"]
["RoboCop"]
["Terminator 2: Judgment Day"]
["Terminator 3: Rise of the Machines"]
["The Terminator"]]
actual (<! (bq/<query
'[:find ?title
:where
[_ :movie/title ?title]]
(<! (<test-conn movies-db))))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(deftest test-basic-queries-ch-1-0 []
(go
(let [expect [[[:box/id "-202"]]
[[:box/id "-203"]]
[[:box/id "-204"]]]
actual (<! (bq/<query
'[:find ?e
:where
[?e :movie/year 1987]]
(<! (<test-conn movies-db))))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(deftest test-basic-queries-ch-1-1 []
(go
(let [expect [[[:box/id "-200"] "The Terminator"]
[[:box/id "-201"] "First Blood"]
[[:box/id "-202"] "Predator"]
[[:box/id "-203"] "Lethal Weapon"]
[[:box/id "-204"] "RoboCop"]
[[:box/id "-205"] "Commando"]
[[:box/id "-206"] "Die Hard"]
[[:box/id "-207"] "Terminator 2: Judgment Day"]
[[:box/id "-208"] "Terminator 3: Rise of the Machines"]
[[:box/id "-209"] "Rambo: First Blood Part II"]
[[:box/id "-210"] "Rambo III"]
[[:box/id "-211"] "Predator 2"]
[[:box/id "-212"] "Lethal Weapon 2"]
[[:box/id "-213"] "Lethal Weapon 3"]
[[:box/id "-214"] "Alien"]
[[:box/id "-215"] "Aliens"]
[[:box/id "-216"] "Mad Max"]
[[:box/id "-217"] "Mad Max 2"]
[[:box/id "-218"] "Mad Max Beyond Thunderdome"]
[[:box/id "-219"] "Braveheart"]]
actual (<! (bq/<query
'[:find ?e ?title
:where
[?e :movie/title ?title]]
(<! (<test-conn movies-db))))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(deftest test-basic-queries-ch-1-2 []
(go
(let [expect [["Alan Rickman"]
["Alexander Godunov"]
["Alyssa Milano"]
["Arnold Schwarzenegger"]
["Brian Dennehy"]
["Bruce Spence"]
["Bruce Willis"]
["Carl Weathers"]
["Carrie Henn"]
["Charles Napier"]
["Claire Danes"]
["Danny Glover"]
["Edward Furlong"]
["Elpidia Carrillo"]
["Gary Busey"]
["George Miller"]
["George Ogilvie"]
["George P. Cosmatos"]
["James Cameron"]
["Joanne Samuel"]
["Joe Pesci"]
["John McTiernan"]
["Jonathan Mostow"]
["Linda Hamilton"]
["Marc de Jonge"]
["Mark L. Lester"]
["Mel Gibson"]
["Michael Biehn"]
["Michael Preston"]
["Nancy Allen"]
["Nick Stahl"]
["Paul Verhoeven"]
["Peter MacDonald"]
["Peter Weller"]
["Rae Dawn Chong"]
["Richard Crenna"]
["Richard Donner"]
["Ridley Scott"]
["Robert Patrick"]
["Ronny Cox"]
["Ruben Blades"]
["Sigourney Weaver"]
["Sophie Marceau"]
["Stephen Hopkins"]
["Steve Bisley"]
["Sylvester Stallone"]
["Ted Kotcheff"]
["Tina Turner"]
["Tom Skerritt"]
["Veronica Cartwright"]]
actual (<! (bq/<query
'[:find ?name
:where
[?p :person/name ?name]]
(merge
(<! (<test-conn movies-db))
#_debug-explain)))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(deftest test-dpat-ch-2-0 []
(go
(let [expect [["Commando"]
["Mad Max Beyond Thunderdome"]
["Rambo: First Blood Part II"]]
actual (<! (bq/<query
'[:find ?title
:where
[?m :movie/title ?title]
[?m :movie/year 1985]]
(merge
(<! (<test-conn movies-db))
#_debug-explain)))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(deftest test-dpat-ch-2-1 []
(go
[[(= (<! (bq/<query
'[:find ?year
:where
[?m :movie/title "Alien"]
[?m :movie/year ?year]]
(<! (<test-conn movies-db))))
[[1979]])]]))
(deftest test-dpat-ch-2-2 []
(go
[[(= (<! (bq/<query
'[:find ?name
:where
[?m :movie/title "RoboCop"]
[?m :movie/director ?d]
[?d :person/name ?name]]
(<! (<test-conn movies-db))))
[["Paul Verhoeven"]])]]))
(deftest test-dpat-ch-2-3 []
(go
(let [expect [["James Cameron"]
["John McTiernan"]
["Jonathan Mostow"]
["Mark L. Lester"]]
actual (<! (bq/<query
'[:find ?name
:where
[?p :person/name "Arnold Schwarzenegger"]
[?m :movie/cast ?p]
[?m :movie/director ?d]
[?d :person/name ?name]]
(merge
#_debug-explain
(<! (<test-conn movies-db)))))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(deftest test-param-queries-ch-3-0 []
(go
[[(= (<! (bq/<query
'[:find ?title
:in $ ?year
:where
[?m :movie/year ?year]
[?m :movie/title ?title]]
(<! (<test-conn movies-db))
1988))
[["Die Hard"] ["Rambo III"]])]]))
(deftest test-param-queries-ch-3-1 []
(go
(let [res (<! (bq/<query
'[:find ?title ?year
:in $ [?title ...]
:where
[?m :movie/title ?title]
[?m :movie/year ?year]]
(<! (<test-conn movies-db))
["Lethal Weapon" "Lethal Weapon 2" "Lethal Weapon 3"]))
target [["Lethal Weapon" 1987]
["Lethal Weapon 2" 1989]
["Lethal Weapon 3" 1992]]]
[[(= res target)
{:res res
:target target}]])))
(deftest test-param-queries-ch-3-2 []
(go
(let [conn (<! (<test-conn movies-db))
expect [["Aliens"] ["The Terminator"]]
actual (<! (bq/<query
'[:find ?title
:in $ ?actor ?director
:where
[?a :person/name ?actor]
[?d :person/name ?director]
[?m :movie/cast ?a]
[?m :movie/director ?d]
[?m :movie/title ?title]]
(merge
conn
#_debug-explain)
"Michael Biehn"
"James Cameron"))]
#_(<! (<dump-conn conn))
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(deftest test-more-queries-ch-4-0 []
(go
(let [expect [["movie/title"]
["movie/year"]
["movie/director"]
["movie/cast"]
["trivia"]]
actual (<! (bq/<query
'[:find ?attr
:in $ ?title
:where
[?m :movie/title ?title]
[?m ?attr]]
(<! (<test-conn movies-db))
"Commando"))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(deftest test-more-queries-ch-4-1 []
(go
(let [expect (vec
(reverse
[["Alexander Godunov"]
["Alan Rickman"]
["Bruce Willis"]
["John McTiernan"]]))
actual (<! (bq/<query
'[:find ?name
:in $ ?title [?attr ...]
:where
[?m :movie/title ?title]
[?m ?attr ?p]
[?p :person/name ?name]]
(merge
(<! (<test-conn movies-db))
{::bsql/debug-explain-query? false})
"Die Hard"
[:movie/cast :movie/director]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(<deftest test-pred-ch-5-0 []
(let [expect [["Alien"] ["Mad Max"]]
actual (<? (bq/<query
'[:find ?title
:in $ ?year
:where
[?m :movie/title ?title]
[?m :movie/year ?y]
[(<= ?y ?year)]]
(<! (<test-conn movies-db))
1979))]
[[(= expect actual)
nil
{:expect expect
:actual nil #_ actual}]]))
(deftest test-pred-ch-5-1 []
(go
(let [actual (<! (bq/<query
'[:find ?actor
:where
[?d :person/name "Danny Glover"]
[?d :person/born ?b1]
[?e :person/born ?b2]
[_ :movie/cast ?e]
[(< ?b2 ?b1)]
[?e :person/name ?actor]]
(merge
(<! (<test-conn movies-db))
#_debug-explain)))
expect [["Alan Rickman"]
["Brian Dennehy"]
["Bruce Spence"]
["Charles Napier"]
["Gary Busey"]
["Joe Pesci"]
["Michael Preston"]
["Richard Crenna"]
["Ronny Cox"]
["Sylvester Stallone"]
["Tina Turner"]
["Tom Skerritt"]]]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(<deftest test-not-equals []
(let [conn (<? (<test-conn movies-db))
result (<! (bq/<query
'[:find ?title
:in $ ?year
:where
[?m :movie/title ?title]
[?m :movie/year ?y]
[(!= ?y ?year)]]
conn
1979))
expect [["Aliens"]
["Braveheart"]
["Commando"]
["Die Hard"]
["First Blood"]
["Lethal Weapon"]
["Lethal Weapon 2"]
["Lethal Weapon 3"]
["Mad Max 2"]
["Mad Max Beyond Thunderdome"]
["Predator"]
["Predator 2"]
["Rambo III"]
["Rambo: First Blood Part II"]
["RoboCop"]
["Terminator 2: Judgment Day"]
["Terminator 3: Rise of the Machines"]
["The Terminator"]]]
[[(= expect result)
nil
{:expect expect
:result result}]]))
(<deftest test-not []
[[true]]
#_(let [conn (<? (<test-conn refs-datoms))
result (<? (bq/<query
'[:find ?e
:where
[?e :box/id]
[?p :box/refs ?e]
#_[(missing? ?p :box/refs)]]
conn))
expect [[:box/id "one"]]]
[[(= expect result)
nil
{:expect expect
:result result}]]))
(comment
(test/<run-var-repl #'test-not)
)
(deftest test-inline-pull-query []
(go
(let [result (<! (bq/<query
'[:find (pull ?e [:box/created-ts])
:where
[?e :box/created-ts 1000]]
(<! (<test-conn refs-datoms))))
expect [[{:box/id "one", :box/created-ts 1000}]]]
[[(= expect result)
nil
{:expect expect
:result result}]])))
(<deftest test-nested-inline-pull-query []
(let [result (<! (bq/<query
'[:find [(pull ?e [:box/created-ts]) ...]
:where
[?e :box/created-ts 1000]]
(<? (<test-conn refs-datoms))))
expect [{:box/id "one", :box/created-ts 1000}]]
[[(= expect result)
nil
{:expect expect
:result result}]]))
(<deftest test-inline-pull-query-error []
(let [result (<! (bq/<query
'[:find (pull ?e '[*])
:where
[?e :box/created-ts]]
(<! (<test-conn refs-datoms))))]
[[(anom/? result)
nil
{:result result}]]))
(deftest test-param-pull-query []
(go
(let [result (<! (bq/<query
'[:find (pull ?e pat)
:in $ pat
:where
[?e :box/created-ts 1000]]
(<! (<test-conn refs-datoms))
[:box/created-ts]))
expect [[{:box/id "one", :box/created-ts 1000}]]]
[[(= expect result)
nil
{:expect expect
:result result}]])))
(comment
(test/<run-var-repl #'test-param-pull-query)
)
(<deftest test-like-query []
(let [result (<! (bq/<query
'[:find ?text
:in $ ?ts ?like-query
:where
[?e :box/created-ts ?ts]
[?e :box/text ?text]
[(sql-like ?text ?like-query)]]
(<? (<test-conn refs-datoms))
1000
"%ith%"))
expect [["hithere"]]]
[[(= expect result)
nil
{:expect expect
:result result}]]))
(<deftest test-bool-query-true []
(let [result (<! (bq/<query
'[:find ?e
:where
[?e :box/bool? true]]
(<? (<test-conn refs-datoms))))
expect [[[:box/id "six"]]]]
[[(= expect result)
nil
{:expect expect
:result result}]]))
(<deftest test-bool-query-false []
(let [result (<! (bq/<query
'[:find ?e
:where
[?e :box/bool? false]]
(<? (<test-conn refs-datoms))))
expect [[[:box/id "seven"]]]]
[[(= expect result)
nil
{:expect expect
:result result}]]))
(comment
(test/<run-var-repl #'test-bool-query-false)
)
(deftest test-ident-param []
(go
(let [conn (<! (<test-conn refs-datoms))
result (<! (bq/<query
'[:find (pull ?e [*])
:in $ ?child
:where
[?e :box/refs ?child]]
conn
[:box/id "five"]))
expect [[{:box/id "two",
:box/updated-ts 2000,
:box/created-ts 2000
:box/refs [{:box/id "five"}]}]]]
[[(= expect result)
nil
{:expect expect
:result result}]])))
(deftest test-ident-param-multi []
(go
(let [result (<! (bq/<query
'[:find (pull ?e [*])
:in $ [?child ...]
:where
[?e :box/refs ?child]]
(<! (<test-conn refs-datoms))
[[:box/id "five"]
[:box/id "two"]]))
expect [[{:box/id "two",
:box/updated-ts 2000,
:box/created-ts 2000
:box/refs [{:box/id "five"}]}]]]
[[(= expect result)
nil
{:expect expect
:result result}]])))
;; Pull
(<deftest test-pull-entity []
(let [expect
{:box/id "one",
:box/created-ts 1000,
:box/updated-ts 1000,
:box/text "hithere",
:box/ref {:box/id "two"},
:box/refs [{:box/id "three"} {:box/id "four"}]}
actual
(<! (bq/<pull
(merge
test-schema
(<? (<test-conn refs-datoms)))
'[*]
{:box/id "one"}))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-pull-wildcard []
(let [expect
{:box/id "one",
:box/created-ts 1000,
:box/updated-ts 1000,
:box/text "hithere",
:box/ref {:box/id "two"},
:box/refs [{:box/id "three"} {:box/id "four"}]}
actual
(<! (bq/<pull
(merge
test-schema
(<? (<test-conn refs-datoms)))
'[*]
[:box/id "one"]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-pull-empty []
(let [conn (<! (<test-conn))
_ (<? (bq/<transact
conn
[[:box/assoc [:box/id "one"] :box/text "hi"]]))
expect []
actual
(<! (bq/<query
'[:find (pull ?e [:box/none])
:where
[?e :box/id "one"]]
(merge
test-schema
conn)))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(deftest test-pull-attrs []
(go
(let [expect
{:box/id "one",
:box/created-ts 1000}
actual
(<! (bq/<pull
(merge
test-schema
(<! (<test-conn refs-datoms)))
'[:box/created-ts]
[:box/id "one"]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(deftest test-pull-single-ref []
(go
(let [expect
{:box/id "one",
:box/created-ts 1000,
:box/updated-ts 1000,
:box/text "hithere",
:box/ref
{:box/id "two",
:box/updated-ts 2000,
:box/created-ts 2000,
:box/refs [{:box/id "five"}]},
:box/refs [{:box/id "three"} {:box/id "four"}]}
actual
(<! (bq/<pull
(merge
test-schema
(<! (<test-conn refs-datoms)))
'[*
{:box/ref [*]}]
[:box/id "one"]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(<deftest test-pull-multi-ref []
(let [expect
{:box/id "one",
:box/created-ts 1000,
:box/updated-ts 1000,
:box/text "hithere",
:box/ref {:box/id "two"},
:box/refs
[{:box/id "three", :box/created-ts 3000, :box/updated-ts 3000}
{:box/id "four", :box/created-ts 4000, :box/updated-ts 4000}]}
actual
(<! (bq/<pull
(merge
test-schema
(<? (<test-conn refs-datoms)))
'[*
{:box/refs [*]}]
[:box/id "one"]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(deftest test-pull-multi-ref-limit []
(go
(let [expect
{:box/id "one",
:box/created-ts 1000,
:box/ref {:box/id "two"},
:box/refs
[{:box/id "three", :box/created-ts 3000}]}
actual
(<! (bq/<pull
(merge
test-schema
(<! (<test-conn refs-datoms)))
'[*
{(limit :box/refs 1) [*]}]
[:box/id "one"]))]
[[true]]
#_[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(<deftest test-pull-multi []
(let [expect
[{:box/id "one",
:box/created-ts 1000}
{:box/id "two",
:box/created-ts 2000}]
actual
(<! (bq/<pull-multi
(merge
test-schema
(<? (<test-conn refs-datoms)))
'[:box/created-ts]
[{:box/id "one"}
{:box/id "two"}]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-transact-basic []
(let [conn (<? (<test-conn))
_ (<! (bq/<transact
(merge
test-schema
conn)
[[:box/assoc
[:box/id "one"]
:box/created-ts
1000]
{:box/id "two"
:box/ref {:box/id "three"
:box/created-ts 3000}
:box/refs [{:box/id "four"
:box/created-ts 4000}
{:box/id "five"
:box/created-ts 5000}]
:box/created-ts 2000}]))
expect [[:box/id "one"]]
actual (<! (bq/<query
'[:find [?e ...]
:where
[?e :box/created-ts 1000]]
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-transact-bool []
(let [conn (<? (<test-conn))
_ (<! (bq/<transact
(merge
test-schema
conn)
[[:box/assoc
[:box/id "one"]
:box/bool?
false]
[:box/assoc
[:box/id "two"]
:box/bool?
true]]))
expect [[:box/id "one"]]
actual (<! (bq/<query
'[:find [?e ...]
:where
[?e :box/bool? false]]
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(comment
(test/<run-var-repl #'test-transact-bool)
)
(<deftest test-transact-dissoc []
(let [conn (<? (<test-conn refs-datoms))
_ (<? (bq/<transact
(merge
test-schema
conn)
[[:box/dissoc
[:box/id "one"]
:box/refs
[:box/id "three"]]]))
expect [{:box/id "one",
:box/refs [{:box/id "four"}]}]
actual (<? (bq/<query
'[:find [(pull ?e [:box/refs]) ...]
:where
[?e :box/id "one"]]
conn))]
#_(bq/<inspect-conn conn)
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-transact-ref-maps []
;; transact should _not_ expand entities in txfs like :box/assoc etc
(let [conn (merge
(<? (<test-conn))
{::bsql/debug-explain-query? false})
_ (<! (bq/<transact
(merge
test-schema
conn)
[[:box/assoc
{:box/id "one"}
:box/ref
{:box/id "two"
:box/created-ts 2000}]]))
actual (<! (bq/<pull
conn
'[*
{:box/ref [*]}]
[:box/id "one"]))
expect {:box/id "one", :box/ref {:box/id "two"}}]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(deftest test-transact-nested-single []
(go
(let [conn (merge
(<! (<test-conn))
{::bsql/debug-explain-query? false})
_ (<! (bq/<transact
(merge
test-schema
conn)
[{:box/id "two"
:box/ref {:box/id "three"
:box/created-ts 3000}
:box/refs [{:box/id "four"
:box/created-ts 4000}
{:box/id "five"
:box/created-ts 5000}]
:box/created-ts 2000}]))
expect [3000]
actual (<! (bq/<query
'[:find [?created-ts ...]
:where
[[:box/id "three"] :box/created-ts ?created-ts]]
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(deftest test-transact-nested-multi []
(go
(let [conn (<! (<test-conn))
_ (<! (bq/<transact
(merge
test-schema
conn)
[{:box/id "two"
:box/ref {:box/id "three"
:box/created-ts 3000}
:box/refs [{:box/id "four"
:box/created-ts 4000}
{:box/id "five"
:box/created-ts 5000}]
:box/created-ts 2000}]))
expect [5000]
actual (<! (bq/<query
'[:find [?created-ts ...]
:where
["five" :box/created-ts ?created-ts]]
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(<deftest test-transact-data-types []
(let [conn (<? (<test-conn))
transact-res
(<! (bq/<transact
(merge
test-schema
conn)
[{:box/id "one"
:box/string "hello"
:box/long 123
:box/double 1.23
:box/bool true
:box/map {:foo "bar"}
:box/vec [1 2 3]
:box/list '(1 2 3)
:box/keyword :keyword}]))
expect {:box/id "one",
:box/vec [1 2 3],
:box/list '(1 2 3),
:box/string "hello",
:box/bool true,
:box/map {:foo "bar"},
:box/double 1.23,
:box/long 123
:box/keyword :keyword}
actual (<! (bq/<pull
conn
'[*]
[:box/id "one"]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]
[(not (anom/? transact-res))
nil
transact-res]]))
(<deftest test-transact-delete []
(let [conn (<? (<test-conn))
_ (<? (bq/<transact
conn
[{:box/id "one"
:box/string "hello"
:box/long 123
:box/double 1.23
:box/bool true
:box/map {:foo "bar"}
:box/vec [1 2 3]
:box/list '(1 2 3)}
[:box/delete [:box/id "one"]]
{:box/id "one"
:box/string "goodbye"}]))
_ (<? (bq/<transact
conn
[]))
expect {:box/id "one"
:box/string "goodbye"}
actual (<! (bq/<pull
conn
'[*]
[:box/id "one"]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-transact-delete-ref []
(let [conn (<? (<test-conn))
_ (<? (bq/<transact
conn
[{:box/id "one"
:box/refs [{:box/id "two"}
{:box/id "three"}]}
[:box/delete [:box/id "two"]]]))
expect {:box/id "one",
:box/refs [{:box/id "three"}]}
actual (<! (bq/<pull
conn
'[*]
[:box/id "one"]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-transact-zeros-string
[]
(let [conn (<? (<test-conn))
_ (<! (bq/<transact
(merge
test-schema
conn)
[[:box/assoc
[:box/id "one"]
:box/title
"000"]]))
expect {:box/id "one"
:box/title "000"}
actual (<! (bq/<pull
conn
'[:box/title]
[:box/id "one"]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(comment
(test/<run-var-repl #'test-transact-zeros-string)
)
;; Reagent stuff
#_(<deftest test-reagent []
(let [conn (<? (<test-conn refs-datoms))
id (ks/uuid)
ratom (<? (br/<tracked-query
id
'[:find ?e
:where
[?e :box/created-ts]]
conn))
res1 @ratom
_ (<? (br/<transact
conn
[[:box/delete [:box/id "one"]]]))
res2 @ratom
expect [[[:box/id "two"]]
[[:box/id "three"]]
[[:box/id "four"]]
[[:box/id "five"]]]]
[[(= expect res2)
nil
{:res2 res2
:expect expect}]]))
(comment
(go
(let [conn (<! (<test-conn))]
(<! (bq/<transact
(merge
test-schema
conn)
[[:box/assoc
[:box/id "one"]
:box/created-ts
1000]
{:box/id "two"
:box/ref {:box/id "three"
:box/created-ts 3000}
:box/refs [{:box/id "four"
:box/created-ts 4000}
{:box/id "five"
:box/created-ts 5000}]
:box/created-ts 2000}]))
(ks/pp (<! (bq/<query
'[:find [?e ...]
:where
[?e :box/created-ts 1000]]
conn)))))
)
(comment
(test/<run-var-repl #'test-pred-ch-5-0)
(test/<run-var-repl #'test-pull-multi-ref)
(test/<run-ns-repl 'rx.node.box2.tests)
;; https://docs.datomic.com/on-prem/query.html
;; http://www.learndatalogtoday.org/
;; punt test-param-queries-ch-3-3
;; punt test-more-queries-ch-4-2 & 3
;; punt test-pred-ch-5-2 & 3
;; punt tranformation functions ch 6
;; punt aggregates
;; punt rules
(go
(ks/pp
(let [conn (<! (<test-conn refs-datoms))]
(<! (sql/<exec
(::bsql/db conn)
["SELECT DISTINCT c0.ENTITY AS \"?e\" FROM datoms AS c0
INNER JOIN datoms AS c1 ON c0.ENTITY=c1.VALUE WHERE NOT c1.ATTR=? AND c0.ENTITY!=c1.VALUE"
"box/refs"])))))
(go
(ks/pp
(let [conn (<! (<test-conn refs-datoms))]
(<! (sql/<exec
(::bsql/db conn)
[(str "SELECT DISTINCT c0.ENTITY as c0ent, c0.ATTR as c0attr, c0.VALUE as c0val, c1.ENTITY as c1ent, c1.ATTR as c1attr, c1.VALUE as c1val from datoms" " AS c0 INNER JOIN datoms AS c1 ON c0.ENTITY=c1.VALUE")])))))
(go
(ks/pp
(let [conn (<! (<test-conn refs-datoms))]
(<! (sql/<exec
(::bsql/db conn)
["
SELECT DISTINCT c0.ENTITY AS \"?e\" FROM datoms AS c0
EXCEPT
SELECT DISTINCT c0.VALUE AS \"?e\" FROM datoms AS c0 WHERE c0.ATTR=?
"
"box/refs"])))))
)
| 90144 | (ns rx.node.box2.tests
(:require [rx.kitchen-sink :as ks]
[rx.box2 :as bq]
[rx.box2.sql :as bsql]
#_[rx.box2.reagent :as br]
[rx.node.sqlite2 :as sql]
[rx.test :as test
:refer-macros [deftest
<deftest]]
[rx.anom :as anom
:refer-macros [<defn <? gol]]
[datascript.query :as dsq]
[datascript.query-v3 :as dsqv3]
[clojure.core.async :as async
:refer [go <!]]))
(def debug-explain
{::bsql/debug-explain-query? true})
(def test-schema {:box/schema
{:box/attrs
[{:box/attr :box/id
:box/ident? true
:box/value-type :box/string}
{:box/attr :box/ref
:box/ref? true
:box/cardinality :box/cardinality-one}
{:box/attr :box/refs
:box/ref? true
:box/cardinality :box/cardinality-many}
{:box/attr :box/updated-ts
:box/index? true
:box/value-type :box/long}
{:box/attr :box/created-ts
:box/index? true
:box/value-type :box/long}]}})
(<defn <test-conn [& [datoms]]
(let [db (<! (sql/<open-db {:name ":memory:"}))]
(anom/throw-if-anom
(<! (sql/<exec db [(bq/create-datoms-sql)])))
(anom/throw-if-anom
(<! (sql/<batch-exec db (bq/create-indexes-sql-vecs))))
(when datoms
(anom/throw-if-anom
(<! (sql/<batch-exec db (bq/insert-datoms-sqls datoms)))))
(merge
{::bsql/db db
::bsql/<exec sql/<exec
::bsql/<batch-exec sql/<batch-exec}
test-schema)))
(defn <dump-conn [{:keys [::bsql/db
::bsql/<exec]}]
(go
(ks/pp
(<! (<exec db ["select * from datoms"])))))
(defn <run-sql [{:keys [::bsql/db
::bsql/<exec]}
sql-vec]
(go
(ks/spy
"RUN SQL"
(<! (<exec db sql-vec)))))
(def foaf-data
[[[:box/id "zk"] "name" "<NAME>" false]
[[:box/id "cindy"] "name" "<NAME>" false]
[[:box/id "zk"] "friend" [:box/id "cindy"] true true]])
(def refs-datoms
[[[:box/id "one"] :box/id "one"]
[[:box/id "one"] :box/created-ts 1000]
[[:box/id "one"] :box/updated-ts 1000]
[[:box/id "one"] :box/text "hithere"]
[[:box/id "one"] :box/ref [:box/id "two"] true]
[[:box/id "two"] :box/id "two"]
[[:box/id "two"] :box/updated-ts 2000]
[[:box/id "two"] :box/created-ts 2000]
[[:box/id "three"] :box/id "three"]
[[:box/id "three"] :box/created-ts 3000]
[[:box/id "three"] :box/updated-ts 3000]
[[:box/id "four"] :box/id "four"]
[[:box/id "four"] :box/created-ts 4000]
[[:box/id "four"] :box/updated-ts 4000]
[[:box/id "one"] :box/refs [:box/id "three"] true true]
[[:box/id "one"] :box/refs [:box/id "four"] true true]
[[:box/id "five"] :box/id "five"]
[[:box/id "five"] :box/created-ts 5000]
[[:box/id "two"] :box/refs [:box/id "five"] true true]
[[:box/id "six"] :box/id "six"]
[[:box/id "six"] :box/bool? true]
[[:box/id "seven"] :box/id "seven"]
[[:box/id "seven"] :box/bool? false]])
(def movies-db
[[[:box/id -100] "person/name" "<NAME>" nil nil]
[[:box/id -100] "person/born" -485308800000 nil nil]
[[:box/id -101] "person/name" "<NAME>" nil nil]
[[:box/id -101] "person/born" -707702400000 nil nil]
[[:box/id -102] "person/name" "<NAME>" nil nil]
[[:box/id -102] "person/born" -418608000000 nil nil]
[[:box/id -103] "person/name" "<NAME>" nil nil]
[[:box/id -103] "person/born" -423532800000 nil nil]
[[:box/id -104] "person/name" "<NAME>" nil nil]
[[:box/id -104] "person/born" -1222473600000 nil nil]
[[:box/id -105] "person/name" "<NAME>" nil nil]
[[:box/id -105] "person/born" -741312000000 nil nil]
[[:box/id -106] "person/name" "<NAME>" nil nil]
[[:box/id -106] "person/born" -1359763200000 nil nil]
[[:box/id -106] "person/death" 1042761600000 nil nil]
[[:box/id -107] "person/name" "<NAME>" nil nil]
[[:box/id -107] "person/born" -993513600000 nil nil]
[[:box/id -108] "person/name" "<NAME>" nil nil]
[[:box/id -108] "person/born" -599011200000 nil nil]
[[:box/id -109] "person/name" "<NAME>" nil nil]
[[:box/id -109] "person/born" -264384000000 nil nil]
[[:box/id -110] "person/name" "<NAME>" nil nil]
[[:box/id -110] "person/born" -693187200000 nil nil]
[[:box/id -111] "person/name" "<NAME>" nil nil]
[[:box/id -111] "person/born" -1252540800000 nil nil]
[[:box/id -112] "person/name" "<NAME>" nil nil]
[[:box/id -112] "person/born" -441676800000 nil nil]
[[:box/id -113] "person/name" "<NAME>" nil nil]
[[:box/id -113] "person/born" -739929600000 nil nil]
[[:box/id -114] "person/name" "<NAME>" nil nil]
[[:box/id -114] "person/born" -802396800000 nil nil]
[[:box/id -115] "person/name" "<NAME>" nil nil]
[[:box/id -115] "person/born" -992736000000 nil nil]
[[:box/id -116] "person/name" "<NAME>" nil nil]
[[:box/id -116] "person/born" -710812800000 nil nil]
[[:box/id -117] "person/name" "<NAME>" nil nil]
[[:box/id -117] "person/born" -616118400000 nil nil]
[[:box/id -118] "person/name" "<NAME>" nil nil]
[[:box/id -118] "person/born" -992304000000 nil nil]
[[:box/id -119] "person/name" "<NAME>" nil nil]
[[:box/id -119] "person/born" -728956800000 nil nil]
[[:box/id -120] "person/name" "<NAME>" nil nil]
[[:box/id -120] "person/born" -278985600000 nil nil]
[[:box/id -121] "person/name" "<NAME>" nil nil]
[[:box/id -121] "person/born" 93571200000 nil nil]
[[:box/id -122] "person/name" "<NAME>" nil nil]
[[:box/id -122] "person/born" -466732800000 nil nil]
[[:box/id -123] "person/name" "<NAME>" nil nil]
[[:box/id -123] "person/born" -752976000000 nil nil]
[[:box/id -124] "person/name" "<NAME>" nil nil]
[[:box/id -124] "person/born" -634089600000 nil nil]
[[:box/id -124] "person/death" 800755200000 nil nil]
[[:box/id -125] "person/name" "<NAME>" nil nil]
[[:box/id -125] "person/born" -352080000000 nil nil]
[[:box/id -126] "person/name" "<NAME>" nil nil]
[[:box/id -126] "person/born" 239328000000 nil nil]
[[:box/id -127] "person/name" "<NAME>" nil nil]
[[:box/id -127] "person/born" -255398400000 nil nil]
[[:box/id -128] "person/name" "<NAME>" nil nil]
[[:box/id -128] "person/born" 313200000000 nil nil]
[[:box/id -129] "person/name" "<NAME>" nil nil]
[[:box/id -129] "person/born" 292723200000 nil nil]
[[:box/id -130] "person/name" "<NAME>" nil nil]
[[:box/id -130] "person/born" -914889600000 nil nil]
[[:box/id -130] "person/death" 1113868800000 nil nil]
[[:box/id -131] "person/name" "<NAME>" nil nil]
[[:box/id -131] "person/born" -1064188800000 nil nil]
[[:box/id -131] "person/death" 1317772800000 nil nil]
[[:box/id -132] "person/name" "<NAME>" nil nil]
[[:box/id -133] "person/name" "<NAME>" nil nil]
[[:box/id -133] "person/born" -658713600000 nil nil]
[[:box/id -133] "person/death" 834019200000 nil nil]
[[:box/id -134] "person/name" "<NAME>" nil nil]
[[:box/id -135] "person/name" "<NAME>" nil nil]
[[:box/id -135] "person/born" -677289600000 nil nil]
[[:box/id -136] "person/name" "<NAME>" nil nil]
[[:box/id -136] "person/born" -848707200000 nil nil]
[[:box/id -137] "person/name" "<NAME>" nil nil]
[[:box/id -137] "person/born" -1012608000000 nil nil]
[[:box/id -138] "person/name" "<NAME>" nil nil]
[[:box/id -138] "person/born" -1147219200000 nil nil]
[[:box/id -139] "person/name" "<NAME>" nil nil]
[[:box/id -139] "person/born" -638496000000 nil nil]
[[:box/id -140] "person/name" "<NAME>" nil nil]
[[:box/id -140] "person/born" -653270400000 nil nil]
[[:box/id -141] "person/name" "<NAME>" nil nil]
[[:box/id -142] "person/name" "<NAME>" nil nil]
[[:box/id -142] "person/born" -783648000000 nil nil]
[[:box/id -143] "person/name" "<NAME>" nil nil]
[[:box/id -143] "person/born" -568598400000 nil nil]
[[:box/id -144] "person/name" "<NAME>" nil nil]
[[:box/id -145] "person/name" "<NAME>" nil nil]
[[:box/id -145] "person/born" -998352000000 nil nil]
[[:box/id -146] "person/name" "<NAME>" nil nil]
[[:box/id -146] "person/born" -766540800000 nil nil]
[[:box/id -147] "person/name" "<NAME>" nil nil]
[[:box/id -147] "person/born" -1225324800000 nil nil]
[[:box/id -148] "person/name" "<NAME>" nil nil]
[[:box/id -148] "person/born" -949881600000 nil nil]
[[:box/id -149] "person/name" "<NAME>" nil nil]
[[:box/id -149] "person/born" -98582400000 nil nil]
[[:box/id -200] "movie/title" "The Terminator" nil nil]
[[:box/id -200] "movie/year" 1984 nil nil]
[[:box/id -200] "movie/director" [:box/id -100] true nil]
[[:box/id -200] "movie/cast" [:box/id -101] true true]
[[:box/id -200] "movie/cast" [:box/id -102] true true]
[[:box/id -200] "movie/cast" [:box/id -103] true true]
[[:box/id -200] "movie/sequel" [:box/id -207] true nil]
[[:box/id -201] "movie/title" "First Blood" nil nil]
[[:box/id -201] "movie/year" 1982 nil nil]
[[:box/id -201] "movie/director" [:box/id -104] true nil]
[[:box/id -201] "movie/cast" [:box/id -105] true true]
[[:box/id -201] "movie/cast" [:box/id -106] true true]
[[:box/id -201] "movie/cast" [:box/id -107] true true]
[[:box/id -201] "movie/sequel" [:box/id -209] true nil]
[[:box/id -202] "movie/title" "Predator" nil nil]
[[:box/id -202] "movie/year" 1987 nil nil]
[[:box/id -202] "movie/director" [:box/id -108] true nil]
[[:box/id -202] "movie/cast" [:box/id -101] true true]
[[:box/id -202] "movie/cast" [:box/id -109] true true]
[[:box/id -202] "movie/cast" [:box/id -110] true true]
[[:box/id -202] "movie/sequel" [:box/id -211] true nil]
[[:box/id -203] "movie/title" "Lethal Weapon" nil nil]
[[:box/id -203] "movie/year" 1987 nil nil]
[[:box/id -203] "movie/director" [:box/id -111] true nil]
[[:box/id -203] "movie/cast" [:box/id -112] true true]
[[:box/id -203] "movie/cast" [:box/id -113] true true]
[[:box/id -203] "movie/cast" [:box/id -114] true true]
[[:box/id -203] "movie/sequel" [:box/id -212] true nil]
[[:box/id -204] "movie/title" "RoboCop" nil nil]
[[:box/id -204] "movie/year" 1987 nil nil]
[[:box/id -204] "movie/director" [:box/id -115] true nil]
[[:box/id -204] "movie/cast" [:box/id -116] true true]
[[:box/id -204] "movie/cast" [:box/id -117] true true]
[[:box/id -204] "movie/cast" [:box/id -118] true true]
[[:box/id -205] "movie/title" "Commando" nil nil]
[[:box/id -205] "movie/year" 1985 nil nil]
[[:box/id -205] "movie/director" [:box/id -119] true nil]
[[:box/id -205] "movie/cast" [:box/id -101] true true]
[[:box/id -205] "movie/cast" [:box/id -120] true true]
[[:box/id -205] "movie/cast" [:box/id -121] true true]
[[:box/id -205]
"trivia"
"In 1986, a sequel was written with an eye to having\n John McTi<NAME>an direct. Sch<NAME> wasn't interested in reprising\n the role. The script was then reworked with a new central character,\n eventually played by <NAME>, and became Die Hard"
nil
nil]
[[:box/id -206] "movie/title" "Die Hard" nil nil]
[[:box/id -206] "movie/year" 1988 nil nil]
[[:box/id -206] "movie/director" [:box/id -108] true nil]
[[:box/id -206] "movie/cast" [:box/id -122] true true]
[[:box/id -206] "movie/cast" [:box/id -123] true true]
[[:box/id -206] "movie/cast" [:box/id -124] true true]
[[:box/id -207] "movie/title" "Terminator 2: Judgment Day" nil nil]
[[:box/id -207] "movie/year" 1991 nil nil]
[[:box/id -207] "movie/director" [:box/id -100] true nil]
[[:box/id -207] "movie/cast" [:box/id -101] true true]
[[:box/id -207] "movie/cast" [:box/id -102] true true]
[[:box/id -207] "movie/cast" [:box/id -125] true true]
[[:box/id -207] "movie/cast" [:box/id -126] true true]
[[:box/id -207] "movie/sequel" [:box/id -208] true nil]
[[:box/id -208]
"movie/title"
"Terminator 3: Rise of the Machines"
nil
nil]
[[:box/id -208] "movie/year" 2003 nil nil]
[[:box/id -208] "movie/director" [:box/id -127] true nil]
[[:box/id -208] "movie/cast" [:box/id -101] true true]
[[:box/id -208] "movie/cast" [:box/id -128] true true]
[[:box/id -208] "movie/cast" [:box/id -129] true true]
[[:box/id -209] "movie/title" "Rambo: First Blood Part II" nil nil]
[[:box/id -209] "movie/year" 1985 nil nil]
[[:box/id -209] "movie/director" [:box/id -130] true nil]
[[:box/id -209] "movie/cast" [:box/id -105] true true]
[[:box/id -209] "movie/cast" [:box/id -106] true true]
[[:box/id -209] "movie/cast" [:box/id -131] true true]
[[:box/id -209] "movie/sequel" [:box/id -210] true nil]
[[:box/id -210] "movie/title" "<NAME>bo III" nil nil]
[[:box/id -210] "movie/year" 1988 nil nil]
[[:box/id -210] "movie/director" [:box/id -132] true nil]
[[:box/id -210] "movie/cast" [:box/id -105] true true]
[[:box/id -210] "movie/cast" [:box/id -106] true true]
[[:box/id -210] "movie/cast" [:box/id -133] true true]
[[:box/id -211] "movie/title" "Predator 2" nil nil]
[[:box/id -211] "movie/year" 1990 nil nil]
[[:box/id -211] "movie/director" [:box/id -134] true nil]
[[:box/id -211] "movie/cast" [:box/id -113] true true]
[[:box/id -211] "movie/cast" [:box/id -114] true true]
[[:box/id -211] "movie/cast" [:box/id -135] true true]
[[:box/id -212] "movie/title" "Lethal Weapon 2" nil nil]
[[:box/id -212] "movie/year" 1989 nil nil]
[[:box/id -212] "movie/director" [:box/id -111] true nil]
[[:box/id -212] "movie/cast" [:box/id -112] true true]
[[:box/id -212] "movie/cast" [:box/id -113] true true]
[[:box/id -212] "movie/cast" [:box/id -136] true true]
[[:box/id -212] "movie/sequel" [:box/id -213] true nil]
[[:box/id -213] "movie/title" "Lethal Weapon 3" nil nil]
[[:box/id -213] "movie/year" 1992 nil nil]
[[:box/id -213] "movie/director" [:box/id -111] true nil]
[[:box/id -213] "movie/cast" [:box/id -112] true true]
[[:box/id -213] "movie/cast" [:box/id -113] true true]
[[:box/id -213] "movie/cast" [:box/id -136] true true]
[[:box/id -214] "movie/title" "Alien" nil nil]
[[:box/id -214] "movie/year" 1979 nil nil]
[[:box/id -214] "movie/director" [:box/id -137] true nil]
[[:box/id -214] "movie/cast" [:box/id -138] true true]
[[:box/id -214] "movie/cast" [:box/id -139] true true]
[[:box/id -214] "movie/cast" [:box/id -140] true true]
[[:box/id -214] "movie/sequel" [:box/id -215] true nil]
[[:box/id -215] "movie/title" "Aliens" nil nil]
[[:box/id -215] "movie/year" 1986 nil nil]
[[:box/id -215] "movie/director" [:box/id -100] true nil]
[[:box/id -215] "movie/cast" [:box/id -139] true true]
[[:box/id -215] "movie/cast" [:box/id -141] true true]
[[:box/id -215] "movie/cast" [:box/id -103] true true]
[[:box/id -216] "movie/title" "<NAME>" nil nil]
[[:box/id -216] "movie/year" 1979 nil nil]
[[:box/id -216] "movie/director" [:box/id -142] true nil]
[[:box/id -216] "movie/cast" [:box/id -112] true true]
[[:box/id -216] "movie/cast" [:box/id -143] true true]
[[:box/id -216] "movie/cast" [:box/id -144] true true]
[[:box/id -216] "movie/sequel" [:box/id -217] true nil]
[[:box/id -217] "movie/title" "Mad Max 2" nil nil]
[[:box/id -217] "movie/year" 1981 nil nil]
[[:box/id -217] "movie/director" [:box/id -142] true nil]
[[:box/id -217] "movie/cast" [:box/id -112] true true]
[[:box/id -217] "movie/cast" [:box/id -145] true true]
[[:box/id -217] "movie/cast" [:box/id -146] true true]
[[:box/id -217] "movie/sequel" [:box/id -218] true nil]
[[:box/id -218] "movie/title" "Mad Max Beyond Thunderdome" nil nil]
[[:box/id -218] "movie/year" 1985 nil nil]
[[:box/id -218] "movie/director" [:box/id -142] true true]
[[:box/id -218] "movie/director" [:box/id -147] true true]
[[:box/id -218] "movie/cast" [:box/id -112] true true]
[[:box/id -218] "movie/cast" [:box/id -148] true true]
[[:box/id -219] "movie/title" "Braveheart" nil nil]
[[:box/id -219] "movie/year" 1995 nil nil]
[[:box/id -219] "movie/director" [:box/id -112] true true]
[[:box/id -219] "movie/cast" [:box/id -112] true true]
[[:box/id -219] "movie/cast" [:box/id -149] true true]])
(<deftest test-query-entity []
(let [conn (<? (<test-conn foaf-data))
expect ["Cindy"]
actual (<! (bq/<query
'[:find [?name ...]
:in $ ?e
:where
[?e :friend ?e2]
[?e2 :name ?name]]
conn
{:box/id "zk"}))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-foaf []
(let [conn (<? (<test-conn foaf-data))
expect ["Cindy"]
actual (<! (bq/<query
'[:find [?name ...]
:where
[?e :name "<NAME>"]
[?e :friend ?e2]
[?e2 :name ?name]]
conn))
ent (<! (bq/<pull
conn
'[*]
[:box/id "zk"]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]
[(not (nil? ent))
"Pull entity succeeded"]]))
(def dq-basic-datoms
[["<NAME>" "age" 21]
["<NAME>" "age" 42]
["ethel" "age" 42]
["<NAME>" "likes" "pizza"]
["<NAME>" "likes" "opera"]
["<NAME>" "likes" "sushi"]
["<NAME>" "name" "<NAME>"]
["<NAME>" "name" "<NAME>"]
["<NAME>" "name" "<NAME>"]])
(<deftest test-query-basic []
(let [expect [[[:box/id "<NAME>"]]
[[:box/id "<NAME>"]]]
actual (<! (bq/<query
'[:find ?e
:where
[?e :age 42]]
(<! (<test-conn dq-basic-datoms))))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-unification []
(let [expect [[[:box/id "<NAME>"] "pizza"] [[:box/id "ethel"] "sushi"]]
actual (<! (bq/<query
'[:find ?e ?x
:where [?e :age 42]
[?e :likes ?x]]
(<! (<test-conn dq-basic-datoms))))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-blanks []
(let [expect [["opera"] ["pizza"] ["sushi"]]
actual (<! (bq/<query
'[:find ?x
:where [_ :likes ?x]]
(merge
#_debug-explain
(<! (<test-conn dq-basic-datoms)))))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-sort-desc []
(let [conn (<? (<test-conn dq-basic-datoms))
expect [["<NAME>" 42] ["<NAME>" 42] ["<NAME>" 21]]
actual (<! (bq/<query
{:dq '[:find [?name ?age]
:where
[?e :age ?age]
[?e :name ?name]]
:sort '[[?age :desc]
[?name :desc]]}
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-sort-asc []
(let [conn (<? (<test-conn dq-basic-datoms))
expect (vec (reverse [["<NAME>" 42] ["<NAME>" 42] ["<NAME>" 21]]))
actual (<! (bq/<query
{:dq '[:find [?name ?age]
:where
[?e :age ?age]
[?e :name ?name]]
:sort '[[?age :asc]
[?name :asc]]}
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-sort-string []
(let [conn (<? (<test-conn movies-db))
expect [["Veronica <NAME>"] ["<NAME>"] ["<NAME>"]]
actual (<! (bq/<query
{:dq '[:find [?name]
:where
[_ :person/name ?name]]
:sort '[[?name :desc]]
:limit 3}
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(comment
(test/<run-var-repl #'test-query-sort-string)
)
(<deftest test-query-sort-pull-wrapped []
(let [conn (<? (<test-conn))
_ (<! (bq/<transact
conn
[{:box/id "one"
:box/created-ts 1}
{:box/id "two"
:box/created-ts 2}]))
expect [[{:box/id "two", :box/created-ts 2}]
[{:box/id "one", :box/created-ts 1}]]
actual (<! (bq/<query
{:dq '[:find (pull ?e [*])
:where
[?e :box/id]
[?e :box/created-ts ?ts]]
:sort '[[?ts :desc]]}
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-sort-pull-unwrapped []
(let [conn (<? (<test-conn))
_ (<! (bq/<transact
conn
[{:box/id "one"
:box/created-ts 1}
{:box/id "two"
:box/created-ts 2}]))
expect [{:box/id "two"
:box/created-ts 2}
{:box/id "one"
:box/created-ts 1}]
actual (<! (bq/<query
{:dq '[:find [(pull ?e [*]) ...]
:where
[?e :box/id]
[?e :box/created-ts ?ts]]
:sort '[[?ts :desc]]}
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-limit []
(let [conn (<? (<test-conn dq-basic-datoms))
expect [["<NAME>" 42] ["<NAME>" 42]]
actual (<! (bq/<query
{:dq '[:find [?name ?age]
:where
[?e :age ?age]
[?e :name ?name]]
:sort '[[?age :desc]
[?name :desc]]
:limit 2}
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-offset []
(let [conn (<? (<test-conn dq-basic-datoms))
expect [["<NAME>" 42] ["<NAME>" 21]]
actual (<! (bq/<query
{:dq '[:find [?name ?age]
:where
[?e :age ?age]
[?e :name ?name]]
:sort '[[?age :desc]
[?name :desc]]
:offset 1}
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-parent-ref []
(let [conn (<? (<test-conn refs-datoms))
expect [[[:box/id "four"]] [[:box/id "three"]]]
actual (<! (bq/<query
{:dq '[:find ?e
:in $ ?p
:where
[?e :box/updated-ts]
[?p :box/refs ?e]]}
conn
{:box/id "one"}))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-missing-attr []
(let [conn (<? (<test-conn refs-datoms))
expect [[[:box/id "one"]]
[[:box/id "seven"]]
[[:box/id "six"]]
[[:box/id "two"]]]
actual (<! (bq/<query
{:dq '[:find ?e
:where
[?e]
(not
[_ :box/refs ?e])]}
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-order-by []
(let [conn (<? (<test-conn refs-datoms))
expect [[[:box/id "two"]]
[[:box/id "one"]]]
actual (<! (bq/<query
{:dq '[:find ?e
:where
[?e]
#_[?e :box/created-ts]
(not
[_ :box/refs ?e])
[?e :box/created-ts ?ts]]
:sort '[[?ts :desc]]
}
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(defn rq []
(gol
(bq/<sql
(<? (<test-conn refs-datoms))
["SELECT DISTINCT c0.ENTITY AS \"?e\" FROM datoms AS c0
LEFT JOIN datoms AS c1 ON c0.ENTITY=c1.VALUE
--EXCEPT
--SELECT DISTINCT c0.ENTITY AS \"?e\" FROM datoms AS c0
--INNER JOIN datoms AS c1 ON c0.ENTITY=c1.VALUE
--WHERE c1.ATTR=?"
#_"box/refs"]
)))
(comment
(test/<run-var-repl #'test-query-order-by)
(rq)
)
(deftest test-edn-ch-0 []
(go
(let [expect [["Alien"]
["Aliens"]
["Braveheart"]
["Commando"]
["Die Hard"]
["First Blood"]
["Lethal Weapon"]
["Lethal Weapon 2"]
["Lethal Weapon 3"]
["Mad Max"]
["Mad Max 2"]
["Mad Max Beyond Thunderdome"]
["Predator"]
["Predator 2"]
["Rambo III"]
["Rambo: First Blood Part II"]
["RoboCop"]
["Terminator 2: Judgment Day"]
["Terminator 3: Rise of the Machines"]
["The Terminator"]]
actual (<! (bq/<query
'[:find ?title
:where
[_ :movie/title ?title]]
(<! (<test-conn movies-db))))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(deftest test-basic-queries-ch-1-0 []
(go
(let [expect [[[:box/id "-202"]]
[[:box/id "-203"]]
[[:box/id "-204"]]]
actual (<! (bq/<query
'[:find ?e
:where
[?e :movie/year 1987]]
(<! (<test-conn movies-db))))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(deftest test-basic-queries-ch-1-1 []
(go
(let [expect [[[:box/id "-200"] "The Terminator"]
[[:box/id "-201"] "First Blood"]
[[:box/id "-202"] "Predator"]
[[:box/id "-203"] "Lethal Weapon"]
[[:box/id "-204"] "RoboCop"]
[[:box/id "-205"] "Commando"]
[[:box/id "-206"] "Die Hard"]
[[:box/id "-207"] "Terminator 2: Judgment Day"]
[[:box/id "-208"] "Terminator 3: Rise of the Machines"]
[[:box/id "-209"] "Rambo: First Blood Part II"]
[[:box/id "-210"] "Rambo III"]
[[:box/id "-211"] "Predator 2"]
[[:box/id "-212"] "Lethal Weapon 2"]
[[:box/id "-213"] "Lethal Weapon 3"]
[[:box/id "-214"] "Alien"]
[[:box/id "-215"] "Aliens"]
[[:box/id "-216"] "Mad Max"]
[[:box/id "-217"] "Mad Max 2"]
[[:box/id "-218"] "Mad Max Beyond Thunderdome"]
[[:box/id "-219"] "Braveheart"]]
actual (<! (bq/<query
'[:find ?e ?title
:where
[?e :movie/title ?title]]
(<! (<test-conn movies-db))))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(deftest test-basic-queries-ch-1-2 []
(go
(let [expect [["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]]
actual (<! (bq/<query
'[:find ?name
:where
[?p :person/name ?name]]
(merge
(<! (<test-conn movies-db))
#_debug-explain)))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(deftest test-dpat-ch-2-0 []
(go
(let [expect [["Commando"]
["Mad Max Beyond Thunderdome"]
["Rambo: First Blood Part II"]]
actual (<! (bq/<query
'[:find ?title
:where
[?m :movie/title ?title]
[?m :movie/year 1985]]
(merge
(<! (<test-conn movies-db))
#_debug-explain)))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(deftest test-dpat-ch-2-1 []
(go
[[(= (<! (bq/<query
'[:find ?year
:where
[?m :movie/title "Alien"]
[?m :movie/year ?year]]
(<! (<test-conn movies-db))))
[[1979]])]]))
(deftest test-dpat-ch-2-2 []
(go
[[(= (<! (bq/<query
'[:find ?name
:where
[?m :movie/title "RoboCop"]
[?m :movie/director ?d]
[?d :person/name ?name]]
(<! (<test-conn movies-db))))
[["<NAME>"]])]]))
(deftest test-dpat-ch-2-3 []
(go
(let [expect [["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]]
actual (<! (bq/<query
'[:find ?name
:where
[?p :person/name "<NAME>"]
[?m :movie/cast ?p]
[?m :movie/director ?d]
[?d :person/name ?name]]
(merge
#_debug-explain
(<! (<test-conn movies-db)))))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(deftest test-param-queries-ch-3-0 []
(go
[[(= (<! (bq/<query
'[:find ?title
:in $ ?year
:where
[?m :movie/year ?year]
[?m :movie/title ?title]]
(<! (<test-conn movies-db))
1988))
[["Die Hard"] ["<NAME>"]])]]))
(deftest test-param-queries-ch-3-1 []
(go
(let [res (<! (bq/<query
'[:find ?title ?year
:in $ [?title ...]
:where
[?m :movie/title ?title]
[?m :movie/year ?year]]
(<! (<test-conn movies-db))
["Lethal Weapon" "Lethal Weapon 2" "Lethal Weapon 3"]))
target [["Lethal Weapon" 1987]
["Lethal Weapon 2" 1989]
["Lethal Weapon 3" 1992]]]
[[(= res target)
{:res res
:target target}]])))
(deftest test-param-queries-ch-3-2 []
(go
(let [conn (<! (<test-conn movies-db))
expect [["Aliens"] ["The Terminator"]]
actual (<! (bq/<query
'[:find ?title
:in $ ?actor ?director
:where
[?a :person/name ?actor]
[?d :person/name ?director]
[?m :movie/cast ?a]
[?m :movie/director ?d]
[?m :movie/title ?title]]
(merge
conn
#_debug-explain)
"<NAME>"
"<NAME>"))]
#_(<! (<dump-conn conn))
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(deftest test-more-queries-ch-4-0 []
(go
(let [expect [["movie/title"]
["movie/year"]
["movie/director"]
["movie/cast"]
["trivia"]]
actual (<! (bq/<query
'[:find ?attr
:in $ ?title
:where
[?m :movie/title ?title]
[?m ?attr]]
(<! (<test-conn movies-db))
"Commando"))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(deftest test-more-queries-ch-4-1 []
(go
(let [expect (vec
(reverse
[["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]]))
actual (<! (bq/<query
'[:find ?name
:in $ ?title [?attr ...]
:where
[?m :movie/title ?title]
[?m ?attr ?p]
[?p :person/name ?name]]
(merge
(<! (<test-conn movies-db))
{::bsql/debug-explain-query? false})
"Die Hard"
[:movie/cast :movie/director]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(<deftest test-pred-ch-5-0 []
(let [expect [["Alien"] ["Mad Max"]]
actual (<? (bq/<query
'[:find ?title
:in $ ?year
:where
[?m :movie/title ?title]
[?m :movie/year ?y]
[(<= ?y ?year)]]
(<! (<test-conn movies-db))
1979))]
[[(= expect actual)
nil
{:expect expect
:actual nil #_ actual}]]))
(deftest test-pred-ch-5-1 []
(go
(let [actual (<! (bq/<query
'[:find ?actor
:where
[?d :person/name "<NAME>"]
[?d :person/born ?b1]
[?e :person/born ?b2]
[_ :movie/cast ?e]
[(< ?b2 ?b1)]
[?e :person/name ?actor]]
(merge
(<! (<test-conn movies-db))
#_debug-explain)))
expect [["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]
["<NAME>"]]]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(<deftest test-not-equals []
(let [conn (<? (<test-conn movies-db))
result (<! (bq/<query
'[:find ?title
:in $ ?year
:where
[?m :movie/title ?title]
[?m :movie/year ?y]
[(!= ?y ?year)]]
conn
1979))
expect [["Aliens"]
["Braveheart"]
["Commando"]
["Die Hard"]
["First Blood"]
["Lethal Weapon"]
["Lethal Weapon 2"]
["Lethal Weapon 3"]
["Mad Max 2"]
["Mad Max Beyond Thunderdome"]
["Predator"]
["Predator 2"]
["Rambo III"]
["Rambo: First Blood Part II"]
["RoboCop"]
["Terminator 2: Judgment Day"]
["Terminator 3: Rise of the Machines"]
["The Terminator"]]]
[[(= expect result)
nil
{:expect expect
:result result}]]))
(<deftest test-not []
[[true]]
#_(let [conn (<? (<test-conn refs-datoms))
result (<? (bq/<query
'[:find ?e
:where
[?e :box/id]
[?p :box/refs ?e]
#_[(missing? ?p :box/refs)]]
conn))
expect [[:box/id "one"]]]
[[(= expect result)
nil
{:expect expect
:result result}]]))
(comment
(test/<run-var-repl #'test-not)
)
(deftest test-inline-pull-query []
(go
(let [result (<! (bq/<query
'[:find (pull ?e [:box/created-ts])
:where
[?e :box/created-ts 1000]]
(<! (<test-conn refs-datoms))))
expect [[{:box/id "one", :box/created-ts 1000}]]]
[[(= expect result)
nil
{:expect expect
:result result}]])))
(<deftest test-nested-inline-pull-query []
(let [result (<! (bq/<query
'[:find [(pull ?e [:box/created-ts]) ...]
:where
[?e :box/created-ts 1000]]
(<? (<test-conn refs-datoms))))
expect [{:box/id "one", :box/created-ts 1000}]]
[[(= expect result)
nil
{:expect expect
:result result}]]))
(<deftest test-inline-pull-query-error []
(let [result (<! (bq/<query
'[:find (pull ?e '[*])
:where
[?e :box/created-ts]]
(<! (<test-conn refs-datoms))))]
[[(anom/? result)
nil
{:result result}]]))
(deftest test-param-pull-query []
(go
(let [result (<! (bq/<query
'[:find (pull ?e pat)
:in $ pat
:where
[?e :box/created-ts 1000]]
(<! (<test-conn refs-datoms))
[:box/created-ts]))
expect [[{:box/id "one", :box/created-ts 1000}]]]
[[(= expect result)
nil
{:expect expect
:result result}]])))
(comment
(test/<run-var-repl #'test-param-pull-query)
)
(<deftest test-like-query []
(let [result (<! (bq/<query
'[:find ?text
:in $ ?ts ?like-query
:where
[?e :box/created-ts ?ts]
[?e :box/text ?text]
[(sql-like ?text ?like-query)]]
(<? (<test-conn refs-datoms))
1000
"%ith%"))
expect [["hithere"]]]
[[(= expect result)
nil
{:expect expect
:result result}]]))
(<deftest test-bool-query-true []
(let [result (<! (bq/<query
'[:find ?e
:where
[?e :box/bool? true]]
(<? (<test-conn refs-datoms))))
expect [[[:box/id "six"]]]]
[[(= expect result)
nil
{:expect expect
:result result}]]))
(<deftest test-bool-query-false []
(let [result (<! (bq/<query
'[:find ?e
:where
[?e :box/bool? false]]
(<? (<test-conn refs-datoms))))
expect [[[:box/id "seven"]]]]
[[(= expect result)
nil
{:expect expect
:result result}]]))
(comment
(test/<run-var-repl #'test-bool-query-false)
)
(deftest test-ident-param []
(go
(let [conn (<! (<test-conn refs-datoms))
result (<! (bq/<query
'[:find (pull ?e [*])
:in $ ?child
:where
[?e :box/refs ?child]]
conn
[:box/id "five"]))
expect [[{:box/id "two",
:box/updated-ts 2000,
:box/created-ts 2000
:box/refs [{:box/id "five"}]}]]]
[[(= expect result)
nil
{:expect expect
:result result}]])))
(deftest test-ident-param-multi []
(go
(let [result (<! (bq/<query
'[:find (pull ?e [*])
:in $ [?child ...]
:where
[?e :box/refs ?child]]
(<! (<test-conn refs-datoms))
[[:box/id "five"]
[:box/id "two"]]))
expect [[{:box/id "two",
:box/updated-ts 2000,
:box/created-ts 2000
:box/refs [{:box/id "five"}]}]]]
[[(= expect result)
nil
{:expect expect
:result result}]])))
;; Pull
(<deftest test-pull-entity []
(let [expect
{:box/id "one",
:box/created-ts 1000,
:box/updated-ts 1000,
:box/text "h<NAME>",
:box/ref {:box/id "two"},
:box/refs [{:box/id "three"} {:box/id "four"}]}
actual
(<! (bq/<pull
(merge
test-schema
(<? (<test-conn refs-datoms)))
'[*]
{:box/id "one"}))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-pull-wildcard []
(let [expect
{:box/id "one",
:box/created-ts 1000,
:box/updated-ts 1000,
:box/text "h<NAME>ere",
:box/ref {:box/id "two"},
:box/refs [{:box/id "three"} {:box/id "four"}]}
actual
(<! (bq/<pull
(merge
test-schema
(<? (<test-conn refs-datoms)))
'[*]
[:box/id "one"]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-pull-empty []
(let [conn (<! (<test-conn))
_ (<? (bq/<transact
conn
[[:box/assoc [:box/id "one"] :box/text "hi"]]))
expect []
actual
(<! (bq/<query
'[:find (pull ?e [:box/none])
:where
[?e :box/id "one"]]
(merge
test-schema
conn)))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(deftest test-pull-attrs []
(go
(let [expect
{:box/id "one",
:box/created-ts 1000}
actual
(<! (bq/<pull
(merge
test-schema
(<! (<test-conn refs-datoms)))
'[:box/created-ts]
[:box/id "one"]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(deftest test-pull-single-ref []
(go
(let [expect
{:box/id "one",
:box/created-ts 1000,
:box/updated-ts 1000,
:box/text "<NAME>",
:box/ref
{:box/id "two",
:box/updated-ts 2000,
:box/created-ts 2000,
:box/refs [{:box/id "five"}]},
:box/refs [{:box/id "three"} {:box/id "four"}]}
actual
(<! (bq/<pull
(merge
test-schema
(<! (<test-conn refs-datoms)))
'[*
{:box/ref [*]}]
[:box/id "one"]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(<deftest test-pull-multi-ref []
(let [expect
{:box/id "one",
:box/created-ts 1000,
:box/updated-ts 1000,
:box/text "<NAME>",
:box/ref {:box/id "two"},
:box/refs
[{:box/id "three", :box/created-ts 3000, :box/updated-ts 3000}
{:box/id "four", :box/created-ts 4000, :box/updated-ts 4000}]}
actual
(<! (bq/<pull
(merge
test-schema
(<? (<test-conn refs-datoms)))
'[*
{:box/refs [*]}]
[:box/id "one"]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(deftest test-pull-multi-ref-limit []
(go
(let [expect
{:box/id "one",
:box/created-ts 1000,
:box/ref {:box/id "two"},
:box/refs
[{:box/id "three", :box/created-ts 3000}]}
actual
(<! (bq/<pull
(merge
test-schema
(<! (<test-conn refs-datoms)))
'[*
{(limit :box/refs 1) [*]}]
[:box/id "one"]))]
[[true]]
#_[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(<deftest test-pull-multi []
(let [expect
[{:box/id "one",
:box/created-ts 1000}
{:box/id "two",
:box/created-ts 2000}]
actual
(<! (bq/<pull-multi
(merge
test-schema
(<? (<test-conn refs-datoms)))
'[:box/created-ts]
[{:box/id "one"}
{:box/id "two"}]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-transact-basic []
(let [conn (<? (<test-conn))
_ (<! (bq/<transact
(merge
test-schema
conn)
[[:box/assoc
[:box/id "one"]
:box/created-ts
1000]
{:box/id "two"
:box/ref {:box/id "three"
:box/created-ts 3000}
:box/refs [{:box/id "four"
:box/created-ts 4000}
{:box/id "five"
:box/created-ts 5000}]
:box/created-ts 2000}]))
expect [[:box/id "one"]]
actual (<! (bq/<query
'[:find [?e ...]
:where
[?e :box/created-ts 1000]]
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-transact-bool []
(let [conn (<? (<test-conn))
_ (<! (bq/<transact
(merge
test-schema
conn)
[[:box/assoc
[:box/id "one"]
:box/bool?
false]
[:box/assoc
[:box/id "two"]
:box/bool?
true]]))
expect [[:box/id "one"]]
actual (<! (bq/<query
'[:find [?e ...]
:where
[?e :box/bool? false]]
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(comment
(test/<run-var-repl #'test-transact-bool)
)
(<deftest test-transact-dissoc []
(let [conn (<? (<test-conn refs-datoms))
_ (<? (bq/<transact
(merge
test-schema
conn)
[[:box/dissoc
[:box/id "one"]
:box/refs
[:box/id "three"]]]))
expect [{:box/id "one",
:box/refs [{:box/id "four"}]}]
actual (<? (bq/<query
'[:find [(pull ?e [:box/refs]) ...]
:where
[?e :box/id "one"]]
conn))]
#_(bq/<inspect-conn conn)
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-transact-ref-maps []
;; transact should _not_ expand entities in txfs like :box/assoc etc
(let [conn (merge
(<? (<test-conn))
{::bsql/debug-explain-query? false})
_ (<! (bq/<transact
(merge
test-schema
conn)
[[:box/assoc
{:box/id "one"}
:box/ref
{:box/id "two"
:box/created-ts 2000}]]))
actual (<! (bq/<pull
conn
'[*
{:box/ref [*]}]
[:box/id "one"]))
expect {:box/id "one", :box/ref {:box/id "two"}}]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(deftest test-transact-nested-single []
(go
(let [conn (merge
(<! (<test-conn))
{::bsql/debug-explain-query? false})
_ (<! (bq/<transact
(merge
test-schema
conn)
[{:box/id "two"
:box/ref {:box/id "three"
:box/created-ts 3000}
:box/refs [{:box/id "four"
:box/created-ts 4000}
{:box/id "five"
:box/created-ts 5000}]
:box/created-ts 2000}]))
expect [3000]
actual (<! (bq/<query
'[:find [?created-ts ...]
:where
[[:box/id "three"] :box/created-ts ?created-ts]]
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(deftest test-transact-nested-multi []
(go
(let [conn (<! (<test-conn))
_ (<! (bq/<transact
(merge
test-schema
conn)
[{:box/id "two"
:box/ref {:box/id "three"
:box/created-ts 3000}
:box/refs [{:box/id "four"
:box/created-ts 4000}
{:box/id "five"
:box/created-ts 5000}]
:box/created-ts 2000}]))
expect [5000]
actual (<! (bq/<query
'[:find [?created-ts ...]
:where
["five" :box/created-ts ?created-ts]]
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(<deftest test-transact-data-types []
(let [conn (<? (<test-conn))
transact-res
(<! (bq/<transact
(merge
test-schema
conn)
[{:box/id "one"
:box/string "hello"
:box/long 123
:box/double 1.23
:box/bool true
:box/map {:foo "bar"}
:box/vec [1 2 3]
:box/list '(1 2 3)
:box/keyword :keyword}]))
expect {:box/id "one",
:box/vec [1 2 3],
:box/list '(1 2 3),
:box/string "hello",
:box/bool true,
:box/map {:foo "bar"},
:box/double 1.23,
:box/long 123
:box/keyword :keyword}
actual (<! (bq/<pull
conn
'[*]
[:box/id "one"]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]
[(not (anom/? transact-res))
nil
transact-res]]))
(<deftest test-transact-delete []
(let [conn (<? (<test-conn))
_ (<? (bq/<transact
conn
[{:box/id "one"
:box/string "hello"
:box/long 123
:box/double 1.23
:box/bool true
:box/map {:foo "bar"}
:box/vec [1 2 3]
:box/list '(1 2 3)}
[:box/delete [:box/id "one"]]
{:box/id "one"
:box/string "goodbye"}]))
_ (<? (bq/<transact
conn
[]))
expect {:box/id "one"
:box/string "goodbye"}
actual (<! (bq/<pull
conn
'[*]
[:box/id "one"]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-transact-delete-ref []
(let [conn (<? (<test-conn))
_ (<? (bq/<transact
conn
[{:box/id "one"
:box/refs [{:box/id "two"}
{:box/id "three"}]}
[:box/delete [:box/id "two"]]]))
expect {:box/id "one",
:box/refs [{:box/id "three"}]}
actual (<! (bq/<pull
conn
'[*]
[:box/id "one"]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-transact-zeros-string
[]
(let [conn (<? (<test-conn))
_ (<! (bq/<transact
(merge
test-schema
conn)
[[:box/assoc
[:box/id "one"]
:box/title
"000"]]))
expect {:box/id "one"
:box/title "000"}
actual (<! (bq/<pull
conn
'[:box/title]
[:box/id "one"]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(comment
(test/<run-var-repl #'test-transact-zeros-string)
)
;; Reagent stuff
#_(<deftest test-reagent []
(let [conn (<? (<test-conn refs-datoms))
id (ks/uuid)
ratom (<? (br/<tracked-query
id
'[:find ?e
:where
[?e :box/created-ts]]
conn))
res1 @ratom
_ (<? (br/<transact
conn
[[:box/delete [:box/id "one"]]]))
res2 @ratom
expect [[[:box/id "two"]]
[[:box/id "three"]]
[[:box/id "four"]]
[[:box/id "five"]]]]
[[(= expect res2)
nil
{:res2 res2
:expect expect}]]))
(comment
(go
(let [conn (<! (<test-conn))]
(<! (bq/<transact
(merge
test-schema
conn)
[[:box/assoc
[:box/id "one"]
:box/created-ts
1000]
{:box/id "two"
:box/ref {:box/id "three"
:box/created-ts 3000}
:box/refs [{:box/id "four"
:box/created-ts 4000}
{:box/id "five"
:box/created-ts 5000}]
:box/created-ts 2000}]))
(ks/pp (<! (bq/<query
'[:find [?e ...]
:where
[?e :box/created-ts 1000]]
conn)))))
)
(comment
(test/<run-var-repl #'test-pred-ch-5-0)
(test/<run-var-repl #'test-pull-multi-ref)
(test/<run-ns-repl 'rx.node.box2.tests)
;; https://docs.datomic.com/on-prem/query.html
;; http://www.learndatalogtoday.org/
;; punt test-param-queries-ch-3-3
;; punt test-more-queries-ch-4-2 & 3
;; punt test-pred-ch-5-2 & 3
;; punt tranformation functions ch 6
;; punt aggregates
;; punt rules
(go
(ks/pp
(let [conn (<! (<test-conn refs-datoms))]
(<! (sql/<exec
(::bsql/db conn)
["SELECT DISTINCT c0.ENTITY AS \"?e\" FROM datoms AS c0
INNER JOIN datoms AS c1 ON c0.ENTITY=c1.VALUE WHERE NOT c1.ATTR=? AND c0.ENTITY!=c1.VALUE"
"box/refs"])))))
(go
(ks/pp
(let [conn (<! (<test-conn refs-datoms))]
(<! (sql/<exec
(::bsql/db conn)
[(str "SELECT DISTINCT c0.ENTITY as c0ent, c0.ATTR as c0attr, c0.VALUE as c0val, c1.ENTITY as c1ent, c1.ATTR as c1attr, c1.VALUE as c1val from datoms" " AS c0 INNER JOIN datoms AS c1 ON c0.ENTITY=c1.VALUE")])))))
(go
(ks/pp
(let [conn (<! (<test-conn refs-datoms))]
(<! (sql/<exec
(::bsql/db conn)
["
SELECT DISTINCT c0.ENTITY AS \"?e\" FROM datoms AS c0
EXCEPT
SELECT DISTINCT c0.VALUE AS \"?e\" FROM datoms AS c0 WHERE c0.ATTR=?
"
"box/refs"])))))
)
| true | (ns rx.node.box2.tests
(:require [rx.kitchen-sink :as ks]
[rx.box2 :as bq]
[rx.box2.sql :as bsql]
#_[rx.box2.reagent :as br]
[rx.node.sqlite2 :as sql]
[rx.test :as test
:refer-macros [deftest
<deftest]]
[rx.anom :as anom
:refer-macros [<defn <? gol]]
[datascript.query :as dsq]
[datascript.query-v3 :as dsqv3]
[clojure.core.async :as async
:refer [go <!]]))
(def debug-explain
{::bsql/debug-explain-query? true})
(def test-schema {:box/schema
{:box/attrs
[{:box/attr :box/id
:box/ident? true
:box/value-type :box/string}
{:box/attr :box/ref
:box/ref? true
:box/cardinality :box/cardinality-one}
{:box/attr :box/refs
:box/ref? true
:box/cardinality :box/cardinality-many}
{:box/attr :box/updated-ts
:box/index? true
:box/value-type :box/long}
{:box/attr :box/created-ts
:box/index? true
:box/value-type :box/long}]}})
(<defn <test-conn [& [datoms]]
(let [db (<! (sql/<open-db {:name ":memory:"}))]
(anom/throw-if-anom
(<! (sql/<exec db [(bq/create-datoms-sql)])))
(anom/throw-if-anom
(<! (sql/<batch-exec db (bq/create-indexes-sql-vecs))))
(when datoms
(anom/throw-if-anom
(<! (sql/<batch-exec db (bq/insert-datoms-sqls datoms)))))
(merge
{::bsql/db db
::bsql/<exec sql/<exec
::bsql/<batch-exec sql/<batch-exec}
test-schema)))
(defn <dump-conn [{:keys [::bsql/db
::bsql/<exec]}]
(go
(ks/pp
(<! (<exec db ["select * from datoms"])))))
(defn <run-sql [{:keys [::bsql/db
::bsql/<exec]}
sql-vec]
(go
(ks/spy
"RUN SQL"
(<! (<exec db sql-vec)))))
(def foaf-data
[[[:box/id "zk"] "name" "PI:NAME:<NAME>END_PI" false]
[[:box/id "cindy"] "name" "PI:NAME:<NAME>END_PI" false]
[[:box/id "zk"] "friend" [:box/id "cindy"] true true]])
(def refs-datoms
[[[:box/id "one"] :box/id "one"]
[[:box/id "one"] :box/created-ts 1000]
[[:box/id "one"] :box/updated-ts 1000]
[[:box/id "one"] :box/text "hithere"]
[[:box/id "one"] :box/ref [:box/id "two"] true]
[[:box/id "two"] :box/id "two"]
[[:box/id "two"] :box/updated-ts 2000]
[[:box/id "two"] :box/created-ts 2000]
[[:box/id "three"] :box/id "three"]
[[:box/id "three"] :box/created-ts 3000]
[[:box/id "three"] :box/updated-ts 3000]
[[:box/id "four"] :box/id "four"]
[[:box/id "four"] :box/created-ts 4000]
[[:box/id "four"] :box/updated-ts 4000]
[[:box/id "one"] :box/refs [:box/id "three"] true true]
[[:box/id "one"] :box/refs [:box/id "four"] true true]
[[:box/id "five"] :box/id "five"]
[[:box/id "five"] :box/created-ts 5000]
[[:box/id "two"] :box/refs [:box/id "five"] true true]
[[:box/id "six"] :box/id "six"]
[[:box/id "six"] :box/bool? true]
[[:box/id "seven"] :box/id "seven"]
[[:box/id "seven"] :box/bool? false]])
(def movies-db
[[[:box/id -100] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -100] "person/born" -485308800000 nil nil]
[[:box/id -101] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -101] "person/born" -707702400000 nil nil]
[[:box/id -102] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -102] "person/born" -418608000000 nil nil]
[[:box/id -103] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -103] "person/born" -423532800000 nil nil]
[[:box/id -104] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -104] "person/born" -1222473600000 nil nil]
[[:box/id -105] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -105] "person/born" -741312000000 nil nil]
[[:box/id -106] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -106] "person/born" -1359763200000 nil nil]
[[:box/id -106] "person/death" 1042761600000 nil nil]
[[:box/id -107] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -107] "person/born" -993513600000 nil nil]
[[:box/id -108] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -108] "person/born" -599011200000 nil nil]
[[:box/id -109] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -109] "person/born" -264384000000 nil nil]
[[:box/id -110] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -110] "person/born" -693187200000 nil nil]
[[:box/id -111] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -111] "person/born" -1252540800000 nil nil]
[[:box/id -112] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -112] "person/born" -441676800000 nil nil]
[[:box/id -113] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -113] "person/born" -739929600000 nil nil]
[[:box/id -114] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -114] "person/born" -802396800000 nil nil]
[[:box/id -115] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -115] "person/born" -992736000000 nil nil]
[[:box/id -116] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -116] "person/born" -710812800000 nil nil]
[[:box/id -117] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -117] "person/born" -616118400000 nil nil]
[[:box/id -118] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -118] "person/born" -992304000000 nil nil]
[[:box/id -119] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -119] "person/born" -728956800000 nil nil]
[[:box/id -120] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -120] "person/born" -278985600000 nil nil]
[[:box/id -121] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -121] "person/born" 93571200000 nil nil]
[[:box/id -122] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -122] "person/born" -466732800000 nil nil]
[[:box/id -123] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -123] "person/born" -752976000000 nil nil]
[[:box/id -124] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -124] "person/born" -634089600000 nil nil]
[[:box/id -124] "person/death" 800755200000 nil nil]
[[:box/id -125] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -125] "person/born" -352080000000 nil nil]
[[:box/id -126] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -126] "person/born" 239328000000 nil nil]
[[:box/id -127] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -127] "person/born" -255398400000 nil nil]
[[:box/id -128] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -128] "person/born" 313200000000 nil nil]
[[:box/id -129] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -129] "person/born" 292723200000 nil nil]
[[:box/id -130] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -130] "person/born" -914889600000 nil nil]
[[:box/id -130] "person/death" 1113868800000 nil nil]
[[:box/id -131] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -131] "person/born" -1064188800000 nil nil]
[[:box/id -131] "person/death" 1317772800000 nil nil]
[[:box/id -132] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -133] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -133] "person/born" -658713600000 nil nil]
[[:box/id -133] "person/death" 834019200000 nil nil]
[[:box/id -134] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -135] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -135] "person/born" -677289600000 nil nil]
[[:box/id -136] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -136] "person/born" -848707200000 nil nil]
[[:box/id -137] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -137] "person/born" -1012608000000 nil nil]
[[:box/id -138] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -138] "person/born" -1147219200000 nil nil]
[[:box/id -139] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -139] "person/born" -638496000000 nil nil]
[[:box/id -140] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -140] "person/born" -653270400000 nil nil]
[[:box/id -141] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -142] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -142] "person/born" -783648000000 nil nil]
[[:box/id -143] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -143] "person/born" -568598400000 nil nil]
[[:box/id -144] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -145] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -145] "person/born" -998352000000 nil nil]
[[:box/id -146] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -146] "person/born" -766540800000 nil nil]
[[:box/id -147] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -147] "person/born" -1225324800000 nil nil]
[[:box/id -148] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -148] "person/born" -949881600000 nil nil]
[[:box/id -149] "person/name" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -149] "person/born" -98582400000 nil nil]
[[:box/id -200] "movie/title" "The Terminator" nil nil]
[[:box/id -200] "movie/year" 1984 nil nil]
[[:box/id -200] "movie/director" [:box/id -100] true nil]
[[:box/id -200] "movie/cast" [:box/id -101] true true]
[[:box/id -200] "movie/cast" [:box/id -102] true true]
[[:box/id -200] "movie/cast" [:box/id -103] true true]
[[:box/id -200] "movie/sequel" [:box/id -207] true nil]
[[:box/id -201] "movie/title" "First Blood" nil nil]
[[:box/id -201] "movie/year" 1982 nil nil]
[[:box/id -201] "movie/director" [:box/id -104] true nil]
[[:box/id -201] "movie/cast" [:box/id -105] true true]
[[:box/id -201] "movie/cast" [:box/id -106] true true]
[[:box/id -201] "movie/cast" [:box/id -107] true true]
[[:box/id -201] "movie/sequel" [:box/id -209] true nil]
[[:box/id -202] "movie/title" "Predator" nil nil]
[[:box/id -202] "movie/year" 1987 nil nil]
[[:box/id -202] "movie/director" [:box/id -108] true nil]
[[:box/id -202] "movie/cast" [:box/id -101] true true]
[[:box/id -202] "movie/cast" [:box/id -109] true true]
[[:box/id -202] "movie/cast" [:box/id -110] true true]
[[:box/id -202] "movie/sequel" [:box/id -211] true nil]
[[:box/id -203] "movie/title" "Lethal Weapon" nil nil]
[[:box/id -203] "movie/year" 1987 nil nil]
[[:box/id -203] "movie/director" [:box/id -111] true nil]
[[:box/id -203] "movie/cast" [:box/id -112] true true]
[[:box/id -203] "movie/cast" [:box/id -113] true true]
[[:box/id -203] "movie/cast" [:box/id -114] true true]
[[:box/id -203] "movie/sequel" [:box/id -212] true nil]
[[:box/id -204] "movie/title" "RoboCop" nil nil]
[[:box/id -204] "movie/year" 1987 nil nil]
[[:box/id -204] "movie/director" [:box/id -115] true nil]
[[:box/id -204] "movie/cast" [:box/id -116] true true]
[[:box/id -204] "movie/cast" [:box/id -117] true true]
[[:box/id -204] "movie/cast" [:box/id -118] true true]
[[:box/id -205] "movie/title" "Commando" nil nil]
[[:box/id -205] "movie/year" 1985 nil nil]
[[:box/id -205] "movie/director" [:box/id -119] true nil]
[[:box/id -205] "movie/cast" [:box/id -101] true true]
[[:box/id -205] "movie/cast" [:box/id -120] true true]
[[:box/id -205] "movie/cast" [:box/id -121] true true]
[[:box/id -205]
"trivia"
"In 1986, a sequel was written with an eye to having\n John McTiPI:NAME:<NAME>END_PIan direct. SchPI:NAME:<NAME>END_PI wasn't interested in reprising\n the role. The script was then reworked with a new central character,\n eventually played by PI:NAME:<NAME>END_PI, and became Die Hard"
nil
nil]
[[:box/id -206] "movie/title" "Die Hard" nil nil]
[[:box/id -206] "movie/year" 1988 nil nil]
[[:box/id -206] "movie/director" [:box/id -108] true nil]
[[:box/id -206] "movie/cast" [:box/id -122] true true]
[[:box/id -206] "movie/cast" [:box/id -123] true true]
[[:box/id -206] "movie/cast" [:box/id -124] true true]
[[:box/id -207] "movie/title" "Terminator 2: Judgment Day" nil nil]
[[:box/id -207] "movie/year" 1991 nil nil]
[[:box/id -207] "movie/director" [:box/id -100] true nil]
[[:box/id -207] "movie/cast" [:box/id -101] true true]
[[:box/id -207] "movie/cast" [:box/id -102] true true]
[[:box/id -207] "movie/cast" [:box/id -125] true true]
[[:box/id -207] "movie/cast" [:box/id -126] true true]
[[:box/id -207] "movie/sequel" [:box/id -208] true nil]
[[:box/id -208]
"movie/title"
"Terminator 3: Rise of the Machines"
nil
nil]
[[:box/id -208] "movie/year" 2003 nil nil]
[[:box/id -208] "movie/director" [:box/id -127] true nil]
[[:box/id -208] "movie/cast" [:box/id -101] true true]
[[:box/id -208] "movie/cast" [:box/id -128] true true]
[[:box/id -208] "movie/cast" [:box/id -129] true true]
[[:box/id -209] "movie/title" "Rambo: First Blood Part II" nil nil]
[[:box/id -209] "movie/year" 1985 nil nil]
[[:box/id -209] "movie/director" [:box/id -130] true nil]
[[:box/id -209] "movie/cast" [:box/id -105] true true]
[[:box/id -209] "movie/cast" [:box/id -106] true true]
[[:box/id -209] "movie/cast" [:box/id -131] true true]
[[:box/id -209] "movie/sequel" [:box/id -210] true nil]
[[:box/id -210] "movie/title" "PI:NAME:<NAME>END_PIbo III" nil nil]
[[:box/id -210] "movie/year" 1988 nil nil]
[[:box/id -210] "movie/director" [:box/id -132] true nil]
[[:box/id -210] "movie/cast" [:box/id -105] true true]
[[:box/id -210] "movie/cast" [:box/id -106] true true]
[[:box/id -210] "movie/cast" [:box/id -133] true true]
[[:box/id -211] "movie/title" "Predator 2" nil nil]
[[:box/id -211] "movie/year" 1990 nil nil]
[[:box/id -211] "movie/director" [:box/id -134] true nil]
[[:box/id -211] "movie/cast" [:box/id -113] true true]
[[:box/id -211] "movie/cast" [:box/id -114] true true]
[[:box/id -211] "movie/cast" [:box/id -135] true true]
[[:box/id -212] "movie/title" "Lethal Weapon 2" nil nil]
[[:box/id -212] "movie/year" 1989 nil nil]
[[:box/id -212] "movie/director" [:box/id -111] true nil]
[[:box/id -212] "movie/cast" [:box/id -112] true true]
[[:box/id -212] "movie/cast" [:box/id -113] true true]
[[:box/id -212] "movie/cast" [:box/id -136] true true]
[[:box/id -212] "movie/sequel" [:box/id -213] true nil]
[[:box/id -213] "movie/title" "Lethal Weapon 3" nil nil]
[[:box/id -213] "movie/year" 1992 nil nil]
[[:box/id -213] "movie/director" [:box/id -111] true nil]
[[:box/id -213] "movie/cast" [:box/id -112] true true]
[[:box/id -213] "movie/cast" [:box/id -113] true true]
[[:box/id -213] "movie/cast" [:box/id -136] true true]
[[:box/id -214] "movie/title" "Alien" nil nil]
[[:box/id -214] "movie/year" 1979 nil nil]
[[:box/id -214] "movie/director" [:box/id -137] true nil]
[[:box/id -214] "movie/cast" [:box/id -138] true true]
[[:box/id -214] "movie/cast" [:box/id -139] true true]
[[:box/id -214] "movie/cast" [:box/id -140] true true]
[[:box/id -214] "movie/sequel" [:box/id -215] true nil]
[[:box/id -215] "movie/title" "Aliens" nil nil]
[[:box/id -215] "movie/year" 1986 nil nil]
[[:box/id -215] "movie/director" [:box/id -100] true nil]
[[:box/id -215] "movie/cast" [:box/id -139] true true]
[[:box/id -215] "movie/cast" [:box/id -141] true true]
[[:box/id -215] "movie/cast" [:box/id -103] true true]
[[:box/id -216] "movie/title" "PI:NAME:<NAME>END_PI" nil nil]
[[:box/id -216] "movie/year" 1979 nil nil]
[[:box/id -216] "movie/director" [:box/id -142] true nil]
[[:box/id -216] "movie/cast" [:box/id -112] true true]
[[:box/id -216] "movie/cast" [:box/id -143] true true]
[[:box/id -216] "movie/cast" [:box/id -144] true true]
[[:box/id -216] "movie/sequel" [:box/id -217] true nil]
[[:box/id -217] "movie/title" "Mad Max 2" nil nil]
[[:box/id -217] "movie/year" 1981 nil nil]
[[:box/id -217] "movie/director" [:box/id -142] true nil]
[[:box/id -217] "movie/cast" [:box/id -112] true true]
[[:box/id -217] "movie/cast" [:box/id -145] true true]
[[:box/id -217] "movie/cast" [:box/id -146] true true]
[[:box/id -217] "movie/sequel" [:box/id -218] true nil]
[[:box/id -218] "movie/title" "Mad Max Beyond Thunderdome" nil nil]
[[:box/id -218] "movie/year" 1985 nil nil]
[[:box/id -218] "movie/director" [:box/id -142] true true]
[[:box/id -218] "movie/director" [:box/id -147] true true]
[[:box/id -218] "movie/cast" [:box/id -112] true true]
[[:box/id -218] "movie/cast" [:box/id -148] true true]
[[:box/id -219] "movie/title" "Braveheart" nil nil]
[[:box/id -219] "movie/year" 1995 nil nil]
[[:box/id -219] "movie/director" [:box/id -112] true true]
[[:box/id -219] "movie/cast" [:box/id -112] true true]
[[:box/id -219] "movie/cast" [:box/id -149] true true]])
(<deftest test-query-entity []
(let [conn (<? (<test-conn foaf-data))
expect ["Cindy"]
actual (<! (bq/<query
'[:find [?name ...]
:in $ ?e
:where
[?e :friend ?e2]
[?e2 :name ?name]]
conn
{:box/id "zk"}))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-foaf []
(let [conn (<? (<test-conn foaf-data))
expect ["Cindy"]
actual (<! (bq/<query
'[:find [?name ...]
:where
[?e :name "PI:NAME:<NAME>END_PI"]
[?e :friend ?e2]
[?e2 :name ?name]]
conn))
ent (<! (bq/<pull
conn
'[*]
[:box/id "zk"]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]
[(not (nil? ent))
"Pull entity succeeded"]]))
(def dq-basic-datoms
[["PI:NAME:<NAME>END_PI" "age" 21]
["PI:NAME:<NAME>END_PI" "age" 42]
["ethel" "age" 42]
["PI:NAME:<NAME>END_PI" "likes" "pizza"]
["PI:NAME:<NAME>END_PI" "likes" "opera"]
["PI:NAME:<NAME>END_PI" "likes" "sushi"]
["PI:NAME:<NAME>END_PI" "name" "PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI" "name" "PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI" "name" "PI:NAME:<NAME>END_PI"]])
(<deftest test-query-basic []
(let [expect [[[:box/id "PI:NAME:<NAME>END_PI"]]
[[:box/id "PI:NAME:<NAME>END_PI"]]]
actual (<! (bq/<query
'[:find ?e
:where
[?e :age 42]]
(<! (<test-conn dq-basic-datoms))))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-unification []
(let [expect [[[:box/id "PI:NAME:<NAME>END_PI"] "pizza"] [[:box/id "ethel"] "sushi"]]
actual (<! (bq/<query
'[:find ?e ?x
:where [?e :age 42]
[?e :likes ?x]]
(<! (<test-conn dq-basic-datoms))))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-blanks []
(let [expect [["opera"] ["pizza"] ["sushi"]]
actual (<! (bq/<query
'[:find ?x
:where [_ :likes ?x]]
(merge
#_debug-explain
(<! (<test-conn dq-basic-datoms)))))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-sort-desc []
(let [conn (<? (<test-conn dq-basic-datoms))
expect [["PI:NAME:<NAME>END_PI" 42] ["PI:NAME:<NAME>END_PI" 42] ["PI:NAME:<NAME>END_PI" 21]]
actual (<! (bq/<query
{:dq '[:find [?name ?age]
:where
[?e :age ?age]
[?e :name ?name]]
:sort '[[?age :desc]
[?name :desc]]}
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-sort-asc []
(let [conn (<? (<test-conn dq-basic-datoms))
expect (vec (reverse [["PI:NAME:<NAME>END_PI" 42] ["PI:NAME:<NAME>END_PI" 42] ["PI:NAME:<NAME>END_PI" 21]]))
actual (<! (bq/<query
{:dq '[:find [?name ?age]
:where
[?e :age ?age]
[?e :name ?name]]
:sort '[[?age :asc]
[?name :asc]]}
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-sort-string []
(let [conn (<? (<test-conn movies-db))
expect [["Veronica PI:NAME:<NAME>END_PI"] ["PI:NAME:<NAME>END_PI"] ["PI:NAME:<NAME>END_PI"]]
actual (<! (bq/<query
{:dq '[:find [?name]
:where
[_ :person/name ?name]]
:sort '[[?name :desc]]
:limit 3}
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(comment
(test/<run-var-repl #'test-query-sort-string)
)
(<deftest test-query-sort-pull-wrapped []
(let [conn (<? (<test-conn))
_ (<! (bq/<transact
conn
[{:box/id "one"
:box/created-ts 1}
{:box/id "two"
:box/created-ts 2}]))
expect [[{:box/id "two", :box/created-ts 2}]
[{:box/id "one", :box/created-ts 1}]]
actual (<! (bq/<query
{:dq '[:find (pull ?e [*])
:where
[?e :box/id]
[?e :box/created-ts ?ts]]
:sort '[[?ts :desc]]}
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-sort-pull-unwrapped []
(let [conn (<? (<test-conn))
_ (<! (bq/<transact
conn
[{:box/id "one"
:box/created-ts 1}
{:box/id "two"
:box/created-ts 2}]))
expect [{:box/id "two"
:box/created-ts 2}
{:box/id "one"
:box/created-ts 1}]
actual (<! (bq/<query
{:dq '[:find [(pull ?e [*]) ...]
:where
[?e :box/id]
[?e :box/created-ts ?ts]]
:sort '[[?ts :desc]]}
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-limit []
(let [conn (<? (<test-conn dq-basic-datoms))
expect [["PI:NAME:<NAME>END_PI" 42] ["PI:NAME:<NAME>END_PI" 42]]
actual (<! (bq/<query
{:dq '[:find [?name ?age]
:where
[?e :age ?age]
[?e :name ?name]]
:sort '[[?age :desc]
[?name :desc]]
:limit 2}
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-offset []
(let [conn (<? (<test-conn dq-basic-datoms))
expect [["PI:NAME:<NAME>END_PI" 42] ["PI:NAME:<NAME>END_PI" 21]]
actual (<! (bq/<query
{:dq '[:find [?name ?age]
:where
[?e :age ?age]
[?e :name ?name]]
:sort '[[?age :desc]
[?name :desc]]
:offset 1}
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-parent-ref []
(let [conn (<? (<test-conn refs-datoms))
expect [[[:box/id "four"]] [[:box/id "three"]]]
actual (<! (bq/<query
{:dq '[:find ?e
:in $ ?p
:where
[?e :box/updated-ts]
[?p :box/refs ?e]]}
conn
{:box/id "one"}))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-missing-attr []
(let [conn (<? (<test-conn refs-datoms))
expect [[[:box/id "one"]]
[[:box/id "seven"]]
[[:box/id "six"]]
[[:box/id "two"]]]
actual (<! (bq/<query
{:dq '[:find ?e
:where
[?e]
(not
[_ :box/refs ?e])]}
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-query-order-by []
(let [conn (<? (<test-conn refs-datoms))
expect [[[:box/id "two"]]
[[:box/id "one"]]]
actual (<! (bq/<query
{:dq '[:find ?e
:where
[?e]
#_[?e :box/created-ts]
(not
[_ :box/refs ?e])
[?e :box/created-ts ?ts]]
:sort '[[?ts :desc]]
}
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(defn rq []
(gol
(bq/<sql
(<? (<test-conn refs-datoms))
["SELECT DISTINCT c0.ENTITY AS \"?e\" FROM datoms AS c0
LEFT JOIN datoms AS c1 ON c0.ENTITY=c1.VALUE
--EXCEPT
--SELECT DISTINCT c0.ENTITY AS \"?e\" FROM datoms AS c0
--INNER JOIN datoms AS c1 ON c0.ENTITY=c1.VALUE
--WHERE c1.ATTR=?"
#_"box/refs"]
)))
(comment
(test/<run-var-repl #'test-query-order-by)
(rq)
)
(deftest test-edn-ch-0 []
(go
(let [expect [["Alien"]
["Aliens"]
["Braveheart"]
["Commando"]
["Die Hard"]
["First Blood"]
["Lethal Weapon"]
["Lethal Weapon 2"]
["Lethal Weapon 3"]
["Mad Max"]
["Mad Max 2"]
["Mad Max Beyond Thunderdome"]
["Predator"]
["Predator 2"]
["Rambo III"]
["Rambo: First Blood Part II"]
["RoboCop"]
["Terminator 2: Judgment Day"]
["Terminator 3: Rise of the Machines"]
["The Terminator"]]
actual (<! (bq/<query
'[:find ?title
:where
[_ :movie/title ?title]]
(<! (<test-conn movies-db))))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(deftest test-basic-queries-ch-1-0 []
(go
(let [expect [[[:box/id "-202"]]
[[:box/id "-203"]]
[[:box/id "-204"]]]
actual (<! (bq/<query
'[:find ?e
:where
[?e :movie/year 1987]]
(<! (<test-conn movies-db))))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(deftest test-basic-queries-ch-1-1 []
(go
(let [expect [[[:box/id "-200"] "The Terminator"]
[[:box/id "-201"] "First Blood"]
[[:box/id "-202"] "Predator"]
[[:box/id "-203"] "Lethal Weapon"]
[[:box/id "-204"] "RoboCop"]
[[:box/id "-205"] "Commando"]
[[:box/id "-206"] "Die Hard"]
[[:box/id "-207"] "Terminator 2: Judgment Day"]
[[:box/id "-208"] "Terminator 3: Rise of the Machines"]
[[:box/id "-209"] "Rambo: First Blood Part II"]
[[:box/id "-210"] "Rambo III"]
[[:box/id "-211"] "Predator 2"]
[[:box/id "-212"] "Lethal Weapon 2"]
[[:box/id "-213"] "Lethal Weapon 3"]
[[:box/id "-214"] "Alien"]
[[:box/id "-215"] "Aliens"]
[[:box/id "-216"] "Mad Max"]
[[:box/id "-217"] "Mad Max 2"]
[[:box/id "-218"] "Mad Max Beyond Thunderdome"]
[[:box/id "-219"] "Braveheart"]]
actual (<! (bq/<query
'[:find ?e ?title
:where
[?e :movie/title ?title]]
(<! (<test-conn movies-db))))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(deftest test-basic-queries-ch-1-2 []
(go
(let [expect [["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]]
actual (<! (bq/<query
'[:find ?name
:where
[?p :person/name ?name]]
(merge
(<! (<test-conn movies-db))
#_debug-explain)))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(deftest test-dpat-ch-2-0 []
(go
(let [expect [["Commando"]
["Mad Max Beyond Thunderdome"]
["Rambo: First Blood Part II"]]
actual (<! (bq/<query
'[:find ?title
:where
[?m :movie/title ?title]
[?m :movie/year 1985]]
(merge
(<! (<test-conn movies-db))
#_debug-explain)))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(deftest test-dpat-ch-2-1 []
(go
[[(= (<! (bq/<query
'[:find ?year
:where
[?m :movie/title "Alien"]
[?m :movie/year ?year]]
(<! (<test-conn movies-db))))
[[1979]])]]))
(deftest test-dpat-ch-2-2 []
(go
[[(= (<! (bq/<query
'[:find ?name
:where
[?m :movie/title "RoboCop"]
[?m :movie/director ?d]
[?d :person/name ?name]]
(<! (<test-conn movies-db))))
[["PI:NAME:<NAME>END_PI"]])]]))
(deftest test-dpat-ch-2-3 []
(go
(let [expect [["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]]
actual (<! (bq/<query
'[:find ?name
:where
[?p :person/name "PI:NAME:<NAME>END_PI"]
[?m :movie/cast ?p]
[?m :movie/director ?d]
[?d :person/name ?name]]
(merge
#_debug-explain
(<! (<test-conn movies-db)))))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(deftest test-param-queries-ch-3-0 []
(go
[[(= (<! (bq/<query
'[:find ?title
:in $ ?year
:where
[?m :movie/year ?year]
[?m :movie/title ?title]]
(<! (<test-conn movies-db))
1988))
[["Die Hard"] ["PI:NAME:<NAME>END_PI"]])]]))
(deftest test-param-queries-ch-3-1 []
(go
(let [res (<! (bq/<query
'[:find ?title ?year
:in $ [?title ...]
:where
[?m :movie/title ?title]
[?m :movie/year ?year]]
(<! (<test-conn movies-db))
["Lethal Weapon" "Lethal Weapon 2" "Lethal Weapon 3"]))
target [["Lethal Weapon" 1987]
["Lethal Weapon 2" 1989]
["Lethal Weapon 3" 1992]]]
[[(= res target)
{:res res
:target target}]])))
(deftest test-param-queries-ch-3-2 []
(go
(let [conn (<! (<test-conn movies-db))
expect [["Aliens"] ["The Terminator"]]
actual (<! (bq/<query
'[:find ?title
:in $ ?actor ?director
:where
[?a :person/name ?actor]
[?d :person/name ?director]
[?m :movie/cast ?a]
[?m :movie/director ?d]
[?m :movie/title ?title]]
(merge
conn
#_debug-explain)
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"))]
#_(<! (<dump-conn conn))
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(deftest test-more-queries-ch-4-0 []
(go
(let [expect [["movie/title"]
["movie/year"]
["movie/director"]
["movie/cast"]
["trivia"]]
actual (<! (bq/<query
'[:find ?attr
:in $ ?title
:where
[?m :movie/title ?title]
[?m ?attr]]
(<! (<test-conn movies-db))
"Commando"))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(deftest test-more-queries-ch-4-1 []
(go
(let [expect (vec
(reverse
[["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]]))
actual (<! (bq/<query
'[:find ?name
:in $ ?title [?attr ...]
:where
[?m :movie/title ?title]
[?m ?attr ?p]
[?p :person/name ?name]]
(merge
(<! (<test-conn movies-db))
{::bsql/debug-explain-query? false})
"Die Hard"
[:movie/cast :movie/director]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(<deftest test-pred-ch-5-0 []
(let [expect [["Alien"] ["Mad Max"]]
actual (<? (bq/<query
'[:find ?title
:in $ ?year
:where
[?m :movie/title ?title]
[?m :movie/year ?y]
[(<= ?y ?year)]]
(<! (<test-conn movies-db))
1979))]
[[(= expect actual)
nil
{:expect expect
:actual nil #_ actual}]]))
(deftest test-pred-ch-5-1 []
(go
(let [actual (<! (bq/<query
'[:find ?actor
:where
[?d :person/name "PI:NAME:<NAME>END_PI"]
[?d :person/born ?b1]
[?e :person/born ?b2]
[_ :movie/cast ?e]
[(< ?b2 ?b1)]
[?e :person/name ?actor]]
(merge
(<! (<test-conn movies-db))
#_debug-explain)))
expect [["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]]]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(<deftest test-not-equals []
(let [conn (<? (<test-conn movies-db))
result (<! (bq/<query
'[:find ?title
:in $ ?year
:where
[?m :movie/title ?title]
[?m :movie/year ?y]
[(!= ?y ?year)]]
conn
1979))
expect [["Aliens"]
["Braveheart"]
["Commando"]
["Die Hard"]
["First Blood"]
["Lethal Weapon"]
["Lethal Weapon 2"]
["Lethal Weapon 3"]
["Mad Max 2"]
["Mad Max Beyond Thunderdome"]
["Predator"]
["Predator 2"]
["Rambo III"]
["Rambo: First Blood Part II"]
["RoboCop"]
["Terminator 2: Judgment Day"]
["Terminator 3: Rise of the Machines"]
["The Terminator"]]]
[[(= expect result)
nil
{:expect expect
:result result}]]))
(<deftest test-not []
[[true]]
#_(let [conn (<? (<test-conn refs-datoms))
result (<? (bq/<query
'[:find ?e
:where
[?e :box/id]
[?p :box/refs ?e]
#_[(missing? ?p :box/refs)]]
conn))
expect [[:box/id "one"]]]
[[(= expect result)
nil
{:expect expect
:result result}]]))
(comment
(test/<run-var-repl #'test-not)
)
(deftest test-inline-pull-query []
(go
(let [result (<! (bq/<query
'[:find (pull ?e [:box/created-ts])
:where
[?e :box/created-ts 1000]]
(<! (<test-conn refs-datoms))))
expect [[{:box/id "one", :box/created-ts 1000}]]]
[[(= expect result)
nil
{:expect expect
:result result}]])))
(<deftest test-nested-inline-pull-query []
(let [result (<! (bq/<query
'[:find [(pull ?e [:box/created-ts]) ...]
:where
[?e :box/created-ts 1000]]
(<? (<test-conn refs-datoms))))
expect [{:box/id "one", :box/created-ts 1000}]]
[[(= expect result)
nil
{:expect expect
:result result}]]))
(<deftest test-inline-pull-query-error []
(let [result (<! (bq/<query
'[:find (pull ?e '[*])
:where
[?e :box/created-ts]]
(<! (<test-conn refs-datoms))))]
[[(anom/? result)
nil
{:result result}]]))
(deftest test-param-pull-query []
(go
(let [result (<! (bq/<query
'[:find (pull ?e pat)
:in $ pat
:where
[?e :box/created-ts 1000]]
(<! (<test-conn refs-datoms))
[:box/created-ts]))
expect [[{:box/id "one", :box/created-ts 1000}]]]
[[(= expect result)
nil
{:expect expect
:result result}]])))
(comment
(test/<run-var-repl #'test-param-pull-query)
)
(<deftest test-like-query []
(let [result (<! (bq/<query
'[:find ?text
:in $ ?ts ?like-query
:where
[?e :box/created-ts ?ts]
[?e :box/text ?text]
[(sql-like ?text ?like-query)]]
(<? (<test-conn refs-datoms))
1000
"%ith%"))
expect [["hithere"]]]
[[(= expect result)
nil
{:expect expect
:result result}]]))
(<deftest test-bool-query-true []
(let [result (<! (bq/<query
'[:find ?e
:where
[?e :box/bool? true]]
(<? (<test-conn refs-datoms))))
expect [[[:box/id "six"]]]]
[[(= expect result)
nil
{:expect expect
:result result}]]))
(<deftest test-bool-query-false []
(let [result (<! (bq/<query
'[:find ?e
:where
[?e :box/bool? false]]
(<? (<test-conn refs-datoms))))
expect [[[:box/id "seven"]]]]
[[(= expect result)
nil
{:expect expect
:result result}]]))
(comment
(test/<run-var-repl #'test-bool-query-false)
)
(deftest test-ident-param []
(go
(let [conn (<! (<test-conn refs-datoms))
result (<! (bq/<query
'[:find (pull ?e [*])
:in $ ?child
:where
[?e :box/refs ?child]]
conn
[:box/id "five"]))
expect [[{:box/id "two",
:box/updated-ts 2000,
:box/created-ts 2000
:box/refs [{:box/id "five"}]}]]]
[[(= expect result)
nil
{:expect expect
:result result}]])))
(deftest test-ident-param-multi []
(go
(let [result (<! (bq/<query
'[:find (pull ?e [*])
:in $ [?child ...]
:where
[?e :box/refs ?child]]
(<! (<test-conn refs-datoms))
[[:box/id "five"]
[:box/id "two"]]))
expect [[{:box/id "two",
:box/updated-ts 2000,
:box/created-ts 2000
:box/refs [{:box/id "five"}]}]]]
[[(= expect result)
nil
{:expect expect
:result result}]])))
;; Pull
(<deftest test-pull-entity []
(let [expect
{:box/id "one",
:box/created-ts 1000,
:box/updated-ts 1000,
:box/text "hPI:NAME:<NAME>END_PI",
:box/ref {:box/id "two"},
:box/refs [{:box/id "three"} {:box/id "four"}]}
actual
(<! (bq/<pull
(merge
test-schema
(<? (<test-conn refs-datoms)))
'[*]
{:box/id "one"}))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-pull-wildcard []
(let [expect
{:box/id "one",
:box/created-ts 1000,
:box/updated-ts 1000,
:box/text "hPI:NAME:<NAME>END_PIere",
:box/ref {:box/id "two"},
:box/refs [{:box/id "three"} {:box/id "four"}]}
actual
(<! (bq/<pull
(merge
test-schema
(<? (<test-conn refs-datoms)))
'[*]
[:box/id "one"]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-pull-empty []
(let [conn (<! (<test-conn))
_ (<? (bq/<transact
conn
[[:box/assoc [:box/id "one"] :box/text "hi"]]))
expect []
actual
(<! (bq/<query
'[:find (pull ?e [:box/none])
:where
[?e :box/id "one"]]
(merge
test-schema
conn)))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(deftest test-pull-attrs []
(go
(let [expect
{:box/id "one",
:box/created-ts 1000}
actual
(<! (bq/<pull
(merge
test-schema
(<! (<test-conn refs-datoms)))
'[:box/created-ts]
[:box/id "one"]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(deftest test-pull-single-ref []
(go
(let [expect
{:box/id "one",
:box/created-ts 1000,
:box/updated-ts 1000,
:box/text "PI:NAME:<NAME>END_PI",
:box/ref
{:box/id "two",
:box/updated-ts 2000,
:box/created-ts 2000,
:box/refs [{:box/id "five"}]},
:box/refs [{:box/id "three"} {:box/id "four"}]}
actual
(<! (bq/<pull
(merge
test-schema
(<! (<test-conn refs-datoms)))
'[*
{:box/ref [*]}]
[:box/id "one"]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(<deftest test-pull-multi-ref []
(let [expect
{:box/id "one",
:box/created-ts 1000,
:box/updated-ts 1000,
:box/text "PI:NAME:<NAME>END_PI",
:box/ref {:box/id "two"},
:box/refs
[{:box/id "three", :box/created-ts 3000, :box/updated-ts 3000}
{:box/id "four", :box/created-ts 4000, :box/updated-ts 4000}]}
actual
(<! (bq/<pull
(merge
test-schema
(<? (<test-conn refs-datoms)))
'[*
{:box/refs [*]}]
[:box/id "one"]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(deftest test-pull-multi-ref-limit []
(go
(let [expect
{:box/id "one",
:box/created-ts 1000,
:box/ref {:box/id "two"},
:box/refs
[{:box/id "three", :box/created-ts 3000}]}
actual
(<! (bq/<pull
(merge
test-schema
(<! (<test-conn refs-datoms)))
'[*
{(limit :box/refs 1) [*]}]
[:box/id "one"]))]
[[true]]
#_[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(<deftest test-pull-multi []
(let [expect
[{:box/id "one",
:box/created-ts 1000}
{:box/id "two",
:box/created-ts 2000}]
actual
(<! (bq/<pull-multi
(merge
test-schema
(<? (<test-conn refs-datoms)))
'[:box/created-ts]
[{:box/id "one"}
{:box/id "two"}]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-transact-basic []
(let [conn (<? (<test-conn))
_ (<! (bq/<transact
(merge
test-schema
conn)
[[:box/assoc
[:box/id "one"]
:box/created-ts
1000]
{:box/id "two"
:box/ref {:box/id "three"
:box/created-ts 3000}
:box/refs [{:box/id "four"
:box/created-ts 4000}
{:box/id "five"
:box/created-ts 5000}]
:box/created-ts 2000}]))
expect [[:box/id "one"]]
actual (<! (bq/<query
'[:find [?e ...]
:where
[?e :box/created-ts 1000]]
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-transact-bool []
(let [conn (<? (<test-conn))
_ (<! (bq/<transact
(merge
test-schema
conn)
[[:box/assoc
[:box/id "one"]
:box/bool?
false]
[:box/assoc
[:box/id "two"]
:box/bool?
true]]))
expect [[:box/id "one"]]
actual (<! (bq/<query
'[:find [?e ...]
:where
[?e :box/bool? false]]
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(comment
(test/<run-var-repl #'test-transact-bool)
)
(<deftest test-transact-dissoc []
(let [conn (<? (<test-conn refs-datoms))
_ (<? (bq/<transact
(merge
test-schema
conn)
[[:box/dissoc
[:box/id "one"]
:box/refs
[:box/id "three"]]]))
expect [{:box/id "one",
:box/refs [{:box/id "four"}]}]
actual (<? (bq/<query
'[:find [(pull ?e [:box/refs]) ...]
:where
[?e :box/id "one"]]
conn))]
#_(bq/<inspect-conn conn)
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-transact-ref-maps []
;; transact should _not_ expand entities in txfs like :box/assoc etc
(let [conn (merge
(<? (<test-conn))
{::bsql/debug-explain-query? false})
_ (<! (bq/<transact
(merge
test-schema
conn)
[[:box/assoc
{:box/id "one"}
:box/ref
{:box/id "two"
:box/created-ts 2000}]]))
actual (<! (bq/<pull
conn
'[*
{:box/ref [*]}]
[:box/id "one"]))
expect {:box/id "one", :box/ref {:box/id "two"}}]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(deftest test-transact-nested-single []
(go
(let [conn (merge
(<! (<test-conn))
{::bsql/debug-explain-query? false})
_ (<! (bq/<transact
(merge
test-schema
conn)
[{:box/id "two"
:box/ref {:box/id "three"
:box/created-ts 3000}
:box/refs [{:box/id "four"
:box/created-ts 4000}
{:box/id "five"
:box/created-ts 5000}]
:box/created-ts 2000}]))
expect [3000]
actual (<! (bq/<query
'[:find [?created-ts ...]
:where
[[:box/id "three"] :box/created-ts ?created-ts]]
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(deftest test-transact-nested-multi []
(go
(let [conn (<! (<test-conn))
_ (<! (bq/<transact
(merge
test-schema
conn)
[{:box/id "two"
:box/ref {:box/id "three"
:box/created-ts 3000}
:box/refs [{:box/id "four"
:box/created-ts 4000}
{:box/id "five"
:box/created-ts 5000}]
:box/created-ts 2000}]))
expect [5000]
actual (<! (bq/<query
'[:find [?created-ts ...]
:where
["five" :box/created-ts ?created-ts]]
conn))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]])))
(<deftest test-transact-data-types []
(let [conn (<? (<test-conn))
transact-res
(<! (bq/<transact
(merge
test-schema
conn)
[{:box/id "one"
:box/string "hello"
:box/long 123
:box/double 1.23
:box/bool true
:box/map {:foo "bar"}
:box/vec [1 2 3]
:box/list '(1 2 3)
:box/keyword :keyword}]))
expect {:box/id "one",
:box/vec [1 2 3],
:box/list '(1 2 3),
:box/string "hello",
:box/bool true,
:box/map {:foo "bar"},
:box/double 1.23,
:box/long 123
:box/keyword :keyword}
actual (<! (bq/<pull
conn
'[*]
[:box/id "one"]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]
[(not (anom/? transact-res))
nil
transact-res]]))
(<deftest test-transact-delete []
(let [conn (<? (<test-conn))
_ (<? (bq/<transact
conn
[{:box/id "one"
:box/string "hello"
:box/long 123
:box/double 1.23
:box/bool true
:box/map {:foo "bar"}
:box/vec [1 2 3]
:box/list '(1 2 3)}
[:box/delete [:box/id "one"]]
{:box/id "one"
:box/string "goodbye"}]))
_ (<? (bq/<transact
conn
[]))
expect {:box/id "one"
:box/string "goodbye"}
actual (<! (bq/<pull
conn
'[*]
[:box/id "one"]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-transact-delete-ref []
(let [conn (<? (<test-conn))
_ (<? (bq/<transact
conn
[{:box/id "one"
:box/refs [{:box/id "two"}
{:box/id "three"}]}
[:box/delete [:box/id "two"]]]))
expect {:box/id "one",
:box/refs [{:box/id "three"}]}
actual (<! (bq/<pull
conn
'[*]
[:box/id "one"]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(<deftest test-transact-zeros-string
[]
(let [conn (<? (<test-conn))
_ (<! (bq/<transact
(merge
test-schema
conn)
[[:box/assoc
[:box/id "one"]
:box/title
"000"]]))
expect {:box/id "one"
:box/title "000"}
actual (<! (bq/<pull
conn
'[:box/title]
[:box/id "one"]))]
[[(= expect actual)
nil
{:expect expect
:actual actual}]]))
(comment
(test/<run-var-repl #'test-transact-zeros-string)
)
;; Reagent stuff
#_(<deftest test-reagent []
(let [conn (<? (<test-conn refs-datoms))
id (ks/uuid)
ratom (<? (br/<tracked-query
id
'[:find ?e
:where
[?e :box/created-ts]]
conn))
res1 @ratom
_ (<? (br/<transact
conn
[[:box/delete [:box/id "one"]]]))
res2 @ratom
expect [[[:box/id "two"]]
[[:box/id "three"]]
[[:box/id "four"]]
[[:box/id "five"]]]]
[[(= expect res2)
nil
{:res2 res2
:expect expect}]]))
(comment
(go
(let [conn (<! (<test-conn))]
(<! (bq/<transact
(merge
test-schema
conn)
[[:box/assoc
[:box/id "one"]
:box/created-ts
1000]
{:box/id "two"
:box/ref {:box/id "three"
:box/created-ts 3000}
:box/refs [{:box/id "four"
:box/created-ts 4000}
{:box/id "five"
:box/created-ts 5000}]
:box/created-ts 2000}]))
(ks/pp (<! (bq/<query
'[:find [?e ...]
:where
[?e :box/created-ts 1000]]
conn)))))
)
(comment
(test/<run-var-repl #'test-pred-ch-5-0)
(test/<run-var-repl #'test-pull-multi-ref)
(test/<run-ns-repl 'rx.node.box2.tests)
;; https://docs.datomic.com/on-prem/query.html
;; http://www.learndatalogtoday.org/
;; punt test-param-queries-ch-3-3
;; punt test-more-queries-ch-4-2 & 3
;; punt test-pred-ch-5-2 & 3
;; punt tranformation functions ch 6
;; punt aggregates
;; punt rules
(go
(ks/pp
(let [conn (<! (<test-conn refs-datoms))]
(<! (sql/<exec
(::bsql/db conn)
["SELECT DISTINCT c0.ENTITY AS \"?e\" FROM datoms AS c0
INNER JOIN datoms AS c1 ON c0.ENTITY=c1.VALUE WHERE NOT c1.ATTR=? AND c0.ENTITY!=c1.VALUE"
"box/refs"])))))
(go
(ks/pp
(let [conn (<! (<test-conn refs-datoms))]
(<! (sql/<exec
(::bsql/db conn)
[(str "SELECT DISTINCT c0.ENTITY as c0ent, c0.ATTR as c0attr, c0.VALUE as c0val, c1.ENTITY as c1ent, c1.ATTR as c1attr, c1.VALUE as c1val from datoms" " AS c0 INNER JOIN datoms AS c1 ON c0.ENTITY=c1.VALUE")])))))
(go
(ks/pp
(let [conn (<! (<test-conn refs-datoms))]
(<! (sql/<exec
(::bsql/db conn)
["
SELECT DISTINCT c0.ENTITY AS \"?e\" FROM datoms AS c0
EXCEPT
SELECT DISTINCT c0.VALUE AS \"?e\" FROM datoms AS c0 WHERE c0.ATTR=?
"
"box/refs"])))))
)
|
[
{
"context": "t\")\n(def source-id \"newsfeed\")\n(def source-token \"c1bfb47c-39b8-4224-bb18-96edf85e3f7b\")\n(declare manifest)\n\n(defn choose-best-link\n \"F",
"end": 1435,
"score": 0.7950267195701599,
"start": 1399,
"tag": "KEY",
"value": "c1bfb47c-39b8-4224-bb18-96edf85e3f7b"
}
] | src/event_data_agents/agents/newsfeed/core.clj | CrossRef/event-data-agents | 3 | ; (with-open [feed (:body (client/get feed-url {:socket-timeout 10000 :conn-timeout 10000 :as :stream}))] (let [reader (new XmlReader feed)] (actions-from-xml-reader "XYZ" feed-url reader)))
(ns event-data-agents.agents.newsfeed.core
"Process every post that appears in a news feed.
Schedule and checkpointing:
Continually loop over the newsfeed list.
Check each newsfeed no more than once per C."
(:require [event-data-agents.util :as util]
[clj-http.client :as client]
[event-data-common.checkpoint :as checkpoint]
[event-data-common.evidence-log :as evidence-log]
[event-data-common.url-cleanup :as url-cleanup]
[clojure.tools.logging :as log]
[clojure.java.io :as io]
[config.core :refer [env]]
[clj-time.core :as clj-time]
[clj-time.coerce :as clj-time-coerce]
[clj-time.format :as clj-time-format]
[throttler.core :refer [throttle-fn]])
(:import [java.net URL]
[java.io InputStreamReader]
[com.rometools.rome.feed.synd SyndFeed SyndEntry SyndContent]
[com.rometools.rome.io SyndFeedInput XmlReader]
[org.apache.commons.codec.digest DigestUtils]
[org.apache.commons.lang3 StringEscapeUtils])
(:gen-class))
(def agent-name "newsfeed-agent")
(def source-id "newsfeed")
(def source-token "c1bfb47c-39b8-4224-bb18-96edf85e3f7b")
(declare manifest)
(defn choose-best-link
"From a seq of links for the same resource, choose the best one based on newsfeed heuristics."
[& urls]
(->> urls
; Remove those that aren't URLs.
(keep #(try (new URL %) (catch Exception _ nil)))
(remove nil?)
; Rank by desirability. Lowest is best.
(sort-by #(cond
; feeds.feedburner.com's URLs go via a Google proxy. Ignore those if possible.
(= (.getHost %) "feedproxy.google.com") 5
:default 1))
first
str))
(def date-format
(:date-time-no-ms clj-time-format/formatters))
(defn parse-section
"Parse a SyndEntry into an Action. Discard the summary and use the url type only.
The Percolator will follow the link to get the content."
[feed-url fetch-date-str ^SyndEntry entry]
(let [title (.getTitle entry)
; Only 'link' is specified as being the URL, but feedburner includes the real URL only in the ID.
; Remove tracking parameters immediately so the action-id is as effective as possible at deduping.
url (url-cleanup/remove-tracking-params
(choose-best-link (.getLink entry) (.getUri entry)))
; Updated date is the date the blog is reported to have been published via the feed.
; Failing that, now, the time we ingested this post URL.
updated (try
(clj-time-coerce/from-date (or (.getUpdatedDate entry)
(.getPublishedDate entry)))
(catch Exception e (clj-time/now)))
; Use the URL of the blog post as the action identifier.
; This means that the same blog post in different feeds (or even sources) will have the same ID.
action-id (DigestUtils/sha1Hex ^String url)]
{:id action-id
:url url
:relation-type-id "discusses"
:occurred-at (clj-time-format/unparse date-format updated)
:observations [{:type :content-url :input-url url :sensitive true}]
:extra {:feed-url feed-url}
:subj {; Title appears as CDATA containing an HTML encoded string (different to XML encoded!)
:title (StringEscapeUtils/unescapeHtml4 title)}}))
(defn actions-from-xml-reader
[evidence-record-id url ^XmlReader reader]
(let [input (new SyndFeedInput)
feed (.build input reader)
entries (.getEntries feed)
parsed-entries (map
(partial
parse-section
url
(clj-time-format/unparse date-format (clj-time/now)))
entries)]
(evidence-log/log! {:i "a0008" :s agent-name :c "newsfeed" :f "parsed-entries"
:v (count parsed-entries) :r evidence-record-id :u url})
parsed-entries))
(defn evidence-record-for-feed
"Get list of parsed Actions from the feed url. Return as an Evidence Record."
[manifest artifact-map feed-url]
(let [base-record (util/build-evidence-record manifest artifact-map)
evidence-record-id (:id base-record)]
(log/info "Retrieve latest from feed:" feed-url)
(evidence-log/log!
{:i "a0009" :s agent-name :c "remote-newsfeed" :f "request" :u feed-url :r evidence-record-id})
(try
(with-open [feed (:body (client/get feed-url {:socket-timeout 10000 :conn-timeout 10000 :as :stream}))]
(let [reader (new XmlReader feed)
actions (actions-from-xml-reader evidence-record-id feed-url reader)]
; Parse succeeded.
(evidence-log/log!
{:i "a000a"
:s agent-name
:c "remote-newsfeed"
:f "parse"
:e "t"
:u feed-url
:r evidence-record-id})
(assoc base-record
; One page of actions.
:pages [{:actions actions}])))
; e.g. com.rometools.rome.io.ParsingFeedException
(catch Exception ex
(do
; Parse failed. Same log ID.
(evidence-log/log!
{:i "a000a"
:s agent-name
:c "remote-newsfeed"
:f "parse"
:e "f"
:u feed-url
:r evidence-record-id})
(log/info "Error parsing data from feed url:" feed-url))))))
(def check-every
"Visit every newsfeed at most this often."
(clj-time/hours 2))
(defn check-newsfeed
[artifact-map newsfeed-url]
(log/info "Check newsfeed url" newsfeed-url)
(let [evidence-record (evidence-record-for-feed manifest artifact-map newsfeed-url)]
(util/send-evidence-record manifest evidence-record)))
(defn main
"Main function for Newsfeed Agent."
[]
(evidence-log/log! {:i "a000c" :s agent-name :c "scan" :f "start"})
(log/info "Start crawl all newsfeeds at" (str (clj-time/now)))
(let [artifact-map (util/fetch-artifact-map manifest ["newsfeed-list"])
newsfeed-list-content (-> artifact-map (get "newsfeed-list") second)
newsfeed-set (clojure.string/split newsfeed-list-content #"\n")
; Check every newsfeed, checkpointing per newsfeed.
results (pmap
#(checkpoint/run-checkpointed!
["newsfeed" "feed-check" %]
(clj-time/hours 1)
; We discard the last-run date anyway, as newsfeeds
; only ever give one page of results.
(clj-time/hours 1)
(fn [_] (check-newsfeed artifact-map %)))
newsfeed-set)]
(log/info "Got newsfeed-list artifact:" (-> artifact-map (get "newsfeed-list") first))
(dorun results)
(evidence-log/log! {:i "a000d" :s agent-name :c "scan" :f "finish"})
(log/info "Finished scan.")))
(def manifest
{:agent-name agent-name
:source-id source-id
:license util/cc-0
:source-token source-token
; Pause 30 minutes between scans to ensure we don't get stuck in a tight loop.
; Each newsfeed is individually checkpointed, so no danger in this being too low.
:schedule [[main (clj-time/minutes 30)]]})
| 64572 | ; (with-open [feed (:body (client/get feed-url {:socket-timeout 10000 :conn-timeout 10000 :as :stream}))] (let [reader (new XmlReader feed)] (actions-from-xml-reader "XYZ" feed-url reader)))
(ns event-data-agents.agents.newsfeed.core
"Process every post that appears in a news feed.
Schedule and checkpointing:
Continually loop over the newsfeed list.
Check each newsfeed no more than once per C."
(:require [event-data-agents.util :as util]
[clj-http.client :as client]
[event-data-common.checkpoint :as checkpoint]
[event-data-common.evidence-log :as evidence-log]
[event-data-common.url-cleanup :as url-cleanup]
[clojure.tools.logging :as log]
[clojure.java.io :as io]
[config.core :refer [env]]
[clj-time.core :as clj-time]
[clj-time.coerce :as clj-time-coerce]
[clj-time.format :as clj-time-format]
[throttler.core :refer [throttle-fn]])
(:import [java.net URL]
[java.io InputStreamReader]
[com.rometools.rome.feed.synd SyndFeed SyndEntry SyndContent]
[com.rometools.rome.io SyndFeedInput XmlReader]
[org.apache.commons.codec.digest DigestUtils]
[org.apache.commons.lang3 StringEscapeUtils])
(:gen-class))
(def agent-name "newsfeed-agent")
(def source-id "newsfeed")
(def source-token "<KEY>")
(declare manifest)
(defn choose-best-link
"From a seq of links for the same resource, choose the best one based on newsfeed heuristics."
[& urls]
(->> urls
; Remove those that aren't URLs.
(keep #(try (new URL %) (catch Exception _ nil)))
(remove nil?)
; Rank by desirability. Lowest is best.
(sort-by #(cond
; feeds.feedburner.com's URLs go via a Google proxy. Ignore those if possible.
(= (.getHost %) "feedproxy.google.com") 5
:default 1))
first
str))
(def date-format
(:date-time-no-ms clj-time-format/formatters))
(defn parse-section
"Parse a SyndEntry into an Action. Discard the summary and use the url type only.
The Percolator will follow the link to get the content."
[feed-url fetch-date-str ^SyndEntry entry]
(let [title (.getTitle entry)
; Only 'link' is specified as being the URL, but feedburner includes the real URL only in the ID.
; Remove tracking parameters immediately so the action-id is as effective as possible at deduping.
url (url-cleanup/remove-tracking-params
(choose-best-link (.getLink entry) (.getUri entry)))
; Updated date is the date the blog is reported to have been published via the feed.
; Failing that, now, the time we ingested this post URL.
updated (try
(clj-time-coerce/from-date (or (.getUpdatedDate entry)
(.getPublishedDate entry)))
(catch Exception e (clj-time/now)))
; Use the URL of the blog post as the action identifier.
; This means that the same blog post in different feeds (or even sources) will have the same ID.
action-id (DigestUtils/sha1Hex ^String url)]
{:id action-id
:url url
:relation-type-id "discusses"
:occurred-at (clj-time-format/unparse date-format updated)
:observations [{:type :content-url :input-url url :sensitive true}]
:extra {:feed-url feed-url}
:subj {; Title appears as CDATA containing an HTML encoded string (different to XML encoded!)
:title (StringEscapeUtils/unescapeHtml4 title)}}))
(defn actions-from-xml-reader
[evidence-record-id url ^XmlReader reader]
(let [input (new SyndFeedInput)
feed (.build input reader)
entries (.getEntries feed)
parsed-entries (map
(partial
parse-section
url
(clj-time-format/unparse date-format (clj-time/now)))
entries)]
(evidence-log/log! {:i "a0008" :s agent-name :c "newsfeed" :f "parsed-entries"
:v (count parsed-entries) :r evidence-record-id :u url})
parsed-entries))
(defn evidence-record-for-feed
"Get list of parsed Actions from the feed url. Return as an Evidence Record."
[manifest artifact-map feed-url]
(let [base-record (util/build-evidence-record manifest artifact-map)
evidence-record-id (:id base-record)]
(log/info "Retrieve latest from feed:" feed-url)
(evidence-log/log!
{:i "a0009" :s agent-name :c "remote-newsfeed" :f "request" :u feed-url :r evidence-record-id})
(try
(with-open [feed (:body (client/get feed-url {:socket-timeout 10000 :conn-timeout 10000 :as :stream}))]
(let [reader (new XmlReader feed)
actions (actions-from-xml-reader evidence-record-id feed-url reader)]
; Parse succeeded.
(evidence-log/log!
{:i "a000a"
:s agent-name
:c "remote-newsfeed"
:f "parse"
:e "t"
:u feed-url
:r evidence-record-id})
(assoc base-record
; One page of actions.
:pages [{:actions actions}])))
; e.g. com.rometools.rome.io.ParsingFeedException
(catch Exception ex
(do
; Parse failed. Same log ID.
(evidence-log/log!
{:i "a000a"
:s agent-name
:c "remote-newsfeed"
:f "parse"
:e "f"
:u feed-url
:r evidence-record-id})
(log/info "Error parsing data from feed url:" feed-url))))))
(def check-every
"Visit every newsfeed at most this often."
(clj-time/hours 2))
(defn check-newsfeed
[artifact-map newsfeed-url]
(log/info "Check newsfeed url" newsfeed-url)
(let [evidence-record (evidence-record-for-feed manifest artifact-map newsfeed-url)]
(util/send-evidence-record manifest evidence-record)))
(defn main
"Main function for Newsfeed Agent."
[]
(evidence-log/log! {:i "a000c" :s agent-name :c "scan" :f "start"})
(log/info "Start crawl all newsfeeds at" (str (clj-time/now)))
(let [artifact-map (util/fetch-artifact-map manifest ["newsfeed-list"])
newsfeed-list-content (-> artifact-map (get "newsfeed-list") second)
newsfeed-set (clojure.string/split newsfeed-list-content #"\n")
; Check every newsfeed, checkpointing per newsfeed.
results (pmap
#(checkpoint/run-checkpointed!
["newsfeed" "feed-check" %]
(clj-time/hours 1)
; We discard the last-run date anyway, as newsfeeds
; only ever give one page of results.
(clj-time/hours 1)
(fn [_] (check-newsfeed artifact-map %)))
newsfeed-set)]
(log/info "Got newsfeed-list artifact:" (-> artifact-map (get "newsfeed-list") first))
(dorun results)
(evidence-log/log! {:i "a000d" :s agent-name :c "scan" :f "finish"})
(log/info "Finished scan.")))
(def manifest
{:agent-name agent-name
:source-id source-id
:license util/cc-0
:source-token source-token
; Pause 30 minutes between scans to ensure we don't get stuck in a tight loop.
; Each newsfeed is individually checkpointed, so no danger in this being too low.
:schedule [[main (clj-time/minutes 30)]]})
| true | ; (with-open [feed (:body (client/get feed-url {:socket-timeout 10000 :conn-timeout 10000 :as :stream}))] (let [reader (new XmlReader feed)] (actions-from-xml-reader "XYZ" feed-url reader)))
(ns event-data-agents.agents.newsfeed.core
"Process every post that appears in a news feed.
Schedule and checkpointing:
Continually loop over the newsfeed list.
Check each newsfeed no more than once per C."
(:require [event-data-agents.util :as util]
[clj-http.client :as client]
[event-data-common.checkpoint :as checkpoint]
[event-data-common.evidence-log :as evidence-log]
[event-data-common.url-cleanup :as url-cleanup]
[clojure.tools.logging :as log]
[clojure.java.io :as io]
[config.core :refer [env]]
[clj-time.core :as clj-time]
[clj-time.coerce :as clj-time-coerce]
[clj-time.format :as clj-time-format]
[throttler.core :refer [throttle-fn]])
(:import [java.net URL]
[java.io InputStreamReader]
[com.rometools.rome.feed.synd SyndFeed SyndEntry SyndContent]
[com.rometools.rome.io SyndFeedInput XmlReader]
[org.apache.commons.codec.digest DigestUtils]
[org.apache.commons.lang3 StringEscapeUtils])
(:gen-class))
(def agent-name "newsfeed-agent")
(def source-id "newsfeed")
(def source-token "PI:KEY:<KEY>END_PI")
(declare manifest)
(defn choose-best-link
"From a seq of links for the same resource, choose the best one based on newsfeed heuristics."
[& urls]
(->> urls
; Remove those that aren't URLs.
(keep #(try (new URL %) (catch Exception _ nil)))
(remove nil?)
; Rank by desirability. Lowest is best.
(sort-by #(cond
; feeds.feedburner.com's URLs go via a Google proxy. Ignore those if possible.
(= (.getHost %) "feedproxy.google.com") 5
:default 1))
first
str))
(def date-format
(:date-time-no-ms clj-time-format/formatters))
(defn parse-section
"Parse a SyndEntry into an Action. Discard the summary and use the url type only.
The Percolator will follow the link to get the content."
[feed-url fetch-date-str ^SyndEntry entry]
(let [title (.getTitle entry)
; Only 'link' is specified as being the URL, but feedburner includes the real URL only in the ID.
; Remove tracking parameters immediately so the action-id is as effective as possible at deduping.
url (url-cleanup/remove-tracking-params
(choose-best-link (.getLink entry) (.getUri entry)))
; Updated date is the date the blog is reported to have been published via the feed.
; Failing that, now, the time we ingested this post URL.
updated (try
(clj-time-coerce/from-date (or (.getUpdatedDate entry)
(.getPublishedDate entry)))
(catch Exception e (clj-time/now)))
; Use the URL of the blog post as the action identifier.
; This means that the same blog post in different feeds (or even sources) will have the same ID.
action-id (DigestUtils/sha1Hex ^String url)]
{:id action-id
:url url
:relation-type-id "discusses"
:occurred-at (clj-time-format/unparse date-format updated)
:observations [{:type :content-url :input-url url :sensitive true}]
:extra {:feed-url feed-url}
:subj {; Title appears as CDATA containing an HTML encoded string (different to XML encoded!)
:title (StringEscapeUtils/unescapeHtml4 title)}}))
(defn actions-from-xml-reader
[evidence-record-id url ^XmlReader reader]
(let [input (new SyndFeedInput)
feed (.build input reader)
entries (.getEntries feed)
parsed-entries (map
(partial
parse-section
url
(clj-time-format/unparse date-format (clj-time/now)))
entries)]
(evidence-log/log! {:i "a0008" :s agent-name :c "newsfeed" :f "parsed-entries"
:v (count parsed-entries) :r evidence-record-id :u url})
parsed-entries))
(defn evidence-record-for-feed
"Get list of parsed Actions from the feed url. Return as an Evidence Record."
[manifest artifact-map feed-url]
(let [base-record (util/build-evidence-record manifest artifact-map)
evidence-record-id (:id base-record)]
(log/info "Retrieve latest from feed:" feed-url)
(evidence-log/log!
{:i "a0009" :s agent-name :c "remote-newsfeed" :f "request" :u feed-url :r evidence-record-id})
(try
(with-open [feed (:body (client/get feed-url {:socket-timeout 10000 :conn-timeout 10000 :as :stream}))]
(let [reader (new XmlReader feed)
actions (actions-from-xml-reader evidence-record-id feed-url reader)]
; Parse succeeded.
(evidence-log/log!
{:i "a000a"
:s agent-name
:c "remote-newsfeed"
:f "parse"
:e "t"
:u feed-url
:r evidence-record-id})
(assoc base-record
; One page of actions.
:pages [{:actions actions}])))
; e.g. com.rometools.rome.io.ParsingFeedException
(catch Exception ex
(do
; Parse failed. Same log ID.
(evidence-log/log!
{:i "a000a"
:s agent-name
:c "remote-newsfeed"
:f "parse"
:e "f"
:u feed-url
:r evidence-record-id})
(log/info "Error parsing data from feed url:" feed-url))))))
(def check-every
"Visit every newsfeed at most this often."
(clj-time/hours 2))
(defn check-newsfeed
[artifact-map newsfeed-url]
(log/info "Check newsfeed url" newsfeed-url)
(let [evidence-record (evidence-record-for-feed manifest artifact-map newsfeed-url)]
(util/send-evidence-record manifest evidence-record)))
(defn main
"Main function for Newsfeed Agent."
[]
(evidence-log/log! {:i "a000c" :s agent-name :c "scan" :f "start"})
(log/info "Start crawl all newsfeeds at" (str (clj-time/now)))
(let [artifact-map (util/fetch-artifact-map manifest ["newsfeed-list"])
newsfeed-list-content (-> artifact-map (get "newsfeed-list") second)
newsfeed-set (clojure.string/split newsfeed-list-content #"\n")
; Check every newsfeed, checkpointing per newsfeed.
results (pmap
#(checkpoint/run-checkpointed!
["newsfeed" "feed-check" %]
(clj-time/hours 1)
; We discard the last-run date anyway, as newsfeeds
; only ever give one page of results.
(clj-time/hours 1)
(fn [_] (check-newsfeed artifact-map %)))
newsfeed-set)]
(log/info "Got newsfeed-list artifact:" (-> artifact-map (get "newsfeed-list") first))
(dorun results)
(evidence-log/log! {:i "a000d" :s agent-name :c "scan" :f "finish"})
(log/info "Finished scan.")))
(def manifest
{:agent-name agent-name
:source-id source-id
:license util/cc-0
:source-token source-token
; Pause 30 minutes between scans to ensure we don't get stuck in a tight loop.
; Each newsfeed is individually checkpointed, so no danger in this being too low.
:schedule [[main (clj-time/minutes 30)]]})
|
[
{
"context": "; Copyright (c) 2017-present Walmart, Inc.\n;\n; Licensed under the Apache License, Vers",
"end": 36,
"score": 0.9219427704811096,
"start": 29,
"tag": "NAME",
"value": "Walmart"
}
] | test/com/walmartlabs/lacinia/indirect_schema_test.clj | henryw374/lacinia-pedestal | 0 | ; Copyright (c) 2017-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.indirect-schema-test
(:require
[clojure.test :refer [deftest is use-fixtures]]
[com.walmartlabs.lacinia.pedestal :as lp]
[clj-http.client :as client]
[clojure.string :as str]
[com.walmartlabs.lacinia.test-utils
:refer [test-server-fixture subscriptions-fixture
send-json-request
send-init send-data
expect-message *ping-subscribes *ping-cleanups
*subscriber-id]]))
(use-fixtures :once (test-server-fixture {:graphiql true
:indirect-schema true
:subscriptions true
:keep-alive-ms 200}))
(use-fixtures :each subscriptions-fixture)
(deftest standard-json-request
(let [response
(send-json-request :post
{:query "{ echo(value: \"hello\") { value method }}"})]
(is (= 200 (:status response)))
(is (= {:data {:echo {:method "post"
:value "hello"}}}
(:body response)))))
(deftest short-subscription
(send-init)
(expect-message {:type "connection_ack"})
;; There's an observability issue with core.async, of course, just as there's an observability
;; problem inside pure and lazy functions. We have to draw conclusions from some global side-effects
;; we've introduced.
(is (= @*ping-subscribes @*ping-cleanups)
"Any prior subscribes have been cleaned up.")
(let [id (swap! *subscriber-id inc)]
(send-data {:id id
:type :start
:payload
{:query "subscription { ping(message: \"short\", count: 2 ) { message }}"}})
(expect-message {:id id
:payload {:data {:ping {:message "short #1"}}}
:type "data"})
(is (> @*ping-subscribes @*ping-cleanups)
"A subscribe is active, but has not been cleaned up.")
(expect-message {:id id
:payload {:data {:ping {:message "short #2"}}}
:type "data"})
(expect-message {:id id
:type "complete"})
(is (= @*ping-subscribes @*ping-cleanups)
"The completed subscription has been cleaned up.")))
| 93164 | ; Copyright (c) 2017-present <NAME>, Inc.
;
; Licensed under the Apache License, Version 2.0 (the "License")
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
(ns com.walmartlabs.lacinia.indirect-schema-test
(:require
[clojure.test :refer [deftest is use-fixtures]]
[com.walmartlabs.lacinia.pedestal :as lp]
[clj-http.client :as client]
[clojure.string :as str]
[com.walmartlabs.lacinia.test-utils
:refer [test-server-fixture subscriptions-fixture
send-json-request
send-init send-data
expect-message *ping-subscribes *ping-cleanups
*subscriber-id]]))
(use-fixtures :once (test-server-fixture {:graphiql true
:indirect-schema true
:subscriptions true
:keep-alive-ms 200}))
(use-fixtures :each subscriptions-fixture)
(deftest standard-json-request
(let [response
(send-json-request :post
{:query "{ echo(value: \"hello\") { value method }}"})]
(is (= 200 (:status response)))
(is (= {:data {:echo {:method "post"
:value "hello"}}}
(:body response)))))
(deftest short-subscription
(send-init)
(expect-message {:type "connection_ack"})
;; There's an observability issue with core.async, of course, just as there's an observability
;; problem inside pure and lazy functions. We have to draw conclusions from some global side-effects
;; we've introduced.
(is (= @*ping-subscribes @*ping-cleanups)
"Any prior subscribes have been cleaned up.")
(let [id (swap! *subscriber-id inc)]
(send-data {:id id
:type :start
:payload
{:query "subscription { ping(message: \"short\", count: 2 ) { message }}"}})
(expect-message {:id id
:payload {:data {:ping {:message "short #1"}}}
:type "data"})
(is (> @*ping-subscribes @*ping-cleanups)
"A subscribe is active, but has not been cleaned up.")
(expect-message {:id id
:payload {:data {:ping {:message "short #2"}}}
:type "data"})
(expect-message {:id id
:type "complete"})
(is (= @*ping-subscribes @*ping-cleanups)
"The completed subscription has been cleaned up.")))
| true | ; Copyright (c) 2017-present PI:NAME:<NAME>END_PI, Inc.
;
; Licensed under the Apache License, Version 2.0 (the "License")
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
(ns com.walmartlabs.lacinia.indirect-schema-test
(:require
[clojure.test :refer [deftest is use-fixtures]]
[com.walmartlabs.lacinia.pedestal :as lp]
[clj-http.client :as client]
[clojure.string :as str]
[com.walmartlabs.lacinia.test-utils
:refer [test-server-fixture subscriptions-fixture
send-json-request
send-init send-data
expect-message *ping-subscribes *ping-cleanups
*subscriber-id]]))
(use-fixtures :once (test-server-fixture {:graphiql true
:indirect-schema true
:subscriptions true
:keep-alive-ms 200}))
(use-fixtures :each subscriptions-fixture)
(deftest standard-json-request
(let [response
(send-json-request :post
{:query "{ echo(value: \"hello\") { value method }}"})]
(is (= 200 (:status response)))
(is (= {:data {:echo {:method "post"
:value "hello"}}}
(:body response)))))
(deftest short-subscription
(send-init)
(expect-message {:type "connection_ack"})
;; There's an observability issue with core.async, of course, just as there's an observability
;; problem inside pure and lazy functions. We have to draw conclusions from some global side-effects
;; we've introduced.
(is (= @*ping-subscribes @*ping-cleanups)
"Any prior subscribes have been cleaned up.")
(let [id (swap! *subscriber-id inc)]
(send-data {:id id
:type :start
:payload
{:query "subscription { ping(message: \"short\", count: 2 ) { message }}"}})
(expect-message {:id id
:payload {:data {:ping {:message "short #1"}}}
:type "data"})
(is (> @*ping-subscribes @*ping-cleanups)
"A subscribe is active, but has not been cleaned up.")
(expect-message {:id id
:payload {:data {:ping {:message "short #2"}}}
:type "data"})
(expect-message {:id id
:type "complete"})
(is (= @*ping-subscribes @*ping-cleanups)
"The completed subscription has been cleaned up.")))
|
[
{
"context": "/some-obelisk-address\"\n :basic-auth [\"username\" \"password\"]})\n\n (def cookie (api/login \"admin\" ",
"end": 8943,
"score": 0.8967368006706238,
"start": 8935,
"tag": "USERNAME",
"value": "username"
},
{
"context": "sk-address\"\n :basic-auth [\"username\" \"password\"]})\n\n (def cookie (api/login \"admin\" \"admin\" opt",
"end": 8954,
"score": 0.8362433910369873,
"start": 8946,
"tag": "PASSWORD",
"value": "password"
}
] | src/obelisk_exporter/core.clj | Akeboshiwind/obelisk-exporter | 0 | (ns obelisk-exporter.core
(:require [obelisk-ui.api :as api]
[bidi.ring :refer [make-handler]]
[ring.util.response :as res]
[ring.adapter.jetty :refer [run-jetty]]
[iapetos.core :as p]
[iapetos.export :as e]
[obelisk-exporter.metrics :as m]
[obelisk-exporter.config :as c]
[clojure.tools.logging :as log]
[clojure.tools.cli :refer [parse-opts]])
(:gen-class))
;;;; --- Prometheus Metrics Registry --- ;;;;
(defn make-registry
[]
(-> (p/collector-registry)
(p/register
;; :hashrateData metrics
(p/gauge :obelisk-exporter/hash-rate-gigahashes-per-second
{:description "The total amount of hashrate each board has."
:labels [:board]})
;; :hashrateData metrics
(p/gauge :obelisk-exporter/memory-free-megabytes
{:description "The amount of free memory"})
(p/gauge :obelisk-exporter/memory-total-megabytes
{:description "The total amount of memory"})
;; :poolStatus metrics
(p/gauge :obelisk-exporter/pool-last-share-time
{:description "The last time a share was received"
:labels [:pool]})
(p/gauge :obelisk-exporter/pool-share-count-total
{:description "The amount of shares"
:labels [:pool :status]})
;; :hashboardStatus
(p/gauge :obelisk-exporter/board-power-supply-temp-celsius
{:description "The temperature of the board power supply"
:labels [:board]})
(p/gauge :obelisk-exporter/board-num-cores-total
{:description "The number of cores a board has available"
:labels [:board]})
(p/gauge :obelisk-exporter/board-temp-celsius
{:description "The temperature of the board"
:labels [:board]})
(p/gauge :obelisk-exporter/board-chip-temp-celsius
{:description "The temperature of the board chip"
:labels [:board]})
(p/gauge :obelisk-exporter/board-hot-chip-temp-celsius
{:description "The temperature of the board hot chip"
:labels [:board]})
(p/gauge :obelisk-exporter/board-share-count-total
{:description "The amount of shares a board has received"
:labels [:board :status]})
(p/gauge :obelisk-exporter/board-num-chips-total
{:description "The number of chips a board has available"
:labels [:board]})
(p/gauge :obelisk-exporter/fan-speed-rmp
{:description "The speed of the fans"
:labels [:fan]}))))
;;;; --- Handlers --- ;;;;
(defn index-handler
[r]
(log/info "User accessed " (:uri r))
(res/response
"<body>Metrics are available <a href=\"/metrics\">here</a>.<br>More information about this exporter is available <a href=\"https://github.com/akeboshiwind/obelisk-exporter\">here</a>.</body>"))
(defn- server-error
[body]
{:status 500
:headers {}
:body body})
(defn- set-metrics
[registry metric value-key data]
(doseq [data-point data]
(let [value (value-key data-point)]
(p/set registry metric (dissoc data-point value-key) value)))
registry)
(comment
(def r
(-> (p/collector-registry)
(p/register
(p/gauge :obelisk/test-total
{:labels [:label]}))))
(set-metrics
r
:obelisk/test-total
:value
[{:value 1 :label 0}
{:value 5 :label 1}
{:value 1 :label 2}])
(->> (e/text-format r)
(print))
[])
(defn metrics-handler
[r]
(log/info "User accessed " (:uri r))
(let [opts (merge {:server-address (c/config :obelisk-ui :server-address)}
(when (c/config :obelisk-ui :basic-auth)
{:basic-auth [(c/config :obelisk-ui :basic-auth :user)
(c/config :obelisk-ui :basic-auth :password)]}))]
(if-let [cookie (api/login (c/config :obelisk-ui :panel :user)
(c/config :obelisk-ui :panel :password)
opts)]
(let [opts (assoc opts :cookie cookie)]
(log/info "Login successful")
(if-let [dashboard (api/dashboard opts)]
(do
(log/info "Dashboard scrape successful")
(-> (make-registry)
;; :hashrateData metrics
(set-metrics :obelisk-exporter/hash-rate-gigahashes-per-second
:hash-rate
(m/hash-rates dashboard))
;; :systemInfo metrics
(p/set :obelisk-exporter/memory-free-megabytes (m/free-memory dashboard))
(p/set :obelisk-exporter/memory-total-megabytes (m/total-memory dashboard))
;; :poolStatus metrics
(set-metrics :obelisk-exporter/pool-last-share-time
:last-share-time
(m/last-share-times dashboard))
(set-metrics :obelisk-exporter/pool-share-count-total
:value
(m/share-count dashboard))
;; :hashboardStatus metrics
(set-metrics :obelisk-exporter/board-power-supply-temp-celsius
:power-supply-temp
(m/power-supply-temp dashboard))
(set-metrics :obelisk-exporter/board-num-cores-total
:num-cores
(m/num-cores dashboard))
(set-metrics :obelisk-exporter/board-temp-celsius
:board-temp
(m/board-temp dashboard))
(set-metrics :obelisk-exporter/board-chip-temp-celsius
:chip-temp
(m/chip-temp dashboard))
(set-metrics :obelisk-exporter/board-hot-chip-temp-celsius
:hot-chip-temp
(m/hot-chip-temp dashboard))
(set-metrics :obelisk-exporter/board-share-count-total
:value
(m/board-share-count dashboard))
(set-metrics :obelisk-exporter/board-num-chips-total
:num-chips
(m/num-chips dashboard))
(set-metrics :obelisk-exporter/fan-speed-rmp
:fan-speed
(m/fan-speeds dashboard))
;; rendering
e/text-format
res/response))
(do
(log/error "Failed to get the dashboard output")
(server-error
"Server Error: Failed to get a decent response from the obelisk ui."))))
(do
(log/error "Failed to login to obelisk panel")
(log/info "OBELISK_SERVER_ADDRESS: " (c/config :obelisk-ui :server-address))
(log/info "BASIC_AUTH_USER: " (c/config :obelisk-ui :basic-auth :user))
(log/info "BASIC_AUTH_PASSWORD: " (if (nil? (c/config :obelisk-ui :basic-auth :password))
"nil"
"not nil"))
(log/info "OBELISK_PANEL_USER: " (c/config :obelisk-ui :panel :user))
(log/info "OBELISK_PANEL_PASSWORD: " (if (nil? (c/config :obelisk-ui :panel :password))
"nil"
"not nil"))
(server-error
"Server Error: Misconfigured, please check configuration.")))))
(defn not-found
[r]
(log/info "User accessed " (:uri r))
(res/not-found "404 Not Found"))
(def routes
["" [["" index-handler]
["/" index-handler]
["/metrics" [["" metrics-handler]
["/" metrics-handler]]]
[true not-found]]])
(def handler
(make-handler routes))
;;;; --- Main --- ;;;;
(def cli-options
[["-h" "--help" "Shows this message"]
[nil "--config.file PATH" "Config YAML file"
:id :config-file]])
(def usage-text
"usage: obelisk-exporter [<flags>]
An exporter for the obelisk miner's panel
Flags:
")
(defn -main
[& args]
(let [{:keys [options summary]} (parse-opts args cli-options)]
(if (:help options)
(do
(println (str usage-text summary)))
(do
(if-let [file (:config-file options)]
(c/load! file)
(c/load!))
(let [server (run-jetty handler {:port (c/config :general :port)
:host (c/config :general :server-address)
:join? false})]
(fn []
(.stop server)))))))
(comment
(def opts {:server-address "http://some-obelisk-address"
:basic-auth ["username" "password"]})
(def cookie (api/login "admin" "admin" opts))
(def opts (assoc opts :cookie cookie))
(def d (api/dashboard opts))
(keys d)
;; The :hashrateData `is` sorted
(->> (:hashrateData d)
(map :time)
(reduce (fn [a b]
(if (> b a)
b
(reduced false)))))
;; ::hash-rate-total
(->> (:hashrateData d)
(last)
(clojure.pprint/pprint))
(->> (:systemInfo d)
(reduce (fn [acc {:keys [name value]}]
(assoc acc name value))
{})
(clojure.pprint/pprint))
(->> (:poolStatus d)
(clojure.pprint/pprint))
(->> (:hashboardStatus d)
(clojure.pprint/pprint))
[])
| 4185 | (ns obelisk-exporter.core
(:require [obelisk-ui.api :as api]
[bidi.ring :refer [make-handler]]
[ring.util.response :as res]
[ring.adapter.jetty :refer [run-jetty]]
[iapetos.core :as p]
[iapetos.export :as e]
[obelisk-exporter.metrics :as m]
[obelisk-exporter.config :as c]
[clojure.tools.logging :as log]
[clojure.tools.cli :refer [parse-opts]])
(:gen-class))
;;;; --- Prometheus Metrics Registry --- ;;;;
(defn make-registry
[]
(-> (p/collector-registry)
(p/register
;; :hashrateData metrics
(p/gauge :obelisk-exporter/hash-rate-gigahashes-per-second
{:description "The total amount of hashrate each board has."
:labels [:board]})
;; :hashrateData metrics
(p/gauge :obelisk-exporter/memory-free-megabytes
{:description "The amount of free memory"})
(p/gauge :obelisk-exporter/memory-total-megabytes
{:description "The total amount of memory"})
;; :poolStatus metrics
(p/gauge :obelisk-exporter/pool-last-share-time
{:description "The last time a share was received"
:labels [:pool]})
(p/gauge :obelisk-exporter/pool-share-count-total
{:description "The amount of shares"
:labels [:pool :status]})
;; :hashboardStatus
(p/gauge :obelisk-exporter/board-power-supply-temp-celsius
{:description "The temperature of the board power supply"
:labels [:board]})
(p/gauge :obelisk-exporter/board-num-cores-total
{:description "The number of cores a board has available"
:labels [:board]})
(p/gauge :obelisk-exporter/board-temp-celsius
{:description "The temperature of the board"
:labels [:board]})
(p/gauge :obelisk-exporter/board-chip-temp-celsius
{:description "The temperature of the board chip"
:labels [:board]})
(p/gauge :obelisk-exporter/board-hot-chip-temp-celsius
{:description "The temperature of the board hot chip"
:labels [:board]})
(p/gauge :obelisk-exporter/board-share-count-total
{:description "The amount of shares a board has received"
:labels [:board :status]})
(p/gauge :obelisk-exporter/board-num-chips-total
{:description "The number of chips a board has available"
:labels [:board]})
(p/gauge :obelisk-exporter/fan-speed-rmp
{:description "The speed of the fans"
:labels [:fan]}))))
;;;; --- Handlers --- ;;;;
(defn index-handler
[r]
(log/info "User accessed " (:uri r))
(res/response
"<body>Metrics are available <a href=\"/metrics\">here</a>.<br>More information about this exporter is available <a href=\"https://github.com/akeboshiwind/obelisk-exporter\">here</a>.</body>"))
(defn- server-error
[body]
{:status 500
:headers {}
:body body})
(defn- set-metrics
[registry metric value-key data]
(doseq [data-point data]
(let [value (value-key data-point)]
(p/set registry metric (dissoc data-point value-key) value)))
registry)
(comment
(def r
(-> (p/collector-registry)
(p/register
(p/gauge :obelisk/test-total
{:labels [:label]}))))
(set-metrics
r
:obelisk/test-total
:value
[{:value 1 :label 0}
{:value 5 :label 1}
{:value 1 :label 2}])
(->> (e/text-format r)
(print))
[])
(defn metrics-handler
[r]
(log/info "User accessed " (:uri r))
(let [opts (merge {:server-address (c/config :obelisk-ui :server-address)}
(when (c/config :obelisk-ui :basic-auth)
{:basic-auth [(c/config :obelisk-ui :basic-auth :user)
(c/config :obelisk-ui :basic-auth :password)]}))]
(if-let [cookie (api/login (c/config :obelisk-ui :panel :user)
(c/config :obelisk-ui :panel :password)
opts)]
(let [opts (assoc opts :cookie cookie)]
(log/info "Login successful")
(if-let [dashboard (api/dashboard opts)]
(do
(log/info "Dashboard scrape successful")
(-> (make-registry)
;; :hashrateData metrics
(set-metrics :obelisk-exporter/hash-rate-gigahashes-per-second
:hash-rate
(m/hash-rates dashboard))
;; :systemInfo metrics
(p/set :obelisk-exporter/memory-free-megabytes (m/free-memory dashboard))
(p/set :obelisk-exporter/memory-total-megabytes (m/total-memory dashboard))
;; :poolStatus metrics
(set-metrics :obelisk-exporter/pool-last-share-time
:last-share-time
(m/last-share-times dashboard))
(set-metrics :obelisk-exporter/pool-share-count-total
:value
(m/share-count dashboard))
;; :hashboardStatus metrics
(set-metrics :obelisk-exporter/board-power-supply-temp-celsius
:power-supply-temp
(m/power-supply-temp dashboard))
(set-metrics :obelisk-exporter/board-num-cores-total
:num-cores
(m/num-cores dashboard))
(set-metrics :obelisk-exporter/board-temp-celsius
:board-temp
(m/board-temp dashboard))
(set-metrics :obelisk-exporter/board-chip-temp-celsius
:chip-temp
(m/chip-temp dashboard))
(set-metrics :obelisk-exporter/board-hot-chip-temp-celsius
:hot-chip-temp
(m/hot-chip-temp dashboard))
(set-metrics :obelisk-exporter/board-share-count-total
:value
(m/board-share-count dashboard))
(set-metrics :obelisk-exporter/board-num-chips-total
:num-chips
(m/num-chips dashboard))
(set-metrics :obelisk-exporter/fan-speed-rmp
:fan-speed
(m/fan-speeds dashboard))
;; rendering
e/text-format
res/response))
(do
(log/error "Failed to get the dashboard output")
(server-error
"Server Error: Failed to get a decent response from the obelisk ui."))))
(do
(log/error "Failed to login to obelisk panel")
(log/info "OBELISK_SERVER_ADDRESS: " (c/config :obelisk-ui :server-address))
(log/info "BASIC_AUTH_USER: " (c/config :obelisk-ui :basic-auth :user))
(log/info "BASIC_AUTH_PASSWORD: " (if (nil? (c/config :obelisk-ui :basic-auth :password))
"nil"
"not nil"))
(log/info "OBELISK_PANEL_USER: " (c/config :obelisk-ui :panel :user))
(log/info "OBELISK_PANEL_PASSWORD: " (if (nil? (c/config :obelisk-ui :panel :password))
"nil"
"not nil"))
(server-error
"Server Error: Misconfigured, please check configuration.")))))
(defn not-found
[r]
(log/info "User accessed " (:uri r))
(res/not-found "404 Not Found"))
(def routes
["" [["" index-handler]
["/" index-handler]
["/metrics" [["" metrics-handler]
["/" metrics-handler]]]
[true not-found]]])
(def handler
(make-handler routes))
;;;; --- Main --- ;;;;
(def cli-options
[["-h" "--help" "Shows this message"]
[nil "--config.file PATH" "Config YAML file"
:id :config-file]])
(def usage-text
"usage: obelisk-exporter [<flags>]
An exporter for the obelisk miner's panel
Flags:
")
(defn -main
[& args]
(let [{:keys [options summary]} (parse-opts args cli-options)]
(if (:help options)
(do
(println (str usage-text summary)))
(do
(if-let [file (:config-file options)]
(c/load! file)
(c/load!))
(let [server (run-jetty handler {:port (c/config :general :port)
:host (c/config :general :server-address)
:join? false})]
(fn []
(.stop server)))))))
(comment
(def opts {:server-address "http://some-obelisk-address"
:basic-auth ["username" "<PASSWORD>"]})
(def cookie (api/login "admin" "admin" opts))
(def opts (assoc opts :cookie cookie))
(def d (api/dashboard opts))
(keys d)
;; The :hashrateData `is` sorted
(->> (:hashrateData d)
(map :time)
(reduce (fn [a b]
(if (> b a)
b
(reduced false)))))
;; ::hash-rate-total
(->> (:hashrateData d)
(last)
(clojure.pprint/pprint))
(->> (:systemInfo d)
(reduce (fn [acc {:keys [name value]}]
(assoc acc name value))
{})
(clojure.pprint/pprint))
(->> (:poolStatus d)
(clojure.pprint/pprint))
(->> (:hashboardStatus d)
(clojure.pprint/pprint))
[])
| true | (ns obelisk-exporter.core
(:require [obelisk-ui.api :as api]
[bidi.ring :refer [make-handler]]
[ring.util.response :as res]
[ring.adapter.jetty :refer [run-jetty]]
[iapetos.core :as p]
[iapetos.export :as e]
[obelisk-exporter.metrics :as m]
[obelisk-exporter.config :as c]
[clojure.tools.logging :as log]
[clojure.tools.cli :refer [parse-opts]])
(:gen-class))
;;;; --- Prometheus Metrics Registry --- ;;;;
(defn make-registry
[]
(-> (p/collector-registry)
(p/register
;; :hashrateData metrics
(p/gauge :obelisk-exporter/hash-rate-gigahashes-per-second
{:description "The total amount of hashrate each board has."
:labels [:board]})
;; :hashrateData metrics
(p/gauge :obelisk-exporter/memory-free-megabytes
{:description "The amount of free memory"})
(p/gauge :obelisk-exporter/memory-total-megabytes
{:description "The total amount of memory"})
;; :poolStatus metrics
(p/gauge :obelisk-exporter/pool-last-share-time
{:description "The last time a share was received"
:labels [:pool]})
(p/gauge :obelisk-exporter/pool-share-count-total
{:description "The amount of shares"
:labels [:pool :status]})
;; :hashboardStatus
(p/gauge :obelisk-exporter/board-power-supply-temp-celsius
{:description "The temperature of the board power supply"
:labels [:board]})
(p/gauge :obelisk-exporter/board-num-cores-total
{:description "The number of cores a board has available"
:labels [:board]})
(p/gauge :obelisk-exporter/board-temp-celsius
{:description "The temperature of the board"
:labels [:board]})
(p/gauge :obelisk-exporter/board-chip-temp-celsius
{:description "The temperature of the board chip"
:labels [:board]})
(p/gauge :obelisk-exporter/board-hot-chip-temp-celsius
{:description "The temperature of the board hot chip"
:labels [:board]})
(p/gauge :obelisk-exporter/board-share-count-total
{:description "The amount of shares a board has received"
:labels [:board :status]})
(p/gauge :obelisk-exporter/board-num-chips-total
{:description "The number of chips a board has available"
:labels [:board]})
(p/gauge :obelisk-exporter/fan-speed-rmp
{:description "The speed of the fans"
:labels [:fan]}))))
;;;; --- Handlers --- ;;;;
(defn index-handler
[r]
(log/info "User accessed " (:uri r))
(res/response
"<body>Metrics are available <a href=\"/metrics\">here</a>.<br>More information about this exporter is available <a href=\"https://github.com/akeboshiwind/obelisk-exporter\">here</a>.</body>"))
(defn- server-error
[body]
{:status 500
:headers {}
:body body})
(defn- set-metrics
[registry metric value-key data]
(doseq [data-point data]
(let [value (value-key data-point)]
(p/set registry metric (dissoc data-point value-key) value)))
registry)
(comment
(def r
(-> (p/collector-registry)
(p/register
(p/gauge :obelisk/test-total
{:labels [:label]}))))
(set-metrics
r
:obelisk/test-total
:value
[{:value 1 :label 0}
{:value 5 :label 1}
{:value 1 :label 2}])
(->> (e/text-format r)
(print))
[])
(defn metrics-handler
[r]
(log/info "User accessed " (:uri r))
(let [opts (merge {:server-address (c/config :obelisk-ui :server-address)}
(when (c/config :obelisk-ui :basic-auth)
{:basic-auth [(c/config :obelisk-ui :basic-auth :user)
(c/config :obelisk-ui :basic-auth :password)]}))]
(if-let [cookie (api/login (c/config :obelisk-ui :panel :user)
(c/config :obelisk-ui :panel :password)
opts)]
(let [opts (assoc opts :cookie cookie)]
(log/info "Login successful")
(if-let [dashboard (api/dashboard opts)]
(do
(log/info "Dashboard scrape successful")
(-> (make-registry)
;; :hashrateData metrics
(set-metrics :obelisk-exporter/hash-rate-gigahashes-per-second
:hash-rate
(m/hash-rates dashboard))
;; :systemInfo metrics
(p/set :obelisk-exporter/memory-free-megabytes (m/free-memory dashboard))
(p/set :obelisk-exporter/memory-total-megabytes (m/total-memory dashboard))
;; :poolStatus metrics
(set-metrics :obelisk-exporter/pool-last-share-time
:last-share-time
(m/last-share-times dashboard))
(set-metrics :obelisk-exporter/pool-share-count-total
:value
(m/share-count dashboard))
;; :hashboardStatus metrics
(set-metrics :obelisk-exporter/board-power-supply-temp-celsius
:power-supply-temp
(m/power-supply-temp dashboard))
(set-metrics :obelisk-exporter/board-num-cores-total
:num-cores
(m/num-cores dashboard))
(set-metrics :obelisk-exporter/board-temp-celsius
:board-temp
(m/board-temp dashboard))
(set-metrics :obelisk-exporter/board-chip-temp-celsius
:chip-temp
(m/chip-temp dashboard))
(set-metrics :obelisk-exporter/board-hot-chip-temp-celsius
:hot-chip-temp
(m/hot-chip-temp dashboard))
(set-metrics :obelisk-exporter/board-share-count-total
:value
(m/board-share-count dashboard))
(set-metrics :obelisk-exporter/board-num-chips-total
:num-chips
(m/num-chips dashboard))
(set-metrics :obelisk-exporter/fan-speed-rmp
:fan-speed
(m/fan-speeds dashboard))
;; rendering
e/text-format
res/response))
(do
(log/error "Failed to get the dashboard output")
(server-error
"Server Error: Failed to get a decent response from the obelisk ui."))))
(do
(log/error "Failed to login to obelisk panel")
(log/info "OBELISK_SERVER_ADDRESS: " (c/config :obelisk-ui :server-address))
(log/info "BASIC_AUTH_USER: " (c/config :obelisk-ui :basic-auth :user))
(log/info "BASIC_AUTH_PASSWORD: " (if (nil? (c/config :obelisk-ui :basic-auth :password))
"nil"
"not nil"))
(log/info "OBELISK_PANEL_USER: " (c/config :obelisk-ui :panel :user))
(log/info "OBELISK_PANEL_PASSWORD: " (if (nil? (c/config :obelisk-ui :panel :password))
"nil"
"not nil"))
(server-error
"Server Error: Misconfigured, please check configuration.")))))
(defn not-found
[r]
(log/info "User accessed " (:uri r))
(res/not-found "404 Not Found"))
(def routes
["" [["" index-handler]
["/" index-handler]
["/metrics" [["" metrics-handler]
["/" metrics-handler]]]
[true not-found]]])
(def handler
(make-handler routes))
;;;; --- Main --- ;;;;
(def cli-options
[["-h" "--help" "Shows this message"]
[nil "--config.file PATH" "Config YAML file"
:id :config-file]])
(def usage-text
"usage: obelisk-exporter [<flags>]
An exporter for the obelisk miner's panel
Flags:
")
(defn -main
[& args]
(let [{:keys [options summary]} (parse-opts args cli-options)]
(if (:help options)
(do
(println (str usage-text summary)))
(do
(if-let [file (:config-file options)]
(c/load! file)
(c/load!))
(let [server (run-jetty handler {:port (c/config :general :port)
:host (c/config :general :server-address)
:join? false})]
(fn []
(.stop server)))))))
(comment
(def opts {:server-address "http://some-obelisk-address"
:basic-auth ["username" "PI:PASSWORD:<PASSWORD>END_PI"]})
(def cookie (api/login "admin" "admin" opts))
(def opts (assoc opts :cookie cookie))
(def d (api/dashboard opts))
(keys d)
;; The :hashrateData `is` sorted
(->> (:hashrateData d)
(map :time)
(reduce (fn [a b]
(if (> b a)
b
(reduced false)))))
;; ::hash-rate-total
(->> (:hashrateData d)
(last)
(clojure.pprint/pprint))
(->> (:systemInfo d)
(reduce (fn [acc {:keys [name value]}]
(assoc acc name value))
{})
(clojure.pprint/pprint))
(->> (:poolStatus d)
(clojure.pprint/pprint))
(->> (:hashboardStatus d)
(clojure.pprint/pprint))
[])
|
[
{
"context": "t\n :keystore nil-keystore\n :key-password \"hunter2\"\n :join? false})\n\n(deftest test-run-jett",
"end": 2069,
"score": 0.999150276184082,
"start": 2062,
"tag": "PASSWORD",
"value": "hunter2"
},
{
"context": "jks\"\n :key-password \"password\"}\n (let [response (http/get test-ssl-url {:i",
"end": 2675,
"score": 0.9992350339889526,
"start": 2667,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "jks\"\n :key-password \"password\"}\n (let [response (http/get test-ssl-url {:i",
"end": 3121,
"score": 0.999039888381958,
"start": 3113,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " :key-password \"password\"\n :join? ",
"end": 4995,
"score": 0.998594343662262,
"start": 4987,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " :key-password \"password\"\n :join? ",
"end": 5604,
"score": 0.9979104399681091,
"start": 5596,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "8\"))\n (is (= (:remote-addr request-map) \"127.0.0.1\"))\n (is (= (:scheme request-map) :http))",
"end": 7763,
"score": 0.9997298121452332,
"start": 7754,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | ring-jetty-adapter/test/ring/adapter/test/jetty.clj | jcf/ring | 0 | (ns ring.adapter.test.jetty
(:require [clojure.test :refer :all]
[ring.adapter.jetty :refer :all]
[clj-http.client :as http])
(:import [org.eclipse.jetty.util.thread QueuedThreadPool]
[org.eclipse.jetty.server Server Request SslConnectionFactory]
[org.eclipse.jetty.server.handler AbstractHandler]
[java.net ServerSocket ConnectException]
[java.security KeyStore]))
(defn- hello-world [request]
{:status 200
:headers {"Content-Type" "text/plain"}
:body "Hello World"})
(defn- content-type-handler [content-type]
(constantly
{:status 200
:headers {"Content-Type" content-type}
:body ""}))
(defn- echo-handler [request]
{:status 200
:headers {"request-map" (str (dissoc request :body))}
:body (:body request)})
(defn- all-threads []
(.keySet (Thread/getAllStackTraces)))
(defmacro with-server [app options & body]
`(let [server# (run-jetty ~app ~(assoc options :join? false))]
(try
~@body
(finally (.stop server#)))))
(defn- find-free-local-port []
(let [socket (ServerSocket. 0)]
(let [port (.getLocalPort socket)]
(.close socket)
port)))
(defn- get-ssl-context-factory
[^Server s]
(->> (seq (.getConnectors s))
(mapcat #(seq (.getConnectionFactories %)))
(filter #(instance? SslConnectionFactory %))
(first)
(.getSslContextFactory)))
(defn- exclude-ciphers [server]
(set (.getExcludeCipherSuites (get-ssl-context-factory server))))
(defn- exclude-protocols [server]
(set (.getExcludeProtocols (get-ssl-context-factory server))))
(def test-port (find-free-local-port))
(def test-ssl-port (find-free-local-port))
(def test-url (str "http://localhost:" test-port))
(def test-ssl-url (str "https://localhost:" test-ssl-port))
(def nil-keystore
(doto (KeyStore/getInstance (KeyStore/getDefaultType)) (.load nil)))
(def test-ssl-options
{:port test-port
:ssl? true
:ssl-port test-ssl-port
:keystore nil-keystore
:key-password "hunter2"
:join? false})
(deftest test-run-jetty
(testing "HTTP server"
(with-server hello-world {:port test-port}
(let [response (http/get test-url)]
(is (= (:status response) 200))
(is (.startsWith (get-in response [:headers "content-type"])
"text/plain"))
(is (= (:body response) "Hello World")))))
(testing "HTTPS server"
(with-server hello-world {:port test-port
:ssl-port test-ssl-port
:keystore "test/keystore.jks"
:key-password "password"}
(let [response (http/get test-ssl-url {:insecure? true})]
(is (= (:status response) 200))
(is (= (:body response) "Hello World")))))
(testing "HTTPS-only server"
(with-server hello-world {:http? false
:port test-port
:ssl-port test-ssl-port
:keystore "test/keystore.jks"
:key-password "password"}
(let [response (http/get test-ssl-url {:insecure? true})]
(is (= (:status response) 200))
(is (= (:body response) "Hello World")))
(is (thrown-with-msg? ConnectException #"Connection refused"
(http/get test-url)))))
(testing "configurator set to run last"
(let [max-threads 20
new-handler (proxy [AbstractHandler] []
(handle [_ ^Request base-request request response]))
configurator (fn [server]
(.setMaxThreads (.getThreadPool server) max-threads)
(.setHandler server new-handler))
server (run-jetty hello-world
{:join? false :port test-port :configurator configurator})]
(is (= (.getMaxThreads (.getThreadPool server)) max-threads))
(is (identical? new-handler (.getHandler server)))
(is (= 1 (count (.getHandlers server))))
(.stop server)))
(testing "setting daemon threads"
(testing "default (daemon off)"
(let [server (run-jetty hello-world {:port test-port :join? false})]
(is (not (.. server getThreadPool isDaemon)))
(.stop server)))
(testing "daemon on"
(let [server (run-jetty hello-world {:port test-port :join? false :daemon? true})]
(is (.. server getThreadPool isDaemon))
(.stop server)))
(testing "daemon off"
(let [server (run-jetty hello-world {:port test-port :join? false :daemon? false})]
(is (not (.. server getThreadPool isDaemon)))
(.stop server))))
(testing "setting max idle timeout"
(let [server (run-jetty hello-world {:port test-port
:ssl-port test-ssl-port
:keystore "test/keystore.jks"
:key-password "password"
:join? false
:max-idle-time 5000})
connectors (. server getConnectors)]
(is (= 5000 (. (first connectors) getIdleTimeout)))
(is (= 5000 (. (second connectors) getIdleTimeout)))
(.stop server)))
(testing "using the default max idle time"
(let [server (run-jetty hello-world {:port test-port
:ssl-port test-ssl-port
:keystore "test/keystore.jks"
:key-password "password"
:join? false})
connectors (. server getConnectors)]
(is (= 200000 (. (first connectors) getIdleTimeout)))
(is (= 200000 (. (second connectors) getIdleTimeout)))
(.stop server)))
(testing "setting min-threads"
(let [server (run-jetty hello-world {:port test-port
:min-threads 3
:join? false})
thread-pool (. server getThreadPool)]
(is (= 3 (. thread-pool getMinThreads)))
(.stop server)))
(testing "default min-threads"
(let [server (run-jetty hello-world {:port test-port
:join? false})
thread-pool (. server getThreadPool)]
(is (= 8 (. thread-pool getMinThreads)))
(.stop server)))
(testing "default character encoding"
(with-server (content-type-handler "text/plain") {:port test-port}
(let [response (http/get test-url)]
(is (.contains
(get-in response [:headers "content-type"])
"text/plain")))))
(testing "custom content-type"
(with-server (content-type-handler "text/plain;charset=UTF-16;version=1") {:port test-port}
(let [response (http/get test-url)]
(is (= (get-in response [:headers "content-type"])
"text/plain;charset=UTF-16;version=1")))))
(testing "request translation"
(with-server echo-handler {:port test-port}
(let [response (http/post (str test-url "/foo/bar/baz?surname=jones&age=123") {:body "hello"})]
(is (= (:status response) 200))
(is (= (:body response) "hello"))
(let [request-map (read-string (get-in response [:headers "request-map"]))]
(is (= (:query-string request-map) "surname=jones&age=123"))
(is (= (:uri request-map) "/foo/bar/baz"))
(is (= (:content-length request-map) 5))
(is (= (:character-encoding request-map) "UTF-8"))
(is (= (:request-method request-map) :post))
(is (= (:content-type request-map) "text/plain; charset=UTF-8"))
(is (= (:remote-addr request-map) "127.0.0.1"))
(is (= (:scheme request-map) :http))
(is (= (:server-name request-map) "localhost"))
(is (= (:server-port request-map) test-port))
(is (= (:ssl-client-cert request-map) nil))))))
(testing "sending 'Server' header in HTTP response'"
(testing ":send-server-version? set to default value (true)"
(with-server hello-world {:port test-port}
(let [response (http/get test-url)]
(is (contains? (:headers response) "Server")))))
(testing ":send-server-version? set to true"
(with-server hello-world {:port test-port
:send-server-version? true}
(let [response (http/get test-url)]
(is (contains? (:headers response) "Server")))))
(testing ":send-server-version? set to false"
(with-server hello-world {:port test-port
:send-server-version? false}
(let [response (http/get test-url)]
(is (not (contains? (:headers response) "Server")))))))
(testing "excluding cipher suites"
(let [cipher "SSL_RSA_WITH_NULL_MD5"
options (assoc test-ssl-options :exclude-ciphers [cipher])
server (run-jetty echo-handler options)]
(try
(is (contains? (exclude-ciphers server) cipher))
(finally
(.stop server)))))
(testing "excluding cipher protocols"
(let [protocol "SSLv2Hello"
options (assoc test-ssl-options :exclude-protocols [protocol])
server (run-jetty echo-handler options)]
(try
(is (contains? (exclude-protocols server) protocol))
(finally
(.stop server)))))
;; Unable to get test working with Jetty 9
(comment
(testing "resource cleanup on exception"
(with-server hello-world {:port test-port}
(let [thread-count (count (all-threads))]
(is (thrown? Exception (run-jetty hello-world {:port test-port})))
(loop [i 0]
(when (and (< i 400) (not= thread-count (count (all-threads))))
(Thread/sleep 250)
(recur (inc i))))
(is (= thread-count (count (all-threads)))))))))
| 115725 | (ns ring.adapter.test.jetty
(:require [clojure.test :refer :all]
[ring.adapter.jetty :refer :all]
[clj-http.client :as http])
(:import [org.eclipse.jetty.util.thread QueuedThreadPool]
[org.eclipse.jetty.server Server Request SslConnectionFactory]
[org.eclipse.jetty.server.handler AbstractHandler]
[java.net ServerSocket ConnectException]
[java.security KeyStore]))
(defn- hello-world [request]
{:status 200
:headers {"Content-Type" "text/plain"}
:body "Hello World"})
(defn- content-type-handler [content-type]
(constantly
{:status 200
:headers {"Content-Type" content-type}
:body ""}))
(defn- echo-handler [request]
{:status 200
:headers {"request-map" (str (dissoc request :body))}
:body (:body request)})
(defn- all-threads []
(.keySet (Thread/getAllStackTraces)))
(defmacro with-server [app options & body]
`(let [server# (run-jetty ~app ~(assoc options :join? false))]
(try
~@body
(finally (.stop server#)))))
(defn- find-free-local-port []
(let [socket (ServerSocket. 0)]
(let [port (.getLocalPort socket)]
(.close socket)
port)))
(defn- get-ssl-context-factory
[^Server s]
(->> (seq (.getConnectors s))
(mapcat #(seq (.getConnectionFactories %)))
(filter #(instance? SslConnectionFactory %))
(first)
(.getSslContextFactory)))
(defn- exclude-ciphers [server]
(set (.getExcludeCipherSuites (get-ssl-context-factory server))))
(defn- exclude-protocols [server]
(set (.getExcludeProtocols (get-ssl-context-factory server))))
(def test-port (find-free-local-port))
(def test-ssl-port (find-free-local-port))
(def test-url (str "http://localhost:" test-port))
(def test-ssl-url (str "https://localhost:" test-ssl-port))
(def nil-keystore
(doto (KeyStore/getInstance (KeyStore/getDefaultType)) (.load nil)))
(def test-ssl-options
{:port test-port
:ssl? true
:ssl-port test-ssl-port
:keystore nil-keystore
:key-password "<PASSWORD>"
:join? false})
(deftest test-run-jetty
(testing "HTTP server"
(with-server hello-world {:port test-port}
(let [response (http/get test-url)]
(is (= (:status response) 200))
(is (.startsWith (get-in response [:headers "content-type"])
"text/plain"))
(is (= (:body response) "Hello World")))))
(testing "HTTPS server"
(with-server hello-world {:port test-port
:ssl-port test-ssl-port
:keystore "test/keystore.jks"
:key-password "<PASSWORD>"}
(let [response (http/get test-ssl-url {:insecure? true})]
(is (= (:status response) 200))
(is (= (:body response) "Hello World")))))
(testing "HTTPS-only server"
(with-server hello-world {:http? false
:port test-port
:ssl-port test-ssl-port
:keystore "test/keystore.jks"
:key-password "<PASSWORD>"}
(let [response (http/get test-ssl-url {:insecure? true})]
(is (= (:status response) 200))
(is (= (:body response) "Hello World")))
(is (thrown-with-msg? ConnectException #"Connection refused"
(http/get test-url)))))
(testing "configurator set to run last"
(let [max-threads 20
new-handler (proxy [AbstractHandler] []
(handle [_ ^Request base-request request response]))
configurator (fn [server]
(.setMaxThreads (.getThreadPool server) max-threads)
(.setHandler server new-handler))
server (run-jetty hello-world
{:join? false :port test-port :configurator configurator})]
(is (= (.getMaxThreads (.getThreadPool server)) max-threads))
(is (identical? new-handler (.getHandler server)))
(is (= 1 (count (.getHandlers server))))
(.stop server)))
(testing "setting daemon threads"
(testing "default (daemon off)"
(let [server (run-jetty hello-world {:port test-port :join? false})]
(is (not (.. server getThreadPool isDaemon)))
(.stop server)))
(testing "daemon on"
(let [server (run-jetty hello-world {:port test-port :join? false :daemon? true})]
(is (.. server getThreadPool isDaemon))
(.stop server)))
(testing "daemon off"
(let [server (run-jetty hello-world {:port test-port :join? false :daemon? false})]
(is (not (.. server getThreadPool isDaemon)))
(.stop server))))
(testing "setting max idle timeout"
(let [server (run-jetty hello-world {:port test-port
:ssl-port test-ssl-port
:keystore "test/keystore.jks"
:key-password "<PASSWORD>"
:join? false
:max-idle-time 5000})
connectors (. server getConnectors)]
(is (= 5000 (. (first connectors) getIdleTimeout)))
(is (= 5000 (. (second connectors) getIdleTimeout)))
(.stop server)))
(testing "using the default max idle time"
(let [server (run-jetty hello-world {:port test-port
:ssl-port test-ssl-port
:keystore "test/keystore.jks"
:key-password "<PASSWORD>"
:join? false})
connectors (. server getConnectors)]
(is (= 200000 (. (first connectors) getIdleTimeout)))
(is (= 200000 (. (second connectors) getIdleTimeout)))
(.stop server)))
(testing "setting min-threads"
(let [server (run-jetty hello-world {:port test-port
:min-threads 3
:join? false})
thread-pool (. server getThreadPool)]
(is (= 3 (. thread-pool getMinThreads)))
(.stop server)))
(testing "default min-threads"
(let [server (run-jetty hello-world {:port test-port
:join? false})
thread-pool (. server getThreadPool)]
(is (= 8 (. thread-pool getMinThreads)))
(.stop server)))
(testing "default character encoding"
(with-server (content-type-handler "text/plain") {:port test-port}
(let [response (http/get test-url)]
(is (.contains
(get-in response [:headers "content-type"])
"text/plain")))))
(testing "custom content-type"
(with-server (content-type-handler "text/plain;charset=UTF-16;version=1") {:port test-port}
(let [response (http/get test-url)]
(is (= (get-in response [:headers "content-type"])
"text/plain;charset=UTF-16;version=1")))))
(testing "request translation"
(with-server echo-handler {:port test-port}
(let [response (http/post (str test-url "/foo/bar/baz?surname=jones&age=123") {:body "hello"})]
(is (= (:status response) 200))
(is (= (:body response) "hello"))
(let [request-map (read-string (get-in response [:headers "request-map"]))]
(is (= (:query-string request-map) "surname=jones&age=123"))
(is (= (:uri request-map) "/foo/bar/baz"))
(is (= (:content-length request-map) 5))
(is (= (:character-encoding request-map) "UTF-8"))
(is (= (:request-method request-map) :post))
(is (= (:content-type request-map) "text/plain; charset=UTF-8"))
(is (= (:remote-addr request-map) "127.0.0.1"))
(is (= (:scheme request-map) :http))
(is (= (:server-name request-map) "localhost"))
(is (= (:server-port request-map) test-port))
(is (= (:ssl-client-cert request-map) nil))))))
(testing "sending 'Server' header in HTTP response'"
(testing ":send-server-version? set to default value (true)"
(with-server hello-world {:port test-port}
(let [response (http/get test-url)]
(is (contains? (:headers response) "Server")))))
(testing ":send-server-version? set to true"
(with-server hello-world {:port test-port
:send-server-version? true}
(let [response (http/get test-url)]
(is (contains? (:headers response) "Server")))))
(testing ":send-server-version? set to false"
(with-server hello-world {:port test-port
:send-server-version? false}
(let [response (http/get test-url)]
(is (not (contains? (:headers response) "Server")))))))
(testing "excluding cipher suites"
(let [cipher "SSL_RSA_WITH_NULL_MD5"
options (assoc test-ssl-options :exclude-ciphers [cipher])
server (run-jetty echo-handler options)]
(try
(is (contains? (exclude-ciphers server) cipher))
(finally
(.stop server)))))
(testing "excluding cipher protocols"
(let [protocol "SSLv2Hello"
options (assoc test-ssl-options :exclude-protocols [protocol])
server (run-jetty echo-handler options)]
(try
(is (contains? (exclude-protocols server) protocol))
(finally
(.stop server)))))
;; Unable to get test working with Jetty 9
(comment
(testing "resource cleanup on exception"
(with-server hello-world {:port test-port}
(let [thread-count (count (all-threads))]
(is (thrown? Exception (run-jetty hello-world {:port test-port})))
(loop [i 0]
(when (and (< i 400) (not= thread-count (count (all-threads))))
(Thread/sleep 250)
(recur (inc i))))
(is (= thread-count (count (all-threads)))))))))
| true | (ns ring.adapter.test.jetty
(:require [clojure.test :refer :all]
[ring.adapter.jetty :refer :all]
[clj-http.client :as http])
(:import [org.eclipse.jetty.util.thread QueuedThreadPool]
[org.eclipse.jetty.server Server Request SslConnectionFactory]
[org.eclipse.jetty.server.handler AbstractHandler]
[java.net ServerSocket ConnectException]
[java.security KeyStore]))
(defn- hello-world [request]
{:status 200
:headers {"Content-Type" "text/plain"}
:body "Hello World"})
(defn- content-type-handler [content-type]
(constantly
{:status 200
:headers {"Content-Type" content-type}
:body ""}))
(defn- echo-handler [request]
{:status 200
:headers {"request-map" (str (dissoc request :body))}
:body (:body request)})
(defn- all-threads []
(.keySet (Thread/getAllStackTraces)))
(defmacro with-server [app options & body]
`(let [server# (run-jetty ~app ~(assoc options :join? false))]
(try
~@body
(finally (.stop server#)))))
(defn- find-free-local-port []
(let [socket (ServerSocket. 0)]
(let [port (.getLocalPort socket)]
(.close socket)
port)))
(defn- get-ssl-context-factory
[^Server s]
(->> (seq (.getConnectors s))
(mapcat #(seq (.getConnectionFactories %)))
(filter #(instance? SslConnectionFactory %))
(first)
(.getSslContextFactory)))
(defn- exclude-ciphers [server]
(set (.getExcludeCipherSuites (get-ssl-context-factory server))))
(defn- exclude-protocols [server]
(set (.getExcludeProtocols (get-ssl-context-factory server))))
(def test-port (find-free-local-port))
(def test-ssl-port (find-free-local-port))
(def test-url (str "http://localhost:" test-port))
(def test-ssl-url (str "https://localhost:" test-ssl-port))
(def nil-keystore
(doto (KeyStore/getInstance (KeyStore/getDefaultType)) (.load nil)))
(def test-ssl-options
{:port test-port
:ssl? true
:ssl-port test-ssl-port
:keystore nil-keystore
:key-password "PI:PASSWORD:<PASSWORD>END_PI"
:join? false})
(deftest test-run-jetty
(testing "HTTP server"
(with-server hello-world {:port test-port}
(let [response (http/get test-url)]
(is (= (:status response) 200))
(is (.startsWith (get-in response [:headers "content-type"])
"text/plain"))
(is (= (:body response) "Hello World")))))
(testing "HTTPS server"
(with-server hello-world {:port test-port
:ssl-port test-ssl-port
:keystore "test/keystore.jks"
:key-password "PI:PASSWORD:<PASSWORD>END_PI"}
(let [response (http/get test-ssl-url {:insecure? true})]
(is (= (:status response) 200))
(is (= (:body response) "Hello World")))))
(testing "HTTPS-only server"
(with-server hello-world {:http? false
:port test-port
:ssl-port test-ssl-port
:keystore "test/keystore.jks"
:key-password "PI:PASSWORD:<PASSWORD>END_PI"}
(let [response (http/get test-ssl-url {:insecure? true})]
(is (= (:status response) 200))
(is (= (:body response) "Hello World")))
(is (thrown-with-msg? ConnectException #"Connection refused"
(http/get test-url)))))
(testing "configurator set to run last"
(let [max-threads 20
new-handler (proxy [AbstractHandler] []
(handle [_ ^Request base-request request response]))
configurator (fn [server]
(.setMaxThreads (.getThreadPool server) max-threads)
(.setHandler server new-handler))
server (run-jetty hello-world
{:join? false :port test-port :configurator configurator})]
(is (= (.getMaxThreads (.getThreadPool server)) max-threads))
(is (identical? new-handler (.getHandler server)))
(is (= 1 (count (.getHandlers server))))
(.stop server)))
(testing "setting daemon threads"
(testing "default (daemon off)"
(let [server (run-jetty hello-world {:port test-port :join? false})]
(is (not (.. server getThreadPool isDaemon)))
(.stop server)))
(testing "daemon on"
(let [server (run-jetty hello-world {:port test-port :join? false :daemon? true})]
(is (.. server getThreadPool isDaemon))
(.stop server)))
(testing "daemon off"
(let [server (run-jetty hello-world {:port test-port :join? false :daemon? false})]
(is (not (.. server getThreadPool isDaemon)))
(.stop server))))
(testing "setting max idle timeout"
(let [server (run-jetty hello-world {:port test-port
:ssl-port test-ssl-port
:keystore "test/keystore.jks"
:key-password "PI:PASSWORD:<PASSWORD>END_PI"
:join? false
:max-idle-time 5000})
connectors (. server getConnectors)]
(is (= 5000 (. (first connectors) getIdleTimeout)))
(is (= 5000 (. (second connectors) getIdleTimeout)))
(.stop server)))
(testing "using the default max idle time"
(let [server (run-jetty hello-world {:port test-port
:ssl-port test-ssl-port
:keystore "test/keystore.jks"
:key-password "PI:PASSWORD:<PASSWORD>END_PI"
:join? false})
connectors (. server getConnectors)]
(is (= 200000 (. (first connectors) getIdleTimeout)))
(is (= 200000 (. (second connectors) getIdleTimeout)))
(.stop server)))
(testing "setting min-threads"
(let [server (run-jetty hello-world {:port test-port
:min-threads 3
:join? false})
thread-pool (. server getThreadPool)]
(is (= 3 (. thread-pool getMinThreads)))
(.stop server)))
(testing "default min-threads"
(let [server (run-jetty hello-world {:port test-port
:join? false})
thread-pool (. server getThreadPool)]
(is (= 8 (. thread-pool getMinThreads)))
(.stop server)))
(testing "default character encoding"
(with-server (content-type-handler "text/plain") {:port test-port}
(let [response (http/get test-url)]
(is (.contains
(get-in response [:headers "content-type"])
"text/plain")))))
(testing "custom content-type"
(with-server (content-type-handler "text/plain;charset=UTF-16;version=1") {:port test-port}
(let [response (http/get test-url)]
(is (= (get-in response [:headers "content-type"])
"text/plain;charset=UTF-16;version=1")))))
(testing "request translation"
(with-server echo-handler {:port test-port}
(let [response (http/post (str test-url "/foo/bar/baz?surname=jones&age=123") {:body "hello"})]
(is (= (:status response) 200))
(is (= (:body response) "hello"))
(let [request-map (read-string (get-in response [:headers "request-map"]))]
(is (= (:query-string request-map) "surname=jones&age=123"))
(is (= (:uri request-map) "/foo/bar/baz"))
(is (= (:content-length request-map) 5))
(is (= (:character-encoding request-map) "UTF-8"))
(is (= (:request-method request-map) :post))
(is (= (:content-type request-map) "text/plain; charset=UTF-8"))
(is (= (:remote-addr request-map) "127.0.0.1"))
(is (= (:scheme request-map) :http))
(is (= (:server-name request-map) "localhost"))
(is (= (:server-port request-map) test-port))
(is (= (:ssl-client-cert request-map) nil))))))
(testing "sending 'Server' header in HTTP response'"
(testing ":send-server-version? set to default value (true)"
(with-server hello-world {:port test-port}
(let [response (http/get test-url)]
(is (contains? (:headers response) "Server")))))
(testing ":send-server-version? set to true"
(with-server hello-world {:port test-port
:send-server-version? true}
(let [response (http/get test-url)]
(is (contains? (:headers response) "Server")))))
(testing ":send-server-version? set to false"
(with-server hello-world {:port test-port
:send-server-version? false}
(let [response (http/get test-url)]
(is (not (contains? (:headers response) "Server")))))))
(testing "excluding cipher suites"
(let [cipher "SSL_RSA_WITH_NULL_MD5"
options (assoc test-ssl-options :exclude-ciphers [cipher])
server (run-jetty echo-handler options)]
(try
(is (contains? (exclude-ciphers server) cipher))
(finally
(.stop server)))))
(testing "excluding cipher protocols"
(let [protocol "SSLv2Hello"
options (assoc test-ssl-options :exclude-protocols [protocol])
server (run-jetty echo-handler options)]
(try
(is (contains? (exclude-protocols server) protocol))
(finally
(.stop server)))))
;; Unable to get test working with Jetty 9
(comment
(testing "resource cleanup on exception"
(with-server hello-world {:port test-port}
(let [thread-count (count (all-threads))]
(is (thrown? Exception (run-jetty hello-world {:port test-port})))
(loop [i 0]
(when (and (< i 400) (not= thread-count (count (all-threads))))
(Thread/sleep 250)
(recur (inc i))))
(is (= thread-count (count (all-threads)))))))))
|
[
{
"context": "with core.async, showing off transducers.\n;;; \n;;; Eli Bendersky [http://eli.thegreenplace.net]\n;;; This code is i",
"end": 77,
"score": 0.9921272397041321,
"start": 64,
"tag": "NAME",
"value": "Eli Bendersky"
}
] | 2017/reducers-transducers-async/clojure/reducers/src/reducers/async_transducer.clj | mikiec84/code-for-blog | 1,199 | ;;; Pipeline with core.async, showing off transducers.
;;;
;;; Eli Bendersky [http://eli.thegreenplace.net]
;;; This code is in the public domain.
(ns reducers.async-transducer
(:require [clojure.core.async :as async]))
;;; Version 1 is similar to the squaring pipeline example in Go, described in:
;;; https://blog.golang.org/pipelines
(defn gen-1
[& nums]
(let [c (async/chan)]
(async/go
(doseq [n nums]
(async/>! c n))
(async/close! c))
c))
(defn sq-1
[cin]
(let [cout (async/chan)]
(async/go-loop [n (async/<! cin)]
(if n
(do
(async/>! cout (* n n))
(recur (async/<! cin)))
(async/close! cout)))
cout))
(defn main-1
[]
(let [c-gen (gen-1 2 3 4 5)
c-sq (sq-1 c-gen)]
(loop [n (async/<!! c-sq)]
(when n
(println n)
(recur (async/<!! c-sq))))))
;;; Version 2 uses Clojure core.async built-ins to-chan and map< to make the
;;; pipeline more succinct. Note that with the advent of transducers, map< is
;;; now deprecated.
(defn gen-2
[& nums]
(async/to-chan nums))
(defn sq-2
[cin]
(async/map< #(* % %) cin))
(defn main-2
[]
(let [c-gen (gen-2 2 3 4 5)
c-sq (sq-2 c-gen)]
(loop [n (async/<!! c-sq)]
(when n
(println n)
(recur (async/<!! c-sq))))))
;;; Version 3 uses transducers. We no longer need a separate sq channel, as we
;;; can attach a squaring transducer onto the generating channel.
(defn main-3
[]
(let [c-sq (async/chan 1 (map #(* % %)))]
(async/onto-chan c-sq [2 3 4 5])
(loop [n (async/<!! c-sq)]
(when n
(println n)
(recur (async/<!! c-sq))))))
(main-3)
| 89310 | ;;; Pipeline with core.async, showing off transducers.
;;;
;;; <NAME> [http://eli.thegreenplace.net]
;;; This code is in the public domain.
(ns reducers.async-transducer
(:require [clojure.core.async :as async]))
;;; Version 1 is similar to the squaring pipeline example in Go, described in:
;;; https://blog.golang.org/pipelines
(defn gen-1
[& nums]
(let [c (async/chan)]
(async/go
(doseq [n nums]
(async/>! c n))
(async/close! c))
c))
(defn sq-1
[cin]
(let [cout (async/chan)]
(async/go-loop [n (async/<! cin)]
(if n
(do
(async/>! cout (* n n))
(recur (async/<! cin)))
(async/close! cout)))
cout))
(defn main-1
[]
(let [c-gen (gen-1 2 3 4 5)
c-sq (sq-1 c-gen)]
(loop [n (async/<!! c-sq)]
(when n
(println n)
(recur (async/<!! c-sq))))))
;;; Version 2 uses Clojure core.async built-ins to-chan and map< to make the
;;; pipeline more succinct. Note that with the advent of transducers, map< is
;;; now deprecated.
(defn gen-2
[& nums]
(async/to-chan nums))
(defn sq-2
[cin]
(async/map< #(* % %) cin))
(defn main-2
[]
(let [c-gen (gen-2 2 3 4 5)
c-sq (sq-2 c-gen)]
(loop [n (async/<!! c-sq)]
(when n
(println n)
(recur (async/<!! c-sq))))))
;;; Version 3 uses transducers. We no longer need a separate sq channel, as we
;;; can attach a squaring transducer onto the generating channel.
(defn main-3
[]
(let [c-sq (async/chan 1 (map #(* % %)))]
(async/onto-chan c-sq [2 3 4 5])
(loop [n (async/<!! c-sq)]
(when n
(println n)
(recur (async/<!! c-sq))))))
(main-3)
| true | ;;; Pipeline with core.async, showing off transducers.
;;;
;;; PI:NAME:<NAME>END_PI [http://eli.thegreenplace.net]
;;; This code is in the public domain.
(ns reducers.async-transducer
(:require [clojure.core.async :as async]))
;;; Version 1 is similar to the squaring pipeline example in Go, described in:
;;; https://blog.golang.org/pipelines
(defn gen-1
[& nums]
(let [c (async/chan)]
(async/go
(doseq [n nums]
(async/>! c n))
(async/close! c))
c))
(defn sq-1
[cin]
(let [cout (async/chan)]
(async/go-loop [n (async/<! cin)]
(if n
(do
(async/>! cout (* n n))
(recur (async/<! cin)))
(async/close! cout)))
cout))
(defn main-1
[]
(let [c-gen (gen-1 2 3 4 5)
c-sq (sq-1 c-gen)]
(loop [n (async/<!! c-sq)]
(when n
(println n)
(recur (async/<!! c-sq))))))
;;; Version 2 uses Clojure core.async built-ins to-chan and map< to make the
;;; pipeline more succinct. Note that with the advent of transducers, map< is
;;; now deprecated.
(defn gen-2
[& nums]
(async/to-chan nums))
(defn sq-2
[cin]
(async/map< #(* % %) cin))
(defn main-2
[]
(let [c-gen (gen-2 2 3 4 5)
c-sq (sq-2 c-gen)]
(loop [n (async/<!! c-sq)]
(when n
(println n)
(recur (async/<!! c-sq))))))
;;; Version 3 uses transducers. We no longer need a separate sq channel, as we
;;; can attach a squaring transducer onto the generating channel.
(defn main-3
[]
(let [c-sq (async/chan 1 (map #(* % %)))]
(async/onto-chan c-sq [2 3 4 5])
(loop [n (async/<!! c-sq)]
(when n
(println n)
(recur (async/<!! c-sq))))))
(main-3)
|
[
{
"context": " max-queue-length 10\n password [:cached \"test-password\"]\n auth-principal \"user@test.com\"\n ",
"end": 1453,
"score": 0.9988710880279541,
"start": 1440,
"tag": "PASSWORD",
"value": "test-password"
},
{
"context": "[:cached \"test-password\"]\n auth-principal \"user@test.com\"\n standard-request {}\n standard-401",
"end": 1493,
"score": 0.9999079704284668,
"start": 1480,
"tag": "EMAIL",
"value": "user@test.com"
},
{
"context": " :authorization/principal \"user@test.com\"\n :authorization/user \"",
"end": 6292,
"score": 0.9998909831047058,
"start": 6279,
"tag": "EMAIL",
"value": "user@test.com"
},
{
"context": " :authorization/principal \"user@test.com\"\n :authorization/user \"",
"end": 7534,
"score": 0.9999046325683594,
"start": 7521,
"tag": "EMAIL",
"value": "user@test.com"
},
{
"context": "\"\n :authorization/user \"user\"\n :headers {\"www-authen",
"end": 7588,
"score": 0.903033971786499,
"start": 7584,
"tag": "USERNAME",
"value": "user"
},
{
"context": " :authorization/principal \"user@test.com\"\n :authorization/user \"",
"end": 8468,
"score": 0.999904453754425,
"start": 8455,
"tag": "EMAIL",
"value": "user@test.com"
},
{
"context": "\"\n :authorization/user \"user\")\n (utils/dissoc-in respo",
"end": 8522,
"score": 0.9529219269752502,
"start": 8518,
"tag": "USERNAME",
"value": "user"
}
] | waiter/test/waiter/auth/spnego_test.clj | mokshjawa/waiter | 0 | ;;
;; Copyright (c) Two Sigma Open Source, LLC
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(ns waiter.auth.spnego-test
(:require [clojure.core.async :as async]
[clojure.test :refer :all]
[waiter.auth.spnego :refer :all]
[waiter.util.utils :as utils]))
(deftest test-decode-input-token
(is (decode-input-token {:headers {"authorization" "Negotiate Kerberos-Auth"}}))
(is (nil? (decode-input-token {:headers {"authorization" "Basic User-Pass"}}))))
(deftest test-encode-output-token
(let [encoded-token (encode-output-token (.getBytes "Kerberos-Auth"))]
(is (= "Kerberos-Auth"
(String. (decode-input-token {:headers {"authorization" encoded-token}}))))))
(deftest test-require-gss
(let [ideal-response {:body "OK" :status 200}
request-handler (constantly ideal-response)
thread-pool (Object.)
max-queue-length 10
password [:cached "test-password"]
auth-principal "user@test.com"
standard-request {}
standard-401-response {:body "Unauthorized"
:headers {"content-type" "text/plain"
"www-authenticate" "Negotiate"}
:status 401
:waiter/response-source :waiter}]
(with-redefs [utils/error-context->text-body #(-> % :message str)]
(testing "too many pending kerberos requests"
(with-redefs [too-many-pending-auth-requests? (constantly true)]
(let [handler (require-gss request-handler thread-pool max-queue-length password)]
(is (= {:body "Too many Kerberos authentication requests"
:headers {"content-type" "text/plain"}
:status 503
:waiter/response-source :waiter}
(handler standard-request))))))
(testing "standard 401 response on missing authorization header"
(with-redefs [too-many-pending-auth-requests? (constantly false)]
(let [handler (require-gss request-handler thread-pool max-queue-length password)]
(is (= standard-401-response (handler standard-request))))))
(testing "kerberos authentication path"
(with-redefs [too-many-pending-auth-requests? (constantly false)]
(let [auth-request (update standard-request :headers assoc "authorization" "Negotiate foo-bar")
error-object (Object.)]
(testing "401 response on failed authentication"
(with-redefs [populate-gss-credentials (fn [_ _ response-chan]
(async/>!! response-chan {:foo :bar}))]
(let [handler (require-gss request-handler thread-pool max-queue-length password)
response (handler auth-request)
response (if (map? response)
response
(async/<!! response))]
(is (= standard-401-response response)))))
(testing "401 response on missing authorization header"
(with-redefs [populate-gss-credentials (fn [_ _ response-chan]
(async/>!! response-chan {:foo :bar}))]
(let [handler (require-gss request-handler thread-pool max-queue-length password)
response (handler standard-request)
response (if (map? response)
response
(async/<!! response))]
(is (= standard-401-response response)))))
(testing "401 response on invalid authorization header"
(with-redefs [populate-gss-credentials (fn [_ _ response-chan]
(async/>!! response-chan {:foo :bar}))]
(let [handler (require-gss request-handler thread-pool max-queue-length password)
auth-request (update standard-request :headers assoc "authorization" "Bearer foo-bar")
response (handler auth-request)
response (if (map? response)
response
(async/<!! response))]
(is (= standard-401-response response)))))
(testing "error object on exception"
(with-redefs [populate-gss-credentials (fn [_ _ response-chan]
(async/>!! response-chan {:error error-object}))]
(let [handler (require-gss request-handler thread-pool max-queue-length password)
response (handler auth-request)
response (if (map? response)
response
(async/<!! response))]
(is (= error-object response)))))
(testing "successful authentication - principal and token"
(with-redefs [populate-gss-credentials (fn [_ _ response-chan]
(async/>!! response-chan {:principal auth-principal
:token "test-token"}))]
(let [handler (require-gss request-handler thread-pool max-queue-length password)
response (handler auth-request)
response (if (map? response)
response
(async/<!! response))]
(is (= (assoc ideal-response
:authorization/method :spnego
:authorization/principal "user@test.com"
:authorization/user "user"
:headers {"www-authenticate" "test-token"})
(utils/dissoc-in response [:headers "set-cookie"]))))))
(testing "successful authentication - principal and token - multiple authorization header"
(with-redefs [populate-gss-credentials (fn [_ _ response-chan]
(async/>!! response-chan {:principal auth-principal
:token "test-token"}))]
(let [handler (require-gss request-handler thread-pool max-queue-length password)
auth-request (update standard-request :headers
assoc "authorization" "Bearer fee-fie,Negotiate foo-bar")
response (handler auth-request)
response (if (map? response)
response
(async/<!! response))]
(is (= (assoc ideal-response
:authorization/method :spnego
:authorization/principal "user@test.com"
:authorization/user "user"
:headers {"www-authenticate" "test-token"})
(utils/dissoc-in response [:headers "set-cookie"]))))))
(testing "successful authentication - principal only"
(with-redefs [populate-gss-credentials (fn [_ _ response-chan]
(async/>!! response-chan {:principal auth-principal}))]
(let [handler (require-gss request-handler thread-pool max-queue-length password)
response (handler auth-request)
response (if (map? response)
response
(async/<!! response))]
(is (= (assoc ideal-response
:authorization/method :spnego
:authorization/principal "user@test.com"
:authorization/user "user")
(utils/dissoc-in response [:headers "set-cookie"]))))))))))))
| 111324 | ;;
;; Copyright (c) Two Sigma Open Source, LLC
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(ns waiter.auth.spnego-test
(:require [clojure.core.async :as async]
[clojure.test :refer :all]
[waiter.auth.spnego :refer :all]
[waiter.util.utils :as utils]))
(deftest test-decode-input-token
(is (decode-input-token {:headers {"authorization" "Negotiate Kerberos-Auth"}}))
(is (nil? (decode-input-token {:headers {"authorization" "Basic User-Pass"}}))))
(deftest test-encode-output-token
(let [encoded-token (encode-output-token (.getBytes "Kerberos-Auth"))]
(is (= "Kerberos-Auth"
(String. (decode-input-token {:headers {"authorization" encoded-token}}))))))
(deftest test-require-gss
(let [ideal-response {:body "OK" :status 200}
request-handler (constantly ideal-response)
thread-pool (Object.)
max-queue-length 10
password [:cached "<PASSWORD>"]
auth-principal "<EMAIL>"
standard-request {}
standard-401-response {:body "Unauthorized"
:headers {"content-type" "text/plain"
"www-authenticate" "Negotiate"}
:status 401
:waiter/response-source :waiter}]
(with-redefs [utils/error-context->text-body #(-> % :message str)]
(testing "too many pending kerberos requests"
(with-redefs [too-many-pending-auth-requests? (constantly true)]
(let [handler (require-gss request-handler thread-pool max-queue-length password)]
(is (= {:body "Too many Kerberos authentication requests"
:headers {"content-type" "text/plain"}
:status 503
:waiter/response-source :waiter}
(handler standard-request))))))
(testing "standard 401 response on missing authorization header"
(with-redefs [too-many-pending-auth-requests? (constantly false)]
(let [handler (require-gss request-handler thread-pool max-queue-length password)]
(is (= standard-401-response (handler standard-request))))))
(testing "kerberos authentication path"
(with-redefs [too-many-pending-auth-requests? (constantly false)]
(let [auth-request (update standard-request :headers assoc "authorization" "Negotiate foo-bar")
error-object (Object.)]
(testing "401 response on failed authentication"
(with-redefs [populate-gss-credentials (fn [_ _ response-chan]
(async/>!! response-chan {:foo :bar}))]
(let [handler (require-gss request-handler thread-pool max-queue-length password)
response (handler auth-request)
response (if (map? response)
response
(async/<!! response))]
(is (= standard-401-response response)))))
(testing "401 response on missing authorization header"
(with-redefs [populate-gss-credentials (fn [_ _ response-chan]
(async/>!! response-chan {:foo :bar}))]
(let [handler (require-gss request-handler thread-pool max-queue-length password)
response (handler standard-request)
response (if (map? response)
response
(async/<!! response))]
(is (= standard-401-response response)))))
(testing "401 response on invalid authorization header"
(with-redefs [populate-gss-credentials (fn [_ _ response-chan]
(async/>!! response-chan {:foo :bar}))]
(let [handler (require-gss request-handler thread-pool max-queue-length password)
auth-request (update standard-request :headers assoc "authorization" "Bearer foo-bar")
response (handler auth-request)
response (if (map? response)
response
(async/<!! response))]
(is (= standard-401-response response)))))
(testing "error object on exception"
(with-redefs [populate-gss-credentials (fn [_ _ response-chan]
(async/>!! response-chan {:error error-object}))]
(let [handler (require-gss request-handler thread-pool max-queue-length password)
response (handler auth-request)
response (if (map? response)
response
(async/<!! response))]
(is (= error-object response)))))
(testing "successful authentication - principal and token"
(with-redefs [populate-gss-credentials (fn [_ _ response-chan]
(async/>!! response-chan {:principal auth-principal
:token "test-token"}))]
(let [handler (require-gss request-handler thread-pool max-queue-length password)
response (handler auth-request)
response (if (map? response)
response
(async/<!! response))]
(is (= (assoc ideal-response
:authorization/method :spnego
:authorization/principal "<EMAIL>"
:authorization/user "user"
:headers {"www-authenticate" "test-token"})
(utils/dissoc-in response [:headers "set-cookie"]))))))
(testing "successful authentication - principal and token - multiple authorization header"
(with-redefs [populate-gss-credentials (fn [_ _ response-chan]
(async/>!! response-chan {:principal auth-principal
:token "test-token"}))]
(let [handler (require-gss request-handler thread-pool max-queue-length password)
auth-request (update standard-request :headers
assoc "authorization" "Bearer fee-fie,Negotiate foo-bar")
response (handler auth-request)
response (if (map? response)
response
(async/<!! response))]
(is (= (assoc ideal-response
:authorization/method :spnego
:authorization/principal "<EMAIL>"
:authorization/user "user"
:headers {"www-authenticate" "test-token"})
(utils/dissoc-in response [:headers "set-cookie"]))))))
(testing "successful authentication - principal only"
(with-redefs [populate-gss-credentials (fn [_ _ response-chan]
(async/>!! response-chan {:principal auth-principal}))]
(let [handler (require-gss request-handler thread-pool max-queue-length password)
response (handler auth-request)
response (if (map? response)
response
(async/<!! response))]
(is (= (assoc ideal-response
:authorization/method :spnego
:authorization/principal "<EMAIL>"
:authorization/user "user")
(utils/dissoc-in response [:headers "set-cookie"]))))))))))))
| true | ;;
;; Copyright (c) Two Sigma Open Source, LLC
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(ns waiter.auth.spnego-test
(:require [clojure.core.async :as async]
[clojure.test :refer :all]
[waiter.auth.spnego :refer :all]
[waiter.util.utils :as utils]))
(deftest test-decode-input-token
(is (decode-input-token {:headers {"authorization" "Negotiate Kerberos-Auth"}}))
(is (nil? (decode-input-token {:headers {"authorization" "Basic User-Pass"}}))))
(deftest test-encode-output-token
(let [encoded-token (encode-output-token (.getBytes "Kerberos-Auth"))]
(is (= "Kerberos-Auth"
(String. (decode-input-token {:headers {"authorization" encoded-token}}))))))
(deftest test-require-gss
(let [ideal-response {:body "OK" :status 200}
request-handler (constantly ideal-response)
thread-pool (Object.)
max-queue-length 10
password [:cached "PI:PASSWORD:<PASSWORD>END_PI"]
auth-principal "PI:EMAIL:<EMAIL>END_PI"
standard-request {}
standard-401-response {:body "Unauthorized"
:headers {"content-type" "text/plain"
"www-authenticate" "Negotiate"}
:status 401
:waiter/response-source :waiter}]
(with-redefs [utils/error-context->text-body #(-> % :message str)]
(testing "too many pending kerberos requests"
(with-redefs [too-many-pending-auth-requests? (constantly true)]
(let [handler (require-gss request-handler thread-pool max-queue-length password)]
(is (= {:body "Too many Kerberos authentication requests"
:headers {"content-type" "text/plain"}
:status 503
:waiter/response-source :waiter}
(handler standard-request))))))
(testing "standard 401 response on missing authorization header"
(with-redefs [too-many-pending-auth-requests? (constantly false)]
(let [handler (require-gss request-handler thread-pool max-queue-length password)]
(is (= standard-401-response (handler standard-request))))))
(testing "kerberos authentication path"
(with-redefs [too-many-pending-auth-requests? (constantly false)]
(let [auth-request (update standard-request :headers assoc "authorization" "Negotiate foo-bar")
error-object (Object.)]
(testing "401 response on failed authentication"
(with-redefs [populate-gss-credentials (fn [_ _ response-chan]
(async/>!! response-chan {:foo :bar}))]
(let [handler (require-gss request-handler thread-pool max-queue-length password)
response (handler auth-request)
response (if (map? response)
response
(async/<!! response))]
(is (= standard-401-response response)))))
(testing "401 response on missing authorization header"
(with-redefs [populate-gss-credentials (fn [_ _ response-chan]
(async/>!! response-chan {:foo :bar}))]
(let [handler (require-gss request-handler thread-pool max-queue-length password)
response (handler standard-request)
response (if (map? response)
response
(async/<!! response))]
(is (= standard-401-response response)))))
(testing "401 response on invalid authorization header"
(with-redefs [populate-gss-credentials (fn [_ _ response-chan]
(async/>!! response-chan {:foo :bar}))]
(let [handler (require-gss request-handler thread-pool max-queue-length password)
auth-request (update standard-request :headers assoc "authorization" "Bearer foo-bar")
response (handler auth-request)
response (if (map? response)
response
(async/<!! response))]
(is (= standard-401-response response)))))
(testing "error object on exception"
(with-redefs [populate-gss-credentials (fn [_ _ response-chan]
(async/>!! response-chan {:error error-object}))]
(let [handler (require-gss request-handler thread-pool max-queue-length password)
response (handler auth-request)
response (if (map? response)
response
(async/<!! response))]
(is (= error-object response)))))
(testing "successful authentication - principal and token"
(with-redefs [populate-gss-credentials (fn [_ _ response-chan]
(async/>!! response-chan {:principal auth-principal
:token "test-token"}))]
(let [handler (require-gss request-handler thread-pool max-queue-length password)
response (handler auth-request)
response (if (map? response)
response
(async/<!! response))]
(is (= (assoc ideal-response
:authorization/method :spnego
:authorization/principal "PI:EMAIL:<EMAIL>END_PI"
:authorization/user "user"
:headers {"www-authenticate" "test-token"})
(utils/dissoc-in response [:headers "set-cookie"]))))))
(testing "successful authentication - principal and token - multiple authorization header"
(with-redefs [populate-gss-credentials (fn [_ _ response-chan]
(async/>!! response-chan {:principal auth-principal
:token "test-token"}))]
(let [handler (require-gss request-handler thread-pool max-queue-length password)
auth-request (update standard-request :headers
assoc "authorization" "Bearer fee-fie,Negotiate foo-bar")
response (handler auth-request)
response (if (map? response)
response
(async/<!! response))]
(is (= (assoc ideal-response
:authorization/method :spnego
:authorization/principal "PI:EMAIL:<EMAIL>END_PI"
:authorization/user "user"
:headers {"www-authenticate" "test-token"})
(utils/dissoc-in response [:headers "set-cookie"]))))))
(testing "successful authentication - principal only"
(with-redefs [populate-gss-credentials (fn [_ _ response-chan]
(async/>!! response-chan {:principal auth-principal}))]
(let [handler (require-gss request-handler thread-pool max-queue-length password)
response (handler auth-request)
response (if (map? response)
response
(async/<!! response))]
(is (= (assoc ideal-response
:authorization/method :spnego
:authorization/principal "PI:EMAIL:<EMAIL>END_PI"
:authorization/user "user")
(utils/dissoc-in response [:headers "set-cookie"]))))))))))))
|
[
{
"context": " (spark/with-context (spark/context :app-name \"Hello World\" :master \"local[2]\")\n (is (= (->> (spa",
"end": 249,
"score": 0.6553745269775391,
"start": 244,
"tag": "NAME",
"value": "Hello"
},
{
"context": " 110))))\n;; (def sc (context :app-name \"Hello App\" :master \"local[2]\"))\n;;\n;; (with-context sc\n",
"end": 676,
"score": 0.6340434551239014,
"start": 671,
"tag": "NAME",
"value": "Hello"
}
] | test/cav/cljspark_test.clj | sethyuan/cljspark | 1 | (ns cav.cljspark-test
(:require [cav.cljspark :as spark]
[cav.cljspark.rdd :as rdd]
[clojure.test :refer :all]))
(deftest spark-context-test
(testing "with context"
(spark/with-context (spark/context :app-name "Hello World" :master "local[2]")
(is (= (->> (spark/parallelize (range 1 11))
(rdd/count))
10))))
(testing "simple map reduce"
(spark/with-context (spark/context :app-name "Simple map" :master "local[2]")
(is (= (->> (spark/parallelize (range 1 11))
(rdd/map (partial * 2))
(rdd/reduce +))
110))))
;; (def sc (context :app-name "Hello App" :master "local[2]"))
;;
;; (with-context sc
;; (let [readme (text-file "README.md" 2)]
;; (-> readme
;; (mapcat #(string/split % " "))
;; (filter #{"Spark"})
;; (count)
;; (println))))
)
| 61058 | (ns cav.cljspark-test
(:require [cav.cljspark :as spark]
[cav.cljspark.rdd :as rdd]
[clojure.test :refer :all]))
(deftest spark-context-test
(testing "with context"
(spark/with-context (spark/context :app-name "<NAME> World" :master "local[2]")
(is (= (->> (spark/parallelize (range 1 11))
(rdd/count))
10))))
(testing "simple map reduce"
(spark/with-context (spark/context :app-name "Simple map" :master "local[2]")
(is (= (->> (spark/parallelize (range 1 11))
(rdd/map (partial * 2))
(rdd/reduce +))
110))))
;; (def sc (context :app-name "<NAME> App" :master "local[2]"))
;;
;; (with-context sc
;; (let [readme (text-file "README.md" 2)]
;; (-> readme
;; (mapcat #(string/split % " "))
;; (filter #{"Spark"})
;; (count)
;; (println))))
)
| true | (ns cav.cljspark-test
(:require [cav.cljspark :as spark]
[cav.cljspark.rdd :as rdd]
[clojure.test :refer :all]))
(deftest spark-context-test
(testing "with context"
(spark/with-context (spark/context :app-name "PI:NAME:<NAME>END_PI World" :master "local[2]")
(is (= (->> (spark/parallelize (range 1 11))
(rdd/count))
10))))
(testing "simple map reduce"
(spark/with-context (spark/context :app-name "Simple map" :master "local[2]")
(is (= (->> (spark/parallelize (range 1 11))
(rdd/map (partial * 2))
(rdd/reduce +))
110))))
;; (def sc (context :app-name "PI:NAME:<NAME>END_PI App" :master "local[2]"))
;;
;; (with-context sc
;; (let [readme (text-file "README.md" 2)]
;; (-> readme
;; (mapcat #(string/split % " "))
;; (filter #{"Spark"})
;; (count)
;; (println))))
)
|
[
{
"context": "l challge on Maratona Behind The Code\"\n :author \"Joao Pedro Poloni Ponce\"\n :email \"poloniponce@protonmail.ch\"\n :url \"htt",
"end": 156,
"score": 0.9998800754547119,
"start": 133,
"tag": "NAME",
"value": "Joao Pedro Poloni Ponce"
},
{
"context": "de\"\n :author \"Joao Pedro Poloni Ponce\"\n :email \"poloniponce@protonmail.ch\"\n :url \"https://github.com/MBTC-2020-TOP100/Cloj",
"end": 193,
"score": 0.9999330639839172,
"start": 168,
"tag": "EMAIL",
"value": "poloniponce@protonmail.ch"
}
] | project.clj | MBTC-2020-TOP100/Clojure-Template | 0 | (defproject clojure-submission "0.1.0-SNAPSHOT"
:description "Clojure app to final challge on Maratona Behind The Code"
:author "Joao Pedro Poloni Ponce"
:email "poloniponce@protonmail.ch"
:url "https://github.com/MBTC-2020-TOP100/Clojure-Template"
:license {:name "Apache-2.0 License "
:url "http://www.apache.org/licenses/LICENSE-2.0"}
:dependencies [[org.clojure/clojure "1.10.0"]
[clj-http "3.10.3"]
[cheshire "5.6.1"]
[org.clojure/data.json "1.0.0"]]
:main ^:skip-aot clojure-submission.core
:target-path "target/%s"
:profiles {:uberjar {:aot :all}})
| 49891 | (defproject clojure-submission "0.1.0-SNAPSHOT"
:description "Clojure app to final challge on Maratona Behind The Code"
:author "<NAME>"
:email "<EMAIL>"
:url "https://github.com/MBTC-2020-TOP100/Clojure-Template"
:license {:name "Apache-2.0 License "
:url "http://www.apache.org/licenses/LICENSE-2.0"}
:dependencies [[org.clojure/clojure "1.10.0"]
[clj-http "3.10.3"]
[cheshire "5.6.1"]
[org.clojure/data.json "1.0.0"]]
:main ^:skip-aot clojure-submission.core
:target-path "target/%s"
:profiles {:uberjar {:aot :all}})
| true | (defproject clojure-submission "0.1.0-SNAPSHOT"
:description "Clojure app to final challge on Maratona Behind The Code"
:author "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"
:url "https://github.com/MBTC-2020-TOP100/Clojure-Template"
:license {:name "Apache-2.0 License "
:url "http://www.apache.org/licenses/LICENSE-2.0"}
:dependencies [[org.clojure/clojure "1.10.0"]
[clj-http "3.10.3"]
[cheshire "5.6.1"]
[org.clojure/data.json "1.0.0"]]
:main ^:skip-aot clojure-submission.core
:target-path "target/%s"
:profiles {:uberjar {:aot :all}})
|
[
{
"context": " ;;\n;; Author: Jon Anthony ",
"end": 1839,
"score": 0.9998437762260437,
"start": 1828,
"tag": "NAME",
"value": "Jon Anthony"
}
] | src/aerobio/htseq/termseq.clj | jsa-aerial/aerobio | 3 | ;;--------------------------------------------------------------------------;;
;; ;;
;; A E R O B I O . H T S E Q . T E R M S E Q ;;
;; ;;
;; 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. ;;
;; ;;
;; Author: Jon Anthony ;;
;; ;;
;;--------------------------------------------------------------------------;;
;;
(ns aerobio.htseq.termseq
[:require
[clojure.data.csv :as csv]
[clojure.string :as cljstr]
[aerial.fs :as fs]
[aerial.utils.coll :refer [vfold] :as coll]
[aerial.utils.string :as str]
[aerial.utils.io :refer [letio] :as io]
[aerial.utils.math.probs-stats :as p]
[aerial.utils.math.infoth :as it]
[aerial.bio.utils.filters :as fil]
[aerobio.params :as pams]
[aerobio.pgmgraph :as pg]
[aerobio.htseq.common :as cmn]
[aerobio.htseq.rnaseq :as rsq]]
)
(defn get-comparison-files-
"Compute the set of comparison bams and the corresponding output csv
for the count table matrix. Comparison sets are based on the
ComparisonSheet.csv for the experiment of eid (the experiment
id). If rep? is true, returns the comparison sets for replicates of
comparison pairs, else returns comparison sets for combined bams."
([eid opt]
(get-comparison-files- eid "ComparisonSheet.csv" opt))
([eid comp-filename opt]
(let [{:keys [rep? runtype]} opt
bpath (if rep? [:rep :bams] [:bams])
fpath (if rep? [:rep :fcnts] [:fcnts])
bams (apply cmn/get-exp-info eid bpath)
fcnts (apply cmn/get-exp-info eid fpath)
runxref (cmn/get-exp-info eid :run-xref)
pre (some (fn[[_ [t pre]]] (when (= t runtype) pre)) runxref)
compvec (->> comp-filename
(fs/join (pams/get-params :nextseq-base) eid)
slurp csv/read-csv rest
(mapv #(mapv (fn[c] (let [[s cond] (str/split #"-" c)]
(str s "-" pre cond))) %)))
bamsvec (mapv (fn[v]
(mapcat #(-> (fs/join bams (str % "*.bam"))
fs/glob sort)
v))
compvec)
otcsvs (mapv (fn[v]
(fs/join fcnts (str (cljstr/join "-" v) ".csv")))
compvec)]
(mapv #(vector %1 %2) bamsvec otcsvs))))
(defmethod cmn/get-comparison-files :termseq
[_ & args]
(apply get-comparison-files- args))
(defn split-filter-fastqs
[eid]
(cmn/split-filter-fastqs eid identity))
(defmethod cmn/get-phase-1-args :termseq
[_ & args]
(apply cmn/get-phase-1-args :rnaseq args))
(defn run-termseq-comparison
[eid recipient comparison-file get-toolinfo template rtype]
(let [_ (rsq/get-phase-2-dirs eid nil)
_ (rsq/get-phase-2-dirs eid :rep)
ftype "CDS" ; <-- BAD 'magic number'
strain (first (cmn/get-exp-info eid :strains))
refnm ((cmn/get-exp-info eid :ncbi-sample-xref) strain)
refgtf (fs/join (cmn/get-exp-info eid :refs) (str refnm ".gtf"))
repcfg (assoc-in template
[:nodes :ph2 :args]
[eid comparison-file
{:rep? true :runtype rtype}
ftype refgtf recipient])
repjob (pg/future+ (cmn/flow-program repcfg get-toolinfo :run true))
cfg (assoc-in template
[:nodes :ph2 :args]
[eid comparison-file
{:rep? false :runtype rtype}
ftype refgtf recipient])
cfgjob (pg/future+ (cmn/flow-program cfg get-toolinfo :run true))]
#_(clojure.pprint/pprint repflow)
[repjob cfgjob]))
(defmethod cmn/run-comparison :termseq
[_ eid recipient compfile get-toolinfo template phase]
(let [rtype (->> phase (str/split #"-") last keyword)]
(run-termseq-comparison
eid recipient compfile get-toolinfo template rtype)))
(defmethod cmn/run-phase-2 :termseq
[_ eid recipient get-toolinfo template phase]
(cmn/run-comparison :termseq
eid recipient "ComparisonSheet.csv" get-toolinfo template phase))
| 21718 | ;;--------------------------------------------------------------------------;;
;; ;;
;; A E R O B I O . H T S E Q . T E R M S E Q ;;
;; ;;
;; 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. ;;
;; ;;
;; Author: <NAME> ;;
;; ;;
;;--------------------------------------------------------------------------;;
;;
(ns aerobio.htseq.termseq
[:require
[clojure.data.csv :as csv]
[clojure.string :as cljstr]
[aerial.fs :as fs]
[aerial.utils.coll :refer [vfold] :as coll]
[aerial.utils.string :as str]
[aerial.utils.io :refer [letio] :as io]
[aerial.utils.math.probs-stats :as p]
[aerial.utils.math.infoth :as it]
[aerial.bio.utils.filters :as fil]
[aerobio.params :as pams]
[aerobio.pgmgraph :as pg]
[aerobio.htseq.common :as cmn]
[aerobio.htseq.rnaseq :as rsq]]
)
(defn get-comparison-files-
"Compute the set of comparison bams and the corresponding output csv
for the count table matrix. Comparison sets are based on the
ComparisonSheet.csv for the experiment of eid (the experiment
id). If rep? is true, returns the comparison sets for replicates of
comparison pairs, else returns comparison sets for combined bams."
([eid opt]
(get-comparison-files- eid "ComparisonSheet.csv" opt))
([eid comp-filename opt]
(let [{:keys [rep? runtype]} opt
bpath (if rep? [:rep :bams] [:bams])
fpath (if rep? [:rep :fcnts] [:fcnts])
bams (apply cmn/get-exp-info eid bpath)
fcnts (apply cmn/get-exp-info eid fpath)
runxref (cmn/get-exp-info eid :run-xref)
pre (some (fn[[_ [t pre]]] (when (= t runtype) pre)) runxref)
compvec (->> comp-filename
(fs/join (pams/get-params :nextseq-base) eid)
slurp csv/read-csv rest
(mapv #(mapv (fn[c] (let [[s cond] (str/split #"-" c)]
(str s "-" pre cond))) %)))
bamsvec (mapv (fn[v]
(mapcat #(-> (fs/join bams (str % "*.bam"))
fs/glob sort)
v))
compvec)
otcsvs (mapv (fn[v]
(fs/join fcnts (str (cljstr/join "-" v) ".csv")))
compvec)]
(mapv #(vector %1 %2) bamsvec otcsvs))))
(defmethod cmn/get-comparison-files :termseq
[_ & args]
(apply get-comparison-files- args))
(defn split-filter-fastqs
[eid]
(cmn/split-filter-fastqs eid identity))
(defmethod cmn/get-phase-1-args :termseq
[_ & args]
(apply cmn/get-phase-1-args :rnaseq args))
(defn run-termseq-comparison
[eid recipient comparison-file get-toolinfo template rtype]
(let [_ (rsq/get-phase-2-dirs eid nil)
_ (rsq/get-phase-2-dirs eid :rep)
ftype "CDS" ; <-- BAD 'magic number'
strain (first (cmn/get-exp-info eid :strains))
refnm ((cmn/get-exp-info eid :ncbi-sample-xref) strain)
refgtf (fs/join (cmn/get-exp-info eid :refs) (str refnm ".gtf"))
repcfg (assoc-in template
[:nodes :ph2 :args]
[eid comparison-file
{:rep? true :runtype rtype}
ftype refgtf recipient])
repjob (pg/future+ (cmn/flow-program repcfg get-toolinfo :run true))
cfg (assoc-in template
[:nodes :ph2 :args]
[eid comparison-file
{:rep? false :runtype rtype}
ftype refgtf recipient])
cfgjob (pg/future+ (cmn/flow-program cfg get-toolinfo :run true))]
#_(clojure.pprint/pprint repflow)
[repjob cfgjob]))
(defmethod cmn/run-comparison :termseq
[_ eid recipient compfile get-toolinfo template phase]
(let [rtype (->> phase (str/split #"-") last keyword)]
(run-termseq-comparison
eid recipient compfile get-toolinfo template rtype)))
(defmethod cmn/run-phase-2 :termseq
[_ eid recipient get-toolinfo template phase]
(cmn/run-comparison :termseq
eid recipient "ComparisonSheet.csv" get-toolinfo template phase))
| true | ;;--------------------------------------------------------------------------;;
;; ;;
;; A E R O B I O . H T S E Q . T E R M S E Q ;;
;; ;;
;; 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. ;;
;; ;;
;; Author: PI:NAME:<NAME>END_PI ;;
;; ;;
;;--------------------------------------------------------------------------;;
;;
(ns aerobio.htseq.termseq
[:require
[clojure.data.csv :as csv]
[clojure.string :as cljstr]
[aerial.fs :as fs]
[aerial.utils.coll :refer [vfold] :as coll]
[aerial.utils.string :as str]
[aerial.utils.io :refer [letio] :as io]
[aerial.utils.math.probs-stats :as p]
[aerial.utils.math.infoth :as it]
[aerial.bio.utils.filters :as fil]
[aerobio.params :as pams]
[aerobio.pgmgraph :as pg]
[aerobio.htseq.common :as cmn]
[aerobio.htseq.rnaseq :as rsq]]
)
(defn get-comparison-files-
"Compute the set of comparison bams and the corresponding output csv
for the count table matrix. Comparison sets are based on the
ComparisonSheet.csv for the experiment of eid (the experiment
id). If rep? is true, returns the comparison sets for replicates of
comparison pairs, else returns comparison sets for combined bams."
([eid opt]
(get-comparison-files- eid "ComparisonSheet.csv" opt))
([eid comp-filename opt]
(let [{:keys [rep? runtype]} opt
bpath (if rep? [:rep :bams] [:bams])
fpath (if rep? [:rep :fcnts] [:fcnts])
bams (apply cmn/get-exp-info eid bpath)
fcnts (apply cmn/get-exp-info eid fpath)
runxref (cmn/get-exp-info eid :run-xref)
pre (some (fn[[_ [t pre]]] (when (= t runtype) pre)) runxref)
compvec (->> comp-filename
(fs/join (pams/get-params :nextseq-base) eid)
slurp csv/read-csv rest
(mapv #(mapv (fn[c] (let [[s cond] (str/split #"-" c)]
(str s "-" pre cond))) %)))
bamsvec (mapv (fn[v]
(mapcat #(-> (fs/join bams (str % "*.bam"))
fs/glob sort)
v))
compvec)
otcsvs (mapv (fn[v]
(fs/join fcnts (str (cljstr/join "-" v) ".csv")))
compvec)]
(mapv #(vector %1 %2) bamsvec otcsvs))))
(defmethod cmn/get-comparison-files :termseq
[_ & args]
(apply get-comparison-files- args))
(defn split-filter-fastqs
[eid]
(cmn/split-filter-fastqs eid identity))
(defmethod cmn/get-phase-1-args :termseq
[_ & args]
(apply cmn/get-phase-1-args :rnaseq args))
(defn run-termseq-comparison
[eid recipient comparison-file get-toolinfo template rtype]
(let [_ (rsq/get-phase-2-dirs eid nil)
_ (rsq/get-phase-2-dirs eid :rep)
ftype "CDS" ; <-- BAD 'magic number'
strain (first (cmn/get-exp-info eid :strains))
refnm ((cmn/get-exp-info eid :ncbi-sample-xref) strain)
refgtf (fs/join (cmn/get-exp-info eid :refs) (str refnm ".gtf"))
repcfg (assoc-in template
[:nodes :ph2 :args]
[eid comparison-file
{:rep? true :runtype rtype}
ftype refgtf recipient])
repjob (pg/future+ (cmn/flow-program repcfg get-toolinfo :run true))
cfg (assoc-in template
[:nodes :ph2 :args]
[eid comparison-file
{:rep? false :runtype rtype}
ftype refgtf recipient])
cfgjob (pg/future+ (cmn/flow-program cfg get-toolinfo :run true))]
#_(clojure.pprint/pprint repflow)
[repjob cfgjob]))
(defmethod cmn/run-comparison :termseq
[_ eid recipient compfile get-toolinfo template phase]
(let [rtype (->> phase (str/split #"-") last keyword)]
(run-termseq-comparison
eid recipient compfile get-toolinfo template rtype)))
(defmethod cmn/run-phase-2 :termseq
[_ eid recipient get-toolinfo template phase]
(cmn/run-comparison :termseq
eid recipient "ComparisonSheet.csv" get-toolinfo template phase))
|
[
{
"context": "r \"retrieving data from larda\") :duration 0 :key \"retData\"})\r\n ; (async/go\r\n ; (let [response (asyn",
"end": 8466,
"score": 0.8774973154067993,
"start": 8459,
"tag": "KEY",
"value": "retData"
}
] | src/weblarda3/explorer.cljs | lacros-tropos/weblarda3 | 0 | (ns weblarda3.explorer
(:require
[reagent.core :as reagent]
[cljs.core.async :as async]
[cljs-http.client :as http]
[ajax.core :as ajax] ; library making error handling possible
[ajax.protocols :as protocol]
[antizer.reagent :as ant]
[clojure.string :as string]
[clojure.set :as set]
[goog.iter]
[weblarda3.vis :as vis]
[cljsjs.msgpack-lite :as msgpack]
[weblarda3.vis :as vis]
[weblarda3.colorplot :as cplot]))
;
;
; link for the data api
; http://larda.tropos.de/larda3/api/lacros_dacapo/POLLY/attbsc1064?rformat=json&interval=1549238460.0-1549396800.0%2C0-8000
; rformat = {bin|msgpack|json}
;
; for the explorer
; http://larda.tropos.de/larda3/explorer/lacros_dacapo/
; http://localhost:3449/explorer.html?interval=1549385800.0-1549396800.0%2C0-8000¶ms=CLOUDNET|WIDTH
; http://localhost:3449/explorer.html?interval=1549385800.0-1549396800.0%2C0-8000¶ms=POLLYNET|attbsc1064
; http://localhost:3449/explorer.html?interval=1549385800.0-1549396800.0%2C0-8000¶ms=CLOUDNET|Z
; http://larda.tropos.de/larda3/explorer/lacros_dacapo?interval=1549385800.0-1549396800.0,0-8000¶ms=CLOUDNET|Z,CLOUDNET|LDR,CLOUDNET_LIMRAD|Z,POLLYNET|attbsc1064
; http://larda.tropos.de/larda3/explorer/lacros_dacapo?interval=1549385800.0-1549396800.0,0-8000¶ms=CLOUDNET|Z,CLOUDNET|LDR,CLOUDNET_LIMRAD|Z,POLLYNET|attbsc1064,SHAUN|VEL
; TODO
; - update link on changes
; - info panel
; - categorial colormaps
; - more agressive compiler options
(println "search" (.. js/window -location -search))
(println "href" (.. js/window -location -href))
; dev or hard coded
;(defonce host "http://larda.tropos.de/larda3/")
;(defonce host "http://larda3.tropos.de/")
;get from index.html <script> tag
;(defonce host js/hostaddr)
(defonce host (second (re-find #"(.+)explorer" js/hostaddr)))
(println "set host " host)
(defn keys-to-str [list]
(goog.iter/join (clj->js (map name list)) "|"))
(defn paramstr-to-vec [param_string]
(string/split param_string #"\|"))
(defonce app-state
(reagent/atom {:coll1-vis true
:c-list []
:c-selected "mosaic"
:c-info {}
:sel-time-range {"ts" [(-> (js/moment) (.utc) (.subtract 4 "hours") (.format "X"))
(-> (js/moment) (.utc) (.format "X"))]
"rg" [0 12000]}
:data-containers {}
:mapping-container-plot {}
:data-loading-progress false
;:colorplotProps {:outerSize {:w 800 :h 450} :imageSize {:w 685 :h 400}}
:colorplotProps {:outerSize {:w 750 :h 450} :imageSize {:w 635 :h 400}}}))
(defonce modal-container (reagent/atom {:show false
:param-str ""}))
(defonce modal-info (reagent/atom {:show false
:title ""
:content "loading.."}))
(defn fetch-description [param_string]
(let [c-name (get-in @app-state [:c-selected])
system (first (string/split param_string #"\|"))
param (second (string/split param_string #"\|"))]
(println "request string" (str host "description/" c-name "/" system "/" param))
(swap! modal-info assoc-in [:title] (str system ": " param))
(async/go (let [response (async/<! (http/get (str host "description/" c-name "/" system "/" param) {:as :raw :with-credentials? false}))]
;(println "retrieved" (:status response) (:body response))
(println "fetched new description string " c-name system param (:status response))
(swap! modal-info assoc-in [:content] (get-in response [:body]))))))
(def colorplotProps-cursor (reagent/cursor app-state [:colorplotProps]))
(def data-containers-cursor (reagent/cursor app-state [:data-containers]))
(def cplot-click (async/chan))
(defn get-permalink []
; ?interval=1549385800.0-1549396800.0%2C0-8000¶ms=CLOUDNET|WIDTH
(let [ts-interval (string/join "-" (get-in @app-state [:sel-time-range "ts"]))
rg-interval (string/join "-" (get-in @app-state [:sel-time-range "rg"]))
interval (str ts-interval "," rg-interval)
params (string/join "," (keys (get-in @app-state [:data-containers])))]
(str host "explorer/" (get @app-state :c-selected) "?interval=" interval "¶ms=" params)))
(defn parse-number-nan [str]
(if (and (> (count str) 0) (not (js/isNaN (js/parseFloat str))))
(js/parseFloat str)
nil))
(defn data-container-extract-meta [data-container]
(let [meta data-container
var (goog.object/get data-container "var")
mask (goog.object/get data-container "mask")
ts (goog.object/get data-container "ts")
rg (goog.object/get data-container "rg")
varconverter (case (goog.object/get data-container"plot_varconverter")
"lin2z" "dB"
(goog.object/get data-container"plot_varconverter"))]
(println "extract-meta:" varconverter)
(js-delete meta "var")
(js-delete meta "mask")
(js-delete meta "ts")
(js-delete meta "rg")
(assoc (js->clj meta)
"plot_varconverter" varconverter
"var" var "mask" mask
"ts" ts "rg" rg)))
(defn hex-comma-and-split [str]
(if str
(string/split (string/replace str #"%2C" ",") #",") []))
(defn infer-time-format [str]
(if (string/includes? str "_")
(case (count str)
11 (.format (js/moment.utc str "YYYYMMDD_HH") "X")
13 (.format (js/moment.utc str "YYYYMMDD_HHmm") "X")
15 (.format (js/moment.utc str "YYYYMMDD_HHmmss") "X"))
str))
(defn interval-to-dict [interval]
(case (count interval)
0 {"ts" [(-> (js/moment) (.utc) (.subtract 4 "hours") (.format "X"))
(-> (js/moment) (.utc) (.format "X"))]
"rg" [0 12000]}
1 {"ts" (mapv infer-time-format (string/split (first interval) #"-"))
"rg" [0 12000]}
2 {"ts" (mapv infer-time-format (string/split (first interval) #"-"))
"rg" (mapv js/parseFloat (string/split (second interval) #"-"))}))
(defn empty-places [dict places]
(vec (set/difference (set places) (set (keys dict)))))
(defn update-plots []
(println "update plots" (get-in @app-state [:mapping-container-plot]))
;(println (keys @data-containers-cursor))
(doall (for [k [0 1 2 3]]
(do (-> (js/d3.select (str "#cp-" k " svg")) (.selectAll "*") (.remove))
(-> (js/d3.select (str "#cp-" k " canvas")) (.node) (.getContext "2d")
(.clearRect 0 0 (get-in @colorplotProps-cursor [:outerSize :w]) (get-in @colorplotProps-cursor [:outerSize :h]))))))
(doall (for [[k v] (get-in @app-state [:mapping-container-plot])]
(do ;(println "update " k v)
;(cplot/colorplot-did-mount colorplotProps-cursor k data-containers-cursor v cplot-click)
(cplot/plot-dispatch colorplotProps-cursor k data-containers-cursor v cplot-click)))))
(defn http-error-handler [uri]
(fn [{:keys [status status-text response]}]
(ant/notification-error {:message (str "Error " status) :duration 0 :description (str "while fetching data " status-text)})
(.log js/console (str "Error occured: " status)
; new TextDecoder ("utf-8") .decode (uint8array)
status-text uri (.decode (js/TextDecoder. "utf-8") response))))
(defn custom-http-get [uri]
(let [channel (async/chan)]
(async/go
(ajax/GET uri
{:with-credentials false
:response-format {:content-type "application/msgpack" :description "data conainer msgpack" :read protocol/-body :type :arraybuffer}
:handler #(async/put! channel %)
:error-handler (http-error-handler uri)}))
channel))
(defn fetch-data [c-name param_string time-interval range-interval]
(let [sys_param (paramstr-to-vec param_string)
url (str host "api/" c-name "/" (first sys_param) "/" (second sys_param) "?rformat=msgpack&interval="
(first time-interval) "-" (last time-interval) "%2C" (first range-interval) "-" (last range-interval))]
(js/console.log "fetch data larda url: " url)
(swap! app-state assoc-in [:data-loading-progress] true)
(ant/notification-open {:message (str "retrieving data from larda") :duration 0 :key "retData"})
; (async/go
; (let [response (async/<! (custom-http-get url))]
; (println response)
; ;(println (msgpack.decode response))
; (println (msgpack.decode (new js/Uint8Array response)))))
;(async/go (let [response (async/<! (http/get url {:response-type :array-buffer :with-credentials? false}))]
(async/go (let [response (async/<! (custom-http-get url))]
(println "fetched data " c-name param_string time-interval range-interval)
(let [decoded (msgpack.decode (new js/Uint8Array response))
mapping-container-plot (get @app-state :mapping-container-plot)
empty-plot (first (empty-places mapping-container-plot [0 1 2 3]))]
;(goog.object/set decoded "var" (c/pull_loc_in decoded))
;(println (type (:body response)) (:body response))
;(js/console.log (type (:body response)) (:body response))
;(js/console.log response (new js/Uint8Array (:body response)))
;(js/console.log "decoded data" decoded)
;(js/console.log "decoded data" (msgpack.decode (new js/Uint8Array (:body response))))
;(swap! app-state assoc-in [:alltrees] decoded)
;(reset! alltrees-cursor decoded)
(swap! app-state assoc-in [:data-containers param_string] (data-container-extract-meta decoded))
(swap! app-state assoc-in [:backend :data-loading-progress] false)
; TODO more sophisticated version required here
(if-not (or (nil? empty-plot) (some #(= param_string %) (vals mapping-container-plot)))
(swap! app-state assoc-in [:mapping-container-plot empty-plot] param_string))
(ant/notification-close "retData")
(update-plots)
(println "data loading done; mapping " mapping-container-plot (get @app-state :mapping-container-plot)))))))
; extract from query string
(defn extract-from-address [address]
(let [href (.. address -href)
;href "http://larda.tropos.de/larda3/explorer/lacros_dacapo/"
;href "http://larda3.tropos.de/explorer/lacros_cycare/"
c-name (last (string/split (first (string/split href #"\?")) #"/"))
query-string (.. address -search)
;query-string "?rformat=json&interval=1549238460.0-1549396800.0%2C0-8000¶ms=CLOUDNET_LIMRAD|VEL"
;query-string "?rformat=json&interval=1549385800.0-1549396800.0%2C0-8000¶ms=CLOUDNET_LIMRAD|VEL,CLOUDNET|CLASS"
; 19951231_235959
;query-string "?rformat=json&interval=1549238460.0-1549396800.0"
;query-string "?rformat=json&interval=19951231_23-19951231_235959"
interval (hex-comma-and-split (second (re-find #"interval=([^&]*)" query-string)))
sel-time-range (interval-to-dict interval)
params (hex-comma-and-split (second (re-find #"params=([^&]*)" query-string)))]
;define default values for interval
(println "extract from address" href query-string)
(println (string/split (first (string/split href #"\?")) #"/") "=> " c-name)
(println "interval" interval (count interval) sel-time-range) (println "params" params)
(swap! app-state assoc-in [:c-selected] c-name)
(if (> (count interval) 0)
(swap! app-state assoc-in [:sel-time-range] sel-time-range))
(doall (for [param params]
(fetch-data (get @app-state :c-selected) param (get-in @app-state [:sel-time-range "ts"]) (get-in @app-state [:sel-time-range "rg"]))))))
;query-string (second (re-find #"camp=([^&]*)" (.. js/window -location -search)))
(extract-from-address (.. js/window -location))
; get the paramaeter list...
(defn fetch-c-info [c-name & [additional-atom]]
(ant/notification-open {:message "loading data availability " :description c-name :duration 0 :key "retData"})
(swap! app-state assoc-in [:param-sel] [])
(async/go (let [response (async/<! (http/get (str host "api/" c-name "/") {:as :json :with-credentials? false}))]
;(println (:status response) (:body response))
(println "fetched new c-info for " c-name (:status response))
(ant/notification-close "retData")
(if-not (= (:status response) 200)
(do (println "response " response)
(ant/notification-error {:message "Error" :duration 0 :description "while fetching campaign info"})))
;(ant/notification-info {:message "Hint" :description "right-click on parameter to display description text" :duration 20})
;(set-initial-selection (get-in response [:body]))
(let [duration (get-in response [:body :config_file :duration])
last (last (last duration))
timestart (.format (js/moment.utc last "YYYYMMDD") "X")
timeend (str (+ (js/parseFloat timestart) (* 6 3600)))]
(if-not (nil? additional-atom)
(do (swap! additional-atom assoc-in ["ts"] [timestart timeend])
(swap! app-state assoc-in [:sel-time-range "ts"] [timestart timeend]))))
(swap! app-state assoc-in [:c-info] (get-in response [:body])))))
; replace camp by /camp/
(async/go (let [response (async/<! (http/get (str host "api/") {:as :json :with-credentials? false}))
query-string (second (re-find #"camp=([^&]*)" (.. js/window -location -search)))]
;(println "found string " query-string (get-in response [:body :campaign_list]))
(if-not (= (:status response) 200)
(do (println "response " response)
(ant/notification-error {:message "Error" :duration 0 :description (str "while fetching basic info " host)})))
(if-not (some #{(get-in @app-state [:c-selected])} (get-in response [:body :campaign_list]))
(swap! app-state assoc-in [:c-selected] (first (get-in response [:body :campaign_list]))))
(if (and (not (nil? query-string)) (some #{query-string} (get-in response [:body :campaign_list])))
(swap! app-state assoc-in [:c-selected] query-string))
; at first check if Query_String provided campaign
(println "fetch campaign list" (:status response) (:body response))
(fetch-c-info (get @app-state :c-selected))
(swap! app-state assoc-in [:c-list] (get-in response [:body :campaign_list]))))
(defn change-campaign [& [additional-atom]]
(fn [c-name]
;this is to update the link
;(let [query-string (.. js/window -location -search)]
; (if (count query-string)
; (js/window.history.replaceState (clj->js nil) (clj->js nil) (string/replace query-string #"camp=([^&]*)" (str "camp=" c-name)))))
(swap! app-state assoc-in [:c-selected] (js->clj c-name))
(swap! app-state assoc-in [:data-containers] {})
(swap! app-state assoc-in [:mapping-container-plot] {})
(update-plots)
(fetch-c-info c-name additional-atom)))
(defn update-time-range [args]
; update app-state
; download for all the present parameters
(swap! app-state assoc-in [:sel-time-range] args)
;when time is updated we need to upddate the data as well
(let [params (vec (keys (get-in @app-state [:data-containers])))]
(println "update params " params)
(swap! app-state assoc-in [:data-containers] {})
(doall (map #(fetch-data (get @app-state :c-selected) % (get-in @app-state [:sel-time-range "ts"]) (get-in @app-state [:sel-time-range "rg"])) params)))
; (doall (for [param params]
; (do (println "update time range" param)
; (fetch-data (get @app-state :c-selected) param
; (get-in @app-state [:sel-time-range "ts"]) (get-in @app-state [:sel-time-range "rg"]))))))
(println "update time range " args))
(defn add-param [param]
;#(reset! panel1-param (js->clj %))
; download
(fetch-data (get @app-state :c-selected) param (get-in @app-state [:sel-time-range "ts"]) (get-in @app-state [:sel-time-range "rg"]))
(console.log "add param " param))
(defn delete-container [param_string]
(fn [] (println param_string (keys (get @app-state :data-containers)))
(swap! app-state assoc-in [:data-containers] (dissoc (get @app-state :data-containers) param_string))
(let [map-cont-plot (get-in @app-state [:mapping-container-plot])
filtered (into {} (filter (fn [[k v]] (not= param_string v)) map-cont-plot))]
(println "filtered " filtered)
(swap! app-state assoc-in [:mapping-container-plot] filtered))
(println "new mapping " (get-in @app-state [:mapping-container-plot]))
(update-plots)))
(defn entry-in-list []
(fn [data-containers k v]
;(js/console.log entry)
;(js/console.log "operator " (get entry "operator") (type (get entry "operator")))
;(js/console.log "ndfilters " (get-in entry ["ndfilters"]))
; (println "id?" (get entry "time") (get entry "id"))
[:tr
[:td k]
[:td [:select {:on-change (fn [e] ;(println (.. e -target -value) (get-in @data-containers [k "colormap"]))
(swap! data-containers assoc-in [k "colormap"] (.. e -target -value)))
:value (get-in @data-containers [k "colormap"])}
(for [cmap (js->clj (js/colormaps.available))]
^{:key cmap} [:option {:value cmap} cmap])]]
[:td [:select {:on-change (fn [e] ;(println (.. e -target -value) (get-in @data-containers [k "colormap"]))
(swap! data-containers assoc-in [k "plot_varconverter"] (.. e -target -value)))
:value (get-in @data-containers [k "plot_varconverter"])}
(for [cmap cplot/avail-var-converters]
^{:key cmap} [:option {:value cmap} cmap])]]
[:td [ant/input {:size "small" :style {:margin-left "0px" :margin-top "0px" :width "65px" :text-align "right"}
:default-value (get-in @data-containers [k "var_lims" 0])
:onChange #(swap! data-containers assoc-in [k "var_lims" 0] (js->clj (.. % -target -value)))}]
" - "
[ant/input {:size "small" :style {:margin-left "0px" :margin-top "0px" :width "65px" :text-align "right"}
:default-value (get-in @data-containers [k "var_lims" 1])
:onChange #(swap! data-containers assoc-in [k "var_lims" 1] (js->clj (.. % -target -value)))}]]
[:td [ant/button {:on-click #((swap! modal-container assoc-in [:param-str] k) (swap! modal-container update-in [:show] not)) :size "small" :icon "bars"}]]
[:td [ant/button {:on-click #((swap! modal-info update-in [:show] not) (fetch-description k)) :size "small" :icon "info-circle"}]]
[:td [ant/button {:on-click (delete-container k) :size "small" :type "danger"} "x"]]]))
(defn editor-container-list [app-state]
(let [data-containers (reagent/atom (get @app-state :data-containers))]
(fn []
(if-not (= (set (keys @data-containers)) (set (keys (get @app-state :data-containers))))
(do (reset! data-containers (get @app-state :data-containers)) (println "made editor data containers consistent")))
[:div
[:table#editorleft
[:thead [:tr [:th "Parameter"] [:th "Colormap"] [:th "Scale"] [:th "Limits"] [:th ""] [:th "Descr."]]]
[:tbody (for [[k v] (get @app-state :data-containers)] ^{:key k} [entry-in-list data-containers k v])]]
[ant/button {:on-click #((swap! app-state assoc-in [:data-containers] @data-containers) (update-plots))
:size "small"} "update plots"]
[:br][:br]
"container - plot - mapping"
[:table#editorleft
[:tbody (doall (for [v [0 1 2 3]] ^{:key v} [:tr
[:td (str "Plot " v)]
[:td [:select {:on-change (fn [e] ;(println (.. e -target -value) (get-in @data-containers [k "colormap"]))
(swap! app-state assoc-in [:mapping-container-plot v] (.. e -target -value))
(update-plots))
:value (get-in @app-state [:mapping-container-plot v])}
(doall (for [params (conj (keys (get @app-state :data-containers)) "")]
^{:key params} [:option {:value params} params]))]]]))]]])))
(defn update-time-by [atm idx-old idx-new amount]
(let [value (js/parseFloat (get-in @atm ["ts" idx-old]))
new (+ value amount)]
;(println "update time " value new)
(swap! atm assoc-in ["ts" idx-new] (str new))))
(defn disabled-date? [current]
(let [duration (get-in @app-state [:c-info :config_file :duration])
testfn (fn [pair current] (and (> current (js/moment.utc (first pair) "YYYYMMDD"))
(< current (.add (js/moment.utc (second pair) "YYYYMMDD") 1 "days"))))
in-one? (mapv #(testfn % current) duration)]
(not (some true? in-one?))))
(defn editor []
(let [panel1-time-range (reagent/atom (get @app-state :sel-time-range))
panel1-param (reagent/atom "select")
check-valid (fn [] (and (< (int (get-in @panel1-time-range ["ts" 0])) (int (get-in @panel1-time-range ["ts" 1])))
(< (- (int (get-in @panel1-time-range ["ts" 1])) (int (get-in @panel1-time-range ["ts" 0]))) 86400)
(< (int (get-in @panel1-time-range ["rg" 0])) (int (get-in @panel1-time-range ["rg" 1])))))]
(fn []
[:div#editor {:style {:min-width "600px" :width "700px" :margin-left "30px"}}
[ant/collapse
[ant/collapse-panel {:header "Time, Range, Parameter" :key "1"}
[ant/row
[ant/col {:span 12}
[:table#editorleft
[:thead]
[:tbody
[:tr [:td "Begin"]
[:td [ant/date-picker {:format "YYYYMMDD_HHmm" :value (.utc (js/moment.unix (get-in @panel1-time-range ["ts" 0])))
:disabled-date disabled-date?
:on-change (fn [_ d] (swap! panel1-time-range assoc-in ["ts" 0] (.format (js/moment.utc d "YYYYMMDD_HHmm") "X")))
:style {:width "100%"} :show-today false :size "small"
:showTime {:use12Hours false :format "HH:mm"}}]
[:br]
[:span.clickable {:on-click #(update-time-by panel1-time-range 0 0 -3600)} "-1h"]
[:span.clickable {:on-click #(update-time-by panel1-time-range 0 0 -600)} "-10min"]
[:span.clickable {:on-click #(update-time-by panel1-time-range 0 0 600)} "+10min"]
[:span.clickable {:on-click #(update-time-by panel1-time-range 0 0 3600)} "+1h"]]]
[:tr [:td "End"]
[:td [ant/date-picker {:format "YYYYMMDD_HHmm" :value (.utc (js/moment.unix (get-in @panel1-time-range ["ts" 1])))
:disabled-date disabled-date?
:on-change (fn [_ d] (swap! panel1-time-range assoc-in ["ts" 1] (.format (js/moment.utc d "YYYYMMDD_HHmm") "X")))
:style {:width "100%"} :show-today false :size "small"
:showTime {:use12Hours false :format "HH:mm"}}]
[:br]
[:span.clickable {:on-click #(update-time-by panel1-time-range 1 1 -3600)} "-1h"]
[:span.clickable {:on-click #(update-time-by panel1-time-range 1 1 -600)} "-10min"]
[:span.clickable {:on-click #(update-time-by panel1-time-range 1 1 600)} "+10min"]
[:span.clickable {:on-click #(update-time-by panel1-time-range 1 1 3600)} "+1h"]
[:span.clickable {:on-click #(update-time-by panel1-time-range 0 1 14400)} "Begin +4h"]]]
[:tr [:td "Range"] [:td [ant/input {:size "small" :style {:margin-left "6px" :margin-top "5px" :width "70px" :text-align "right"}
:default-value (get-in @panel1-time-range ["rg" 0])
:onChange #(swap! panel1-time-range assoc-in ["rg" 0] (js->clj (.. % -target -value)))}]
" - "
[ant/input {:size "small" :style {:margin-left "6px" :margin-top "5px" :width "70px" :text-align "right"}
:default-value (get-in @panel1-time-range ["rg" 1])
:onChange #(swap! panel1-time-range assoc-in ["rg" 1] (js->clj (.. % -target -value)))}]]]
[:tr]]] [ant/button {:on-click #(update-time-range @panel1-time-range)
:disabled (not (check-valid))
:size "small"} "update"]]
[ant/col {:span 12}
[:table#editorleft
[:thead]
[:tbody
[:tr [:td "Campaign"] [:td [ant/select {:showSearch true
:placeholder "select campaign"
:value (get-in @app-state [:c-selected])
:onChange (change-campaign panel1-time-range)
:style {:width "150px"} :size "small"}
(for [c-name (get-in @app-state [:c-list])] ^{:key c-name} [ant/select-option {:value c-name} c-name])]]]
[:tr [:td "Add Parameter"]
[:td
[ant/tree-select {:value @panel1-param :size "small"
:placeholder "Please select" :showSearch true
:onChange (fn [param] (reset! panel1-param (js->clj param)) (add-param (js->clj param)))}
(doall (for [system (sort (keys (get-in @app-state [:c-info :connectors])))]
^{:key system} [ant/tree-tree-node {:title system :selectable false :style {:font-size 11}}
(for [param (sort (keys (get-in @app-state [:c-info :connectors (keyword system) :params])))]
^{:key (keys-to-str [system param])} [ant/tree-tree-node
{:value (keys-to-str [system param])
:title (keys-to-str [system param])}])]))]]]]]]
(if (> (int (get-in @panel1-time-range ["ts" 0])) (int (get-in @panel1-time-range ["ts" 1]))) [:p.er "Time: begin > end"])
(if (> (- (int (get-in @panel1-time-range ["ts" 1])) (int (get-in @panel1-time-range ["ts" 0]))) 86400) [:p.er "Time: too long"])
;(if (< (count (get @panel1-data :sel-camp)) 1) [:p.er "Select campaign"])
(if (> (int (get-in @panel1-time-range ["rg" 0])) (int (get-in @panel1-time-range ["rg" 1]))) [:p.er "Range: top > bottom"])
[ant/col {:span 24} [:br] [:div [ant/button {:on-click #(js/custom.copy_string (get-permalink)) :size "small"} "copy permalink"]
[:span.permalink (get-permalink)]]]]]]
[ant/collapse
[ant/collapse-panel {:header "Plot properties" :key "1"}
[editor-container-list app-state]]]])))
; (defn list-data-contianers []
; [:div#rightfloat (doall (for [data-cont (keys (get-in @app-state [:data-containers]))] ^{:key data-cont} [:div data-cont [:br]]))])
(defn colorplot-component [id]
(reagent/create-class
{:reagent-render #(cplot/colorplot-render colorplotProps-cursor id)
:component-did-mount #(cplot/plot-dispatch colorplotProps-cursor id data-containers-cursor (get-in @app-state [:mapping-container-plot id]) cplot-click)
:component-did-update #(cplot/plot-dispatch colorplotProps-cursor id data-containers-cursor (get-in @app-state [:mapping-container-plot id]) cplot-click)}))
(defn display-modal-info []
(fn []
[ant/modal {:visible (get-in @modal-info [:show]) :title (str "Description " (get-in @modal-info [:title]))
:on-ok #(reset! modal-info {:show false :title "" :content "loading..."})
:on-cancel #(reset! modal-info {:show false :title "" :content "loading..."})}
(reagent/as-element [:div {:dangerouslySetInnerHTML {:__html (string/replace (get-in @modal-info [:content]) #"\n" "<br />")}}])]))
(defn data-container-meta-only [data-container]
(let [new (dissoc data-container "var" "mask" "ts" "rg")
ts (get data-container "ts")
rg (get data-container "rg")]
(assoc new
"ts" [(first ts) (last ts)] "rg" [(first rg) (last rg)])))
(defn pretty-container [data-container]
(with-out-str (cljs.pprint/pprint data-container)))
(defn display-modal-container []
(fn []
[ant/modal {:visible (get-in @modal-container [:show]) :title (str "data_container " (get-in @modal-container [:param-str]))
:on-ok #(reset! modal-container {:show false :param-str ""})
:on-cancel #(reset! modal-container {:show false :param-str ""})}
(let [container-meta (data-container-meta-only (get-in @app-state [:data-containers (get-in @modal-container [:param-str])]))
pretty-str (js/JSON.stringify (clj->js container-meta) js/undefined 2)]
;(console.log (clj->js pretty-str))
(reagent/as-element [:div {:dangerouslySetInnerHTML {:__html (str "<pre>" (string/replace pretty-str #"\n" "<br />") "</pre>")}}]))]))
(defn page []
[:div
[:h1 "Data explorer"]
[editor]
;[list-data-contianers]
[:div.colorplot-container
[colorplot-component 0]
[colorplot-component 1]]
[:div.colorplot-container
[colorplot-component 2]
[colorplot-component 3]]
[:div {:id "tree-tooltip"}]
[display-modal-info]
[display-modal-container]
[:br]])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Initialize App
; (defn dev-setup []
; (when ^boolean js/goog.DEBUG
; (enable-console-print!)
; (println "dev mode")))
(enable-console-print!)
(defn reload []
(reagent/render [page]
(.getElementById js/document "app")))
(defn ^:export main []
;(dev-setup)
(reload))
| 58299 | (ns weblarda3.explorer
(:require
[reagent.core :as reagent]
[cljs.core.async :as async]
[cljs-http.client :as http]
[ajax.core :as ajax] ; library making error handling possible
[ajax.protocols :as protocol]
[antizer.reagent :as ant]
[clojure.string :as string]
[clojure.set :as set]
[goog.iter]
[weblarda3.vis :as vis]
[cljsjs.msgpack-lite :as msgpack]
[weblarda3.vis :as vis]
[weblarda3.colorplot :as cplot]))
;
;
; link for the data api
; http://larda.tropos.de/larda3/api/lacros_dacapo/POLLY/attbsc1064?rformat=json&interval=1549238460.0-1549396800.0%2C0-8000
; rformat = {bin|msgpack|json}
;
; for the explorer
; http://larda.tropos.de/larda3/explorer/lacros_dacapo/
; http://localhost:3449/explorer.html?interval=1549385800.0-1549396800.0%2C0-8000¶ms=CLOUDNET|WIDTH
; http://localhost:3449/explorer.html?interval=1549385800.0-1549396800.0%2C0-8000¶ms=POLLYNET|attbsc1064
; http://localhost:3449/explorer.html?interval=1549385800.0-1549396800.0%2C0-8000¶ms=CLOUDNET|Z
; http://larda.tropos.de/larda3/explorer/lacros_dacapo?interval=1549385800.0-1549396800.0,0-8000¶ms=CLOUDNET|Z,CLOUDNET|LDR,CLOUDNET_LIMRAD|Z,POLLYNET|attbsc1064
; http://larda.tropos.de/larda3/explorer/lacros_dacapo?interval=1549385800.0-1549396800.0,0-8000¶ms=CLOUDNET|Z,CLOUDNET|LDR,CLOUDNET_LIMRAD|Z,POLLYNET|attbsc1064,SHAUN|VEL
; TODO
; - update link on changes
; - info panel
; - categorial colormaps
; - more agressive compiler options
(println "search" (.. js/window -location -search))
(println "href" (.. js/window -location -href))
; dev or hard coded
;(defonce host "http://larda.tropos.de/larda3/")
;(defonce host "http://larda3.tropos.de/")
;get from index.html <script> tag
;(defonce host js/hostaddr)
(defonce host (second (re-find #"(.+)explorer" js/hostaddr)))
(println "set host " host)
(defn keys-to-str [list]
(goog.iter/join (clj->js (map name list)) "|"))
(defn paramstr-to-vec [param_string]
(string/split param_string #"\|"))
(defonce app-state
(reagent/atom {:coll1-vis true
:c-list []
:c-selected "mosaic"
:c-info {}
:sel-time-range {"ts" [(-> (js/moment) (.utc) (.subtract 4 "hours") (.format "X"))
(-> (js/moment) (.utc) (.format "X"))]
"rg" [0 12000]}
:data-containers {}
:mapping-container-plot {}
:data-loading-progress false
;:colorplotProps {:outerSize {:w 800 :h 450} :imageSize {:w 685 :h 400}}
:colorplotProps {:outerSize {:w 750 :h 450} :imageSize {:w 635 :h 400}}}))
(defonce modal-container (reagent/atom {:show false
:param-str ""}))
(defonce modal-info (reagent/atom {:show false
:title ""
:content "loading.."}))
(defn fetch-description [param_string]
(let [c-name (get-in @app-state [:c-selected])
system (first (string/split param_string #"\|"))
param (second (string/split param_string #"\|"))]
(println "request string" (str host "description/" c-name "/" system "/" param))
(swap! modal-info assoc-in [:title] (str system ": " param))
(async/go (let [response (async/<! (http/get (str host "description/" c-name "/" system "/" param) {:as :raw :with-credentials? false}))]
;(println "retrieved" (:status response) (:body response))
(println "fetched new description string " c-name system param (:status response))
(swap! modal-info assoc-in [:content] (get-in response [:body]))))))
(def colorplotProps-cursor (reagent/cursor app-state [:colorplotProps]))
(def data-containers-cursor (reagent/cursor app-state [:data-containers]))
(def cplot-click (async/chan))
(defn get-permalink []
; ?interval=1549385800.0-1549396800.0%2C0-8000¶ms=CLOUDNET|WIDTH
(let [ts-interval (string/join "-" (get-in @app-state [:sel-time-range "ts"]))
rg-interval (string/join "-" (get-in @app-state [:sel-time-range "rg"]))
interval (str ts-interval "," rg-interval)
params (string/join "," (keys (get-in @app-state [:data-containers])))]
(str host "explorer/" (get @app-state :c-selected) "?interval=" interval "¶ms=" params)))
(defn parse-number-nan [str]
(if (and (> (count str) 0) (not (js/isNaN (js/parseFloat str))))
(js/parseFloat str)
nil))
(defn data-container-extract-meta [data-container]
(let [meta data-container
var (goog.object/get data-container "var")
mask (goog.object/get data-container "mask")
ts (goog.object/get data-container "ts")
rg (goog.object/get data-container "rg")
varconverter (case (goog.object/get data-container"plot_varconverter")
"lin2z" "dB"
(goog.object/get data-container"plot_varconverter"))]
(println "extract-meta:" varconverter)
(js-delete meta "var")
(js-delete meta "mask")
(js-delete meta "ts")
(js-delete meta "rg")
(assoc (js->clj meta)
"plot_varconverter" varconverter
"var" var "mask" mask
"ts" ts "rg" rg)))
(defn hex-comma-and-split [str]
(if str
(string/split (string/replace str #"%2C" ",") #",") []))
(defn infer-time-format [str]
(if (string/includes? str "_")
(case (count str)
11 (.format (js/moment.utc str "YYYYMMDD_HH") "X")
13 (.format (js/moment.utc str "YYYYMMDD_HHmm") "X")
15 (.format (js/moment.utc str "YYYYMMDD_HHmmss") "X"))
str))
(defn interval-to-dict [interval]
(case (count interval)
0 {"ts" [(-> (js/moment) (.utc) (.subtract 4 "hours") (.format "X"))
(-> (js/moment) (.utc) (.format "X"))]
"rg" [0 12000]}
1 {"ts" (mapv infer-time-format (string/split (first interval) #"-"))
"rg" [0 12000]}
2 {"ts" (mapv infer-time-format (string/split (first interval) #"-"))
"rg" (mapv js/parseFloat (string/split (second interval) #"-"))}))
(defn empty-places [dict places]
(vec (set/difference (set places) (set (keys dict)))))
(defn update-plots []
(println "update plots" (get-in @app-state [:mapping-container-plot]))
;(println (keys @data-containers-cursor))
(doall (for [k [0 1 2 3]]
(do (-> (js/d3.select (str "#cp-" k " svg")) (.selectAll "*") (.remove))
(-> (js/d3.select (str "#cp-" k " canvas")) (.node) (.getContext "2d")
(.clearRect 0 0 (get-in @colorplotProps-cursor [:outerSize :w]) (get-in @colorplotProps-cursor [:outerSize :h]))))))
(doall (for [[k v] (get-in @app-state [:mapping-container-plot])]
(do ;(println "update " k v)
;(cplot/colorplot-did-mount colorplotProps-cursor k data-containers-cursor v cplot-click)
(cplot/plot-dispatch colorplotProps-cursor k data-containers-cursor v cplot-click)))))
(defn http-error-handler [uri]
(fn [{:keys [status status-text response]}]
(ant/notification-error {:message (str "Error " status) :duration 0 :description (str "while fetching data " status-text)})
(.log js/console (str "Error occured: " status)
; new TextDecoder ("utf-8") .decode (uint8array)
status-text uri (.decode (js/TextDecoder. "utf-8") response))))
(defn custom-http-get [uri]
(let [channel (async/chan)]
(async/go
(ajax/GET uri
{:with-credentials false
:response-format {:content-type "application/msgpack" :description "data conainer msgpack" :read protocol/-body :type :arraybuffer}
:handler #(async/put! channel %)
:error-handler (http-error-handler uri)}))
channel))
(defn fetch-data [c-name param_string time-interval range-interval]
(let [sys_param (paramstr-to-vec param_string)
url (str host "api/" c-name "/" (first sys_param) "/" (second sys_param) "?rformat=msgpack&interval="
(first time-interval) "-" (last time-interval) "%2C" (first range-interval) "-" (last range-interval))]
(js/console.log "fetch data larda url: " url)
(swap! app-state assoc-in [:data-loading-progress] true)
(ant/notification-open {:message (str "retrieving data from larda") :duration 0 :key "<KEY>"})
; (async/go
; (let [response (async/<! (custom-http-get url))]
; (println response)
; ;(println (msgpack.decode response))
; (println (msgpack.decode (new js/Uint8Array response)))))
;(async/go (let [response (async/<! (http/get url {:response-type :array-buffer :with-credentials? false}))]
(async/go (let [response (async/<! (custom-http-get url))]
(println "fetched data " c-name param_string time-interval range-interval)
(let [decoded (msgpack.decode (new js/Uint8Array response))
mapping-container-plot (get @app-state :mapping-container-plot)
empty-plot (first (empty-places mapping-container-plot [0 1 2 3]))]
;(goog.object/set decoded "var" (c/pull_loc_in decoded))
;(println (type (:body response)) (:body response))
;(js/console.log (type (:body response)) (:body response))
;(js/console.log response (new js/Uint8Array (:body response)))
;(js/console.log "decoded data" decoded)
;(js/console.log "decoded data" (msgpack.decode (new js/Uint8Array (:body response))))
;(swap! app-state assoc-in [:alltrees] decoded)
;(reset! alltrees-cursor decoded)
(swap! app-state assoc-in [:data-containers param_string] (data-container-extract-meta decoded))
(swap! app-state assoc-in [:backend :data-loading-progress] false)
; TODO more sophisticated version required here
(if-not (or (nil? empty-plot) (some #(= param_string %) (vals mapping-container-plot)))
(swap! app-state assoc-in [:mapping-container-plot empty-plot] param_string))
(ant/notification-close "retData")
(update-plots)
(println "data loading done; mapping " mapping-container-plot (get @app-state :mapping-container-plot)))))))
; extract from query string
(defn extract-from-address [address]
(let [href (.. address -href)
;href "http://larda.tropos.de/larda3/explorer/lacros_dacapo/"
;href "http://larda3.tropos.de/explorer/lacros_cycare/"
c-name (last (string/split (first (string/split href #"\?")) #"/"))
query-string (.. address -search)
;query-string "?rformat=json&interval=1549238460.0-1549396800.0%2C0-8000¶ms=CLOUDNET_LIMRAD|VEL"
;query-string "?rformat=json&interval=1549385800.0-1549396800.0%2C0-8000¶ms=CLOUDNET_LIMRAD|VEL,CLOUDNET|CLASS"
; 19951231_235959
;query-string "?rformat=json&interval=1549238460.0-1549396800.0"
;query-string "?rformat=json&interval=19951231_23-19951231_235959"
interval (hex-comma-and-split (second (re-find #"interval=([^&]*)" query-string)))
sel-time-range (interval-to-dict interval)
params (hex-comma-and-split (second (re-find #"params=([^&]*)" query-string)))]
;define default values for interval
(println "extract from address" href query-string)
(println (string/split (first (string/split href #"\?")) #"/") "=> " c-name)
(println "interval" interval (count interval) sel-time-range) (println "params" params)
(swap! app-state assoc-in [:c-selected] c-name)
(if (> (count interval) 0)
(swap! app-state assoc-in [:sel-time-range] sel-time-range))
(doall (for [param params]
(fetch-data (get @app-state :c-selected) param (get-in @app-state [:sel-time-range "ts"]) (get-in @app-state [:sel-time-range "rg"]))))))
;query-string (second (re-find #"camp=([^&]*)" (.. js/window -location -search)))
(extract-from-address (.. js/window -location))
; get the paramaeter list...
(defn fetch-c-info [c-name & [additional-atom]]
(ant/notification-open {:message "loading data availability " :description c-name :duration 0 :key "retData"})
(swap! app-state assoc-in [:param-sel] [])
(async/go (let [response (async/<! (http/get (str host "api/" c-name "/") {:as :json :with-credentials? false}))]
;(println (:status response) (:body response))
(println "fetched new c-info for " c-name (:status response))
(ant/notification-close "retData")
(if-not (= (:status response) 200)
(do (println "response " response)
(ant/notification-error {:message "Error" :duration 0 :description "while fetching campaign info"})))
;(ant/notification-info {:message "Hint" :description "right-click on parameter to display description text" :duration 20})
;(set-initial-selection (get-in response [:body]))
(let [duration (get-in response [:body :config_file :duration])
last (last (last duration))
timestart (.format (js/moment.utc last "YYYYMMDD") "X")
timeend (str (+ (js/parseFloat timestart) (* 6 3600)))]
(if-not (nil? additional-atom)
(do (swap! additional-atom assoc-in ["ts"] [timestart timeend])
(swap! app-state assoc-in [:sel-time-range "ts"] [timestart timeend]))))
(swap! app-state assoc-in [:c-info] (get-in response [:body])))))
; replace camp by /camp/
(async/go (let [response (async/<! (http/get (str host "api/") {:as :json :with-credentials? false}))
query-string (second (re-find #"camp=([^&]*)" (.. js/window -location -search)))]
;(println "found string " query-string (get-in response [:body :campaign_list]))
(if-not (= (:status response) 200)
(do (println "response " response)
(ant/notification-error {:message "Error" :duration 0 :description (str "while fetching basic info " host)})))
(if-not (some #{(get-in @app-state [:c-selected])} (get-in response [:body :campaign_list]))
(swap! app-state assoc-in [:c-selected] (first (get-in response [:body :campaign_list]))))
(if (and (not (nil? query-string)) (some #{query-string} (get-in response [:body :campaign_list])))
(swap! app-state assoc-in [:c-selected] query-string))
; at first check if Query_String provided campaign
(println "fetch campaign list" (:status response) (:body response))
(fetch-c-info (get @app-state :c-selected))
(swap! app-state assoc-in [:c-list] (get-in response [:body :campaign_list]))))
(defn change-campaign [& [additional-atom]]
(fn [c-name]
;this is to update the link
;(let [query-string (.. js/window -location -search)]
; (if (count query-string)
; (js/window.history.replaceState (clj->js nil) (clj->js nil) (string/replace query-string #"camp=([^&]*)" (str "camp=" c-name)))))
(swap! app-state assoc-in [:c-selected] (js->clj c-name))
(swap! app-state assoc-in [:data-containers] {})
(swap! app-state assoc-in [:mapping-container-plot] {})
(update-plots)
(fetch-c-info c-name additional-atom)))
(defn update-time-range [args]
; update app-state
; download for all the present parameters
(swap! app-state assoc-in [:sel-time-range] args)
;when time is updated we need to upddate the data as well
(let [params (vec (keys (get-in @app-state [:data-containers])))]
(println "update params " params)
(swap! app-state assoc-in [:data-containers] {})
(doall (map #(fetch-data (get @app-state :c-selected) % (get-in @app-state [:sel-time-range "ts"]) (get-in @app-state [:sel-time-range "rg"])) params)))
; (doall (for [param params]
; (do (println "update time range" param)
; (fetch-data (get @app-state :c-selected) param
; (get-in @app-state [:sel-time-range "ts"]) (get-in @app-state [:sel-time-range "rg"]))))))
(println "update time range " args))
(defn add-param [param]
;#(reset! panel1-param (js->clj %))
; download
(fetch-data (get @app-state :c-selected) param (get-in @app-state [:sel-time-range "ts"]) (get-in @app-state [:sel-time-range "rg"]))
(console.log "add param " param))
(defn delete-container [param_string]
(fn [] (println param_string (keys (get @app-state :data-containers)))
(swap! app-state assoc-in [:data-containers] (dissoc (get @app-state :data-containers) param_string))
(let [map-cont-plot (get-in @app-state [:mapping-container-plot])
filtered (into {} (filter (fn [[k v]] (not= param_string v)) map-cont-plot))]
(println "filtered " filtered)
(swap! app-state assoc-in [:mapping-container-plot] filtered))
(println "new mapping " (get-in @app-state [:mapping-container-plot]))
(update-plots)))
(defn entry-in-list []
(fn [data-containers k v]
;(js/console.log entry)
;(js/console.log "operator " (get entry "operator") (type (get entry "operator")))
;(js/console.log "ndfilters " (get-in entry ["ndfilters"]))
; (println "id?" (get entry "time") (get entry "id"))
[:tr
[:td k]
[:td [:select {:on-change (fn [e] ;(println (.. e -target -value) (get-in @data-containers [k "colormap"]))
(swap! data-containers assoc-in [k "colormap"] (.. e -target -value)))
:value (get-in @data-containers [k "colormap"])}
(for [cmap (js->clj (js/colormaps.available))]
^{:key cmap} [:option {:value cmap} cmap])]]
[:td [:select {:on-change (fn [e] ;(println (.. e -target -value) (get-in @data-containers [k "colormap"]))
(swap! data-containers assoc-in [k "plot_varconverter"] (.. e -target -value)))
:value (get-in @data-containers [k "plot_varconverter"])}
(for [cmap cplot/avail-var-converters]
^{:key cmap} [:option {:value cmap} cmap])]]
[:td [ant/input {:size "small" :style {:margin-left "0px" :margin-top "0px" :width "65px" :text-align "right"}
:default-value (get-in @data-containers [k "var_lims" 0])
:onChange #(swap! data-containers assoc-in [k "var_lims" 0] (js->clj (.. % -target -value)))}]
" - "
[ant/input {:size "small" :style {:margin-left "0px" :margin-top "0px" :width "65px" :text-align "right"}
:default-value (get-in @data-containers [k "var_lims" 1])
:onChange #(swap! data-containers assoc-in [k "var_lims" 1] (js->clj (.. % -target -value)))}]]
[:td [ant/button {:on-click #((swap! modal-container assoc-in [:param-str] k) (swap! modal-container update-in [:show] not)) :size "small" :icon "bars"}]]
[:td [ant/button {:on-click #((swap! modal-info update-in [:show] not) (fetch-description k)) :size "small" :icon "info-circle"}]]
[:td [ant/button {:on-click (delete-container k) :size "small" :type "danger"} "x"]]]))
(defn editor-container-list [app-state]
(let [data-containers (reagent/atom (get @app-state :data-containers))]
(fn []
(if-not (= (set (keys @data-containers)) (set (keys (get @app-state :data-containers))))
(do (reset! data-containers (get @app-state :data-containers)) (println "made editor data containers consistent")))
[:div
[:table#editorleft
[:thead [:tr [:th "Parameter"] [:th "Colormap"] [:th "Scale"] [:th "Limits"] [:th ""] [:th "Descr."]]]
[:tbody (for [[k v] (get @app-state :data-containers)] ^{:key k} [entry-in-list data-containers k v])]]
[ant/button {:on-click #((swap! app-state assoc-in [:data-containers] @data-containers) (update-plots))
:size "small"} "update plots"]
[:br][:br]
"container - plot - mapping"
[:table#editorleft
[:tbody (doall (for [v [0 1 2 3]] ^{:key v} [:tr
[:td (str "Plot " v)]
[:td [:select {:on-change (fn [e] ;(println (.. e -target -value) (get-in @data-containers [k "colormap"]))
(swap! app-state assoc-in [:mapping-container-plot v] (.. e -target -value))
(update-plots))
:value (get-in @app-state [:mapping-container-plot v])}
(doall (for [params (conj (keys (get @app-state :data-containers)) "")]
^{:key params} [:option {:value params} params]))]]]))]]])))
(defn update-time-by [atm idx-old idx-new amount]
(let [value (js/parseFloat (get-in @atm ["ts" idx-old]))
new (+ value amount)]
;(println "update time " value new)
(swap! atm assoc-in ["ts" idx-new] (str new))))
(defn disabled-date? [current]
(let [duration (get-in @app-state [:c-info :config_file :duration])
testfn (fn [pair current] (and (> current (js/moment.utc (first pair) "YYYYMMDD"))
(< current (.add (js/moment.utc (second pair) "YYYYMMDD") 1 "days"))))
in-one? (mapv #(testfn % current) duration)]
(not (some true? in-one?))))
(defn editor []
(let [panel1-time-range (reagent/atom (get @app-state :sel-time-range))
panel1-param (reagent/atom "select")
check-valid (fn [] (and (< (int (get-in @panel1-time-range ["ts" 0])) (int (get-in @panel1-time-range ["ts" 1])))
(< (- (int (get-in @panel1-time-range ["ts" 1])) (int (get-in @panel1-time-range ["ts" 0]))) 86400)
(< (int (get-in @panel1-time-range ["rg" 0])) (int (get-in @panel1-time-range ["rg" 1])))))]
(fn []
[:div#editor {:style {:min-width "600px" :width "700px" :margin-left "30px"}}
[ant/collapse
[ant/collapse-panel {:header "Time, Range, Parameter" :key "1"}
[ant/row
[ant/col {:span 12}
[:table#editorleft
[:thead]
[:tbody
[:tr [:td "Begin"]
[:td [ant/date-picker {:format "YYYYMMDD_HHmm" :value (.utc (js/moment.unix (get-in @panel1-time-range ["ts" 0])))
:disabled-date disabled-date?
:on-change (fn [_ d] (swap! panel1-time-range assoc-in ["ts" 0] (.format (js/moment.utc d "YYYYMMDD_HHmm") "X")))
:style {:width "100%"} :show-today false :size "small"
:showTime {:use12Hours false :format "HH:mm"}}]
[:br]
[:span.clickable {:on-click #(update-time-by panel1-time-range 0 0 -3600)} "-1h"]
[:span.clickable {:on-click #(update-time-by panel1-time-range 0 0 -600)} "-10min"]
[:span.clickable {:on-click #(update-time-by panel1-time-range 0 0 600)} "+10min"]
[:span.clickable {:on-click #(update-time-by panel1-time-range 0 0 3600)} "+1h"]]]
[:tr [:td "End"]
[:td [ant/date-picker {:format "YYYYMMDD_HHmm" :value (.utc (js/moment.unix (get-in @panel1-time-range ["ts" 1])))
:disabled-date disabled-date?
:on-change (fn [_ d] (swap! panel1-time-range assoc-in ["ts" 1] (.format (js/moment.utc d "YYYYMMDD_HHmm") "X")))
:style {:width "100%"} :show-today false :size "small"
:showTime {:use12Hours false :format "HH:mm"}}]
[:br]
[:span.clickable {:on-click #(update-time-by panel1-time-range 1 1 -3600)} "-1h"]
[:span.clickable {:on-click #(update-time-by panel1-time-range 1 1 -600)} "-10min"]
[:span.clickable {:on-click #(update-time-by panel1-time-range 1 1 600)} "+10min"]
[:span.clickable {:on-click #(update-time-by panel1-time-range 1 1 3600)} "+1h"]
[:span.clickable {:on-click #(update-time-by panel1-time-range 0 1 14400)} "Begin +4h"]]]
[:tr [:td "Range"] [:td [ant/input {:size "small" :style {:margin-left "6px" :margin-top "5px" :width "70px" :text-align "right"}
:default-value (get-in @panel1-time-range ["rg" 0])
:onChange #(swap! panel1-time-range assoc-in ["rg" 0] (js->clj (.. % -target -value)))}]
" - "
[ant/input {:size "small" :style {:margin-left "6px" :margin-top "5px" :width "70px" :text-align "right"}
:default-value (get-in @panel1-time-range ["rg" 1])
:onChange #(swap! panel1-time-range assoc-in ["rg" 1] (js->clj (.. % -target -value)))}]]]
[:tr]]] [ant/button {:on-click #(update-time-range @panel1-time-range)
:disabled (not (check-valid))
:size "small"} "update"]]
[ant/col {:span 12}
[:table#editorleft
[:thead]
[:tbody
[:tr [:td "Campaign"] [:td [ant/select {:showSearch true
:placeholder "select campaign"
:value (get-in @app-state [:c-selected])
:onChange (change-campaign panel1-time-range)
:style {:width "150px"} :size "small"}
(for [c-name (get-in @app-state [:c-list])] ^{:key c-name} [ant/select-option {:value c-name} c-name])]]]
[:tr [:td "Add Parameter"]
[:td
[ant/tree-select {:value @panel1-param :size "small"
:placeholder "Please select" :showSearch true
:onChange (fn [param] (reset! panel1-param (js->clj param)) (add-param (js->clj param)))}
(doall (for [system (sort (keys (get-in @app-state [:c-info :connectors])))]
^{:key system} [ant/tree-tree-node {:title system :selectable false :style {:font-size 11}}
(for [param (sort (keys (get-in @app-state [:c-info :connectors (keyword system) :params])))]
^{:key (keys-to-str [system param])} [ant/tree-tree-node
{:value (keys-to-str [system param])
:title (keys-to-str [system param])}])]))]]]]]]
(if (> (int (get-in @panel1-time-range ["ts" 0])) (int (get-in @panel1-time-range ["ts" 1]))) [:p.er "Time: begin > end"])
(if (> (- (int (get-in @panel1-time-range ["ts" 1])) (int (get-in @panel1-time-range ["ts" 0]))) 86400) [:p.er "Time: too long"])
;(if (< (count (get @panel1-data :sel-camp)) 1) [:p.er "Select campaign"])
(if (> (int (get-in @panel1-time-range ["rg" 0])) (int (get-in @panel1-time-range ["rg" 1]))) [:p.er "Range: top > bottom"])
[ant/col {:span 24} [:br] [:div [ant/button {:on-click #(js/custom.copy_string (get-permalink)) :size "small"} "copy permalink"]
[:span.permalink (get-permalink)]]]]]]
[ant/collapse
[ant/collapse-panel {:header "Plot properties" :key "1"}
[editor-container-list app-state]]]])))
; (defn list-data-contianers []
; [:div#rightfloat (doall (for [data-cont (keys (get-in @app-state [:data-containers]))] ^{:key data-cont} [:div data-cont [:br]]))])
(defn colorplot-component [id]
(reagent/create-class
{:reagent-render #(cplot/colorplot-render colorplotProps-cursor id)
:component-did-mount #(cplot/plot-dispatch colorplotProps-cursor id data-containers-cursor (get-in @app-state [:mapping-container-plot id]) cplot-click)
:component-did-update #(cplot/plot-dispatch colorplotProps-cursor id data-containers-cursor (get-in @app-state [:mapping-container-plot id]) cplot-click)}))
(defn display-modal-info []
(fn []
[ant/modal {:visible (get-in @modal-info [:show]) :title (str "Description " (get-in @modal-info [:title]))
:on-ok #(reset! modal-info {:show false :title "" :content "loading..."})
:on-cancel #(reset! modal-info {:show false :title "" :content "loading..."})}
(reagent/as-element [:div {:dangerouslySetInnerHTML {:__html (string/replace (get-in @modal-info [:content]) #"\n" "<br />")}}])]))
(defn data-container-meta-only [data-container]
(let [new (dissoc data-container "var" "mask" "ts" "rg")
ts (get data-container "ts")
rg (get data-container "rg")]
(assoc new
"ts" [(first ts) (last ts)] "rg" [(first rg) (last rg)])))
(defn pretty-container [data-container]
(with-out-str (cljs.pprint/pprint data-container)))
(defn display-modal-container []
(fn []
[ant/modal {:visible (get-in @modal-container [:show]) :title (str "data_container " (get-in @modal-container [:param-str]))
:on-ok #(reset! modal-container {:show false :param-str ""})
:on-cancel #(reset! modal-container {:show false :param-str ""})}
(let [container-meta (data-container-meta-only (get-in @app-state [:data-containers (get-in @modal-container [:param-str])]))
pretty-str (js/JSON.stringify (clj->js container-meta) js/undefined 2)]
;(console.log (clj->js pretty-str))
(reagent/as-element [:div {:dangerouslySetInnerHTML {:__html (str "<pre>" (string/replace pretty-str #"\n" "<br />") "</pre>")}}]))]))
(defn page []
[:div
[:h1 "Data explorer"]
[editor]
;[list-data-contianers]
[:div.colorplot-container
[colorplot-component 0]
[colorplot-component 1]]
[:div.colorplot-container
[colorplot-component 2]
[colorplot-component 3]]
[:div {:id "tree-tooltip"}]
[display-modal-info]
[display-modal-container]
[:br]])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Initialize App
; (defn dev-setup []
; (when ^boolean js/goog.DEBUG
; (enable-console-print!)
; (println "dev mode")))
(enable-console-print!)
(defn reload []
(reagent/render [page]
(.getElementById js/document "app")))
(defn ^:export main []
;(dev-setup)
(reload))
| true | (ns weblarda3.explorer
(:require
[reagent.core :as reagent]
[cljs.core.async :as async]
[cljs-http.client :as http]
[ajax.core :as ajax] ; library making error handling possible
[ajax.protocols :as protocol]
[antizer.reagent :as ant]
[clojure.string :as string]
[clojure.set :as set]
[goog.iter]
[weblarda3.vis :as vis]
[cljsjs.msgpack-lite :as msgpack]
[weblarda3.vis :as vis]
[weblarda3.colorplot :as cplot]))
;
;
; link for the data api
; http://larda.tropos.de/larda3/api/lacros_dacapo/POLLY/attbsc1064?rformat=json&interval=1549238460.0-1549396800.0%2C0-8000
; rformat = {bin|msgpack|json}
;
; for the explorer
; http://larda.tropos.de/larda3/explorer/lacros_dacapo/
; http://localhost:3449/explorer.html?interval=1549385800.0-1549396800.0%2C0-8000¶ms=CLOUDNET|WIDTH
; http://localhost:3449/explorer.html?interval=1549385800.0-1549396800.0%2C0-8000¶ms=POLLYNET|attbsc1064
; http://localhost:3449/explorer.html?interval=1549385800.0-1549396800.0%2C0-8000¶ms=CLOUDNET|Z
; http://larda.tropos.de/larda3/explorer/lacros_dacapo?interval=1549385800.0-1549396800.0,0-8000¶ms=CLOUDNET|Z,CLOUDNET|LDR,CLOUDNET_LIMRAD|Z,POLLYNET|attbsc1064
; http://larda.tropos.de/larda3/explorer/lacros_dacapo?interval=1549385800.0-1549396800.0,0-8000¶ms=CLOUDNET|Z,CLOUDNET|LDR,CLOUDNET_LIMRAD|Z,POLLYNET|attbsc1064,SHAUN|VEL
; TODO
; - update link on changes
; - info panel
; - categorial colormaps
; - more agressive compiler options
(println "search" (.. js/window -location -search))
(println "href" (.. js/window -location -href))
; dev or hard coded
;(defonce host "http://larda.tropos.de/larda3/")
;(defonce host "http://larda3.tropos.de/")
;get from index.html <script> tag
;(defonce host js/hostaddr)
(defonce host (second (re-find #"(.+)explorer" js/hostaddr)))
(println "set host " host)
(defn keys-to-str [list]
(goog.iter/join (clj->js (map name list)) "|"))
(defn paramstr-to-vec [param_string]
(string/split param_string #"\|"))
(defonce app-state
(reagent/atom {:coll1-vis true
:c-list []
:c-selected "mosaic"
:c-info {}
:sel-time-range {"ts" [(-> (js/moment) (.utc) (.subtract 4 "hours") (.format "X"))
(-> (js/moment) (.utc) (.format "X"))]
"rg" [0 12000]}
:data-containers {}
:mapping-container-plot {}
:data-loading-progress false
;:colorplotProps {:outerSize {:w 800 :h 450} :imageSize {:w 685 :h 400}}
:colorplotProps {:outerSize {:w 750 :h 450} :imageSize {:w 635 :h 400}}}))
(defonce modal-container (reagent/atom {:show false
:param-str ""}))
(defonce modal-info (reagent/atom {:show false
:title ""
:content "loading.."}))
(defn fetch-description [param_string]
(let [c-name (get-in @app-state [:c-selected])
system (first (string/split param_string #"\|"))
param (second (string/split param_string #"\|"))]
(println "request string" (str host "description/" c-name "/" system "/" param))
(swap! modal-info assoc-in [:title] (str system ": " param))
(async/go (let [response (async/<! (http/get (str host "description/" c-name "/" system "/" param) {:as :raw :with-credentials? false}))]
;(println "retrieved" (:status response) (:body response))
(println "fetched new description string " c-name system param (:status response))
(swap! modal-info assoc-in [:content] (get-in response [:body]))))))
(def colorplotProps-cursor (reagent/cursor app-state [:colorplotProps]))
(def data-containers-cursor (reagent/cursor app-state [:data-containers]))
(def cplot-click (async/chan))
(defn get-permalink []
; ?interval=1549385800.0-1549396800.0%2C0-8000¶ms=CLOUDNET|WIDTH
(let [ts-interval (string/join "-" (get-in @app-state [:sel-time-range "ts"]))
rg-interval (string/join "-" (get-in @app-state [:sel-time-range "rg"]))
interval (str ts-interval "," rg-interval)
params (string/join "," (keys (get-in @app-state [:data-containers])))]
(str host "explorer/" (get @app-state :c-selected) "?interval=" interval "¶ms=" params)))
(defn parse-number-nan [str]
(if (and (> (count str) 0) (not (js/isNaN (js/parseFloat str))))
(js/parseFloat str)
nil))
(defn data-container-extract-meta [data-container]
(let [meta data-container
var (goog.object/get data-container "var")
mask (goog.object/get data-container "mask")
ts (goog.object/get data-container "ts")
rg (goog.object/get data-container "rg")
varconverter (case (goog.object/get data-container"plot_varconverter")
"lin2z" "dB"
(goog.object/get data-container"plot_varconverter"))]
(println "extract-meta:" varconverter)
(js-delete meta "var")
(js-delete meta "mask")
(js-delete meta "ts")
(js-delete meta "rg")
(assoc (js->clj meta)
"plot_varconverter" varconverter
"var" var "mask" mask
"ts" ts "rg" rg)))
(defn hex-comma-and-split [str]
(if str
(string/split (string/replace str #"%2C" ",") #",") []))
(defn infer-time-format [str]
(if (string/includes? str "_")
(case (count str)
11 (.format (js/moment.utc str "YYYYMMDD_HH") "X")
13 (.format (js/moment.utc str "YYYYMMDD_HHmm") "X")
15 (.format (js/moment.utc str "YYYYMMDD_HHmmss") "X"))
str))
(defn interval-to-dict [interval]
(case (count interval)
0 {"ts" [(-> (js/moment) (.utc) (.subtract 4 "hours") (.format "X"))
(-> (js/moment) (.utc) (.format "X"))]
"rg" [0 12000]}
1 {"ts" (mapv infer-time-format (string/split (first interval) #"-"))
"rg" [0 12000]}
2 {"ts" (mapv infer-time-format (string/split (first interval) #"-"))
"rg" (mapv js/parseFloat (string/split (second interval) #"-"))}))
(defn empty-places [dict places]
(vec (set/difference (set places) (set (keys dict)))))
(defn update-plots []
(println "update plots" (get-in @app-state [:mapping-container-plot]))
;(println (keys @data-containers-cursor))
(doall (for [k [0 1 2 3]]
(do (-> (js/d3.select (str "#cp-" k " svg")) (.selectAll "*") (.remove))
(-> (js/d3.select (str "#cp-" k " canvas")) (.node) (.getContext "2d")
(.clearRect 0 0 (get-in @colorplotProps-cursor [:outerSize :w]) (get-in @colorplotProps-cursor [:outerSize :h]))))))
(doall (for [[k v] (get-in @app-state [:mapping-container-plot])]
(do ;(println "update " k v)
;(cplot/colorplot-did-mount colorplotProps-cursor k data-containers-cursor v cplot-click)
(cplot/plot-dispatch colorplotProps-cursor k data-containers-cursor v cplot-click)))))
(defn http-error-handler [uri]
(fn [{:keys [status status-text response]}]
(ant/notification-error {:message (str "Error " status) :duration 0 :description (str "while fetching data " status-text)})
(.log js/console (str "Error occured: " status)
; new TextDecoder ("utf-8") .decode (uint8array)
status-text uri (.decode (js/TextDecoder. "utf-8") response))))
(defn custom-http-get [uri]
(let [channel (async/chan)]
(async/go
(ajax/GET uri
{:with-credentials false
:response-format {:content-type "application/msgpack" :description "data conainer msgpack" :read protocol/-body :type :arraybuffer}
:handler #(async/put! channel %)
:error-handler (http-error-handler uri)}))
channel))
(defn fetch-data [c-name param_string time-interval range-interval]
(let [sys_param (paramstr-to-vec param_string)
url (str host "api/" c-name "/" (first sys_param) "/" (second sys_param) "?rformat=msgpack&interval="
(first time-interval) "-" (last time-interval) "%2C" (first range-interval) "-" (last range-interval))]
(js/console.log "fetch data larda url: " url)
(swap! app-state assoc-in [:data-loading-progress] true)
(ant/notification-open {:message (str "retrieving data from larda") :duration 0 :key "PI:KEY:<KEY>END_PI"})
; (async/go
; (let [response (async/<! (custom-http-get url))]
; (println response)
; ;(println (msgpack.decode response))
; (println (msgpack.decode (new js/Uint8Array response)))))
;(async/go (let [response (async/<! (http/get url {:response-type :array-buffer :with-credentials? false}))]
(async/go (let [response (async/<! (custom-http-get url))]
(println "fetched data " c-name param_string time-interval range-interval)
(let [decoded (msgpack.decode (new js/Uint8Array response))
mapping-container-plot (get @app-state :mapping-container-plot)
empty-plot (first (empty-places mapping-container-plot [0 1 2 3]))]
;(goog.object/set decoded "var" (c/pull_loc_in decoded))
;(println (type (:body response)) (:body response))
;(js/console.log (type (:body response)) (:body response))
;(js/console.log response (new js/Uint8Array (:body response)))
;(js/console.log "decoded data" decoded)
;(js/console.log "decoded data" (msgpack.decode (new js/Uint8Array (:body response))))
;(swap! app-state assoc-in [:alltrees] decoded)
;(reset! alltrees-cursor decoded)
(swap! app-state assoc-in [:data-containers param_string] (data-container-extract-meta decoded))
(swap! app-state assoc-in [:backend :data-loading-progress] false)
; TODO more sophisticated version required here
(if-not (or (nil? empty-plot) (some #(= param_string %) (vals mapping-container-plot)))
(swap! app-state assoc-in [:mapping-container-plot empty-plot] param_string))
(ant/notification-close "retData")
(update-plots)
(println "data loading done; mapping " mapping-container-plot (get @app-state :mapping-container-plot)))))))
; extract from query string
(defn extract-from-address [address]
(let [href (.. address -href)
;href "http://larda.tropos.de/larda3/explorer/lacros_dacapo/"
;href "http://larda3.tropos.de/explorer/lacros_cycare/"
c-name (last (string/split (first (string/split href #"\?")) #"/"))
query-string (.. address -search)
;query-string "?rformat=json&interval=1549238460.0-1549396800.0%2C0-8000¶ms=CLOUDNET_LIMRAD|VEL"
;query-string "?rformat=json&interval=1549385800.0-1549396800.0%2C0-8000¶ms=CLOUDNET_LIMRAD|VEL,CLOUDNET|CLASS"
; 19951231_235959
;query-string "?rformat=json&interval=1549238460.0-1549396800.0"
;query-string "?rformat=json&interval=19951231_23-19951231_235959"
interval (hex-comma-and-split (second (re-find #"interval=([^&]*)" query-string)))
sel-time-range (interval-to-dict interval)
params (hex-comma-and-split (second (re-find #"params=([^&]*)" query-string)))]
;define default values for interval
(println "extract from address" href query-string)
(println (string/split (first (string/split href #"\?")) #"/") "=> " c-name)
(println "interval" interval (count interval) sel-time-range) (println "params" params)
(swap! app-state assoc-in [:c-selected] c-name)
(if (> (count interval) 0)
(swap! app-state assoc-in [:sel-time-range] sel-time-range))
(doall (for [param params]
(fetch-data (get @app-state :c-selected) param (get-in @app-state [:sel-time-range "ts"]) (get-in @app-state [:sel-time-range "rg"]))))))
;query-string (second (re-find #"camp=([^&]*)" (.. js/window -location -search)))
(extract-from-address (.. js/window -location))
; get the paramaeter list...
(defn fetch-c-info [c-name & [additional-atom]]
(ant/notification-open {:message "loading data availability " :description c-name :duration 0 :key "retData"})
(swap! app-state assoc-in [:param-sel] [])
(async/go (let [response (async/<! (http/get (str host "api/" c-name "/") {:as :json :with-credentials? false}))]
;(println (:status response) (:body response))
(println "fetched new c-info for " c-name (:status response))
(ant/notification-close "retData")
(if-not (= (:status response) 200)
(do (println "response " response)
(ant/notification-error {:message "Error" :duration 0 :description "while fetching campaign info"})))
;(ant/notification-info {:message "Hint" :description "right-click on parameter to display description text" :duration 20})
;(set-initial-selection (get-in response [:body]))
(let [duration (get-in response [:body :config_file :duration])
last (last (last duration))
timestart (.format (js/moment.utc last "YYYYMMDD") "X")
timeend (str (+ (js/parseFloat timestart) (* 6 3600)))]
(if-not (nil? additional-atom)
(do (swap! additional-atom assoc-in ["ts"] [timestart timeend])
(swap! app-state assoc-in [:sel-time-range "ts"] [timestart timeend]))))
(swap! app-state assoc-in [:c-info] (get-in response [:body])))))
; replace camp by /camp/
(async/go (let [response (async/<! (http/get (str host "api/") {:as :json :with-credentials? false}))
query-string (second (re-find #"camp=([^&]*)" (.. js/window -location -search)))]
;(println "found string " query-string (get-in response [:body :campaign_list]))
(if-not (= (:status response) 200)
(do (println "response " response)
(ant/notification-error {:message "Error" :duration 0 :description (str "while fetching basic info " host)})))
(if-not (some #{(get-in @app-state [:c-selected])} (get-in response [:body :campaign_list]))
(swap! app-state assoc-in [:c-selected] (first (get-in response [:body :campaign_list]))))
(if (and (not (nil? query-string)) (some #{query-string} (get-in response [:body :campaign_list])))
(swap! app-state assoc-in [:c-selected] query-string))
; at first check if Query_String provided campaign
(println "fetch campaign list" (:status response) (:body response))
(fetch-c-info (get @app-state :c-selected))
(swap! app-state assoc-in [:c-list] (get-in response [:body :campaign_list]))))
(defn change-campaign [& [additional-atom]]
(fn [c-name]
;this is to update the link
;(let [query-string (.. js/window -location -search)]
; (if (count query-string)
; (js/window.history.replaceState (clj->js nil) (clj->js nil) (string/replace query-string #"camp=([^&]*)" (str "camp=" c-name)))))
(swap! app-state assoc-in [:c-selected] (js->clj c-name))
(swap! app-state assoc-in [:data-containers] {})
(swap! app-state assoc-in [:mapping-container-plot] {})
(update-plots)
(fetch-c-info c-name additional-atom)))
(defn update-time-range [args]
; update app-state
; download for all the present parameters
(swap! app-state assoc-in [:sel-time-range] args)
;when time is updated we need to upddate the data as well
(let [params (vec (keys (get-in @app-state [:data-containers])))]
(println "update params " params)
(swap! app-state assoc-in [:data-containers] {})
(doall (map #(fetch-data (get @app-state :c-selected) % (get-in @app-state [:sel-time-range "ts"]) (get-in @app-state [:sel-time-range "rg"])) params)))
; (doall (for [param params]
; (do (println "update time range" param)
; (fetch-data (get @app-state :c-selected) param
; (get-in @app-state [:sel-time-range "ts"]) (get-in @app-state [:sel-time-range "rg"]))))))
(println "update time range " args))
(defn add-param [param]
;#(reset! panel1-param (js->clj %))
; download
(fetch-data (get @app-state :c-selected) param (get-in @app-state [:sel-time-range "ts"]) (get-in @app-state [:sel-time-range "rg"]))
(console.log "add param " param))
(defn delete-container [param_string]
(fn [] (println param_string (keys (get @app-state :data-containers)))
(swap! app-state assoc-in [:data-containers] (dissoc (get @app-state :data-containers) param_string))
(let [map-cont-plot (get-in @app-state [:mapping-container-plot])
filtered (into {} (filter (fn [[k v]] (not= param_string v)) map-cont-plot))]
(println "filtered " filtered)
(swap! app-state assoc-in [:mapping-container-plot] filtered))
(println "new mapping " (get-in @app-state [:mapping-container-plot]))
(update-plots)))
(defn entry-in-list []
(fn [data-containers k v]
;(js/console.log entry)
;(js/console.log "operator " (get entry "operator") (type (get entry "operator")))
;(js/console.log "ndfilters " (get-in entry ["ndfilters"]))
; (println "id?" (get entry "time") (get entry "id"))
[:tr
[:td k]
[:td [:select {:on-change (fn [e] ;(println (.. e -target -value) (get-in @data-containers [k "colormap"]))
(swap! data-containers assoc-in [k "colormap"] (.. e -target -value)))
:value (get-in @data-containers [k "colormap"])}
(for [cmap (js->clj (js/colormaps.available))]
^{:key cmap} [:option {:value cmap} cmap])]]
[:td [:select {:on-change (fn [e] ;(println (.. e -target -value) (get-in @data-containers [k "colormap"]))
(swap! data-containers assoc-in [k "plot_varconverter"] (.. e -target -value)))
:value (get-in @data-containers [k "plot_varconverter"])}
(for [cmap cplot/avail-var-converters]
^{:key cmap} [:option {:value cmap} cmap])]]
[:td [ant/input {:size "small" :style {:margin-left "0px" :margin-top "0px" :width "65px" :text-align "right"}
:default-value (get-in @data-containers [k "var_lims" 0])
:onChange #(swap! data-containers assoc-in [k "var_lims" 0] (js->clj (.. % -target -value)))}]
" - "
[ant/input {:size "small" :style {:margin-left "0px" :margin-top "0px" :width "65px" :text-align "right"}
:default-value (get-in @data-containers [k "var_lims" 1])
:onChange #(swap! data-containers assoc-in [k "var_lims" 1] (js->clj (.. % -target -value)))}]]
[:td [ant/button {:on-click #((swap! modal-container assoc-in [:param-str] k) (swap! modal-container update-in [:show] not)) :size "small" :icon "bars"}]]
[:td [ant/button {:on-click #((swap! modal-info update-in [:show] not) (fetch-description k)) :size "small" :icon "info-circle"}]]
[:td [ant/button {:on-click (delete-container k) :size "small" :type "danger"} "x"]]]))
(defn editor-container-list [app-state]
(let [data-containers (reagent/atom (get @app-state :data-containers))]
(fn []
(if-not (= (set (keys @data-containers)) (set (keys (get @app-state :data-containers))))
(do (reset! data-containers (get @app-state :data-containers)) (println "made editor data containers consistent")))
[:div
[:table#editorleft
[:thead [:tr [:th "Parameter"] [:th "Colormap"] [:th "Scale"] [:th "Limits"] [:th ""] [:th "Descr."]]]
[:tbody (for [[k v] (get @app-state :data-containers)] ^{:key k} [entry-in-list data-containers k v])]]
[ant/button {:on-click #((swap! app-state assoc-in [:data-containers] @data-containers) (update-plots))
:size "small"} "update plots"]
[:br][:br]
"container - plot - mapping"
[:table#editorleft
[:tbody (doall (for [v [0 1 2 3]] ^{:key v} [:tr
[:td (str "Plot " v)]
[:td [:select {:on-change (fn [e] ;(println (.. e -target -value) (get-in @data-containers [k "colormap"]))
(swap! app-state assoc-in [:mapping-container-plot v] (.. e -target -value))
(update-plots))
:value (get-in @app-state [:mapping-container-plot v])}
(doall (for [params (conj (keys (get @app-state :data-containers)) "")]
^{:key params} [:option {:value params} params]))]]]))]]])))
(defn update-time-by [atm idx-old idx-new amount]
(let [value (js/parseFloat (get-in @atm ["ts" idx-old]))
new (+ value amount)]
;(println "update time " value new)
(swap! atm assoc-in ["ts" idx-new] (str new))))
(defn disabled-date? [current]
(let [duration (get-in @app-state [:c-info :config_file :duration])
testfn (fn [pair current] (and (> current (js/moment.utc (first pair) "YYYYMMDD"))
(< current (.add (js/moment.utc (second pair) "YYYYMMDD") 1 "days"))))
in-one? (mapv #(testfn % current) duration)]
(not (some true? in-one?))))
(defn editor []
(let [panel1-time-range (reagent/atom (get @app-state :sel-time-range))
panel1-param (reagent/atom "select")
check-valid (fn [] (and (< (int (get-in @panel1-time-range ["ts" 0])) (int (get-in @panel1-time-range ["ts" 1])))
(< (- (int (get-in @panel1-time-range ["ts" 1])) (int (get-in @panel1-time-range ["ts" 0]))) 86400)
(< (int (get-in @panel1-time-range ["rg" 0])) (int (get-in @panel1-time-range ["rg" 1])))))]
(fn []
[:div#editor {:style {:min-width "600px" :width "700px" :margin-left "30px"}}
[ant/collapse
[ant/collapse-panel {:header "Time, Range, Parameter" :key "1"}
[ant/row
[ant/col {:span 12}
[:table#editorleft
[:thead]
[:tbody
[:tr [:td "Begin"]
[:td [ant/date-picker {:format "YYYYMMDD_HHmm" :value (.utc (js/moment.unix (get-in @panel1-time-range ["ts" 0])))
:disabled-date disabled-date?
:on-change (fn [_ d] (swap! panel1-time-range assoc-in ["ts" 0] (.format (js/moment.utc d "YYYYMMDD_HHmm") "X")))
:style {:width "100%"} :show-today false :size "small"
:showTime {:use12Hours false :format "HH:mm"}}]
[:br]
[:span.clickable {:on-click #(update-time-by panel1-time-range 0 0 -3600)} "-1h"]
[:span.clickable {:on-click #(update-time-by panel1-time-range 0 0 -600)} "-10min"]
[:span.clickable {:on-click #(update-time-by panel1-time-range 0 0 600)} "+10min"]
[:span.clickable {:on-click #(update-time-by panel1-time-range 0 0 3600)} "+1h"]]]
[:tr [:td "End"]
[:td [ant/date-picker {:format "YYYYMMDD_HHmm" :value (.utc (js/moment.unix (get-in @panel1-time-range ["ts" 1])))
:disabled-date disabled-date?
:on-change (fn [_ d] (swap! panel1-time-range assoc-in ["ts" 1] (.format (js/moment.utc d "YYYYMMDD_HHmm") "X")))
:style {:width "100%"} :show-today false :size "small"
:showTime {:use12Hours false :format "HH:mm"}}]
[:br]
[:span.clickable {:on-click #(update-time-by panel1-time-range 1 1 -3600)} "-1h"]
[:span.clickable {:on-click #(update-time-by panel1-time-range 1 1 -600)} "-10min"]
[:span.clickable {:on-click #(update-time-by panel1-time-range 1 1 600)} "+10min"]
[:span.clickable {:on-click #(update-time-by panel1-time-range 1 1 3600)} "+1h"]
[:span.clickable {:on-click #(update-time-by panel1-time-range 0 1 14400)} "Begin +4h"]]]
[:tr [:td "Range"] [:td [ant/input {:size "small" :style {:margin-left "6px" :margin-top "5px" :width "70px" :text-align "right"}
:default-value (get-in @panel1-time-range ["rg" 0])
:onChange #(swap! panel1-time-range assoc-in ["rg" 0] (js->clj (.. % -target -value)))}]
" - "
[ant/input {:size "small" :style {:margin-left "6px" :margin-top "5px" :width "70px" :text-align "right"}
:default-value (get-in @panel1-time-range ["rg" 1])
:onChange #(swap! panel1-time-range assoc-in ["rg" 1] (js->clj (.. % -target -value)))}]]]
[:tr]]] [ant/button {:on-click #(update-time-range @panel1-time-range)
:disabled (not (check-valid))
:size "small"} "update"]]
[ant/col {:span 12}
[:table#editorleft
[:thead]
[:tbody
[:tr [:td "Campaign"] [:td [ant/select {:showSearch true
:placeholder "select campaign"
:value (get-in @app-state [:c-selected])
:onChange (change-campaign panel1-time-range)
:style {:width "150px"} :size "small"}
(for [c-name (get-in @app-state [:c-list])] ^{:key c-name} [ant/select-option {:value c-name} c-name])]]]
[:tr [:td "Add Parameter"]
[:td
[ant/tree-select {:value @panel1-param :size "small"
:placeholder "Please select" :showSearch true
:onChange (fn [param] (reset! panel1-param (js->clj param)) (add-param (js->clj param)))}
(doall (for [system (sort (keys (get-in @app-state [:c-info :connectors])))]
^{:key system} [ant/tree-tree-node {:title system :selectable false :style {:font-size 11}}
(for [param (sort (keys (get-in @app-state [:c-info :connectors (keyword system) :params])))]
^{:key (keys-to-str [system param])} [ant/tree-tree-node
{:value (keys-to-str [system param])
:title (keys-to-str [system param])}])]))]]]]]]
(if (> (int (get-in @panel1-time-range ["ts" 0])) (int (get-in @panel1-time-range ["ts" 1]))) [:p.er "Time: begin > end"])
(if (> (- (int (get-in @panel1-time-range ["ts" 1])) (int (get-in @panel1-time-range ["ts" 0]))) 86400) [:p.er "Time: too long"])
;(if (< (count (get @panel1-data :sel-camp)) 1) [:p.er "Select campaign"])
(if (> (int (get-in @panel1-time-range ["rg" 0])) (int (get-in @panel1-time-range ["rg" 1]))) [:p.er "Range: top > bottom"])
[ant/col {:span 24} [:br] [:div [ant/button {:on-click #(js/custom.copy_string (get-permalink)) :size "small"} "copy permalink"]
[:span.permalink (get-permalink)]]]]]]
[ant/collapse
[ant/collapse-panel {:header "Plot properties" :key "1"}
[editor-container-list app-state]]]])))
; (defn list-data-contianers []
; [:div#rightfloat (doall (for [data-cont (keys (get-in @app-state [:data-containers]))] ^{:key data-cont} [:div data-cont [:br]]))])
(defn colorplot-component [id]
(reagent/create-class
{:reagent-render #(cplot/colorplot-render colorplotProps-cursor id)
:component-did-mount #(cplot/plot-dispatch colorplotProps-cursor id data-containers-cursor (get-in @app-state [:mapping-container-plot id]) cplot-click)
:component-did-update #(cplot/plot-dispatch colorplotProps-cursor id data-containers-cursor (get-in @app-state [:mapping-container-plot id]) cplot-click)}))
(defn display-modal-info []
(fn []
[ant/modal {:visible (get-in @modal-info [:show]) :title (str "Description " (get-in @modal-info [:title]))
:on-ok #(reset! modal-info {:show false :title "" :content "loading..."})
:on-cancel #(reset! modal-info {:show false :title "" :content "loading..."})}
(reagent/as-element [:div {:dangerouslySetInnerHTML {:__html (string/replace (get-in @modal-info [:content]) #"\n" "<br />")}}])]))
(defn data-container-meta-only [data-container]
(let [new (dissoc data-container "var" "mask" "ts" "rg")
ts (get data-container "ts")
rg (get data-container "rg")]
(assoc new
"ts" [(first ts) (last ts)] "rg" [(first rg) (last rg)])))
(defn pretty-container [data-container]
(with-out-str (cljs.pprint/pprint data-container)))
(defn display-modal-container []
(fn []
[ant/modal {:visible (get-in @modal-container [:show]) :title (str "data_container " (get-in @modal-container [:param-str]))
:on-ok #(reset! modal-container {:show false :param-str ""})
:on-cancel #(reset! modal-container {:show false :param-str ""})}
(let [container-meta (data-container-meta-only (get-in @app-state [:data-containers (get-in @modal-container [:param-str])]))
pretty-str (js/JSON.stringify (clj->js container-meta) js/undefined 2)]
;(console.log (clj->js pretty-str))
(reagent/as-element [:div {:dangerouslySetInnerHTML {:__html (str "<pre>" (string/replace pretty-str #"\n" "<br />") "</pre>")}}]))]))
(defn page []
[:div
[:h1 "Data explorer"]
[editor]
;[list-data-contianers]
[:div.colorplot-container
[colorplot-component 0]
[colorplot-component 1]]
[:div.colorplot-container
[colorplot-component 2]
[colorplot-component 3]]
[:div {:id "tree-tooltip"}]
[display-modal-info]
[display-modal-container]
[:br]])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Initialize App
; (defn dev-setup []
; (when ^boolean js/goog.DEBUG
; (enable-console-print!)
; (println "dev mode")))
(enable-console-print!)
(defn reload []
(reagent/render [page]
(.getElementById js/document "app")))
(defn ^:export main []
;(dev-setup)
(reload))
|
[
{
"context": ";; Copyright (c) 2015 <Diego Souza>\n\n;; Permission is hereby granted, free of charge",
"end": 34,
"score": 0.9998735189437866,
"start": 23,
"tag": "NAME",
"value": "Diego Souza"
}
] | src/storaged/src/leela/storaged/network/router.clj | locaweb/leela | 22 | ;; Copyright (c) 2015 <Diego Souza>
;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation
;; files (the "Software"), to deal in the Software without
;; restriction, including without limitation the rights to use, copy,
;; modify, merge, publish, distribute, sublicense, and/or sell copies
;; of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(ns leela.storaged.network.router
(:import
[org.zeromq ZMQ ZMQ$Socket ZMQ$Context ZMQ$Poller ZMQ$PollItem]
[java.util.concurrent TimeUnit BlockingQueue LinkedBlockingQueue])
(:require
[clojure.tools.logging :refer [trace info warn]]
[leela.storaged.control :refer [forever supervise]]
[leela.storaged.network.zhelpers :as z]
[leela.storaged.network.protocol :refer [unframe]]
[leela.storaged.network.controller :as ctrl]))
(defn- enqueue [fh ^BlockingQueue queue exec-fn [peer body]]
(when-not (or (empty? peer) (empty? body))
(when-not (.offer queue [peer body])
(do
(warn "queue full, dropping request")
(z/sendmsg fh peer ((:onerr exec-fn)))))))
(defn- routing-loop [ifh ofh queue exec-fn]
(forever
(let [[^ZMQ$PollItem ifh-info ^ZMQ$PollItem ofh-info] (z/poll -1 [ifh [ZMQ$Poller/POLLIN] ofh [ZMQ$Poller/POLLIN]])]
(when (.isReadable ifh-info)
(enqueue ifh queue exec-fn (z/recvmsg ifh)))
(when (.isReadable ofh-info)
(let [[peer msg] (z/recvmsg ofh)]
(z/sendmsg ifh peer msg))))))
(defn- run-worker [^ZMQ$Context ctx tid endpoint ^BlockingQueue queue exec-fn]
(with-open [fh (.socket ctx ZMQ/PUSH)]
(trace (format "ENTER:run-worker %d:%s" tid endpoint))
(.connect (z/setup-socket fh) endpoint)
(forever
(let [[peer msg] (.take queue)
reply ((:onjob exec-fn) (first msg))]
(z/sendmsg fh peer [reply])))))
(defn- fork-worker [ctx tid endpoint queue exec-fn]
(.start (Thread. #(supervise (run-worker ctx tid endpoint queue exec-fn)))))
(defn- router-start1 [^ZMQ$Context ctx exec-fn cfg]
(trace "ENTER:router-start1")
(with-open [ifh (.socket ctx ZMQ/ROUTER)
ofh (.socket ctx ZMQ/PULL)]
(let [queue (LinkedBlockingQueue. ^int (:queue-size cfg))
endpoint "inproc://storaged.pipe"]
(info (format "router-start1; config=%s" cfg))
(.bind (z/setup-socket ofh) endpoint)
(.bind (z/setup-socket ifh) (:endpoint cfg))
(dotimes [tid (:capabilities cfg)] (fork-worker ctx tid endpoint queue exec-fn))
(supervise (routing-loop ifh ofh queue exec-fn))))
(trace "EXIT:router-start1"))
(defn router-start [ctx exec-fn cfg]
(supervise (router-start1 ctx exec-fn cfg)))
| 28660 | ;; Copyright (c) 2015 <<NAME>>
;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation
;; files (the "Software"), to deal in the Software without
;; restriction, including without limitation the rights to use, copy,
;; modify, merge, publish, distribute, sublicense, and/or sell copies
;; of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(ns leela.storaged.network.router
(:import
[org.zeromq ZMQ ZMQ$Socket ZMQ$Context ZMQ$Poller ZMQ$PollItem]
[java.util.concurrent TimeUnit BlockingQueue LinkedBlockingQueue])
(:require
[clojure.tools.logging :refer [trace info warn]]
[leela.storaged.control :refer [forever supervise]]
[leela.storaged.network.zhelpers :as z]
[leela.storaged.network.protocol :refer [unframe]]
[leela.storaged.network.controller :as ctrl]))
(defn- enqueue [fh ^BlockingQueue queue exec-fn [peer body]]
(when-not (or (empty? peer) (empty? body))
(when-not (.offer queue [peer body])
(do
(warn "queue full, dropping request")
(z/sendmsg fh peer ((:onerr exec-fn)))))))
(defn- routing-loop [ifh ofh queue exec-fn]
(forever
(let [[^ZMQ$PollItem ifh-info ^ZMQ$PollItem ofh-info] (z/poll -1 [ifh [ZMQ$Poller/POLLIN] ofh [ZMQ$Poller/POLLIN]])]
(when (.isReadable ifh-info)
(enqueue ifh queue exec-fn (z/recvmsg ifh)))
(when (.isReadable ofh-info)
(let [[peer msg] (z/recvmsg ofh)]
(z/sendmsg ifh peer msg))))))
(defn- run-worker [^ZMQ$Context ctx tid endpoint ^BlockingQueue queue exec-fn]
(with-open [fh (.socket ctx ZMQ/PUSH)]
(trace (format "ENTER:run-worker %d:%s" tid endpoint))
(.connect (z/setup-socket fh) endpoint)
(forever
(let [[peer msg] (.take queue)
reply ((:onjob exec-fn) (first msg))]
(z/sendmsg fh peer [reply])))))
(defn- fork-worker [ctx tid endpoint queue exec-fn]
(.start (Thread. #(supervise (run-worker ctx tid endpoint queue exec-fn)))))
(defn- router-start1 [^ZMQ$Context ctx exec-fn cfg]
(trace "ENTER:router-start1")
(with-open [ifh (.socket ctx ZMQ/ROUTER)
ofh (.socket ctx ZMQ/PULL)]
(let [queue (LinkedBlockingQueue. ^int (:queue-size cfg))
endpoint "inproc://storaged.pipe"]
(info (format "router-start1; config=%s" cfg))
(.bind (z/setup-socket ofh) endpoint)
(.bind (z/setup-socket ifh) (:endpoint cfg))
(dotimes [tid (:capabilities cfg)] (fork-worker ctx tid endpoint queue exec-fn))
(supervise (routing-loop ifh ofh queue exec-fn))))
(trace "EXIT:router-start1"))
(defn router-start [ctx exec-fn cfg]
(supervise (router-start1 ctx exec-fn cfg)))
| true | ;; Copyright (c) 2015 <PI:NAME:<NAME>END_PI>
;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation
;; files (the "Software"), to deal in the Software without
;; restriction, including without limitation the rights to use, copy,
;; modify, merge, publish, distribute, sublicense, and/or sell copies
;; of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(ns leela.storaged.network.router
(:import
[org.zeromq ZMQ ZMQ$Socket ZMQ$Context ZMQ$Poller ZMQ$PollItem]
[java.util.concurrent TimeUnit BlockingQueue LinkedBlockingQueue])
(:require
[clojure.tools.logging :refer [trace info warn]]
[leela.storaged.control :refer [forever supervise]]
[leela.storaged.network.zhelpers :as z]
[leela.storaged.network.protocol :refer [unframe]]
[leela.storaged.network.controller :as ctrl]))
(defn- enqueue [fh ^BlockingQueue queue exec-fn [peer body]]
(when-not (or (empty? peer) (empty? body))
(when-not (.offer queue [peer body])
(do
(warn "queue full, dropping request")
(z/sendmsg fh peer ((:onerr exec-fn)))))))
(defn- routing-loop [ifh ofh queue exec-fn]
(forever
(let [[^ZMQ$PollItem ifh-info ^ZMQ$PollItem ofh-info] (z/poll -1 [ifh [ZMQ$Poller/POLLIN] ofh [ZMQ$Poller/POLLIN]])]
(when (.isReadable ifh-info)
(enqueue ifh queue exec-fn (z/recvmsg ifh)))
(when (.isReadable ofh-info)
(let [[peer msg] (z/recvmsg ofh)]
(z/sendmsg ifh peer msg))))))
(defn- run-worker [^ZMQ$Context ctx tid endpoint ^BlockingQueue queue exec-fn]
(with-open [fh (.socket ctx ZMQ/PUSH)]
(trace (format "ENTER:run-worker %d:%s" tid endpoint))
(.connect (z/setup-socket fh) endpoint)
(forever
(let [[peer msg] (.take queue)
reply ((:onjob exec-fn) (first msg))]
(z/sendmsg fh peer [reply])))))
(defn- fork-worker [ctx tid endpoint queue exec-fn]
(.start (Thread. #(supervise (run-worker ctx tid endpoint queue exec-fn)))))
(defn- router-start1 [^ZMQ$Context ctx exec-fn cfg]
(trace "ENTER:router-start1")
(with-open [ifh (.socket ctx ZMQ/ROUTER)
ofh (.socket ctx ZMQ/PULL)]
(let [queue (LinkedBlockingQueue. ^int (:queue-size cfg))
endpoint "inproc://storaged.pipe"]
(info (format "router-start1; config=%s" cfg))
(.bind (z/setup-socket ofh) endpoint)
(.bind (z/setup-socket ifh) (:endpoint cfg))
(dotimes [tid (:capabilities cfg)] (fork-worker ctx tid endpoint queue exec-fn))
(supervise (routing-loop ifh ofh queue exec-fn))))
(trace "EXIT:router-start1"))
(defn router-start [ctx exec-fn cfg]
(supervise (router-start1 ctx exec-fn cfg)))
|
[
{
"context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li",
"end": 111,
"score": 0.9998101592063904,
"start": 96,
"tag": "NAME",
"value": "Ragnar Svensson"
},
{
"context": "-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold License version 1.0 ",
"end": 129,
"score": 0.9998217821121216,
"start": 113,
"tag": "NAME",
"value": "Christian Murray"
}
] | editor/src/clj/editor/volatile_cache.clj | cmarincia/defold | 0 | ;; Copyright 2020-2022 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 Ragnar Svensson, Christian Murray
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; Unless required by applicable law or agreed to in writing, software distributed
;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
;; CONDITIONS OF ANY KIND, either express or implied. See the License for the
;; specific language governing permissions and limitations under the License.
(ns editor.volatile-cache
(:require [clojure.core.cache :as cache]))
(set! *warn-on-reflection* true)
(cache/defcache VolatileCache [cache accessed]
cache/CacheProtocol
(lookup [_ item]
(get cache item))
(lookup [_ item not-found]
(get cache item not-found))
(has? [_ item]
(contains? cache item))
(hit [this item]
(VolatileCache. cache (conj accessed item)))
(miss [this item result]
(VolatileCache. (assoc cache item result) (conj accessed item)))
(evict [_ key]
(VolatileCache. (dissoc cache key) (disj accessed key)))
(seed [_ base]
(VolatileCache. base #{})))
(defn volatile-cache-factory [base]
(VolatileCache. base #{}))
(defn prune [^VolatileCache volatile-cache]
(let [accessed-fn (.accessed volatile-cache)]
(VolatileCache. (into {} (filter (fn [[k v]] (accessed-fn k)) (.cache volatile-cache))) #{})))
| 53630 | ;; Copyright 2020-2022 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 <NAME>, <NAME>
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; Unless required by applicable law or agreed to in writing, software distributed
;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
;; CONDITIONS OF ANY KIND, either express or implied. See the License for the
;; specific language governing permissions and limitations under the License.
(ns editor.volatile-cache
(:require [clojure.core.cache :as cache]))
(set! *warn-on-reflection* true)
(cache/defcache VolatileCache [cache accessed]
cache/CacheProtocol
(lookup [_ item]
(get cache item))
(lookup [_ item not-found]
(get cache item not-found))
(has? [_ item]
(contains? cache item))
(hit [this item]
(VolatileCache. cache (conj accessed item)))
(miss [this item result]
(VolatileCache. (assoc cache item result) (conj accessed item)))
(evict [_ key]
(VolatileCache. (dissoc cache key) (disj accessed key)))
(seed [_ base]
(VolatileCache. base #{})))
(defn volatile-cache-factory [base]
(VolatileCache. base #{}))
(defn prune [^VolatileCache volatile-cache]
(let [accessed-fn (.accessed volatile-cache)]
(VolatileCache. (into {} (filter (fn [[k v]] (accessed-fn k)) (.cache volatile-cache))) #{})))
| true | ;; Copyright 2020-2022 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; Unless required by applicable law or agreed to in writing, software distributed
;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
;; CONDITIONS OF ANY KIND, either express or implied. See the License for the
;; specific language governing permissions and limitations under the License.
(ns editor.volatile-cache
(:require [clojure.core.cache :as cache]))
(set! *warn-on-reflection* true)
(cache/defcache VolatileCache [cache accessed]
cache/CacheProtocol
(lookup [_ item]
(get cache item))
(lookup [_ item not-found]
(get cache item not-found))
(has? [_ item]
(contains? cache item))
(hit [this item]
(VolatileCache. cache (conj accessed item)))
(miss [this item result]
(VolatileCache. (assoc cache item result) (conj accessed item)))
(evict [_ key]
(VolatileCache. (dissoc cache key) (disj accessed key)))
(seed [_ base]
(VolatileCache. base #{})))
(defn volatile-cache-factory [base]
(VolatileCache. base #{}))
(defn prune [^VolatileCache volatile-cache]
(let [accessed-fn (.accessed volatile-cache)]
(VolatileCache. (into {} (filter (fn [[k v]] (accessed-fn k)) (.cache volatile-cache))) #{})))
|
[
{
"context": "; MIT License\n;\n; Copyright (c) 2017 Frederic Merizen\n;\n; Permission is hereby granted, free of charge,",
"end": 53,
"score": 0.9998421669006348,
"start": 37,
"tag": "NAME",
"value": "Frederic Merizen"
}
] | src/plumula/soles.clj | plumula/soles | 0 | ; MIT License
;
; Copyright (c) 2017 Frederic Merizen
;
; 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 plumula.soles
{:boot/export-tasks true}
(:require [adzerk.bootlaces :refer [bootlaces! build-jar push-snapshot push-release]]
[boot.core :as boot]
[boot.lein :as lein]
[boot.task.built-in :as task]
[clojure.java.io :as io]
[plumula.soles.dependencies :as deps]
[plumula.soles.task-pipeline :as pipe]))
(defn add-dir!
"Add `dir` to the `key` path in the environment, providing `dir` actually
is a directory.
"
[key dir]
(when (.isDirectory (io/file dir))
(boot/merge-env! key #{dir})))
(defmacro import-vars
"Make vars from the namespace `ns` available in `*ns*` too.
They can then be `require`d from `*ns*` as if they had been defined there.
`names` should be a sequence of symbols naming the vars to import."
[ns names]
`(do
~@(apply concat
(for [name names
:let [src (symbol (str ns) (str name))]]
`((def ~name ~(resolve src))
(alter-meta! (var ~name) merge (meta (var ~src))))))))
(import-vars plumula.soles.dependencies (add-dependencies!))
(boot/deftask testing
"Profile setup for running tests."
[]
(add-dir! :source-paths "test")
(add-dir! :resource-paths "dev-resources")
identity)
(boot/deftask old
"List dependencies that have newer versions available."
[]
(task/show :updates true))
(defmacro when-handles
"Executes the `body` if the `language` is a member of `platforms`."
[language platforms & body]
`(when ((keyword ~language) ~platforms)
~@body))
(defn platform-ns-symbol
"If called with just one argument, return the unqualified symbol corresponding
to the namespace that contains the pipeline for the `language`.
If called with an extra name argument, return the qualified symbol
corresponding to that name inside the namespace that contains the pipeline for
the `language`"
([language]
(symbol (str "plumula.soles." (name language))))
([language name]
(symbol (str (platform-ns-symbol language)) name)))
(defrecord LanguagePipelineFactory [language dependencies]
pipe/PipelineFactory
(dependencies-for [_ platforms]
(when-handles language platforms
(deps/scopify [:test dependencies])))
(pipeline-for [_ platforms]
(when-handles language platforms
(require (platform-ns-symbol language))
@(resolve (platform-ns-symbol language "pipeline")))))
(boot/deftask deploy-local
"Deploy project to local maven repository."
[]
(build-jar))
(boot/deftask deploy-snapshot
"Deploy snapshot version of project to clojars."
[]
(comp
(build-jar)
(push-snapshot)))
(boot/deftask deploy-release
"Deploy release version of project to clojars."
[]
(comp
(build-jar)
(push-release)))
| 86979 | ; MIT License
;
; Copyright (c) 2017 <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 plumula.soles
{:boot/export-tasks true}
(:require [adzerk.bootlaces :refer [bootlaces! build-jar push-snapshot push-release]]
[boot.core :as boot]
[boot.lein :as lein]
[boot.task.built-in :as task]
[clojure.java.io :as io]
[plumula.soles.dependencies :as deps]
[plumula.soles.task-pipeline :as pipe]))
(defn add-dir!
"Add `dir` to the `key` path in the environment, providing `dir` actually
is a directory.
"
[key dir]
(when (.isDirectory (io/file dir))
(boot/merge-env! key #{dir})))
(defmacro import-vars
"Make vars from the namespace `ns` available in `*ns*` too.
They can then be `require`d from `*ns*` as if they had been defined there.
`names` should be a sequence of symbols naming the vars to import."
[ns names]
`(do
~@(apply concat
(for [name names
:let [src (symbol (str ns) (str name))]]
`((def ~name ~(resolve src))
(alter-meta! (var ~name) merge (meta (var ~src))))))))
(import-vars plumula.soles.dependencies (add-dependencies!))
(boot/deftask testing
"Profile setup for running tests."
[]
(add-dir! :source-paths "test")
(add-dir! :resource-paths "dev-resources")
identity)
(boot/deftask old
"List dependencies that have newer versions available."
[]
(task/show :updates true))
(defmacro when-handles
"Executes the `body` if the `language` is a member of `platforms`."
[language platforms & body]
`(when ((keyword ~language) ~platforms)
~@body))
(defn platform-ns-symbol
"If called with just one argument, return the unqualified symbol corresponding
to the namespace that contains the pipeline for the `language`.
If called with an extra name argument, return the qualified symbol
corresponding to that name inside the namespace that contains the pipeline for
the `language`"
([language]
(symbol (str "plumula.soles." (name language))))
([language name]
(symbol (str (platform-ns-symbol language)) name)))
(defrecord LanguagePipelineFactory [language dependencies]
pipe/PipelineFactory
(dependencies-for [_ platforms]
(when-handles language platforms
(deps/scopify [:test dependencies])))
(pipeline-for [_ platforms]
(when-handles language platforms
(require (platform-ns-symbol language))
@(resolve (platform-ns-symbol language "pipeline")))))
(boot/deftask deploy-local
"Deploy project to local maven repository."
[]
(build-jar))
(boot/deftask deploy-snapshot
"Deploy snapshot version of project to clojars."
[]
(comp
(build-jar)
(push-snapshot)))
(boot/deftask deploy-release
"Deploy release version of project to clojars."
[]
(comp
(build-jar)
(push-release)))
| true | ; MIT License
;
; Copyright (c) 2017 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 plumula.soles
{:boot/export-tasks true}
(:require [adzerk.bootlaces :refer [bootlaces! build-jar push-snapshot push-release]]
[boot.core :as boot]
[boot.lein :as lein]
[boot.task.built-in :as task]
[clojure.java.io :as io]
[plumula.soles.dependencies :as deps]
[plumula.soles.task-pipeline :as pipe]))
(defn add-dir!
"Add `dir` to the `key` path in the environment, providing `dir` actually
is a directory.
"
[key dir]
(when (.isDirectory (io/file dir))
(boot/merge-env! key #{dir})))
(defmacro import-vars
"Make vars from the namespace `ns` available in `*ns*` too.
They can then be `require`d from `*ns*` as if they had been defined there.
`names` should be a sequence of symbols naming the vars to import."
[ns names]
`(do
~@(apply concat
(for [name names
:let [src (symbol (str ns) (str name))]]
`((def ~name ~(resolve src))
(alter-meta! (var ~name) merge (meta (var ~src))))))))
(import-vars plumula.soles.dependencies (add-dependencies!))
(boot/deftask testing
"Profile setup for running tests."
[]
(add-dir! :source-paths "test")
(add-dir! :resource-paths "dev-resources")
identity)
(boot/deftask old
"List dependencies that have newer versions available."
[]
(task/show :updates true))
(defmacro when-handles
"Executes the `body` if the `language` is a member of `platforms`."
[language platforms & body]
`(when ((keyword ~language) ~platforms)
~@body))
(defn platform-ns-symbol
"If called with just one argument, return the unqualified symbol corresponding
to the namespace that contains the pipeline for the `language`.
If called with an extra name argument, return the qualified symbol
corresponding to that name inside the namespace that contains the pipeline for
the `language`"
([language]
(symbol (str "plumula.soles." (name language))))
([language name]
(symbol (str (platform-ns-symbol language)) name)))
(defrecord LanguagePipelineFactory [language dependencies]
pipe/PipelineFactory
(dependencies-for [_ platforms]
(when-handles language platforms
(deps/scopify [:test dependencies])))
(pipeline-for [_ platforms]
(when-handles language platforms
(require (platform-ns-symbol language))
@(resolve (platform-ns-symbol language "pipeline")))))
(boot/deftask deploy-local
"Deploy project to local maven repository."
[]
(build-jar))
(boot/deftask deploy-snapshot
"Deploy snapshot version of project to clojars."
[]
(comp
(build-jar)
(push-snapshot)))
(boot/deftask deploy-release
"Deploy release version of project to clojars."
[]
(comp
(build-jar)
(push-release)))
|
[
{
"context": "ils/->mailto\n {:email \"lipasinfo@jyu.fi\"\n :subject (tr :help/pe",
"end": 12632,
"score": 0.9999233484268188,
"start": 12616,
"tag": "EMAIL",
"value": "lipasinfo@jyu.fi"
}
] | webapp/src/cljs/lipas/ui/energy/views.cljs | lipas-liikuntapaikat/lipas | 49 | (ns lipas.ui.energy.views
(:require
[lipas.ui.charts :as charts]
[lipas.ui.components :as lui]
[lipas.ui.energy.events :as events]
[lipas.ui.energy.subs :as subs]
[lipas.ui.mui :as mui]
[lipas.ui.utils :refer [<== ==>] :as utils]
[reagent.core :as r]))
(defn form [{:keys [tr data on-change disabled? spectators? cold?]}]
[mui/form-group
;; Electricity Mwh
[lui/text-field
{:label (tr :lipas.energy-consumption/electricity)
:disabled disabled?
:type "number"
:value (-> data :energy-consumption :electricity-mwh)
:spec :lipas.energy-consumption/electricity-mwh
:adornment (tr :physical-units/mwh)
:on-change #(on-change [:energy-consumption :electricity-mwh] %)}]
;; Heat Mwh
[lui/text-field
{:label (tr :lipas.energy-consumption/heat)
:disabled disabled?
:type "number"
:spec :lipas.energy-consumption/heat-mwh
:adornment (tr :physical-units/mwh)
:value (-> data :energy-consumption :heat-mwh)
:on-change #(on-change [:energy-consumption :heat-mwh] %)}]
;; Cold Mwh
(when cold?
[lui/text-field
{:label (tr :lipas.energy-consumption/cold)
:disabled disabled?
:type "number"
:spec :lipas.energy-consumption/cold-mwh
:adornment (tr :physical-units/mwh)
:value (-> data :energy-consumption :cold-mwh)
:on-change #(on-change [:energy-consumption :cold-mwh] %)}])
;; Water m³
[lui/text-field
{:label (tr :lipas.energy-consumption/water)
:disabled disabled?
:type "number"
:spec :lipas.energy-consumption/water-m3
:adornment (tr :physical-units/m3)
:value (-> data :energy-consumption :water-m3)
:on-change #(on-change [:energy-consumption :water-m3] %)}]
;; Spectators
(when spectators?
[lui/text-field
{:label (tr :lipas.visitors/spectators-count)
:type "number"
:spec :lipas.visitors/spectators-count
:adornment (tr :units/person)
:value (-> data :visitors :spectators-count)
:on-change #(on-change [:visitors :spectators-count] %)}])
;; Visitors
[lui/text-field
{:label (tr :lipas.visitors/total-count)
:type "number"
:spec :lipas.visitors/total-count
:adornment (tr :units/person)
:value (-> data :visitors :total-count)
:on-change #(on-change [:visitors :total-count] %)}]
;; Operating hours
[lui/text-field
{:label (tr :lipas.energy-consumption/operating-hours)
:type "number"
:spec :lipas.energy-consumption/operating-hours
:adornment (tr :duration/hour)
:value (-> data :energy-consumption :operating-hours)
:on-change #(on-change [:energy-consumption :operating-hours] %)}]])
(defn form-monthly [{:keys [tr data on-change spectators? cold?]}]
[mui/form-group
[:div {:style {:overflow-x "auto"}}
[mui/table
;; Headers
[mui/table-head
[mui/table-row
[mui/table-cell (tr :time/month)]
[mui/table-cell (tr :lipas.energy-consumption/electricity)]
[mui/table-cell (tr :lipas.energy-consumption/heat)]
(when cold?
[mui/table-cell (tr :lipas.energy-consumption/cold)])
[mui/table-cell (tr :lipas.energy-consumption/water)]
(when spectators?
[mui/table-cell (tr :lipas.visitors/spectators-count)])
[mui/table-cell (tr :lipas.visitors/total-count)]
[mui/table-cell (tr :lipas.energy-consumption/operating-hours)]]]
;; Body
(into [mui/table-body]
(for [month [:jan :feb :mar :apr :may :jun :jul :aug :sep :oct :nov :dec]
:let [energy-kw :energy-consumption-monthly
visitors-kw :visitors-monthly
energy-data (get-in data [:energy-consumption-monthly month])
visitors-data (get-in data [:visitors-monthly month])]]
[mui/table-row
[mui/table-cell (tr (keyword :month month))]
[mui/table-cell
;; Electricity Mwh
[lui/text-field
{:type "number"
:spec :lipas.energy-consumption/electricity-mwh
:value (:electricity-mwh energy-data)
:on-change #(on-change [energy-kw month :electricity-mwh] %)}]]
;; Heat Mwh
[mui/table-cell
[lui/text-field
{:type "number"
:spec :lipas.energy-consumption/heat-mwh
:value (:heat-mwh energy-data)
:on-change #(on-change [energy-kw month :heat-mwh] %)}]]
;; Cold Mwh
(when cold?
[mui/table-cell
[lui/text-field
{:type "number"
:spec :lipas.energy-consumption/cold-mwh
:value (:cold-mwh energy-data)
:on-change #(on-change [energy-kw month :cold-mwh] %)}]])
;; Water m³
[mui/table-cell
[lui/text-field
{:type "number"
:spec :lipas.energy-consumption/water-m3
:value (:water-m3 energy-data)
:on-change #(on-change [energy-kw month :water-m3] %)}]]
;; Spectators
(when spectators?
[mui/table-cell
[lui/text-field
{:type "number"
:spec :lipas.visitors/spectators-count
:value (:spectators-count visitors-data)
:on-change #(on-change [visitors-kw month :spectators-count] %)}]])
;; Visitors
[mui/table-cell
[lui/text-field
{:type "number"
:spec :lipas.visitors/total-count
:value (:total-count visitors-data)
:on-change #(on-change [visitors-kw month :total-count] %)}]]
;; Operating hours
[mui/table-cell
[lui/text-field
{:type "number"
:spec :lipas.energy-consumption/operating-hours
:value (:operating-hours energy-data)
:on-change #(on-change [energy-kw month :operating-hours] %)}]]]))]]])
(defn make-headers [tr cold?]
(filter some?
[[:year (tr :time/year)]
[:electricity-mwh (tr :lipas.energy-consumption/electricity)]
[:heat-mwh (tr :lipas.energy-consumption/heat)]
(when cold? [:cold-mwh (tr :lipas.energy-consumption/cold)])
[:water-m3 (tr :lipas.energy-consumption/water)]]))
(defn table [{:keys [tr items read-only? cold? on-select]}]
[lui/table {:headers (make-headers tr cold?)
:items items
:key-fn :year
:sort-fn :year
:sort-asc? true
:on-select on-select
:hide-action-btn? true
:read-only? read-only?}])
(defn set-field
[lipas-id path value]
(==> [::events/edit-field lipas-id path value]))
(defn tab-container [& children]
(into [:div {:style {:margin-top "1em" :margin-bottom "1em"}}]
children))
(defn contains-other-buildings-form [{:keys [tr set-field data]}]
[mui/grid {:container true :style {:margin-bottom "1em"}}
[mui/grid {:item true :xs 12}
[lui/checkbox
{:label (tr :lipas.energy-consumption/contains-other-buildings?)
:value (-> data :energy-consumption :contains-other-buildings?)
:on-change #(set-field [:energy-consumption :contains-other-buildings?] %)}]]
(when (-> data :energy-consumption :contains-other-buildings?)
[mui/grid {:item true :xs 12}
[lui/text-field
{:style {:width "100%"}
:spec :lipas.sports-site/comment
:label (tr :lipas.sports-site/comment)
:value (-> data :energy-consumption :comment)
:multiline false
:on-change #(set-field [:energy-consumption :comment] %)}]])])
(defn energy-form [{:keys [tr year cold? spectators?]}]
(let [data (<== [::subs/energy-consumption-rev])
lipas-id (:lipas-id data)
energy-history (<== [::subs/energy-consumption-history])
edits-valid? (<== [::subs/edits-valid? lipas-id])
;; monthly-data? (<== [::subs/monthly-data-exists?])
set-field (partial set-field lipas-id)]
(r/with-let [monthly-energy? (r/atom false)]
[mui/grid {:container true}
;; Energy consumption
[lui/form-card
{:title (tr :lipas.energy-consumption/headline-year year)
:xs 12 :md 12 :lg 12}
[mui/tabs
{:value (int @monthly-energy?)
:on-change #(swap! monthly-energy? not)}
[mui/tab {:label (tr :lipas.energy-consumption/yearly)}]
[mui/tab {:label (tr :lipas.energy-consumption/monthly)}]]
(case @monthly-energy?
false
[tab-container
[contains-other-buildings-form
{:tr tr :data data :set-field set-field}]
^{:key year}
[form
{:tr tr
:disabled? @monthly-energy?
:cold? cold?
:spectators? spectators?
:data (select-keys data [:energy-consumption :visitors])
:on-change set-field}]]
true
[tab-container
[contains-other-buildings-form
{:tr tr :data data :set-field set-field}]
^{:key year}
[form-monthly
{:tr tr
:cold? cold?
:spectators? spectators?
:data (select-keys data [:energy-consumption-monthly
:visitors-monthly])
:on-change #(==> [::events/set-monthly-value lipas-id %1 %2])}]])
[lui/expansion-panel {:label (tr :actions/show-all-years)}
[table
{:tr tr :cold? true :read-only? true :items energy-history}]]]
;; Actions
[lui/floating-container
{:right 16
:bottom 16
:background-color "transparent"}
[lui/save-button
{:variant "extendedFab"
:disabled (not edits-valid?)
:color "secondary"
:on-click #(==> [::events/commit-energy-consumption data])
:tooltip (tr :actions/save)}]]
;; Small footer on top of which floating container may scroll
[mui/grid
{:item true :xs 12 :style {:height "5em" :background-color mui/gray1}}]])))
(defn energy-consumption-form
[{:keys [tr editable-sites spectators? cold?]}]
(let [logged-in? (<== [:lipas.ui.user.subs/logged-in?])
site (<== [::subs/energy-consumption-site])
years (<== [::subs/energy-consumption-years-list])
year (<== [::subs/energy-consumption-year])
sites editable-sites
lipas-id (get-in site [:history (:latest site) :lipas-id])
;; Fix stale data when jumping between swimming-pool and
;; ice-stadium portals
_ (when-not (some #{lipas-id} (map :lipas-id sites))
(==> [::events/select-energy-consumption-site nil]))]
(if-not logged-in?
[mui/paper {:style {:padding "1em"}}
[mui/grid {:container true :spacing 16}
[mui/grid {:item true}
[mui/typography {:variant "h5" :color "secondary"}
(tr :restricted/login-or-register)]]
[mui/grid {:item true :xs 12}
[lui/login-button
{:label (tr :login/headline)
:on-click #(utils/navigate! "/kirjaudu" :comeback? true)}]]
[mui/grid {:item true}
[lui/register-button
{:label (tr :register/headline)
:on-click #(utils/navigate! "/rekisteroidy")}]]]]
[mui/grid {:container true}
(when-not sites
[mui/grid {:container true}
[mui/grid {:item true :xs 12}
[mui/paper {:style {:padding "1em"}}
[lui/icon-text
{:icon "lock"
:text (tr :lipas.user/no-permissions)}]
[mui/typography {:style {:display "inline" :margin-left "0.75em"}}
(tr :help/permissions-help)]
[mui/link
{:color "secondary"
:variant "body2"
:href (utils/->mailto
{:email "lipasinfo@jyu.fi"
:subject (tr :help/permissions-help-subject)
:body (tr :help/permissions-help-body)} )}
(tr :general/here)]
[mui/typography {:style {:display "inline"}}
"."]]]])
(when sites
[lui/form-card {:title (tr :actions/select-hall)
:xs 12 :md 12 :lg 12}
[mui/form-group
[lui/select
{:label (tr :actions/select-hall)
:value lipas-id
:items sites
:label-fn :name
:value-fn :lipas-id
:on-change #(==> [::events/select-energy-consumption-site %])}]]])
(when (and sites site)
[lui/form-card {:title (tr :actions/select-year)
:xs 12 :md 12 :lg 12}
[mui/form-group
[lui/select
{:label (tr :actions/select-year)
:value year
:items years
:sort-cmp utils/reverse-cmp
:on-change #(==> [::events/select-energy-consumption-year %])}]]])
(when (and sites site year)
[energy-form
{:tr tr
:year year
:spectators? spectators?
:cold? cold?}])])))
(defn energy-stats [{:keys [tr year on-year-change stats link]}]
(let [energy-type (<== [::subs/chart-energy-type])]
[mui/grid {:container true}
;;; Energy chart
[mui/grid {:item true :xs 12 :md 12}
[mui/card {:square true}
;; [mui/card-header {:title (tr :lipas.energy-stats/headline year)}]
[mui/card-content
[mui/grid {:container true :spacing 16 :style {:margin-bottom "1em"}}
[mui/grid {:item true :xs 12 :style {:margin-top "1em"}}
[mui/typography {:variant "h3" :color "secondary"}
(tr :lipas.energy-stats/headline year)]]
;; Select year for stats
[mui/grid {:item true}
[lui/year-selector
{:style {:min-width "100px"}
:label (tr :actions/select-year)
:years (range 2000 utils/this-year)
:value year
:on-change on-year-change}]]
;; Select energy to display in the chart
[mui/grid {:item true}
[lui/select
{:style {:min-width "150px"}
:label (tr :actions/choose-energy)
:items [{:value :energy-mwh
:label (tr :lipas.energy-stats/energy-mwh)}
{:value :electricity-mwh
:label (tr :lipas.energy-stats/electricity-mwh)}
{:value :heat-mwh
:label (tr :lipas.energy-stats/heat-mwh)}
{:value :water-m3
:label (tr :lipas.energy-stats/water-m3)}]
:value energy-type
:on-change #(==> [::events/select-energy-type %])}]]]
(when-not (seq (:data-points stats))
[mui/typography {:color "error"}
(tr :error/no-data)])
;; The Chart
[charts/energy-chart
{:energy energy-type
:energy-label (tr (keyword :lipas.energy-stats energy-type))
:data (:data-points stats)}]
[mui/grid {:container true :spacing 16 :align-items "center" :justify "flex-start"}
[mui/grid {:item true :xs 12}
;; Is your hall missing from the chart? -> Report consumption
[mui/typography {:style {:margin-top "0.5em" :opacity 0.7} :variant "h3"}
(tr :lipas.energy-stats/hall-missing?)]]
[mui/grid {:item true :xs 12 :sm 6 :md 4 :lg 4}
[charts/energy-totals-gauge
(let [total (-> stats :counts :sites)
reported (get-in stats [:counts energy-type])
not-reported (- total reported)]
{:energy-type energy-type
:data
[{:name (tr :lipas.energy-stats/reported reported)
:value reported}
{:name (tr :lipas.energy-stats/not-reported not-reported)
:value not-reported}]})]]
;; Report conssumption button
[mui/grid {:item true :xs 12 :sm 6 :lg 4}
[mui/button
{:color "secondary"
:size "large"
:variant "extendedFab"
:href link}
[mui/icon {:style {:margin-right "0.25em"}} "edit"]
(tr :lipas.energy-stats/report)]]]]]]]))
(defn hof [{:keys [tr stats year]}]
;;; Hall of Fame (all energy info for previous year reported)
[mui/mui-theme-provider {:theme mui/jyu-theme-dark}
[mui/grid {:item true :xs 12 :md 12 :lg 12}
[mui/card {:square true :style {:background-color mui/primary}}
[mui/card-content
[mui/typography {:variant "h2" :style {:color mui/gold}}
"Hall of Fame"]
[mui/typography
{:variant "h6"
:style
{:margin-top "0.75em" :color mui/gray1}}
(tr :lipas.energy-stats/energy-reported-for year)]
[:div {:style {:margin-top "1em"}}
(into
[mui/list {:dense true :style {:column-width "300px"}}]
(for [m (:hall-of-fame stats)]
[mui/list-item {:style {:break-inside :avoid}}
[mui/list-item-icon {:style {:margin-right 0 :color mui/gold}}
[mui/icon "star"]]
[mui/list-item-text {:variant "body2" :color "default"}
(:name m)]]))]]]]])
(defn localize-months [tr]
(let [months [:jan :feb :mar :apr :may :jun
:jul :aug :sep :oct :nov :dec]]
(reduce (fn [m k] (assoc m k (tr (keyword :month k))))
{}
months)))
(defn monthly-chart [{:keys [tr lipas-id year]}]
(let [data (<== [::subs/monthly-chart-data lipas-id year])
labels (merge
{:electricity-mwh (tr :lipas.energy-stats/electricity-mwh)
:heat-mwh (tr :lipas.energy-stats/heat-mwh)
:cold-mwh (tr :lipas.energy-stats/cold-mwh)
:water-m3 (tr :lipas.energy-stats/water-m3)}
(localize-months tr))]
[mui/paper {:style {:margin-top "1em"}
:elevation 0}
[mui/typography {:variant "h6" :color :secondary}
(tr :lipas.energy-consumption/monthly-readings-in-year year)]
(if (not-empty data)
[:div {:style {:padding-top "1em"}}
[charts/monthly-chart
{:data data
:labels labels}]]
[mui/typography
(tr :lipas.energy-consumption/not-reported-monthly)])]))
(defn monthly-visitors-chart [{:keys [tr lipas-id year]}]
(let [data (<== [::subs/monthly-visitors-chart-data lipas-id year])
labels (merge
{:total-count (tr :lipas.visitors/total-count)
:spectators-count (tr :lipas.visitors/spectators-count)}
(localize-months tr))]
[mui/paper {:style {:margin-top "1em"} :elevation 0}
[mui/typography {:variant "h6" :color :secondary}
(tr :lipas.visitors/monthly-visitors-in-year year)]
(if (not-empty data)
[:div {:style {:padding-top "1em"}}
[charts/monthly-chart
{:data data
:labels labels}]]
[mui/typography
(tr :lipas.visitors/not-reported-monthly)])]))
| 109156 | (ns lipas.ui.energy.views
(:require
[lipas.ui.charts :as charts]
[lipas.ui.components :as lui]
[lipas.ui.energy.events :as events]
[lipas.ui.energy.subs :as subs]
[lipas.ui.mui :as mui]
[lipas.ui.utils :refer [<== ==>] :as utils]
[reagent.core :as r]))
(defn form [{:keys [tr data on-change disabled? spectators? cold?]}]
[mui/form-group
;; Electricity Mwh
[lui/text-field
{:label (tr :lipas.energy-consumption/electricity)
:disabled disabled?
:type "number"
:value (-> data :energy-consumption :electricity-mwh)
:spec :lipas.energy-consumption/electricity-mwh
:adornment (tr :physical-units/mwh)
:on-change #(on-change [:energy-consumption :electricity-mwh] %)}]
;; Heat Mwh
[lui/text-field
{:label (tr :lipas.energy-consumption/heat)
:disabled disabled?
:type "number"
:spec :lipas.energy-consumption/heat-mwh
:adornment (tr :physical-units/mwh)
:value (-> data :energy-consumption :heat-mwh)
:on-change #(on-change [:energy-consumption :heat-mwh] %)}]
;; Cold Mwh
(when cold?
[lui/text-field
{:label (tr :lipas.energy-consumption/cold)
:disabled disabled?
:type "number"
:spec :lipas.energy-consumption/cold-mwh
:adornment (tr :physical-units/mwh)
:value (-> data :energy-consumption :cold-mwh)
:on-change #(on-change [:energy-consumption :cold-mwh] %)}])
;; Water m³
[lui/text-field
{:label (tr :lipas.energy-consumption/water)
:disabled disabled?
:type "number"
:spec :lipas.energy-consumption/water-m3
:adornment (tr :physical-units/m3)
:value (-> data :energy-consumption :water-m3)
:on-change #(on-change [:energy-consumption :water-m3] %)}]
;; Spectators
(when spectators?
[lui/text-field
{:label (tr :lipas.visitors/spectators-count)
:type "number"
:spec :lipas.visitors/spectators-count
:adornment (tr :units/person)
:value (-> data :visitors :spectators-count)
:on-change #(on-change [:visitors :spectators-count] %)}])
;; Visitors
[lui/text-field
{:label (tr :lipas.visitors/total-count)
:type "number"
:spec :lipas.visitors/total-count
:adornment (tr :units/person)
:value (-> data :visitors :total-count)
:on-change #(on-change [:visitors :total-count] %)}]
;; Operating hours
[lui/text-field
{:label (tr :lipas.energy-consumption/operating-hours)
:type "number"
:spec :lipas.energy-consumption/operating-hours
:adornment (tr :duration/hour)
:value (-> data :energy-consumption :operating-hours)
:on-change #(on-change [:energy-consumption :operating-hours] %)}]])
(defn form-monthly [{:keys [tr data on-change spectators? cold?]}]
[mui/form-group
[:div {:style {:overflow-x "auto"}}
[mui/table
;; Headers
[mui/table-head
[mui/table-row
[mui/table-cell (tr :time/month)]
[mui/table-cell (tr :lipas.energy-consumption/electricity)]
[mui/table-cell (tr :lipas.energy-consumption/heat)]
(when cold?
[mui/table-cell (tr :lipas.energy-consumption/cold)])
[mui/table-cell (tr :lipas.energy-consumption/water)]
(when spectators?
[mui/table-cell (tr :lipas.visitors/spectators-count)])
[mui/table-cell (tr :lipas.visitors/total-count)]
[mui/table-cell (tr :lipas.energy-consumption/operating-hours)]]]
;; Body
(into [mui/table-body]
(for [month [:jan :feb :mar :apr :may :jun :jul :aug :sep :oct :nov :dec]
:let [energy-kw :energy-consumption-monthly
visitors-kw :visitors-monthly
energy-data (get-in data [:energy-consumption-monthly month])
visitors-data (get-in data [:visitors-monthly month])]]
[mui/table-row
[mui/table-cell (tr (keyword :month month))]
[mui/table-cell
;; Electricity Mwh
[lui/text-field
{:type "number"
:spec :lipas.energy-consumption/electricity-mwh
:value (:electricity-mwh energy-data)
:on-change #(on-change [energy-kw month :electricity-mwh] %)}]]
;; Heat Mwh
[mui/table-cell
[lui/text-field
{:type "number"
:spec :lipas.energy-consumption/heat-mwh
:value (:heat-mwh energy-data)
:on-change #(on-change [energy-kw month :heat-mwh] %)}]]
;; Cold Mwh
(when cold?
[mui/table-cell
[lui/text-field
{:type "number"
:spec :lipas.energy-consumption/cold-mwh
:value (:cold-mwh energy-data)
:on-change #(on-change [energy-kw month :cold-mwh] %)}]])
;; Water m³
[mui/table-cell
[lui/text-field
{:type "number"
:spec :lipas.energy-consumption/water-m3
:value (:water-m3 energy-data)
:on-change #(on-change [energy-kw month :water-m3] %)}]]
;; Spectators
(when spectators?
[mui/table-cell
[lui/text-field
{:type "number"
:spec :lipas.visitors/spectators-count
:value (:spectators-count visitors-data)
:on-change #(on-change [visitors-kw month :spectators-count] %)}]])
;; Visitors
[mui/table-cell
[lui/text-field
{:type "number"
:spec :lipas.visitors/total-count
:value (:total-count visitors-data)
:on-change #(on-change [visitors-kw month :total-count] %)}]]
;; Operating hours
[mui/table-cell
[lui/text-field
{:type "number"
:spec :lipas.energy-consumption/operating-hours
:value (:operating-hours energy-data)
:on-change #(on-change [energy-kw month :operating-hours] %)}]]]))]]])
(defn make-headers [tr cold?]
(filter some?
[[:year (tr :time/year)]
[:electricity-mwh (tr :lipas.energy-consumption/electricity)]
[:heat-mwh (tr :lipas.energy-consumption/heat)]
(when cold? [:cold-mwh (tr :lipas.energy-consumption/cold)])
[:water-m3 (tr :lipas.energy-consumption/water)]]))
(defn table [{:keys [tr items read-only? cold? on-select]}]
[lui/table {:headers (make-headers tr cold?)
:items items
:key-fn :year
:sort-fn :year
:sort-asc? true
:on-select on-select
:hide-action-btn? true
:read-only? read-only?}])
(defn set-field
[lipas-id path value]
(==> [::events/edit-field lipas-id path value]))
(defn tab-container [& children]
(into [:div {:style {:margin-top "1em" :margin-bottom "1em"}}]
children))
(defn contains-other-buildings-form [{:keys [tr set-field data]}]
[mui/grid {:container true :style {:margin-bottom "1em"}}
[mui/grid {:item true :xs 12}
[lui/checkbox
{:label (tr :lipas.energy-consumption/contains-other-buildings?)
:value (-> data :energy-consumption :contains-other-buildings?)
:on-change #(set-field [:energy-consumption :contains-other-buildings?] %)}]]
(when (-> data :energy-consumption :contains-other-buildings?)
[mui/grid {:item true :xs 12}
[lui/text-field
{:style {:width "100%"}
:spec :lipas.sports-site/comment
:label (tr :lipas.sports-site/comment)
:value (-> data :energy-consumption :comment)
:multiline false
:on-change #(set-field [:energy-consumption :comment] %)}]])])
(defn energy-form [{:keys [tr year cold? spectators?]}]
(let [data (<== [::subs/energy-consumption-rev])
lipas-id (:lipas-id data)
energy-history (<== [::subs/energy-consumption-history])
edits-valid? (<== [::subs/edits-valid? lipas-id])
;; monthly-data? (<== [::subs/monthly-data-exists?])
set-field (partial set-field lipas-id)]
(r/with-let [monthly-energy? (r/atom false)]
[mui/grid {:container true}
;; Energy consumption
[lui/form-card
{:title (tr :lipas.energy-consumption/headline-year year)
:xs 12 :md 12 :lg 12}
[mui/tabs
{:value (int @monthly-energy?)
:on-change #(swap! monthly-energy? not)}
[mui/tab {:label (tr :lipas.energy-consumption/yearly)}]
[mui/tab {:label (tr :lipas.energy-consumption/monthly)}]]
(case @monthly-energy?
false
[tab-container
[contains-other-buildings-form
{:tr tr :data data :set-field set-field}]
^{:key year}
[form
{:tr tr
:disabled? @monthly-energy?
:cold? cold?
:spectators? spectators?
:data (select-keys data [:energy-consumption :visitors])
:on-change set-field}]]
true
[tab-container
[contains-other-buildings-form
{:tr tr :data data :set-field set-field}]
^{:key year}
[form-monthly
{:tr tr
:cold? cold?
:spectators? spectators?
:data (select-keys data [:energy-consumption-monthly
:visitors-monthly])
:on-change #(==> [::events/set-monthly-value lipas-id %1 %2])}]])
[lui/expansion-panel {:label (tr :actions/show-all-years)}
[table
{:tr tr :cold? true :read-only? true :items energy-history}]]]
;; Actions
[lui/floating-container
{:right 16
:bottom 16
:background-color "transparent"}
[lui/save-button
{:variant "extendedFab"
:disabled (not edits-valid?)
:color "secondary"
:on-click #(==> [::events/commit-energy-consumption data])
:tooltip (tr :actions/save)}]]
;; Small footer on top of which floating container may scroll
[mui/grid
{:item true :xs 12 :style {:height "5em" :background-color mui/gray1}}]])))
(defn energy-consumption-form
[{:keys [tr editable-sites spectators? cold?]}]
(let [logged-in? (<== [:lipas.ui.user.subs/logged-in?])
site (<== [::subs/energy-consumption-site])
years (<== [::subs/energy-consumption-years-list])
year (<== [::subs/energy-consumption-year])
sites editable-sites
lipas-id (get-in site [:history (:latest site) :lipas-id])
;; Fix stale data when jumping between swimming-pool and
;; ice-stadium portals
_ (when-not (some #{lipas-id} (map :lipas-id sites))
(==> [::events/select-energy-consumption-site nil]))]
(if-not logged-in?
[mui/paper {:style {:padding "1em"}}
[mui/grid {:container true :spacing 16}
[mui/grid {:item true}
[mui/typography {:variant "h5" :color "secondary"}
(tr :restricted/login-or-register)]]
[mui/grid {:item true :xs 12}
[lui/login-button
{:label (tr :login/headline)
:on-click #(utils/navigate! "/kirjaudu" :comeback? true)}]]
[mui/grid {:item true}
[lui/register-button
{:label (tr :register/headline)
:on-click #(utils/navigate! "/rekisteroidy")}]]]]
[mui/grid {:container true}
(when-not sites
[mui/grid {:container true}
[mui/grid {:item true :xs 12}
[mui/paper {:style {:padding "1em"}}
[lui/icon-text
{:icon "lock"
:text (tr :lipas.user/no-permissions)}]
[mui/typography {:style {:display "inline" :margin-left "0.75em"}}
(tr :help/permissions-help)]
[mui/link
{:color "secondary"
:variant "body2"
:href (utils/->mailto
{:email "<EMAIL>"
:subject (tr :help/permissions-help-subject)
:body (tr :help/permissions-help-body)} )}
(tr :general/here)]
[mui/typography {:style {:display "inline"}}
"."]]]])
(when sites
[lui/form-card {:title (tr :actions/select-hall)
:xs 12 :md 12 :lg 12}
[mui/form-group
[lui/select
{:label (tr :actions/select-hall)
:value lipas-id
:items sites
:label-fn :name
:value-fn :lipas-id
:on-change #(==> [::events/select-energy-consumption-site %])}]]])
(when (and sites site)
[lui/form-card {:title (tr :actions/select-year)
:xs 12 :md 12 :lg 12}
[mui/form-group
[lui/select
{:label (tr :actions/select-year)
:value year
:items years
:sort-cmp utils/reverse-cmp
:on-change #(==> [::events/select-energy-consumption-year %])}]]])
(when (and sites site year)
[energy-form
{:tr tr
:year year
:spectators? spectators?
:cold? cold?}])])))
(defn energy-stats [{:keys [tr year on-year-change stats link]}]
(let [energy-type (<== [::subs/chart-energy-type])]
[mui/grid {:container true}
;;; Energy chart
[mui/grid {:item true :xs 12 :md 12}
[mui/card {:square true}
;; [mui/card-header {:title (tr :lipas.energy-stats/headline year)}]
[mui/card-content
[mui/grid {:container true :spacing 16 :style {:margin-bottom "1em"}}
[mui/grid {:item true :xs 12 :style {:margin-top "1em"}}
[mui/typography {:variant "h3" :color "secondary"}
(tr :lipas.energy-stats/headline year)]]
;; Select year for stats
[mui/grid {:item true}
[lui/year-selector
{:style {:min-width "100px"}
:label (tr :actions/select-year)
:years (range 2000 utils/this-year)
:value year
:on-change on-year-change}]]
;; Select energy to display in the chart
[mui/grid {:item true}
[lui/select
{:style {:min-width "150px"}
:label (tr :actions/choose-energy)
:items [{:value :energy-mwh
:label (tr :lipas.energy-stats/energy-mwh)}
{:value :electricity-mwh
:label (tr :lipas.energy-stats/electricity-mwh)}
{:value :heat-mwh
:label (tr :lipas.energy-stats/heat-mwh)}
{:value :water-m3
:label (tr :lipas.energy-stats/water-m3)}]
:value energy-type
:on-change #(==> [::events/select-energy-type %])}]]]
(when-not (seq (:data-points stats))
[mui/typography {:color "error"}
(tr :error/no-data)])
;; The Chart
[charts/energy-chart
{:energy energy-type
:energy-label (tr (keyword :lipas.energy-stats energy-type))
:data (:data-points stats)}]
[mui/grid {:container true :spacing 16 :align-items "center" :justify "flex-start"}
[mui/grid {:item true :xs 12}
;; Is your hall missing from the chart? -> Report consumption
[mui/typography {:style {:margin-top "0.5em" :opacity 0.7} :variant "h3"}
(tr :lipas.energy-stats/hall-missing?)]]
[mui/grid {:item true :xs 12 :sm 6 :md 4 :lg 4}
[charts/energy-totals-gauge
(let [total (-> stats :counts :sites)
reported (get-in stats [:counts energy-type])
not-reported (- total reported)]
{:energy-type energy-type
:data
[{:name (tr :lipas.energy-stats/reported reported)
:value reported}
{:name (tr :lipas.energy-stats/not-reported not-reported)
:value not-reported}]})]]
;; Report conssumption button
[mui/grid {:item true :xs 12 :sm 6 :lg 4}
[mui/button
{:color "secondary"
:size "large"
:variant "extendedFab"
:href link}
[mui/icon {:style {:margin-right "0.25em"}} "edit"]
(tr :lipas.energy-stats/report)]]]]]]]))
(defn hof [{:keys [tr stats year]}]
;;; Hall of Fame (all energy info for previous year reported)
[mui/mui-theme-provider {:theme mui/jyu-theme-dark}
[mui/grid {:item true :xs 12 :md 12 :lg 12}
[mui/card {:square true :style {:background-color mui/primary}}
[mui/card-content
[mui/typography {:variant "h2" :style {:color mui/gold}}
"Hall of Fame"]
[mui/typography
{:variant "h6"
:style
{:margin-top "0.75em" :color mui/gray1}}
(tr :lipas.energy-stats/energy-reported-for year)]
[:div {:style {:margin-top "1em"}}
(into
[mui/list {:dense true :style {:column-width "300px"}}]
(for [m (:hall-of-fame stats)]
[mui/list-item {:style {:break-inside :avoid}}
[mui/list-item-icon {:style {:margin-right 0 :color mui/gold}}
[mui/icon "star"]]
[mui/list-item-text {:variant "body2" :color "default"}
(:name m)]]))]]]]])
(defn localize-months [tr]
(let [months [:jan :feb :mar :apr :may :jun
:jul :aug :sep :oct :nov :dec]]
(reduce (fn [m k] (assoc m k (tr (keyword :month k))))
{}
months)))
(defn monthly-chart [{:keys [tr lipas-id year]}]
(let [data (<== [::subs/monthly-chart-data lipas-id year])
labels (merge
{:electricity-mwh (tr :lipas.energy-stats/electricity-mwh)
:heat-mwh (tr :lipas.energy-stats/heat-mwh)
:cold-mwh (tr :lipas.energy-stats/cold-mwh)
:water-m3 (tr :lipas.energy-stats/water-m3)}
(localize-months tr))]
[mui/paper {:style {:margin-top "1em"}
:elevation 0}
[mui/typography {:variant "h6" :color :secondary}
(tr :lipas.energy-consumption/monthly-readings-in-year year)]
(if (not-empty data)
[:div {:style {:padding-top "1em"}}
[charts/monthly-chart
{:data data
:labels labels}]]
[mui/typography
(tr :lipas.energy-consumption/not-reported-monthly)])]))
(defn monthly-visitors-chart [{:keys [tr lipas-id year]}]
(let [data (<== [::subs/monthly-visitors-chart-data lipas-id year])
labels (merge
{:total-count (tr :lipas.visitors/total-count)
:spectators-count (tr :lipas.visitors/spectators-count)}
(localize-months tr))]
[mui/paper {:style {:margin-top "1em"} :elevation 0}
[mui/typography {:variant "h6" :color :secondary}
(tr :lipas.visitors/monthly-visitors-in-year year)]
(if (not-empty data)
[:div {:style {:padding-top "1em"}}
[charts/monthly-chart
{:data data
:labels labels}]]
[mui/typography
(tr :lipas.visitors/not-reported-monthly)])]))
| true | (ns lipas.ui.energy.views
(:require
[lipas.ui.charts :as charts]
[lipas.ui.components :as lui]
[lipas.ui.energy.events :as events]
[lipas.ui.energy.subs :as subs]
[lipas.ui.mui :as mui]
[lipas.ui.utils :refer [<== ==>] :as utils]
[reagent.core :as r]))
(defn form [{:keys [tr data on-change disabled? spectators? cold?]}]
[mui/form-group
;; Electricity Mwh
[lui/text-field
{:label (tr :lipas.energy-consumption/electricity)
:disabled disabled?
:type "number"
:value (-> data :energy-consumption :electricity-mwh)
:spec :lipas.energy-consumption/electricity-mwh
:adornment (tr :physical-units/mwh)
:on-change #(on-change [:energy-consumption :electricity-mwh] %)}]
;; Heat Mwh
[lui/text-field
{:label (tr :lipas.energy-consumption/heat)
:disabled disabled?
:type "number"
:spec :lipas.energy-consumption/heat-mwh
:adornment (tr :physical-units/mwh)
:value (-> data :energy-consumption :heat-mwh)
:on-change #(on-change [:energy-consumption :heat-mwh] %)}]
;; Cold Mwh
(when cold?
[lui/text-field
{:label (tr :lipas.energy-consumption/cold)
:disabled disabled?
:type "number"
:spec :lipas.energy-consumption/cold-mwh
:adornment (tr :physical-units/mwh)
:value (-> data :energy-consumption :cold-mwh)
:on-change #(on-change [:energy-consumption :cold-mwh] %)}])
;; Water m³
[lui/text-field
{:label (tr :lipas.energy-consumption/water)
:disabled disabled?
:type "number"
:spec :lipas.energy-consumption/water-m3
:adornment (tr :physical-units/m3)
:value (-> data :energy-consumption :water-m3)
:on-change #(on-change [:energy-consumption :water-m3] %)}]
;; Spectators
(when spectators?
[lui/text-field
{:label (tr :lipas.visitors/spectators-count)
:type "number"
:spec :lipas.visitors/spectators-count
:adornment (tr :units/person)
:value (-> data :visitors :spectators-count)
:on-change #(on-change [:visitors :spectators-count] %)}])
;; Visitors
[lui/text-field
{:label (tr :lipas.visitors/total-count)
:type "number"
:spec :lipas.visitors/total-count
:adornment (tr :units/person)
:value (-> data :visitors :total-count)
:on-change #(on-change [:visitors :total-count] %)}]
;; Operating hours
[lui/text-field
{:label (tr :lipas.energy-consumption/operating-hours)
:type "number"
:spec :lipas.energy-consumption/operating-hours
:adornment (tr :duration/hour)
:value (-> data :energy-consumption :operating-hours)
:on-change #(on-change [:energy-consumption :operating-hours] %)}]])
(defn form-monthly [{:keys [tr data on-change spectators? cold?]}]
[mui/form-group
[:div {:style {:overflow-x "auto"}}
[mui/table
;; Headers
[mui/table-head
[mui/table-row
[mui/table-cell (tr :time/month)]
[mui/table-cell (tr :lipas.energy-consumption/electricity)]
[mui/table-cell (tr :lipas.energy-consumption/heat)]
(when cold?
[mui/table-cell (tr :lipas.energy-consumption/cold)])
[mui/table-cell (tr :lipas.energy-consumption/water)]
(when spectators?
[mui/table-cell (tr :lipas.visitors/spectators-count)])
[mui/table-cell (tr :lipas.visitors/total-count)]
[mui/table-cell (tr :lipas.energy-consumption/operating-hours)]]]
;; Body
(into [mui/table-body]
(for [month [:jan :feb :mar :apr :may :jun :jul :aug :sep :oct :nov :dec]
:let [energy-kw :energy-consumption-monthly
visitors-kw :visitors-monthly
energy-data (get-in data [:energy-consumption-monthly month])
visitors-data (get-in data [:visitors-monthly month])]]
[mui/table-row
[mui/table-cell (tr (keyword :month month))]
[mui/table-cell
;; Electricity Mwh
[lui/text-field
{:type "number"
:spec :lipas.energy-consumption/electricity-mwh
:value (:electricity-mwh energy-data)
:on-change #(on-change [energy-kw month :electricity-mwh] %)}]]
;; Heat Mwh
[mui/table-cell
[lui/text-field
{:type "number"
:spec :lipas.energy-consumption/heat-mwh
:value (:heat-mwh energy-data)
:on-change #(on-change [energy-kw month :heat-mwh] %)}]]
;; Cold Mwh
(when cold?
[mui/table-cell
[lui/text-field
{:type "number"
:spec :lipas.energy-consumption/cold-mwh
:value (:cold-mwh energy-data)
:on-change #(on-change [energy-kw month :cold-mwh] %)}]])
;; Water m³
[mui/table-cell
[lui/text-field
{:type "number"
:spec :lipas.energy-consumption/water-m3
:value (:water-m3 energy-data)
:on-change #(on-change [energy-kw month :water-m3] %)}]]
;; Spectators
(when spectators?
[mui/table-cell
[lui/text-field
{:type "number"
:spec :lipas.visitors/spectators-count
:value (:spectators-count visitors-data)
:on-change #(on-change [visitors-kw month :spectators-count] %)}]])
;; Visitors
[mui/table-cell
[lui/text-field
{:type "number"
:spec :lipas.visitors/total-count
:value (:total-count visitors-data)
:on-change #(on-change [visitors-kw month :total-count] %)}]]
;; Operating hours
[mui/table-cell
[lui/text-field
{:type "number"
:spec :lipas.energy-consumption/operating-hours
:value (:operating-hours energy-data)
:on-change #(on-change [energy-kw month :operating-hours] %)}]]]))]]])
(defn make-headers [tr cold?]
(filter some?
[[:year (tr :time/year)]
[:electricity-mwh (tr :lipas.energy-consumption/electricity)]
[:heat-mwh (tr :lipas.energy-consumption/heat)]
(when cold? [:cold-mwh (tr :lipas.energy-consumption/cold)])
[:water-m3 (tr :lipas.energy-consumption/water)]]))
(defn table [{:keys [tr items read-only? cold? on-select]}]
[lui/table {:headers (make-headers tr cold?)
:items items
:key-fn :year
:sort-fn :year
:sort-asc? true
:on-select on-select
:hide-action-btn? true
:read-only? read-only?}])
(defn set-field
[lipas-id path value]
(==> [::events/edit-field lipas-id path value]))
(defn tab-container [& children]
(into [:div {:style {:margin-top "1em" :margin-bottom "1em"}}]
children))
(defn contains-other-buildings-form [{:keys [tr set-field data]}]
[mui/grid {:container true :style {:margin-bottom "1em"}}
[mui/grid {:item true :xs 12}
[lui/checkbox
{:label (tr :lipas.energy-consumption/contains-other-buildings?)
:value (-> data :energy-consumption :contains-other-buildings?)
:on-change #(set-field [:energy-consumption :contains-other-buildings?] %)}]]
(when (-> data :energy-consumption :contains-other-buildings?)
[mui/grid {:item true :xs 12}
[lui/text-field
{:style {:width "100%"}
:spec :lipas.sports-site/comment
:label (tr :lipas.sports-site/comment)
:value (-> data :energy-consumption :comment)
:multiline false
:on-change #(set-field [:energy-consumption :comment] %)}]])])
(defn energy-form [{:keys [tr year cold? spectators?]}]
(let [data (<== [::subs/energy-consumption-rev])
lipas-id (:lipas-id data)
energy-history (<== [::subs/energy-consumption-history])
edits-valid? (<== [::subs/edits-valid? lipas-id])
;; monthly-data? (<== [::subs/monthly-data-exists?])
set-field (partial set-field lipas-id)]
(r/with-let [monthly-energy? (r/atom false)]
[mui/grid {:container true}
;; Energy consumption
[lui/form-card
{:title (tr :lipas.energy-consumption/headline-year year)
:xs 12 :md 12 :lg 12}
[mui/tabs
{:value (int @monthly-energy?)
:on-change #(swap! monthly-energy? not)}
[mui/tab {:label (tr :lipas.energy-consumption/yearly)}]
[mui/tab {:label (tr :lipas.energy-consumption/monthly)}]]
(case @monthly-energy?
false
[tab-container
[contains-other-buildings-form
{:tr tr :data data :set-field set-field}]
^{:key year}
[form
{:tr tr
:disabled? @monthly-energy?
:cold? cold?
:spectators? spectators?
:data (select-keys data [:energy-consumption :visitors])
:on-change set-field}]]
true
[tab-container
[contains-other-buildings-form
{:tr tr :data data :set-field set-field}]
^{:key year}
[form-monthly
{:tr tr
:cold? cold?
:spectators? spectators?
:data (select-keys data [:energy-consumption-monthly
:visitors-monthly])
:on-change #(==> [::events/set-monthly-value lipas-id %1 %2])}]])
[lui/expansion-panel {:label (tr :actions/show-all-years)}
[table
{:tr tr :cold? true :read-only? true :items energy-history}]]]
;; Actions
[lui/floating-container
{:right 16
:bottom 16
:background-color "transparent"}
[lui/save-button
{:variant "extendedFab"
:disabled (not edits-valid?)
:color "secondary"
:on-click #(==> [::events/commit-energy-consumption data])
:tooltip (tr :actions/save)}]]
;; Small footer on top of which floating container may scroll
[mui/grid
{:item true :xs 12 :style {:height "5em" :background-color mui/gray1}}]])))
(defn energy-consumption-form
[{:keys [tr editable-sites spectators? cold?]}]
(let [logged-in? (<== [:lipas.ui.user.subs/logged-in?])
site (<== [::subs/energy-consumption-site])
years (<== [::subs/energy-consumption-years-list])
year (<== [::subs/energy-consumption-year])
sites editable-sites
lipas-id (get-in site [:history (:latest site) :lipas-id])
;; Fix stale data when jumping between swimming-pool and
;; ice-stadium portals
_ (when-not (some #{lipas-id} (map :lipas-id sites))
(==> [::events/select-energy-consumption-site nil]))]
(if-not logged-in?
[mui/paper {:style {:padding "1em"}}
[mui/grid {:container true :spacing 16}
[mui/grid {:item true}
[mui/typography {:variant "h5" :color "secondary"}
(tr :restricted/login-or-register)]]
[mui/grid {:item true :xs 12}
[lui/login-button
{:label (tr :login/headline)
:on-click #(utils/navigate! "/kirjaudu" :comeback? true)}]]
[mui/grid {:item true}
[lui/register-button
{:label (tr :register/headline)
:on-click #(utils/navigate! "/rekisteroidy")}]]]]
[mui/grid {:container true}
(when-not sites
[mui/grid {:container true}
[mui/grid {:item true :xs 12}
[mui/paper {:style {:padding "1em"}}
[lui/icon-text
{:icon "lock"
:text (tr :lipas.user/no-permissions)}]
[mui/typography {:style {:display "inline" :margin-left "0.75em"}}
(tr :help/permissions-help)]
[mui/link
{:color "secondary"
:variant "body2"
:href (utils/->mailto
{:email "PI:EMAIL:<EMAIL>END_PI"
:subject (tr :help/permissions-help-subject)
:body (tr :help/permissions-help-body)} )}
(tr :general/here)]
[mui/typography {:style {:display "inline"}}
"."]]]])
(when sites
[lui/form-card {:title (tr :actions/select-hall)
:xs 12 :md 12 :lg 12}
[mui/form-group
[lui/select
{:label (tr :actions/select-hall)
:value lipas-id
:items sites
:label-fn :name
:value-fn :lipas-id
:on-change #(==> [::events/select-energy-consumption-site %])}]]])
(when (and sites site)
[lui/form-card {:title (tr :actions/select-year)
:xs 12 :md 12 :lg 12}
[mui/form-group
[lui/select
{:label (tr :actions/select-year)
:value year
:items years
:sort-cmp utils/reverse-cmp
:on-change #(==> [::events/select-energy-consumption-year %])}]]])
(when (and sites site year)
[energy-form
{:tr tr
:year year
:spectators? spectators?
:cold? cold?}])])))
(defn energy-stats [{:keys [tr year on-year-change stats link]}]
(let [energy-type (<== [::subs/chart-energy-type])]
[mui/grid {:container true}
;;; Energy chart
[mui/grid {:item true :xs 12 :md 12}
[mui/card {:square true}
;; [mui/card-header {:title (tr :lipas.energy-stats/headline year)}]
[mui/card-content
[mui/grid {:container true :spacing 16 :style {:margin-bottom "1em"}}
[mui/grid {:item true :xs 12 :style {:margin-top "1em"}}
[mui/typography {:variant "h3" :color "secondary"}
(tr :lipas.energy-stats/headline year)]]
;; Select year for stats
[mui/grid {:item true}
[lui/year-selector
{:style {:min-width "100px"}
:label (tr :actions/select-year)
:years (range 2000 utils/this-year)
:value year
:on-change on-year-change}]]
;; Select energy to display in the chart
[mui/grid {:item true}
[lui/select
{:style {:min-width "150px"}
:label (tr :actions/choose-energy)
:items [{:value :energy-mwh
:label (tr :lipas.energy-stats/energy-mwh)}
{:value :electricity-mwh
:label (tr :lipas.energy-stats/electricity-mwh)}
{:value :heat-mwh
:label (tr :lipas.energy-stats/heat-mwh)}
{:value :water-m3
:label (tr :lipas.energy-stats/water-m3)}]
:value energy-type
:on-change #(==> [::events/select-energy-type %])}]]]
(when-not (seq (:data-points stats))
[mui/typography {:color "error"}
(tr :error/no-data)])
;; The Chart
[charts/energy-chart
{:energy energy-type
:energy-label (tr (keyword :lipas.energy-stats energy-type))
:data (:data-points stats)}]
[mui/grid {:container true :spacing 16 :align-items "center" :justify "flex-start"}
[mui/grid {:item true :xs 12}
;; Is your hall missing from the chart? -> Report consumption
[mui/typography {:style {:margin-top "0.5em" :opacity 0.7} :variant "h3"}
(tr :lipas.energy-stats/hall-missing?)]]
[mui/grid {:item true :xs 12 :sm 6 :md 4 :lg 4}
[charts/energy-totals-gauge
(let [total (-> stats :counts :sites)
reported (get-in stats [:counts energy-type])
not-reported (- total reported)]
{:energy-type energy-type
:data
[{:name (tr :lipas.energy-stats/reported reported)
:value reported}
{:name (tr :lipas.energy-stats/not-reported not-reported)
:value not-reported}]})]]
;; Report conssumption button
[mui/grid {:item true :xs 12 :sm 6 :lg 4}
[mui/button
{:color "secondary"
:size "large"
:variant "extendedFab"
:href link}
[mui/icon {:style {:margin-right "0.25em"}} "edit"]
(tr :lipas.energy-stats/report)]]]]]]]))
(defn hof [{:keys [tr stats year]}]
;;; Hall of Fame (all energy info for previous year reported)
[mui/mui-theme-provider {:theme mui/jyu-theme-dark}
[mui/grid {:item true :xs 12 :md 12 :lg 12}
[mui/card {:square true :style {:background-color mui/primary}}
[mui/card-content
[mui/typography {:variant "h2" :style {:color mui/gold}}
"Hall of Fame"]
[mui/typography
{:variant "h6"
:style
{:margin-top "0.75em" :color mui/gray1}}
(tr :lipas.energy-stats/energy-reported-for year)]
[:div {:style {:margin-top "1em"}}
(into
[mui/list {:dense true :style {:column-width "300px"}}]
(for [m (:hall-of-fame stats)]
[mui/list-item {:style {:break-inside :avoid}}
[mui/list-item-icon {:style {:margin-right 0 :color mui/gold}}
[mui/icon "star"]]
[mui/list-item-text {:variant "body2" :color "default"}
(:name m)]]))]]]]])
(defn localize-months [tr]
(let [months [:jan :feb :mar :apr :may :jun
:jul :aug :sep :oct :nov :dec]]
(reduce (fn [m k] (assoc m k (tr (keyword :month k))))
{}
months)))
(defn monthly-chart [{:keys [tr lipas-id year]}]
(let [data (<== [::subs/monthly-chart-data lipas-id year])
labels (merge
{:electricity-mwh (tr :lipas.energy-stats/electricity-mwh)
:heat-mwh (tr :lipas.energy-stats/heat-mwh)
:cold-mwh (tr :lipas.energy-stats/cold-mwh)
:water-m3 (tr :lipas.energy-stats/water-m3)}
(localize-months tr))]
[mui/paper {:style {:margin-top "1em"}
:elevation 0}
[mui/typography {:variant "h6" :color :secondary}
(tr :lipas.energy-consumption/monthly-readings-in-year year)]
(if (not-empty data)
[:div {:style {:padding-top "1em"}}
[charts/monthly-chart
{:data data
:labels labels}]]
[mui/typography
(tr :lipas.energy-consumption/not-reported-monthly)])]))
(defn monthly-visitors-chart [{:keys [tr lipas-id year]}]
(let [data (<== [::subs/monthly-visitors-chart-data lipas-id year])
labels (merge
{:total-count (tr :lipas.visitors/total-count)
:spectators-count (tr :lipas.visitors/spectators-count)}
(localize-months tr))]
[mui/paper {:style {:margin-top "1em"} :elevation 0}
[mui/typography {:variant "h6" :color :secondary}
(tr :lipas.visitors/monthly-visitors-in-year year)]
(if (not-empty data)
[:div {:style {:padding-top "1em"}}
[charts/monthly-chart
{:data data
:labels labels}]]
[mui/typography
(tr :lipas.visitors/not-reported-monthly)])]))
|
[
{
"context": "est-part-*\n (is (= \"easter\" (part-* max-key [\"eedadn\" \"drvtee\" \"eandsr\" \"raavrd\"\n ",
"end": 487,
"score": 0.6145433187484741,
"start": 484,
"tag": "KEY",
"value": "adn"
},
{
"context": "*\n (is (= \"easter\" (part-* max-key [\"eedadn\" \"drvtee\" \"eandsr\" \"raavrd\"\n ",
"end": 496,
"score": 0.504120945930481,
"start": 493,
"tag": "KEY",
"value": "tee"
},
{
"context": " (= \"easter\" (part-* max-key [\"eedadn\" \"drvtee\" \"eandsr\" \"raavrd\"\n \"ate",
"end": 505,
"score": 0.5544806718826294,
"start": 500,
"tag": "KEY",
"value": "andsr"
},
{
"context": "r\" (part-* max-key [\"eedadn\" \"drvtee\" \"eandsr\" \"raavrd\"\n \"atevrs\" \"tsr",
"end": 514,
"score": 0.5508162975311279,
"start": 510,
"tag": "KEY",
"value": "avrd"
}
] | src/aoc/2016/06.clj | callum-oakley/advent-of-code | 2 | (ns aoc.2016.06
(:require
[aoc.vector :refer [transpose]]
[clojure.string :as str]
[clojure.test :refer [deftest is]]))
(defn part-* [opt messages]
(->> (transpose messages)
(map #(key (apply opt val (frequencies %))))
(apply str)))
(defn part-1 []
(->> "input/2016/06" slurp str/split-lines (part-* max-key)))
(defn part-2 []
(->> "input/2016/06" slurp str/split-lines (part-* min-key)))
(deftest test-part-*
(is (= "easter" (part-* max-key ["eedadn" "drvtee" "eandsr" "raavrd"
"atevrs" "tsrnev" "sdttsa" "rasrtv"
"nssdts" "ntnada" "svetve" "tesnvt"
"vntsnd" "vrdear" "dvrsen" "enarar"]))))
| 98029 | (ns aoc.2016.06
(:require
[aoc.vector :refer [transpose]]
[clojure.string :as str]
[clojure.test :refer [deftest is]]))
(defn part-* [opt messages]
(->> (transpose messages)
(map #(key (apply opt val (frequencies %))))
(apply str)))
(defn part-1 []
(->> "input/2016/06" slurp str/split-lines (part-* max-key)))
(defn part-2 []
(->> "input/2016/06" slurp str/split-lines (part-* min-key)))
(deftest test-part-*
(is (= "easter" (part-* max-key ["eed<KEY>" "drv<KEY>" "e<KEY>" "ra<KEY>"
"atevrs" "tsrnev" "sdttsa" "rasrtv"
"nssdts" "ntnada" "svetve" "tesnvt"
"vntsnd" "vrdear" "dvrsen" "enarar"]))))
| true | (ns aoc.2016.06
(:require
[aoc.vector :refer [transpose]]
[clojure.string :as str]
[clojure.test :refer [deftest is]]))
(defn part-* [opt messages]
(->> (transpose messages)
(map #(key (apply opt val (frequencies %))))
(apply str)))
(defn part-1 []
(->> "input/2016/06" slurp str/split-lines (part-* max-key)))
(defn part-2 []
(->> "input/2016/06" slurp str/split-lines (part-* min-key)))
(deftest test-part-*
(is (= "easter" (part-* max-key ["eedPI:KEY:<KEY>END_PI" "drvPI:KEY:<KEY>END_PI" "ePI:KEY:<KEY>END_PI" "raPI:KEY:<KEY>END_PI"
"atevrs" "tsrnev" "sdttsa" "rasrtv"
"nssdts" "ntnada" "svetve" "tesnvt"
"vntsnd" "vrdear" "dvrsen" "enarar"]))))
|
[
{
"context": ";; Copyright (c) Michal Kurťák\n;; All rights reserved.\n(ns ^:no-doc salt.api\n (",
"end": 30,
"score": 0.9998176693916321,
"start": 17,
"tag": "NAME",
"value": "Michal Kurťák"
},
{
"context": "ms {:eauth eauth\n :username username\n :password password}}))\n\n(",
"end": 949,
"score": 0.9920414090156555,
"start": 941,
"tag": "USERNAME",
"value": "username"
},
{
"context": "sername username\n :password password}}))\n\n(defn create-request\n [{:keys [::s/master-u",
"end": 992,
"score": 0.9988697171211243,
"start": 984,
"tag": "PASSWORD",
"value": "password"
}
] | src/salt/api.clj | mkurtak/clj-salt-api | 9 | ;; Copyright (c) Michal Kurťák
;; All rights reserved.
(ns ^:no-doc salt.api
(:require
[clojure.core.async :as a]
[clojure.string :as str]
[salt.core :as s]
[salt.http :as http]
[salt.retry :as retry]))
(def ending-slash #"/$")
(def starting-slash #"^/")
(defn- throw-err
"Simple wrapper that throws exception if e is Throwable, otherwise just return e."
[e]
(if (instance? Throwable e) (throw e) e))
(defn- add-url-path
[url path]
(if (str/blank? path)
url
(str/join "/" [(str/replace url ending-slash "")
(str/replace path starting-slash "")])))
(defn create-login-request
[{:keys [::s/master-url ::s/username ::s/password ::s/eauth]
:or {eauth "pam"}
:as opts}]
(merge opts
{:url (add-url-path master-url "/login")
:method :post
:headers {"Accept" "application/json"}
:form-params {:eauth eauth
:username username
:password password}}))
(defn create-request
[{:keys [::s/master-url :url :method :headers :content-type]
{:keys [:token]} ::s/login-response
:or {method :post content-type :json}
:as opts}]
(merge opts
{:url (add-url-path master-url url)
:method method
:content-type content-type
:headers (merge headers {"Accept" "application/json"
"X-Auth-token" token})}))
(defn create-sse-request
[{:keys [::s/master-url :headers]
{:keys [:token]} ::s/login-response
:as opts}]
(merge opts
{:url (add-url-path master-url "/events")
:method :get
:headers (merge headers {"Accept" "application/json"
"X-Auth-token" token})}))
(defn- parse-return-vector
[{[result] :return :as body}]
(if result
result
(throw (ex-info "Could not parse token" {::s/response-body body}))))
(defn http-request
[req resp-chan]
(retry/with-retry #(http/request req) resp-chan))
(defn login
"Executes login [[salt.http/request]], handles exception, parses body and return new channel with response.
Prepends master-url and appends '/login' to ring request url.
Request is retried with default backoff and retriable?. See [[salt.retry/with-retry]] for more details.
Exception and parsed body is sent with channel and channel is closed afterwards.
Request is aleph ring request with additonal keys:
| Key | Description |
| -------------------------| ------------|
| `::salt.core/master-url` | Base url of salt-master. Its prepended to ring :url
| `::salt.core/username` | Username to be used in salt authetincation if any
| `::salt.core/password` | Password to be used in salt authetincation if any
| `::salt.core/eauth` | Eauth system to be used in salt authentication. Please refer saltstack documentation for available values"
[req]
(http-request
(create-login-request req)
(a/chan 1 (comp
(map throw-err)
(map http/parse-body)
(map parse-return-vector))
identity)))
(defn request
"Executes [[salt.http/request]], handles exception, parses body and return new channel with response.
Prepends master-url to ring request url.
Request is retried with default backoff and retriable?. See [[salt.retry/with-retry]] for more details.
Exception and parsed body is sent with channel and channel is closed afterwards.
Request is aleph ring request with additonal keys:
| Key | Description |
| ------------------------------| ------------|
| `::salt.core/master-url` | Base url of salt-master. Its prepended to ring :url
| `::salt.core/login-response` | Response from [[salt.api/login]]|"
[req]
(http-request
(create-request req)
(a/chan 1 (comp
(map throw-err)
(map http/parse-body))
identity)))
(defn logout
"Executes logout request with [[request]] function."
[req]
(request (assoc req :url "/logout")))
(defn sse
"Executes [[salt.http/request]], handles exception, parses individual SSEs and return new channel emiting SSEs.
Prepends master-url and appends '/events' to ring request url.
Request is retried with default backoff and retriable?. See [[salt.retry/with-retry]] for more details.
If exception occurs, it is written to the channel and channel is closed.
If SSE connection is closed, channel is closed.
Request is aleph ring request with additonal keys
| Key | Description |
| ------------------------------| ------------|
| `::salt.core/master-url` | Base url of salt-master. It is preepended :url
| `::salt.core/login-response` | Response from [[salt.api/login]]"
[req pool-opts sse-buffer-size]
(http/sse (create-sse-request req)
pool-opts
(a/chan sse-buffer-size
(comp
(map throw-err)
(map http/parse-sse))
identity)))
(defn close-sse
[connection]
(http/close-sse connection))
| 12735 | ;; Copyright (c) <NAME>
;; All rights reserved.
(ns ^:no-doc salt.api
(:require
[clojure.core.async :as a]
[clojure.string :as str]
[salt.core :as s]
[salt.http :as http]
[salt.retry :as retry]))
(def ending-slash #"/$")
(def starting-slash #"^/")
(defn- throw-err
"Simple wrapper that throws exception if e is Throwable, otherwise just return e."
[e]
(if (instance? Throwable e) (throw e) e))
(defn- add-url-path
[url path]
(if (str/blank? path)
url
(str/join "/" [(str/replace url ending-slash "")
(str/replace path starting-slash "")])))
(defn create-login-request
[{:keys [::s/master-url ::s/username ::s/password ::s/eauth]
:or {eauth "pam"}
:as opts}]
(merge opts
{:url (add-url-path master-url "/login")
:method :post
:headers {"Accept" "application/json"}
:form-params {:eauth eauth
:username username
:password <PASSWORD>}}))
(defn create-request
[{:keys [::s/master-url :url :method :headers :content-type]
{:keys [:token]} ::s/login-response
:or {method :post content-type :json}
:as opts}]
(merge opts
{:url (add-url-path master-url url)
:method method
:content-type content-type
:headers (merge headers {"Accept" "application/json"
"X-Auth-token" token})}))
(defn create-sse-request
[{:keys [::s/master-url :headers]
{:keys [:token]} ::s/login-response
:as opts}]
(merge opts
{:url (add-url-path master-url "/events")
:method :get
:headers (merge headers {"Accept" "application/json"
"X-Auth-token" token})}))
(defn- parse-return-vector
[{[result] :return :as body}]
(if result
result
(throw (ex-info "Could not parse token" {::s/response-body body}))))
(defn http-request
[req resp-chan]
(retry/with-retry #(http/request req) resp-chan))
(defn login
"Executes login [[salt.http/request]], handles exception, parses body and return new channel with response.
Prepends master-url and appends '/login' to ring request url.
Request is retried with default backoff and retriable?. See [[salt.retry/with-retry]] for more details.
Exception and parsed body is sent with channel and channel is closed afterwards.
Request is aleph ring request with additonal keys:
| Key | Description |
| -------------------------| ------------|
| `::salt.core/master-url` | Base url of salt-master. Its prepended to ring :url
| `::salt.core/username` | Username to be used in salt authetincation if any
| `::salt.core/password` | Password to be used in salt authetincation if any
| `::salt.core/eauth` | Eauth system to be used in salt authentication. Please refer saltstack documentation for available values"
[req]
(http-request
(create-login-request req)
(a/chan 1 (comp
(map throw-err)
(map http/parse-body)
(map parse-return-vector))
identity)))
(defn request
"Executes [[salt.http/request]], handles exception, parses body and return new channel with response.
Prepends master-url to ring request url.
Request is retried with default backoff and retriable?. See [[salt.retry/with-retry]] for more details.
Exception and parsed body is sent with channel and channel is closed afterwards.
Request is aleph ring request with additonal keys:
| Key | Description |
| ------------------------------| ------------|
| `::salt.core/master-url` | Base url of salt-master. Its prepended to ring :url
| `::salt.core/login-response` | Response from [[salt.api/login]]|"
[req]
(http-request
(create-request req)
(a/chan 1 (comp
(map throw-err)
(map http/parse-body))
identity)))
(defn logout
"Executes logout request with [[request]] function."
[req]
(request (assoc req :url "/logout")))
(defn sse
"Executes [[salt.http/request]], handles exception, parses individual SSEs and return new channel emiting SSEs.
Prepends master-url and appends '/events' to ring request url.
Request is retried with default backoff and retriable?. See [[salt.retry/with-retry]] for more details.
If exception occurs, it is written to the channel and channel is closed.
If SSE connection is closed, channel is closed.
Request is aleph ring request with additonal keys
| Key | Description |
| ------------------------------| ------------|
| `::salt.core/master-url` | Base url of salt-master. It is preepended :url
| `::salt.core/login-response` | Response from [[salt.api/login]]"
[req pool-opts sse-buffer-size]
(http/sse (create-sse-request req)
pool-opts
(a/chan sse-buffer-size
(comp
(map throw-err)
(map http/parse-sse))
identity)))
(defn close-sse
[connection]
(http/close-sse connection))
| true | ;; Copyright (c) PI:NAME:<NAME>END_PI
;; All rights reserved.
(ns ^:no-doc salt.api
(:require
[clojure.core.async :as a]
[clojure.string :as str]
[salt.core :as s]
[salt.http :as http]
[salt.retry :as retry]))
(def ending-slash #"/$")
(def starting-slash #"^/")
(defn- throw-err
"Simple wrapper that throws exception if e is Throwable, otherwise just return e."
[e]
(if (instance? Throwable e) (throw e) e))
(defn- add-url-path
[url path]
(if (str/blank? path)
url
(str/join "/" [(str/replace url ending-slash "")
(str/replace path starting-slash "")])))
(defn create-login-request
[{:keys [::s/master-url ::s/username ::s/password ::s/eauth]
:or {eauth "pam"}
:as opts}]
(merge opts
{:url (add-url-path master-url "/login")
:method :post
:headers {"Accept" "application/json"}
:form-params {:eauth eauth
:username username
:password PI:PASSWORD:<PASSWORD>END_PI}}))
(defn create-request
[{:keys [::s/master-url :url :method :headers :content-type]
{:keys [:token]} ::s/login-response
:or {method :post content-type :json}
:as opts}]
(merge opts
{:url (add-url-path master-url url)
:method method
:content-type content-type
:headers (merge headers {"Accept" "application/json"
"X-Auth-token" token})}))
(defn create-sse-request
[{:keys [::s/master-url :headers]
{:keys [:token]} ::s/login-response
:as opts}]
(merge opts
{:url (add-url-path master-url "/events")
:method :get
:headers (merge headers {"Accept" "application/json"
"X-Auth-token" token})}))
(defn- parse-return-vector
[{[result] :return :as body}]
(if result
result
(throw (ex-info "Could not parse token" {::s/response-body body}))))
(defn http-request
[req resp-chan]
(retry/with-retry #(http/request req) resp-chan))
(defn login
"Executes login [[salt.http/request]], handles exception, parses body and return new channel with response.
Prepends master-url and appends '/login' to ring request url.
Request is retried with default backoff and retriable?. See [[salt.retry/with-retry]] for more details.
Exception and parsed body is sent with channel and channel is closed afterwards.
Request is aleph ring request with additonal keys:
| Key | Description |
| -------------------------| ------------|
| `::salt.core/master-url` | Base url of salt-master. Its prepended to ring :url
| `::salt.core/username` | Username to be used in salt authetincation if any
| `::salt.core/password` | Password to be used in salt authetincation if any
| `::salt.core/eauth` | Eauth system to be used in salt authentication. Please refer saltstack documentation for available values"
[req]
(http-request
(create-login-request req)
(a/chan 1 (comp
(map throw-err)
(map http/parse-body)
(map parse-return-vector))
identity)))
(defn request
"Executes [[salt.http/request]], handles exception, parses body and return new channel with response.
Prepends master-url to ring request url.
Request is retried with default backoff and retriable?. See [[salt.retry/with-retry]] for more details.
Exception and parsed body is sent with channel and channel is closed afterwards.
Request is aleph ring request with additonal keys:
| Key | Description |
| ------------------------------| ------------|
| `::salt.core/master-url` | Base url of salt-master. Its prepended to ring :url
| `::salt.core/login-response` | Response from [[salt.api/login]]|"
[req]
(http-request
(create-request req)
(a/chan 1 (comp
(map throw-err)
(map http/parse-body))
identity)))
(defn logout
"Executes logout request with [[request]] function."
[req]
(request (assoc req :url "/logout")))
(defn sse
"Executes [[salt.http/request]], handles exception, parses individual SSEs and return new channel emiting SSEs.
Prepends master-url and appends '/events' to ring request url.
Request is retried with default backoff and retriable?. See [[salt.retry/with-retry]] for more details.
If exception occurs, it is written to the channel and channel is closed.
If SSE connection is closed, channel is closed.
Request is aleph ring request with additonal keys
| Key | Description |
| ------------------------------| ------------|
| `::salt.core/master-url` | Base url of salt-master. It is preepended :url
| `::salt.core/login-response` | Response from [[salt.api/login]]"
[req pool-opts sse-buffer-size]
(http/sse (create-sse-request req)
pool-opts
(a/chan sse-buffer-size
(comp
(map throw-err)
(map http/parse-sse))
identity)))
(defn close-sse
[connection]
(http/close-sse connection))
|
[
{
"context": " double-digits?)]\n (is (valid-password? 111111))\n (is (not (valid-password? 223450)))\n (is",
"end": 595,
"score": 0.9987189769744873,
"start": 589,
"tag": "PASSWORD",
"value": "111111"
},
{
"context": "-password? 111111))\n (is (not (valid-password? 223450)))\n (is (not (valid-password? 123789)))))\n\n(->",
"end": 634,
"score": 0.9984485507011414,
"start": 628,
"tag": "PASSWORD",
"value": "223450"
},
{
"context": "password? 223450)))\n (is (not (valid-password? 123789)))))\n\n(->> (range 235741 706948)\n (filter (ev",
"end": 674,
"score": 0.9983763098716736,
"start": 668,
"tag": "PASSWORD",
"value": "123789"
},
{
"context": "ly-double-digits?)]\n (is (not (valid-password? 111111)))\n (is (not (valid-password? 223450)))\n (i",
"end": 1100,
"score": 0.9976439476013184,
"start": 1094,
"tag": "PASSWORD",
"value": "111111"
},
{
"context": "password? 111111)))\n (is (not (valid-password? 223450)))\n (is (not (valid-password? 123789)))\n (i",
"end": 1140,
"score": 0.9977104067802429,
"start": 1134,
"tag": "PASSWORD",
"value": "223450"
},
{
"context": "password? 223450)))\n (is (not (valid-password? 123789)))\n (is (valid-password? 112233))\n (is (not",
"end": 1180,
"score": 0.9969608187675476,
"start": 1174,
"tag": "PASSWORD",
"value": "123789"
},
{
"context": "alid-password? 123789)))\n (is (valid-password? 112233))\n (is (not (valid-password? 123444)))\n (is",
"end": 1215,
"score": 0.9972819685935974,
"start": 1209,
"tag": "PASSWORD",
"value": "112233"
},
{
"context": "-password? 112233))\n (is (not (valid-password? 123444)))\n (is (valid-password? 111122))\n (is (val",
"end": 1254,
"score": 0.9960463643074036,
"start": 1248,
"tag": "PASSWORD",
"value": "123444"
},
{
"context": "alid-password? 123444)))\n (is (valid-password? 111122))\n (is (valid-password? 122345))\n (is (vali",
"end": 1289,
"score": 0.9974133372306824,
"start": 1283,
"tag": "PASSWORD",
"value": "111122"
},
{
"context": "valid-password? 111122))\n (is (valid-password? 122345))\n (is (valid-password? 113444))))\n\n(->> (rang",
"end": 1323,
"score": 0.9988831877708435,
"start": 1317,
"tag": "PASSWORD",
"value": "122345"
},
{
"context": "valid-password? 122345))\n (is (valid-password? 113444))))\n\n(->> (range 235741 706948)\n (filter (eve",
"end": 1357,
"score": 0.9970526099205017,
"start": 1351,
"tag": "PASSWORD",
"value": "113444"
}
] | clj/src/advent-of-code-2019/day04.clj | fabioyamate/advent-of-code | 0 | (ns advent-of-code-2019.day04
(:use clojure.test)
(:require [clojure.java.io :as io]))
;; Day 4 - Secure Container
;; https://adventofcode.com/2019/day/4
(defn digits
[input]
(seq (str input)))
(defn only-increasing-digits?
;; given the input is too small, doing super naive check
[input]
(= (sort (digits input))
(digits input)))
(defn double-digits?
[input]
(< (count (distinct (digits input)))
6))
(deftest level-1
(let [valid-password? (every-pred only-increasing-digits?
double-digits?)]
(is (valid-password? 111111))
(is (not (valid-password? 223450)))
(is (not (valid-password? 123789)))))
(->> (range 235741 706948)
(filter (every-pred only-increasing-digits?
double-digits?))
count)
;; => 1178
(defn exactly-double-digits?
[input]
(some #(= 2 %)
(vals (frequencies (digits input)))))
(deftest level-2
(let [valid-password? (every-pred only-increasing-digits?
exactly-double-digits?)]
(is (not (valid-password? 111111)))
(is (not (valid-password? 223450)))
(is (not (valid-password? 123789)))
(is (valid-password? 112233))
(is (not (valid-password? 123444)))
(is (valid-password? 111122))
(is (valid-password? 122345))
(is (valid-password? 113444))))
(->> (range 235741 706948)
(filter (every-pred only-increasing-digits?
exactly-double-digits?))
count)
;; => 763
| 29603 | (ns advent-of-code-2019.day04
(:use clojure.test)
(:require [clojure.java.io :as io]))
;; Day 4 - Secure Container
;; https://adventofcode.com/2019/day/4
(defn digits
[input]
(seq (str input)))
(defn only-increasing-digits?
;; given the input is too small, doing super naive check
[input]
(= (sort (digits input))
(digits input)))
(defn double-digits?
[input]
(< (count (distinct (digits input)))
6))
(deftest level-1
(let [valid-password? (every-pred only-increasing-digits?
double-digits?)]
(is (valid-password? <PASSWORD>))
(is (not (valid-password? <PASSWORD>)))
(is (not (valid-password? <PASSWORD>)))))
(->> (range 235741 706948)
(filter (every-pred only-increasing-digits?
double-digits?))
count)
;; => 1178
(defn exactly-double-digits?
[input]
(some #(= 2 %)
(vals (frequencies (digits input)))))
(deftest level-2
(let [valid-password? (every-pred only-increasing-digits?
exactly-double-digits?)]
(is (not (valid-password? <PASSWORD>)))
(is (not (valid-password? <PASSWORD>)))
(is (not (valid-password? <PASSWORD>)))
(is (valid-password? <PASSWORD>))
(is (not (valid-password? <PASSWORD>)))
(is (valid-password? <PASSWORD>))
(is (valid-password? <PASSWORD>))
(is (valid-password? <PASSWORD>))))
(->> (range 235741 706948)
(filter (every-pred only-increasing-digits?
exactly-double-digits?))
count)
;; => 763
| true | (ns advent-of-code-2019.day04
(:use clojure.test)
(:require [clojure.java.io :as io]))
;; Day 4 - Secure Container
;; https://adventofcode.com/2019/day/4
(defn digits
[input]
(seq (str input)))
(defn only-increasing-digits?
;; given the input is too small, doing super naive check
[input]
(= (sort (digits input))
(digits input)))
(defn double-digits?
[input]
(< (count (distinct (digits input)))
6))
(deftest level-1
(let [valid-password? (every-pred only-increasing-digits?
double-digits?)]
(is (valid-password? PI:PASSWORD:<PASSWORD>END_PI))
(is (not (valid-password? PI:PASSWORD:<PASSWORD>END_PI)))
(is (not (valid-password? PI:PASSWORD:<PASSWORD>END_PI)))))
(->> (range 235741 706948)
(filter (every-pred only-increasing-digits?
double-digits?))
count)
;; => 1178
(defn exactly-double-digits?
[input]
(some #(= 2 %)
(vals (frequencies (digits input)))))
(deftest level-2
(let [valid-password? (every-pred only-increasing-digits?
exactly-double-digits?)]
(is (not (valid-password? PI:PASSWORD:<PASSWORD>END_PI)))
(is (not (valid-password? PI:PASSWORD:<PASSWORD>END_PI)))
(is (not (valid-password? PI:PASSWORD:<PASSWORD>END_PI)))
(is (valid-password? PI:PASSWORD:<PASSWORD>END_PI))
(is (not (valid-password? PI:PASSWORD:<PASSWORD>END_PI)))
(is (valid-password? PI:PASSWORD:<PASSWORD>END_PI))
(is (valid-password? PI:PASSWORD:<PASSWORD>END_PI))
(is (valid-password? PI:PASSWORD:<PASSWORD>END_PI))))
(->> (range 235741 706948)
(filter (every-pred only-increasing-digits?
exactly-double-digits?))
count)
;; => 763
|
[
{
"context": ";;A Copyright (c) Michal Kurťák\n;; All rights reserved.\n(ns ^:no-doc salt.client.",
"end": 32,
"score": 0.9998041987419128,
"start": 19,
"tag": "NAME",
"value": "Michal Kurťák"
}
] | src/salt/client/request.clj | mkurtak/clj-salt-api | 9 | ;;A Copyright (c) Michal Kurťák
;; All rights reserved.
(ns ^:no-doc salt.client.request
(:require [clojure.core.async :as a]
[salt.api :as api]
[salt.core :as s]))
(defn create-request
[{:keys [:client :request]}]
(merge (select-keys client [::s/master-url ::s/login-response])
(::s/default-http-request client)
request))
(defn create-login-request
[{:keys [:client]}]
(merge (select-keys client [::s/master-url ::s/username ::s/password ::s/eauth])
(::s/default-http-request client)))
(defn token-valid?
[{{:keys [:token :expire]} ::s/login-response}]
(and token (number? expire) (< (/ (System/currentTimeMillis) 1000) expire)))
(defn handle-validate-token
"If token is valid execute HTTP request,
otherwise execute HTTP request on /login endpoint."
[{:keys [:client] :as op}]
(if (token-valid? client)
(assoc op :command :request :body (create-request op))
(assoc op :command :login :body (create-login-request op))))
(defn- handle-request
[op response]
(if (= :unauthorized (::s/response-category (ex-data response)))
(assoc op
:command :login ;login if unauthorized response received
:body (create-login-request op))
(assoc op :command (if (instance? Throwable response) :error :response)
:body response)))
(defn- handle-login
[{:keys [:client] :as op} login-response]
(if (instance? Throwable login-response)
(assoc op :command :error :body login-response)
(assoc op
:command :swap-login
:client (assoc client ::s/login-response login-response))))
(defn swap-login!
[client-atom {:keys [:client]}]
(swap! client-atom assoc ::s/login-response (::s/login-response client)))
(defn handle-swap-login
[op]
(assoc op :command :request :body (create-request op)))
(defn initial-op
[client-atom req]
{:command :validate :request req :client @client-atom})
(defn handle-response
[{:keys [command] :as op} response]
(try
(case command
:validate (handle-validate-token op)
:login (handle-login op response)
:swap-login (handle-swap-login op)
:request (handle-request op response)
:error nil
:response nil)
(catch Throwable e
(assoc op :command :error :body e))))
(defn request
"Invoke [[salt.api/request]] request and returns channel which deliver the response.
This function logs in user if not already logged in and handles unauthorized exception.
Channel will deliver:
- Parsed salt-api response body
- Exception if error occurs
Channel is closed after response is delivered.
Request will be merged with client default-http-request. See [[salt.client/client]] for more details."
[client-atom req resp-chan]
(a/go
(loop [{:keys [command body] :as op}
(initial-op client-atom req)]
(when command
(->> (case command
:validate nil
:login (a/<! (api/login body))
:swap-login (swap-login! client-atom op)
:request (a/<! (api/request body))
:response (do (a/>! resp-chan body)
(a/close! resp-chan))
:error (do (a/>! resp-chan body)
(a/close! resp-chan)))
(handle-response op)
(recur)))))
resp-chan)
| 120720 | ;;A Copyright (c) <NAME>
;; All rights reserved.
(ns ^:no-doc salt.client.request
(:require [clojure.core.async :as a]
[salt.api :as api]
[salt.core :as s]))
(defn create-request
[{:keys [:client :request]}]
(merge (select-keys client [::s/master-url ::s/login-response])
(::s/default-http-request client)
request))
(defn create-login-request
[{:keys [:client]}]
(merge (select-keys client [::s/master-url ::s/username ::s/password ::s/eauth])
(::s/default-http-request client)))
(defn token-valid?
[{{:keys [:token :expire]} ::s/login-response}]
(and token (number? expire) (< (/ (System/currentTimeMillis) 1000) expire)))
(defn handle-validate-token
"If token is valid execute HTTP request,
otherwise execute HTTP request on /login endpoint."
[{:keys [:client] :as op}]
(if (token-valid? client)
(assoc op :command :request :body (create-request op))
(assoc op :command :login :body (create-login-request op))))
(defn- handle-request
[op response]
(if (= :unauthorized (::s/response-category (ex-data response)))
(assoc op
:command :login ;login if unauthorized response received
:body (create-login-request op))
(assoc op :command (if (instance? Throwable response) :error :response)
:body response)))
(defn- handle-login
[{:keys [:client] :as op} login-response]
(if (instance? Throwable login-response)
(assoc op :command :error :body login-response)
(assoc op
:command :swap-login
:client (assoc client ::s/login-response login-response))))
(defn swap-login!
[client-atom {:keys [:client]}]
(swap! client-atom assoc ::s/login-response (::s/login-response client)))
(defn handle-swap-login
[op]
(assoc op :command :request :body (create-request op)))
(defn initial-op
[client-atom req]
{:command :validate :request req :client @client-atom})
(defn handle-response
[{:keys [command] :as op} response]
(try
(case command
:validate (handle-validate-token op)
:login (handle-login op response)
:swap-login (handle-swap-login op)
:request (handle-request op response)
:error nil
:response nil)
(catch Throwable e
(assoc op :command :error :body e))))
(defn request
"Invoke [[salt.api/request]] request and returns channel which deliver the response.
This function logs in user if not already logged in and handles unauthorized exception.
Channel will deliver:
- Parsed salt-api response body
- Exception if error occurs
Channel is closed after response is delivered.
Request will be merged with client default-http-request. See [[salt.client/client]] for more details."
[client-atom req resp-chan]
(a/go
(loop [{:keys [command body] :as op}
(initial-op client-atom req)]
(when command
(->> (case command
:validate nil
:login (a/<! (api/login body))
:swap-login (swap-login! client-atom op)
:request (a/<! (api/request body))
:response (do (a/>! resp-chan body)
(a/close! resp-chan))
:error (do (a/>! resp-chan body)
(a/close! resp-chan)))
(handle-response op)
(recur)))))
resp-chan)
| true | ;;A Copyright (c) PI:NAME:<NAME>END_PI
;; All rights reserved.
(ns ^:no-doc salt.client.request
(:require [clojure.core.async :as a]
[salt.api :as api]
[salt.core :as s]))
(defn create-request
[{:keys [:client :request]}]
(merge (select-keys client [::s/master-url ::s/login-response])
(::s/default-http-request client)
request))
(defn create-login-request
[{:keys [:client]}]
(merge (select-keys client [::s/master-url ::s/username ::s/password ::s/eauth])
(::s/default-http-request client)))
(defn token-valid?
[{{:keys [:token :expire]} ::s/login-response}]
(and token (number? expire) (< (/ (System/currentTimeMillis) 1000) expire)))
(defn handle-validate-token
"If token is valid execute HTTP request,
otherwise execute HTTP request on /login endpoint."
[{:keys [:client] :as op}]
(if (token-valid? client)
(assoc op :command :request :body (create-request op))
(assoc op :command :login :body (create-login-request op))))
(defn- handle-request
[op response]
(if (= :unauthorized (::s/response-category (ex-data response)))
(assoc op
:command :login ;login if unauthorized response received
:body (create-login-request op))
(assoc op :command (if (instance? Throwable response) :error :response)
:body response)))
(defn- handle-login
[{:keys [:client] :as op} login-response]
(if (instance? Throwable login-response)
(assoc op :command :error :body login-response)
(assoc op
:command :swap-login
:client (assoc client ::s/login-response login-response))))
(defn swap-login!
[client-atom {:keys [:client]}]
(swap! client-atom assoc ::s/login-response (::s/login-response client)))
(defn handle-swap-login
[op]
(assoc op :command :request :body (create-request op)))
(defn initial-op
[client-atom req]
{:command :validate :request req :client @client-atom})
(defn handle-response
[{:keys [command] :as op} response]
(try
(case command
:validate (handle-validate-token op)
:login (handle-login op response)
:swap-login (handle-swap-login op)
:request (handle-request op response)
:error nil
:response nil)
(catch Throwable e
(assoc op :command :error :body e))))
(defn request
"Invoke [[salt.api/request]] request and returns channel which deliver the response.
This function logs in user if not already logged in and handles unauthorized exception.
Channel will deliver:
- Parsed salt-api response body
- Exception if error occurs
Channel is closed after response is delivered.
Request will be merged with client default-http-request. See [[salt.client/client]] for more details."
[client-atom req resp-chan]
(a/go
(loop [{:keys [command body] :as op}
(initial-op client-atom req)]
(when command
(->> (case command
:validate nil
:login (a/<! (api/login body))
:swap-login (swap-login! client-atom op)
:request (a/<! (api/request body))
:response (do (a/>! resp-chan body)
(a/close! resp-chan))
:error (do (a/>! resp-chan body)
(a/close! resp-chan)))
(handle-response op)
(recur)))))
resp-chan)
|
[
{
"context": "omment\n (db/cmd-create-or-update-greeting! {:id \"german\" :template \"Hallo, %s\"} {:connection (:db user/sy",
"end": 2156,
"score": 0.7507357001304626,
"start": 2150,
"tag": "USERNAME",
"value": "german"
},
{
"context": "tion (:db user/system)})\n (db/get-greeting {:id \"german\"} {:connection (:db user/system)})\n )\n",
"end": 2305,
"score": 0.6012059450149536,
"start": 2299,
"tag": "NAME",
"value": "german"
}
] | src/friboo_hello_world_full/api.clj | dryewo/friboo-hello-world-full | 4 | (ns friboo-hello-world-full.api
(:require [org.zalando.stups.friboo.system.http :refer [def-http-component]]
[org.zalando.stups.friboo.ring :refer :all]
[org.zalando.stups.friboo.log :as log]
[org.zalando.stups.friboo.config :refer [require-config]]
[io.sarnowski.swagger1st.util.api :refer [throw-error]]
[friboo-hello-world-full.db :as db]
[ring.util.response :refer :all]))
; define the API component and its dependencies
(def-http-component API "api/api.yaml" [db])
(def default-http-configuration
{:http-port 8080})
(defn throw-ex-info
"Throws `ex-info` for HTTP 500 with error description inside."
[e]
(log/error e (str e))
(throw (ex-info "Internal server error" {:http-code 500 :details (str e)})))
(defmacro wrap-handler
"Common part for every handler function, including content-type-json and nice exception handling."
[& body]
`(content-type-json
(try
~@body
(catch Exception e#
(throw-ex-info e#)))))
(defn get-hello
"Says hello"
[{:keys [name] :as params} request db]
(wrap-handler
(log/warn "Hello called for" name)
(response {:message (str "Hello " name)})))
(defn create-or-update-greeting-template
[{:keys [greeting_id greeting_template] :as params} request db]
(wrap-handler
(db/cmd-create-or-update-greeting!
(merge greeting_template {:id greeting_id})
{:connection db})
{:status 204}))
(defn delete-greeting-template
[{:keys [greeting_id] :as params} request db]
(wrap-handler
(db/cmd-delete-greeting! {:id greeting_id} {:connection db})
{:status 204}))
(defn get-templated-greeting
"Says hello"
[{:keys [name greeting_id] :as params} request db]
(wrap-handler
(log/info "Hello called for " name " with greeting template id " greeting_id)
(if-let [greeting-template (first (db/cmd-get-greeting {:id greeting_id} {:connection db}))]
(response {:message (format (:g_template greeting-template) name)})
(not-found {:message (str "Template not found with ID: " greeting_id)}))))
(comment
(db/cmd-create-or-update-greeting! {:id "german" :template "Hallo, %s"} {:connection (:db user/system)})
(db/get-all-greetings {} {:connection (:db user/system)})
(db/get-greeting {:id "german"} {:connection (:db user/system)})
)
| 73129 | (ns friboo-hello-world-full.api
(:require [org.zalando.stups.friboo.system.http :refer [def-http-component]]
[org.zalando.stups.friboo.ring :refer :all]
[org.zalando.stups.friboo.log :as log]
[org.zalando.stups.friboo.config :refer [require-config]]
[io.sarnowski.swagger1st.util.api :refer [throw-error]]
[friboo-hello-world-full.db :as db]
[ring.util.response :refer :all]))
; define the API component and its dependencies
(def-http-component API "api/api.yaml" [db])
(def default-http-configuration
{:http-port 8080})
(defn throw-ex-info
"Throws `ex-info` for HTTP 500 with error description inside."
[e]
(log/error e (str e))
(throw (ex-info "Internal server error" {:http-code 500 :details (str e)})))
(defmacro wrap-handler
"Common part for every handler function, including content-type-json and nice exception handling."
[& body]
`(content-type-json
(try
~@body
(catch Exception e#
(throw-ex-info e#)))))
(defn get-hello
"Says hello"
[{:keys [name] :as params} request db]
(wrap-handler
(log/warn "Hello called for" name)
(response {:message (str "Hello " name)})))
(defn create-or-update-greeting-template
[{:keys [greeting_id greeting_template] :as params} request db]
(wrap-handler
(db/cmd-create-or-update-greeting!
(merge greeting_template {:id greeting_id})
{:connection db})
{:status 204}))
(defn delete-greeting-template
[{:keys [greeting_id] :as params} request db]
(wrap-handler
(db/cmd-delete-greeting! {:id greeting_id} {:connection db})
{:status 204}))
(defn get-templated-greeting
"Says hello"
[{:keys [name greeting_id] :as params} request db]
(wrap-handler
(log/info "Hello called for " name " with greeting template id " greeting_id)
(if-let [greeting-template (first (db/cmd-get-greeting {:id greeting_id} {:connection db}))]
(response {:message (format (:g_template greeting-template) name)})
(not-found {:message (str "Template not found with ID: " greeting_id)}))))
(comment
(db/cmd-create-or-update-greeting! {:id "german" :template "Hallo, %s"} {:connection (:db user/system)})
(db/get-all-greetings {} {:connection (:db user/system)})
(db/get-greeting {:id "<NAME>"} {:connection (:db user/system)})
)
| true | (ns friboo-hello-world-full.api
(:require [org.zalando.stups.friboo.system.http :refer [def-http-component]]
[org.zalando.stups.friboo.ring :refer :all]
[org.zalando.stups.friboo.log :as log]
[org.zalando.stups.friboo.config :refer [require-config]]
[io.sarnowski.swagger1st.util.api :refer [throw-error]]
[friboo-hello-world-full.db :as db]
[ring.util.response :refer :all]))
; define the API component and its dependencies
(def-http-component API "api/api.yaml" [db])
(def default-http-configuration
{:http-port 8080})
(defn throw-ex-info
"Throws `ex-info` for HTTP 500 with error description inside."
[e]
(log/error e (str e))
(throw (ex-info "Internal server error" {:http-code 500 :details (str e)})))
(defmacro wrap-handler
"Common part for every handler function, including content-type-json and nice exception handling."
[& body]
`(content-type-json
(try
~@body
(catch Exception e#
(throw-ex-info e#)))))
(defn get-hello
"Says hello"
[{:keys [name] :as params} request db]
(wrap-handler
(log/warn "Hello called for" name)
(response {:message (str "Hello " name)})))
(defn create-or-update-greeting-template
[{:keys [greeting_id greeting_template] :as params} request db]
(wrap-handler
(db/cmd-create-or-update-greeting!
(merge greeting_template {:id greeting_id})
{:connection db})
{:status 204}))
(defn delete-greeting-template
[{:keys [greeting_id] :as params} request db]
(wrap-handler
(db/cmd-delete-greeting! {:id greeting_id} {:connection db})
{:status 204}))
(defn get-templated-greeting
"Says hello"
[{:keys [name greeting_id] :as params} request db]
(wrap-handler
(log/info "Hello called for " name " with greeting template id " greeting_id)
(if-let [greeting-template (first (db/cmd-get-greeting {:id greeting_id} {:connection db}))]
(response {:message (format (:g_template greeting-template) name)})
(not-found {:message (str "Template not found with ID: " greeting_id)}))))
(comment
(db/cmd-create-or-update-greeting! {:id "german" :template "Hallo, %s"} {:connection (:db user/system)})
(db/get-all-greetings {} {:connection (:db user/system)})
(db/get-greeting {:id "PI:NAME:<NAME>END_PI"} {:connection (:db user/system)})
)
|
[
{
"context": ":identifiers first :identifier)]\n\n {:first_name firstName\n :oauth_user_id (:id linkedin-user)\n :las",
"end": 2049,
"score": 0.9974932670593262,
"start": 2040,
"tag": "NAME",
"value": "firstName"
},
{
"context": ":oauth_user_id (:id linkedin-user)\n :last_name lastName\n :picture_url picture-url\n :country locat",
"end": 2114,
"score": 0.9988635182380676,
"start": 2106,
"tag": "NAME",
"value": "lastName"
}
] | src/clj/salava/oauth/linkedin.clj | Vilikkki/salava | 0 | (ns salava.oauth.linkedin
(:require [slingshot.slingshot :refer :all]
[clojure.set :refer [rename-keys]]
[clojure.string :refer [upper-case]]
[salava.oauth.db :as d]
[salava.core.countries :refer [all-countries]]
[salava.core.util :refer [get-site-url get-base-path]]))
(def linkedin-login-redirect-path "/oauth/linkedin")
(defn linkedin-access-token [ctx code redirect-path]
(let [app-id (get-in ctx [:config :oauth :linkedin :app-id])
app-secret (get-in ctx [:config :oauth :linkedin :app-secret])
redirect-url (str (get-site-url ctx) (get-base-path ctx) redirect-path)
opts {:content-type :x-www-form-urlencoded
:form-params {:code code
:client_id app-id
:client_secret app-secret
:redirect_uri redirect-url
:grant_type "authorization_code"}}]
(d/access-token :post "https://www.linkedin.com/oauth/v2/accessToken" opts)
#_(d/access-token :post "https://www.linkedin.com/uas/oauth2/accessToken" opts)))
(defn parse-linkedin-user [ctx linkedin-user]
(let [;location (or (get-in linkedin-user [:location :country :code]) (get-in ctx [:config :user :default-country]))
;language (get-in ctx [:config :user :default-language])
user-locale (when (= (get-in linkedin-user [:firstName :preferredLocale]) (get-in linkedin-user [:lastName :preferredLocale]))
(get-in linkedin-user [:firstName :preferredLocale] nil))
location (get-in ctx [:config :user :default-country])
language (get user-locale :language (get-in ctx [:config :user :default-language]))
firstName (-> linkedin-user :firstName :localized vals first)
lastName (-> linkedin-user :lastName :localized vals first)
picture-url (some-> (get-in linkedin-user [:profilePicture (keyword "displayImage~") :elements]) first :identifiers first :identifier)]
{:first_name firstName
:oauth_user_id (:id linkedin-user)
:last_name lastName
:picture_url picture-url
:country location
:language language
:email (:email linkedin-user)}))
(defn linkedin-login [ctx code state current-user-id error]
(try+
(if (or error (not (and code state)))
(throw+ "oauth/Unexpectederroroccured"))
(let [access-token (linkedin-access-token ctx code linkedin-login-redirect-path)
linkedin-user (d/oauth-user ctx "https://api.linkedin.com/v2/me?projection=(id,firstName,lastName,profilePicture(displayImage~:playableStreams))" {:oauth-token access-token} parse-linkedin-user) #_(d/oauth-user ctx "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,picture-url,email-address,location)?format=json" {:oauth-token access-token} parse-linkedin-user)
email-handle (keyword "handle~")
email (some-> (d/oauth-request :get "https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))" {:oauth-token access-token}) :elements first email-handle :emailAddress)
user-id (d/get-or-create-user ctx "linkedin" (assoc linkedin-user :email email) current-user-id)]
(do
(d/update-user-last_login ctx user-id)
{:status "success" :user-id user-id}))
(catch Object _
{:status "error" :message _})))
(defn linkedin-deauthorize [ctx current-user-id]
(try+
(d/remove-oauth-user ctx current-user-id "linkedin")
{:status "success"}
(catch Object _
{:status "error" :message _})))
| 28089 | (ns salava.oauth.linkedin
(:require [slingshot.slingshot :refer :all]
[clojure.set :refer [rename-keys]]
[clojure.string :refer [upper-case]]
[salava.oauth.db :as d]
[salava.core.countries :refer [all-countries]]
[salava.core.util :refer [get-site-url get-base-path]]))
(def linkedin-login-redirect-path "/oauth/linkedin")
(defn linkedin-access-token [ctx code redirect-path]
(let [app-id (get-in ctx [:config :oauth :linkedin :app-id])
app-secret (get-in ctx [:config :oauth :linkedin :app-secret])
redirect-url (str (get-site-url ctx) (get-base-path ctx) redirect-path)
opts {:content-type :x-www-form-urlencoded
:form-params {:code code
:client_id app-id
:client_secret app-secret
:redirect_uri redirect-url
:grant_type "authorization_code"}}]
(d/access-token :post "https://www.linkedin.com/oauth/v2/accessToken" opts)
#_(d/access-token :post "https://www.linkedin.com/uas/oauth2/accessToken" opts)))
(defn parse-linkedin-user [ctx linkedin-user]
(let [;location (or (get-in linkedin-user [:location :country :code]) (get-in ctx [:config :user :default-country]))
;language (get-in ctx [:config :user :default-language])
user-locale (when (= (get-in linkedin-user [:firstName :preferredLocale]) (get-in linkedin-user [:lastName :preferredLocale]))
(get-in linkedin-user [:firstName :preferredLocale] nil))
location (get-in ctx [:config :user :default-country])
language (get user-locale :language (get-in ctx [:config :user :default-language]))
firstName (-> linkedin-user :firstName :localized vals first)
lastName (-> linkedin-user :lastName :localized vals first)
picture-url (some-> (get-in linkedin-user [:profilePicture (keyword "displayImage~") :elements]) first :identifiers first :identifier)]
{:first_name <NAME>
:oauth_user_id (:id linkedin-user)
:last_name <NAME>
:picture_url picture-url
:country location
:language language
:email (:email linkedin-user)}))
(defn linkedin-login [ctx code state current-user-id error]
(try+
(if (or error (not (and code state)))
(throw+ "oauth/Unexpectederroroccured"))
(let [access-token (linkedin-access-token ctx code linkedin-login-redirect-path)
linkedin-user (d/oauth-user ctx "https://api.linkedin.com/v2/me?projection=(id,firstName,lastName,profilePicture(displayImage~:playableStreams))" {:oauth-token access-token} parse-linkedin-user) #_(d/oauth-user ctx "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,picture-url,email-address,location)?format=json" {:oauth-token access-token} parse-linkedin-user)
email-handle (keyword "handle~")
email (some-> (d/oauth-request :get "https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))" {:oauth-token access-token}) :elements first email-handle :emailAddress)
user-id (d/get-or-create-user ctx "linkedin" (assoc linkedin-user :email email) current-user-id)]
(do
(d/update-user-last_login ctx user-id)
{:status "success" :user-id user-id}))
(catch Object _
{:status "error" :message _})))
(defn linkedin-deauthorize [ctx current-user-id]
(try+
(d/remove-oauth-user ctx current-user-id "linkedin")
{:status "success"}
(catch Object _
{:status "error" :message _})))
| true | (ns salava.oauth.linkedin
(:require [slingshot.slingshot :refer :all]
[clojure.set :refer [rename-keys]]
[clojure.string :refer [upper-case]]
[salava.oauth.db :as d]
[salava.core.countries :refer [all-countries]]
[salava.core.util :refer [get-site-url get-base-path]]))
(def linkedin-login-redirect-path "/oauth/linkedin")
(defn linkedin-access-token [ctx code redirect-path]
(let [app-id (get-in ctx [:config :oauth :linkedin :app-id])
app-secret (get-in ctx [:config :oauth :linkedin :app-secret])
redirect-url (str (get-site-url ctx) (get-base-path ctx) redirect-path)
opts {:content-type :x-www-form-urlencoded
:form-params {:code code
:client_id app-id
:client_secret app-secret
:redirect_uri redirect-url
:grant_type "authorization_code"}}]
(d/access-token :post "https://www.linkedin.com/oauth/v2/accessToken" opts)
#_(d/access-token :post "https://www.linkedin.com/uas/oauth2/accessToken" opts)))
(defn parse-linkedin-user [ctx linkedin-user]
(let [;location (or (get-in linkedin-user [:location :country :code]) (get-in ctx [:config :user :default-country]))
;language (get-in ctx [:config :user :default-language])
user-locale (when (= (get-in linkedin-user [:firstName :preferredLocale]) (get-in linkedin-user [:lastName :preferredLocale]))
(get-in linkedin-user [:firstName :preferredLocale] nil))
location (get-in ctx [:config :user :default-country])
language (get user-locale :language (get-in ctx [:config :user :default-language]))
firstName (-> linkedin-user :firstName :localized vals first)
lastName (-> linkedin-user :lastName :localized vals first)
picture-url (some-> (get-in linkedin-user [:profilePicture (keyword "displayImage~") :elements]) first :identifiers first :identifier)]
{:first_name PI:NAME:<NAME>END_PI
:oauth_user_id (:id linkedin-user)
:last_name PI:NAME:<NAME>END_PI
:picture_url picture-url
:country location
:language language
:email (:email linkedin-user)}))
(defn linkedin-login [ctx code state current-user-id error]
(try+
(if (or error (not (and code state)))
(throw+ "oauth/Unexpectederroroccured"))
(let [access-token (linkedin-access-token ctx code linkedin-login-redirect-path)
linkedin-user (d/oauth-user ctx "https://api.linkedin.com/v2/me?projection=(id,firstName,lastName,profilePicture(displayImage~:playableStreams))" {:oauth-token access-token} parse-linkedin-user) #_(d/oauth-user ctx "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,picture-url,email-address,location)?format=json" {:oauth-token access-token} parse-linkedin-user)
email-handle (keyword "handle~")
email (some-> (d/oauth-request :get "https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))" {:oauth-token access-token}) :elements first email-handle :emailAddress)
user-id (d/get-or-create-user ctx "linkedin" (assoc linkedin-user :email email) current-user-id)]
(do
(d/update-user-last_login ctx user-id)
{:status "success" :user-id user-id}))
(catch Object _
{:status "error" :message _})))
(defn linkedin-deauthorize [ctx current-user-id]
(try+
(d/remove-oauth-user ctx current-user-id "linkedin")
{:status "success"}
(catch Object _
{:status "error" :message _})))
|
[
{
"context": "ription and validation\"\n :url \"http://github.com/plumatic/schema\"\n :license {:name \"Eclipse Public License",
"end": 160,
"score": 0.9995445609092712,
"start": 152,
"tag": "USERNAME",
"value": "plumatic"
},
{
"context": "uild \"1.0.5\"]\n [com.cemerick/clojurescript.test \"0.3.1\"]]\n :",
"end": 835,
"score": 0.5302759408950806,
"start": 829,
"tag": "USERNAME",
"value": "merick"
},
{
"context": "% \"x\")}\n :src-dir-uri \"http://github.com/plumatic/schema/blob/master/\"\n :src-linenum-ancho",
"end": 4080,
"score": 0.9740643501281738,
"start": 4072,
"tag": "USERNAME",
"value": "plumatic"
},
{
"context": "linenum-anchor-prefix \"L\"}\n\n :signing {:gpg-key \"66E0BF75\"})\n",
"end": 4175,
"score": 0.9989456534385681,
"start": 4167,
"tag": "KEY",
"value": "66E0BF75"
}
] | server/target/META-INF/leiningen/prismatic/schema/project.clj | OctavioBR/healthcheck | 0 | (defproject prismatic/schema "1.1.3"
:description "Clojure(Script) library for declarative data description and validation"
:url "http://github.com/plumatic/schema"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:profiles {:dev {:dependencies [[org.clojure/clojure "1.7.0"]
[org.clojure/clojurescript "0.0-2760"]
[org.clojure/tools.nrepl "0.2.5"]
[org.clojure/test.check "0.9.0"]
[potemkin "0.4.1"]]
:plugins [[com.keminglabs/cljx "0.6.0" :exclusions [org.clojure/clojure]]
[codox "0.8.8"]
[lein-cljsbuild "1.0.5"]
[com.cemerick/clojurescript.test "0.3.1"]]
:cljx {:builds [{:source-paths ["src/cljx"]
:output-path "target/generated/src/clj"
:rules :clj}
{:source-paths ["src/cljx"]
:output-path "target/generated/src/cljs"
:rules :cljs}
{:source-paths ["test/cljx"]
:output-path "target/generated/test/clj"
:rules :clj}
{:source-paths ["test/cljx"]
:output-path "target/generated/test/cljs"
:rules :cljs}]}}
:1.8 {:dependencies [[org.clojure/clojure "1.8.0"] [org.clojure/clojurescript "0.0-3308"]]}
:1.9 {:dependencies [[org.clojure/clojure "1.9.0-alpha5"] [org.clojure/clojurescript "0.0-3308"]]}}
:aliases {"all" ["with-profile" "dev:dev,1.8:dev,1.9"]
"deploy" ["do" "clean," "cljx" "once," "deploy" "clojars"]
"test" ["do" "clean," "cljx" "once," "test," "with-profile" "dev" "cljsbuild" "test"]}
:jar-exclusions [#"\.cljx|\.swp|\.swo|\.DS_Store"]
:lein-release {:deploy-via :shell
:shell ["lein" "deploy"]}
:auto-clean false
:source-paths ["target/generated/src/clj" "src/clj"]
:resource-paths ["target/generated/src/cljs"]
:test-paths ["target/generated/test/clj" "test/clj"]
:cljsbuild {:test-commands {"unit" ["phantomjs" :runner
"this.literal_js_was_evaluated=true"
"target/unit-test.js"]
"unit-no-assert" ["phantomjs" :runner
"this.literal_js_was_evaluated=true"
"target/unit-test-no-assert.js"]}
:builds
{:dev {:source-paths ["src/clj" "target/generated/src/cljs"]
:compiler {:output-to "target/main.js"
:optimizations :whitespace
:pretty-print true}}
:test {:source-paths ["src/clj" "test/clj"
"target/generated/src/cljs"
"target/generated/test/cljs"]
:compiler {:output-to "target/unit-test.js"
:optimizations :whitespace
:pretty-print true}}
:test-no-assert {:source-paths ["src/clj" "test/clj"
"target/generated/src/cljs"
"target/generated/test/cljs"]
:assert false
:compiler {:output-to "target/unit-test-no-assert.js"
:optimizations :whitespace
:pretty-print true}}}}
:codox {:src-uri-mapping {#"target/generated/src/clj" #(str "src/cljx/" % "x")}
:src-dir-uri "http://github.com/plumatic/schema/blob/master/"
:src-linenum-anchor-prefix "L"}
:signing {:gpg-key "66E0BF75"})
| 116799 | (defproject prismatic/schema "1.1.3"
:description "Clojure(Script) library for declarative data description and validation"
:url "http://github.com/plumatic/schema"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:profiles {:dev {:dependencies [[org.clojure/clojure "1.7.0"]
[org.clojure/clojurescript "0.0-2760"]
[org.clojure/tools.nrepl "0.2.5"]
[org.clojure/test.check "0.9.0"]
[potemkin "0.4.1"]]
:plugins [[com.keminglabs/cljx "0.6.0" :exclusions [org.clojure/clojure]]
[codox "0.8.8"]
[lein-cljsbuild "1.0.5"]
[com.cemerick/clojurescript.test "0.3.1"]]
:cljx {:builds [{:source-paths ["src/cljx"]
:output-path "target/generated/src/clj"
:rules :clj}
{:source-paths ["src/cljx"]
:output-path "target/generated/src/cljs"
:rules :cljs}
{:source-paths ["test/cljx"]
:output-path "target/generated/test/clj"
:rules :clj}
{:source-paths ["test/cljx"]
:output-path "target/generated/test/cljs"
:rules :cljs}]}}
:1.8 {:dependencies [[org.clojure/clojure "1.8.0"] [org.clojure/clojurescript "0.0-3308"]]}
:1.9 {:dependencies [[org.clojure/clojure "1.9.0-alpha5"] [org.clojure/clojurescript "0.0-3308"]]}}
:aliases {"all" ["with-profile" "dev:dev,1.8:dev,1.9"]
"deploy" ["do" "clean," "cljx" "once," "deploy" "clojars"]
"test" ["do" "clean," "cljx" "once," "test," "with-profile" "dev" "cljsbuild" "test"]}
:jar-exclusions [#"\.cljx|\.swp|\.swo|\.DS_Store"]
:lein-release {:deploy-via :shell
:shell ["lein" "deploy"]}
:auto-clean false
:source-paths ["target/generated/src/clj" "src/clj"]
:resource-paths ["target/generated/src/cljs"]
:test-paths ["target/generated/test/clj" "test/clj"]
:cljsbuild {:test-commands {"unit" ["phantomjs" :runner
"this.literal_js_was_evaluated=true"
"target/unit-test.js"]
"unit-no-assert" ["phantomjs" :runner
"this.literal_js_was_evaluated=true"
"target/unit-test-no-assert.js"]}
:builds
{:dev {:source-paths ["src/clj" "target/generated/src/cljs"]
:compiler {:output-to "target/main.js"
:optimizations :whitespace
:pretty-print true}}
:test {:source-paths ["src/clj" "test/clj"
"target/generated/src/cljs"
"target/generated/test/cljs"]
:compiler {:output-to "target/unit-test.js"
:optimizations :whitespace
:pretty-print true}}
:test-no-assert {:source-paths ["src/clj" "test/clj"
"target/generated/src/cljs"
"target/generated/test/cljs"]
:assert false
:compiler {:output-to "target/unit-test-no-assert.js"
:optimizations :whitespace
:pretty-print true}}}}
:codox {:src-uri-mapping {#"target/generated/src/clj" #(str "src/cljx/" % "x")}
:src-dir-uri "http://github.com/plumatic/schema/blob/master/"
:src-linenum-anchor-prefix "L"}
:signing {:gpg-key "<KEY>"})
| true | (defproject prismatic/schema "1.1.3"
:description "Clojure(Script) library for declarative data description and validation"
:url "http://github.com/plumatic/schema"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:profiles {:dev {:dependencies [[org.clojure/clojure "1.7.0"]
[org.clojure/clojurescript "0.0-2760"]
[org.clojure/tools.nrepl "0.2.5"]
[org.clojure/test.check "0.9.0"]
[potemkin "0.4.1"]]
:plugins [[com.keminglabs/cljx "0.6.0" :exclusions [org.clojure/clojure]]
[codox "0.8.8"]
[lein-cljsbuild "1.0.5"]
[com.cemerick/clojurescript.test "0.3.1"]]
:cljx {:builds [{:source-paths ["src/cljx"]
:output-path "target/generated/src/clj"
:rules :clj}
{:source-paths ["src/cljx"]
:output-path "target/generated/src/cljs"
:rules :cljs}
{:source-paths ["test/cljx"]
:output-path "target/generated/test/clj"
:rules :clj}
{:source-paths ["test/cljx"]
:output-path "target/generated/test/cljs"
:rules :cljs}]}}
:1.8 {:dependencies [[org.clojure/clojure "1.8.0"] [org.clojure/clojurescript "0.0-3308"]]}
:1.9 {:dependencies [[org.clojure/clojure "1.9.0-alpha5"] [org.clojure/clojurescript "0.0-3308"]]}}
:aliases {"all" ["with-profile" "dev:dev,1.8:dev,1.9"]
"deploy" ["do" "clean," "cljx" "once," "deploy" "clojars"]
"test" ["do" "clean," "cljx" "once," "test," "with-profile" "dev" "cljsbuild" "test"]}
:jar-exclusions [#"\.cljx|\.swp|\.swo|\.DS_Store"]
:lein-release {:deploy-via :shell
:shell ["lein" "deploy"]}
:auto-clean false
:source-paths ["target/generated/src/clj" "src/clj"]
:resource-paths ["target/generated/src/cljs"]
:test-paths ["target/generated/test/clj" "test/clj"]
:cljsbuild {:test-commands {"unit" ["phantomjs" :runner
"this.literal_js_was_evaluated=true"
"target/unit-test.js"]
"unit-no-assert" ["phantomjs" :runner
"this.literal_js_was_evaluated=true"
"target/unit-test-no-assert.js"]}
:builds
{:dev {:source-paths ["src/clj" "target/generated/src/cljs"]
:compiler {:output-to "target/main.js"
:optimizations :whitespace
:pretty-print true}}
:test {:source-paths ["src/clj" "test/clj"
"target/generated/src/cljs"
"target/generated/test/cljs"]
:compiler {:output-to "target/unit-test.js"
:optimizations :whitespace
:pretty-print true}}
:test-no-assert {:source-paths ["src/clj" "test/clj"
"target/generated/src/cljs"
"target/generated/test/cljs"]
:assert false
:compiler {:output-to "target/unit-test-no-assert.js"
:optimizations :whitespace
:pretty-print true}}}}
:codox {:src-uri-mapping {#"target/generated/src/clj" #(str "src/cljx/" % "x")}
:src-dir-uri "http://github.com/plumatic/schema/blob/master/"
:src-linenum-anchor-prefix "L"}
:signing {:gpg-key "PI:KEY:<KEY>END_PI"})
|
[
{
"context": "g\"\n (is (= [{:color :green\n :name \"the name\"\n :message nil}]\n (fir",
"end": 1461,
"score": 0.581275224685669,
"start": 1458,
"tag": "NAME",
"value": "the"
},
{
"context": "r\"\n (is (= [{:color :green\n :name \"the name\"\n :message nil}]\n (fir",
"end": 3676,
"score": 0.506145179271698,
"start": 3673,
"tag": "NAME",
"value": "the"
},
{
"context": " (-> (sut/components {:jobs [{:name \"the name\"\n :s",
"end": 5255,
"score": 0.8357968926429749,
"start": 5247,
"tag": "NAME",
"value": "the name"
},
{
"context": " (is (nil? (-> (sut/components {:jobs [{:name \"the name\"\n :stat",
"end": 5915,
"score": 0.888326108455658,
"start": 5907,
"tag": "NAME",
"value": "the name"
}
] | test/greenyet/parse_test.clj | galeksandrp/greenyet | 10 | (ns greenyet.parse-test
(:require [greenyet.parse :as sut]
[clojure.test :refer :all]))
(defn- first-non-nil-message [result]
(some->> result
second
flatten
(remove nil?)
first))
(deftest test-components
(testing "should accept simple config with key only"
(is (= [{:color :green
:name "jobs 0"
:message nil}]
(first (sut/components {:jobs [{:color "green"}]}
{:components "jobs"})))))
(testing "should return warning if components not found"
(is (re-find #"read components.+components"
(-> (sut/components {}
{:components "components"})
first-non-nil-message))))
(testing "should return warning if components not found for json-path"
(is (re-find #"read components.+\$\.components"
(-> (sut/components {}
{:components {:json-path "$.components"}})
first-non-nil-message))))
(testing "should return warning if match is not a list"
(is (re-find #"List expected.+components.+'jobs'"
(-> (sut/components {:jobs "a_string"}
{:components "jobs"})
first-non-nil-message))))
(testing "should return components for complex config"
(is (= [{:color :green
:name "the name"
:message nil}]
(first (sut/components {:jobs [{:the_name "the name"
:status "green"}]}
{:components {:json-path "$.jobs"
:name "the_name"
:color "status"}})))))
(testing "should return warning if match is not a list for json-path"
(is (re-find #"List expected.+components.+'\{:json-path \"\$\.int\"\}'"
(-> (sut/components {:int 1}
{:components {:json-path "$.int"}})
first-non-nil-message))))
(testing "should assume key path as default for name for json-path"
(is (= [{:color :green
:name "jobs 0"
:message nil}]
(first (sut/components {:jobs [{:status "green"}]}
{:components {:json-path "$.jobs"
:color "status"}})))))
(testing "should assume key path as default for name for json-path with multiple individual matches"
(is (= [{:color :green
:name "jobs 0"
:message nil}]
(first (sut/components {:jobs [{:status "green"}]}
{:components {:json-path "$.jobs[*]"
:color "status"}})))))
(testing "should assume key path as default for name for json-path with map structure"
(is (= [{:color :red
:name "jobs one"
:message nil}]
(first (sut/components {:jobs {:one {:color "red"}}}
{:components "jobs"})))))
(testing "should assume key path as default for name for json-path with map structure with json-path"
(is (= [{:color :green
:name "jobs one"
:message nil}]
(first (sut/components {:jobs {:one {:status "green"}}}
{:components {:json-path "$.jobs"
:color "status"}})))))
(testing "should assume default for color"
(is (= [{:color :green
:name "the name"
:message nil}]
(first (sut/components {:jobs [{:the_name "the name"
:color "green"}]}
{:components {:json-path "$.jobs"
:name "the_name"}})))))
(testing "should return warning if message is configured but missing"
(is (re-find #"component message.+'message'"
(-> (sut/components {:jobs [{:the_name "the name"
:status "green"}]}
{:components {:json-path "$.jobs"
:name "the_name"
:color "status"
:message "message"}})
first-non-nil-message))))
(testing "should accept null values"
(is (nil? (-> (sut/components {:jobs [{:the_name "the name"
:status "green"
:message nil}]}
{:components {:json-path "$.jobs"
:name "the_name"
:color "status"
:message "message"}})
first-non-nil-message))))
(testing "should call out default color config on error"
(is (re-find #"component color.+'color'"
(-> (sut/components {:jobs [{:name "the name"
:status "green"}]}
{:components "jobs"})
first-non-nil-message))))
(testing "should call out default name config on error"
(is (re-find #"component name.+'the_name'"
(-> (sut/components {:jobs [{:color "green"}]}
{:components {:json-path "$.jobs"
:name "the_name"}})
first-non-nil-message))))
(testing "should correctly extract complex color with green-value"
(is (nil? (-> (sut/components {:jobs [{:name "the name"
:status false}]}
{:components {:json-path "$.jobs"
:color {:json-path "$.status"
:green-value true}}})
first-non-nil-message)))))
(deftest test-message
(testing "should return message"
(is (= "the_message"
(first (sut/message {:text "the_message"}
{:message "text"})))))
(testing "should return warning if message is configured but missing"
(is (re-find #"message.+'text'"
(-> (sut/message {}
{:message "text"})
second))))
(testing "should accept null values"
(is (nil? (-> (sut/message {:text nil}
{:message "text"})
second)))))
(deftest test-package-version
(testing "should return package-version"
(is (= "component-1.2.3"
(first (sut/package-version {:version "component-1.2.3"}
{:package-version "version"})))))
(testing "should return warning if package-version is configured but missing"
(is (re-find #"package-version.+'version'"
(-> (sut/package-version {}
{:package-version "version"})
second))))
(testing "should return warning if package-version is null"
(is (re-find #"package-version.+'version'"
(-> (sut/package-version {:version nil}
{:package-version "version"})
second))))
(testing "should be optional"
(is (nil? (-> (sut/package-version {}
{})
second)))))
| 55044 | (ns greenyet.parse-test
(:require [greenyet.parse :as sut]
[clojure.test :refer :all]))
(defn- first-non-nil-message [result]
(some->> result
second
flatten
(remove nil?)
first))
(deftest test-components
(testing "should accept simple config with key only"
(is (= [{:color :green
:name "jobs 0"
:message nil}]
(first (sut/components {:jobs [{:color "green"}]}
{:components "jobs"})))))
(testing "should return warning if components not found"
(is (re-find #"read components.+components"
(-> (sut/components {}
{:components "components"})
first-non-nil-message))))
(testing "should return warning if components not found for json-path"
(is (re-find #"read components.+\$\.components"
(-> (sut/components {}
{:components {:json-path "$.components"}})
first-non-nil-message))))
(testing "should return warning if match is not a list"
(is (re-find #"List expected.+components.+'jobs'"
(-> (sut/components {:jobs "a_string"}
{:components "jobs"})
first-non-nil-message))))
(testing "should return components for complex config"
(is (= [{:color :green
:name "<NAME> name"
:message nil}]
(first (sut/components {:jobs [{:the_name "the name"
:status "green"}]}
{:components {:json-path "$.jobs"
:name "the_name"
:color "status"}})))))
(testing "should return warning if match is not a list for json-path"
(is (re-find #"List expected.+components.+'\{:json-path \"\$\.int\"\}'"
(-> (sut/components {:int 1}
{:components {:json-path "$.int"}})
first-non-nil-message))))
(testing "should assume key path as default for name for json-path"
(is (= [{:color :green
:name "jobs 0"
:message nil}]
(first (sut/components {:jobs [{:status "green"}]}
{:components {:json-path "$.jobs"
:color "status"}})))))
(testing "should assume key path as default for name for json-path with multiple individual matches"
(is (= [{:color :green
:name "jobs 0"
:message nil}]
(first (sut/components {:jobs [{:status "green"}]}
{:components {:json-path "$.jobs[*]"
:color "status"}})))))
(testing "should assume key path as default for name for json-path with map structure"
(is (= [{:color :red
:name "jobs one"
:message nil}]
(first (sut/components {:jobs {:one {:color "red"}}}
{:components "jobs"})))))
(testing "should assume key path as default for name for json-path with map structure with json-path"
(is (= [{:color :green
:name "jobs one"
:message nil}]
(first (sut/components {:jobs {:one {:status "green"}}}
{:components {:json-path "$.jobs"
:color "status"}})))))
(testing "should assume default for color"
(is (= [{:color :green
:name "<NAME> name"
:message nil}]
(first (sut/components {:jobs [{:the_name "the name"
:color "green"}]}
{:components {:json-path "$.jobs"
:name "the_name"}})))))
(testing "should return warning if message is configured but missing"
(is (re-find #"component message.+'message'"
(-> (sut/components {:jobs [{:the_name "the name"
:status "green"}]}
{:components {:json-path "$.jobs"
:name "the_name"
:color "status"
:message "message"}})
first-non-nil-message))))
(testing "should accept null values"
(is (nil? (-> (sut/components {:jobs [{:the_name "the name"
:status "green"
:message nil}]}
{:components {:json-path "$.jobs"
:name "the_name"
:color "status"
:message "message"}})
first-non-nil-message))))
(testing "should call out default color config on error"
(is (re-find #"component color.+'color'"
(-> (sut/components {:jobs [{:name "<NAME>"
:status "green"}]}
{:components "jobs"})
first-non-nil-message))))
(testing "should call out default name config on error"
(is (re-find #"component name.+'the_name'"
(-> (sut/components {:jobs [{:color "green"}]}
{:components {:json-path "$.jobs"
:name "the_name"}})
first-non-nil-message))))
(testing "should correctly extract complex color with green-value"
(is (nil? (-> (sut/components {:jobs [{:name "<NAME>"
:status false}]}
{:components {:json-path "$.jobs"
:color {:json-path "$.status"
:green-value true}}})
first-non-nil-message)))))
(deftest test-message
(testing "should return message"
(is (= "the_message"
(first (sut/message {:text "the_message"}
{:message "text"})))))
(testing "should return warning if message is configured but missing"
(is (re-find #"message.+'text'"
(-> (sut/message {}
{:message "text"})
second))))
(testing "should accept null values"
(is (nil? (-> (sut/message {:text nil}
{:message "text"})
second)))))
(deftest test-package-version
(testing "should return package-version"
(is (= "component-1.2.3"
(first (sut/package-version {:version "component-1.2.3"}
{:package-version "version"})))))
(testing "should return warning if package-version is configured but missing"
(is (re-find #"package-version.+'version'"
(-> (sut/package-version {}
{:package-version "version"})
second))))
(testing "should return warning if package-version is null"
(is (re-find #"package-version.+'version'"
(-> (sut/package-version {:version nil}
{:package-version "version"})
second))))
(testing "should be optional"
(is (nil? (-> (sut/package-version {}
{})
second)))))
| true | (ns greenyet.parse-test
(:require [greenyet.parse :as sut]
[clojure.test :refer :all]))
(defn- first-non-nil-message [result]
(some->> result
second
flatten
(remove nil?)
first))
(deftest test-components
(testing "should accept simple config with key only"
(is (= [{:color :green
:name "jobs 0"
:message nil}]
(first (sut/components {:jobs [{:color "green"}]}
{:components "jobs"})))))
(testing "should return warning if components not found"
(is (re-find #"read components.+components"
(-> (sut/components {}
{:components "components"})
first-non-nil-message))))
(testing "should return warning if components not found for json-path"
(is (re-find #"read components.+\$\.components"
(-> (sut/components {}
{:components {:json-path "$.components"}})
first-non-nil-message))))
(testing "should return warning if match is not a list"
(is (re-find #"List expected.+components.+'jobs'"
(-> (sut/components {:jobs "a_string"}
{:components "jobs"})
first-non-nil-message))))
(testing "should return components for complex config"
(is (= [{:color :green
:name "PI:NAME:<NAME>END_PI name"
:message nil}]
(first (sut/components {:jobs [{:the_name "the name"
:status "green"}]}
{:components {:json-path "$.jobs"
:name "the_name"
:color "status"}})))))
(testing "should return warning if match is not a list for json-path"
(is (re-find #"List expected.+components.+'\{:json-path \"\$\.int\"\}'"
(-> (sut/components {:int 1}
{:components {:json-path "$.int"}})
first-non-nil-message))))
(testing "should assume key path as default for name for json-path"
(is (= [{:color :green
:name "jobs 0"
:message nil}]
(first (sut/components {:jobs [{:status "green"}]}
{:components {:json-path "$.jobs"
:color "status"}})))))
(testing "should assume key path as default for name for json-path with multiple individual matches"
(is (= [{:color :green
:name "jobs 0"
:message nil}]
(first (sut/components {:jobs [{:status "green"}]}
{:components {:json-path "$.jobs[*]"
:color "status"}})))))
(testing "should assume key path as default for name for json-path with map structure"
(is (= [{:color :red
:name "jobs one"
:message nil}]
(first (sut/components {:jobs {:one {:color "red"}}}
{:components "jobs"})))))
(testing "should assume key path as default for name for json-path with map structure with json-path"
(is (= [{:color :green
:name "jobs one"
:message nil}]
(first (sut/components {:jobs {:one {:status "green"}}}
{:components {:json-path "$.jobs"
:color "status"}})))))
(testing "should assume default for color"
(is (= [{:color :green
:name "PI:NAME:<NAME>END_PI name"
:message nil}]
(first (sut/components {:jobs [{:the_name "the name"
:color "green"}]}
{:components {:json-path "$.jobs"
:name "the_name"}})))))
(testing "should return warning if message is configured but missing"
(is (re-find #"component message.+'message'"
(-> (sut/components {:jobs [{:the_name "the name"
:status "green"}]}
{:components {:json-path "$.jobs"
:name "the_name"
:color "status"
:message "message"}})
first-non-nil-message))))
(testing "should accept null values"
(is (nil? (-> (sut/components {:jobs [{:the_name "the name"
:status "green"
:message nil}]}
{:components {:json-path "$.jobs"
:name "the_name"
:color "status"
:message "message"}})
first-non-nil-message))))
(testing "should call out default color config on error"
(is (re-find #"component color.+'color'"
(-> (sut/components {:jobs [{:name "PI:NAME:<NAME>END_PI"
:status "green"}]}
{:components "jobs"})
first-non-nil-message))))
(testing "should call out default name config on error"
(is (re-find #"component name.+'the_name'"
(-> (sut/components {:jobs [{:color "green"}]}
{:components {:json-path "$.jobs"
:name "the_name"}})
first-non-nil-message))))
(testing "should correctly extract complex color with green-value"
(is (nil? (-> (sut/components {:jobs [{:name "PI:NAME:<NAME>END_PI"
:status false}]}
{:components {:json-path "$.jobs"
:color {:json-path "$.status"
:green-value true}}})
first-non-nil-message)))))
(deftest test-message
(testing "should return message"
(is (= "the_message"
(first (sut/message {:text "the_message"}
{:message "text"})))))
(testing "should return warning if message is configured but missing"
(is (re-find #"message.+'text'"
(-> (sut/message {}
{:message "text"})
second))))
(testing "should accept null values"
(is (nil? (-> (sut/message {:text nil}
{:message "text"})
second)))))
(deftest test-package-version
(testing "should return package-version"
(is (= "component-1.2.3"
(first (sut/package-version {:version "component-1.2.3"}
{:package-version "version"})))))
(testing "should return warning if package-version is configured but missing"
(is (re-find #"package-version.+'version'"
(-> (sut/package-version {}
{:package-version "version"})
second))))
(testing "should return warning if package-version is null"
(is (re-find #"package-version.+'version'"
(-> (sut/package-version {:version nil}
{:package-version "version"})
second))))
(testing "should be optional"
(is (nil? (-> (sut/package-version {}
{})
second)))))
|
[
{
"context": "))\n\n(def pretend-database {:person {:id 42 :name \"Joe\" :address \"111 Nowhere\" :cc-number \"1234-4444-555",
"end": 2333,
"score": 0.9995977878570557,
"start": 2330,
"tag": "NAME",
"value": "Joe"
}
] | src/book/book/demos/server_query_security.cljs | levitanong/fulcro | 0 | (ns book.demos.server-query-security
(:require
[fulcro.client.data-fetch :as df]
[fulcro.client.primitives :as prim :refer [defsc]]
[fulcro.client.mutations :refer [defmutation]]
[com.rpl.specter :as s]
[clojure.set :as set]
[fulcro.client.dom :as dom]
[fulcro.server :as server]
[com.stuartsierra.component :as c]
[fulcro.client.data-fetch :as df]
[fulcro.logging :as log]
[fulcro.client :as fc]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; SERVER:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; A map from "entry-level" concept/entity to a set of the allowed graph read/navigation keywords
(def whitelist {:person #{:name :address :mate}})
(defn keywords-in-query
"Returns all of the keywords in the given (arbitrarily nested) query."
[query] (set (s/select (s/walker keyword?) query)))
; TODO: determine if the user is allowed to start at the given keyword for entity with given ID
(defn authorized-root-entity?
"Returns true if the given user is allowed to run a query rooted at the entity indicated by the combination of
query keyword and entity ID.
TODO: Implement some logic here."
[user keyword id] true)
(defn is-authorized-query?
"Returns true if the given query is ok with respect to the top-level key of the API query (which should have already
been authorized by `authorized-root-entity?`."
[query top-key]
(let [keywords-allowed (get whitelist top-key #{})
insecure-keywords (set/difference (keywords-in-query query) keywords-allowed)]
(empty? insecure-keywords)))
(defprotocol Auth
(can-access-entity? [this user key entityid] "Check if the given user is allowed to access the entity designated by the given key and entity id")
(authorized-query? [this user top-key query] "Check if the given user is allowed to access all of the data in the query that starts at the given join key"))
(defrecord Authorizer []
c/Lifecycle
(start [this] this)
(stop [this] this)
Auth
(can-access-entity? [this user key entityid] (authorized-root-entity? user key entityid))
(authorized-query? [this user top-key query] (is-authorized-query? query top-key)))
(defn make-authorizer [] (map->Authorizer {}))
(def pretend-database {:person {:id 42 :name "Joe" :address "111 Nowhere" :cc-number "1234-4444-5555-2222"}})
(server/defquery-root :person
(value [{:keys [request query] :as env} params]
(let [authorization (make-authorizer)
user (:user request)]
(log/info (str authorization "w/user" user))
(or
(and
;; of course, the params would be derived from the request/headers/etc.
(can-access-entity? authorization user :person 42)
(authorized-query? authorization user :person query))
(throw (ex-info "Unauthorized query!" {:status 401 :body {:query query}})))
;; Emulate a datomic pull kind of operation...
(select-keys (get pretend-database :person) query))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; CLIENT:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def initial-state {:ui/react-key "abc"})
(defonce app (atom (fc/new-fulcro-client
:initial-state initial-state
:started-callback
(fn [{:keys [reconciler]}]
; TODO
))))
(defsc Person [this {:keys [name address cc-number]}]
{:query [:ui/fetch-state :name :address :cc-number]}
(dom/div
(dom/ul
(dom/li (str "name: " name))
(dom/li (str "address: " address))
(dom/li (str "cc-number: " cc-number)))))
(def ui-person (prim/factory Person))
(defmutation clear-error [params] (action [{:keys [state]}] (swap! state dissoc :fulcro/server-error)))
(defsc Root [this {:keys [person fulcro/server-error] :as props}]
{:query [{:person (prim/get-query Person)} :fulcro/server-error]}
(dom/div
(when server-error
(dom/p (pr-str "SERVER ERROR: " server-error)))
(dom/button {:onClick (fn []
(prim/transact! this `[(clear-error {})])
(df/load this :person Person {:refresh [:person]}))} "Query for person with credit card")
(dom/button {:onClick (fn []
(prim/transact! this `[(clear-error {})])
(df/load this :person Person {:refresh [:person] :without #{:cc-number}}))} "Query for person WITHOUT credit card")
(df/lazily-loaded ui-person person)))
| 10730 | (ns book.demos.server-query-security
(:require
[fulcro.client.data-fetch :as df]
[fulcro.client.primitives :as prim :refer [defsc]]
[fulcro.client.mutations :refer [defmutation]]
[com.rpl.specter :as s]
[clojure.set :as set]
[fulcro.client.dom :as dom]
[fulcro.server :as server]
[com.stuartsierra.component :as c]
[fulcro.client.data-fetch :as df]
[fulcro.logging :as log]
[fulcro.client :as fc]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; SERVER:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; A map from "entry-level" concept/entity to a set of the allowed graph read/navigation keywords
(def whitelist {:person #{:name :address :mate}})
(defn keywords-in-query
"Returns all of the keywords in the given (arbitrarily nested) query."
[query] (set (s/select (s/walker keyword?) query)))
; TODO: determine if the user is allowed to start at the given keyword for entity with given ID
(defn authorized-root-entity?
"Returns true if the given user is allowed to run a query rooted at the entity indicated by the combination of
query keyword and entity ID.
TODO: Implement some logic here."
[user keyword id] true)
(defn is-authorized-query?
"Returns true if the given query is ok with respect to the top-level key of the API query (which should have already
been authorized by `authorized-root-entity?`."
[query top-key]
(let [keywords-allowed (get whitelist top-key #{})
insecure-keywords (set/difference (keywords-in-query query) keywords-allowed)]
(empty? insecure-keywords)))
(defprotocol Auth
(can-access-entity? [this user key entityid] "Check if the given user is allowed to access the entity designated by the given key and entity id")
(authorized-query? [this user top-key query] "Check if the given user is allowed to access all of the data in the query that starts at the given join key"))
(defrecord Authorizer []
c/Lifecycle
(start [this] this)
(stop [this] this)
Auth
(can-access-entity? [this user key entityid] (authorized-root-entity? user key entityid))
(authorized-query? [this user top-key query] (is-authorized-query? query top-key)))
(defn make-authorizer [] (map->Authorizer {}))
(def pretend-database {:person {:id 42 :name "<NAME>" :address "111 Nowhere" :cc-number "1234-4444-5555-2222"}})
(server/defquery-root :person
(value [{:keys [request query] :as env} params]
(let [authorization (make-authorizer)
user (:user request)]
(log/info (str authorization "w/user" user))
(or
(and
;; of course, the params would be derived from the request/headers/etc.
(can-access-entity? authorization user :person 42)
(authorized-query? authorization user :person query))
(throw (ex-info "Unauthorized query!" {:status 401 :body {:query query}})))
;; Emulate a datomic pull kind of operation...
(select-keys (get pretend-database :person) query))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; CLIENT:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def initial-state {:ui/react-key "abc"})
(defonce app (atom (fc/new-fulcro-client
:initial-state initial-state
:started-callback
(fn [{:keys [reconciler]}]
; TODO
))))
(defsc Person [this {:keys [name address cc-number]}]
{:query [:ui/fetch-state :name :address :cc-number]}
(dom/div
(dom/ul
(dom/li (str "name: " name))
(dom/li (str "address: " address))
(dom/li (str "cc-number: " cc-number)))))
(def ui-person (prim/factory Person))
(defmutation clear-error [params] (action [{:keys [state]}] (swap! state dissoc :fulcro/server-error)))
(defsc Root [this {:keys [person fulcro/server-error] :as props}]
{:query [{:person (prim/get-query Person)} :fulcro/server-error]}
(dom/div
(when server-error
(dom/p (pr-str "SERVER ERROR: " server-error)))
(dom/button {:onClick (fn []
(prim/transact! this `[(clear-error {})])
(df/load this :person Person {:refresh [:person]}))} "Query for person with credit card")
(dom/button {:onClick (fn []
(prim/transact! this `[(clear-error {})])
(df/load this :person Person {:refresh [:person] :without #{:cc-number}}))} "Query for person WITHOUT credit card")
(df/lazily-loaded ui-person person)))
| true | (ns book.demos.server-query-security
(:require
[fulcro.client.data-fetch :as df]
[fulcro.client.primitives :as prim :refer [defsc]]
[fulcro.client.mutations :refer [defmutation]]
[com.rpl.specter :as s]
[clojure.set :as set]
[fulcro.client.dom :as dom]
[fulcro.server :as server]
[com.stuartsierra.component :as c]
[fulcro.client.data-fetch :as df]
[fulcro.logging :as log]
[fulcro.client :as fc]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; SERVER:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; A map from "entry-level" concept/entity to a set of the allowed graph read/navigation keywords
(def whitelist {:person #{:name :address :mate}})
(defn keywords-in-query
"Returns all of the keywords in the given (arbitrarily nested) query."
[query] (set (s/select (s/walker keyword?) query)))
; TODO: determine if the user is allowed to start at the given keyword for entity with given ID
(defn authorized-root-entity?
"Returns true if the given user is allowed to run a query rooted at the entity indicated by the combination of
query keyword and entity ID.
TODO: Implement some logic here."
[user keyword id] true)
(defn is-authorized-query?
"Returns true if the given query is ok with respect to the top-level key of the API query (which should have already
been authorized by `authorized-root-entity?`."
[query top-key]
(let [keywords-allowed (get whitelist top-key #{})
insecure-keywords (set/difference (keywords-in-query query) keywords-allowed)]
(empty? insecure-keywords)))
(defprotocol Auth
(can-access-entity? [this user key entityid] "Check if the given user is allowed to access the entity designated by the given key and entity id")
(authorized-query? [this user top-key query] "Check if the given user is allowed to access all of the data in the query that starts at the given join key"))
(defrecord Authorizer []
c/Lifecycle
(start [this] this)
(stop [this] this)
Auth
(can-access-entity? [this user key entityid] (authorized-root-entity? user key entityid))
(authorized-query? [this user top-key query] (is-authorized-query? query top-key)))
(defn make-authorizer [] (map->Authorizer {}))
(def pretend-database {:person {:id 42 :name "PI:NAME:<NAME>END_PI" :address "111 Nowhere" :cc-number "1234-4444-5555-2222"}})
(server/defquery-root :person
(value [{:keys [request query] :as env} params]
(let [authorization (make-authorizer)
user (:user request)]
(log/info (str authorization "w/user" user))
(or
(and
;; of course, the params would be derived from the request/headers/etc.
(can-access-entity? authorization user :person 42)
(authorized-query? authorization user :person query))
(throw (ex-info "Unauthorized query!" {:status 401 :body {:query query}})))
;; Emulate a datomic pull kind of operation...
(select-keys (get pretend-database :person) query))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; CLIENT:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def initial-state {:ui/react-key "abc"})
(defonce app (atom (fc/new-fulcro-client
:initial-state initial-state
:started-callback
(fn [{:keys [reconciler]}]
; TODO
))))
(defsc Person [this {:keys [name address cc-number]}]
{:query [:ui/fetch-state :name :address :cc-number]}
(dom/div
(dom/ul
(dom/li (str "name: " name))
(dom/li (str "address: " address))
(dom/li (str "cc-number: " cc-number)))))
(def ui-person (prim/factory Person))
(defmutation clear-error [params] (action [{:keys [state]}] (swap! state dissoc :fulcro/server-error)))
(defsc Root [this {:keys [person fulcro/server-error] :as props}]
{:query [{:person (prim/get-query Person)} :fulcro/server-error]}
(dom/div
(when server-error
(dom/p (pr-str "SERVER ERROR: " server-error)))
(dom/button {:onClick (fn []
(prim/transact! this `[(clear-error {})])
(df/load this :person Person {:refresh [:person]}))} "Query for person with credit card")
(dom/button {:onClick (fn []
(prim/transact! this `[(clear-error {})])
(df/load this :person Person {:refresh [:person] :without #{:cc-number}}))} "Query for person WITHOUT credit card")
(df/lazily-loaded ui-person person)))
|
[
{
"context": "nFactory\"\n :broker-user user\n :broker-password password})\n\n(defn sql-storage [db-spec]\n {:eva.v2.storage",
"end": 1189,
"score": 0.9987201690673828,
"start": 1181,
"tag": "PASSWORD",
"value": "password"
}
] | common.alpha/src/eva/catalog/common/alpha/config.clj | Workiva/eva-catalog | 1 | ;; Copyright 2018-2019 Workiva Inc.
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns eva.catalog.common.alpha.config
"Namespace for evaluating configuration files in. Contains helper functions
which make evaluating and expanding configurations simpler."
(:require [eva.catalog.common.alpha.utils :refer [env required-env]])
(:import [java.io PushbackReader]))
(defn broker-uri [uri] {:messenger-node-config/type :broker-uri, :broker-uri uri})
(defn activemq-broker [uri user password]
{:messenger-node-config/type :broker-uri,
:broker-uri uri
:broker-type "org.apache.activemq.ActiveMQConnectionFactory"
:broker-user user
:broker-password password})
(defn sql-storage [db-spec]
{:eva.v2.storage.block-store.types/storage-type :eva.v2.storage.block-store.types/sql
:eva.v2.storage.block-store.impl.sql/db-spec db-spec})
(defn database [partition-id database-id]
{:eva.v2.storage.value-store.core/partition-id partition-id
:eva.v2.database.core/id database-id})
(defn address [type database-conf]
(format "eva.v2.%s.%s.%s"
(name type)
(:eva.v2.storage.value-store.core/partition-id database-conf)
(:eva.v2.database.core/id database-conf)))
(defn empty-catalog [] {:flat-configs #{}})
(defn flat-catalog-config [broker-conf
storage-conf
{:as database-conf :keys [:eva.v2.storage.value-store.core/partition-id
:eva.v2.database.core/id]}]
(let [tc (merge broker-conf
storage-conf
database-conf
{:eva.v2.messaging.address/transaction-submission (address "transact" database-conf)
:eva.v2.messaging.address/transaction-publication (address "transacted" database-conf)
:eva.v2.messaging.address/index-updates (address "index-updates" database-conf)})]
tc))
(defn add-flat-config [catalog tenant category label config]
(update catalog :flat-configs conj (merge config {::tenant tenant ::category category ::label label})))
(defn assign-transactor-group
[catalog
transactor-group
{:keys [:category :label :tenant]}]
(assert (not= :unassigned transactor-group)
":unassigned is reserved and cannot be used as a transactor-group")
(assert (not= (str :unassigned) transactor-group)
":unassigned is reserved and cannot be used as a transactor-group")
(assert (or category label tenant)
"must provide at least one of category, label, or tenant")
(update catalog :transactor-groups
(fnil conj #{})
(-> {}
(assoc ::transactor-group transactor-group)
(cond->
category (assoc ::category category)
label (assoc ::label label)
tenant (assoc ::tenant tenant)))))
| 104217 | ;; Copyright 2018-2019 Workiva Inc.
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns eva.catalog.common.alpha.config
"Namespace for evaluating configuration files in. Contains helper functions
which make evaluating and expanding configurations simpler."
(:require [eva.catalog.common.alpha.utils :refer [env required-env]])
(:import [java.io PushbackReader]))
(defn broker-uri [uri] {:messenger-node-config/type :broker-uri, :broker-uri uri})
(defn activemq-broker [uri user password]
{:messenger-node-config/type :broker-uri,
:broker-uri uri
:broker-type "org.apache.activemq.ActiveMQConnectionFactory"
:broker-user user
:broker-password <PASSWORD>})
(defn sql-storage [db-spec]
{:eva.v2.storage.block-store.types/storage-type :eva.v2.storage.block-store.types/sql
:eva.v2.storage.block-store.impl.sql/db-spec db-spec})
(defn database [partition-id database-id]
{:eva.v2.storage.value-store.core/partition-id partition-id
:eva.v2.database.core/id database-id})
(defn address [type database-conf]
(format "eva.v2.%s.%s.%s"
(name type)
(:eva.v2.storage.value-store.core/partition-id database-conf)
(:eva.v2.database.core/id database-conf)))
(defn empty-catalog [] {:flat-configs #{}})
(defn flat-catalog-config [broker-conf
storage-conf
{:as database-conf :keys [:eva.v2.storage.value-store.core/partition-id
:eva.v2.database.core/id]}]
(let [tc (merge broker-conf
storage-conf
database-conf
{:eva.v2.messaging.address/transaction-submission (address "transact" database-conf)
:eva.v2.messaging.address/transaction-publication (address "transacted" database-conf)
:eva.v2.messaging.address/index-updates (address "index-updates" database-conf)})]
tc))
(defn add-flat-config [catalog tenant category label config]
(update catalog :flat-configs conj (merge config {::tenant tenant ::category category ::label label})))
(defn assign-transactor-group
[catalog
transactor-group
{:keys [:category :label :tenant]}]
(assert (not= :unassigned transactor-group)
":unassigned is reserved and cannot be used as a transactor-group")
(assert (not= (str :unassigned) transactor-group)
":unassigned is reserved and cannot be used as a transactor-group")
(assert (or category label tenant)
"must provide at least one of category, label, or tenant")
(update catalog :transactor-groups
(fnil conj #{})
(-> {}
(assoc ::transactor-group transactor-group)
(cond->
category (assoc ::category category)
label (assoc ::label label)
tenant (assoc ::tenant tenant)))))
| true | ;; Copyright 2018-2019 Workiva Inc.
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns eva.catalog.common.alpha.config
"Namespace for evaluating configuration files in. Contains helper functions
which make evaluating and expanding configurations simpler."
(:require [eva.catalog.common.alpha.utils :refer [env required-env]])
(:import [java.io PushbackReader]))
(defn broker-uri [uri] {:messenger-node-config/type :broker-uri, :broker-uri uri})
(defn activemq-broker [uri user password]
{:messenger-node-config/type :broker-uri,
:broker-uri uri
:broker-type "org.apache.activemq.ActiveMQConnectionFactory"
:broker-user user
:broker-password PI:PASSWORD:<PASSWORD>END_PI})
(defn sql-storage [db-spec]
{:eva.v2.storage.block-store.types/storage-type :eva.v2.storage.block-store.types/sql
:eva.v2.storage.block-store.impl.sql/db-spec db-spec})
(defn database [partition-id database-id]
{:eva.v2.storage.value-store.core/partition-id partition-id
:eva.v2.database.core/id database-id})
(defn address [type database-conf]
(format "eva.v2.%s.%s.%s"
(name type)
(:eva.v2.storage.value-store.core/partition-id database-conf)
(:eva.v2.database.core/id database-conf)))
(defn empty-catalog [] {:flat-configs #{}})
(defn flat-catalog-config [broker-conf
storage-conf
{:as database-conf :keys [:eva.v2.storage.value-store.core/partition-id
:eva.v2.database.core/id]}]
(let [tc (merge broker-conf
storage-conf
database-conf
{:eva.v2.messaging.address/transaction-submission (address "transact" database-conf)
:eva.v2.messaging.address/transaction-publication (address "transacted" database-conf)
:eva.v2.messaging.address/index-updates (address "index-updates" database-conf)})]
tc))
(defn add-flat-config [catalog tenant category label config]
(update catalog :flat-configs conj (merge config {::tenant tenant ::category category ::label label})))
(defn assign-transactor-group
[catalog
transactor-group
{:keys [:category :label :tenant]}]
(assert (not= :unassigned transactor-group)
":unassigned is reserved and cannot be used as a transactor-group")
(assert (not= (str :unassigned) transactor-group)
":unassigned is reserved and cannot be used as a transactor-group")
(assert (or category label tenant)
"must provide at least one of category, label, or tenant")
(update catalog :transactor-groups
(fnil conj #{})
(-> {}
(assoc ::transactor-group transactor-group)
(cond->
category (assoc ::category category)
label (assoc ::label label)
tenant (assoc ::tenant tenant)))))
|
[
{
"context": "\n [:h2 \"WhoAmI?\"]\n (bulletpoints\n [\"Klaus Azesberger\"\n [:a {:href \"https://twitter.com/Psychode",
"end": 422,
"score": 0.9998797178268433,
"start": 406,
"tag": "NAME",
"value": "Klaus Azesberger"
},
{
"context": "esberger\"\n [:a {:href \"https://twitter.com/PsychodelicDad\"} \"@PsychodelicDad\"]\n [:a {:href \"https://",
"end": 478,
"score": 0.9996036887168884,
"start": 464,
"tag": "USERNAME",
"value": "PsychodelicDad"
},
{
"context": " [:a {:href \"https://twitter.com/PsychodelicDad\"} \"@PsychodelicDad\"]\n [:a {:href \"https://github.com/kazesber",
"end": 497,
"score": 0.9996705651283264,
"start": 481,
"tag": "USERNAME",
"value": "\"@PsychodelicDad"
},
{
"context": "delicDad\"]\n [:a {:href \"https://github.com/kazesberger\"} \"https://github.com/kazesberger\"]\n \"Tech",
"end": 550,
"score": 0.9996339082717896,
"start": 539,
"tag": "USERNAME",
"value": "kazesberger"
},
{
"context": "ps://github.com/kazesberger\"} \"https://github.com/kazesberger\"]\n \"Tech Lead Platform Team @ Bearingpoint",
"end": 584,
"score": 0.9996297955513,
"start": 573,
"tag": "USERNAME",
"value": "kazesberger"
}
] | docs/js/compiled/out/reveal/slides.cljs | kazesberger/git-ws-deck | 0 | (ns reveal.slides)
(defn bulletpoints [items]
(let [li-attributes {:class "fragment"}]
(vec (concat [:ul] (map #(vector :li li-attributes %) items)))))
(defn note [s]
[:aside {:class "notes"} s])
(def slides
[
[:section
[:h1 "git workshop"]
[:h3 "new austrian coding school"]]
[:section
(note "what are your expectations?")
[:h2 "WhoAmI?"]
(bulletpoints
["Klaus Azesberger"
[:a {:href "https://twitter.com/PsychodelicDad"} "@PsychodelicDad"]
[:a {:href "https://github.com/kazesberger"} "https://github.com/kazesberger"]
"Tech Lead Platform Team @ Bearingpoint Technology Graz"])]
[:section
[:h2 "git/VCS: why / purpose ?"]
(bulletpoints
["Collaboration"
"Storing Versions"
"Travel in time and perspective"
"Understanding what happened"])]
[:section
[:h2 "why platform(s) like github?"]
(bulletpoints
["open source"
"contribution governance"
"social coding"
"explore your interests"])]
[:section
[:h2 "parts of git"]
(bulletpoints
[[:a {:href "https://git-scm.com/about/staging-area"} "Working Dir"]
[:a {:href "https://git-scm.com/about/staging-area"} "Staging Area"]
[:a {:href "https://git-scm.com/about/staging-area"} "Repo(s)"]
"remote repositories"])]
[:section
[:img {:src "img/gitrepos.svg"}]]
[:section
[:h2 "KataCoda"]
[:p "Everyday knowledge = every course except the #7"]]
[:section
[:h2 "advice: commit messages"]
[:p [:a {:href "https://chris.beams.io/posts/git-commit/"} "https://chris.beams.io/posts/git-commit/"]]]
[:section
[:h2 "IDE git support"]
[:h4 "a short tour"]]
[:section
[:h2 "recap/intro on essential terms"]
(bulletpoints
["clone"
"create a branch (this is not a fork)"
"integrate a branch"
"merge"
"fast forward merge"
"conflict"
"3-way-merge"
"rebase"
"fork"])]
[:section
[:h2 "github PR workflow"]
[:h4 [:a {:href "https://guides.github.com/introduction/flow/"} "github guide"]]]
[:section
[:h2 "conflict demo"]
[:img {:src "img/resolveConflict.png"}]]
[:section
[:h2 "cheat sheets / docs / help"]
(bulletpoints
["git --help"
"git <command> --help"
"stackoverflow / google"
"slack / community"])]
[:section
[:section
[:h2 "Contribute!"]
(bulletpoints
["first contributions are often just docs"
"Issues / Testing / help wanted label"
[:b "github-profile > CV"]
"#100DaysOfCode"
"daily coding katas"])]
[:section
[:h2 "daily exercise"]
(bulletpoints
["side projects to explore tech/libs"
[:a {:href "https://www.hackerrank.com/"} "https://www.hackerrank.com/"]
[:a {:href "https://exercism.io"} "https://exercism.io"]
[:a {:href "https://adventofcode.com/"} "https://adventofcode.com/"]
[:a {:href "https://www.freecodecamp.org/"} "https://www.freecodecamp.org/"]
[:a {:href "https://codepen.io"} "https://codepen.io"]])]]
[:section
[:h2 "Configuration tweaks"]
(bulletpoints
["pull.autostash"
"pull.autorebase"
"log alias / configs"
"difftool"
"default editor"
"github 2fa"])]
[:section
[:h2 "more github features"]
(bulletpoints
["gh-pages"
"badges"
"actions"])]
[:section
[:h2 "even more links :)"]
(bulletpoints
["habits of an efficient dev"
"badges"
"actions"])]])
(defn all
"Add here all slides you want to see in your presentation."
[]
slides) | 40038 | (ns reveal.slides)
(defn bulletpoints [items]
(let [li-attributes {:class "fragment"}]
(vec (concat [:ul] (map #(vector :li li-attributes %) items)))))
(defn note [s]
[:aside {:class "notes"} s])
(def slides
[
[:section
[:h1 "git workshop"]
[:h3 "new austrian coding school"]]
[:section
(note "what are your expectations?")
[:h2 "WhoAmI?"]
(bulletpoints
["<NAME>"
[:a {:href "https://twitter.com/PsychodelicDad"} "@PsychodelicDad"]
[:a {:href "https://github.com/kazesberger"} "https://github.com/kazesberger"]
"Tech Lead Platform Team @ Bearingpoint Technology Graz"])]
[:section
[:h2 "git/VCS: why / purpose ?"]
(bulletpoints
["Collaboration"
"Storing Versions"
"Travel in time and perspective"
"Understanding what happened"])]
[:section
[:h2 "why platform(s) like github?"]
(bulletpoints
["open source"
"contribution governance"
"social coding"
"explore your interests"])]
[:section
[:h2 "parts of git"]
(bulletpoints
[[:a {:href "https://git-scm.com/about/staging-area"} "Working Dir"]
[:a {:href "https://git-scm.com/about/staging-area"} "Staging Area"]
[:a {:href "https://git-scm.com/about/staging-area"} "Repo(s)"]
"remote repositories"])]
[:section
[:img {:src "img/gitrepos.svg"}]]
[:section
[:h2 "KataCoda"]
[:p "Everyday knowledge = every course except the #7"]]
[:section
[:h2 "advice: commit messages"]
[:p [:a {:href "https://chris.beams.io/posts/git-commit/"} "https://chris.beams.io/posts/git-commit/"]]]
[:section
[:h2 "IDE git support"]
[:h4 "a short tour"]]
[:section
[:h2 "recap/intro on essential terms"]
(bulletpoints
["clone"
"create a branch (this is not a fork)"
"integrate a branch"
"merge"
"fast forward merge"
"conflict"
"3-way-merge"
"rebase"
"fork"])]
[:section
[:h2 "github PR workflow"]
[:h4 [:a {:href "https://guides.github.com/introduction/flow/"} "github guide"]]]
[:section
[:h2 "conflict demo"]
[:img {:src "img/resolveConflict.png"}]]
[:section
[:h2 "cheat sheets / docs / help"]
(bulletpoints
["git --help"
"git <command> --help"
"stackoverflow / google"
"slack / community"])]
[:section
[:section
[:h2 "Contribute!"]
(bulletpoints
["first contributions are often just docs"
"Issues / Testing / help wanted label"
[:b "github-profile > CV"]
"#100DaysOfCode"
"daily coding katas"])]
[:section
[:h2 "daily exercise"]
(bulletpoints
["side projects to explore tech/libs"
[:a {:href "https://www.hackerrank.com/"} "https://www.hackerrank.com/"]
[:a {:href "https://exercism.io"} "https://exercism.io"]
[:a {:href "https://adventofcode.com/"} "https://adventofcode.com/"]
[:a {:href "https://www.freecodecamp.org/"} "https://www.freecodecamp.org/"]
[:a {:href "https://codepen.io"} "https://codepen.io"]])]]
[:section
[:h2 "Configuration tweaks"]
(bulletpoints
["pull.autostash"
"pull.autorebase"
"log alias / configs"
"difftool"
"default editor"
"github 2fa"])]
[:section
[:h2 "more github features"]
(bulletpoints
["gh-pages"
"badges"
"actions"])]
[:section
[:h2 "even more links :)"]
(bulletpoints
["habits of an efficient dev"
"badges"
"actions"])]])
(defn all
"Add here all slides you want to see in your presentation."
[]
slides) | true | (ns reveal.slides)
(defn bulletpoints [items]
(let [li-attributes {:class "fragment"}]
(vec (concat [:ul] (map #(vector :li li-attributes %) items)))))
(defn note [s]
[:aside {:class "notes"} s])
(def slides
[
[:section
[:h1 "git workshop"]
[:h3 "new austrian coding school"]]
[:section
(note "what are your expectations?")
[:h2 "WhoAmI?"]
(bulletpoints
["PI:NAME:<NAME>END_PI"
[:a {:href "https://twitter.com/PsychodelicDad"} "@PsychodelicDad"]
[:a {:href "https://github.com/kazesberger"} "https://github.com/kazesberger"]
"Tech Lead Platform Team @ Bearingpoint Technology Graz"])]
[:section
[:h2 "git/VCS: why / purpose ?"]
(bulletpoints
["Collaboration"
"Storing Versions"
"Travel in time and perspective"
"Understanding what happened"])]
[:section
[:h2 "why platform(s) like github?"]
(bulletpoints
["open source"
"contribution governance"
"social coding"
"explore your interests"])]
[:section
[:h2 "parts of git"]
(bulletpoints
[[:a {:href "https://git-scm.com/about/staging-area"} "Working Dir"]
[:a {:href "https://git-scm.com/about/staging-area"} "Staging Area"]
[:a {:href "https://git-scm.com/about/staging-area"} "Repo(s)"]
"remote repositories"])]
[:section
[:img {:src "img/gitrepos.svg"}]]
[:section
[:h2 "KataCoda"]
[:p "Everyday knowledge = every course except the #7"]]
[:section
[:h2 "advice: commit messages"]
[:p [:a {:href "https://chris.beams.io/posts/git-commit/"} "https://chris.beams.io/posts/git-commit/"]]]
[:section
[:h2 "IDE git support"]
[:h4 "a short tour"]]
[:section
[:h2 "recap/intro on essential terms"]
(bulletpoints
["clone"
"create a branch (this is not a fork)"
"integrate a branch"
"merge"
"fast forward merge"
"conflict"
"3-way-merge"
"rebase"
"fork"])]
[:section
[:h2 "github PR workflow"]
[:h4 [:a {:href "https://guides.github.com/introduction/flow/"} "github guide"]]]
[:section
[:h2 "conflict demo"]
[:img {:src "img/resolveConflict.png"}]]
[:section
[:h2 "cheat sheets / docs / help"]
(bulletpoints
["git --help"
"git <command> --help"
"stackoverflow / google"
"slack / community"])]
[:section
[:section
[:h2 "Contribute!"]
(bulletpoints
["first contributions are often just docs"
"Issues / Testing / help wanted label"
[:b "github-profile > CV"]
"#100DaysOfCode"
"daily coding katas"])]
[:section
[:h2 "daily exercise"]
(bulletpoints
["side projects to explore tech/libs"
[:a {:href "https://www.hackerrank.com/"} "https://www.hackerrank.com/"]
[:a {:href "https://exercism.io"} "https://exercism.io"]
[:a {:href "https://adventofcode.com/"} "https://adventofcode.com/"]
[:a {:href "https://www.freecodecamp.org/"} "https://www.freecodecamp.org/"]
[:a {:href "https://codepen.io"} "https://codepen.io"]])]]
[:section
[:h2 "Configuration tweaks"]
(bulletpoints
["pull.autostash"
"pull.autorebase"
"log alias / configs"
"difftool"
"default editor"
"github 2fa"])]
[:section
[:h2 "more github features"]
(bulletpoints
["gh-pages"
"badges"
"actions"])]
[:section
[:h2 "even more links :)"]
(bulletpoints
["habits of an efficient dev"
"badges"
"actions"])]])
(defn all
"Add here all slides you want to see in your presentation."
[]
slides) |
[
{
"context": "og-in\n {:username username\n :password pass",
"end": 2357,
"score": 0.9984323382377625,
"start": 2349,
"tag": "USERNAME",
"value": "username"
},
{
"context": "rname\n :password password})))))\n (remote [env]\n (m/with-target en",
"end": 2411,
"score": 0.9977800250053406,
"start": 2403,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "tate change-password-form-ident]\n (let [{::keys [change-password-error]}\n (get-in state (conj change-password-for",
"end": 4743,
"score": 0.9606317281723022,
"start": 4722,
"tag": "PASSWORD",
"value": "change-password-error"
}
] | src/main/violit/model/account.cljs | eoogbe/violit-clj | 0 | ;;; Copyright 2022 Google LLC
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
(ns violit.model.account
(:require
[com.fulcrologic.fulcro.algorithms.form-state :as fs]
[com.fulcrologic.fulcro.algorithms.merge :as merge]
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.mutations :as m :refer [defmutation]]
[com.fulcrologic.fulcro.ui-state-machines :as uism]
[taoensso.timbre :as log]
[violit.logger :as logger]
[violit.model.session :as session]
[violit.schema.account :as account]
[violit.ui.core.loading-indicator :as loading-indicator]))
(defn signup-form-path
([] [:component/id ::SignupForm])
([field] [:component/id ::SignupForm field]))
(defn create-account*
[state]
(let [signup-form-class (comp/registry-key->class :violit.ui.account.signup-form/SignupForm)]
(-> state
(loading-indicator/set-visible* true)
(merge/merge-component signup-form-class {:ui/busy? true}))))
(defmutation create-account [{:keys [diff] :as params}]
(action [{:keys [state]}]
(logger/log-entity "Creating account for" params)
(swap! state create-account*))
(ok-action [{:keys [state ref component]}]
(let [{::account/keys [username password]} (-> diff vals first)
{::keys [signup-error]} (get-in @state (conj ref :ui/signup-result))]
(swap! state assoc-in (conj ref :ui/busy?) false)
(if signup-error
(swap! state loading-indicator/set-visible* false)
(do
(session/set-unauthenticated-callbacks! component)
(uism/trigger! component
::session/sessionsm
:event/log-in
{:username username
:password password})))))
(remote [env]
(m/with-target env (signup-form-path :ui/signup-result))))
(defn open-delete-account-form*
[state profile-ident]
(let [delete-account-form-class (comp/registry-key->class
:violit.ui.account.delete-account-form/DeleteAccountForm)]
(-> state
(merge/merge-component delete-account-form-class
{:ui/username ""}
:replace (conj profile-ident :ui/delete-account-form))
(assoc-in (conj profile-ident :ui/open-delete-account-form?) true))))
(defmutation open-delete-account-form [_params]
(action [{:keys [state ref]}]
(swap! state open-delete-account-form* ref)))
(defmutation delete-account [_params]
(action [_env] (log/info "Permanently deleting current account"))
(remote [_env] true))
(defn change-password-form-path
([] [:component/id ::ChangePasswordForm])
([field] [:component/id ::ChangePasswordForm field]))
(defn open-change-password-form*
[state profile-ident]
(let [change-password-form-class (comp/registry-key->class
:violit.ui.account.change-password-form/ChangePasswordForm)]
(-> state
(merge/merge-component
change-password-form-class
{::account/old-password ""
::account/new-password ""
::account/password-confirmation ""
:ui/change-password-result {::change-password-error false}}
:replace (conj profile-ident :ui/change-password-form))
(fs/clear-complete* (change-password-form-path))
(assoc-in (conj profile-ident :ui/open-change-password-form?) true))))
(defmutation open-change-password-form [_params]
(action [{:keys [state ref]}]
(swap! state open-change-password-form* ref)))
(defn update-password*
[state]
(let [change-password-form-class (comp/registry-key->class
:violit.ui.account.change-password-form/ChangePasswordForm)]
(log/info "Updating current account password")
(-> state
(loading-indicator/set-visible* true)
(merge/merge-component change-password-form-class {:ui/busy? true}))))
(defn finish-update-password*
[state change-password-form-ident]
(let [{::keys [change-password-error]}
(get-in state (conj change-password-form-ident :ui/change-password-result))
{::account/keys [username]} (get-in state (session/credentials-path))
open-change-password-form-path
(account/account-path username :ui/open-change-password-form?)]
(if change-password-error
(-> state
(update-in change-password-form-ident merge {::account/old-password ""
:ui/busy? false})
(loading-indicator/set-visible* false))
(-> state
(assoc-in open-change-password-form-path false)
(assoc-in (conj change-password-form-ident :ui/busy?) false)
(loading-indicator/set-visible* false)))))
(defmutation update-password [_params]
(action [{:keys [state]}]
(swap! state update-password*))
(ok-action [{:keys [state ref]}]
(swap! state finish-update-password* ref))
(remote [env]
(m/with-target env (change-password-form-path :ui/change-password-result))))
(defn close-pronouns-form*
[state {:keys [username]}]
(log/info "Closing pronouns form")
(-> state
(fs/pristine->entity* (account/account-path username))
(update-in (account/account-path username) dissoc :ui/pronouns-form)))
(defmutation close-pronouns-form [params]
(action [{:keys [state]}]
(swap! state close-pronouns-form* params)))
(defn open-pronouns-form*
[state {:keys [username]}]
(log/info "Opening pronouns form")
(let [pronouns-form-class (comp/registry-key->class :violit.ui.account.pronouns-form/PronounsForm)
pronouns-form-ident (account/account-path username)]
(-> state
(fs/add-form-config* pronouns-form-class pronouns-form-ident)
(fs/mark-complete* pronouns-form-ident)
(assoc-in (account/account-path username :ui/pronouns-form) pronouns-form-ident))))
(defmutation open-pronouns-form [params]
(action [{:keys [state]}]
(swap! state open-pronouns-form* params)))
(defn update-pronouns*
[state {:keys [username diff] :as params}]
(log/info "Updating pronouns" params)
(let [new-pronouns (-> diff first second ::account/pronouns :after account/mk-pronouns)]
(-> state
(fs/entity->pristine* (account/account-path username))
(update-in (account/account-path username)
#(-> %
(dissoc :ui/pronouns-form)
(assoc ::account/pronouns new-pronouns))))))
(defmutation update-pronouns [params]
(action [{:keys [state]}]
(swap! state update-pronouns* params))
(remote [_env] true))
| 24141 | ;;; Copyright 2022 Google LLC
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
(ns violit.model.account
(:require
[com.fulcrologic.fulcro.algorithms.form-state :as fs]
[com.fulcrologic.fulcro.algorithms.merge :as merge]
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.mutations :as m :refer [defmutation]]
[com.fulcrologic.fulcro.ui-state-machines :as uism]
[taoensso.timbre :as log]
[violit.logger :as logger]
[violit.model.session :as session]
[violit.schema.account :as account]
[violit.ui.core.loading-indicator :as loading-indicator]))
(defn signup-form-path
([] [:component/id ::SignupForm])
([field] [:component/id ::SignupForm field]))
(defn create-account*
[state]
(let [signup-form-class (comp/registry-key->class :violit.ui.account.signup-form/SignupForm)]
(-> state
(loading-indicator/set-visible* true)
(merge/merge-component signup-form-class {:ui/busy? true}))))
(defmutation create-account [{:keys [diff] :as params}]
(action [{:keys [state]}]
(logger/log-entity "Creating account for" params)
(swap! state create-account*))
(ok-action [{:keys [state ref component]}]
(let [{::account/keys [username password]} (-> diff vals first)
{::keys [signup-error]} (get-in @state (conj ref :ui/signup-result))]
(swap! state assoc-in (conj ref :ui/busy?) false)
(if signup-error
(swap! state loading-indicator/set-visible* false)
(do
(session/set-unauthenticated-callbacks! component)
(uism/trigger! component
::session/sessionsm
:event/log-in
{:username username
:password <PASSWORD>})))))
(remote [env]
(m/with-target env (signup-form-path :ui/signup-result))))
(defn open-delete-account-form*
[state profile-ident]
(let [delete-account-form-class (comp/registry-key->class
:violit.ui.account.delete-account-form/DeleteAccountForm)]
(-> state
(merge/merge-component delete-account-form-class
{:ui/username ""}
:replace (conj profile-ident :ui/delete-account-form))
(assoc-in (conj profile-ident :ui/open-delete-account-form?) true))))
(defmutation open-delete-account-form [_params]
(action [{:keys [state ref]}]
(swap! state open-delete-account-form* ref)))
(defmutation delete-account [_params]
(action [_env] (log/info "Permanently deleting current account"))
(remote [_env] true))
(defn change-password-form-path
([] [:component/id ::ChangePasswordForm])
([field] [:component/id ::ChangePasswordForm field]))
(defn open-change-password-form*
[state profile-ident]
(let [change-password-form-class (comp/registry-key->class
:violit.ui.account.change-password-form/ChangePasswordForm)]
(-> state
(merge/merge-component
change-password-form-class
{::account/old-password ""
::account/new-password ""
::account/password-confirmation ""
:ui/change-password-result {::change-password-error false}}
:replace (conj profile-ident :ui/change-password-form))
(fs/clear-complete* (change-password-form-path))
(assoc-in (conj profile-ident :ui/open-change-password-form?) true))))
(defmutation open-change-password-form [_params]
(action [{:keys [state ref]}]
(swap! state open-change-password-form* ref)))
(defn update-password*
[state]
(let [change-password-form-class (comp/registry-key->class
:violit.ui.account.change-password-form/ChangePasswordForm)]
(log/info "Updating current account password")
(-> state
(loading-indicator/set-visible* true)
(merge/merge-component change-password-form-class {:ui/busy? true}))))
(defn finish-update-password*
[state change-password-form-ident]
(let [{::keys [<PASSWORD>]}
(get-in state (conj change-password-form-ident :ui/change-password-result))
{::account/keys [username]} (get-in state (session/credentials-path))
open-change-password-form-path
(account/account-path username :ui/open-change-password-form?)]
(if change-password-error
(-> state
(update-in change-password-form-ident merge {::account/old-password ""
:ui/busy? false})
(loading-indicator/set-visible* false))
(-> state
(assoc-in open-change-password-form-path false)
(assoc-in (conj change-password-form-ident :ui/busy?) false)
(loading-indicator/set-visible* false)))))
(defmutation update-password [_params]
(action [{:keys [state]}]
(swap! state update-password*))
(ok-action [{:keys [state ref]}]
(swap! state finish-update-password* ref))
(remote [env]
(m/with-target env (change-password-form-path :ui/change-password-result))))
(defn close-pronouns-form*
[state {:keys [username]}]
(log/info "Closing pronouns form")
(-> state
(fs/pristine->entity* (account/account-path username))
(update-in (account/account-path username) dissoc :ui/pronouns-form)))
(defmutation close-pronouns-form [params]
(action [{:keys [state]}]
(swap! state close-pronouns-form* params)))
(defn open-pronouns-form*
[state {:keys [username]}]
(log/info "Opening pronouns form")
(let [pronouns-form-class (comp/registry-key->class :violit.ui.account.pronouns-form/PronounsForm)
pronouns-form-ident (account/account-path username)]
(-> state
(fs/add-form-config* pronouns-form-class pronouns-form-ident)
(fs/mark-complete* pronouns-form-ident)
(assoc-in (account/account-path username :ui/pronouns-form) pronouns-form-ident))))
(defmutation open-pronouns-form [params]
(action [{:keys [state]}]
(swap! state open-pronouns-form* params)))
(defn update-pronouns*
[state {:keys [username diff] :as params}]
(log/info "Updating pronouns" params)
(let [new-pronouns (-> diff first second ::account/pronouns :after account/mk-pronouns)]
(-> state
(fs/entity->pristine* (account/account-path username))
(update-in (account/account-path username)
#(-> %
(dissoc :ui/pronouns-form)
(assoc ::account/pronouns new-pronouns))))))
(defmutation update-pronouns [params]
(action [{:keys [state]}]
(swap! state update-pronouns* params))
(remote [_env] true))
| true | ;;; Copyright 2022 Google LLC
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
(ns violit.model.account
(:require
[com.fulcrologic.fulcro.algorithms.form-state :as fs]
[com.fulcrologic.fulcro.algorithms.merge :as merge]
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.mutations :as m :refer [defmutation]]
[com.fulcrologic.fulcro.ui-state-machines :as uism]
[taoensso.timbre :as log]
[violit.logger :as logger]
[violit.model.session :as session]
[violit.schema.account :as account]
[violit.ui.core.loading-indicator :as loading-indicator]))
(defn signup-form-path
([] [:component/id ::SignupForm])
([field] [:component/id ::SignupForm field]))
(defn create-account*
[state]
(let [signup-form-class (comp/registry-key->class :violit.ui.account.signup-form/SignupForm)]
(-> state
(loading-indicator/set-visible* true)
(merge/merge-component signup-form-class {:ui/busy? true}))))
(defmutation create-account [{:keys [diff] :as params}]
(action [{:keys [state]}]
(logger/log-entity "Creating account for" params)
(swap! state create-account*))
(ok-action [{:keys [state ref component]}]
(let [{::account/keys [username password]} (-> diff vals first)
{::keys [signup-error]} (get-in @state (conj ref :ui/signup-result))]
(swap! state assoc-in (conj ref :ui/busy?) false)
(if signup-error
(swap! state loading-indicator/set-visible* false)
(do
(session/set-unauthenticated-callbacks! component)
(uism/trigger! component
::session/sessionsm
:event/log-in
{:username username
:password PI:PASSWORD:<PASSWORD>END_PI})))))
(remote [env]
(m/with-target env (signup-form-path :ui/signup-result))))
(defn open-delete-account-form*
[state profile-ident]
(let [delete-account-form-class (comp/registry-key->class
:violit.ui.account.delete-account-form/DeleteAccountForm)]
(-> state
(merge/merge-component delete-account-form-class
{:ui/username ""}
:replace (conj profile-ident :ui/delete-account-form))
(assoc-in (conj profile-ident :ui/open-delete-account-form?) true))))
(defmutation open-delete-account-form [_params]
(action [{:keys [state ref]}]
(swap! state open-delete-account-form* ref)))
(defmutation delete-account [_params]
(action [_env] (log/info "Permanently deleting current account"))
(remote [_env] true))
(defn change-password-form-path
([] [:component/id ::ChangePasswordForm])
([field] [:component/id ::ChangePasswordForm field]))
(defn open-change-password-form*
[state profile-ident]
(let [change-password-form-class (comp/registry-key->class
:violit.ui.account.change-password-form/ChangePasswordForm)]
(-> state
(merge/merge-component
change-password-form-class
{::account/old-password ""
::account/new-password ""
::account/password-confirmation ""
:ui/change-password-result {::change-password-error false}}
:replace (conj profile-ident :ui/change-password-form))
(fs/clear-complete* (change-password-form-path))
(assoc-in (conj profile-ident :ui/open-change-password-form?) true))))
(defmutation open-change-password-form [_params]
(action [{:keys [state ref]}]
(swap! state open-change-password-form* ref)))
(defn update-password*
[state]
(let [change-password-form-class (comp/registry-key->class
:violit.ui.account.change-password-form/ChangePasswordForm)]
(log/info "Updating current account password")
(-> state
(loading-indicator/set-visible* true)
(merge/merge-component change-password-form-class {:ui/busy? true}))))
(defn finish-update-password*
[state change-password-form-ident]
(let [{::keys [PI:PASSWORD:<PASSWORD>END_PI]}
(get-in state (conj change-password-form-ident :ui/change-password-result))
{::account/keys [username]} (get-in state (session/credentials-path))
open-change-password-form-path
(account/account-path username :ui/open-change-password-form?)]
(if change-password-error
(-> state
(update-in change-password-form-ident merge {::account/old-password ""
:ui/busy? false})
(loading-indicator/set-visible* false))
(-> state
(assoc-in open-change-password-form-path false)
(assoc-in (conj change-password-form-ident :ui/busy?) false)
(loading-indicator/set-visible* false)))))
(defmutation update-password [_params]
(action [{:keys [state]}]
(swap! state update-password*))
(ok-action [{:keys [state ref]}]
(swap! state finish-update-password* ref))
(remote [env]
(m/with-target env (change-password-form-path :ui/change-password-result))))
(defn close-pronouns-form*
[state {:keys [username]}]
(log/info "Closing pronouns form")
(-> state
(fs/pristine->entity* (account/account-path username))
(update-in (account/account-path username) dissoc :ui/pronouns-form)))
(defmutation close-pronouns-form [params]
(action [{:keys [state]}]
(swap! state close-pronouns-form* params)))
(defn open-pronouns-form*
[state {:keys [username]}]
(log/info "Opening pronouns form")
(let [pronouns-form-class (comp/registry-key->class :violit.ui.account.pronouns-form/PronounsForm)
pronouns-form-ident (account/account-path username)]
(-> state
(fs/add-form-config* pronouns-form-class pronouns-form-ident)
(fs/mark-complete* pronouns-form-ident)
(assoc-in (account/account-path username :ui/pronouns-form) pronouns-form-ident))))
(defmutation open-pronouns-form [params]
(action [{:keys [state]}]
(swap! state open-pronouns-form* params)))
(defn update-pronouns*
[state {:keys [username diff] :as params}]
(log/info "Updating pronouns" params)
(let [new-pronouns (-> diff first second ::account/pronouns :after account/mk-pronouns)]
(-> state
(fs/entity->pristine* (account/account-path username))
(update-in (account/account-path username)
#(-> %
(dissoc :ui/pronouns-form)
(assoc ::account/pronouns new-pronouns))))))
(defmutation update-pronouns [params]
(action [{:keys [state]}]
(swap! state update-pronouns* params))
(remote [_env] true))
|
[
{
"context": "eftest basics\n (let [msg (mail/make-message :to \"one@example.com\"\n :from \"two@exampl",
"end": 294,
"score": 0.9999217987060547,
"start": 279,
"tag": "EMAIL",
"value": "one@example.com"
},
{
"context": "xample.com\"\n :from \"two@example.com\"\n :subject \"test\"\n ",
"end": 349,
"score": 0.9999225735664368,
"start": 334,
"tag": "EMAIL",
"value": "two@example.com"
}
] | test/test/appengine_magic/services/mail.clj | zenlambda/appengine-magic | 41 | (ns test.appengine-magic.services.mail
(:use clojure.test)
(:require [appengine-magic.services.mail :as mail]
[appengine-magic.testing :as ae-testing]))
(use-fixtures :each (ae-testing/local-services :all))
(deftest basics
(let [msg (mail/make-message :to "one@example.com"
:from "two@example.com"
:subject "test"
:text-body "hello world")]
(mail/send msg)))
| 94129 | (ns test.appengine-magic.services.mail
(:use clojure.test)
(:require [appengine-magic.services.mail :as mail]
[appengine-magic.testing :as ae-testing]))
(use-fixtures :each (ae-testing/local-services :all))
(deftest basics
(let [msg (mail/make-message :to "<EMAIL>"
:from "<EMAIL>"
:subject "test"
:text-body "hello world")]
(mail/send msg)))
| true | (ns test.appengine-magic.services.mail
(:use clojure.test)
(:require [appengine-magic.services.mail :as mail]
[appengine-magic.testing :as ae-testing]))
(use-fixtures :each (ae-testing/local-services :all))
(deftest basics
(let [msg (mail/make-message :to "PI:EMAIL:<EMAIL>END_PI"
:from "PI:EMAIL:<EMAIL>END_PI"
:subject "test"
:text-body "hello world")]
(mail/send msg)))
|
[
{
"context": "k-table [:publicid :s]\n \t {:range-keydef [:editorid :s]\n \t \t:throughput {:read 2 :write 2} :block? t",
"end": 1190,
"score": 0.9160784482955933,
"start": 1188,
"tag": "KEY",
"value": "id"
},
{
"context": "s votes-table [:publicid :s]\n \t {:range-keydef [:userid :s]\n \t \t:throughput {:read 2 :write 2} :block? t",
"end": 1362,
"score": 0.7365078330039978,
"start": 1356,
"tag": "KEY",
"value": "userid"
},
{
"context": "table [:publicid :s]\n \t {:range-keydef [:userid :s]\n \t \t:throughput {:read 2 :write 2} :block? true",
"end": 1365,
"score": 0.552629828453064,
"start": 1364,
"tag": "KEY",
"value": "s"
}
] | src/hackvoter/data.clj | srgb/HackVoter | 0 | (ns hackvoter.data
(:require [cheshire.core :as json]
[clj-http.client :as http]
[clojure.string :refer [blank?]]
[environ.core :refer [env]]
[taoensso.faraday :as far]
[clj-time.core :as time]
[clojure.tools.logging :refer [warn error]]))
(def votingstage (atom (keyword (env :voting-stage))))
(def valid-stages #{:submission :votingallowed :completed})
(defn- remove-empty-entries
[map-entries]
(into {} (remove #(empty? (str (second %))) map-entries)))
(def client-opts
(remove-empty-entries
{:access-key (env :aws-access-key)
:secret-key (env :aws-secret-key)
:endpoint (env :dynamo-endpoint)}))
(def hack-table (env :hacks-table))
(def votes-table (env :hack-votes-table))
(defn- table-exists? [name]
(try
(let [table (far/describe-table client-opts name)
exists (zero? (compare :active (:status table)))]
exists)
(catch Exception _ false)))
(defn- query-table [table query]
(try
(far/query client-opts table query)
(catch Exception _ nil)))
(defn ensure-hacks-table []
(far/ensure-table client-opts hack-table [:publicid :s]
{:range-keydef [:editorid :s]
:throughput {:read 2 :write 2} :block? true }))
(defn ensure-votes-table []
(far/ensure-table client-opts votes-table [:publicid :s]
{:range-keydef [:userid :s]
:throughput {:read 2 :write 2} :block? true }))
(defn get-user-votes [userid]
(let [allhacks (far/scan client-opts hack-table)
uservotes (filter (fn[x] (and (zero? (compare userid (:userid x))) (pos? (:votes x)))) (far/scan client-opts votes-table))]
(map (fn[hack]
(let [id (:publicid hack)
vote (:votes (first (filter (fn[x] (zero? (compare id (:publicid x)))) uservotes)))]
{:id id :uservotes (if (nil? vote) 0N vote)})) allhacks)))
(defn- parse-int [s]
(Integer. (re-find #"\d+" s)))
(defn get-config-items []
(let [stage @votingstage]
{ :currency (env :currency)
:allocation (parse-int (env :allocation))
:maxspend (parse-int (env :max-spend))
:votingstage stage
:configuredvotingstage (keyword (env :voting-stage))
:allowvoting (zero? (compare :votingallowed stage))
:showvotes (zero? (compare :completed stage))}))
(defn update-voting-stage [newstage]
(let [keystage (keyword newstage)]
(if (contains? valid-stages keystage)
(do (reset! votingstage keystage)
true)
false)))
(defn sum-all-votes []
(let [votes (far/scan client-opts votes-table)]
(apply merge-with + (map (fn[vote] (array-map (keyword (:publicid vote)) (:votes vote))) votes))))
(defn sum-all-votes-json []
(let [votes (far/scan client-opts votes-table)
config (get-config-items)
allowvoting (:allowvoting config)
showvotes (:showvotes config)]
(if showvotes
(map (fn[x] {:id (name (key x)) :votes (val x)}) (sum-all-votes))
[])))
(defn list-hacks [adminview]
(let [rawhacks (far/scan client-opts hack-table)
hacks (if adminview rawhacks (map #(dissoc % :editorid) rawhacks))
config (get-config-items)
allowvoting (:allowvoting config)
showvotes (or adminview (:showvotes config))
votes (sum-all-votes)]
;(prn (str "list-hacks allowvoting=" allowvoting " showvotes=" showvotes " adminview=" adminview))
;(prn votes)
(if (and showvotes (not (nil? votes)))
(sort-by :votes > (map (fn [hack] (let [numvotes ((keyword (:publicid hack)) votes)] (assoc hack :votes (if (nil? numvotes) 0 numvotes)))) hacks))
(sort-by :title hacks))))
(defn store-hack [hack]
(let [editorid (:editorid hack)
publicid (:publicid hack)
title (:title hack)
description (:description hack)
creator (:creator hack)
imgurl (:imgurl hack)]
(warn (str "store-hack editorid=" editorid " publicid=" publicid " title=" title " description=" description " creator=" creator " imgurl=" imgurl))
(far/put-item client-opts hack-table {:publicid publicid
:editorid editorid
:title title
:description description
:creator creator
:imgurl imgurl
:lastupdate (str (time/now))})))
(defn store-vote [userid publicid votes]
; validate the allocation in case some smart-ass uses jquery to post bad votes :)
(warn (str "store-vote userid=" userid " publicid=" publicid " votes=" votes))
(let [config (get-config-items)
allowvoting (:allowvoting config)
allocation (:allocation config)
maxspend (:maxspend config)
existingvotes (get-user-votes userid)
uservotesincludingthis (+ votes (reduce + (map (fn[x] (if (zero? (compare publicid (:id x))) 0 (:uservotes x))) existingvotes)))
votewithinbudget (and (<= votes maxspend) (<= uservotesincludingthis allocation))
oktostore (and allowvoting votewithinbudget)]
(when oktostore
(far/put-item client-opts votes-table {:userid userid
:publicid publicid
:votes votes
:lastupdate (str (time/now))}))))
; primary access by publicid
(defn get-hack-by-publicid [publicid]
(first (query-table hack-table {:publicid [:eq publicid]})))
(defn get-hack-by-editorid [editorid]
(first (filter (fn[x] (zero? (compare editorid (:editorid x)))) (far/scan client-opts hack-table))))
(defn- delete-vote [publicidtogo vote]
(let [publicid (:publicid vote)
userid (:userid vote)]
;(prn (str "delete-vote " publicid " " userid))
(when (zero? (compare publicidtogo publicid))
(far/delete-item client-opts votes-table {:publicid publicid :userid userid})))
publicidtogo)
(defn delete-hack-and-votes [editorid]
(str "delete-hack-and-votes " editorid)
(let [hack (get-hack-by-editorid editorid)
publicid (:publicid hack)
votes (far/scan client-opts votes-table)
proceed (not (nil? hack))]
; delete votes first...
(prn proceed)
(when proceed
(doseq [v votes] (delete-vote publicid v))
(far/delete-item client-opts hack-table {:publicid publicid :editorid editorid}))
editorid))
| 104571 | (ns hackvoter.data
(:require [cheshire.core :as json]
[clj-http.client :as http]
[clojure.string :refer [blank?]]
[environ.core :refer [env]]
[taoensso.faraday :as far]
[clj-time.core :as time]
[clojure.tools.logging :refer [warn error]]))
(def votingstage (atom (keyword (env :voting-stage))))
(def valid-stages #{:submission :votingallowed :completed})
(defn- remove-empty-entries
[map-entries]
(into {} (remove #(empty? (str (second %))) map-entries)))
(def client-opts
(remove-empty-entries
{:access-key (env :aws-access-key)
:secret-key (env :aws-secret-key)
:endpoint (env :dynamo-endpoint)}))
(def hack-table (env :hacks-table))
(def votes-table (env :hack-votes-table))
(defn- table-exists? [name]
(try
(let [table (far/describe-table client-opts name)
exists (zero? (compare :active (:status table)))]
exists)
(catch Exception _ false)))
(defn- query-table [table query]
(try
(far/query client-opts table query)
(catch Exception _ nil)))
(defn ensure-hacks-table []
(far/ensure-table client-opts hack-table [:publicid :s]
{:range-keydef [:editor<KEY> :s]
:throughput {:read 2 :write 2} :block? true }))
(defn ensure-votes-table []
(far/ensure-table client-opts votes-table [:publicid :s]
{:range-keydef [:<KEY> :<KEY>]
:throughput {:read 2 :write 2} :block? true }))
(defn get-user-votes [userid]
(let [allhacks (far/scan client-opts hack-table)
uservotes (filter (fn[x] (and (zero? (compare userid (:userid x))) (pos? (:votes x)))) (far/scan client-opts votes-table))]
(map (fn[hack]
(let [id (:publicid hack)
vote (:votes (first (filter (fn[x] (zero? (compare id (:publicid x)))) uservotes)))]
{:id id :uservotes (if (nil? vote) 0N vote)})) allhacks)))
(defn- parse-int [s]
(Integer. (re-find #"\d+" s)))
(defn get-config-items []
(let [stage @votingstage]
{ :currency (env :currency)
:allocation (parse-int (env :allocation))
:maxspend (parse-int (env :max-spend))
:votingstage stage
:configuredvotingstage (keyword (env :voting-stage))
:allowvoting (zero? (compare :votingallowed stage))
:showvotes (zero? (compare :completed stage))}))
(defn update-voting-stage [newstage]
(let [keystage (keyword newstage)]
(if (contains? valid-stages keystage)
(do (reset! votingstage keystage)
true)
false)))
(defn sum-all-votes []
(let [votes (far/scan client-opts votes-table)]
(apply merge-with + (map (fn[vote] (array-map (keyword (:publicid vote)) (:votes vote))) votes))))
(defn sum-all-votes-json []
(let [votes (far/scan client-opts votes-table)
config (get-config-items)
allowvoting (:allowvoting config)
showvotes (:showvotes config)]
(if showvotes
(map (fn[x] {:id (name (key x)) :votes (val x)}) (sum-all-votes))
[])))
(defn list-hacks [adminview]
(let [rawhacks (far/scan client-opts hack-table)
hacks (if adminview rawhacks (map #(dissoc % :editorid) rawhacks))
config (get-config-items)
allowvoting (:allowvoting config)
showvotes (or adminview (:showvotes config))
votes (sum-all-votes)]
;(prn (str "list-hacks allowvoting=" allowvoting " showvotes=" showvotes " adminview=" adminview))
;(prn votes)
(if (and showvotes (not (nil? votes)))
(sort-by :votes > (map (fn [hack] (let [numvotes ((keyword (:publicid hack)) votes)] (assoc hack :votes (if (nil? numvotes) 0 numvotes)))) hacks))
(sort-by :title hacks))))
(defn store-hack [hack]
(let [editorid (:editorid hack)
publicid (:publicid hack)
title (:title hack)
description (:description hack)
creator (:creator hack)
imgurl (:imgurl hack)]
(warn (str "store-hack editorid=" editorid " publicid=" publicid " title=" title " description=" description " creator=" creator " imgurl=" imgurl))
(far/put-item client-opts hack-table {:publicid publicid
:editorid editorid
:title title
:description description
:creator creator
:imgurl imgurl
:lastupdate (str (time/now))})))
(defn store-vote [userid publicid votes]
; validate the allocation in case some smart-ass uses jquery to post bad votes :)
(warn (str "store-vote userid=" userid " publicid=" publicid " votes=" votes))
(let [config (get-config-items)
allowvoting (:allowvoting config)
allocation (:allocation config)
maxspend (:maxspend config)
existingvotes (get-user-votes userid)
uservotesincludingthis (+ votes (reduce + (map (fn[x] (if (zero? (compare publicid (:id x))) 0 (:uservotes x))) existingvotes)))
votewithinbudget (and (<= votes maxspend) (<= uservotesincludingthis allocation))
oktostore (and allowvoting votewithinbudget)]
(when oktostore
(far/put-item client-opts votes-table {:userid userid
:publicid publicid
:votes votes
:lastupdate (str (time/now))}))))
; primary access by publicid
(defn get-hack-by-publicid [publicid]
(first (query-table hack-table {:publicid [:eq publicid]})))
(defn get-hack-by-editorid [editorid]
(first (filter (fn[x] (zero? (compare editorid (:editorid x)))) (far/scan client-opts hack-table))))
(defn- delete-vote [publicidtogo vote]
(let [publicid (:publicid vote)
userid (:userid vote)]
;(prn (str "delete-vote " publicid " " userid))
(when (zero? (compare publicidtogo publicid))
(far/delete-item client-opts votes-table {:publicid publicid :userid userid})))
publicidtogo)
(defn delete-hack-and-votes [editorid]
(str "delete-hack-and-votes " editorid)
(let [hack (get-hack-by-editorid editorid)
publicid (:publicid hack)
votes (far/scan client-opts votes-table)
proceed (not (nil? hack))]
; delete votes first...
(prn proceed)
(when proceed
(doseq [v votes] (delete-vote publicid v))
(far/delete-item client-opts hack-table {:publicid publicid :editorid editorid}))
editorid))
| true | (ns hackvoter.data
(:require [cheshire.core :as json]
[clj-http.client :as http]
[clojure.string :refer [blank?]]
[environ.core :refer [env]]
[taoensso.faraday :as far]
[clj-time.core :as time]
[clojure.tools.logging :refer [warn error]]))
(def votingstage (atom (keyword (env :voting-stage))))
(def valid-stages #{:submission :votingallowed :completed})
(defn- remove-empty-entries
[map-entries]
(into {} (remove #(empty? (str (second %))) map-entries)))
(def client-opts
(remove-empty-entries
{:access-key (env :aws-access-key)
:secret-key (env :aws-secret-key)
:endpoint (env :dynamo-endpoint)}))
(def hack-table (env :hacks-table))
(def votes-table (env :hack-votes-table))
(defn- table-exists? [name]
(try
(let [table (far/describe-table client-opts name)
exists (zero? (compare :active (:status table)))]
exists)
(catch Exception _ false)))
(defn- query-table [table query]
(try
(far/query client-opts table query)
(catch Exception _ nil)))
(defn ensure-hacks-table []
(far/ensure-table client-opts hack-table [:publicid :s]
{:range-keydef [:editorPI:KEY:<KEY>END_PI :s]
:throughput {:read 2 :write 2} :block? true }))
(defn ensure-votes-table []
(far/ensure-table client-opts votes-table [:publicid :s]
{:range-keydef [:PI:KEY:<KEY>END_PI :PI:KEY:<KEY>END_PI]
:throughput {:read 2 :write 2} :block? true }))
(defn get-user-votes [userid]
(let [allhacks (far/scan client-opts hack-table)
uservotes (filter (fn[x] (and (zero? (compare userid (:userid x))) (pos? (:votes x)))) (far/scan client-opts votes-table))]
(map (fn[hack]
(let [id (:publicid hack)
vote (:votes (first (filter (fn[x] (zero? (compare id (:publicid x)))) uservotes)))]
{:id id :uservotes (if (nil? vote) 0N vote)})) allhacks)))
(defn- parse-int [s]
(Integer. (re-find #"\d+" s)))
(defn get-config-items []
(let [stage @votingstage]
{ :currency (env :currency)
:allocation (parse-int (env :allocation))
:maxspend (parse-int (env :max-spend))
:votingstage stage
:configuredvotingstage (keyword (env :voting-stage))
:allowvoting (zero? (compare :votingallowed stage))
:showvotes (zero? (compare :completed stage))}))
(defn update-voting-stage [newstage]
(let [keystage (keyword newstage)]
(if (contains? valid-stages keystage)
(do (reset! votingstage keystage)
true)
false)))
(defn sum-all-votes []
(let [votes (far/scan client-opts votes-table)]
(apply merge-with + (map (fn[vote] (array-map (keyword (:publicid vote)) (:votes vote))) votes))))
(defn sum-all-votes-json []
(let [votes (far/scan client-opts votes-table)
config (get-config-items)
allowvoting (:allowvoting config)
showvotes (:showvotes config)]
(if showvotes
(map (fn[x] {:id (name (key x)) :votes (val x)}) (sum-all-votes))
[])))
(defn list-hacks [adminview]
(let [rawhacks (far/scan client-opts hack-table)
hacks (if adminview rawhacks (map #(dissoc % :editorid) rawhacks))
config (get-config-items)
allowvoting (:allowvoting config)
showvotes (or adminview (:showvotes config))
votes (sum-all-votes)]
;(prn (str "list-hacks allowvoting=" allowvoting " showvotes=" showvotes " adminview=" adminview))
;(prn votes)
(if (and showvotes (not (nil? votes)))
(sort-by :votes > (map (fn [hack] (let [numvotes ((keyword (:publicid hack)) votes)] (assoc hack :votes (if (nil? numvotes) 0 numvotes)))) hacks))
(sort-by :title hacks))))
(defn store-hack [hack]
(let [editorid (:editorid hack)
publicid (:publicid hack)
title (:title hack)
description (:description hack)
creator (:creator hack)
imgurl (:imgurl hack)]
(warn (str "store-hack editorid=" editorid " publicid=" publicid " title=" title " description=" description " creator=" creator " imgurl=" imgurl))
(far/put-item client-opts hack-table {:publicid publicid
:editorid editorid
:title title
:description description
:creator creator
:imgurl imgurl
:lastupdate (str (time/now))})))
(defn store-vote [userid publicid votes]
; validate the allocation in case some smart-ass uses jquery to post bad votes :)
(warn (str "store-vote userid=" userid " publicid=" publicid " votes=" votes))
(let [config (get-config-items)
allowvoting (:allowvoting config)
allocation (:allocation config)
maxspend (:maxspend config)
existingvotes (get-user-votes userid)
uservotesincludingthis (+ votes (reduce + (map (fn[x] (if (zero? (compare publicid (:id x))) 0 (:uservotes x))) existingvotes)))
votewithinbudget (and (<= votes maxspend) (<= uservotesincludingthis allocation))
oktostore (and allowvoting votewithinbudget)]
(when oktostore
(far/put-item client-opts votes-table {:userid userid
:publicid publicid
:votes votes
:lastupdate (str (time/now))}))))
; primary access by publicid
(defn get-hack-by-publicid [publicid]
(first (query-table hack-table {:publicid [:eq publicid]})))
(defn get-hack-by-editorid [editorid]
(first (filter (fn[x] (zero? (compare editorid (:editorid x)))) (far/scan client-opts hack-table))))
(defn- delete-vote [publicidtogo vote]
(let [publicid (:publicid vote)
userid (:userid vote)]
;(prn (str "delete-vote " publicid " " userid))
(when (zero? (compare publicidtogo publicid))
(far/delete-item client-opts votes-table {:publicid publicid :userid userid})))
publicidtogo)
(defn delete-hack-and-votes [editorid]
(str "delete-hack-and-votes " editorid)
(let [hack (get-hack-by-editorid editorid)
publicid (:publicid hack)
votes (far/scan client-opts votes-table)
proceed (not (nil? hack))]
; delete votes first...
(prn proceed)
(when proceed
(doseq [v votes] (delete-vote publicid v))
(far/delete-item client-opts hack-table {:publicid publicid :editorid editorid}))
editorid))
|
[
{
"context": "ent from login page\n (ui/page {:author \"Bor Hodošček/Hinoki Project\"\n :description",
"end": 895,
"score": 0.9998776316642761,
"start": 883,
"tag": "NAME",
"value": "Bor Hodošček"
},
{
"context": "\n (fn [ctx]\n (ui/page {:author \"Bor Hodošček/Hinoki Project\"\n :description",
"end": 1578,
"score": 0.9998860359191895,
"start": 1566,
"tag": "NAME",
"value": "Bor Hodošček"
}
] | src/cypress_editor/web_server.clj | borh/cypress-editor | 0 | ;; Copyright © 2016, JUXT LTD.
(ns cypress-editor.web-server
(:require
[bidi.bidi :refer [tag]]
[bidi.vhosts :refer [make-handler vhosts-model]]
[clojure.tools.logging :refer :all]
[com.stuartsierra.component :refer [Lifecycle using]]
[clojure.java.io :as io]
[cypress-editor.bulma-ui :as ui]
[schema.core :as s]
[yada.resources.webjar-resource :refer [webjars-route-pair]]
[yada.yada :refer [handler resource] :as yada]
[clojure.string :as str]))
(defn content-routes []
["/"
[["index.html"
(yada/resource
{:id :cypress-editor.resources/index
:methods
{:get
{:produces {:media-type #{"text/html"}
:language #{"en"
"ja-jp;q=0.9"}}
:response
(fn [ctx]
;; TODO tempura, session content from login page
(ui/page {:author "Bor Hodošček/Hinoki Project"
:description "Cypress Fulltext Search"
:title "Cypress Fulltext Search"
:app-name "Cypress Fulltext Search"
:lang (case (yada/language ctx)
"en" "en"
"ja-jp" "ja"
"en")}))}}})]
["login"
(yada/resource
{:id :cypress-editor.resources/login
:methods
{:get
{:produces {:media-type #{"text/html"}
:language #{"en"
"ja-jp;q=0.9"}}
:response
(fn [ctx]
(ui/page {:author "Bor Hodošček/Hinoki Project"
:description "Cypress Fulltext Search"
:title "Cypress Fulltext Search Login"
:app-name "Cypress Fulltext Search"
:lang (case (yada/language ctx)
"en" "en"
"ja-jp" "ja"
"en")
:body [:div#login]}))}}})]
["" (assoc (yada/redirect :cypress-editor.resources/index)
:id :cypress-editor.resources/content)]
["debug.html"
(yada/resource
{:id :cypress-editor.resources/debug
:methods
{:get
{:produces #{"text/plain"}
:response (fn [ctx]
(str/join "\n"
(for [path [:webjar/bootstrap
:webjar/bulma
:cypress-editor.resources/index
:cypress-editor.resources/content]]
(str path " => " (yada/path-for ctx path)))))}}})]
["assets" (->> (webjars-route-pair)
second
(map (fn [[wj-name wj-resource]]
[wj-name
(assoc wj-resource
:id (keyword "webjar" wj-name))]))
(into []))]
[""
(-> (yada/as-resource (io/file "target"))
(assoc :id :cypress-editor.resources/static))]]])
(defn routes
"Create the URI route structure for our application."
[config]
[""
[;; Our content routes, and potentially other routes.
(content-routes)
;; This is a backstop. Always produce a 404 if we get there. This
;; ensures we never pass nil back to Aleph.
[true (handler nil)]]])
(s/defrecord WebServer [host :- s/Str
port :- s/Int
scheme :- (s/enum :http :https)
listener]
Lifecycle
(start [component]
(if listener
component ; idempotence
(let [vhosts-model
(vhosts-model
[{:scheme scheme :host host}
(routes {:port port})])
listener (yada/listener vhosts-model {:port port})]
(infof "Started web-server on %s://%s:%s" (name scheme) host (:port listener))
(assoc component :listener listener))))
(stop [component]
(when-let [close (get-in component [:listener :close])]
(close))
(assoc component :listener nil)))
(defn new-web-server []
(using
(map->WebServer {})
[]))
| 100232 | ;; Copyright © 2016, JUXT LTD.
(ns cypress-editor.web-server
(:require
[bidi.bidi :refer [tag]]
[bidi.vhosts :refer [make-handler vhosts-model]]
[clojure.tools.logging :refer :all]
[com.stuartsierra.component :refer [Lifecycle using]]
[clojure.java.io :as io]
[cypress-editor.bulma-ui :as ui]
[schema.core :as s]
[yada.resources.webjar-resource :refer [webjars-route-pair]]
[yada.yada :refer [handler resource] :as yada]
[clojure.string :as str]))
(defn content-routes []
["/"
[["index.html"
(yada/resource
{:id :cypress-editor.resources/index
:methods
{:get
{:produces {:media-type #{"text/html"}
:language #{"en"
"ja-jp;q=0.9"}}
:response
(fn [ctx]
;; TODO tempura, session content from login page
(ui/page {:author "<NAME>/Hinoki Project"
:description "Cypress Fulltext Search"
:title "Cypress Fulltext Search"
:app-name "Cypress Fulltext Search"
:lang (case (yada/language ctx)
"en" "en"
"ja-jp" "ja"
"en")}))}}})]
["login"
(yada/resource
{:id :cypress-editor.resources/login
:methods
{:get
{:produces {:media-type #{"text/html"}
:language #{"en"
"ja-jp;q=0.9"}}
:response
(fn [ctx]
(ui/page {:author "<NAME>/Hinoki Project"
:description "Cypress Fulltext Search"
:title "Cypress Fulltext Search Login"
:app-name "Cypress Fulltext Search"
:lang (case (yada/language ctx)
"en" "en"
"ja-jp" "ja"
"en")
:body [:div#login]}))}}})]
["" (assoc (yada/redirect :cypress-editor.resources/index)
:id :cypress-editor.resources/content)]
["debug.html"
(yada/resource
{:id :cypress-editor.resources/debug
:methods
{:get
{:produces #{"text/plain"}
:response (fn [ctx]
(str/join "\n"
(for [path [:webjar/bootstrap
:webjar/bulma
:cypress-editor.resources/index
:cypress-editor.resources/content]]
(str path " => " (yada/path-for ctx path)))))}}})]
["assets" (->> (webjars-route-pair)
second
(map (fn [[wj-name wj-resource]]
[wj-name
(assoc wj-resource
:id (keyword "webjar" wj-name))]))
(into []))]
[""
(-> (yada/as-resource (io/file "target"))
(assoc :id :cypress-editor.resources/static))]]])
(defn routes
"Create the URI route structure for our application."
[config]
[""
[;; Our content routes, and potentially other routes.
(content-routes)
;; This is a backstop. Always produce a 404 if we get there. This
;; ensures we never pass nil back to Aleph.
[true (handler nil)]]])
(s/defrecord WebServer [host :- s/Str
port :- s/Int
scheme :- (s/enum :http :https)
listener]
Lifecycle
(start [component]
(if listener
component ; idempotence
(let [vhosts-model
(vhosts-model
[{:scheme scheme :host host}
(routes {:port port})])
listener (yada/listener vhosts-model {:port port})]
(infof "Started web-server on %s://%s:%s" (name scheme) host (:port listener))
(assoc component :listener listener))))
(stop [component]
(when-let [close (get-in component [:listener :close])]
(close))
(assoc component :listener nil)))
(defn new-web-server []
(using
(map->WebServer {})
[]))
| true | ;; Copyright © 2016, JUXT LTD.
(ns cypress-editor.web-server
(:require
[bidi.bidi :refer [tag]]
[bidi.vhosts :refer [make-handler vhosts-model]]
[clojure.tools.logging :refer :all]
[com.stuartsierra.component :refer [Lifecycle using]]
[clojure.java.io :as io]
[cypress-editor.bulma-ui :as ui]
[schema.core :as s]
[yada.resources.webjar-resource :refer [webjars-route-pair]]
[yada.yada :refer [handler resource] :as yada]
[clojure.string :as str]))
(defn content-routes []
["/"
[["index.html"
(yada/resource
{:id :cypress-editor.resources/index
:methods
{:get
{:produces {:media-type #{"text/html"}
:language #{"en"
"ja-jp;q=0.9"}}
:response
(fn [ctx]
;; TODO tempura, session content from login page
(ui/page {:author "PI:NAME:<NAME>END_PI/Hinoki Project"
:description "Cypress Fulltext Search"
:title "Cypress Fulltext Search"
:app-name "Cypress Fulltext Search"
:lang (case (yada/language ctx)
"en" "en"
"ja-jp" "ja"
"en")}))}}})]
["login"
(yada/resource
{:id :cypress-editor.resources/login
:methods
{:get
{:produces {:media-type #{"text/html"}
:language #{"en"
"ja-jp;q=0.9"}}
:response
(fn [ctx]
(ui/page {:author "PI:NAME:<NAME>END_PI/Hinoki Project"
:description "Cypress Fulltext Search"
:title "Cypress Fulltext Search Login"
:app-name "Cypress Fulltext Search"
:lang (case (yada/language ctx)
"en" "en"
"ja-jp" "ja"
"en")
:body [:div#login]}))}}})]
["" (assoc (yada/redirect :cypress-editor.resources/index)
:id :cypress-editor.resources/content)]
["debug.html"
(yada/resource
{:id :cypress-editor.resources/debug
:methods
{:get
{:produces #{"text/plain"}
:response (fn [ctx]
(str/join "\n"
(for [path [:webjar/bootstrap
:webjar/bulma
:cypress-editor.resources/index
:cypress-editor.resources/content]]
(str path " => " (yada/path-for ctx path)))))}}})]
["assets" (->> (webjars-route-pair)
second
(map (fn [[wj-name wj-resource]]
[wj-name
(assoc wj-resource
:id (keyword "webjar" wj-name))]))
(into []))]
[""
(-> (yada/as-resource (io/file "target"))
(assoc :id :cypress-editor.resources/static))]]])
(defn routes
"Create the URI route structure for our application."
[config]
[""
[;; Our content routes, and potentially other routes.
(content-routes)
;; This is a backstop. Always produce a 404 if we get there. This
;; ensures we never pass nil back to Aleph.
[true (handler nil)]]])
(s/defrecord WebServer [host :- s/Str
port :- s/Int
scheme :- (s/enum :http :https)
listener]
Lifecycle
(start [component]
(if listener
component ; idempotence
(let [vhosts-model
(vhosts-model
[{:scheme scheme :host host}
(routes {:port port})])
listener (yada/listener vhosts-model {:port port})]
(infof "Started web-server on %s://%s:%s" (name scheme) host (:port listener))
(assoc component :listener listener))))
(stop [component]
(when-let [close (get-in component [:listener :close])]
(close))
(assoc component :listener nil)))
(defn new-web-server []
(using
(map->WebServer {})
[]))
|
[
{
"context": "sql://localhost/addiscore?user=addiscore&password=develop\"\n :patavi-task-silence-ti",
"end": 1048,
"score": 0.9973764419555664,
"start": 1041,
"tag": "PASSWORD",
"value": "develop"
}
] | server-cached/project.clj | ConnorStroomberg/patavi | 0 | (defproject server-cached "0.2.5-1"
:description "Patavi is a distributed system for exposing R as WAMP"
:license {:name "The MIT License"
:url "http://opensource.org/licenses/MIT"
:distribution :repo}
:url "http://patavi.com"
:plugins [[lein-environ "0.4.0"]]
:dependencies [[org.clojure/clojure "1.5.1"]
[org.clojure/java.jdbc "0.3.3"]
[postgresql "9.1-901-1.jdbc4"]
[patavi.server "0.2.5-1"]]
:env {:broker-frontend-socket "ipc://frontend.ipc"
:broker-updates-socket "ipc://updates.ipc"
:broker-backend-socket "tcp://*:7740"
:ws-origin-re "https?://.*"
:ws-base-uri "http://api.patavi.com/"}
:profiles {:uberjar {:aot :all}
:dev {:dependencies [[criterium "0.4.2"]
[org.clojure/tools.namespace "0.2.4"]
[org.zeromq/jeromq "0.3.4"]]
:env {:patavi-cache-db-url "postgresql://localhost/addiscore?user=addiscore&password=develop"
:patavi-task-silence-timeout 20000
:patavi-task-global-timeout 300000}}
:production {:dependencies [[org.zeromq/jzmq "3.0.1"]]
:jvm-opts ["-server" "-Djava.library.path=/usr/lib:/usr/local/lib"]}}
:main patavi.server.server-cached)
| 66685 | (defproject server-cached "0.2.5-1"
:description "Patavi is a distributed system for exposing R as WAMP"
:license {:name "The MIT License"
:url "http://opensource.org/licenses/MIT"
:distribution :repo}
:url "http://patavi.com"
:plugins [[lein-environ "0.4.0"]]
:dependencies [[org.clojure/clojure "1.5.1"]
[org.clojure/java.jdbc "0.3.3"]
[postgresql "9.1-901-1.jdbc4"]
[patavi.server "0.2.5-1"]]
:env {:broker-frontend-socket "ipc://frontend.ipc"
:broker-updates-socket "ipc://updates.ipc"
:broker-backend-socket "tcp://*:7740"
:ws-origin-re "https?://.*"
:ws-base-uri "http://api.patavi.com/"}
:profiles {:uberjar {:aot :all}
:dev {:dependencies [[criterium "0.4.2"]
[org.clojure/tools.namespace "0.2.4"]
[org.zeromq/jeromq "0.3.4"]]
:env {:patavi-cache-db-url "postgresql://localhost/addiscore?user=addiscore&password=<PASSWORD>"
:patavi-task-silence-timeout 20000
:patavi-task-global-timeout 300000}}
:production {:dependencies [[org.zeromq/jzmq "3.0.1"]]
:jvm-opts ["-server" "-Djava.library.path=/usr/lib:/usr/local/lib"]}}
:main patavi.server.server-cached)
| true | (defproject server-cached "0.2.5-1"
:description "Patavi is a distributed system for exposing R as WAMP"
:license {:name "The MIT License"
:url "http://opensource.org/licenses/MIT"
:distribution :repo}
:url "http://patavi.com"
:plugins [[lein-environ "0.4.0"]]
:dependencies [[org.clojure/clojure "1.5.1"]
[org.clojure/java.jdbc "0.3.3"]
[postgresql "9.1-901-1.jdbc4"]
[patavi.server "0.2.5-1"]]
:env {:broker-frontend-socket "ipc://frontend.ipc"
:broker-updates-socket "ipc://updates.ipc"
:broker-backend-socket "tcp://*:7740"
:ws-origin-re "https?://.*"
:ws-base-uri "http://api.patavi.com/"}
:profiles {:uberjar {:aot :all}
:dev {:dependencies [[criterium "0.4.2"]
[org.clojure/tools.namespace "0.2.4"]
[org.zeromq/jeromq "0.3.4"]]
:env {:patavi-cache-db-url "postgresql://localhost/addiscore?user=addiscore&password=PI:PASSWORD:<PASSWORD>END_PI"
:patavi-task-silence-timeout 20000
:patavi-task-global-timeout 300000}}
:production {:dependencies [[org.zeromq/jzmq "3.0.1"]]
:jvm-opts ["-server" "-Djava.library.path=/usr/lib:/usr/local/lib"]}}
:main patavi.server.server-cached)
|
[
{
"context": "#_(ns ^{:author \"John Alan McDonald\" :date \"2016-08-29\"\n :doc \"Run javadoc on z",
"end": 35,
"score": 0.9998741149902344,
"start": 17,
"tag": "NAME",
"value": "John Alan McDonald"
}
] | src/scripts/clojure/zana/scripts/doc/javadoc.clj | wahpenayo/zana | 2 | #_(ns ^{:author "John Alan McDonald" :date "2016-08-29"
:doc "Run javadoc on zana java source." }
zana.scripts.doc.javadoc)
;;------------------------------------------------------------------------------
;; need to add jdkX.Y.Z_bbb/lib/tools.jar to classpath for this to work.
;; probably easier to use maven or a shell script
#_(com.sun.tools.javadoc.Main/execute
(into-array
["-d" "target/javadoc"
"-sourcepath" "src/main/java"
"-doctitle" "Zana Java classes"
"-overview" "src/main/java/overview.html"
"-public"
"-version"
"-author"
"-quiet"
"zana.java"])
;;------------------------------------------------------------------------------
| 38035 | #_(ns ^{:author "<NAME>" :date "2016-08-29"
:doc "Run javadoc on zana java source." }
zana.scripts.doc.javadoc)
;;------------------------------------------------------------------------------
;; need to add jdkX.Y.Z_bbb/lib/tools.jar to classpath for this to work.
;; probably easier to use maven or a shell script
#_(com.sun.tools.javadoc.Main/execute
(into-array
["-d" "target/javadoc"
"-sourcepath" "src/main/java"
"-doctitle" "Zana Java classes"
"-overview" "src/main/java/overview.html"
"-public"
"-version"
"-author"
"-quiet"
"zana.java"])
;;------------------------------------------------------------------------------
| true | #_(ns ^{:author "PI:NAME:<NAME>END_PI" :date "2016-08-29"
:doc "Run javadoc on zana java source." }
zana.scripts.doc.javadoc)
;;------------------------------------------------------------------------------
;; need to add jdkX.Y.Z_bbb/lib/tools.jar to classpath for this to work.
;; probably easier to use maven or a shell script
#_(com.sun.tools.javadoc.Main/execute
(into-array
["-d" "target/javadoc"
"-sourcepath" "src/main/java"
"-doctitle" "Zana Java classes"
"-overview" "src/main/java/overview.html"
"-public"
"-version"
"-author"
"-quiet"
"zana.java"])
;;------------------------------------------------------------------------------
|
[
{
"context": "(time/t -2 1900)\r\n :max (time/t -2 2100)}\r\n\r\n \"teraz\"\r\n \"w tej chwili\"\r\n \"w tym momencie\"\r\n (dateti",
"end": 195,
"score": 0.7857049703598022,
"start": 190,
"tag": "NAME",
"value": "teraz"
},
{
"context": "m momencie\"\r\n (datetime 2013 2 12 4 30 00)\r\n\r\n \"dziś\"\r\n \"dzis\"\r\n \"dzisiaj\"\r\n \"obecnego dnia\"\r\n \"tego d",
"end": 276,
"score": 0.6523864269256592,
"start": 273,
"tag": "NAME",
"value": "ziś"
},
{
"context": "nia\"\r\n \"tego dnia\"\r\n (datetime 2013 2 12)\r\n\r\n \"wczoraj\"\r\n (datetime 2013 2 11)\r\n\r\n \"jutro\"\r\n (datetim",
"end": 367,
"score": 0.5571542382240295,
"start": 362,
"tag": "NAME",
"value": "zoraj"
},
{
"context": " 12)\r\n\r\n \"wczoraj\"\r\n (datetime 2013 2 11)\r\n\r\n \"jutro\"\r\n (datetime 2013 2 13)\r\n\r\n \"pojutrze\"\r\n \"po jut",
"end": 404,
"score": 0.7668089270591736,
"start": 399,
"tag": "NAME",
"value": "jutro"
},
{
"context": " 11)\r\n\r\n \"jutro\"\r\n (datetime 2013 2 13)\r\n\r\n \"pojutrze\"\r\n \"po jutrze\"\r\n (datetime 2013 2 14)\r\n\r\n \"ponied",
"end": 443,
"score": 0.6572088003158569,
"start": 438,
"tag": "NAME",
"value": "utrze"
},
{
"context": "jutrze\"\r\n \"po jutrze\"\r\n (datetime 2013 2 14)\r\n\r\n \"poniedziałek\"\r\n \"pon.\"\r\n \"ten poniedziałek\"\r\n (datetime 2013 2",
"end": 499,
"score": 0.9806210398674011,
"start": 487,
"tag": "NAME",
"value": "poniedziałek"
},
{
"context": "iałek\"\r\n (datetime 2013 2 18 :day-of-week 1)\r\n\r\n \"Poniedziałek, 18 Luty\"\r\n \"Poniedziałek, Luty 18\"\r\n \"Poniedział",
"end": 586,
"score": 0.9157134890556335,
"start": 574,
"tag": "NAME",
"value": "Poniedziałek"
},
{
"context": ":day-of-week 1)\r\n\r\n \"Poniedziałek, 18 Luty\"\r\n \"Poniedziałek, Luty 18\"\r\n \"Poniedziałek 18tego Lutego\"\r\n \"",
"end": 607,
"score": 0.5452420711517334,
"start": 603,
"tag": "NAME",
"value": "iedz"
},
{
"context": "f-week 1)\r\n\r\n \"Poniedziałek, 18 Luty\"\r\n \"Poniedziałek, Luty 18\"\r\n \"Poniedziałek 18tego Lutego\"\r\n \"Pon",
"end": 610,
"score": 0.5145626068115234,
"start": 609,
"tag": "NAME",
"value": "ł"
},
{
"context": "niedziałek, 18 Luty\"\r\n \"Poniedziałek, Luty 18\"\r\n \"Poniedziałek 18tego Lutego\"\r\n \"Poniedziałek 18-tego Lutego\"\r\n ",
"end": 638,
"score": 0.864168107509613,
"start": 626,
"tag": "NAME",
"value": "Poniedziałek"
},
{
"context": "ek\"\r\n \"wt.\"\r\n \"wtr.\"\r\n (datetime 2013 2 19)\r\n\r\n \"czwartek\"\r\n \"ten czwartek\"\r\n \"czw\"\r\n \"czw.\"\r\n (datetim",
"end": 987,
"score": 0.8734837770462036,
"start": 979,
"tag": "NAME",
"value": "czwartek"
},
{
"context": "\"\r\n (datetime 2013 2 19)\r\n\r\n \"czwartek\"\r\n \"ten czwartek\"\r\n \"czw\"\r\n \"czw.\"\r\n (datetime 2013 2 14)\r\n\r\n",
"end": 1003,
"score": 0.6426544189453125,
"start": 998,
"tag": "NAME",
"value": "zwart"
},
{
"context": "\r\n \"czw\"\r\n \"czw.\"\r\n (datetime 2013 2 14)\r\n\r\n \"piatek\"\r\n \"ten piatek\"\r\n \"pia\"\r\n \"pia.\"\r\n (datetime ",
"end": 1062,
"score": 0.9221556782722473,
"start": 1056,
"tag": "NAME",
"value": "piatek"
},
{
"context": "zw.\"\r\n (datetime 2013 2 14)\r\n\r\n \"piatek\"\r\n \"ten piatek\"\r\n \"pia\"\r\n \"pia.\"\r\n (datetime 2013 2 15)\r\n\r\n ",
"end": 1078,
"score": 0.8358147740364075,
"start": 1072,
"tag": "NAME",
"value": "piatek"
},
{
"context": "time 2013 2 14)\r\n\r\n \"piatek\"\r\n \"ten piatek\"\r\n \"pia\"\r\n \"pia.\"\r\n (datetime 2013 2 15)\r\n\r\n \"sobota\"\r",
"end": 1087,
"score": 0.8371627330780029,
"start": 1084,
"tag": "NAME",
"value": "pia"
},
{
"context": "\r\n \"pia\"\r\n \"pia.\"\r\n (datetime 2013 2 15)\r\n\r\n \"sobota\"\r\n \"ta sobota\"\r\n \"sob\"\r\n \"sob.\"\r\n (datetime 2",
"end": 1135,
"score": 0.8341293334960938,
"start": 1129,
"tag": "NAME",
"value": "sobota"
},
{
"context": "pia.\"\r\n (datetime 2013 2 15)\r\n\r\n \"sobota\"\r\n \"ta sobota\"\r\n \"sob\"\r\n \"sob.\"\r\n (datetime 2013 2 16)\r\n\r\n ",
"end": 1150,
"score": 0.7014564871788025,
"start": 1144,
"tag": "NAME",
"value": "sobota"
},
{
"context": "\r\n \"sob\"\r\n \"sob.\"\r\n (datetime 2013 2 16)\r\n\r\n \"niedziela\"\r\n \"ta niedziela\"\r\n \"niedz\"\r\n \"niedz.\"\r\n (dat",
"end": 1210,
"score": 0.6086797714233398,
"start": 1201,
"tag": "NAME",
"value": "niedziela"
},
{
"context": " (datetime 2013 2 16)\r\n\r\n \"niedziela\"\r\n \"ta niedziela\"\r\n \"niedz\"\r\n \"niedz.\"\r\n (datetime 2013 2 17)\r",
"end": 1227,
"score": 0.5684604048728943,
"start": 1223,
"tag": "NAME",
"value": "ziel"
},
{
"context": " \"niedz\"\r\n \"niedz.\"\r\n (datetime 2013 2 17)\r\n\r\n \"pierwszy marca\"\r\n \"pierwszego marca\"\r\n \"marzec pierwszy\"\r\n \"1szy",
"end": 1296,
"score": 0.9721972346305847,
"start": 1282,
"tag": "NAME",
"value": "pierwszy marca"
},
{
"context": ")\r\n\r\n \"pierwszy marca\"\r\n \"pierwszego marca\"\r\n \"marzec pierwszy\"\r\n \"1szy marca\"\r\n \"1szy marzec\"\r\n (datetime 2013",
"end": 1337,
"score": 0.679755449295044,
"start": 1325,
"tag": "NAME",
"value": "zec pierwszy"
},
{
"context": "c\"\r\n (datetime 2013 3 1 :day 1 :month 3)\r\n\r\n \"marzec 3\"\r\n \"marzec 3ci\"\r\n \"3go marca\"\r\n (datetime 2013 ",
"end": 1420,
"score": 0.6277792453765869,
"start": 1417,
"tag": "NAME",
"value": "zec"
},
{
"context": "tego Lutego\"\r\n \"2/15\"\r\n ;;\"on 2/15\" POLISH PLZ\r\n \"Pietnastego Lutego\"\r\n \"Piętnasty Luty\"\r\n \"Luty Piętnastego\"\r\n (datet",
"end": 1961,
"score": 0.9412683844566345,
"start": 1943,
"tag": "NAME",
"value": "Pietnastego Lutego"
},
{
"context": "n 2/15\" POLISH PLZ\r\n \"Pietnastego Lutego\"\r\n \"Piętnasty Luty\"\r\n \"Luty Piętnastego\"\r\n (datetime 2013 2 15 ",
"end": 1975,
"score": 0.5459567904472351,
"start": 1971,
"tag": "NAME",
"value": "asty"
},
{
"context": "PLZ\r\n \"Pietnastego Lutego\"\r\n \"Piętnasty Luty\"\r\n \"Luty Piętnastego\"\r\n (datetime 2013 2 15 :day 15 :month 2)\r\n\r\n \"Sie",
"end": 2001,
"score": 0.7661184668540955,
"start": 1986,
"tag": "NAME",
"value": "uty Piętnastego"
},
{
"context": " Sie.\"\r\n (datetime 2013 8 8 :day 8 :month 8)\r\n\r\n \"Październik 2014\"\r\n \"Pazdziernika 2014\"\r\n (datetime 2014 10 :",
"end": 2189,
"score": 0.9792317748069763,
"start": 2178,
"tag": "NAME",
"value": "Październik"
},
{
"context": "DON'T]\r\n (datetime 2013 2 22 :day-of-week 2)\r\n\r\n \"nastepny Marzec\"\r\n (datetime 2013 3)\r\n\r\n \"Marzec po nastepnym\" ;;",
"end": 2883,
"score": 0.9601818919181824,
"start": 2868,
"tag": "NAME",
"value": "nastepny Marzec"
},
{
"context": "2)\r\n\r\n \"nastepny Marzec\"\r\n (datetime 2013 3)\r\n\r\n \"Marzec po nastepnym\" ;; [REMOVE]\r\n (datetime 2014 3)\r\n\r\n",
"end": 2916,
"score": 0.9833070635795593,
"start": 2910,
"tag": "NAME",
"value": "Marzec"
},
{
"context": "o nastepnym\" ;; [REMOVE]\r\n (datetime 2014 3)\r\n\r\n \"Niedziela, 10 Luty\"\r\n \"Niedziela, Luty 10\"\r\n \"Niedziela, 10",
"end": 2977,
"score": 0.9693011045455933,
"start": 2968,
"tag": "NAME",
"value": "Niedziela"
},
{
"context": "]\r\n (datetime 2014 3)\r\n\r\n \"Niedziela, 10 Luty\"\r\n \"Niedziela, Luty 10\"\r\n \"Niedziela, 10tego Luty\"\r\n \"Niedziela",
"end": 3000,
"score": 0.8123494386672974,
"start": 2991,
"tag": "NAME",
"value": "Niedziela"
},
{
"context": "\r\n \"Niedziela, 10 Luty\"\r\n \"Niedziela, Luty 10\"\r\n \"Niedziela, 10tego Luty\"\r\n \"Niedziela, 10-tego Luty\"\r\n \"Nied",
"end": 3023,
"score": 0.9238735437393188,
"start": 3014,
"tag": "NAME",
"value": "Niedziela"
},
{
"context": "Niedziela, Luty 10\"\r\n \"Niedziela, 10tego Luty\"\r\n \"Niedziela, 10-tego Luty\"\r\n \"Niedziela, 10-ty Lutego\"\r\n \"Ni",
"end": 3049,
"score": 0.7823349237442017,
"start": 3041,
"tag": "NAME",
"value": "Niedziel"
},
{
"context": "iela, 10tego Luty\"\r\n \"Niedziela, 10-tego Luty\"\r\n \"Niedziela, 10-ty Lutego\"\r\n \"Niedziela, 10tego Lutego\"\r\n (da",
"end": 3078,
"score": 0.8514490127563477,
"start": 3069,
"tag": "NAME",
"value": "Niedziela"
},
{
"context": "ela, 10-tego Luty\"\r\n \"Niedziela, 10-ty Lutego\"\r\n \"Niedziela, 10tego Lutego\"\r\n (datetime 2013 2 10 :day-of-wee",
"end": 3106,
"score": 0.8097732663154602,
"start": 3097,
"tag": "NAME",
"value": "Niedziela"
},
{
"context": "e 2013 2 13 :day-of-week 3 :day 13 :month 2)\r\n\r\n \"Poniedziałek, Luty 18\"\r\n \"Poniedziałek, 18 Lutego\"\r\n \"Pon, Lut",
"end": 3369,
"score": 0.9634361267089844,
"start": 3357,
"tag": "NAME",
"value": "Poniedziałek"
},
{
"context": " :day 13 :month 2)\r\n\r\n \"Poniedziałek, Luty 18\"\r\n \"Poniedziałek, 18 Lutego\"\r\n \"Pon, Luty 18\"\r\n (datetime 2013 2 1",
"end": 3395,
"score": 0.9563769698143005,
"start": 3383,
"tag": "NAME",
"value": "Poniedziałek"
},
{
"context": "działek, Luty 18\"\r\n \"Poniedziałek, 18 Lutego\"\r\n \"Pon, Luty 18\"\r\n (datetime 2013 2 18 :day-of-week 1 :d",
"end": 3414,
"score": 0.5070935487747192,
"start": 3412,
"tag": "NAME",
"value": "on"
},
{
"context": "\r\n\r\n \"nastepny wtorek\" ; when today is Tuesday, \"mardi prochain\" is a week from now\r\n (datetime 2013 2 19 :day-o",
"end": 4845,
"score": 0.912874698638916,
"start": 4831,
"tag": "NAME",
"value": "mardi prochain"
},
{
"context": "zień przed wczoraj\"\r\n (datetime 2013 2 10)\r\n\r\n \"ostatni Poniedziałek Marca\"\r\n (datetime 2013 3 25 :day-o",
"end": 5645,
"score": 0.7728058099746704,
"start": 5638,
"tag": "NAME",
"value": "ostatni"
},
{
"context": "zed wczoraj\"\r\n (datetime 2013 2 10)\r\n\r\n \"ostatni Poniedziałek Marca\"\r\n (datetime 2013 3 25 :day-of-week 1)\r\n\r\n \"osta",
"end": 5664,
"score": 0.9941113591194153,
"start": 5646,
"tag": "NAME",
"value": "Poniedziałek Marca"
},
{
"context": "arca\"\r\n (datetime 2013 3 25 :day-of-week 1)\r\n\r\n \"ostatnia Niedziela w Marcu 2014\"\r\n \"ostatnia Niedziela ",
"end": 5715,
"score": 0.8619071841239929,
"start": 5710,
"tag": "NAME",
"value": "ostat"
},
{
"context": "\r\n (datetime 2013 3 25 :day-of-week 1)\r\n\r\n \"ostatnia Niedziela w Marcu 2014\"\r\n \"ostatnia Niedziela mar",
"end": 5718,
"score": 0.45758187770843506,
"start": 5715,
"tag": "NAME",
"value": "nia"
},
{
"context": " (datetime 2013 3 25 :day-of-week 1)\r\n\r\n \"ostatnia Niedziela w Marcu 2014\"\r\n \"ostatnia Niedziela marca 2014\"\r\n",
"end": 5728,
"score": 0.9941709637641907,
"start": 5719,
"tag": "NAME",
"value": "Niedziela"
},
{
"context": "\r\n\r\n \"ostatnia Niedziela w Marcu 2014\"\r\n \"ostatnia Niedziela marca 2014\"\r\n (datetime 2014 3 30 :day-of-week ",
"end": 5763,
"score": 0.7501541376113892,
"start": 5755,
"tag": "NAME",
"value": "Niedziel"
},
{
"context": " \"memorial day\"\r\n;; (datetime 2013 5 27)\r\n\r\n \"Dzień Mamy\"\r\n (datetime 2013 5 12)\r\n\r\n \"Dzień Taty\"\r\n (da",
"end": 12796,
"score": 0.9998184442520142,
"start": 12786,
"tag": "NAME",
"value": "Dzień Mamy"
},
{
"context": ")\r\n\r\n \"Dzień Mamy\"\r\n (datetime 2013 5 12)\r\n\r\n \"Dzień Taty\"\r\n (datetime 2013 6 16)\r\n\r\n ;; \"memorial day w",
"end": 12838,
"score": 0.999856173992157,
"start": 12828,
"tag": "NAME",
"value": "Dzień Taty"
},
{
"context": ")\r\n\r\n \"halloween\"\r\n (datetime 2013 10 31)\r\n\r\n \"dzień dziękczynienia\"\r\n \"dziękczynienie\"\r\n (datetime 2013 11 28)\r\n\r\n",
"end": 13157,
"score": 0.9731331467628479,
"start": 13137,
"tag": "NAME",
"value": "dzień dziękczynienia"
}
] | resources/languages/pl/corpus/time.clj | guivn/duckling | 922 | (
; Context map
; Tuesday Feb 12, 2013 at 4:30am is the "now" for the tests
{:reference-time (time/t -2 2013 2 12 4 30 0)
:min (time/t -2 1900)
:max (time/t -2 2100)}
"teraz"
"w tej chwili"
"w tym momencie"
(datetime 2013 2 12 4 30 00)
"dziś"
"dzis"
"dzisiaj"
"obecnego dnia"
"tego dnia"
(datetime 2013 2 12)
"wczoraj"
(datetime 2013 2 11)
"jutro"
(datetime 2013 2 13)
"pojutrze"
"po jutrze"
(datetime 2013 2 14)
"poniedziałek"
"pon."
"ten poniedziałek"
(datetime 2013 2 18 :day-of-week 1)
"Poniedziałek, 18 Luty"
"Poniedziałek, Luty 18"
"Poniedziałek 18tego Lutego"
"Poniedziałek 18-tego Lutego"
"Poniedziałek, 18-tego Lutego"
"poniedzialek, 18go Lutego"
"Pon, 18 Luty"
(datetime 2013 2 18 :day-of-week 1 :day 18 :month 2)
"Sobota, 2ego Lutego"
(datetime 2013 2 2 :day-of-week 2 :day 2 :month 2)
"Wtorek"
"nastepny wtorek"
"wt."
"wtr."
(datetime 2013 2 19)
"czwartek"
"ten czwartek"
"czw"
"czw."
(datetime 2013 2 14)
"piatek"
"ten piatek"
"pia"
"pia."
(datetime 2013 2 15)
"sobota"
"ta sobota"
"sob"
"sob."
(datetime 2013 2 16)
"niedziela"
"ta niedziela"
"niedz"
"niedz."
(datetime 2013 2 17)
"pierwszy marca"
"pierwszego marca"
"marzec pierwszy"
"1szy marca"
"1szy marzec"
(datetime 2013 3 1 :day 1 :month 3)
"marzec 3"
"marzec 3ci"
"3go marca"
(datetime 2013 3 3 :day 3 :month 3)
;; ;;coto
;; "the ides of march"
;; (datetime 2013 3 15 :month 3)
"3ci marca 2015"
"marzec 3ci 2015"
"3 marzec 2015"
"marzec 3 2015"
"trzeci marca 2015"
"3/3/2015"
"3/3/15"
"2015-3-3"
"2015-03-03"
(datetime 2015 3 3 :day 3 :month 3 :year 2015)
;; TODO FIX??
;; "na 15"
;; "na 15tego"
;; (datetime 2013 2 15 :day 15)
"15 Luty"
"15 Lutego"
"Luty 15"
"15-tego Lutego"
"2/15"
;;"on 2/15" POLISH PLZ
"Pietnastego Lutego"
"Piętnasty Luty"
"Luty Piętnastego"
(datetime 2013 2 15 :day 15 :month 2)
"Sierpień 8"
"Sie 8"
"Sier 8"
"Sierp. 8"
"8 Sie."
"Ósmy Sie."
"Osmego Sie."
(datetime 2013 8 8 :day 8 :month 8)
"Październik 2014"
"Pazdziernika 2014"
(datetime 2014 10 :year 2014 :month 10)
"10/31/1974"
"10/31/74"
"10-31-74"
(datetime 1974 10 31 :day 31 :month 10 :year 1974)
"14kwiecien 2015"
"Kwiecień 14, 2015"
"14tego Kwietnia 15"
"14-tego Kwietnia 15"
"14-ty Kwietnia 15"
"Czternasty Kwietnia 15"
"Czternastego Kwietnia 15"
(datetime 2015 4 14 :day 14 :month 4 :years 2015)
"nastepny wtorek"
"kolejny wtorek"
"kolejnego wtorku"
"nastepnego wtorku"
"wtorek w przyszłym tygodniu"
"wtorek za tydzień"
(datetime 2013 2 19 :day-of-week 2)
"piatek po nastepnym" ;;DO PPL SAY IT THAT WAY? - [NOPE THEY DON'T]
(datetime 2013 2 22 :day-of-week 2)
"nastepny Marzec"
(datetime 2013 3)
"Marzec po nastepnym" ;; [REMOVE]
(datetime 2014 3)
"Niedziela, 10 Luty"
"Niedziela, Luty 10"
"Niedziela, 10tego Luty"
"Niedziela, 10-tego Luty"
"Niedziela, 10-ty Lutego"
"Niedziela, 10tego Lutego"
(datetime 2013 2 10 :day-of-week 7 :day 10 :month 2)
"Śr., Luty13"
"Śr., 13Luty"
"sr, 13Luty"
"sr, 13tego Lutego"
"Śro., 13Lutego"
"Środa trzynastego lutego"
(datetime 2013 2 13 :day-of-week 3 :day 13 :month 2)
"Poniedziałek, Luty 18"
"Poniedziałek, 18 Lutego"
"Pon, Luty 18"
(datetime 2013 2 18 :day-of-week 1 :day 18 :month 2)
;; ; ;; Cycles
"ten tydzien"
"ten tydzień"
"ten tyg"
"tym tygodniu"
(datetime 2013 2 11 :grain :week)
"ostatni tydzien"
"poprzedniego tygodnia"
(datetime 2013 2 4 :grain :week)
"nastepny tydzien"
"nastepnego tygodnia"
(datetime 2013 2 18 :grain :week)
"ostatni miesiac"
"poprzedni miesiac"
"poprzedniego miesiąca"
"po przedniego miesiąca"
"ostatniego miesiaca"
(datetime 2013 1)
"nastepnego miesiaca"
(datetime 2013 3)
"ten kwartał"
"tego kwartału"
"tym kwartale"
(datetime 2013 1 1 :grain :quarter)
"nastepny kwartał"
"następny kwartal"
"kolejnym kwartale"
(datetime 2013 4 1 :grain :quarter)
"trzeci kwartał"
(datetime 2013 7 1 :grain :quarter)
"4ty kwartał 2018"
(datetime 2018 10 1 :grain :quarter)
"poprzedni rok"
"ostatni rok"
(datetime 2012)
"ten rok"
"tym roku"
"obecny rok"
"w obecny rok"
"w obecnym roku"
(datetime 2013)
"w kolejnym roku"
"kolejny rok"
(datetime 2014)
"poprzednia niedziela"
"niedziela z ostatniego tygodnia" ;; [I can see someone say that]
"niedziela ostatniego tygodnia"
"niedziela poprzedniego tygodnia"
"ostatnia niedziela"
(datetime 2013 2 10 :day-of-week 7)
"ostatni wtorek"
"poprzedni wtorek"
(datetime 2013 2 5 :day-of-week 2)
"nastepny wtorek" ; when today is Tuesday, "mardi prochain" is a week from now
(datetime 2013 2 19 :day-of-week 2)
"nastepna środa" ; when today is Tuesday, "mercredi prochain" is tomorrow
(datetime 2013 2 13 :day-of-week 3)
;;"wednesday of next week"
"sroda nastepnego tygodnia"
"środa w przyszłym tygodniu"
"środa za tydzień"
(datetime 2013 2 20 :day-of-week 3)
"piatek nastepnego tygodnia"
(datetime 2013 2 22 :day-of-week 5)
"poniedzialek tego tygodnia"
(datetime 2013 2 11 :day-of-week 1)
"wtorek tego tygodnia"
"wtorek w tym tygodniu"
"ten wtorek"
(datetime 2013 2 12 :day-of-week 2)
"środa w tym tygodniu"
"ta środa"
(datetime 2013 2 13 :day-of-week 3)
"pojutrze"
"po jutrze"
"dzień po jutrze"
(datetime 2013 2 14)
"dzień przed wczoraj"
(datetime 2013 2 10)
"ostatni Poniedziałek Marca"
(datetime 2013 3 25 :day-of-week 1)
"ostatnia Niedziela w Marcu 2014"
"ostatnia Niedziela marca 2014"
(datetime 2014 3 30 :day-of-week 7)
"trzeci dzień października"
"trzeci dzień w październiku"
(datetime 2013 10 3)
"pierwszy tydzień października 2014"
"pierwszy tydzien w październiku 2014"
(datetime 2014 10 6 :grain :week)
;; TODO JAK TO BEDZIE PO PL? "Tydzien w ktorym jest 6ty paź"?
;; "the week of october 6th"
;; "the week of october 7th"
;; (datetime 2013 10 7 :grain :week)
"ostatni dzień w październiku 2015"
"ostatni dzień października 2015"
(datetime 2015 10 31)
"ostatni tydzień we wrześniu 2014"
"ostatni tydzień września 2014"
(datetime 2014 9 22 :grain :week)
;; nth of
"pierwszy wtorek w październiku"
"pierwszy wtorek października"
(datetime 2013 10 1)
"trzeci wtorek we wrześniu 2014"
"trzeci wtorek września 2014"
(datetime 2014 9 16)
"pierwsza środa w październiku 2014"
"pierwsza środa października 2014"
(datetime 2014 10 1)
"druga środa w październiku 2014"
"druga środa października 2014"
(datetime 2014 10 8)
;; Hours
"o 3 rano"
"3 rano"
"3 z rana"
"o trzeciej rano"
"o trzeciej z rana"
(datetime 2013 2 13 3)
"3:18 rano"
(datetime 2013 2 12 3 18)
"o trzeciej"
"o 3 po południu"
"3 po południu"
"3 popołudniu"
"trzecia popoludniu"
"o trzeciej popoludniu"
"piętnasta godzina"
"15sta godzina"
"o piętnastej"
"o 15stej"
(datetime 2013 2 12 15 :hour 3 :meridiem :pm)
"6 po południu"
"6 popołudniu"
"szósta popoludniu"
"o szostej popoludniu"
"o 18stej"
"osiemnasta godzina"
"o osiemnastej"
(datetime 2013 2 12 18 :hour 6 :meridiem :pm)
"7 po południu"
"7 popołudniu"
"siódma popoludniu"
"o siodmej popoludniu"
"o dziewiętnastej"
"dziewietnasta godzina"
(datetime 2013 2 12 19 :hour 7 :meridiem :pm)
"8 wieczorem"
"8 popołudniu"
"osma w nocy"
"ósma wieczorem"
"dwudziesta godzina"
(datetime 2013 2 12 20 :hour 8 :meridiem :pm)
"dziewiata wieczorem"
"dziewiąta popołudniu"
"dziewiata po południu"
"dziewiąta wieczorem"
"dziewiąta nocą"
"dziewiąta w nocy"
"9 wieczorem"
"9 popołudniu"
"9 po południu"
"9 wieczorem"
"9 nocą"
"9 w nocy"
"o dziewiatej w nocy"
"dwudziesta pierwsza godzina"
"dwudziestapierwsza godzina"
(datetime 2013 2 12 21 :hour 9 :meridiem :pm)
"dziesiąta wieczorem"
"dziesiata popołudniu"
"dziesiata po południu"
"dziesiata wieczorem"
"dziesiata nocą"
"10 w nocy"
"o dziesiatej w nocy"
"o dwudziestej drugiej"
(datetime 2013 2 12 22 :hour 10 :meridiem :pm)
"jedenasta wieczorem"
"jedenasta w nocy"
"11 w nocy"
"11 wieczorem"
"o jedenastej wieczorem"
"o dwudziestejtrzeciej"
(datetime 2013 2 12 23 :hour 11 :meridiem :pm)
"jutro o drugiej"
(datetime 2013 2 13 2)
"po jutrze o drugiej"
(datetime 2013 2 14 2)
;; "3ish pm" ;; FIXME pm overrides precision
;; "3pm approximately"
"około 3 po południu"
"około trzeciej"
"koło trzeciej"
"o koło trzeciej"
"mniej wiecej o 3"
"tak o 15stej"
;; "at about 3pm"
(datetime 2013 2 12 15 :hour 3 :meridiem :pm) ;; :precision "approximate"
;; "tomorrow 5pm sharp" ;; FIXME precision is lost
"jutro równo o piątej popołudniu"
"jutro równo o 17-stej"
(datetime 2013 2 13 17 :hour 5 :meridiem :pm) ;; :precision "exact"
;; "at 15 past 3pm"
"piętnaście po trzeciej"
"15 po trzeciej"
"kwadrans po 3"
"trzecia piętnaście"
;; "3:15 in the afternon"
"15:15"
;; "3:15pm"
;; "3:15PM"
;; "3:15p"
(datetime 2013 2 12 15 15 :hour 3 :minute 15 :meridiem :pm)
"20 po 3"
"3:20"
"3:20 w poludnie"
"trzecia dwadzieścia"
(datetime 2013 2 12 15 20 :hour 3 :minute 20 :meridiem :pm)
;; "at half past three pm"
"w pół do szesnastej"
"pol po trzeciej"
"15:30"
;; "3:30pm"
;; "3:30PM"
;; "330 p.m."
;; "3:30 p m"
(datetime 2013 2 12 15 30 :hour 3 :minute 30 :meridiem :pm)
"3:30"
;; "half three"
(datetime 2013 2 12 15 30 :hour 3 :minute 30)
"15:23:24"
(datetime 2013 2 12 15 23 24 :hour 15 :minute 23 :second 24)
"kwadrans do południa"
"kwadrans przed południem"
"kwadrans do 12stej"
"11:45"
(datetime 2013 2 12 11 45 :hour 11 :minute 45)
;;"8 dziś wieczorem" FIX Should produce both the interval and time?
"8 wieczorem"
"8 tego wieczora"
(datetime 2013 2 12 20)
;; Mixing date and time
"o 7:30 popołudniu Piatek, 20 Wrzesień"
"o 7:30 popołudniu Piatek, Wrzesień 20"
(datetime 2013 9 20 19 30 :hour 7 :minute 30 :meridiem :pm)
"o 9 rano w Sobote"
"w Sobote na 9 rano"
(datetime 2013 2 16 9 :day-of-week 6 :hour 9 :meridiem :am)
"Pia, Lip 18, 2014 19:00"
(datetime 2014 7 18 19 0 :day-of-week 5 :hour 7 :meridiem :pm)
;; ; ;; Involving periods
"w sekundę"
"za sekundę"
"sekunde od teraz"
(datetime 2013 2 12 4 30 1)
"za minutę"
"za jedną minutę"
"przez minutę"
(datetime 2013 2 12 4 31 0)
"w 2 minuty"
"za jeszcze 2 minuty"
"2 minuty od teraz"
(datetime 2013 2 12 4 32 0)
"w 60 minut"
(datetime 2013 2 12 5 30 0)
"w pół godziny"
(datetime 2013 2 12 5 0 0)
"w 2.5 godziny"
"w 2 i pół godziny"
(datetime 2013 2 12 7 0 0)
"w godzinę"
"w 1h"
"w przeciągu godziny"
(datetime 2013 2 12 5 30)
"w kilka godzin"
(datetime 2013 2 12 7 30)
"w 24 godziny"
(datetime 2013 2 13 4 30)
"w jeden dzień"
"dzień od dziś"
(datetime 2013 2 13 4)
"3 lata od dziś"
;;"za trzy lata od dzisiaj" Gives the correct result but produces two
;;identical winners
(datetime 2016 2)
"w 7 dni"
(datetime 2013 2 19 4)
"w jeden tydzień"
"w tydzień"
(datetime 2013 2 19)
"za około pół godziny" ;; FIXME precision is lost
"za jakieś pół godziny"
(datetime 2013 2 12 5 0 0) ;; :precision "approximate"
"7 dni temu"
(datetime 2013 2 5 4)
"14 dni temu"
;;"a fortnight ago"
(datetime 2013 1 29 4)
"tydzien temu"
"jeden tydzień temu"
"1 tydzień temu"
(datetime 2013 2 5)
"trzy tygodnie temu"
(datetime 2013 1 22)
"trzy miesiące temu"
(datetime 2012 11 12)
"dwa lata temu"
(datetime 2011 2)
"7 dni potem"
(datetime 2013 2 19 4)
"14 dni później"
;;"a fortnight hence"
(datetime 2013 2 26 4)
"tydzień później"
"jeden tydzień później"
"1 tydzień później"
(datetime 2013 2 19)
"trzy tygodnie później"
(datetime 2013 3 5)
"trzy miesiące później"
(datetime 2013 5 12)
"dwa lata później"
(datetime 2015 2)
;; ; Seasons
"to lato"
"w to lato"
(datetime-interval [2013 6 21] [2013 9 24])
"ta zima"
"tej zimy"
(datetime-interval [2012 12 21] [2013 3 21])
;; ; US holidays (http://www.timeanddate.com/holidays/us/)
"Wigilia Bożego Narodzenia"
"Wigilia"
(datetime 2013 12 24)
"święta Bożego Narodzenia"
"boże narodzenie"
(datetime 2013 12 25)
"sylwester"
(datetime 2013 12 31)
"walentynki"
(datetime 2013 2 14)
;; "memorial day"
;; (datetime 2013 5 27)
"Dzień Mamy"
(datetime 2013 5 12)
"Dzień Taty"
(datetime 2013 6 16)
;; "memorial day week-end"
;; (datetime-interval [2013 5 24 18] [2013 5 28 0])
;; "independence day"
;; "4th of July"
;; "4 of july"
;; (datetime 2013 7 4)
;; "labor day"
;; (datetime 2013 9 2)
"halloween"
(datetime 2013 10 31)
"dzień dziękczynienia"
"dziękczynienie"
(datetime 2013 11 28)
;; ; Part of day (morning, afternoon...)
"ten wieczór"
"dzisiejszy wieczór"
(datetime-interval [2013 2 12 18] [2013 2 13 00])
"jutrzejszy wieczór"
"Środowy wieczór"
"jutrzejsza noc"
(datetime-interval [2013 2 13 18] [2013 2 14 00])
;; "tomorrow lunch"
;; "tomorrow at lunch"
;; (datetime-interval [2013 2 13 12] [2013 2 13 14])
"wczorajszy wieczór"
(datetime-interval [2013 2 11 18] [2013 2 12 00])
"ten week-end"
"ten weekend"
"ten wekend"
(datetime-interval [2013 2 15 18] [2013 2 18 00])
"poniedziałkowy poranek"
(datetime-interval [2013 2 18 4] [2013 2 18 12])
;; TODO
;; "luty 15tego o poranku"
;; "15 lutego o poranku"
;; "poranek 15tego lutego"
;; (datetime-interval [2013 2 15 4] [2013 2 15 12])
;; ; Intervals involving cycles
"ostatnie 2 sekundy"
"ostatnie dwie sekundy"
(datetime-interval [2013 2 12 4 29 58] [2013 2 12 4 30 00])
"kolejne 3 sekundy"
"kolejne trzy sekundy"
(datetime-interval [2013 2 12 4 30 01] [2013 2 12 4 30 04])
"ostatnie 2 minuty"
"ostatnie dwie minuty"
(datetime-interval [2013 2 12 4 28] [2013 2 12 4 30])
"kolejne 3 minuty"
"nastepne trzy minuty"
(datetime-interval [2013 2 12 4 31] [2013 2 12 4 34])
"ostatnia 1 godzina"
"poprzednia jedna godzina"
(datetime-interval [2013 2 12 3] [2013 2 12 4])
"kolejne 3 godziny"
"kolejne trzy godziny"
(datetime-interval [2013 2 12 5] [2013 2 12 8])
"ostatnie 2 dni"
"ostatnie dwa dni"
"poprzednie 2 dni"
(datetime-interval [2013 2 10] [2013 2 12])
"nastepne 3 dni"
"nastepne trzy dni"
(datetime-interval [2013 2 13] [2013 2 16])
"nastepne kilka dni"
(datetime-interval [2013 2 13] [2013 2 16])
"ostatnie 2 tygodnie"
"ostatnie dwa tygodnie"
"poprzednie 2 tygodnie"
(datetime-interval [2013 1 28 :grain :week] [2013 2 11 :grain :week])
"nastepne 3 tygodnie"
"nastepne trzy tygodnie"
(datetime-interval [2013 2 18 :grain :week] [2013 3 11 :grain :week])
"ostatnie 2 miesiace"
"ostatnie dwa miesiące"
(datetime-interval [2012 12] [2013 02])
"nastepne trzy miesiące"
(datetime-interval [2013 3] [2013 6])
"ostatnie 2 lata"
"ostatnie dwa lata"
(datetime-interval [2011] [2013])
"nastepne 3 lata"
"kolejne trzy lata"
(datetime-interval [2014] [2017])
;; ; Explicit intervals
"Lipiec 13-15"
"Lipca 13 do 15"
;; "Lipca 13tego do 15tego" ;;FIX gives hours instaed of dates
"Lipiec 13 - Lipiec 15"
(datetime-interval [2013 7 13] [2013 7 16])
"Sie 8 - Sie 12"
(datetime-interval [2013 8 8] [2013 8 13])
"9:30 - 11:00"
(datetime-interval [2013 2 12 9 30] [2013 2 12 11 1])
"od 9:30 - 11:00 w Czwartek"
"miedzy 9:30 a 11:00 w czwartek"
"9:30 - 11:00 w czwartek"
"pozniej niż 9:30 ale przed 11:00 w Czwartek"
"Czwartek od 9:30 do 11:00"
(datetime-interval [2013 2 14 9 30] [2013 2 14 11 1])
"Czwartek od 9 rano do 11 rano"
(datetime-interval [2013 2 14 9] [2013 2 14 12])
"11:30-1:30" ; go train this rule!
"11:30-1:30"
"11:30-1:30"
"11:30-1:30"
"11:30-1:30"
"11:30-1:30"
"11:30-1:30"
(datetime-interval [2013 2 12 11 30] [2013 2 12 13 31])
;; "1:30 PM on Sat, Sep 21"
;; (datetime 2013 9 21 13 30)
"w ciągu 2 tygodni"
"w ciągu dwóch tygodni"
(datetime-interval [2013 2 12 4 30 0] [2013 2 26])
"przed drugą po południu"
"przed drugą"
(datetime 2013 2 12 14 :direction :before)
;; "by 2:00pm"
;; (datetime-interval [2013 2 12 4 30 0] [2013 2 12 14])
;; "by EOD"
;; (datetime-interval [2013 2 12 4 30 0] [2013 2 13 0])
;; "by EOM"
;; (datetime-interval [2013 2 12 4 30 0] [2013 3 1 0])
;; "by the end of next month"
;; (datetime-interval [2013 2 12 4 30 0] [2013 4 1 0])
;; ; Timezones
;; "4pm CET"
;; (datetime 2013 2 12 16 :hour 4 :meridiem :pm :timezone "CET")
;; "Thursday 8:00 GMT"
;; (datetime 2013 2 14 8 00 :timezone "GMT")
;; Bookface tests
"dziś o drugiej w południe"
"o drugiej popołudniu"
(datetime 2013 2 12 14)
"4/25 o 4 popołudniu"
"4/25 o 16"
"4/25 o szesnastej"
(datetime 2013 4 25 16)
"3 popoludniu jutro"
(datetime 2013 2 13 15)
"po drugiej po poludniu"
(datetime 2013 2 12 14 :direction :after)
"po pięciu dniach"
(datetime 2013 2 17 4 :direction :after)
"po drugiej po południu"
(datetime 2013 2 12 14 :direction :after)
"przed 11 rano"
(datetime 2013 2 12 11 :direction :before)
"jutro przed 11 rano" ;; FIXME this is actually not ambiguous. it's midnight to 11 am
(datetime 2013 2 13 11 :direction :before)
"w południe"
(datetime-interval [2013 2 12 12] [2013 2 12 19])
;; "at 1:30pm"
;; "1:30pm"
;; (datetime 2013 2 12 13 30)
"w 15 minut"
"w piętnaście minut"
(datetime 2013 2 12 4 45 0)
;; "after lunch"
;; (datetime-interval [2013 2 12 13] [2013 2 12 17])
"10:30"
(datetime 2013 2 12 10 30)
;; "morning" ;; how should we deal with fb mornings?
;; (datetime-interval [2013 2 12 4] [2013 2 12 12])
"nastepny pon"
"kolejny poniedziałek"
(datetime 2013 2 18 :day-of-week 1)
)
| 113855 | (
; Context map
; Tuesday Feb 12, 2013 at 4:30am is the "now" for the tests
{:reference-time (time/t -2 2013 2 12 4 30 0)
:min (time/t -2 1900)
:max (time/t -2 2100)}
"<NAME>"
"w tej chwili"
"w tym momencie"
(datetime 2013 2 12 4 30 00)
"d<NAME>"
"dzis"
"dzisiaj"
"obecnego dnia"
"tego dnia"
(datetime 2013 2 12)
"wc<NAME>"
(datetime 2013 2 11)
"<NAME>"
(datetime 2013 2 13)
"poj<NAME>"
"po jutrze"
(datetime 2013 2 14)
"<NAME>"
"pon."
"ten poniedziałek"
(datetime 2013 2 18 :day-of-week 1)
"<NAME>, 18 Luty"
"Pon<NAME>ia<NAME>ek, Luty 18"
"<NAME> 18tego Lutego"
"Poniedziałek 18-tego Lutego"
"Poniedziałek, 18-tego Lutego"
"poniedzialek, 18go Lutego"
"Pon, 18 Luty"
(datetime 2013 2 18 :day-of-week 1 :day 18 :month 2)
"Sobota, 2ego Lutego"
(datetime 2013 2 2 :day-of-week 2 :day 2 :month 2)
"Wtorek"
"nastepny wtorek"
"wt."
"wtr."
(datetime 2013 2 19)
"<NAME>"
"ten c<NAME>ek"
"czw"
"czw."
(datetime 2013 2 14)
"<NAME>"
"ten <NAME>"
"<NAME>"
"pia."
(datetime 2013 2 15)
"<NAME>"
"ta <NAME>"
"sob"
"sob."
(datetime 2013 2 16)
"<NAME>"
"ta nied<NAME>a"
"niedz"
"niedz."
(datetime 2013 2 17)
"<NAME>"
"pierwszego marca"
"mar<NAME>"
"1szy marca"
"1szy marzec"
(datetime 2013 3 1 :day 1 :month 3)
"mar<NAME> 3"
"marzec 3ci"
"3go marca"
(datetime 2013 3 3 :day 3 :month 3)
;; ;;coto
;; "the ides of march"
;; (datetime 2013 3 15 :month 3)
"3ci marca 2015"
"marzec 3ci 2015"
"3 marzec 2015"
"marzec 3 2015"
"trzeci marca 2015"
"3/3/2015"
"3/3/15"
"2015-3-3"
"2015-03-03"
(datetime 2015 3 3 :day 3 :month 3 :year 2015)
;; TODO FIX??
;; "na 15"
;; "na 15tego"
;; (datetime 2013 2 15 :day 15)
"15 Luty"
"15 Lutego"
"Luty 15"
"15-tego Lutego"
"2/15"
;;"on 2/15" POLISH PLZ
"<NAME>"
"Piętn<NAME> Luty"
"L<NAME>"
(datetime 2013 2 15 :day 15 :month 2)
"Sierpień 8"
"Sie 8"
"Sier 8"
"Sierp. 8"
"8 Sie."
"Ósmy Sie."
"Osmego Sie."
(datetime 2013 8 8 :day 8 :month 8)
"<NAME> 2014"
"Pazdziernika 2014"
(datetime 2014 10 :year 2014 :month 10)
"10/31/1974"
"10/31/74"
"10-31-74"
(datetime 1974 10 31 :day 31 :month 10 :year 1974)
"14kwiecien 2015"
"Kwiecień 14, 2015"
"14tego Kwietnia 15"
"14-tego Kwietnia 15"
"14-ty Kwietnia 15"
"Czternasty Kwietnia 15"
"Czternastego Kwietnia 15"
(datetime 2015 4 14 :day 14 :month 4 :years 2015)
"nastepny wtorek"
"kolejny wtorek"
"kolejnego wtorku"
"nastepnego wtorku"
"wtorek w przyszłym tygodniu"
"wtorek za tydzień"
(datetime 2013 2 19 :day-of-week 2)
"piatek po nastepnym" ;;DO PPL SAY IT THAT WAY? - [NOPE THEY DON'T]
(datetime 2013 2 22 :day-of-week 2)
"<NAME>"
(datetime 2013 3)
"<NAME> po nastepnym" ;; [REMOVE]
(datetime 2014 3)
"<NAME>, 10 Luty"
"<NAME>, Luty 10"
"<NAME>, 10tego Luty"
"<NAME>a, 10-tego Luty"
"<NAME>, 10-ty Lutego"
"<NAME>, 10tego Lutego"
(datetime 2013 2 10 :day-of-week 7 :day 10 :month 2)
"Śr., Luty13"
"Śr., 13Luty"
"sr, 13Luty"
"sr, 13tego Lutego"
"Śro., 13Lutego"
"Środa trzynastego lutego"
(datetime 2013 2 13 :day-of-week 3 :day 13 :month 2)
"<NAME>, Luty 18"
"<NAME>, 18 Lutego"
"P<NAME>, Luty 18"
(datetime 2013 2 18 :day-of-week 1 :day 18 :month 2)
;; ; ;; Cycles
"ten tydzien"
"ten tydzień"
"ten tyg"
"tym tygodniu"
(datetime 2013 2 11 :grain :week)
"ostatni tydzien"
"poprzedniego tygodnia"
(datetime 2013 2 4 :grain :week)
"nastepny tydzien"
"nastepnego tygodnia"
(datetime 2013 2 18 :grain :week)
"ostatni miesiac"
"poprzedni miesiac"
"poprzedniego miesiąca"
"po przedniego miesiąca"
"ostatniego miesiaca"
(datetime 2013 1)
"nastepnego miesiaca"
(datetime 2013 3)
"ten kwartał"
"tego kwartału"
"tym kwartale"
(datetime 2013 1 1 :grain :quarter)
"nastepny kwartał"
"następny kwartal"
"kolejnym kwartale"
(datetime 2013 4 1 :grain :quarter)
"trzeci kwartał"
(datetime 2013 7 1 :grain :quarter)
"4ty kwartał 2018"
(datetime 2018 10 1 :grain :quarter)
"poprzedni rok"
"ostatni rok"
(datetime 2012)
"ten rok"
"tym roku"
"obecny rok"
"w obecny rok"
"w obecnym roku"
(datetime 2013)
"w kolejnym roku"
"kolejny rok"
(datetime 2014)
"poprzednia niedziela"
"niedziela z ostatniego tygodnia" ;; [I can see someone say that]
"niedziela ostatniego tygodnia"
"niedziela poprzedniego tygodnia"
"ostatnia niedziela"
(datetime 2013 2 10 :day-of-week 7)
"ostatni wtorek"
"poprzedni wtorek"
(datetime 2013 2 5 :day-of-week 2)
"nastepny wtorek" ; when today is Tuesday, "<NAME>" is a week from now
(datetime 2013 2 19 :day-of-week 2)
"nastepna środa" ; when today is Tuesday, "mercredi prochain" is tomorrow
(datetime 2013 2 13 :day-of-week 3)
;;"wednesday of next week"
"sroda nastepnego tygodnia"
"środa w przyszłym tygodniu"
"środa za tydzień"
(datetime 2013 2 20 :day-of-week 3)
"piatek nastepnego tygodnia"
(datetime 2013 2 22 :day-of-week 5)
"poniedzialek tego tygodnia"
(datetime 2013 2 11 :day-of-week 1)
"wtorek tego tygodnia"
"wtorek w tym tygodniu"
"ten wtorek"
(datetime 2013 2 12 :day-of-week 2)
"środa w tym tygodniu"
"ta środa"
(datetime 2013 2 13 :day-of-week 3)
"pojutrze"
"po jutrze"
"dzień po jutrze"
(datetime 2013 2 14)
"dzień przed wczoraj"
(datetime 2013 2 10)
"<NAME> <NAME>"
(datetime 2013 3 25 :day-of-week 1)
"<NAME> <NAME> <NAME> w Marcu 2014"
"ostatnia <NAME>a marca 2014"
(datetime 2014 3 30 :day-of-week 7)
"trzeci dzień października"
"trzeci dzień w październiku"
(datetime 2013 10 3)
"pierwszy tydzień października 2014"
"pierwszy tydzien w październiku 2014"
(datetime 2014 10 6 :grain :week)
;; TODO JAK TO BEDZIE PO PL? "Tydzien w ktorym jest 6ty paź"?
;; "the week of october 6th"
;; "the week of october 7th"
;; (datetime 2013 10 7 :grain :week)
"ostatni dzień w październiku 2015"
"ostatni dzień października 2015"
(datetime 2015 10 31)
"ostatni tydzień we wrześniu 2014"
"ostatni tydzień września 2014"
(datetime 2014 9 22 :grain :week)
;; nth of
"pierwszy wtorek w październiku"
"pierwszy wtorek października"
(datetime 2013 10 1)
"trzeci wtorek we wrześniu 2014"
"trzeci wtorek września 2014"
(datetime 2014 9 16)
"pierwsza środa w październiku 2014"
"pierwsza środa października 2014"
(datetime 2014 10 1)
"druga środa w październiku 2014"
"druga środa października 2014"
(datetime 2014 10 8)
;; Hours
"o 3 rano"
"3 rano"
"3 z rana"
"o trzeciej rano"
"o trzeciej z rana"
(datetime 2013 2 13 3)
"3:18 rano"
(datetime 2013 2 12 3 18)
"o trzeciej"
"o 3 po południu"
"3 po południu"
"3 popołudniu"
"trzecia popoludniu"
"o trzeciej popoludniu"
"piętnasta godzina"
"15sta godzina"
"o piętnastej"
"o 15stej"
(datetime 2013 2 12 15 :hour 3 :meridiem :pm)
"6 po południu"
"6 popołudniu"
"szósta popoludniu"
"o szostej popoludniu"
"o 18stej"
"osiemnasta godzina"
"o osiemnastej"
(datetime 2013 2 12 18 :hour 6 :meridiem :pm)
"7 po południu"
"7 popołudniu"
"siódma popoludniu"
"o siodmej popoludniu"
"o dziewiętnastej"
"dziewietnasta godzina"
(datetime 2013 2 12 19 :hour 7 :meridiem :pm)
"8 wieczorem"
"8 popołudniu"
"osma w nocy"
"ósma wieczorem"
"dwudziesta godzina"
(datetime 2013 2 12 20 :hour 8 :meridiem :pm)
"dziewiata wieczorem"
"dziewiąta popołudniu"
"dziewiata po południu"
"dziewiąta wieczorem"
"dziewiąta nocą"
"dziewiąta w nocy"
"9 wieczorem"
"9 popołudniu"
"9 po południu"
"9 wieczorem"
"9 nocą"
"9 w nocy"
"o dziewiatej w nocy"
"dwudziesta pierwsza godzina"
"dwudziestapierwsza godzina"
(datetime 2013 2 12 21 :hour 9 :meridiem :pm)
"dziesiąta wieczorem"
"dziesiata popołudniu"
"dziesiata po południu"
"dziesiata wieczorem"
"dziesiata nocą"
"10 w nocy"
"o dziesiatej w nocy"
"o dwudziestej drugiej"
(datetime 2013 2 12 22 :hour 10 :meridiem :pm)
"jedenasta wieczorem"
"jedenasta w nocy"
"11 w nocy"
"11 wieczorem"
"o jedenastej wieczorem"
"o dwudziestejtrzeciej"
(datetime 2013 2 12 23 :hour 11 :meridiem :pm)
"jutro o drugiej"
(datetime 2013 2 13 2)
"po jutrze o drugiej"
(datetime 2013 2 14 2)
;; "3ish pm" ;; FIXME pm overrides precision
;; "3pm approximately"
"około 3 po południu"
"około trzeciej"
"koło trzeciej"
"o koło trzeciej"
"mniej wiecej o 3"
"tak o 15stej"
;; "at about 3pm"
(datetime 2013 2 12 15 :hour 3 :meridiem :pm) ;; :precision "approximate"
;; "tomorrow 5pm sharp" ;; FIXME precision is lost
"jutro równo o piątej popołudniu"
"jutro równo o 17-stej"
(datetime 2013 2 13 17 :hour 5 :meridiem :pm) ;; :precision "exact"
;; "at 15 past 3pm"
"piętnaście po trzeciej"
"15 po trzeciej"
"kwadrans po 3"
"trzecia piętnaście"
;; "3:15 in the afternon"
"15:15"
;; "3:15pm"
;; "3:15PM"
;; "3:15p"
(datetime 2013 2 12 15 15 :hour 3 :minute 15 :meridiem :pm)
"20 po 3"
"3:20"
"3:20 w poludnie"
"trzecia dwadzieścia"
(datetime 2013 2 12 15 20 :hour 3 :minute 20 :meridiem :pm)
;; "at half past three pm"
"w pół do szesnastej"
"pol po trzeciej"
"15:30"
;; "3:30pm"
;; "3:30PM"
;; "330 p.m."
;; "3:30 p m"
(datetime 2013 2 12 15 30 :hour 3 :minute 30 :meridiem :pm)
"3:30"
;; "half three"
(datetime 2013 2 12 15 30 :hour 3 :minute 30)
"15:23:24"
(datetime 2013 2 12 15 23 24 :hour 15 :minute 23 :second 24)
"kwadrans do południa"
"kwadrans przed południem"
"kwadrans do 12stej"
"11:45"
(datetime 2013 2 12 11 45 :hour 11 :minute 45)
;;"8 dziś wieczorem" FIX Should produce both the interval and time?
"8 wieczorem"
"8 tego wieczora"
(datetime 2013 2 12 20)
;; Mixing date and time
"o 7:30 popołudniu Piatek, 20 Wrzesień"
"o 7:30 popołudniu Piatek, Wrzesień 20"
(datetime 2013 9 20 19 30 :hour 7 :minute 30 :meridiem :pm)
"o 9 rano w Sobote"
"w Sobote na 9 rano"
(datetime 2013 2 16 9 :day-of-week 6 :hour 9 :meridiem :am)
"Pia, Lip 18, 2014 19:00"
(datetime 2014 7 18 19 0 :day-of-week 5 :hour 7 :meridiem :pm)
;; ; ;; Involving periods
"w sekundę"
"za sekundę"
"sekunde od teraz"
(datetime 2013 2 12 4 30 1)
"za minutę"
"za jedną minutę"
"przez minutę"
(datetime 2013 2 12 4 31 0)
"w 2 minuty"
"za jeszcze 2 minuty"
"2 minuty od teraz"
(datetime 2013 2 12 4 32 0)
"w 60 minut"
(datetime 2013 2 12 5 30 0)
"w pół godziny"
(datetime 2013 2 12 5 0 0)
"w 2.5 godziny"
"w 2 i pół godziny"
(datetime 2013 2 12 7 0 0)
"w godzinę"
"w 1h"
"w przeciągu godziny"
(datetime 2013 2 12 5 30)
"w kilka godzin"
(datetime 2013 2 12 7 30)
"w 24 godziny"
(datetime 2013 2 13 4 30)
"w jeden dzień"
"dzień od dziś"
(datetime 2013 2 13 4)
"3 lata od dziś"
;;"za trzy lata od dzisiaj" Gives the correct result but produces two
;;identical winners
(datetime 2016 2)
"w 7 dni"
(datetime 2013 2 19 4)
"w jeden tydzień"
"w tydzień"
(datetime 2013 2 19)
"za około pół godziny" ;; FIXME precision is lost
"za jakieś pół godziny"
(datetime 2013 2 12 5 0 0) ;; :precision "approximate"
"7 dni temu"
(datetime 2013 2 5 4)
"14 dni temu"
;;"a fortnight ago"
(datetime 2013 1 29 4)
"tydzien temu"
"jeden tydzień temu"
"1 tydzień temu"
(datetime 2013 2 5)
"trzy tygodnie temu"
(datetime 2013 1 22)
"trzy miesiące temu"
(datetime 2012 11 12)
"dwa lata temu"
(datetime 2011 2)
"7 dni potem"
(datetime 2013 2 19 4)
"14 dni później"
;;"a fortnight hence"
(datetime 2013 2 26 4)
"tydzień później"
"jeden tydzień później"
"1 tydzień później"
(datetime 2013 2 19)
"trzy tygodnie później"
(datetime 2013 3 5)
"trzy miesiące później"
(datetime 2013 5 12)
"dwa lata później"
(datetime 2015 2)
;; ; Seasons
"to lato"
"w to lato"
(datetime-interval [2013 6 21] [2013 9 24])
"ta zima"
"tej zimy"
(datetime-interval [2012 12 21] [2013 3 21])
;; ; US holidays (http://www.timeanddate.com/holidays/us/)
"Wigilia Bożego Narodzenia"
"Wigilia"
(datetime 2013 12 24)
"święta Bożego Narodzenia"
"boże narodzenie"
(datetime 2013 12 25)
"sylwester"
(datetime 2013 12 31)
"walentynki"
(datetime 2013 2 14)
;; "memorial day"
;; (datetime 2013 5 27)
"<NAME>"
(datetime 2013 5 12)
"<NAME>"
(datetime 2013 6 16)
;; "memorial day week-end"
;; (datetime-interval [2013 5 24 18] [2013 5 28 0])
;; "independence day"
;; "4th of July"
;; "4 of july"
;; (datetime 2013 7 4)
;; "labor day"
;; (datetime 2013 9 2)
"halloween"
(datetime 2013 10 31)
"<NAME>"
"dziękczynienie"
(datetime 2013 11 28)
;; ; Part of day (morning, afternoon...)
"ten wieczór"
"dzisiejszy wieczór"
(datetime-interval [2013 2 12 18] [2013 2 13 00])
"jutrzejszy wieczór"
"Środowy wieczór"
"jutrzejsza noc"
(datetime-interval [2013 2 13 18] [2013 2 14 00])
;; "tomorrow lunch"
;; "tomorrow at lunch"
;; (datetime-interval [2013 2 13 12] [2013 2 13 14])
"wczorajszy wieczór"
(datetime-interval [2013 2 11 18] [2013 2 12 00])
"ten week-end"
"ten weekend"
"ten wekend"
(datetime-interval [2013 2 15 18] [2013 2 18 00])
"poniedziałkowy poranek"
(datetime-interval [2013 2 18 4] [2013 2 18 12])
;; TODO
;; "luty 15tego o poranku"
;; "15 lutego o poranku"
;; "poranek 15tego lutego"
;; (datetime-interval [2013 2 15 4] [2013 2 15 12])
;; ; Intervals involving cycles
"ostatnie 2 sekundy"
"ostatnie dwie sekundy"
(datetime-interval [2013 2 12 4 29 58] [2013 2 12 4 30 00])
"kolejne 3 sekundy"
"kolejne trzy sekundy"
(datetime-interval [2013 2 12 4 30 01] [2013 2 12 4 30 04])
"ostatnie 2 minuty"
"ostatnie dwie minuty"
(datetime-interval [2013 2 12 4 28] [2013 2 12 4 30])
"kolejne 3 minuty"
"nastepne trzy minuty"
(datetime-interval [2013 2 12 4 31] [2013 2 12 4 34])
"ostatnia 1 godzina"
"poprzednia jedna godzina"
(datetime-interval [2013 2 12 3] [2013 2 12 4])
"kolejne 3 godziny"
"kolejne trzy godziny"
(datetime-interval [2013 2 12 5] [2013 2 12 8])
"ostatnie 2 dni"
"ostatnie dwa dni"
"poprzednie 2 dni"
(datetime-interval [2013 2 10] [2013 2 12])
"nastepne 3 dni"
"nastepne trzy dni"
(datetime-interval [2013 2 13] [2013 2 16])
"nastepne kilka dni"
(datetime-interval [2013 2 13] [2013 2 16])
"ostatnie 2 tygodnie"
"ostatnie dwa tygodnie"
"poprzednie 2 tygodnie"
(datetime-interval [2013 1 28 :grain :week] [2013 2 11 :grain :week])
"nastepne 3 tygodnie"
"nastepne trzy tygodnie"
(datetime-interval [2013 2 18 :grain :week] [2013 3 11 :grain :week])
"ostatnie 2 miesiace"
"ostatnie dwa miesiące"
(datetime-interval [2012 12] [2013 02])
"nastepne trzy miesiące"
(datetime-interval [2013 3] [2013 6])
"ostatnie 2 lata"
"ostatnie dwa lata"
(datetime-interval [2011] [2013])
"nastepne 3 lata"
"kolejne trzy lata"
(datetime-interval [2014] [2017])
;; ; Explicit intervals
"Lipiec 13-15"
"Lipca 13 do 15"
;; "Lipca 13tego do 15tego" ;;FIX gives hours instaed of dates
"Lipiec 13 - Lipiec 15"
(datetime-interval [2013 7 13] [2013 7 16])
"Sie 8 - Sie 12"
(datetime-interval [2013 8 8] [2013 8 13])
"9:30 - 11:00"
(datetime-interval [2013 2 12 9 30] [2013 2 12 11 1])
"od 9:30 - 11:00 w Czwartek"
"miedzy 9:30 a 11:00 w czwartek"
"9:30 - 11:00 w czwartek"
"pozniej niż 9:30 ale przed 11:00 w Czwartek"
"Czwartek od 9:30 do 11:00"
(datetime-interval [2013 2 14 9 30] [2013 2 14 11 1])
"Czwartek od 9 rano do 11 rano"
(datetime-interval [2013 2 14 9] [2013 2 14 12])
"11:30-1:30" ; go train this rule!
"11:30-1:30"
"11:30-1:30"
"11:30-1:30"
"11:30-1:30"
"11:30-1:30"
"11:30-1:30"
(datetime-interval [2013 2 12 11 30] [2013 2 12 13 31])
;; "1:30 PM on Sat, Sep 21"
;; (datetime 2013 9 21 13 30)
"w ciągu 2 tygodni"
"w ciągu dwóch tygodni"
(datetime-interval [2013 2 12 4 30 0] [2013 2 26])
"przed drugą po południu"
"przed drugą"
(datetime 2013 2 12 14 :direction :before)
;; "by 2:00pm"
;; (datetime-interval [2013 2 12 4 30 0] [2013 2 12 14])
;; "by EOD"
;; (datetime-interval [2013 2 12 4 30 0] [2013 2 13 0])
;; "by EOM"
;; (datetime-interval [2013 2 12 4 30 0] [2013 3 1 0])
;; "by the end of next month"
;; (datetime-interval [2013 2 12 4 30 0] [2013 4 1 0])
;; ; Timezones
;; "4pm CET"
;; (datetime 2013 2 12 16 :hour 4 :meridiem :pm :timezone "CET")
;; "Thursday 8:00 GMT"
;; (datetime 2013 2 14 8 00 :timezone "GMT")
;; Bookface tests
"dziś o drugiej w południe"
"o drugiej popołudniu"
(datetime 2013 2 12 14)
"4/25 o 4 popołudniu"
"4/25 o 16"
"4/25 o szesnastej"
(datetime 2013 4 25 16)
"3 popoludniu jutro"
(datetime 2013 2 13 15)
"po drugiej po poludniu"
(datetime 2013 2 12 14 :direction :after)
"po pięciu dniach"
(datetime 2013 2 17 4 :direction :after)
"po drugiej po południu"
(datetime 2013 2 12 14 :direction :after)
"przed 11 rano"
(datetime 2013 2 12 11 :direction :before)
"jutro przed 11 rano" ;; FIXME this is actually not ambiguous. it's midnight to 11 am
(datetime 2013 2 13 11 :direction :before)
"w południe"
(datetime-interval [2013 2 12 12] [2013 2 12 19])
;; "at 1:30pm"
;; "1:30pm"
;; (datetime 2013 2 12 13 30)
"w 15 minut"
"w piętnaście minut"
(datetime 2013 2 12 4 45 0)
;; "after lunch"
;; (datetime-interval [2013 2 12 13] [2013 2 12 17])
"10:30"
(datetime 2013 2 12 10 30)
;; "morning" ;; how should we deal with fb mornings?
;; (datetime-interval [2013 2 12 4] [2013 2 12 12])
"nastepny pon"
"kolejny poniedziałek"
(datetime 2013 2 18 :day-of-week 1)
)
| true | (
; Context map
; Tuesday Feb 12, 2013 at 4:30am is the "now" for the tests
{:reference-time (time/t -2 2013 2 12 4 30 0)
:min (time/t -2 1900)
:max (time/t -2 2100)}
"PI:NAME:<NAME>END_PI"
"w tej chwili"
"w tym momencie"
(datetime 2013 2 12 4 30 00)
"dPI:NAME:<NAME>END_PI"
"dzis"
"dzisiaj"
"obecnego dnia"
"tego dnia"
(datetime 2013 2 12)
"wcPI:NAME:<NAME>END_PI"
(datetime 2013 2 11)
"PI:NAME:<NAME>END_PI"
(datetime 2013 2 13)
"pojPI:NAME:<NAME>END_PI"
"po jutrze"
(datetime 2013 2 14)
"PI:NAME:<NAME>END_PI"
"pon."
"ten poniedziałek"
(datetime 2013 2 18 :day-of-week 1)
"PI:NAME:<NAME>END_PI, 18 Luty"
"PonPI:NAME:<NAME>END_PIiaPI:NAME:<NAME>END_PIek, Luty 18"
"PI:NAME:<NAME>END_PI 18tego Lutego"
"Poniedziałek 18-tego Lutego"
"Poniedziałek, 18-tego Lutego"
"poniedzialek, 18go Lutego"
"Pon, 18 Luty"
(datetime 2013 2 18 :day-of-week 1 :day 18 :month 2)
"Sobota, 2ego Lutego"
(datetime 2013 2 2 :day-of-week 2 :day 2 :month 2)
"Wtorek"
"nastepny wtorek"
"wt."
"wtr."
(datetime 2013 2 19)
"PI:NAME:<NAME>END_PI"
"ten cPI:NAME:<NAME>END_PIek"
"czw"
"czw."
(datetime 2013 2 14)
"PI:NAME:<NAME>END_PI"
"ten PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"pia."
(datetime 2013 2 15)
"PI:NAME:<NAME>END_PI"
"ta PI:NAME:<NAME>END_PI"
"sob"
"sob."
(datetime 2013 2 16)
"PI:NAME:<NAME>END_PI"
"ta niedPI:NAME:<NAME>END_PIa"
"niedz"
"niedz."
(datetime 2013 2 17)
"PI:NAME:<NAME>END_PI"
"pierwszego marca"
"marPI:NAME:<NAME>END_PI"
"1szy marca"
"1szy marzec"
(datetime 2013 3 1 :day 1 :month 3)
"marPI:NAME:<NAME>END_PI 3"
"marzec 3ci"
"3go marca"
(datetime 2013 3 3 :day 3 :month 3)
;; ;;coto
;; "the ides of march"
;; (datetime 2013 3 15 :month 3)
"3ci marca 2015"
"marzec 3ci 2015"
"3 marzec 2015"
"marzec 3 2015"
"trzeci marca 2015"
"3/3/2015"
"3/3/15"
"2015-3-3"
"2015-03-03"
(datetime 2015 3 3 :day 3 :month 3 :year 2015)
;; TODO FIX??
;; "na 15"
;; "na 15tego"
;; (datetime 2013 2 15 :day 15)
"15 Luty"
"15 Lutego"
"Luty 15"
"15-tego Lutego"
"2/15"
;;"on 2/15" POLISH PLZ
"PI:NAME:<NAME>END_PI"
"PiętnPI:NAME:<NAME>END_PI Luty"
"LPI:NAME:<NAME>END_PI"
(datetime 2013 2 15 :day 15 :month 2)
"Sierpień 8"
"Sie 8"
"Sier 8"
"Sierp. 8"
"8 Sie."
"Ósmy Sie."
"Osmego Sie."
(datetime 2013 8 8 :day 8 :month 8)
"PI:NAME:<NAME>END_PI 2014"
"Pazdziernika 2014"
(datetime 2014 10 :year 2014 :month 10)
"10/31/1974"
"10/31/74"
"10-31-74"
(datetime 1974 10 31 :day 31 :month 10 :year 1974)
"14kwiecien 2015"
"Kwiecień 14, 2015"
"14tego Kwietnia 15"
"14-tego Kwietnia 15"
"14-ty Kwietnia 15"
"Czternasty Kwietnia 15"
"Czternastego Kwietnia 15"
(datetime 2015 4 14 :day 14 :month 4 :years 2015)
"nastepny wtorek"
"kolejny wtorek"
"kolejnego wtorku"
"nastepnego wtorku"
"wtorek w przyszłym tygodniu"
"wtorek za tydzień"
(datetime 2013 2 19 :day-of-week 2)
"piatek po nastepnym" ;;DO PPL SAY IT THAT WAY? - [NOPE THEY DON'T]
(datetime 2013 2 22 :day-of-week 2)
"PI:NAME:<NAME>END_PI"
(datetime 2013 3)
"PI:NAME:<NAME>END_PI po nastepnym" ;; [REMOVE]
(datetime 2014 3)
"PI:NAME:<NAME>END_PI, 10 Luty"
"PI:NAME:<NAME>END_PI, Luty 10"
"PI:NAME:<NAME>END_PI, 10tego Luty"
"PI:NAME:<NAME>END_PIa, 10-tego Luty"
"PI:NAME:<NAME>END_PI, 10-ty Lutego"
"PI:NAME:<NAME>END_PI, 10tego Lutego"
(datetime 2013 2 10 :day-of-week 7 :day 10 :month 2)
"Śr., Luty13"
"Śr., 13Luty"
"sr, 13Luty"
"sr, 13tego Lutego"
"Śro., 13Lutego"
"Środa trzynastego lutego"
(datetime 2013 2 13 :day-of-week 3 :day 13 :month 2)
"PI:NAME:<NAME>END_PI, Luty 18"
"PI:NAME:<NAME>END_PI, 18 Lutego"
"PPI:NAME:<NAME>END_PI, Luty 18"
(datetime 2013 2 18 :day-of-week 1 :day 18 :month 2)
;; ; ;; Cycles
"ten tydzien"
"ten tydzień"
"ten tyg"
"tym tygodniu"
(datetime 2013 2 11 :grain :week)
"ostatni tydzien"
"poprzedniego tygodnia"
(datetime 2013 2 4 :grain :week)
"nastepny tydzien"
"nastepnego tygodnia"
(datetime 2013 2 18 :grain :week)
"ostatni miesiac"
"poprzedni miesiac"
"poprzedniego miesiąca"
"po przedniego miesiąca"
"ostatniego miesiaca"
(datetime 2013 1)
"nastepnego miesiaca"
(datetime 2013 3)
"ten kwartał"
"tego kwartału"
"tym kwartale"
(datetime 2013 1 1 :grain :quarter)
"nastepny kwartał"
"następny kwartal"
"kolejnym kwartale"
(datetime 2013 4 1 :grain :quarter)
"trzeci kwartał"
(datetime 2013 7 1 :grain :quarter)
"4ty kwartał 2018"
(datetime 2018 10 1 :grain :quarter)
"poprzedni rok"
"ostatni rok"
(datetime 2012)
"ten rok"
"tym roku"
"obecny rok"
"w obecny rok"
"w obecnym roku"
(datetime 2013)
"w kolejnym roku"
"kolejny rok"
(datetime 2014)
"poprzednia niedziela"
"niedziela z ostatniego tygodnia" ;; [I can see someone say that]
"niedziela ostatniego tygodnia"
"niedziela poprzedniego tygodnia"
"ostatnia niedziela"
(datetime 2013 2 10 :day-of-week 7)
"ostatni wtorek"
"poprzedni wtorek"
(datetime 2013 2 5 :day-of-week 2)
"nastepny wtorek" ; when today is Tuesday, "PI:NAME:<NAME>END_PI" is a week from now
(datetime 2013 2 19 :day-of-week 2)
"nastepna środa" ; when today is Tuesday, "mercredi prochain" is tomorrow
(datetime 2013 2 13 :day-of-week 3)
;;"wednesday of next week"
"sroda nastepnego tygodnia"
"środa w przyszłym tygodniu"
"środa za tydzień"
(datetime 2013 2 20 :day-of-week 3)
"piatek nastepnego tygodnia"
(datetime 2013 2 22 :day-of-week 5)
"poniedzialek tego tygodnia"
(datetime 2013 2 11 :day-of-week 1)
"wtorek tego tygodnia"
"wtorek w tym tygodniu"
"ten wtorek"
(datetime 2013 2 12 :day-of-week 2)
"środa w tym tygodniu"
"ta środa"
(datetime 2013 2 13 :day-of-week 3)
"pojutrze"
"po jutrze"
"dzień po jutrze"
(datetime 2013 2 14)
"dzień przed wczoraj"
(datetime 2013 2 10)
"PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI"
(datetime 2013 3 25 :day-of-week 1)
"PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI w Marcu 2014"
"ostatnia PI:NAME:<NAME>END_PIa marca 2014"
(datetime 2014 3 30 :day-of-week 7)
"trzeci dzień października"
"trzeci dzień w październiku"
(datetime 2013 10 3)
"pierwszy tydzień października 2014"
"pierwszy tydzien w październiku 2014"
(datetime 2014 10 6 :grain :week)
;; TODO JAK TO BEDZIE PO PL? "Tydzien w ktorym jest 6ty paź"?
;; "the week of october 6th"
;; "the week of october 7th"
;; (datetime 2013 10 7 :grain :week)
"ostatni dzień w październiku 2015"
"ostatni dzień października 2015"
(datetime 2015 10 31)
"ostatni tydzień we wrześniu 2014"
"ostatni tydzień września 2014"
(datetime 2014 9 22 :grain :week)
;; nth of
"pierwszy wtorek w październiku"
"pierwszy wtorek października"
(datetime 2013 10 1)
"trzeci wtorek we wrześniu 2014"
"trzeci wtorek września 2014"
(datetime 2014 9 16)
"pierwsza środa w październiku 2014"
"pierwsza środa października 2014"
(datetime 2014 10 1)
"druga środa w październiku 2014"
"druga środa października 2014"
(datetime 2014 10 8)
;; Hours
"o 3 rano"
"3 rano"
"3 z rana"
"o trzeciej rano"
"o trzeciej z rana"
(datetime 2013 2 13 3)
"3:18 rano"
(datetime 2013 2 12 3 18)
"o trzeciej"
"o 3 po południu"
"3 po południu"
"3 popołudniu"
"trzecia popoludniu"
"o trzeciej popoludniu"
"piętnasta godzina"
"15sta godzina"
"o piętnastej"
"o 15stej"
(datetime 2013 2 12 15 :hour 3 :meridiem :pm)
"6 po południu"
"6 popołudniu"
"szósta popoludniu"
"o szostej popoludniu"
"o 18stej"
"osiemnasta godzina"
"o osiemnastej"
(datetime 2013 2 12 18 :hour 6 :meridiem :pm)
"7 po południu"
"7 popołudniu"
"siódma popoludniu"
"o siodmej popoludniu"
"o dziewiętnastej"
"dziewietnasta godzina"
(datetime 2013 2 12 19 :hour 7 :meridiem :pm)
"8 wieczorem"
"8 popołudniu"
"osma w nocy"
"ósma wieczorem"
"dwudziesta godzina"
(datetime 2013 2 12 20 :hour 8 :meridiem :pm)
"dziewiata wieczorem"
"dziewiąta popołudniu"
"dziewiata po południu"
"dziewiąta wieczorem"
"dziewiąta nocą"
"dziewiąta w nocy"
"9 wieczorem"
"9 popołudniu"
"9 po południu"
"9 wieczorem"
"9 nocą"
"9 w nocy"
"o dziewiatej w nocy"
"dwudziesta pierwsza godzina"
"dwudziestapierwsza godzina"
(datetime 2013 2 12 21 :hour 9 :meridiem :pm)
"dziesiąta wieczorem"
"dziesiata popołudniu"
"dziesiata po południu"
"dziesiata wieczorem"
"dziesiata nocą"
"10 w nocy"
"o dziesiatej w nocy"
"o dwudziestej drugiej"
(datetime 2013 2 12 22 :hour 10 :meridiem :pm)
"jedenasta wieczorem"
"jedenasta w nocy"
"11 w nocy"
"11 wieczorem"
"o jedenastej wieczorem"
"o dwudziestejtrzeciej"
(datetime 2013 2 12 23 :hour 11 :meridiem :pm)
"jutro o drugiej"
(datetime 2013 2 13 2)
"po jutrze o drugiej"
(datetime 2013 2 14 2)
;; "3ish pm" ;; FIXME pm overrides precision
;; "3pm approximately"
"około 3 po południu"
"około trzeciej"
"koło trzeciej"
"o koło trzeciej"
"mniej wiecej o 3"
"tak o 15stej"
;; "at about 3pm"
(datetime 2013 2 12 15 :hour 3 :meridiem :pm) ;; :precision "approximate"
;; "tomorrow 5pm sharp" ;; FIXME precision is lost
"jutro równo o piątej popołudniu"
"jutro równo o 17-stej"
(datetime 2013 2 13 17 :hour 5 :meridiem :pm) ;; :precision "exact"
;; "at 15 past 3pm"
"piętnaście po trzeciej"
"15 po trzeciej"
"kwadrans po 3"
"trzecia piętnaście"
;; "3:15 in the afternon"
"15:15"
;; "3:15pm"
;; "3:15PM"
;; "3:15p"
(datetime 2013 2 12 15 15 :hour 3 :minute 15 :meridiem :pm)
"20 po 3"
"3:20"
"3:20 w poludnie"
"trzecia dwadzieścia"
(datetime 2013 2 12 15 20 :hour 3 :minute 20 :meridiem :pm)
;; "at half past three pm"
"w pół do szesnastej"
"pol po trzeciej"
"15:30"
;; "3:30pm"
;; "3:30PM"
;; "330 p.m."
;; "3:30 p m"
(datetime 2013 2 12 15 30 :hour 3 :minute 30 :meridiem :pm)
"3:30"
;; "half three"
(datetime 2013 2 12 15 30 :hour 3 :minute 30)
"15:23:24"
(datetime 2013 2 12 15 23 24 :hour 15 :minute 23 :second 24)
"kwadrans do południa"
"kwadrans przed południem"
"kwadrans do 12stej"
"11:45"
(datetime 2013 2 12 11 45 :hour 11 :minute 45)
;;"8 dziś wieczorem" FIX Should produce both the interval and time?
"8 wieczorem"
"8 tego wieczora"
(datetime 2013 2 12 20)
;; Mixing date and time
"o 7:30 popołudniu Piatek, 20 Wrzesień"
"o 7:30 popołudniu Piatek, Wrzesień 20"
(datetime 2013 9 20 19 30 :hour 7 :minute 30 :meridiem :pm)
"o 9 rano w Sobote"
"w Sobote na 9 rano"
(datetime 2013 2 16 9 :day-of-week 6 :hour 9 :meridiem :am)
"Pia, Lip 18, 2014 19:00"
(datetime 2014 7 18 19 0 :day-of-week 5 :hour 7 :meridiem :pm)
;; ; ;; Involving periods
"w sekundę"
"za sekundę"
"sekunde od teraz"
(datetime 2013 2 12 4 30 1)
"za minutę"
"za jedną minutę"
"przez minutę"
(datetime 2013 2 12 4 31 0)
"w 2 minuty"
"za jeszcze 2 minuty"
"2 minuty od teraz"
(datetime 2013 2 12 4 32 0)
"w 60 minut"
(datetime 2013 2 12 5 30 0)
"w pół godziny"
(datetime 2013 2 12 5 0 0)
"w 2.5 godziny"
"w 2 i pół godziny"
(datetime 2013 2 12 7 0 0)
"w godzinę"
"w 1h"
"w przeciągu godziny"
(datetime 2013 2 12 5 30)
"w kilka godzin"
(datetime 2013 2 12 7 30)
"w 24 godziny"
(datetime 2013 2 13 4 30)
"w jeden dzień"
"dzień od dziś"
(datetime 2013 2 13 4)
"3 lata od dziś"
;;"za trzy lata od dzisiaj" Gives the correct result but produces two
;;identical winners
(datetime 2016 2)
"w 7 dni"
(datetime 2013 2 19 4)
"w jeden tydzień"
"w tydzień"
(datetime 2013 2 19)
"za około pół godziny" ;; FIXME precision is lost
"za jakieś pół godziny"
(datetime 2013 2 12 5 0 0) ;; :precision "approximate"
"7 dni temu"
(datetime 2013 2 5 4)
"14 dni temu"
;;"a fortnight ago"
(datetime 2013 1 29 4)
"tydzien temu"
"jeden tydzień temu"
"1 tydzień temu"
(datetime 2013 2 5)
"trzy tygodnie temu"
(datetime 2013 1 22)
"trzy miesiące temu"
(datetime 2012 11 12)
"dwa lata temu"
(datetime 2011 2)
"7 dni potem"
(datetime 2013 2 19 4)
"14 dni później"
;;"a fortnight hence"
(datetime 2013 2 26 4)
"tydzień później"
"jeden tydzień później"
"1 tydzień później"
(datetime 2013 2 19)
"trzy tygodnie później"
(datetime 2013 3 5)
"trzy miesiące później"
(datetime 2013 5 12)
"dwa lata później"
(datetime 2015 2)
;; ; Seasons
"to lato"
"w to lato"
(datetime-interval [2013 6 21] [2013 9 24])
"ta zima"
"tej zimy"
(datetime-interval [2012 12 21] [2013 3 21])
;; ; US holidays (http://www.timeanddate.com/holidays/us/)
"Wigilia Bożego Narodzenia"
"Wigilia"
(datetime 2013 12 24)
"święta Bożego Narodzenia"
"boże narodzenie"
(datetime 2013 12 25)
"sylwester"
(datetime 2013 12 31)
"walentynki"
(datetime 2013 2 14)
;; "memorial day"
;; (datetime 2013 5 27)
"PI:NAME:<NAME>END_PI"
(datetime 2013 5 12)
"PI:NAME:<NAME>END_PI"
(datetime 2013 6 16)
;; "memorial day week-end"
;; (datetime-interval [2013 5 24 18] [2013 5 28 0])
;; "independence day"
;; "4th of July"
;; "4 of july"
;; (datetime 2013 7 4)
;; "labor day"
;; (datetime 2013 9 2)
"halloween"
(datetime 2013 10 31)
"PI:NAME:<NAME>END_PI"
"dziękczynienie"
(datetime 2013 11 28)
;; ; Part of day (morning, afternoon...)
"ten wieczór"
"dzisiejszy wieczór"
(datetime-interval [2013 2 12 18] [2013 2 13 00])
"jutrzejszy wieczór"
"Środowy wieczór"
"jutrzejsza noc"
(datetime-interval [2013 2 13 18] [2013 2 14 00])
;; "tomorrow lunch"
;; "tomorrow at lunch"
;; (datetime-interval [2013 2 13 12] [2013 2 13 14])
"wczorajszy wieczór"
(datetime-interval [2013 2 11 18] [2013 2 12 00])
"ten week-end"
"ten weekend"
"ten wekend"
(datetime-interval [2013 2 15 18] [2013 2 18 00])
"poniedziałkowy poranek"
(datetime-interval [2013 2 18 4] [2013 2 18 12])
;; TODO
;; "luty 15tego o poranku"
;; "15 lutego o poranku"
;; "poranek 15tego lutego"
;; (datetime-interval [2013 2 15 4] [2013 2 15 12])
;; ; Intervals involving cycles
"ostatnie 2 sekundy"
"ostatnie dwie sekundy"
(datetime-interval [2013 2 12 4 29 58] [2013 2 12 4 30 00])
"kolejne 3 sekundy"
"kolejne trzy sekundy"
(datetime-interval [2013 2 12 4 30 01] [2013 2 12 4 30 04])
"ostatnie 2 minuty"
"ostatnie dwie minuty"
(datetime-interval [2013 2 12 4 28] [2013 2 12 4 30])
"kolejne 3 minuty"
"nastepne trzy minuty"
(datetime-interval [2013 2 12 4 31] [2013 2 12 4 34])
"ostatnia 1 godzina"
"poprzednia jedna godzina"
(datetime-interval [2013 2 12 3] [2013 2 12 4])
"kolejne 3 godziny"
"kolejne trzy godziny"
(datetime-interval [2013 2 12 5] [2013 2 12 8])
"ostatnie 2 dni"
"ostatnie dwa dni"
"poprzednie 2 dni"
(datetime-interval [2013 2 10] [2013 2 12])
"nastepne 3 dni"
"nastepne trzy dni"
(datetime-interval [2013 2 13] [2013 2 16])
"nastepne kilka dni"
(datetime-interval [2013 2 13] [2013 2 16])
"ostatnie 2 tygodnie"
"ostatnie dwa tygodnie"
"poprzednie 2 tygodnie"
(datetime-interval [2013 1 28 :grain :week] [2013 2 11 :grain :week])
"nastepne 3 tygodnie"
"nastepne trzy tygodnie"
(datetime-interval [2013 2 18 :grain :week] [2013 3 11 :grain :week])
"ostatnie 2 miesiace"
"ostatnie dwa miesiące"
(datetime-interval [2012 12] [2013 02])
"nastepne trzy miesiące"
(datetime-interval [2013 3] [2013 6])
"ostatnie 2 lata"
"ostatnie dwa lata"
(datetime-interval [2011] [2013])
"nastepne 3 lata"
"kolejne trzy lata"
(datetime-interval [2014] [2017])
;; ; Explicit intervals
"Lipiec 13-15"
"Lipca 13 do 15"
;; "Lipca 13tego do 15tego" ;;FIX gives hours instaed of dates
"Lipiec 13 - Lipiec 15"
(datetime-interval [2013 7 13] [2013 7 16])
"Sie 8 - Sie 12"
(datetime-interval [2013 8 8] [2013 8 13])
"9:30 - 11:00"
(datetime-interval [2013 2 12 9 30] [2013 2 12 11 1])
"od 9:30 - 11:00 w Czwartek"
"miedzy 9:30 a 11:00 w czwartek"
"9:30 - 11:00 w czwartek"
"pozniej niż 9:30 ale przed 11:00 w Czwartek"
"Czwartek od 9:30 do 11:00"
(datetime-interval [2013 2 14 9 30] [2013 2 14 11 1])
"Czwartek od 9 rano do 11 rano"
(datetime-interval [2013 2 14 9] [2013 2 14 12])
"11:30-1:30" ; go train this rule!
"11:30-1:30"
"11:30-1:30"
"11:30-1:30"
"11:30-1:30"
"11:30-1:30"
"11:30-1:30"
(datetime-interval [2013 2 12 11 30] [2013 2 12 13 31])
;; "1:30 PM on Sat, Sep 21"
;; (datetime 2013 9 21 13 30)
"w ciągu 2 tygodni"
"w ciągu dwóch tygodni"
(datetime-interval [2013 2 12 4 30 0] [2013 2 26])
"przed drugą po południu"
"przed drugą"
(datetime 2013 2 12 14 :direction :before)
;; "by 2:00pm"
;; (datetime-interval [2013 2 12 4 30 0] [2013 2 12 14])
;; "by EOD"
;; (datetime-interval [2013 2 12 4 30 0] [2013 2 13 0])
;; "by EOM"
;; (datetime-interval [2013 2 12 4 30 0] [2013 3 1 0])
;; "by the end of next month"
;; (datetime-interval [2013 2 12 4 30 0] [2013 4 1 0])
;; ; Timezones
;; "4pm CET"
;; (datetime 2013 2 12 16 :hour 4 :meridiem :pm :timezone "CET")
;; "Thursday 8:00 GMT"
;; (datetime 2013 2 14 8 00 :timezone "GMT")
;; Bookface tests
"dziś o drugiej w południe"
"o drugiej popołudniu"
(datetime 2013 2 12 14)
"4/25 o 4 popołudniu"
"4/25 o 16"
"4/25 o szesnastej"
(datetime 2013 4 25 16)
"3 popoludniu jutro"
(datetime 2013 2 13 15)
"po drugiej po poludniu"
(datetime 2013 2 12 14 :direction :after)
"po pięciu dniach"
(datetime 2013 2 17 4 :direction :after)
"po drugiej po południu"
(datetime 2013 2 12 14 :direction :after)
"przed 11 rano"
(datetime 2013 2 12 11 :direction :before)
"jutro przed 11 rano" ;; FIXME this is actually not ambiguous. it's midnight to 11 am
(datetime 2013 2 13 11 :direction :before)
"w południe"
(datetime-interval [2013 2 12 12] [2013 2 12 19])
;; "at 1:30pm"
;; "1:30pm"
;; (datetime 2013 2 12 13 30)
"w 15 minut"
"w piętnaście minut"
(datetime 2013 2 12 4 45 0)
;; "after lunch"
;; (datetime-interval [2013 2 12 13] [2013 2 12 17])
"10:30"
(datetime 2013 2 12 10 30)
;; "morning" ;; how should we deal with fb mornings?
;; (datetime-interval [2013 2 12 4] [2013 2 12 12])
"nastepny pon"
"kolejny poniedziałek"
(datetime 2013 2 18 :day-of-week 1)
)
|
[
{
"context": "))\n\n(defn clean-vehicle\n [o]\n (let [safe-keys [:id :year :make :model :color :gas_type :license_plate :vin\n :t",
"end": 336,
"score": 0.9207040071487427,
"start": 306,
"tag": "KEY",
"value": "id :year :make :model :color :"
},
{
"context": "let [safe-keys [:id :year :make :model :color :gas_type :license_plate :vin\n :timestamp_c",
"end": 346,
"score": 0.7093985080718994,
"start": 340,
"tag": "KEY",
"value": "type :"
},
{
"context": ":year :make :model :color :gas_type :license_plate :vin\n :timestamp_created]\n ",
"end": 361,
"score": 0.7866310477256775,
"start": 360,
"tag": "KEY",
"value": ":"
},
{
"context": " :license_plate :vin\n :timestamp_created]\n key-old->new {:gas_type :octane}]",
"end": 394,
"score": 0.6070619225502014,
"start": 394,
"tag": "KEY",
"value": ""
},
{
"context": " :timestamp_created]\n key-old->new {:gas_type :octane}]\n (-> o\n (select-keys safe-keys)\n ",
"end": 443,
"score": 0.8546283841133118,
"start": 427,
"tag": "KEY",
"value": "gas_type :octane"
}
] | src/api/vehicles.clj | Purple-Services/api-service | 8 | (ns api.vehicles
(:require [common.config :as config]
[common.db :refer [!select !insert mysql-escape-str]]
[common.util :refer [convert-timestamp]]
[clojure.set :refer [rename-keys]]
[clojure.string :as s]))
(defn clean-vehicle
[o]
(let [safe-keys [:id :year :make :model :color :gas_type :license_plate :vin
:timestamp_created]
key-old->new {:gas_type :octane}]
(-> o
(select-keys safe-keys)
(rename-keys key-old->new)
convert-timestamp)))
(defn get-by-user
"Gets all a user's vehicles."
[db-conn user-id]
{:success true
:vehicles (into []
(map clean-vehicle
(!select db-conn
"vehicles"
["*"]
{:user_id user-id
:active 1}
:append "ORDER BY timestamp_created DESC")))})
| 24251 | (ns api.vehicles
(:require [common.config :as config]
[common.db :refer [!select !insert mysql-escape-str]]
[common.util :refer [convert-timestamp]]
[clojure.set :refer [rename-keys]]
[clojure.string :as s]))
(defn clean-vehicle
[o]
(let [safe-keys [:<KEY>gas_<KEY>license_plate <KEY>vin
:timestamp<KEY>_created]
key-old->new {:<KEY>}]
(-> o
(select-keys safe-keys)
(rename-keys key-old->new)
convert-timestamp)))
(defn get-by-user
"Gets all a user's vehicles."
[db-conn user-id]
{:success true
:vehicles (into []
(map clean-vehicle
(!select db-conn
"vehicles"
["*"]
{:user_id user-id
:active 1}
:append "ORDER BY timestamp_created DESC")))})
| true | (ns api.vehicles
(:require [common.config :as config]
[common.db :refer [!select !insert mysql-escape-str]]
[common.util :refer [convert-timestamp]]
[clojure.set :refer [rename-keys]]
[clojure.string :as s]))
(defn clean-vehicle
[o]
(let [safe-keys [:PI:KEY:<KEY>END_PIgas_PI:KEY:<KEY>END_PIlicense_plate PI:KEY:<KEY>END_PIvin
:timestampPI:KEY:<KEY>END_PI_created]
key-old->new {:PI:KEY:<KEY>END_PI}]
(-> o
(select-keys safe-keys)
(rename-keys key-old->new)
convert-timestamp)))
(defn get-by-user
"Gets all a user's vehicles."
[db-conn user-id]
{:success true
:vehicles (into []
(map clean-vehicle
(!select db-conn
"vehicles"
["*"]
{:user_id user-id
:active 1}
:append "ORDER BY timestamp_created DESC")))})
|
[
{
"context": "ach test-utils/reset-db-fixture)\n\n(def test-user \"the-user\")\n(def test-pass \"usersecret\")\n\n(def test-admin-u",
"end": 363,
"score": 0.9602493643760681,
"start": 355,
"tag": "USERNAME",
"value": "the-user"
},
{
"context": "ture)\n\n(def test-user \"the-user\")\n(def test-pass \"usersecret\")\n\n(def test-admin-user \"admin\")\n(def test-admin-",
"end": 392,
"score": 0.9994077682495117,
"start": 382,
"tag": "PASSWORD",
"value": "usersecret"
},
{
"context": "ef test-admin-user \"admin\")\n(def test-admin-pass \"adminsecret\")\n\n(defn user-login []\n (test-utils/login test-u",
"end": 459,
"score": 0.9993276596069336,
"start": 448,
"tag": "PASSWORD",
"value": "adminsecret"
},
{
"context": "(test-utils/add-test-booking-successfully {:name \"Tom Anderson\"\n :",
"end": 835,
"score": 0.999724805355072,
"start": 823,
"tag": "NAME",
"value": "Tom Anderson"
},
{
"context": " :email \"tom@example.com\"\n :",
"end": 982,
"score": 0.9999287724494934,
"start": 967,
"tag": "EMAIL",
"value": "tom@example.com"
},
{
"context": "(test-utils/add-test-booking-successfully {:name \"Jack Anderson\"\n :",
"end": 1264,
"score": 0.9998148083686829,
"start": 1251,
"tag": "NAME",
"value": "Jack Anderson"
},
{
"context": " :yacht_name \"s/y Abastanza\"\n ",
"end": 1332,
"score": 0.44460341334342957,
"start": 1330,
"tag": "NAME",
"value": "Ab"
},
{
"context": " :email \"jack@example.com\"\n :",
"end": 1412,
"score": 0.9999271631240845,
"start": 1396,
"tag": "EMAIL",
"value": "jack@example.com"
},
{
"context": "-bookings)))\n (is (contains-key-vals {:name \"Jack Anderson\" :yacht_name \"s/y Abastanza\" :booked_date \"2019-0",
"end": 1822,
"score": 0.9998027682304382,
"start": 1809,
"tag": "NAME",
"value": "Jack Anderson"
},
{
"context": "s-key-vals {:name \"Jack Anderson\" :yacht_name \"s/y Abastanza\" :booked_date \"2019-05-01\"} b1))\n (is (conta",
"end": 1850,
"score": 0.8473996520042419,
"start": 1841,
"tag": "NAME",
"value": "Abastanza"
},
{
"context": "05-01\"} b1))\n (is (contains-key-vals {:name \"Jack Anderson\" :yacht_name \"s/y Abastanza\" :booked_date \"2019-0",
"end": 1934,
"score": 0.9997572898864746,
"start": 1921,
"tag": "NAME",
"value": "Jack Anderson"
},
{
"context": "s-key-vals {:name \"Jack Anderson\" :yacht_name \"s/y Abastanza\" :booked_date \"2019-05-02\"} b2))\n (is (conta",
"end": 1962,
"score": 0.9592978358268738,
"start": 1953,
"tag": "NAME",
"value": "Abastanza"
},
{
"context": "05-02\"} b2))\n (is (contains-key-vals {:name \"Tom Anderson\" :yacht_name \"s/y Meriruoho\" :booked_date \"2019-0",
"end": 2045,
"score": 0.9997944831848145,
"start": 2033,
"tag": "NAME",
"value": "Tom Anderson"
},
{
"context": "ns-key-vals {:name \"Tom Anderson\" :yacht_name \"s/y Meriruoho\" :booked_date \"2019-05-10\"} b3))\n (is (conta",
"end": 2073,
"score": 0.8222494721412659,
"start": 2064,
"tag": "NAME",
"value": "Meriruoho"
},
{
"context": "05-10\"} b3))\n (is (contains-key-vals {:name \"Tom Anderson\" :yacht_name \"s/y Meriruoho\" :booked_date \"2019-0",
"end": 2156,
"score": 0.9997749924659729,
"start": 2144,
"tag": "NAME",
"value": "Tom Anderson"
},
{
"context": "ns-key-vals {:name \"Tom Anderson\" :yacht_name \"s/y Meriruoho\" :booked_date \"2019-05-11\"} b4)))))\n\n(def test-bo",
"end": 2184,
"score": 0.8499799966812134,
"start": 2175,
"tag": "NAME",
"value": "Meriruoho"
},
{
"context": " \"2019-05-11\"} b4)))))\n\n(def test-booking {:name \"Tom Anderson\"\n :yacht_name \"s/y Meriruoho\"\n ",
"end": 2260,
"score": 0.9997772574424744,
"start": 2248,
"tag": "NAME",
"value": "Tom Anderson"
},
{
"context": "\"Tom Anderson\"\n :yacht_name \"s/y Meriruoho\"\n :email \"tom@example.com\"\n",
"end": 2303,
"score": 0.6074689030647278,
"start": 2298,
"tag": "NAME",
"value": "Merir"
},
{
"context": "t_name \"s/y Meriruoho\"\n :email \"tom@example.com\"\n :phone \"+35802312345\"\n ",
"end": 2351,
"score": 0.9999216794967651,
"start": 2336,
"tag": "EMAIL",
"value": "tom@example.com"
},
{
"context": "(test-utils/add-test-booking-successfully {:name \"Tom Anderson\"\n :",
"end": 5881,
"score": 0.9996741414070129,
"start": 5869,
"tag": "NAME",
"value": "Tom Anderson"
},
{
"context": " :yacht_name \"s/y Meriruoho\"\n :",
"end": 5956,
"score": 0.7238744497299194,
"start": 5947,
"tag": "NAME",
"value": "Meriruoho"
},
{
"context": " :email \"tom@example.com\"\n :",
"end": 6028,
"score": 0.9999245405197144,
"start": 6013,
"tag": "EMAIL",
"value": "tom@example.com"
},
{
"context": "e-booking-successfully (test-utils/get-secret-id \"Tom Anderson\")\n {:n",
"end": 6324,
"score": 0.9994346499443054,
"start": 6312,
"tag": "NAME",
"value": "Tom Anderson"
},
{
"context": " {:name \"Tom Anderson\"\n :ya",
"end": 6391,
"score": 0.9998242259025574,
"start": 6379,
"tag": "NAME",
"value": "Tom Anderson"
},
{
"context": " :yacht_name \"s/y Meriruoho\"\n :em",
"end": 6464,
"score": 0.8254247903823853,
"start": 6455,
"tag": "NAME",
"value": "Meriruoho"
},
{
"context": " :email \"tom@example.com\"\n :ph",
"end": 6534,
"score": 0.999925971031189,
"start": 6519,
"tag": "EMAIL",
"value": "tom@example.com"
},
{
"context": "lues token)]\n (is (contains-key-vals {:name \"Tom Anderson\" :yacht_name \"s/y Meriruoho\" :booked_date \"2019-0",
"end": 6857,
"score": 0.9998185038566589,
"start": 6845,
"tag": "NAME",
"value": "Tom Anderson"
},
{
"context": "05-15\"} b1))\n (is (contains-key-vals {:name \"Tom Anderson\" :yacht_name \"s/y Meriruoho\" :booked_date \"2019-0",
"end": 6968,
"score": 0.9998352527618408,
"start": 6956,
"tag": "NAME",
"value": "Tom Anderson"
},
{
"context": "(test-utils/add-test-booking-successfully {:name \"Tom Anderson\"\n :",
"end": 7184,
"score": 0.9998448491096497,
"start": 7172,
"tag": "NAME",
"value": "Tom Anderson"
},
{
"context": " :email \"tom@example.com\"\n :",
"end": 7331,
"score": 0.9999240040779114,
"start": 7316,
"tag": "EMAIL",
"value": "tom@example.com"
},
{
"context": "booking-fails-with-400 (test-utils/get-secret-id \"Tom Anderson\")\n {:nam",
"end": 7625,
"score": 0.9997051358222961,
"start": 7613,
"tag": "NAME",
"value": "Tom Anderson"
},
{
"context": " {:name \"Tom Anderson\"\n :yach",
"end": 7690,
"score": 0.9998462796211243,
"start": 7678,
"tag": "NAME",
"value": "Tom Anderson"
},
{
"context": " :email \"tom@example.com\"\n :phon",
"end": 7829,
"score": 0.9999265670776367,
"start": 7814,
"tag": "EMAIL",
"value": "tom@example.com"
},
{
"context": " (test-utils/add-test-booking-unchecked {:name \"Tom Anderson\"\n :yac",
"end": 8182,
"score": 0.9998350143432617,
"start": 8170,
"tag": "NAME",
"value": "Tom Anderson"
},
{
"context": " :email \"tom@example.com\"\n :pho",
"end": 8323,
"score": 0.999925971031189,
"start": 8308,
"tag": "EMAIL",
"value": "tom@example.com"
},
{
"context": "e-booking-successfully (test-utils/get-secret-id \"Tom Anderson\")\n {:n",
"end": 8561,
"score": 0.9997571110725403,
"start": 8549,
"tag": "NAME",
"value": "Tom Anderson"
},
{
"context": " {:name \"Tom Anderson\"\n :ya",
"end": 8628,
"score": 0.9998252987861633,
"start": 8616,
"tag": "NAME",
"value": "Tom Anderson"
},
{
"context": " :email \"tom@example.com\"\n :ph",
"end": 8771,
"score": 0.9999250173568726,
"start": 8756,
"tag": "EMAIL",
"value": "tom@example.com"
},
{
"context": "values token)]\n (is (contains-key-vals {:name \"Tom Anderson\" :yacht_name \"s/y Meriruoho\" :booked_date \"2019-0",
"end": 9088,
"score": 0.9998383522033691,
"start": 9076,
"tag": "NAME",
"value": "Tom Anderson"
},
{
"context": "9-01-15\"} b1))\n (is (contains-key-vals {:name \"Tom Anderson\" :yacht_name \"s/y Meriruoho\" :booked_date \"2019-0",
"end": 9197,
"score": 0.9998288154602051,
"start": 9185,
"tag": "NAME",
"value": "Tom Anderson"
},
{
"context": " (test-utils/add-test-booking-unchecked {:name \"Tom Anderson\"\n :yac",
"end": 9413,
"score": 0.9998142123222351,
"start": 9401,
"tag": "NAME",
"value": "Tom Anderson"
},
{
"context": " :email \"tom@example.com\"\n :pho",
"end": 9554,
"score": 0.9999250173568726,
"start": 9539,
"tag": "EMAIL",
"value": "tom@example.com"
},
{
"context": "booking-fails-with-400 (test-utils/get-secret-id \"Tom Anderson\")\n {:nam",
"end": 9794,
"score": 0.9991338849067688,
"start": 9782,
"tag": "NAME",
"value": "Tom Anderson"
},
{
"context": " {:name \"Tom Anderson\"\n :yach",
"end": 9859,
"score": 0.9998566508293152,
"start": 9847,
"tag": "NAME",
"value": "Tom Anderson"
},
{
"context": " :email \"tom@example.com\"\n :phon",
"end": 9998,
"score": 0.999925971031189,
"start": 9983,
"tag": "EMAIL",
"value": "tom@example.com"
},
{
"context": " (test-utils/add-test-booking-unchecked {:name \"Tom Anderson\"\n :yac",
"end": 10350,
"score": 0.9998109936714172,
"start": 10338,
"tag": "NAME",
"value": "Tom Anderson"
},
{
"context": " :yacht_name \"s/y Meriruoho\"\n ",
"end": 10416,
"score": 0.6842594146728516,
"start": 10413,
"tag": "NAME",
"value": "Mer"
},
{
"context": " :email \"tom@example.com\"\n :pho",
"end": 10491,
"score": 0.9999257326126099,
"start": 10476,
"tag": "EMAIL",
"value": "tom@example.com"
},
{
"context": "booking-fails-with-400 (test-utils/get-secret-id \"Tom Anderson\")\n {:nam",
"end": 10731,
"score": 0.9998332858085632,
"start": 10719,
"tag": "NAME",
"value": "Tom Anderson"
},
{
"context": " {:name \"Tom Anderson\"\n :yach",
"end": 10796,
"score": 0.9999008178710938,
"start": 10784,
"tag": "NAME",
"value": "Tom Anderson"
},
{
"context": " :yacht_name \"s/y Meriruoho\"\n :emai",
"end": 10867,
"score": 0.9847440123558044,
"start": 10858,
"tag": "NAME",
"value": "Meriruoho"
},
{
"context": " :email \"tom@example.com\"\n :phon",
"end": 10935,
"score": 0.999927818775177,
"start": 10920,
"tag": "EMAIL",
"value": "tom@example.com"
},
{
"context": "(test-utils/add-test-booking-successfully {:name \"Matti Myöhäinen\"\n :",
"end": 11305,
"score": 0.9999013543128967,
"start": 11290,
"tag": "NAME",
"value": "Matti Myöhäinen"
},
{
"context": " :email \"matti@example.com\"\n :",
"end": 11456,
"score": 0.999925434589386,
"start": 11439,
"tag": "EMAIL",
"value": "matti@example.com"
},
{
"context": "booking-fails-with-400 (test-utils/get-secret-id \"Matti Myöhäinen\")\n {:nam",
"end": 11755,
"score": 0.9998899102210999,
"start": 11740,
"tag": "NAME",
"value": "Matti Myöhäinen"
},
{
"context": " {:name \"Matti Myöhäinen\"\n :yach",
"end": 11823,
"score": 0.9998974800109863,
"start": 11808,
"tag": "NAME",
"value": "Matti Myöhäinen"
},
{
"context": " :email \"matti@example.com\"\n :phon",
"end": 11966,
"score": 0.9999261498451233,
"start": 11949,
"tag": "EMAIL",
"value": "matti@example.com"
},
{
"context": "(test-utils/add-test-booking-successfully {:name \"Matti Myöhäinen\"\n :",
"end": 12314,
"score": 0.9998971223831177,
"start": 12299,
"tag": "NAME",
"value": "Matti Myöhäinen"
},
{
"context": " :email \"matti@example.com\"\n :",
"end": 12465,
"score": 0.9999265074729919,
"start": 12448,
"tag": "EMAIL",
"value": "matti@example.com"
},
{
"context": "add-test-booking-successfully-parsed-body {:name \"Kimmo Kiireinen\"\n ",
"end": 12855,
"score": 0.9998763203620911,
"start": 12840,
"tag": "NAME",
"value": "Kimmo Kiireinen"
},
{
"context": " :email \"kimmo@example.com\"\n ",
"end": 13042,
"score": 0.9999269843101501,
"start": 13025,
"tag": "EMAIL",
"value": "kimmo@example.com"
},
{
"context": "add-test-booking-successfully-parsed-body {:name \"Reino Rahamies\"\n ",
"end": 14099,
"score": 0.9998877644538879,
"start": 14085,
"tag": "NAME",
"value": "Reino Rahamies"
},
{
"context": " :email \"reiska@example.com\"\n ",
"end": 14290,
"score": 0.9999309778213501,
"start": 14272,
"tag": "EMAIL",
"value": "reiska@example.com"
},
{
"context": "add-test-booking-successfully-parsed-body {:name \"Eero Esteellinen\"\n ",
"end": 15138,
"score": 0.9998904466629028,
"start": 15122,
"tag": "NAME",
"value": "Eero Esteellinen"
},
{
"context": " :email \"eero@example.com\"\n ",
"end": 15327,
"score": 0.99992436170578,
"start": 15311,
"tag": "EMAIL",
"value": "eero@example.com"
},
{
"context": " {:name \"Eero Esteellinen\"\n ",
"end": 15994,
"score": 0.9998914003372192,
"start": 15978,
"tag": "NAME",
"value": "Eero Esteellinen"
},
{
"context": " :email \"eero@example.com\"\n ",
"end": 16193,
"score": 0.9999201893806458,
"start": 16177,
"tag": "EMAIL",
"value": "eero@example.com"
},
{
"context": "add-test-booking-successfully-parsed-body {:name \"Pekka Päättämätön\"\n ",
"end": 17303,
"score": 0.9447029829025269,
"start": 17286,
"tag": "NAME",
"value": "Pekka Päättämätön"
},
{
"context": " :email \"pekka@example.com\"\n ",
"end": 17484,
"score": 0.999925971031189,
"start": 17467,
"tag": "EMAIL",
"value": "pekka@example.com"
},
{
"context": "booking-fails-with-400 (test-utils/get-secret-id \"Pekka Päättämätön\")\n {:n",
"end": 17830,
"score": 0.9726076126098633,
"start": 17813,
"tag": "NAME",
"value": "Pekka Päättämätön"
},
{
"context": " {:name \"Pekka Päättämätön\"\n :ya",
"end": 17902,
"score": 0.9998083114624023,
"start": 17885,
"tag": "NAME",
"value": "Pekka Päättämätön"
},
{
"context": " :email \"pekka@example.com\"\n :ph",
"end": 18051,
"score": 0.9999266266822815,
"start": 18034,
"tag": "EMAIL",
"value": "pekka@example.com"
},
{
"context": "add-test-booking-successfully-parsed-body {:name \"Teijo Tuuliviiri\"\n ",
"end": 18473,
"score": 0.9998835325241089,
"start": 18457,
"tag": "NAME",
"value": "Teijo Tuuliviiri"
},
{
"context": " :email \"teijo@example.com\"\n ",
"end": 18647,
"score": 0.9999279975891113,
"start": 18630,
"tag": "EMAIL",
"value": "teijo@example.com"
},
{
"context": "booking-fails-with-400 (test-utils/get-secret-id \"Teijo Tuuliviiri\")\n {na",
"end": 19067,
"score": 0.9976708889007568,
"start": 19051,
"tag": "NAME",
"value": "Teijo Tuuliviiri"
},
{
"context": " {name \"Teijo Tuuliviiri\"\n :ya",
"end": 19137,
"score": 0.9998934864997864,
"start": 19121,
"tag": "NAME",
"value": "Teijo Tuuliviiri"
},
{
"context": " :email \"teijo@example.com\"\n :ph",
"end": 19279,
"score": 0.9999280571937561,
"start": 19262,
"tag": "EMAIL",
"value": "teijo@example.com"
},
{
"context": "add-test-booking-successfully-parsed-body {:name \"Oiva Yövuorolainen\"\n ",
"end": 19693,
"score": 0.9998332262039185,
"start": 19675,
"tag": "NAME",
"value": "Oiva Yövuorolainen"
},
{
"context": " :email \"teijo@example.com\"\n ",
"end": 19867,
"score": 0.9999285340309143,
"start": 19850,
"tag": "EMAIL",
"value": "teijo@example.com"
},
{
"context": " {:name \"Oiva Yövuorolainen\"\n :ya",
"end": 20287,
"score": 0.999862551689148,
"start": 20269,
"tag": "NAME",
"value": "Oiva Yövuorolainen"
},
{
"context": " :email \"teijo@example.com\"\n :ph",
"end": 20429,
"score": 0.9999246001243591,
"start": 20412,
"tag": "EMAIL",
"value": "teijo@example.com"
},
{
"context": "2] (test-utils/add-test-booking-unchecked {:name \"Tom Anderson\"\n ",
"end": 20850,
"score": 0.9998552203178406,
"start": 20838,
"tag": "NAME",
"value": "Tom Anderson"
},
{
"context": " :email \"tom@example.com\"\n ",
"end": 21039,
"score": 0.9999278783798218,
"start": 21024,
"tag": "EMAIL",
"value": "tom@example.com"
},
{
"context": "fter-delete)))\n (is (contains-key-vals {:name \"Tom Anderson\" :yacht_name \"s/y Meriruoho\" :booked_date \"2019-0",
"end": 21588,
"score": 0.9998307824134827,
"start": 21576,
"tag": "NAME",
"value": "Tom Anderson"
},
{
"context": "2] (test-utils/add-test-booking-unchecked {:name \"Tom Anderson\"\n ",
"end": 21829,
"score": 0.9998394846916199,
"start": 21817,
"tag": "NAME",
"value": "Tom Anderson"
},
{
"context": " :email \"tom@example.com\"\n ",
"end": 22018,
"score": 0.9999288320541382,
"start": 22003,
"tag": "EMAIL",
"value": "tom@example.com"
},
{
"context": "(test-utils/add-test-booking-successfully {:name \"Teijo Tuuliviiri\"\n ",
"end": 22652,
"score": 0.9998931884765625,
"start": 22636,
"tag": "NAME",
"value": "Teijo Tuuliviiri"
},
{
"context": " :email \"teijo@example.com\"\n ",
"end": 22810,
"score": 0.9999225735664368,
"start": 22793,
"tag": "EMAIL",
"value": "teijo@example.com"
},
{
"context": "(test-utils/add-test-booking-successfully {:name \"Turkka Tarkkaavainen\"\n ",
"end": 23196,
"score": 0.9998919367790222,
"start": 23176,
"tag": "NAME",
"value": "Turkka Tarkkaavainen"
},
{
"context": " :email \"turkka@example.com\"\n ",
"end": 23353,
"score": 0.9999255537986755,
"start": 23335,
"tag": "EMAIL",
"value": "turkka@example.com"
},
{
"context": "sers 1)]\n (is (= 2 (count users)))\n (is (= \"Teijo Tuuliviiri\" (:name teijo)))\n (is (= 1 (:number_of_paid_bo",
"end": 23818,
"score": 0.9997584223747253,
"start": 23802,
"tag": "NAME",
"value": "Teijo Tuuliviiri"
},
{
"context": "ber_of_paid_bookings teijo)))\n (is (= \"Turkka Tarkkaavainen\\\" (:name turkka)\"))\n (is (nil? (:numb",
"end": 23907,
"score": 0.8470509648323059,
"start": 23904,
"tag": "NAME",
"value": "ark"
},
{
"context": "(test-utils/add-test-booking-successfully {:name \"Teijo Tuuliviiri\"\n :",
"end": 24153,
"score": 0.99989914894104,
"start": 24137,
"tag": "NAME",
"value": "Teijo Tuuliviiri"
},
{
"context": " :email \"teijo@example.com\"\n :",
"end": 24299,
"score": 0.9999303817749023,
"start": 24282,
"tag": "EMAIL",
"value": "teijo@example.com"
},
{
"context": "\n\n(deftest admin-update-user\n (let [user {:name \"Teijo Tuuliviiri\"\n :yacht_name \"s/y windex\"\n ",
"end": 24754,
"score": 0.9998980760574341,
"start": 24738,
"tag": "NAME",
"value": "Teijo Tuuliviiri"
},
{
"context": " :yacht_name \"s/y windex\"\n :email \"teijo@example.com\"\n :phone \"040333333434\"\n ",
"end": 24834,
"score": 0.9999286532402039,
"start": 24817,
"tag": "EMAIL",
"value": "teijo@example.com"
},
{
"context": "ngs 0)\n (assoc :email \"teijo2@example.com\")\n (dissoc :selected_d",
"end": 25408,
"score": 0.9999310970306396,
"start": 25390,
"tag": "EMAIL",
"value": "teijo2@example.com"
}
] | test/clj/m_cal/booking_tests.clj | jaittola/m-cal | 0 | (ns m-cal.booking-tests
(:require [clojure.test :refer [deftest is testing use-fixtures]]
[clojure.string :refer [blank?]]
[m-cal.test-utils :as test-utils]
[m-cal.config :as app-config]))
(use-fixtures :once test-utils/setup-handler-config-fixture)
(use-fixtures :each test-utils/reset-db-fixture)
(def test-user "the-user")
(def test-pass "usersecret")
(def test-admin-user "admin")
(def test-admin-pass "adminsecret")
(defn user-login []
(test-utils/login test-user test-pass))
(defn admin-login []
(test-utils/login test-admin-user test-admin-pass))
(defn contains-key-vals [expected actual]
(every? (fn [[k v]] (= v (get actual k)))
expected))
(deftest can-list-all-bookings
(let [token (user-login)]
(test-utils/add-test-booking-successfully {:name "Tom Anderson"
:yacht_name "s/y Meriruoho"
:email "tom@example.com"
:phone "040123 4343"
:selected_dates ["2019-05-10" "2019-05-11"]}
token)
(test-utils/add-test-booking-successfully {:name "Jack Anderson"
:yacht_name "s/y Abastanza"
:email "jack@example.com"
:phone "+358 40123 4343"
:selected_dates ["2019-05-01" "2019-05-02"]}
token)
(let [all-bookings (test-utils/get-all-booking-values token)
[b1 b2 b3 b4] all-bookings]
(is (= 4 (count all-bookings)))
(is (contains-key-vals {:name "Jack Anderson" :yacht_name "s/y Abastanza" :booked_date "2019-05-01"} b1))
(is (contains-key-vals {:name "Jack Anderson" :yacht_name "s/y Abastanza" :booked_date "2019-05-02"} b2))
(is (contains-key-vals {:name "Tom Anderson" :yacht_name "s/y Meriruoho" :booked_date "2019-05-10"} b3))
(is (contains-key-vals {:name "Tom Anderson" :yacht_name "s/y Meriruoho" :booked_date "2019-05-11"} b4)))))
(def test-booking {:name "Tom Anderson"
:yacht_name "s/y Meriruoho"
:email "tom@example.com"
:phone "+35802312345"
:selected_dates ["2019-05-12" "2019-05-13"]})
(defn assert-add-booking-fails-with-401
[booking]
(let [response (test-utils/add-test-booking booking)]
(is (= 401 (:status response)))))
(defn assert-add-booking-fails-with-400
[booking token]
(let [response (test-utils/add-test-booking booking token)]
(is (= 400 (:status response)))))
(defn assert-update-booking-fails-with-400
[secret-id booking token]
(let [response (test-utils/update-booking secret-id booking token)]
(is (= 400 (:status response)))))
(deftest user-login-is-required-to-access-bookings
(testing "user must be logged in to add a booking"
(assert-add-booking-fails-with-401 test-booking))
(testing "user must be logged in to list bookings"
(let [response (test-utils/get-all-bookings)]
(is (= 401 (:status response)))))
(testing "user must have a valid token list bookings"
(let [token (user-login) ;; do not use this token
response (test-utils/get-all-bookings "1234")]
(is (= 401 (:status response))))))
(deftest admin-login-is-required-to-access-admin-apis
(testing "admin booking list api cannot be accessed without a token"
(let [response (test-utils/get-all-bookings-admin)]
(is (= 401 (:status response)))))
(testing "admin booking list api cannot be accessed with a user token"
(let [user-token (user-login)
response (test-utils/get-all-bookings-admin user-token)]
(is (= 401 (:status response)))))
(testing "admin booking list api returns a success with an admin token"
(let [admin-token (admin-login)
response (test-utils/get-all-bookings-admin admin-token)]
(is (= 200 (:status response)))))) ;; this test should be expanded to check content
(deftest booking-is-validated
(let [token (user-login)]
(testing "all fields are required"
(doseq [missing-key [:name :yacht_name :phone :email :selected_dates]]
(assert-add-booking-fails-with-400 (dissoc test-booking missing-key) token)))
(testing "dates must be in proper format, take I"
(assert-add-booking-fails-with-400 (assoc test-booking :selected_dates ["abcd" "2019-05-13"]) token))
(testing "dates must be in proper format, take II"
(assert-add-booking-fails-with-400 (assoc test-booking :selected_dates ["2018-13-12" "2019-05-13"]) token))
(testing "dates cannot be before the configured date range"
(assert-add-booking-fails-with-400 (assoc test-booking :selected_dates ["2018-06-12" "2019-05-13"]) token))
(testing "dates for inserts cannot be before today"
(assert-add-booking-fails-with-400 (assoc test-booking :selected_dates ["2018-09-12" "2019-05-13"]) token))
(testing "dates cannot be too far into the future"
(assert-add-booking-fails-with-400 (assoc test-booking :selected_dates ["2019-05-12" "2019-01-13"]) token))
(testing "only one date (two are needed)"
(assert-add-booking-fails-with-400 (assoc test-booking :selected_dates ["2019-05-12"]) token))
(testing "three dates (two are needed)"
(assert-add-booking-fails-with-400 (assoc test-booking :selected_dates ["2019-05-12" "2019-01-13" "2019-01-13"]) token))
(testing "phone number must be in an appropriate format I"
(assert-add-booking-fails-with-400 (assoc test-booking :phone "98989898989") token))))
(deftest can-update-booking
(let [token (user-login)]
(test-utils/add-test-booking-successfully {:name "Tom Anderson"
:yacht_name "s/y Meriruoho"
:email "tom@example.com"
:phone "0812342 2"
:selected_dates ["2019-05-12" "2019-05-13"]}
token)
(test-utils/update-booking-successfully (test-utils/get-secret-id "Tom Anderson")
{:name "Tom Anderson"
:yacht_name "s/y Meriruoho"
:email "tom@example.com"
:phone "+35840998877663"
:selected_dates ["2019-05-15" "2019-05-16"]}
token)
(let [[b1 b2] (test-utils/get-all-booking-values token)]
(is (contains-key-vals {:name "Tom Anderson" :yacht_name "s/y Meriruoho" :booked_date "2019-05-15"} b1))
(is (contains-key-vals {:name "Tom Anderson" :yacht_name "s/y Meriruoho" :booked_date "2019-05-16"} b2)))))
(deftest booking-update-cannot-contain-only-one-booking
(let [token (user-login)]
(test-utils/add-test-booking-successfully {:name "Tom Anderson"
:yacht_name "s/y Meriruoho"
:email "tom@example.com"
:phone "0812342 2"
:selected_dates ["2019-05-12" "2019-05-13"]}
token)
(assert-update-booking-fails-with-400 (test-utils/get-secret-id "Tom Anderson")
{:name "Tom Anderson"
:yacht_name "s/y Meriruoho"
:email "tom@example.com"
:phone "+35840998877663"
:selected_dates ["2019-05-15"]}
token)))
(deftest booking-update-can-contain-unmodified-dates-in-the-past
(let [token (user-login)]
(test-utils/add-test-booking-unchecked {:name "Tom Anderson"
:yacht_name "s/y Meriruoho"
:email "tom@example.com"
:phone "0912344 5"
:selected_dates ["2019-01-15" "2019-04-13"]})
(test-utils/update-booking-successfully (test-utils/get-secret-id "Tom Anderson")
{:name "Tom Anderson"
:yacht_name "s/y Meriruoho"
:email "tom@example.com"
:phone "+497123412348"
:selected_dates ["2019-01-15" "2019-05-14"]}
token)
(let [[b1 b2] (test-utils/get-all-booking-values token)]
(is (contains-key-vals {:name "Tom Anderson" :yacht_name "s/y Meriruoho" :booked_date "2019-01-15"} b1))
(is (contains-key-vals {:name "Tom Anderson" :yacht_name "s/y Meriruoho" :booked_date "2019-05-14"} b2)))))
(deftest user-cannot-modify-future-dates-to-past-in-update
(let [token (user-login)]
(test-utils/add-test-booking-unchecked {:name "Tom Anderson"
:yacht_name "s/y Meriruoho"
:email "tom@example.com"
:phone "0412222114424"
:selected_dates ["2019-02-02" "2019-04-13"]})
(assert-update-booking-fails-with-400 (test-utils/get-secret-id "Tom Anderson")
{:name "Tom Anderson"
:yacht_name "s/y Meriruoho"
:email "tom@example.com"
:phone "0501234"
:selected_dates ["2019-02-02" "2019-01-31"]}
token)))
(deftest user-cannot-modify-past-dates-to-future-in-update
(let [token (user-login)]
(test-utils/add-test-booking-unchecked {:name "Tom Anderson"
:yacht_name "s/y Meriruoho"
:email "tom@example.com"
:phone "0412222114424"
:selected_dates ["2019-02-02" "2019-04-13"]})
(assert-update-booking-fails-with-400 (test-utils/get-secret-id "Tom Anderson")
{:name "Tom Anderson"
:yacht_name "s/y Meriruoho"
:email "tom@example.com"
:phone "0501234"
:selected_dates ["2019-04-12" "2019-04-13"]}
token)))
(deftest user-can-make-booking-within-buffer-days-but-cannot-change-it
(let [token (user-login)]
(test-utils/add-test-booking-successfully {:name "Matti Myöhäinen"
:yacht_name "s/y Last Minute"
:email "matti@example.com"
:phone "04012345690"
:selected_dates ["2019-03-10" "2019-03-04"]}
token)
(assert-update-booking-fails-with-400 (test-utils/get-secret-id "Matti Myöhäinen")
{:name "Matti Myöhäinen"
:yacht_name "s/y Last minute"
:email "matti@example.com"
:phone "04012345690"
:selected_dates ["2019-03-10" "2019-03-09"]}
token)))
(deftest user-can-make-booking-for-same-date
(let [token (user-login)]
(test-utils/add-test-booking-successfully {:name "Matti Myöhäinen"
:yacht_name "s/y Last Minute"
:email "matti@example.com"
:phone "04012345690"
:selected_dates [(app-config/today) "2019-03-31"]}
token)))
(deftest user-can-pay-one-booking-and-select-one
(let [token (user-login)
body (test-utils/add-test-booking-successfully-parsed-body {:name "Kimmo Kiireinen"
:yacht_name "s/y Quick"
:email "kimmo@example.com"
:phone "0401212122"
:selected_dates ["2019-04-02"]
:number_of_paid_bookings 1}
token)
{ user-id :user_id secret-id :secret_id number-of-paid-bookings :number_of_paid_bookings } (:user body)
all-bookings-in-db (test-utils/get-all-booking-values token)
user-bookings-in-db (->> all-bookings-in-db
(filter #(= (:user-id %) user-id))
(map #(:booked_date %)))]
(is (not (blank? secret-id)))
(is (= 1 number-of-paid-bookings))
(is (= ["2019-04-02"] (:selected_dates body)))
(is (= (:selected_dates body) user-bookings-in-db))))
(deftest user-can-pay-all-and-not-book
(let [token (user-login)
body (test-utils/add-test-booking-successfully-parsed-body {:name "Reino Rahamies"
:yacht_name "s/y Well off"
:email "reiska@example.com"
:phone "0409999999"
:selected_dates []
:number_of_paid_bookings 2}
token)
{ user-id :user_id secret-id :secret_id number-of-paid-bookings :number_of_paid_bookings } (:user body)
all-bookings-in-db (test-utils/get-all-booking-values token)]
(is (not (blank? secret-id)))
(is (= 2 number-of-paid-bookings))
(is (= [] (:selected_dates body)))
(is (= [] all-bookings-in-db))))
(deftest user-can-update-with-one-booking-paid-for
(let [token (user-login)
body (test-utils/add-test-booking-successfully-parsed-body {:name "Eero Esteellinen"
:yacht_name "s/y Obstacle"
:email "eero@example.com"
:phone "0403333333"
:selected_dates ["2019-04-04"]
:number_of_paid_bookings 1}
token)
{ user-id :user_id secret-id :secret_id} (:user body)
query-result (test-utils/get-user-bookings secret-id token)
update-body (test-utils/update-booking-successfully-parsed-body secret-id
{:name "Eero Esteellinen"
:yacht_name "s/y Obstacle"
:email "eero@example.com"
:phone "0403333333"
:selected_dates ["2019-05-02"]}
token)
number-of-paid-bookings (-> update-body
:user
:number_of_paid_bookings)
all-bookings-in-db (test-utils/get-all-booking-values token)
user-bookings-in-db (->> all-bookings-in-db
(filter #(= (:user-id %) user-id))
(map #(:booked_date %)))]
(is (not (blank? secret-id)))
(is (= 1 number-of-paid-bookings))
(is (= ["2019-05-02"] (:selected_dates update-body)))
(is (= (:selected_dates update-body) user-bookings-in-db))))
(deftest user-cannot-modify-paid-booking-count
(let [token (user-login)]
(testing "with no paid bookings, user cannot change to paid bookings"
(test-utils/add-test-booking-successfully-parsed-body {:name "Pekka Päättämätön"
:yacht_name "s/y left-or-right"
:email "pekka@example.com"
:phone "040333333434"
:selected_dates ["2019-04-09" "2019-04-10"]}
token)
(assert-update-booking-fails-with-400 (test-utils/get-secret-id "Pekka Päättämätön")
{:name "Pekka Päättämätön"
:yacht_name "s/y left-or-right"
:email "pekka@example.com"
:phone "040333333434"
:selected_dates []
:number_of_paid_bookings 2}
token))
(testing "with one paid booking, user cannot change to fully paid bookings"
(test-utils/add-test-booking-successfully-parsed-body {:name "Teijo Tuuliviiri"
:yacht_name "s/y windex"
:email "teijo@example.com"
:phone "040333333434"
:selected_dates ["2019-04-11"]
:number_of_paid_bookings 1}
token)
(assert-update-booking-fails-with-400 (test-utils/get-secret-id "Teijo Tuuliviiri")
{name "Teijo Tuuliviiri"
:yacht_name "s/y windex"
:email "teijo@example.com"
:phone "040333333434"
:selected_dates []
:number_of_paid_bookings 2}
token))
(testing "with bookings, user cannot change to one paid booking"
(test-utils/add-test-booking-successfully-parsed-body {:name "Oiva Yövuorolainen"
:yacht_name "s/y windex"
:email "teijo@example.com"
:phone "040333333434"
:selected_dates ["2019-04-12" "2019-04-13"]}
token)
(assert-update-booking-fails-with-400 (test-utils/get-secret-id "Oiva Yövuorolainen")
{:name "Oiva Yövuorolainen"
:yacht_name "s/y windex"
:email "teijo@example.com"
:phone "040333333434"
:selected_dates ["2019-04-12"]
:number_of_paid_bookings 1}
token))))
(deftest admin-del-booking
(let [admin-token (admin-login)
[booking1 booking2] (test-utils/add-test-booking-unchecked {:name "Tom Anderson"
:yacht_name "s/y Meriruoho"
:email "tom@example.com"
:phone "0412222114424"
:selected_dates ["2019-02-02" "2019-04-13"]})
del-response (test-utils/delete-booking-admin (:booking_id booking1) admin-token)
bookings-after-delete (test-utils/get-all-booking-values admin-token)
b1 (first bookings-after-delete)]
(is (= 200 (:status del-response)))
(is (= 1 (count bookings-after-delete)))
(is (contains-key-vals {:name "Tom Anderson" :yacht_name "s/y Meriruoho" :booked_date "2019-04-13"} b1))))
(deftest admin-del-booking-not-available-with-user-token
(let [user-token (user-login)
[booking1 booking2] (test-utils/add-test-booking-unchecked {:name "Tom Anderson"
:yacht_name "s/y Meriruoho"
:email "tom@example.com"
:phone "0412222114424"
:selected_dates ["2019-02-02" "2019-04-13"]})
del-response (test-utils/delete-booking-admin (:booking_id booking1) user-token)
bookings-after-delete (test-utils/get-all-booking-values user-token)]
(is (= 401 (:status del-response)))
(is (= 2 (count bookings-after-delete)))))
(deftest admin-list-all-users
(let [admin-token (admin-login)
user-token (user-login)
_ (test-utils/add-test-booking-successfully {:name "Teijo Tuuliviiri"
:yacht_name "s/y windex"
:email "teijo@example.com"
:phone "040333333434"
:selected_dates ["2019-04-11"]
:number_of_paid_bookings 1}
user-token)
_ (test-utils/add-test-booking-successfully {:name "Turkka Tarkkaavainen"
:yacht_name "s/y View"
:email "turkka@example.com"
:phone "040333332211"
:selected_dates ["2019-04-12" "2019-04-13"]}
user-token)
body (test-utils/get-all-users-admin-successfully-parsed-body admin-token)
users (:users body)
teijo (first users)
turkka (nth users 1)]
(is (= 2 (count users)))
(is (= "Teijo Tuuliviiri" (:name teijo)))
(is (= 1 (:number_of_paid_bookings teijo)))
(is (= "Turkka Tarkkaavainen\" (:name turkka)"))
(is (nil? (:number_of_paid_bookings turkka)))))
(deftest admin-list-all-users-not-available-with-user-token
(let [user-token (user-login)]
(test-utils/add-test-booking-successfully {:name "Teijo Tuuliviiri"
:yacht_name "s/y windex"
:email "teijo@example.com"
:phone "040333333434"
:selected_dates ["2019-04-11"]
:number_of_paid_bookings 1}
user-token)
(is (= 401 (->
(test-utils/get-all-users-admin user-token)
:status)))))
(deftest admin-update-user
(let [user {:name "Teijo Tuuliviiri"
:yacht_name "s/y windex"
:email "teijo@example.com"
:phone "040333333434"
:selected_dates ["2019-04-11"]
:number_of_paid_bookings 1}
admin-token (admin-login)
user-token (user-login)
user-with-booking (test-utils/add-test-booking-successfully-parsed-body user
user-token)
user-id (-> user-with-booking :user :id)
user-for-update (-> user
(assoc :number_of_paid_bookings 0)
(assoc :email "teijo2@example.com")
(dissoc :selected_dates))
update-result (test-utils/update-user-admin user-id
user-for-update
admin-token)
update-result-body (try
(test-utils/extract-json-body update-result)
(catch Exception _ nil))]
(is (= 200 (:status update-result)))
(is (= user-for-update (-> update-result-body
:user
(select-keys [:name :yacht_name :email :phone :number_of_paid_bookings]))))))
| 109366 | (ns m-cal.booking-tests
(:require [clojure.test :refer [deftest is testing use-fixtures]]
[clojure.string :refer [blank?]]
[m-cal.test-utils :as test-utils]
[m-cal.config :as app-config]))
(use-fixtures :once test-utils/setup-handler-config-fixture)
(use-fixtures :each test-utils/reset-db-fixture)
(def test-user "the-user")
(def test-pass "<PASSWORD>")
(def test-admin-user "admin")
(def test-admin-pass "<PASSWORD>")
(defn user-login []
(test-utils/login test-user test-pass))
(defn admin-login []
(test-utils/login test-admin-user test-admin-pass))
(defn contains-key-vals [expected actual]
(every? (fn [[k v]] (= v (get actual k)))
expected))
(deftest can-list-all-bookings
(let [token (user-login)]
(test-utils/add-test-booking-successfully {:name "<NAME>"
:yacht_name "s/y Meriruoho"
:email "<EMAIL>"
:phone "040123 4343"
:selected_dates ["2019-05-10" "2019-05-11"]}
token)
(test-utils/add-test-booking-successfully {:name "<NAME>"
:yacht_name "s/y <NAME>astanza"
:email "<EMAIL>"
:phone "+358 40123 4343"
:selected_dates ["2019-05-01" "2019-05-02"]}
token)
(let [all-bookings (test-utils/get-all-booking-values token)
[b1 b2 b3 b4] all-bookings]
(is (= 4 (count all-bookings)))
(is (contains-key-vals {:name "<NAME>" :yacht_name "s/y <NAME>" :booked_date "2019-05-01"} b1))
(is (contains-key-vals {:name "<NAME>" :yacht_name "s/y <NAME>" :booked_date "2019-05-02"} b2))
(is (contains-key-vals {:name "<NAME>" :yacht_name "s/y <NAME>" :booked_date "2019-05-10"} b3))
(is (contains-key-vals {:name "<NAME>" :yacht_name "s/y <NAME>" :booked_date "2019-05-11"} b4)))))
(def test-booking {:name "<NAME>"
:yacht_name "s/y <NAME>uoho"
:email "<EMAIL>"
:phone "+35802312345"
:selected_dates ["2019-05-12" "2019-05-13"]})
(defn assert-add-booking-fails-with-401
[booking]
(let [response (test-utils/add-test-booking booking)]
(is (= 401 (:status response)))))
(defn assert-add-booking-fails-with-400
[booking token]
(let [response (test-utils/add-test-booking booking token)]
(is (= 400 (:status response)))))
(defn assert-update-booking-fails-with-400
[secret-id booking token]
(let [response (test-utils/update-booking secret-id booking token)]
(is (= 400 (:status response)))))
(deftest user-login-is-required-to-access-bookings
(testing "user must be logged in to add a booking"
(assert-add-booking-fails-with-401 test-booking))
(testing "user must be logged in to list bookings"
(let [response (test-utils/get-all-bookings)]
(is (= 401 (:status response)))))
(testing "user must have a valid token list bookings"
(let [token (user-login) ;; do not use this token
response (test-utils/get-all-bookings "1234")]
(is (= 401 (:status response))))))
(deftest admin-login-is-required-to-access-admin-apis
(testing "admin booking list api cannot be accessed without a token"
(let [response (test-utils/get-all-bookings-admin)]
(is (= 401 (:status response)))))
(testing "admin booking list api cannot be accessed with a user token"
(let [user-token (user-login)
response (test-utils/get-all-bookings-admin user-token)]
(is (= 401 (:status response)))))
(testing "admin booking list api returns a success with an admin token"
(let [admin-token (admin-login)
response (test-utils/get-all-bookings-admin admin-token)]
(is (= 200 (:status response)))))) ;; this test should be expanded to check content
(deftest booking-is-validated
(let [token (user-login)]
(testing "all fields are required"
(doseq [missing-key [:name :yacht_name :phone :email :selected_dates]]
(assert-add-booking-fails-with-400 (dissoc test-booking missing-key) token)))
(testing "dates must be in proper format, take I"
(assert-add-booking-fails-with-400 (assoc test-booking :selected_dates ["abcd" "2019-05-13"]) token))
(testing "dates must be in proper format, take II"
(assert-add-booking-fails-with-400 (assoc test-booking :selected_dates ["2018-13-12" "2019-05-13"]) token))
(testing "dates cannot be before the configured date range"
(assert-add-booking-fails-with-400 (assoc test-booking :selected_dates ["2018-06-12" "2019-05-13"]) token))
(testing "dates for inserts cannot be before today"
(assert-add-booking-fails-with-400 (assoc test-booking :selected_dates ["2018-09-12" "2019-05-13"]) token))
(testing "dates cannot be too far into the future"
(assert-add-booking-fails-with-400 (assoc test-booking :selected_dates ["2019-05-12" "2019-01-13"]) token))
(testing "only one date (two are needed)"
(assert-add-booking-fails-with-400 (assoc test-booking :selected_dates ["2019-05-12"]) token))
(testing "three dates (two are needed)"
(assert-add-booking-fails-with-400 (assoc test-booking :selected_dates ["2019-05-12" "2019-01-13" "2019-01-13"]) token))
(testing "phone number must be in an appropriate format I"
(assert-add-booking-fails-with-400 (assoc test-booking :phone "98989898989") token))))
(deftest can-update-booking
(let [token (user-login)]
(test-utils/add-test-booking-successfully {:name "<NAME>"
:yacht_name "s/y <NAME>"
:email "<EMAIL>"
:phone "0812342 2"
:selected_dates ["2019-05-12" "2019-05-13"]}
token)
(test-utils/update-booking-successfully (test-utils/get-secret-id "<NAME>")
{:name "<NAME>"
:yacht_name "s/y <NAME>"
:email "<EMAIL>"
:phone "+35840998877663"
:selected_dates ["2019-05-15" "2019-05-16"]}
token)
(let [[b1 b2] (test-utils/get-all-booking-values token)]
(is (contains-key-vals {:name "<NAME>" :yacht_name "s/y Meriruoho" :booked_date "2019-05-15"} b1))
(is (contains-key-vals {:name "<NAME>" :yacht_name "s/y Meriruoho" :booked_date "2019-05-16"} b2)))))
(deftest booking-update-cannot-contain-only-one-booking
(let [token (user-login)]
(test-utils/add-test-booking-successfully {:name "<NAME>"
:yacht_name "s/y Meriruoho"
:email "<EMAIL>"
:phone "0812342 2"
:selected_dates ["2019-05-12" "2019-05-13"]}
token)
(assert-update-booking-fails-with-400 (test-utils/get-secret-id "<NAME>")
{:name "<NAME>"
:yacht_name "s/y Meriruoho"
:email "<EMAIL>"
:phone "+35840998877663"
:selected_dates ["2019-05-15"]}
token)))
(deftest booking-update-can-contain-unmodified-dates-in-the-past
(let [token (user-login)]
(test-utils/add-test-booking-unchecked {:name "<NAME>"
:yacht_name "s/y Meriruoho"
:email "<EMAIL>"
:phone "0912344 5"
:selected_dates ["2019-01-15" "2019-04-13"]})
(test-utils/update-booking-successfully (test-utils/get-secret-id "<NAME>")
{:name "<NAME>"
:yacht_name "s/y Meriruoho"
:email "<EMAIL>"
:phone "+497123412348"
:selected_dates ["2019-01-15" "2019-05-14"]}
token)
(let [[b1 b2] (test-utils/get-all-booking-values token)]
(is (contains-key-vals {:name "<NAME>" :yacht_name "s/y Meriruoho" :booked_date "2019-01-15"} b1))
(is (contains-key-vals {:name "<NAME>" :yacht_name "s/y Meriruoho" :booked_date "2019-05-14"} b2)))))
(deftest user-cannot-modify-future-dates-to-past-in-update
(let [token (user-login)]
(test-utils/add-test-booking-unchecked {:name "<NAME>"
:yacht_name "s/y Meriruoho"
:email "<EMAIL>"
:phone "0412222114424"
:selected_dates ["2019-02-02" "2019-04-13"]})
(assert-update-booking-fails-with-400 (test-utils/get-secret-id "<NAME>")
{:name "<NAME>"
:yacht_name "s/y Meriruoho"
:email "<EMAIL>"
:phone "0501234"
:selected_dates ["2019-02-02" "2019-01-31"]}
token)))
(deftest user-cannot-modify-past-dates-to-future-in-update
(let [token (user-login)]
(test-utils/add-test-booking-unchecked {:name "<NAME>"
:yacht_name "s/y <NAME>iruoho"
:email "<EMAIL>"
:phone "0412222114424"
:selected_dates ["2019-02-02" "2019-04-13"]})
(assert-update-booking-fails-with-400 (test-utils/get-secret-id "<NAME>")
{:name "<NAME>"
:yacht_name "s/y <NAME>"
:email "<EMAIL>"
:phone "0501234"
:selected_dates ["2019-04-12" "2019-04-13"]}
token)))
(deftest user-can-make-booking-within-buffer-days-but-cannot-change-it
(let [token (user-login)]
(test-utils/add-test-booking-successfully {:name "<NAME>"
:yacht_name "s/y Last Minute"
:email "<EMAIL>"
:phone "04012345690"
:selected_dates ["2019-03-10" "2019-03-04"]}
token)
(assert-update-booking-fails-with-400 (test-utils/get-secret-id "<NAME>")
{:name "<NAME>"
:yacht_name "s/y Last minute"
:email "<EMAIL>"
:phone "04012345690"
:selected_dates ["2019-03-10" "2019-03-09"]}
token)))
(deftest user-can-make-booking-for-same-date
(let [token (user-login)]
(test-utils/add-test-booking-successfully {:name "<NAME>"
:yacht_name "s/y Last Minute"
:email "<EMAIL>"
:phone "04012345690"
:selected_dates [(app-config/today) "2019-03-31"]}
token)))
(deftest user-can-pay-one-booking-and-select-one
(let [token (user-login)
body (test-utils/add-test-booking-successfully-parsed-body {:name "<NAME>"
:yacht_name "s/y Quick"
:email "<EMAIL>"
:phone "0401212122"
:selected_dates ["2019-04-02"]
:number_of_paid_bookings 1}
token)
{ user-id :user_id secret-id :secret_id number-of-paid-bookings :number_of_paid_bookings } (:user body)
all-bookings-in-db (test-utils/get-all-booking-values token)
user-bookings-in-db (->> all-bookings-in-db
(filter #(= (:user-id %) user-id))
(map #(:booked_date %)))]
(is (not (blank? secret-id)))
(is (= 1 number-of-paid-bookings))
(is (= ["2019-04-02"] (:selected_dates body)))
(is (= (:selected_dates body) user-bookings-in-db))))
(deftest user-can-pay-all-and-not-book
(let [token (user-login)
body (test-utils/add-test-booking-successfully-parsed-body {:name "<NAME>"
:yacht_name "s/y Well off"
:email "<EMAIL>"
:phone "0409999999"
:selected_dates []
:number_of_paid_bookings 2}
token)
{ user-id :user_id secret-id :secret_id number-of-paid-bookings :number_of_paid_bookings } (:user body)
all-bookings-in-db (test-utils/get-all-booking-values token)]
(is (not (blank? secret-id)))
(is (= 2 number-of-paid-bookings))
(is (= [] (:selected_dates body)))
(is (= [] all-bookings-in-db))))
(deftest user-can-update-with-one-booking-paid-for
(let [token (user-login)
body (test-utils/add-test-booking-successfully-parsed-body {:name "<NAME>"
:yacht_name "s/y Obstacle"
:email "<EMAIL>"
:phone "0403333333"
:selected_dates ["2019-04-04"]
:number_of_paid_bookings 1}
token)
{ user-id :user_id secret-id :secret_id} (:user body)
query-result (test-utils/get-user-bookings secret-id token)
update-body (test-utils/update-booking-successfully-parsed-body secret-id
{:name "<NAME>"
:yacht_name "s/y Obstacle"
:email "<EMAIL>"
:phone "0403333333"
:selected_dates ["2019-05-02"]}
token)
number-of-paid-bookings (-> update-body
:user
:number_of_paid_bookings)
all-bookings-in-db (test-utils/get-all-booking-values token)
user-bookings-in-db (->> all-bookings-in-db
(filter #(= (:user-id %) user-id))
(map #(:booked_date %)))]
(is (not (blank? secret-id)))
(is (= 1 number-of-paid-bookings))
(is (= ["2019-05-02"] (:selected_dates update-body)))
(is (= (:selected_dates update-body) user-bookings-in-db))))
(deftest user-cannot-modify-paid-booking-count
(let [token (user-login)]
(testing "with no paid bookings, user cannot change to paid bookings"
(test-utils/add-test-booking-successfully-parsed-body {:name "<NAME>"
:yacht_name "s/y left-or-right"
:email "<EMAIL>"
:phone "040333333434"
:selected_dates ["2019-04-09" "2019-04-10"]}
token)
(assert-update-booking-fails-with-400 (test-utils/get-secret-id "<NAME>")
{:name "<NAME>"
:yacht_name "s/y left-or-right"
:email "<EMAIL>"
:phone "040333333434"
:selected_dates []
:number_of_paid_bookings 2}
token))
(testing "with one paid booking, user cannot change to fully paid bookings"
(test-utils/add-test-booking-successfully-parsed-body {:name "<NAME>"
:yacht_name "s/y windex"
:email "<EMAIL>"
:phone "040333333434"
:selected_dates ["2019-04-11"]
:number_of_paid_bookings 1}
token)
(assert-update-booking-fails-with-400 (test-utils/get-secret-id "<NAME>")
{name "<NAME>"
:yacht_name "s/y windex"
:email "<EMAIL>"
:phone "040333333434"
:selected_dates []
:number_of_paid_bookings 2}
token))
(testing "with bookings, user cannot change to one paid booking"
(test-utils/add-test-booking-successfully-parsed-body {:name "<NAME>"
:yacht_name "s/y windex"
:email "<EMAIL>"
:phone "040333333434"
:selected_dates ["2019-04-12" "2019-04-13"]}
token)
(assert-update-booking-fails-with-400 (test-utils/get-secret-id "Oiva Yövuorolainen")
{:name "<NAME>"
:yacht_name "s/y windex"
:email "<EMAIL>"
:phone "040333333434"
:selected_dates ["2019-04-12"]
:number_of_paid_bookings 1}
token))))
(deftest admin-del-booking
(let [admin-token (admin-login)
[booking1 booking2] (test-utils/add-test-booking-unchecked {:name "<NAME>"
:yacht_name "s/y Meriruoho"
:email "<EMAIL>"
:phone "0412222114424"
:selected_dates ["2019-02-02" "2019-04-13"]})
del-response (test-utils/delete-booking-admin (:booking_id booking1) admin-token)
bookings-after-delete (test-utils/get-all-booking-values admin-token)
b1 (first bookings-after-delete)]
(is (= 200 (:status del-response)))
(is (= 1 (count bookings-after-delete)))
(is (contains-key-vals {:name "<NAME>" :yacht_name "s/y Meriruoho" :booked_date "2019-04-13"} b1))))
(deftest admin-del-booking-not-available-with-user-token
(let [user-token (user-login)
[booking1 booking2] (test-utils/add-test-booking-unchecked {:name "<NAME>"
:yacht_name "s/y Meriruoho"
:email "<EMAIL>"
:phone "0412222114424"
:selected_dates ["2019-02-02" "2019-04-13"]})
del-response (test-utils/delete-booking-admin (:booking_id booking1) user-token)
bookings-after-delete (test-utils/get-all-booking-values user-token)]
(is (= 401 (:status del-response)))
(is (= 2 (count bookings-after-delete)))))
(deftest admin-list-all-users
(let [admin-token (admin-login)
user-token (user-login)
_ (test-utils/add-test-booking-successfully {:name "<NAME>"
:yacht_name "s/y windex"
:email "<EMAIL>"
:phone "040333333434"
:selected_dates ["2019-04-11"]
:number_of_paid_bookings 1}
user-token)
_ (test-utils/add-test-booking-successfully {:name "<NAME>"
:yacht_name "s/y View"
:email "<EMAIL>"
:phone "040333332211"
:selected_dates ["2019-04-12" "2019-04-13"]}
user-token)
body (test-utils/get-all-users-admin-successfully-parsed-body admin-token)
users (:users body)
teijo (first users)
turkka (nth users 1)]
(is (= 2 (count users)))
(is (= "<NAME>" (:name teijo)))
(is (= 1 (:number_of_paid_bookings teijo)))
(is (= "Turkka T<NAME>kaavainen\" (:name turkka)"))
(is (nil? (:number_of_paid_bookings turkka)))))
(deftest admin-list-all-users-not-available-with-user-token
(let [user-token (user-login)]
(test-utils/add-test-booking-successfully {:name "<NAME>"
:yacht_name "s/y windex"
:email "<EMAIL>"
:phone "040333333434"
:selected_dates ["2019-04-11"]
:number_of_paid_bookings 1}
user-token)
(is (= 401 (->
(test-utils/get-all-users-admin user-token)
:status)))))
(deftest admin-update-user
(let [user {:name "<NAME>"
:yacht_name "s/y windex"
:email "<EMAIL>"
:phone "040333333434"
:selected_dates ["2019-04-11"]
:number_of_paid_bookings 1}
admin-token (admin-login)
user-token (user-login)
user-with-booking (test-utils/add-test-booking-successfully-parsed-body user
user-token)
user-id (-> user-with-booking :user :id)
user-for-update (-> user
(assoc :number_of_paid_bookings 0)
(assoc :email "<EMAIL>")
(dissoc :selected_dates))
update-result (test-utils/update-user-admin user-id
user-for-update
admin-token)
update-result-body (try
(test-utils/extract-json-body update-result)
(catch Exception _ nil))]
(is (= 200 (:status update-result)))
(is (= user-for-update (-> update-result-body
:user
(select-keys [:name :yacht_name :email :phone :number_of_paid_bookings]))))))
| true | (ns m-cal.booking-tests
(:require [clojure.test :refer [deftest is testing use-fixtures]]
[clojure.string :refer [blank?]]
[m-cal.test-utils :as test-utils]
[m-cal.config :as app-config]))
(use-fixtures :once test-utils/setup-handler-config-fixture)
(use-fixtures :each test-utils/reset-db-fixture)
(def test-user "the-user")
(def test-pass "PI:PASSWORD:<PASSWORD>END_PI")
(def test-admin-user "admin")
(def test-admin-pass "PI:PASSWORD:<PASSWORD>END_PI")
(defn user-login []
(test-utils/login test-user test-pass))
(defn admin-login []
(test-utils/login test-admin-user test-admin-pass))
(defn contains-key-vals [expected actual]
(every? (fn [[k v]] (= v (get actual k)))
expected))
(deftest can-list-all-bookings
(let [token (user-login)]
(test-utils/add-test-booking-successfully {:name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y Meriruoho"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "040123 4343"
:selected_dates ["2019-05-10" "2019-05-11"]}
token)
(test-utils/add-test-booking-successfully {:name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y PI:NAME:<NAME>END_PIastanza"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "+358 40123 4343"
:selected_dates ["2019-05-01" "2019-05-02"]}
token)
(let [all-bookings (test-utils/get-all-booking-values token)
[b1 b2 b3 b4] all-bookings]
(is (= 4 (count all-bookings)))
(is (contains-key-vals {:name "PI:NAME:<NAME>END_PI" :yacht_name "s/y PI:NAME:<NAME>END_PI" :booked_date "2019-05-01"} b1))
(is (contains-key-vals {:name "PI:NAME:<NAME>END_PI" :yacht_name "s/y PI:NAME:<NAME>END_PI" :booked_date "2019-05-02"} b2))
(is (contains-key-vals {:name "PI:NAME:<NAME>END_PI" :yacht_name "s/y PI:NAME:<NAME>END_PI" :booked_date "2019-05-10"} b3))
(is (contains-key-vals {:name "PI:NAME:<NAME>END_PI" :yacht_name "s/y PI:NAME:<NAME>END_PI" :booked_date "2019-05-11"} b4)))))
(def test-booking {:name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y PI:NAME:<NAME>END_PIuoho"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "+35802312345"
:selected_dates ["2019-05-12" "2019-05-13"]})
(defn assert-add-booking-fails-with-401
[booking]
(let [response (test-utils/add-test-booking booking)]
(is (= 401 (:status response)))))
(defn assert-add-booking-fails-with-400
[booking token]
(let [response (test-utils/add-test-booking booking token)]
(is (= 400 (:status response)))))
(defn assert-update-booking-fails-with-400
[secret-id booking token]
(let [response (test-utils/update-booking secret-id booking token)]
(is (= 400 (:status response)))))
(deftest user-login-is-required-to-access-bookings
(testing "user must be logged in to add a booking"
(assert-add-booking-fails-with-401 test-booking))
(testing "user must be logged in to list bookings"
(let [response (test-utils/get-all-bookings)]
(is (= 401 (:status response)))))
(testing "user must have a valid token list bookings"
(let [token (user-login) ;; do not use this token
response (test-utils/get-all-bookings "1234")]
(is (= 401 (:status response))))))
(deftest admin-login-is-required-to-access-admin-apis
(testing "admin booking list api cannot be accessed without a token"
(let [response (test-utils/get-all-bookings-admin)]
(is (= 401 (:status response)))))
(testing "admin booking list api cannot be accessed with a user token"
(let [user-token (user-login)
response (test-utils/get-all-bookings-admin user-token)]
(is (= 401 (:status response)))))
(testing "admin booking list api returns a success with an admin token"
(let [admin-token (admin-login)
response (test-utils/get-all-bookings-admin admin-token)]
(is (= 200 (:status response)))))) ;; this test should be expanded to check content
(deftest booking-is-validated
(let [token (user-login)]
(testing "all fields are required"
(doseq [missing-key [:name :yacht_name :phone :email :selected_dates]]
(assert-add-booking-fails-with-400 (dissoc test-booking missing-key) token)))
(testing "dates must be in proper format, take I"
(assert-add-booking-fails-with-400 (assoc test-booking :selected_dates ["abcd" "2019-05-13"]) token))
(testing "dates must be in proper format, take II"
(assert-add-booking-fails-with-400 (assoc test-booking :selected_dates ["2018-13-12" "2019-05-13"]) token))
(testing "dates cannot be before the configured date range"
(assert-add-booking-fails-with-400 (assoc test-booking :selected_dates ["2018-06-12" "2019-05-13"]) token))
(testing "dates for inserts cannot be before today"
(assert-add-booking-fails-with-400 (assoc test-booking :selected_dates ["2018-09-12" "2019-05-13"]) token))
(testing "dates cannot be too far into the future"
(assert-add-booking-fails-with-400 (assoc test-booking :selected_dates ["2019-05-12" "2019-01-13"]) token))
(testing "only one date (two are needed)"
(assert-add-booking-fails-with-400 (assoc test-booking :selected_dates ["2019-05-12"]) token))
(testing "three dates (two are needed)"
(assert-add-booking-fails-with-400 (assoc test-booking :selected_dates ["2019-05-12" "2019-01-13" "2019-01-13"]) token))
(testing "phone number must be in an appropriate format I"
(assert-add-booking-fails-with-400 (assoc test-booking :phone "98989898989") token))))
(deftest can-update-booking
(let [token (user-login)]
(test-utils/add-test-booking-successfully {:name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "0812342 2"
:selected_dates ["2019-05-12" "2019-05-13"]}
token)
(test-utils/update-booking-successfully (test-utils/get-secret-id "PI:NAME:<NAME>END_PI")
{:name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "+35840998877663"
:selected_dates ["2019-05-15" "2019-05-16"]}
token)
(let [[b1 b2] (test-utils/get-all-booking-values token)]
(is (contains-key-vals {:name "PI:NAME:<NAME>END_PI" :yacht_name "s/y Meriruoho" :booked_date "2019-05-15"} b1))
(is (contains-key-vals {:name "PI:NAME:<NAME>END_PI" :yacht_name "s/y Meriruoho" :booked_date "2019-05-16"} b2)))))
(deftest booking-update-cannot-contain-only-one-booking
(let [token (user-login)]
(test-utils/add-test-booking-successfully {:name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y Meriruoho"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "0812342 2"
:selected_dates ["2019-05-12" "2019-05-13"]}
token)
(assert-update-booking-fails-with-400 (test-utils/get-secret-id "PI:NAME:<NAME>END_PI")
{:name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y Meriruoho"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "+35840998877663"
:selected_dates ["2019-05-15"]}
token)))
(deftest booking-update-can-contain-unmodified-dates-in-the-past
(let [token (user-login)]
(test-utils/add-test-booking-unchecked {:name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y Meriruoho"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "0912344 5"
:selected_dates ["2019-01-15" "2019-04-13"]})
(test-utils/update-booking-successfully (test-utils/get-secret-id "PI:NAME:<NAME>END_PI")
{:name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y Meriruoho"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "+497123412348"
:selected_dates ["2019-01-15" "2019-05-14"]}
token)
(let [[b1 b2] (test-utils/get-all-booking-values token)]
(is (contains-key-vals {:name "PI:NAME:<NAME>END_PI" :yacht_name "s/y Meriruoho" :booked_date "2019-01-15"} b1))
(is (contains-key-vals {:name "PI:NAME:<NAME>END_PI" :yacht_name "s/y Meriruoho" :booked_date "2019-05-14"} b2)))))
(deftest user-cannot-modify-future-dates-to-past-in-update
(let [token (user-login)]
(test-utils/add-test-booking-unchecked {:name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y Meriruoho"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "0412222114424"
:selected_dates ["2019-02-02" "2019-04-13"]})
(assert-update-booking-fails-with-400 (test-utils/get-secret-id "PI:NAME:<NAME>END_PI")
{:name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y Meriruoho"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "0501234"
:selected_dates ["2019-02-02" "2019-01-31"]}
token)))
(deftest user-cannot-modify-past-dates-to-future-in-update
(let [token (user-login)]
(test-utils/add-test-booking-unchecked {:name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y PI:NAME:<NAME>END_PIiruoho"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "0412222114424"
:selected_dates ["2019-02-02" "2019-04-13"]})
(assert-update-booking-fails-with-400 (test-utils/get-secret-id "PI:NAME:<NAME>END_PI")
{:name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "0501234"
:selected_dates ["2019-04-12" "2019-04-13"]}
token)))
(deftest user-can-make-booking-within-buffer-days-but-cannot-change-it
(let [token (user-login)]
(test-utils/add-test-booking-successfully {:name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y Last Minute"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "04012345690"
:selected_dates ["2019-03-10" "2019-03-04"]}
token)
(assert-update-booking-fails-with-400 (test-utils/get-secret-id "PI:NAME:<NAME>END_PI")
{:name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y Last minute"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "04012345690"
:selected_dates ["2019-03-10" "2019-03-09"]}
token)))
(deftest user-can-make-booking-for-same-date
(let [token (user-login)]
(test-utils/add-test-booking-successfully {:name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y Last Minute"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "04012345690"
:selected_dates [(app-config/today) "2019-03-31"]}
token)))
(deftest user-can-pay-one-booking-and-select-one
(let [token (user-login)
body (test-utils/add-test-booking-successfully-parsed-body {:name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y Quick"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "0401212122"
:selected_dates ["2019-04-02"]
:number_of_paid_bookings 1}
token)
{ user-id :user_id secret-id :secret_id number-of-paid-bookings :number_of_paid_bookings } (:user body)
all-bookings-in-db (test-utils/get-all-booking-values token)
user-bookings-in-db (->> all-bookings-in-db
(filter #(= (:user-id %) user-id))
(map #(:booked_date %)))]
(is (not (blank? secret-id)))
(is (= 1 number-of-paid-bookings))
(is (= ["2019-04-02"] (:selected_dates body)))
(is (= (:selected_dates body) user-bookings-in-db))))
(deftest user-can-pay-all-and-not-book
(let [token (user-login)
body (test-utils/add-test-booking-successfully-parsed-body {:name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y Well off"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "0409999999"
:selected_dates []
:number_of_paid_bookings 2}
token)
{ user-id :user_id secret-id :secret_id number-of-paid-bookings :number_of_paid_bookings } (:user body)
all-bookings-in-db (test-utils/get-all-booking-values token)]
(is (not (blank? secret-id)))
(is (= 2 number-of-paid-bookings))
(is (= [] (:selected_dates body)))
(is (= [] all-bookings-in-db))))
(deftest user-can-update-with-one-booking-paid-for
(let [token (user-login)
body (test-utils/add-test-booking-successfully-parsed-body {:name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y Obstacle"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "0403333333"
:selected_dates ["2019-04-04"]
:number_of_paid_bookings 1}
token)
{ user-id :user_id secret-id :secret_id} (:user body)
query-result (test-utils/get-user-bookings secret-id token)
update-body (test-utils/update-booking-successfully-parsed-body secret-id
{:name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y Obstacle"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "0403333333"
:selected_dates ["2019-05-02"]}
token)
number-of-paid-bookings (-> update-body
:user
:number_of_paid_bookings)
all-bookings-in-db (test-utils/get-all-booking-values token)
user-bookings-in-db (->> all-bookings-in-db
(filter #(= (:user-id %) user-id))
(map #(:booked_date %)))]
(is (not (blank? secret-id)))
(is (= 1 number-of-paid-bookings))
(is (= ["2019-05-02"] (:selected_dates update-body)))
(is (= (:selected_dates update-body) user-bookings-in-db))))
(deftest user-cannot-modify-paid-booking-count
(let [token (user-login)]
(testing "with no paid bookings, user cannot change to paid bookings"
(test-utils/add-test-booking-successfully-parsed-body {:name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y left-or-right"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "040333333434"
:selected_dates ["2019-04-09" "2019-04-10"]}
token)
(assert-update-booking-fails-with-400 (test-utils/get-secret-id "PI:NAME:<NAME>END_PI")
{:name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y left-or-right"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "040333333434"
:selected_dates []
:number_of_paid_bookings 2}
token))
(testing "with one paid booking, user cannot change to fully paid bookings"
(test-utils/add-test-booking-successfully-parsed-body {:name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y windex"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "040333333434"
:selected_dates ["2019-04-11"]
:number_of_paid_bookings 1}
token)
(assert-update-booking-fails-with-400 (test-utils/get-secret-id "PI:NAME:<NAME>END_PI")
{name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y windex"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "040333333434"
:selected_dates []
:number_of_paid_bookings 2}
token))
(testing "with bookings, user cannot change to one paid booking"
(test-utils/add-test-booking-successfully-parsed-body {:name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y windex"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "040333333434"
:selected_dates ["2019-04-12" "2019-04-13"]}
token)
(assert-update-booking-fails-with-400 (test-utils/get-secret-id "Oiva Yövuorolainen")
{:name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y windex"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "040333333434"
:selected_dates ["2019-04-12"]
:number_of_paid_bookings 1}
token))))
(deftest admin-del-booking
(let [admin-token (admin-login)
[booking1 booking2] (test-utils/add-test-booking-unchecked {:name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y Meriruoho"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "0412222114424"
:selected_dates ["2019-02-02" "2019-04-13"]})
del-response (test-utils/delete-booking-admin (:booking_id booking1) admin-token)
bookings-after-delete (test-utils/get-all-booking-values admin-token)
b1 (first bookings-after-delete)]
(is (= 200 (:status del-response)))
(is (= 1 (count bookings-after-delete)))
(is (contains-key-vals {:name "PI:NAME:<NAME>END_PI" :yacht_name "s/y Meriruoho" :booked_date "2019-04-13"} b1))))
(deftest admin-del-booking-not-available-with-user-token
(let [user-token (user-login)
[booking1 booking2] (test-utils/add-test-booking-unchecked {:name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y Meriruoho"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "0412222114424"
:selected_dates ["2019-02-02" "2019-04-13"]})
del-response (test-utils/delete-booking-admin (:booking_id booking1) user-token)
bookings-after-delete (test-utils/get-all-booking-values user-token)]
(is (= 401 (:status del-response)))
(is (= 2 (count bookings-after-delete)))))
(deftest admin-list-all-users
(let [admin-token (admin-login)
user-token (user-login)
_ (test-utils/add-test-booking-successfully {:name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y windex"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "040333333434"
:selected_dates ["2019-04-11"]
:number_of_paid_bookings 1}
user-token)
_ (test-utils/add-test-booking-successfully {:name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y View"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "040333332211"
:selected_dates ["2019-04-12" "2019-04-13"]}
user-token)
body (test-utils/get-all-users-admin-successfully-parsed-body admin-token)
users (:users body)
teijo (first users)
turkka (nth users 1)]
(is (= 2 (count users)))
(is (= "PI:NAME:<NAME>END_PI" (:name teijo)))
(is (= 1 (:number_of_paid_bookings teijo)))
(is (= "Turkka TPI:NAME:<NAME>END_PIkaavainen\" (:name turkka)"))
(is (nil? (:number_of_paid_bookings turkka)))))
(deftest admin-list-all-users-not-available-with-user-token
(let [user-token (user-login)]
(test-utils/add-test-booking-successfully {:name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y windex"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "040333333434"
:selected_dates ["2019-04-11"]
:number_of_paid_bookings 1}
user-token)
(is (= 401 (->
(test-utils/get-all-users-admin user-token)
:status)))))
(deftest admin-update-user
(let [user {:name "PI:NAME:<NAME>END_PI"
:yacht_name "s/y windex"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "040333333434"
:selected_dates ["2019-04-11"]
:number_of_paid_bookings 1}
admin-token (admin-login)
user-token (user-login)
user-with-booking (test-utils/add-test-booking-successfully-parsed-body user
user-token)
user-id (-> user-with-booking :user :id)
user-for-update (-> user
(assoc :number_of_paid_bookings 0)
(assoc :email "PI:EMAIL:<EMAIL>END_PI")
(dissoc :selected_dates))
update-result (test-utils/update-user-admin user-id
user-for-update
admin-token)
update-result-body (try
(test-utils/extract-json-body update-result)
(catch Exception _ nil))]
(is (= 200 (:status update-result)))
(is (= user-for-update (-> update-result-body
:user
(select-keys [:name :yacht_name :email :phone :number_of_paid_bookings]))))))
|
[
{
"context": "key \"YOUR-API-KEY-HERE\"\n ::secret \"testSecret123\"})\n\n (def post-credential-response\n (post-cre",
"end": 4230,
"score": 0.9953624606132507,
"start": 4217,
"tag": "KEY",
"value": "testSecret123"
}
] | src/nuid/clj_example.clj | NuID/clj-example | 1 | (ns nuid.clj-example
(:require
[clj-http.client :as http]
[clojure.data.json :as json]
[nuid.credential :as credential]
[nuid.credential.challenge :as challenge]
[nuid.credential.lib :as credential.lib]
[nuid.zk.protocol :as zk.protocol]))
(def ^:private encode-body
"NOTE: `nuid.credential.lib/stringify` and `nuid.credential.lib/keywordize`
are helpers necessary for use with encoders that don't respect namespaces.
Encoders that maintain namespaces alleviate this concern and don't require
additional transformation. For that reason it is recommended to use `Transit`
when interacting with the NuID Auth API, if available."
(comp
json/write-str
credential.lib/stringify))
(def ^:private decode-body
(comp
credential.lib/keywordize
(fn [x] (json/read-str x :key-fn keyword))))
(defn post-credential
"Create a new credential based on `:nuid.clj-example/secret` and register it
to Ethereum's Rinkeby test network. In the future, developers will have
control over how credentials are routed and stored."
[{::keys [api-key api-root-url secret] :or {secret "testSecret123"}}]
(let [endpoint (str api-root-url "/credential")
verified (challenge/->verified secret zk.protocol/default)
body (encode-body {::credential/verified verified})
params {:headers {"X-API-Key" api-key}
:content-type :json
:body body}
response (http/post endpoint params)]
(if (= (:status response) 201)
(update response :body decode-body)
response)))
(defn get-credential
"Retrieve public credential data by its persistent identifier, `:nu/id`. The
`:nu/id` of a given credential is simply an encoded public key.
NOTE: Public credential data can also be retrieved by alternative addresses,
such as a ledger transaction id, IPFS hash, torrent address, etc.. The NuID
Auth API aims to give these persistence facilities a unified interface to
facilitate easy retrieval for developers. Credential data can also be
retrieved directly from any persistence abstraction with public read
semantics."
[{::keys [api-key api-root-url] :nu/keys [id]}]
(let [endpoint (str api-root-url "/credential/" id)
params {:headers {"X-API-Key" api-key}}
response (http/get endpoint params)]
(if (= (:status response) 200)
(update response :body decode-body)
response)))
(defn post-challenge
"Issue a short-lived, time-bound challenge against public credential data. The
challenge can be used to create a stateless authentication flow for
persistent, cross-service identities.
NOTE: This endpoint considers any well-formed credential valid input. The
credential needn't be registered through the NuID Auth API, e.g. using
`post-credential`, and needn't be persisted at all. This allows the
`/challenge` endpoint to serve OTP and ephemeral identity use-cases in
addition to traditional login."
[{::keys [api-key api-root-url] :nuid/keys [credential]}]
(let [endpoint (str api-root-url "/challenge")
body (encode-body {:nuid/credential credential})
params {:headers {"X-API-Key" api-key}
:content-type :json
:body body}
response (http/post endpoint params)]
(if (= (:status response) 201)
(update response :body decode-body)
response)))
(defn post-verify
"Verify a `nuid.credential/proof` derived from a given challenge as returned
by `/challenge`.
NOTE: Currently, the NuID Auth API supports a JWT-based flow, but in-built
support for OAuth, OIDC, and other standards-based protocols are on the
immediate roadmap."
[{::keys [api-key api-root-url] ::challenge/keys [jwt] ::credential/keys [proof]}]
(let [endpoint (str api-root-url "/challenge/verify")
body (encode-body {::challenge/jwt jwt ::credential/proof proof})
params {:headers {"X-API-Key" api-key}
:content-type :json
:body body}]
(http/post endpoint params)))
(comment
(def opts
{::api-root-url "https://auth.nuid.io"
::api-key "YOUR-API-KEY-HERE"
::secret "testSecret123"})
(def post-credential-response
(post-credential opts))
(def get-credential-response
(let [id (get-in post-credential-response [:body :nu/id])
opts (assoc opts :nu/id id)]
(get-credential opts)))
(def post-challenge-response
(let [credential (get-in get-credential-response [:body :nuid/credential])
opts (assoc opts :nuid/credential credential)]
(post-challenge opts)))
(def post-verify-response
"NOTE: the `nuid.credential.challenge/jwt` from `post-challenge-response`
expires after 5 seconds by default. The following will result in a `400` if
the JWT has expired, which makes this invocation time-sensitive with respect
to evaluating `post-challenge-response`."
(let [jwt (get-in post-challenge-response [:body ::challenge/jwt])
challenge (challenge/<-jwt jwt)
proof (challenge/->proof (::secret opts) challenge)
opts (assoc opts ::challenge/jwt jwt ::credential/proof proof)]
(try
(post-verify opts)
(catch Exception e
(if (= (:status (ex-data e)) 400)
(prn "Response status 400. NOTE: JWT may have expired.")
(throw e))))))
)
| 108829 | (ns nuid.clj-example
(:require
[clj-http.client :as http]
[clojure.data.json :as json]
[nuid.credential :as credential]
[nuid.credential.challenge :as challenge]
[nuid.credential.lib :as credential.lib]
[nuid.zk.protocol :as zk.protocol]))
(def ^:private encode-body
"NOTE: `nuid.credential.lib/stringify` and `nuid.credential.lib/keywordize`
are helpers necessary for use with encoders that don't respect namespaces.
Encoders that maintain namespaces alleviate this concern and don't require
additional transformation. For that reason it is recommended to use `Transit`
when interacting with the NuID Auth API, if available."
(comp
json/write-str
credential.lib/stringify))
(def ^:private decode-body
(comp
credential.lib/keywordize
(fn [x] (json/read-str x :key-fn keyword))))
(defn post-credential
"Create a new credential based on `:nuid.clj-example/secret` and register it
to Ethereum's Rinkeby test network. In the future, developers will have
control over how credentials are routed and stored."
[{::keys [api-key api-root-url secret] :or {secret "testSecret123"}}]
(let [endpoint (str api-root-url "/credential")
verified (challenge/->verified secret zk.protocol/default)
body (encode-body {::credential/verified verified})
params {:headers {"X-API-Key" api-key}
:content-type :json
:body body}
response (http/post endpoint params)]
(if (= (:status response) 201)
(update response :body decode-body)
response)))
(defn get-credential
"Retrieve public credential data by its persistent identifier, `:nu/id`. The
`:nu/id` of a given credential is simply an encoded public key.
NOTE: Public credential data can also be retrieved by alternative addresses,
such as a ledger transaction id, IPFS hash, torrent address, etc.. The NuID
Auth API aims to give these persistence facilities a unified interface to
facilitate easy retrieval for developers. Credential data can also be
retrieved directly from any persistence abstraction with public read
semantics."
[{::keys [api-key api-root-url] :nu/keys [id]}]
(let [endpoint (str api-root-url "/credential/" id)
params {:headers {"X-API-Key" api-key}}
response (http/get endpoint params)]
(if (= (:status response) 200)
(update response :body decode-body)
response)))
(defn post-challenge
"Issue a short-lived, time-bound challenge against public credential data. The
challenge can be used to create a stateless authentication flow for
persistent, cross-service identities.
NOTE: This endpoint considers any well-formed credential valid input. The
credential needn't be registered through the NuID Auth API, e.g. using
`post-credential`, and needn't be persisted at all. This allows the
`/challenge` endpoint to serve OTP and ephemeral identity use-cases in
addition to traditional login."
[{::keys [api-key api-root-url] :nuid/keys [credential]}]
(let [endpoint (str api-root-url "/challenge")
body (encode-body {:nuid/credential credential})
params {:headers {"X-API-Key" api-key}
:content-type :json
:body body}
response (http/post endpoint params)]
(if (= (:status response) 201)
(update response :body decode-body)
response)))
(defn post-verify
"Verify a `nuid.credential/proof` derived from a given challenge as returned
by `/challenge`.
NOTE: Currently, the NuID Auth API supports a JWT-based flow, but in-built
support for OAuth, OIDC, and other standards-based protocols are on the
immediate roadmap."
[{::keys [api-key api-root-url] ::challenge/keys [jwt] ::credential/keys [proof]}]
(let [endpoint (str api-root-url "/challenge/verify")
body (encode-body {::challenge/jwt jwt ::credential/proof proof})
params {:headers {"X-API-Key" api-key}
:content-type :json
:body body}]
(http/post endpoint params)))
(comment
(def opts
{::api-root-url "https://auth.nuid.io"
::api-key "YOUR-API-KEY-HERE"
::secret "<KEY>"})
(def post-credential-response
(post-credential opts))
(def get-credential-response
(let [id (get-in post-credential-response [:body :nu/id])
opts (assoc opts :nu/id id)]
(get-credential opts)))
(def post-challenge-response
(let [credential (get-in get-credential-response [:body :nuid/credential])
opts (assoc opts :nuid/credential credential)]
(post-challenge opts)))
(def post-verify-response
"NOTE: the `nuid.credential.challenge/jwt` from `post-challenge-response`
expires after 5 seconds by default. The following will result in a `400` if
the JWT has expired, which makes this invocation time-sensitive with respect
to evaluating `post-challenge-response`."
(let [jwt (get-in post-challenge-response [:body ::challenge/jwt])
challenge (challenge/<-jwt jwt)
proof (challenge/->proof (::secret opts) challenge)
opts (assoc opts ::challenge/jwt jwt ::credential/proof proof)]
(try
(post-verify opts)
(catch Exception e
(if (= (:status (ex-data e)) 400)
(prn "Response status 400. NOTE: JWT may have expired.")
(throw e))))))
)
| true | (ns nuid.clj-example
(:require
[clj-http.client :as http]
[clojure.data.json :as json]
[nuid.credential :as credential]
[nuid.credential.challenge :as challenge]
[nuid.credential.lib :as credential.lib]
[nuid.zk.protocol :as zk.protocol]))
(def ^:private encode-body
"NOTE: `nuid.credential.lib/stringify` and `nuid.credential.lib/keywordize`
are helpers necessary for use with encoders that don't respect namespaces.
Encoders that maintain namespaces alleviate this concern and don't require
additional transformation. For that reason it is recommended to use `Transit`
when interacting with the NuID Auth API, if available."
(comp
json/write-str
credential.lib/stringify))
(def ^:private decode-body
(comp
credential.lib/keywordize
(fn [x] (json/read-str x :key-fn keyword))))
(defn post-credential
"Create a new credential based on `:nuid.clj-example/secret` and register it
to Ethereum's Rinkeby test network. In the future, developers will have
control over how credentials are routed and stored."
[{::keys [api-key api-root-url secret] :or {secret "testSecret123"}}]
(let [endpoint (str api-root-url "/credential")
verified (challenge/->verified secret zk.protocol/default)
body (encode-body {::credential/verified verified})
params {:headers {"X-API-Key" api-key}
:content-type :json
:body body}
response (http/post endpoint params)]
(if (= (:status response) 201)
(update response :body decode-body)
response)))
(defn get-credential
"Retrieve public credential data by its persistent identifier, `:nu/id`. The
`:nu/id` of a given credential is simply an encoded public key.
NOTE: Public credential data can also be retrieved by alternative addresses,
such as a ledger transaction id, IPFS hash, torrent address, etc.. The NuID
Auth API aims to give these persistence facilities a unified interface to
facilitate easy retrieval for developers. Credential data can also be
retrieved directly from any persistence abstraction with public read
semantics."
[{::keys [api-key api-root-url] :nu/keys [id]}]
(let [endpoint (str api-root-url "/credential/" id)
params {:headers {"X-API-Key" api-key}}
response (http/get endpoint params)]
(if (= (:status response) 200)
(update response :body decode-body)
response)))
(defn post-challenge
"Issue a short-lived, time-bound challenge against public credential data. The
challenge can be used to create a stateless authentication flow for
persistent, cross-service identities.
NOTE: This endpoint considers any well-formed credential valid input. The
credential needn't be registered through the NuID Auth API, e.g. using
`post-credential`, and needn't be persisted at all. This allows the
`/challenge` endpoint to serve OTP and ephemeral identity use-cases in
addition to traditional login."
[{::keys [api-key api-root-url] :nuid/keys [credential]}]
(let [endpoint (str api-root-url "/challenge")
body (encode-body {:nuid/credential credential})
params {:headers {"X-API-Key" api-key}
:content-type :json
:body body}
response (http/post endpoint params)]
(if (= (:status response) 201)
(update response :body decode-body)
response)))
(defn post-verify
"Verify a `nuid.credential/proof` derived from a given challenge as returned
by `/challenge`.
NOTE: Currently, the NuID Auth API supports a JWT-based flow, but in-built
support for OAuth, OIDC, and other standards-based protocols are on the
immediate roadmap."
[{::keys [api-key api-root-url] ::challenge/keys [jwt] ::credential/keys [proof]}]
(let [endpoint (str api-root-url "/challenge/verify")
body (encode-body {::challenge/jwt jwt ::credential/proof proof})
params {:headers {"X-API-Key" api-key}
:content-type :json
:body body}]
(http/post endpoint params)))
(comment
(def opts
{::api-root-url "https://auth.nuid.io"
::api-key "YOUR-API-KEY-HERE"
::secret "PI:KEY:<KEY>END_PI"})
(def post-credential-response
(post-credential opts))
(def get-credential-response
(let [id (get-in post-credential-response [:body :nu/id])
opts (assoc opts :nu/id id)]
(get-credential opts)))
(def post-challenge-response
(let [credential (get-in get-credential-response [:body :nuid/credential])
opts (assoc opts :nuid/credential credential)]
(post-challenge opts)))
(def post-verify-response
"NOTE: the `nuid.credential.challenge/jwt` from `post-challenge-response`
expires after 5 seconds by default. The following will result in a `400` if
the JWT has expired, which makes this invocation time-sensitive with respect
to evaluating `post-challenge-response`."
(let [jwt (get-in post-challenge-response [:body ::challenge/jwt])
challenge (challenge/<-jwt jwt)
proof (challenge/->proof (::secret opts) challenge)
opts (assoc opts ::challenge/jwt jwt ::credential/proof proof)]
(try
(post-verify opts)
(catch Exception e
(if (= (:status (ex-data e)) 400)
(prn "Response status 400. NOTE: JWT may have expired.")
(throw e))))))
)
|
[
{
"context": ";\n; Copyright 2020 AppsFlyer\n;\n; Licensed under the Apache License, Version 2.",
"end": 28,
"score": 0.9393107891082764,
"start": 19,
"tag": "USERNAME",
"value": "AppsFlyer"
},
{
"context": "dentical both places.\"\n (let [fields {\"name\" \"John Smith\"\n \"email\" \"john@smithcorp.com\"\n ",
"end": 6110,
"score": 0.997962236404419,
"start": 6100,
"tag": "NAME",
"value": "John Smith"
},
{
"context": " {\"name\" \"John Smith\"\n \"email\" \"john@smithcorp.com\"\n \"text\" \"Hey! I am John -> {ho",
"end": 6157,
"score": 0.999931275844574,
"start": 6139,
"tag": "EMAIL",
"value": "john@smithcorp.com"
},
{
"context": "mithcorp.com\"\n \"text\" \"Hey! I am John -> {how} about & this?\"}]\n (let [res @(helpe",
"end": 6200,
"score": 0.9994051456451416,
"start": 6196,
"tag": "NAME",
"value": "John"
}
] | src/test/clojure/com/appsflyer/donkey/client_test.clj | svanburen/donkey | 1 | ;
; Copyright 2020 AppsFlyer
;
; 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 ^:integration com.appsflyer.donkey.client-test
(:require [clojure.test :refer [deftest testing is use-fixtures]]
[com.appsflyer.donkey.middleware.params :as params]
[com.appsflyer.donkey.test-helper :as helper]
[com.appsflyer.donkey.routes :as routes])
(:import (io.netty.handler.codec.http HttpResponseStatus)
(clojure.lang ExceptionInfo)
(com.appsflyer.donkey.client.exception UnsupportedDataTypeException)
(java.nio.charset StandardCharsets)))
(def route-maps
[routes/root-200
routes/echo-route
routes/explicit-consumes-json
routes/explicit-produces-json])
(use-fixtures :once
helper/init-donkey
(fn [test-fn] (helper/init-donkey-server test-fn route-maps [(params/parse-query-params)]))
helper/init-donkey-client)
(deftest test-basic-functionality
(testing "it should get a 200 response code"
(let [res @(helper/make-request {:method :get :uri "/"})]
(is (= 200 (:status res))))))
(deftest test-ring-compliant-response
(testing "The response should include at least :status, :headers, and :body fields"
(let [res @(helper/make-request {:method :get :uri "/echo"})]
(is (= 200 (:status res)))
(is (< 0 (Integer/valueOf ^String (get-in res [:headers "content-length"]))))
(is (bytes? (:body res))))))
(deftest test-not-found-status-code
(testing "it should return a NOT FOUND response when a route doesn't exist"
(let [res @(helper/make-request {:method :post :uri "/foo"})]
(is (= (.code HttpResponseStatus/NOT_FOUND) (:status res))))))
(deftest test-method-not-allowed-status-code
(testing "it should return a METHOD NOT ALLOWED response when an HTTP verb is not supported"
(let [res @(helper/make-request {:method :post :uri "/"})]
(is (= (.code HttpResponseStatus/METHOD_NOT_ALLOWED) (:status res))))))
(deftest test-not-acceptable-status-code
(testing "it should return a NOT ACCEPTABLE response when a route does
not produce an acceptable request mime type"
(let [res @(helper/make-request {:method :get
:uri "/produces/json"
:headers {"accept" "text/html"}})]
(is (= (.code HttpResponseStatus/NOT_ACCEPTABLE) (:status res))))))
(deftest test-unsupported-media-type-status-code
(testing "it should return an UNSUPPORTED MEDIA TYPE response when a route does
not consume the requests mime type"
(let [res @(helper/make-request {:method :post
:uri "/consumes/json"
:headers {"content-type" "text/plain"}}
"Hello world!")]
(is (= (.code HttpResponseStatus/UNSUPPORTED_MEDIA_TYPE) (:status res))))))
(deftest test-bad-request-status-code
(testing "it should return a BAD REQUEST response when the route consumes a mime type
and the request doesn't have a content-type"
(let [res @(helper/make-request {:method :post
:uri "/consumes/json"}
"{\"foo\":\"bar\"}")]
(is (= (.code HttpResponseStatus/BAD_REQUEST) (:status res))))))
(deftest test-unsupported-data-type-exception
(testing "the operation should fail when the body is not a string or byte[]"
(let [ex @(helper/make-request {:method :get
:uri "/"}
{:foo "bar"})]
(is (instance? ExceptionInfo ex))
(is (instance? UnsupportedDataTypeException (ex-cause ex))))))
(defn- parse-response-body [response]
(let [body (:body response)]
(if (string? body)
(read-string body)
(read-string (String. ^bytes body StandardCharsets/UTF_8)))))
(deftest test-query-parameters
(testing "it should parse query parameters in the uri"
(let [params "baz=3&foo=bar"
expected {"baz" "3" "foo" "bar"}
res @(helper/make-request {:method :get, :uri (str "/echo?" params)})
body (parse-response-body res)]
(is (= params (:query-string body)))
(is (= expected (:query-params body)))))
(testing "it should parse query parameters in the configuration and add them
to the url"
(let [res @(helper/make-request {:method :get,
:uri "/echo?key=value",
:query-params {"baz" "3" "foo" "bar"}})
body (parse-response-body res)
expected-query-string "key=value&baz=3&foo=bar"
expected-query-params {"baz" "3" "foo" "bar" "key" "value"}]
(is (= expected-query-string (:query-string body)))
(is (= expected-query-params (:query-params body))))))
(deftest test-unicode-decoding
(let [expected "高性能HTTPServer和Client"
encoded "%E9%AB%98%E6%80%A7%E8%83%BDHTTPServer%E5%92%8CClient"]
(testing "it should decode urlencoded strings in the url and body"
(let [res @(helper/make-request {:method :get, :uri (str "/echo?str=" encoded)})]
(is (= expected (get-in (parse-response-body res) [:query-params "str"]))))
(let [res @(helper/submit-form {:method :post :uri "/echo"} {"str" encoded})]
(is (= expected (get-in (parse-response-body res) [:form-params "str"])))))))
(deftest test-urlencoded-forms
(testing "the form fields should be encoded by the client and then decoded
by the server so they are identical both places."
(let [fields {"name" "John Smith"
"email" "john@smithcorp.com"
"text" "Hey! I am John -> {how} about & this?"}]
(let [res @(helper/submit-form {:method :post :uri "/echo"} fields)]
(let [body (parse-response-body res)]
(is (= "application/x-www-form-urlencoded" (get-in body [:headers "content-type"])))
(is (= fields (:form-params body))))))))
(deftest test-absolute-url
(testing "it should return a 200 response"
(let [res @(helper/make-request {:method :get,
:url (str "http://localhost:" helper/DEFAULT-PORT "/")})]
(is (= 200 (:status res))))
(let [res @(helper/make-request {:method :get,
:url (str "http://localhost:" helper/DEFAULT-PORT)})]
(is (= 200 (:status res))))))
#_(deftest test-https-endpoint
(let [latch (CountDownLatch. 1)]
(->
(client/request helper/donkey-client {:host "reqres.in"
:port 443
:ssl true
:uri "/api/users?page=2"
:method :get})
(request/submit)
(result/on-success (fn [res] (println res) (.countDown latch)))
(result/on-fail (fn [ex] (println ex) (.countDown latch))))
(.await latch 3 TimeUnit/SECONDS)))
;(deftest test-json-file-upload
; (let [file-opts {"filename" "upload-text.json"
; "pathname" (str (System/getProperty "user.dir") "/src/test/resources/upload-text.json")
; "media-type" "application/json"
; "upload-as" "text"}]
; (let [res @(helper/submit-multi-part-form {:method :post :uri "/echo"} {"my-file" file-opts})]
; (let [body (parse-response-body res)]
; (is (.startsWith ^String (get-in body [:headers "content-type"]) "multipart/form-data")))))
;
; (let [file-opts {"filename" "donkey.png"
; "pathname" (str (System/getProperty "user.dir") "/src/test/resources/donkey.png")
; "media-type" "image/png"
; "upload-as" "binary"}]
; (let [res @(helper/submit-multi-part-form {:method :post :uri "/echo"} {"my-file" file-opts})]
; (let [body (parse-response-body res)]
; (is (.startsWith ^String (get-in body [:headers "content-type"]) "multipart/form-data"))))))
| 83866 | ;
; Copyright 2020 AppsFlyer
;
; 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 ^:integration com.appsflyer.donkey.client-test
(:require [clojure.test :refer [deftest testing is use-fixtures]]
[com.appsflyer.donkey.middleware.params :as params]
[com.appsflyer.donkey.test-helper :as helper]
[com.appsflyer.donkey.routes :as routes])
(:import (io.netty.handler.codec.http HttpResponseStatus)
(clojure.lang ExceptionInfo)
(com.appsflyer.donkey.client.exception UnsupportedDataTypeException)
(java.nio.charset StandardCharsets)))
(def route-maps
[routes/root-200
routes/echo-route
routes/explicit-consumes-json
routes/explicit-produces-json])
(use-fixtures :once
helper/init-donkey
(fn [test-fn] (helper/init-donkey-server test-fn route-maps [(params/parse-query-params)]))
helper/init-donkey-client)
(deftest test-basic-functionality
(testing "it should get a 200 response code"
(let [res @(helper/make-request {:method :get :uri "/"})]
(is (= 200 (:status res))))))
(deftest test-ring-compliant-response
(testing "The response should include at least :status, :headers, and :body fields"
(let [res @(helper/make-request {:method :get :uri "/echo"})]
(is (= 200 (:status res)))
(is (< 0 (Integer/valueOf ^String (get-in res [:headers "content-length"]))))
(is (bytes? (:body res))))))
(deftest test-not-found-status-code
(testing "it should return a NOT FOUND response when a route doesn't exist"
(let [res @(helper/make-request {:method :post :uri "/foo"})]
(is (= (.code HttpResponseStatus/NOT_FOUND) (:status res))))))
(deftest test-method-not-allowed-status-code
(testing "it should return a METHOD NOT ALLOWED response when an HTTP verb is not supported"
(let [res @(helper/make-request {:method :post :uri "/"})]
(is (= (.code HttpResponseStatus/METHOD_NOT_ALLOWED) (:status res))))))
(deftest test-not-acceptable-status-code
(testing "it should return a NOT ACCEPTABLE response when a route does
not produce an acceptable request mime type"
(let [res @(helper/make-request {:method :get
:uri "/produces/json"
:headers {"accept" "text/html"}})]
(is (= (.code HttpResponseStatus/NOT_ACCEPTABLE) (:status res))))))
(deftest test-unsupported-media-type-status-code
(testing "it should return an UNSUPPORTED MEDIA TYPE response when a route does
not consume the requests mime type"
(let [res @(helper/make-request {:method :post
:uri "/consumes/json"
:headers {"content-type" "text/plain"}}
"Hello world!")]
(is (= (.code HttpResponseStatus/UNSUPPORTED_MEDIA_TYPE) (:status res))))))
(deftest test-bad-request-status-code
(testing "it should return a BAD REQUEST response when the route consumes a mime type
and the request doesn't have a content-type"
(let [res @(helper/make-request {:method :post
:uri "/consumes/json"}
"{\"foo\":\"bar\"}")]
(is (= (.code HttpResponseStatus/BAD_REQUEST) (:status res))))))
(deftest test-unsupported-data-type-exception
(testing "the operation should fail when the body is not a string or byte[]"
(let [ex @(helper/make-request {:method :get
:uri "/"}
{:foo "bar"})]
(is (instance? ExceptionInfo ex))
(is (instance? UnsupportedDataTypeException (ex-cause ex))))))
(defn- parse-response-body [response]
(let [body (:body response)]
(if (string? body)
(read-string body)
(read-string (String. ^bytes body StandardCharsets/UTF_8)))))
(deftest test-query-parameters
(testing "it should parse query parameters in the uri"
(let [params "baz=3&foo=bar"
expected {"baz" "3" "foo" "bar"}
res @(helper/make-request {:method :get, :uri (str "/echo?" params)})
body (parse-response-body res)]
(is (= params (:query-string body)))
(is (= expected (:query-params body)))))
(testing "it should parse query parameters in the configuration and add them
to the url"
(let [res @(helper/make-request {:method :get,
:uri "/echo?key=value",
:query-params {"baz" "3" "foo" "bar"}})
body (parse-response-body res)
expected-query-string "key=value&baz=3&foo=bar"
expected-query-params {"baz" "3" "foo" "bar" "key" "value"}]
(is (= expected-query-string (:query-string body)))
(is (= expected-query-params (:query-params body))))))
(deftest test-unicode-decoding
(let [expected "高性能HTTPServer和Client"
encoded "%E9%AB%98%E6%80%A7%E8%83%BDHTTPServer%E5%92%8CClient"]
(testing "it should decode urlencoded strings in the url and body"
(let [res @(helper/make-request {:method :get, :uri (str "/echo?str=" encoded)})]
(is (= expected (get-in (parse-response-body res) [:query-params "str"]))))
(let [res @(helper/submit-form {:method :post :uri "/echo"} {"str" encoded})]
(is (= expected (get-in (parse-response-body res) [:form-params "str"])))))))
(deftest test-urlencoded-forms
(testing "the form fields should be encoded by the client and then decoded
by the server so they are identical both places."
(let [fields {"name" "<NAME>"
"email" "<EMAIL>"
"text" "Hey! I am <NAME> -> {how} about & this?"}]
(let [res @(helper/submit-form {:method :post :uri "/echo"} fields)]
(let [body (parse-response-body res)]
(is (= "application/x-www-form-urlencoded" (get-in body [:headers "content-type"])))
(is (= fields (:form-params body))))))))
(deftest test-absolute-url
(testing "it should return a 200 response"
(let [res @(helper/make-request {:method :get,
:url (str "http://localhost:" helper/DEFAULT-PORT "/")})]
(is (= 200 (:status res))))
(let [res @(helper/make-request {:method :get,
:url (str "http://localhost:" helper/DEFAULT-PORT)})]
(is (= 200 (:status res))))))
#_(deftest test-https-endpoint
(let [latch (CountDownLatch. 1)]
(->
(client/request helper/donkey-client {:host "reqres.in"
:port 443
:ssl true
:uri "/api/users?page=2"
:method :get})
(request/submit)
(result/on-success (fn [res] (println res) (.countDown latch)))
(result/on-fail (fn [ex] (println ex) (.countDown latch))))
(.await latch 3 TimeUnit/SECONDS)))
;(deftest test-json-file-upload
; (let [file-opts {"filename" "upload-text.json"
; "pathname" (str (System/getProperty "user.dir") "/src/test/resources/upload-text.json")
; "media-type" "application/json"
; "upload-as" "text"}]
; (let [res @(helper/submit-multi-part-form {:method :post :uri "/echo"} {"my-file" file-opts})]
; (let [body (parse-response-body res)]
; (is (.startsWith ^String (get-in body [:headers "content-type"]) "multipart/form-data")))))
;
; (let [file-opts {"filename" "donkey.png"
; "pathname" (str (System/getProperty "user.dir") "/src/test/resources/donkey.png")
; "media-type" "image/png"
; "upload-as" "binary"}]
; (let [res @(helper/submit-multi-part-form {:method :post :uri "/echo"} {"my-file" file-opts})]
; (let [body (parse-response-body res)]
; (is (.startsWith ^String (get-in body [:headers "content-type"]) "multipart/form-data"))))))
| true | ;
; Copyright 2020 AppsFlyer
;
; 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 ^:integration com.appsflyer.donkey.client-test
(:require [clojure.test :refer [deftest testing is use-fixtures]]
[com.appsflyer.donkey.middleware.params :as params]
[com.appsflyer.donkey.test-helper :as helper]
[com.appsflyer.donkey.routes :as routes])
(:import (io.netty.handler.codec.http HttpResponseStatus)
(clojure.lang ExceptionInfo)
(com.appsflyer.donkey.client.exception UnsupportedDataTypeException)
(java.nio.charset StandardCharsets)))
(def route-maps
[routes/root-200
routes/echo-route
routes/explicit-consumes-json
routes/explicit-produces-json])
(use-fixtures :once
helper/init-donkey
(fn [test-fn] (helper/init-donkey-server test-fn route-maps [(params/parse-query-params)]))
helper/init-donkey-client)
(deftest test-basic-functionality
(testing "it should get a 200 response code"
(let [res @(helper/make-request {:method :get :uri "/"})]
(is (= 200 (:status res))))))
(deftest test-ring-compliant-response
(testing "The response should include at least :status, :headers, and :body fields"
(let [res @(helper/make-request {:method :get :uri "/echo"})]
(is (= 200 (:status res)))
(is (< 0 (Integer/valueOf ^String (get-in res [:headers "content-length"]))))
(is (bytes? (:body res))))))
(deftest test-not-found-status-code
(testing "it should return a NOT FOUND response when a route doesn't exist"
(let [res @(helper/make-request {:method :post :uri "/foo"})]
(is (= (.code HttpResponseStatus/NOT_FOUND) (:status res))))))
(deftest test-method-not-allowed-status-code
(testing "it should return a METHOD NOT ALLOWED response when an HTTP verb is not supported"
(let [res @(helper/make-request {:method :post :uri "/"})]
(is (= (.code HttpResponseStatus/METHOD_NOT_ALLOWED) (:status res))))))
(deftest test-not-acceptable-status-code
(testing "it should return a NOT ACCEPTABLE response when a route does
not produce an acceptable request mime type"
(let [res @(helper/make-request {:method :get
:uri "/produces/json"
:headers {"accept" "text/html"}})]
(is (= (.code HttpResponseStatus/NOT_ACCEPTABLE) (:status res))))))
(deftest test-unsupported-media-type-status-code
(testing "it should return an UNSUPPORTED MEDIA TYPE response when a route does
not consume the requests mime type"
(let [res @(helper/make-request {:method :post
:uri "/consumes/json"
:headers {"content-type" "text/plain"}}
"Hello world!")]
(is (= (.code HttpResponseStatus/UNSUPPORTED_MEDIA_TYPE) (:status res))))))
(deftest test-bad-request-status-code
(testing "it should return a BAD REQUEST response when the route consumes a mime type
and the request doesn't have a content-type"
(let [res @(helper/make-request {:method :post
:uri "/consumes/json"}
"{\"foo\":\"bar\"}")]
(is (= (.code HttpResponseStatus/BAD_REQUEST) (:status res))))))
(deftest test-unsupported-data-type-exception
(testing "the operation should fail when the body is not a string or byte[]"
(let [ex @(helper/make-request {:method :get
:uri "/"}
{:foo "bar"})]
(is (instance? ExceptionInfo ex))
(is (instance? UnsupportedDataTypeException (ex-cause ex))))))
(defn- parse-response-body [response]
(let [body (:body response)]
(if (string? body)
(read-string body)
(read-string (String. ^bytes body StandardCharsets/UTF_8)))))
(deftest test-query-parameters
(testing "it should parse query parameters in the uri"
(let [params "baz=3&foo=bar"
expected {"baz" "3" "foo" "bar"}
res @(helper/make-request {:method :get, :uri (str "/echo?" params)})
body (parse-response-body res)]
(is (= params (:query-string body)))
(is (= expected (:query-params body)))))
(testing "it should parse query parameters in the configuration and add them
to the url"
(let [res @(helper/make-request {:method :get,
:uri "/echo?key=value",
:query-params {"baz" "3" "foo" "bar"}})
body (parse-response-body res)
expected-query-string "key=value&baz=3&foo=bar"
expected-query-params {"baz" "3" "foo" "bar" "key" "value"}]
(is (= expected-query-string (:query-string body)))
(is (= expected-query-params (:query-params body))))))
(deftest test-unicode-decoding
(let [expected "高性能HTTPServer和Client"
encoded "%E9%AB%98%E6%80%A7%E8%83%BDHTTPServer%E5%92%8CClient"]
(testing "it should decode urlencoded strings in the url and body"
(let [res @(helper/make-request {:method :get, :uri (str "/echo?str=" encoded)})]
(is (= expected (get-in (parse-response-body res) [:query-params "str"]))))
(let [res @(helper/submit-form {:method :post :uri "/echo"} {"str" encoded})]
(is (= expected (get-in (parse-response-body res) [:form-params "str"])))))))
(deftest test-urlencoded-forms
(testing "the form fields should be encoded by the client and then decoded
by the server so they are identical both places."
(let [fields {"name" "PI:NAME:<NAME>END_PI"
"email" "PI:EMAIL:<EMAIL>END_PI"
"text" "Hey! I am PI:NAME:<NAME>END_PI -> {how} about & this?"}]
(let [res @(helper/submit-form {:method :post :uri "/echo"} fields)]
(let [body (parse-response-body res)]
(is (= "application/x-www-form-urlencoded" (get-in body [:headers "content-type"])))
(is (= fields (:form-params body))))))))
(deftest test-absolute-url
(testing "it should return a 200 response"
(let [res @(helper/make-request {:method :get,
:url (str "http://localhost:" helper/DEFAULT-PORT "/")})]
(is (= 200 (:status res))))
(let [res @(helper/make-request {:method :get,
:url (str "http://localhost:" helper/DEFAULT-PORT)})]
(is (= 200 (:status res))))))
#_(deftest test-https-endpoint
(let [latch (CountDownLatch. 1)]
(->
(client/request helper/donkey-client {:host "reqres.in"
:port 443
:ssl true
:uri "/api/users?page=2"
:method :get})
(request/submit)
(result/on-success (fn [res] (println res) (.countDown latch)))
(result/on-fail (fn [ex] (println ex) (.countDown latch))))
(.await latch 3 TimeUnit/SECONDS)))
;(deftest test-json-file-upload
; (let [file-opts {"filename" "upload-text.json"
; "pathname" (str (System/getProperty "user.dir") "/src/test/resources/upload-text.json")
; "media-type" "application/json"
; "upload-as" "text"}]
; (let [res @(helper/submit-multi-part-form {:method :post :uri "/echo"} {"my-file" file-opts})]
; (let [body (parse-response-body res)]
; (is (.startsWith ^String (get-in body [:headers "content-type"]) "multipart/form-data")))))
;
; (let [file-opts {"filename" "donkey.png"
; "pathname" (str (System/getProperty "user.dir") "/src/test/resources/donkey.png")
; "media-type" "image/png"
; "upload-as" "binary"}]
; (let [res @(helper/submit-multi-part-form {:method :post :uri "/echo"} {"my-file" file-opts})]
; (let [body (parse-response-body res)]
; (is (.startsWith ^String (get-in body [:headers "content-type"]) "multipart/form-data"))))))
|
[
{
"context": " \"Code Complete 2nd Edition\"\n :author \"Steve McConnell\"\n :year 2004}\n {:title \"Clea",
"end": 266,
"score": 0.9998973608016968,
"start": 251,
"tag": "NAME",
"value": "Steve McConnell"
},
{
"context": " {:title \"Clean Code\"\n :author \"Robert C. Martin\"\n :year 2008}\n {:title \"The ",
"end": 361,
"score": 0.9998984336853027,
"start": 345,
"tag": "NAME",
"value": "Robert C. Martin"
},
{
"context": " {:title \"The Last Lecture\"\n :author \"Randy Pausch\"\n :year 2008}]]\n (is (= (books/ge",
"end": 458,
"score": 0.9998976588249207,
"start": 446,
"tag": "NAME",
"value": "Randy Pausch"
}
] | 04-clojure/01-examples/05-get-and-unit-test/test/core/books_test.clj | jersson/microservices-templates | 1 | (ns core.books-test
(:require [clojure.test :refer :all]
[core.books :as books]))
(deftest get-all-books-test
(testing "Should return the same books"
(let [books
[{:title "Code Complete 2nd Edition"
:author "Steve McConnell"
:year 2004}
{:title "Clean Code"
:author "Robert C. Martin"
:year 2008}
{:title "The Last Lecture"
:author "Randy Pausch"
:year 2008}]]
(is (= (books/get-all-books) books)))))
| 53524 | (ns core.books-test
(:require [clojure.test :refer :all]
[core.books :as books]))
(deftest get-all-books-test
(testing "Should return the same books"
(let [books
[{:title "Code Complete 2nd Edition"
:author "<NAME>"
:year 2004}
{:title "Clean Code"
:author "<NAME>"
:year 2008}
{:title "The Last Lecture"
:author "<NAME>"
:year 2008}]]
(is (= (books/get-all-books) books)))))
| true | (ns core.books-test
(:require [clojure.test :refer :all]
[core.books :as books]))
(deftest get-all-books-test
(testing "Should return the same books"
(let [books
[{:title "Code Complete 2nd Edition"
:author "PI:NAME:<NAME>END_PI"
:year 2004}
{:title "Clean Code"
:author "PI:NAME:<NAME>END_PI"
:year 2008}
{:title "The Last Lecture"
:author "PI:NAME:<NAME>END_PI"
:year 2008}]]
(is (= (books/get-all-books) books)))))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.