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": " once dependencies have been met.\"\n :author \"Sam Aaron & Jeff Rose\"}\n overtone.libs.deps\n (:require [c", "end": 147, "score": 0.9998733401298523, "start": 138, "tag": "NAME", "value": "Sam Aaron" }, { "context": "dencies have been met.\"\n :author \"Sam Aaron & Jeff Rose\"}\n overtone.libs.deps\n (:require [clojure.set :", "end": 159, "score": 0.999866783618927, "start": 150, "tag": "NAME", "value": "Jeff Rose" } ]
src/overtone/libs/deps.clj
rosejn/overtone
4
(ns ^{:doc "A basic dependency system for specifying the execution of fns once dependencies have been met." :author "Sam Aaron & Jeff Rose"} overtone.libs.deps (:require [clojure.set :as set] [overtone.util.log :as log])) ;; A representation of the state of the dependencies: ;; :satisified - a set of keywords representing ids for each of the satisfied ;; dependencies ;; :todo - a list of functions with associated dependencies which need ;; to be executed when those dependencies are met ;; :done - a list of functions with associated dependencies which have ;; already been executed as their dependencies have been met (defonce dep-state* (agent {:satisfied #{} :todo [] :done []})) (defn- process-handler "Returns a new deps map containing either processed handler or it placed in the todo list" [dep-state key deps task] (apply assoc dep-state (if (set/superset? (:satisfied dep-state) deps) (do (task) [:done (conj (:done dep-state) [key deps task])]) [:todo (conj (:todo dep-state) [key deps task])]))) (defn- replace-handler "Replace all occurances of handers with the given key with the new handler and deps set" [dep-state key deps task] (let [replacer-fn #(if (= key (first %)) [key deps task] %)] {:satisfied (dep-state :satisfied) :todo (map replacer-fn (dep-state :todo)) :done (map replacer-fn (dep-state :done))})) (defn- key-known? "Returns true or false depending on whether this key is associated with a handler in either the completed or todo lists." [dep-state key] (some #(= key (first %)) (concat (:done dep-state) (:todo dep-state)))) (defn- on-deps* "If a handler with this key has already been registered, just replace the handler - either in todo or completed. If the key is unknown, then either execute the handler if the deps are satisfied or add it to the todo list" [dep-state key deps task] (if (key-known? dep-state key) (replace-handler dep-state key deps task) (process-handler dep-state key deps task))) (defn- satisfy* [{:keys [satisfied todo done]} new-deps] ;(log/info (format "new-deps: %s" new-deps)) (let [satisfied (set/union satisfied new-deps) ;_ (log/info (format "satisfied: %s" satisfied)) execute-tasks (fn [[final-done final-todo] [key deps task]] ;(log/info (format "Satisfied? = %s --- sat: %s deps: %s" (set/superset? satisfied deps) satisfied deps)) (if (set/superset? satisfied deps) (do ;(log/info "Satisfying deps: " deps) (task) [(conj final-done [key deps task]) final-todo]) [final-done (conj final-todo [key deps task])])) [t-done t-todo] (reduce execute-tasks [done []] todo)] {:satisfied satisfied :done t-done :todo t-todo})) (defn- deps->set "Converts deps to a deps-set. Deals with single elements or collections." [deps] (if (coll? deps) (set deps) (set [deps]))) (defn on-deps "Specify that a function should be called once one or more dependencies have been satisfied. The function is run immediately if the deps have already been satisfied, otherwise it will run as soon as they are. If a dep handler has already been registered with the same key, a second registration with just replace the first. Uses an agent so it's safe to call this from within a transaction." [deps key handler] (let [deps (deps->set deps)] (send-off dep-state* on-deps* key deps handler))) (defn satisfy-deps "Specifies that a list of dependencies have been satisfied. Uses an agent so it's safe to call this from within a transaction." [& deps] (send-off dep-state* satisfy* (set deps))) (defn reset-deps "Reset the dependency system. Uses an agent so it's safe to call this from within a transaction." [] (send dep-state* (fn [& args] {:satisfied #{} :todo [] :done []}))) (defn unsatisfy-all-dependencies "Unsatisfy all deps and reset completed tasks as todo tasks. Uses an agent so it's safe to call this from within a transaction." [] (send dep-state* (fn [deps] {:satisfied #{} :todo (deps :done) :done []}))) (defn satisfied-deps "Returns a set of all satisfied deps" [] (:satisfied @dep-state*)) (defn deps-satisfied? "Returns true if all the deps (specified either as a single dep or a collection of deps) have been satisfied." [deps] (let [deps (deps->set deps)] (set/superset? (satisfied-deps) deps))) (defn wait-until-deps-satisfied "Makes the current thread sleep until specified deps have been satisfied. Thread enters a sleep cycle sleeping for wait-time ms before each dep check. If timeout is a positive value throws timeout exception if deps haven't been satisfied by timeout ms. Default wait-time is 100ms and default timeout is 10000 ms" ([deps] (wait-until-deps-satisfied deps 10000 100)) ([deps timeout] (wait-until-deps-satisfied deps timeout 100)) ([deps timeout wait-time] (if (<= timeout 0) (while (not (deps-satisfied? deps)) (Thread/sleep wait-time)) (loop [sleep-time 0] (when (> sleep-time timeout) (throw (Exception. (str "The following deps took too long to be satisfied: " deps)))) (when-not (deps-satisfied? deps) (Thread/sleep wait-time) (recur (+ sleep-time wait-time)))))))
376
(ns ^{:doc "A basic dependency system for specifying the execution of fns once dependencies have been met." :author "<NAME> & <NAME>"} overtone.libs.deps (:require [clojure.set :as set] [overtone.util.log :as log])) ;; A representation of the state of the dependencies: ;; :satisified - a set of keywords representing ids for each of the satisfied ;; dependencies ;; :todo - a list of functions with associated dependencies which need ;; to be executed when those dependencies are met ;; :done - a list of functions with associated dependencies which have ;; already been executed as their dependencies have been met (defonce dep-state* (agent {:satisfied #{} :todo [] :done []})) (defn- process-handler "Returns a new deps map containing either processed handler or it placed in the todo list" [dep-state key deps task] (apply assoc dep-state (if (set/superset? (:satisfied dep-state) deps) (do (task) [:done (conj (:done dep-state) [key deps task])]) [:todo (conj (:todo dep-state) [key deps task])]))) (defn- replace-handler "Replace all occurances of handers with the given key with the new handler and deps set" [dep-state key deps task] (let [replacer-fn #(if (= key (first %)) [key deps task] %)] {:satisfied (dep-state :satisfied) :todo (map replacer-fn (dep-state :todo)) :done (map replacer-fn (dep-state :done))})) (defn- key-known? "Returns true or false depending on whether this key is associated with a handler in either the completed or todo lists." [dep-state key] (some #(= key (first %)) (concat (:done dep-state) (:todo dep-state)))) (defn- on-deps* "If a handler with this key has already been registered, just replace the handler - either in todo or completed. If the key is unknown, then either execute the handler if the deps are satisfied or add it to the todo list" [dep-state key deps task] (if (key-known? dep-state key) (replace-handler dep-state key deps task) (process-handler dep-state key deps task))) (defn- satisfy* [{:keys [satisfied todo done]} new-deps] ;(log/info (format "new-deps: %s" new-deps)) (let [satisfied (set/union satisfied new-deps) ;_ (log/info (format "satisfied: %s" satisfied)) execute-tasks (fn [[final-done final-todo] [key deps task]] ;(log/info (format "Satisfied? = %s --- sat: %s deps: %s" (set/superset? satisfied deps) satisfied deps)) (if (set/superset? satisfied deps) (do ;(log/info "Satisfying deps: " deps) (task) [(conj final-done [key deps task]) final-todo]) [final-done (conj final-todo [key deps task])])) [t-done t-todo] (reduce execute-tasks [done []] todo)] {:satisfied satisfied :done t-done :todo t-todo})) (defn- deps->set "Converts deps to a deps-set. Deals with single elements or collections." [deps] (if (coll? deps) (set deps) (set [deps]))) (defn on-deps "Specify that a function should be called once one or more dependencies have been satisfied. The function is run immediately if the deps have already been satisfied, otherwise it will run as soon as they are. If a dep handler has already been registered with the same key, a second registration with just replace the first. Uses an agent so it's safe to call this from within a transaction." [deps key handler] (let [deps (deps->set deps)] (send-off dep-state* on-deps* key deps handler))) (defn satisfy-deps "Specifies that a list of dependencies have been satisfied. Uses an agent so it's safe to call this from within a transaction." [& deps] (send-off dep-state* satisfy* (set deps))) (defn reset-deps "Reset the dependency system. Uses an agent so it's safe to call this from within a transaction." [] (send dep-state* (fn [& args] {:satisfied #{} :todo [] :done []}))) (defn unsatisfy-all-dependencies "Unsatisfy all deps and reset completed tasks as todo tasks. Uses an agent so it's safe to call this from within a transaction." [] (send dep-state* (fn [deps] {:satisfied #{} :todo (deps :done) :done []}))) (defn satisfied-deps "Returns a set of all satisfied deps" [] (:satisfied @dep-state*)) (defn deps-satisfied? "Returns true if all the deps (specified either as a single dep or a collection of deps) have been satisfied." [deps] (let [deps (deps->set deps)] (set/superset? (satisfied-deps) deps))) (defn wait-until-deps-satisfied "Makes the current thread sleep until specified deps have been satisfied. Thread enters a sleep cycle sleeping for wait-time ms before each dep check. If timeout is a positive value throws timeout exception if deps haven't been satisfied by timeout ms. Default wait-time is 100ms and default timeout is 10000 ms" ([deps] (wait-until-deps-satisfied deps 10000 100)) ([deps timeout] (wait-until-deps-satisfied deps timeout 100)) ([deps timeout wait-time] (if (<= timeout 0) (while (not (deps-satisfied? deps)) (Thread/sleep wait-time)) (loop [sleep-time 0] (when (> sleep-time timeout) (throw (Exception. (str "The following deps took too long to be satisfied: " deps)))) (when-not (deps-satisfied? deps) (Thread/sleep wait-time) (recur (+ sleep-time wait-time)))))))
true
(ns ^{:doc "A basic dependency system for specifying the execution of fns once dependencies have been met." :author "PI:NAME:<NAME>END_PI & PI:NAME:<NAME>END_PI"} overtone.libs.deps (:require [clojure.set :as set] [overtone.util.log :as log])) ;; A representation of the state of the dependencies: ;; :satisified - a set of keywords representing ids for each of the satisfied ;; dependencies ;; :todo - a list of functions with associated dependencies which need ;; to be executed when those dependencies are met ;; :done - a list of functions with associated dependencies which have ;; already been executed as their dependencies have been met (defonce dep-state* (agent {:satisfied #{} :todo [] :done []})) (defn- process-handler "Returns a new deps map containing either processed handler or it placed in the todo list" [dep-state key deps task] (apply assoc dep-state (if (set/superset? (:satisfied dep-state) deps) (do (task) [:done (conj (:done dep-state) [key deps task])]) [:todo (conj (:todo dep-state) [key deps task])]))) (defn- replace-handler "Replace all occurances of handers with the given key with the new handler and deps set" [dep-state key deps task] (let [replacer-fn #(if (= key (first %)) [key deps task] %)] {:satisfied (dep-state :satisfied) :todo (map replacer-fn (dep-state :todo)) :done (map replacer-fn (dep-state :done))})) (defn- key-known? "Returns true or false depending on whether this key is associated with a handler in either the completed or todo lists." [dep-state key] (some #(= key (first %)) (concat (:done dep-state) (:todo dep-state)))) (defn- on-deps* "If a handler with this key has already been registered, just replace the handler - either in todo or completed. If the key is unknown, then either execute the handler if the deps are satisfied or add it to the todo list" [dep-state key deps task] (if (key-known? dep-state key) (replace-handler dep-state key deps task) (process-handler dep-state key deps task))) (defn- satisfy* [{:keys [satisfied todo done]} new-deps] ;(log/info (format "new-deps: %s" new-deps)) (let [satisfied (set/union satisfied new-deps) ;_ (log/info (format "satisfied: %s" satisfied)) execute-tasks (fn [[final-done final-todo] [key deps task]] ;(log/info (format "Satisfied? = %s --- sat: %s deps: %s" (set/superset? satisfied deps) satisfied deps)) (if (set/superset? satisfied deps) (do ;(log/info "Satisfying deps: " deps) (task) [(conj final-done [key deps task]) final-todo]) [final-done (conj final-todo [key deps task])])) [t-done t-todo] (reduce execute-tasks [done []] todo)] {:satisfied satisfied :done t-done :todo t-todo})) (defn- deps->set "Converts deps to a deps-set. Deals with single elements or collections." [deps] (if (coll? deps) (set deps) (set [deps]))) (defn on-deps "Specify that a function should be called once one or more dependencies have been satisfied. The function is run immediately if the deps have already been satisfied, otherwise it will run as soon as they are. If a dep handler has already been registered with the same key, a second registration with just replace the first. Uses an agent so it's safe to call this from within a transaction." [deps key handler] (let [deps (deps->set deps)] (send-off dep-state* on-deps* key deps handler))) (defn satisfy-deps "Specifies that a list of dependencies have been satisfied. Uses an agent so it's safe to call this from within a transaction." [& deps] (send-off dep-state* satisfy* (set deps))) (defn reset-deps "Reset the dependency system. Uses an agent so it's safe to call this from within a transaction." [] (send dep-state* (fn [& args] {:satisfied #{} :todo [] :done []}))) (defn unsatisfy-all-dependencies "Unsatisfy all deps and reset completed tasks as todo tasks. Uses an agent so it's safe to call this from within a transaction." [] (send dep-state* (fn [deps] {:satisfied #{} :todo (deps :done) :done []}))) (defn satisfied-deps "Returns a set of all satisfied deps" [] (:satisfied @dep-state*)) (defn deps-satisfied? "Returns true if all the deps (specified either as a single dep or a collection of deps) have been satisfied." [deps] (let [deps (deps->set deps)] (set/superset? (satisfied-deps) deps))) (defn wait-until-deps-satisfied "Makes the current thread sleep until specified deps have been satisfied. Thread enters a sleep cycle sleeping for wait-time ms before each dep check. If timeout is a positive value throws timeout exception if deps haven't been satisfied by timeout ms. Default wait-time is 100ms and default timeout is 10000 ms" ([deps] (wait-until-deps-satisfied deps 10000 100)) ([deps timeout] (wait-until-deps-satisfied deps timeout 100)) ([deps timeout wait-time] (if (<= timeout 0) (while (not (deps-satisfied? deps)) (Thread/sleep wait-time)) (loop [sleep-time 0] (when (> sleep-time timeout) (throw (Exception. (str "The following deps took too long to be satisfied: " deps)))) (when-not (deps-satisfied? deps) (Thread/sleep wait-time) (recur (+ sleep-time wait-time)))))))
[ { "context": "f extracts of talks\n;\n; * Intro To Clojure\n; -by Brian Will (http://www.youtube.com/playlist?list=PLAC43CFB13", "end": 146, "score": 0.9998868107795715, "start": 136, "tag": "NAME", "value": "Brian Will" }, { "context": "(clojure.core/in-ns (quote abionic))\n(def msg \"sayonara\")\n(clojure.core/println msg)\n(clojure.core/in-ns ", "end": 2807, "score": 0.8776013255119324, "start": 2802, "tag": "NAME", "value": "onara" } ]
talks-articles/languages-n-runtimes/clojure/intro_to_clojure/intro-to-clojure.clj
abhishekkr/tutorials_as_code
37
; just some timepass code to remind of language structs ; ; CLOJURE ; ; combination of extracts of talks ; ; * Intro To Clojure ; -by Brian Will (http://www.youtube.com/playlist?list=PLAC43CFB134E85266) ; ; * Uncle Bob Martin presents Clojure ; - by Uncle Bob ; ; * LearnXinYMinutes.com/doc/clojure ; ; to quick help ;(doc first) ; first call should be to set namespace (ns clojureintro) ; tick ` :: means its data not a func so eval and place '("I WAZ CLISP BEFORE!") '(+ 5 10) (println '(+ 5 10)) (eval '(+ 5 10)) (println `(+ 5 10)) (println (eval `(+ 5 10))) (println (/ 20 5 2)) (println (repeat 2 5)) (println (apply + (repeat 2 5))) (println (first [20 5 2])) (println (next [20 5 2])) (println "NOT STRING IN SINGLE-QUOTE") (println (+ 1 2 3 4 5)) (println *clojure-version* "\n" + "\n" *file* "\n" - "\n" :KEYWORD_SYMBOL) (println *compile-path* :key "abcde" 1 2) (println "list" '(3 4 5)) ; list is (3 4 5) ...to data-fy it use apostrophe (println "vector" [6 7 8 9]) (println "hashmap" {"f" "u" 1 2}) (println ({"f" "u" 1 2} "f")) (println ({"f" "u" 1 2} 1)) ;special forms list ; boolean states (println (or)) (println (or true false false)) (println (and)) (println (and true true false)) (println true false (not true)) ; equality condition and str concatenating every argument as string (println (str (= 1 1) (= 1 2))) ; if conditional (println ">>>>> if conditional") (println ( if (< 1 2) "what" "now")) (println ( if (> 1 2) "what")) ; quote (println ">>>>> quote") (println (quote (f (o) o))) ; def (println ">>>>> def") (def what {1 2 3 4}) ; var mapping (println (what 3)) ; do (println ">>>>> do") (println (do (def var1 "Var~1") (print) (what 1) ) ) ; let (println ">>>>> let") (def abc 1) (def xyz 2) (def pqr (let [abc "none" xyz 7] (println abc) (+ 3 xyz))) (println pqr) ; fn (println ">>>>> fn") (def add (fn fn_add [num1, num2] (+ num1 num2) fn_add)) (def add (fn fn_add [num1, num2] (+ num1 num2) fn_add)) (println (add 1 9)) (def add (fn [num1, num2] (+ num1 num2))) (println (add 1 9)) (def sub (fn [num1, num2] (- num1 num2))) (println (sub 1 9)) ; . (. class method argument*) (. instance method argument*) (println ">>>>> .") ;(. System println "ABC") ; new (new class argument*) (println ">>>>> new") (new java.util.Date) ;(new java.util.Timer false) (println ">>>>> clojure.core") (println (clojure.core/+ 1 2)) (println (clojure.core/* 1 2)) ; lexical scoping (println ">>>>> lexical scoping") (println (let [abc 1000] (def plus100 (fn [abc] (+ abc 100))) (println (plus100 1)) (sub 1500 abc) ) ) ; NameSpacing Vars (println ">>>>> clojure namespacing") (clojure.core/in-ns (quote abk)) (def msg "welcome") (clojure.core/println msg) (clojure.core/in-ns (quote abionic)) (def msg "sayonara") (clojure.core/println msg) (clojure.core/in-ns (quote abk)) (clojure.core/println "current namespace (abk):" msg) (clojure.core/println "abionic namespace:" abionic/msg) (clojure.core/refer (quote clojure.core)) (println ">>>>> clojure core refer || println wouldn't have worked before refer") (def plus (+ 3 7)) (println plus) (ns clojureintro) (def currentnsVar 1) (println currentnsVar) (ns newns) (def currentnsVar 10) (println currentnsVar) (ns clojureintro) (println currentnsVar) ; tail recursion [end-of-function recursion drop calling func frame optimization] (println ">>>>> tail recursion") (def showUpto100 (fn [num] (print num " ") (if (< num 100) (recur (+ num 1)) ) ) ) (println (showUpto100 97)) ; loop (println ">>>>> loop") (loop [idx 5] (print idx " ") (if (< idx 15) (recur (+ idx 10)) ) ) (println) ; creating methods ;; Macros (println ">>>>> using Macros in-built") (defn mul [n1 n2] (* n1 n2)) ; => (def mul (fn [n1 n2] (* n1 n2))) (println (mul 5 10)) ;; also nameless function defs (def div (fn [n1 n2] (/ n1 n2))) (println (div 50 10)) ;; also shortcut to nameless function defs (def Div #(/ %1 %2)) (println (Div 10 5)) (def Sqr #(* % %)) (println (Sqr 10)) ;(println ">>>>> creating Macros") ;(defmacro name [parameter*] expression*) ; sequence first,rest ; ;(def lst1 (1 2 3 4 5)) ;(println (first lst1) ; ;(loop [l1 (1 2 3 4 5)] ; (print (first l1)) ; if( (< 2 1) ; (recur (rest l1)) ) ; )
49342
; just some timepass code to remind of language structs ; ; CLOJURE ; ; combination of extracts of talks ; ; * Intro To Clojure ; -by <NAME> (http://www.youtube.com/playlist?list=PLAC43CFB134E85266) ; ; * Uncle Bob Martin presents Clojure ; - by Uncle Bob ; ; * LearnXinYMinutes.com/doc/clojure ; ; to quick help ;(doc first) ; first call should be to set namespace (ns clojureintro) ; tick ` :: means its data not a func so eval and place '("I WAZ CLISP BEFORE!") '(+ 5 10) (println '(+ 5 10)) (eval '(+ 5 10)) (println `(+ 5 10)) (println (eval `(+ 5 10))) (println (/ 20 5 2)) (println (repeat 2 5)) (println (apply + (repeat 2 5))) (println (first [20 5 2])) (println (next [20 5 2])) (println "NOT STRING IN SINGLE-QUOTE") (println (+ 1 2 3 4 5)) (println *clojure-version* "\n" + "\n" *file* "\n" - "\n" :KEYWORD_SYMBOL) (println *compile-path* :key "abcde" 1 2) (println "list" '(3 4 5)) ; list is (3 4 5) ...to data-fy it use apostrophe (println "vector" [6 7 8 9]) (println "hashmap" {"f" "u" 1 2}) (println ({"f" "u" 1 2} "f")) (println ({"f" "u" 1 2} 1)) ;special forms list ; boolean states (println (or)) (println (or true false false)) (println (and)) (println (and true true false)) (println true false (not true)) ; equality condition and str concatenating every argument as string (println (str (= 1 1) (= 1 2))) ; if conditional (println ">>>>> if conditional") (println ( if (< 1 2) "what" "now")) (println ( if (> 1 2) "what")) ; quote (println ">>>>> quote") (println (quote (f (o) o))) ; def (println ">>>>> def") (def what {1 2 3 4}) ; var mapping (println (what 3)) ; do (println ">>>>> do") (println (do (def var1 "Var~1") (print) (what 1) ) ) ; let (println ">>>>> let") (def abc 1) (def xyz 2) (def pqr (let [abc "none" xyz 7] (println abc) (+ 3 xyz))) (println pqr) ; fn (println ">>>>> fn") (def add (fn fn_add [num1, num2] (+ num1 num2) fn_add)) (def add (fn fn_add [num1, num2] (+ num1 num2) fn_add)) (println (add 1 9)) (def add (fn [num1, num2] (+ num1 num2))) (println (add 1 9)) (def sub (fn [num1, num2] (- num1 num2))) (println (sub 1 9)) ; . (. class method argument*) (. instance method argument*) (println ">>>>> .") ;(. System println "ABC") ; new (new class argument*) (println ">>>>> new") (new java.util.Date) ;(new java.util.Timer false) (println ">>>>> clojure.core") (println (clojure.core/+ 1 2)) (println (clojure.core/* 1 2)) ; lexical scoping (println ">>>>> lexical scoping") (println (let [abc 1000] (def plus100 (fn [abc] (+ abc 100))) (println (plus100 1)) (sub 1500 abc) ) ) ; NameSpacing Vars (println ">>>>> clojure namespacing") (clojure.core/in-ns (quote abk)) (def msg "welcome") (clojure.core/println msg) (clojure.core/in-ns (quote abionic)) (def msg "say<NAME>") (clojure.core/println msg) (clojure.core/in-ns (quote abk)) (clojure.core/println "current namespace (abk):" msg) (clojure.core/println "abionic namespace:" abionic/msg) (clojure.core/refer (quote clojure.core)) (println ">>>>> clojure core refer || println wouldn't have worked before refer") (def plus (+ 3 7)) (println plus) (ns clojureintro) (def currentnsVar 1) (println currentnsVar) (ns newns) (def currentnsVar 10) (println currentnsVar) (ns clojureintro) (println currentnsVar) ; tail recursion [end-of-function recursion drop calling func frame optimization] (println ">>>>> tail recursion") (def showUpto100 (fn [num] (print num " ") (if (< num 100) (recur (+ num 1)) ) ) ) (println (showUpto100 97)) ; loop (println ">>>>> loop") (loop [idx 5] (print idx " ") (if (< idx 15) (recur (+ idx 10)) ) ) (println) ; creating methods ;; Macros (println ">>>>> using Macros in-built") (defn mul [n1 n2] (* n1 n2)) ; => (def mul (fn [n1 n2] (* n1 n2))) (println (mul 5 10)) ;; also nameless function defs (def div (fn [n1 n2] (/ n1 n2))) (println (div 50 10)) ;; also shortcut to nameless function defs (def Div #(/ %1 %2)) (println (Div 10 5)) (def Sqr #(* % %)) (println (Sqr 10)) ;(println ">>>>> creating Macros") ;(defmacro name [parameter*] expression*) ; sequence first,rest ; ;(def lst1 (1 2 3 4 5)) ;(println (first lst1) ; ;(loop [l1 (1 2 3 4 5)] ; (print (first l1)) ; if( (< 2 1) ; (recur (rest l1)) ) ; )
true
; just some timepass code to remind of language structs ; ; CLOJURE ; ; combination of extracts of talks ; ; * Intro To Clojure ; -by PI:NAME:<NAME>END_PI (http://www.youtube.com/playlist?list=PLAC43CFB134E85266) ; ; * Uncle Bob Martin presents Clojure ; - by Uncle Bob ; ; * LearnXinYMinutes.com/doc/clojure ; ; to quick help ;(doc first) ; first call should be to set namespace (ns clojureintro) ; tick ` :: means its data not a func so eval and place '("I WAZ CLISP BEFORE!") '(+ 5 10) (println '(+ 5 10)) (eval '(+ 5 10)) (println `(+ 5 10)) (println (eval `(+ 5 10))) (println (/ 20 5 2)) (println (repeat 2 5)) (println (apply + (repeat 2 5))) (println (first [20 5 2])) (println (next [20 5 2])) (println "NOT STRING IN SINGLE-QUOTE") (println (+ 1 2 3 4 5)) (println *clojure-version* "\n" + "\n" *file* "\n" - "\n" :KEYWORD_SYMBOL) (println *compile-path* :key "abcde" 1 2) (println "list" '(3 4 5)) ; list is (3 4 5) ...to data-fy it use apostrophe (println "vector" [6 7 8 9]) (println "hashmap" {"f" "u" 1 2}) (println ({"f" "u" 1 2} "f")) (println ({"f" "u" 1 2} 1)) ;special forms list ; boolean states (println (or)) (println (or true false false)) (println (and)) (println (and true true false)) (println true false (not true)) ; equality condition and str concatenating every argument as string (println (str (= 1 1) (= 1 2))) ; if conditional (println ">>>>> if conditional") (println ( if (< 1 2) "what" "now")) (println ( if (> 1 2) "what")) ; quote (println ">>>>> quote") (println (quote (f (o) o))) ; def (println ">>>>> def") (def what {1 2 3 4}) ; var mapping (println (what 3)) ; do (println ">>>>> do") (println (do (def var1 "Var~1") (print) (what 1) ) ) ; let (println ">>>>> let") (def abc 1) (def xyz 2) (def pqr (let [abc "none" xyz 7] (println abc) (+ 3 xyz))) (println pqr) ; fn (println ">>>>> fn") (def add (fn fn_add [num1, num2] (+ num1 num2) fn_add)) (def add (fn fn_add [num1, num2] (+ num1 num2) fn_add)) (println (add 1 9)) (def add (fn [num1, num2] (+ num1 num2))) (println (add 1 9)) (def sub (fn [num1, num2] (- num1 num2))) (println (sub 1 9)) ; . (. class method argument*) (. instance method argument*) (println ">>>>> .") ;(. System println "ABC") ; new (new class argument*) (println ">>>>> new") (new java.util.Date) ;(new java.util.Timer false) (println ">>>>> clojure.core") (println (clojure.core/+ 1 2)) (println (clojure.core/* 1 2)) ; lexical scoping (println ">>>>> lexical scoping") (println (let [abc 1000] (def plus100 (fn [abc] (+ abc 100))) (println (plus100 1)) (sub 1500 abc) ) ) ; NameSpacing Vars (println ">>>>> clojure namespacing") (clojure.core/in-ns (quote abk)) (def msg "welcome") (clojure.core/println msg) (clojure.core/in-ns (quote abionic)) (def msg "sayPI:NAME:<NAME>END_PI") (clojure.core/println msg) (clojure.core/in-ns (quote abk)) (clojure.core/println "current namespace (abk):" msg) (clojure.core/println "abionic namespace:" abionic/msg) (clojure.core/refer (quote clojure.core)) (println ">>>>> clojure core refer || println wouldn't have worked before refer") (def plus (+ 3 7)) (println plus) (ns clojureintro) (def currentnsVar 1) (println currentnsVar) (ns newns) (def currentnsVar 10) (println currentnsVar) (ns clojureintro) (println currentnsVar) ; tail recursion [end-of-function recursion drop calling func frame optimization] (println ">>>>> tail recursion") (def showUpto100 (fn [num] (print num " ") (if (< num 100) (recur (+ num 1)) ) ) ) (println (showUpto100 97)) ; loop (println ">>>>> loop") (loop [idx 5] (print idx " ") (if (< idx 15) (recur (+ idx 10)) ) ) (println) ; creating methods ;; Macros (println ">>>>> using Macros in-built") (defn mul [n1 n2] (* n1 n2)) ; => (def mul (fn [n1 n2] (* n1 n2))) (println (mul 5 10)) ;; also nameless function defs (def div (fn [n1 n2] (/ n1 n2))) (println (div 50 10)) ;; also shortcut to nameless function defs (def Div #(/ %1 %2)) (println (Div 10 5)) (def Sqr #(* % %)) (println (Sqr 10)) ;(println ">>>>> creating Macros") ;(defmacro name [parameter*] expression*) ; sequence first,rest ; ;(def lst1 (1 2 3 4 5)) ;(println (first lst1) ; ;(loop [l1 (1 2 3 4 5)] ; (print (first l1)) ; if( (< 2 1) ; (recur (rest l1)) ) ; )
[ { "context": ";; Copyright (c) Stuart Sierra, 2012. All rights reserved. The use and\n;; distri", "end": 30, "score": 0.9998565912246704, "start": 17, "tag": "NAME", "value": "Stuart Sierra" } ]
output/conjure_deps/toolsnamespace/v0v3v1/clojure/tools/namespace/dir.clj
Olical/conjure-deps
4
;; Copyright (c) Stuart Sierra, 2012. All rights reserved. The use and ;; distribution terms for this software are covered by the Eclipse ;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this ;; distribution. By using this software in any fashion, you are ;; agreeing to be bound by the terms of this license. You must not ;; remove this notice, or any other, from this software. (ns conjure-deps.toolsnamespace.v0v3v1.clojure.tools.namespace.dir (:require [conjure-deps.toolsnamespace.v0v3v1.clojure.tools.namespace.file :as file] [conjure-deps.toolsnamespace.v0v3v1.clojure.tools.namespace.find :as find] [conjure-deps.toolsnamespace.v0v3v1.clojure.tools.namespace.track :as track] [conjure-deps.javaclasspath.v0v3v0.clojure.java.classpath :refer [classpath-directories]] [clojure.java.io :as io] [clojure.set :as set] [clojure.string :as string]) (:import (java.io File) (java.util.regex Pattern))) (defn- find-files [dirs platform] (->> dirs (map io/file) (map #(.getCanonicalFile ^File %)) (filter #(.exists ^File %)) (mapcat #(find/find-sources-in-dir % platform)) (map #(.getCanonicalFile ^File %)))) (defn- modified-files [tracker files] (filter #(< (::time tracker 0) (.lastModified ^File %)) files)) (defn- deleted-files [tracker files] (set/difference (::files tracker #{}) (set files))) (defn- update-files [tracker deleted modified {:keys [read-opts]}] (let [now (System/currentTimeMillis)] (-> tracker (update-in [::files] #(if % (apply disj % deleted) #{})) (file/remove-files deleted) (update-in [::files] into modified) (file/add-files modified read-opts) (assoc ::time now)))) (defn scan-files "Scans files to find those which have changed since the last time 'scan-files' was run; updates the dependency tracker with new/changed/deleted files. files is the collection of files to scan. Optional third argument is map of options: :platform Either clj (default) or cljs, both defined in conjure-deps.toolsnamespace.v0v3v1.clojure.tools.namespace.find, controls reader options for parsing files. :add-all? If true, assumes all extant files are modified regardless of filesystem timestamps." {:added "0.3.0"} ([tracker files] (scan-files tracker files nil)) ([tracker files {:keys [platform add-all?]}] (let [deleted (seq (deleted-files tracker files)) modified (if add-all? files (seq (modified-files tracker files)))] (if (or deleted modified) (update-files tracker deleted modified platform) tracker)))) (defn scan-dirs "Scans directories for files which have changed since the last time 'scan-dirs' or 'scan-files' was run; updates the dependency tracker with new/changed/deleted files. dirs is the collection of directories to scan, defaults to all directories on Clojure's classpath. Optional third argument is map of options: :platform Either clj (default) or cljs, both defined in conjure-deps.toolsnamespace.v0v3v1.clojure.tools.namespace.find, controls file extensions and reader options. :add-all? If true, assumes all extant files are modified regardless of filesystem timestamps." {:added "0.3.0"} ([tracker] (scan-dirs tracker nil nil)) ([tracker dirs] (scan-dirs tracker dirs nil)) ([tracker dirs {:keys [platform add-all?] :as options}] (let [ds (or (seq dirs) (classpath-directories))] (scan-files tracker (find-files ds platform) options)))) (defn scan "DEPRECATED: replaced by scan-dirs. Scans directories for Clojure (.clj, .cljc) source files which have changed since the last time 'scan' was run; update the dependency tracker with new/changed/deleted files. If no dirs given, defaults to all directories on the classpath." {:added "0.2.0" :deprecated "0.3.0"} [tracker & dirs] (scan-dirs tracker dirs {:platform find/clj})) (defn scan-all "DEPRECATED: replaced by scan-dirs. Scans directories for all Clojure source files and updates the dependency tracker to reload files. If no dirs given, defaults to all directories on the classpath." {:added "0.2.0" :deprecated "0.3.0"} [tracker & dirs] (scan-dirs tracker dirs {:platform find/clj :add-all? true}))
61941
;; Copyright (c) <NAME>, 2012. All rights reserved. The use and ;; distribution terms for this software are covered by the Eclipse ;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this ;; distribution. By using this software in any fashion, you are ;; agreeing to be bound by the terms of this license. You must not ;; remove this notice, or any other, from this software. (ns conjure-deps.toolsnamespace.v0v3v1.clojure.tools.namespace.dir (:require [conjure-deps.toolsnamespace.v0v3v1.clojure.tools.namespace.file :as file] [conjure-deps.toolsnamespace.v0v3v1.clojure.tools.namespace.find :as find] [conjure-deps.toolsnamespace.v0v3v1.clojure.tools.namespace.track :as track] [conjure-deps.javaclasspath.v0v3v0.clojure.java.classpath :refer [classpath-directories]] [clojure.java.io :as io] [clojure.set :as set] [clojure.string :as string]) (:import (java.io File) (java.util.regex Pattern))) (defn- find-files [dirs platform] (->> dirs (map io/file) (map #(.getCanonicalFile ^File %)) (filter #(.exists ^File %)) (mapcat #(find/find-sources-in-dir % platform)) (map #(.getCanonicalFile ^File %)))) (defn- modified-files [tracker files] (filter #(< (::time tracker 0) (.lastModified ^File %)) files)) (defn- deleted-files [tracker files] (set/difference (::files tracker #{}) (set files))) (defn- update-files [tracker deleted modified {:keys [read-opts]}] (let [now (System/currentTimeMillis)] (-> tracker (update-in [::files] #(if % (apply disj % deleted) #{})) (file/remove-files deleted) (update-in [::files] into modified) (file/add-files modified read-opts) (assoc ::time now)))) (defn scan-files "Scans files to find those which have changed since the last time 'scan-files' was run; updates the dependency tracker with new/changed/deleted files. files is the collection of files to scan. Optional third argument is map of options: :platform Either clj (default) or cljs, both defined in conjure-deps.toolsnamespace.v0v3v1.clojure.tools.namespace.find, controls reader options for parsing files. :add-all? If true, assumes all extant files are modified regardless of filesystem timestamps." {:added "0.3.0"} ([tracker files] (scan-files tracker files nil)) ([tracker files {:keys [platform add-all?]}] (let [deleted (seq (deleted-files tracker files)) modified (if add-all? files (seq (modified-files tracker files)))] (if (or deleted modified) (update-files tracker deleted modified platform) tracker)))) (defn scan-dirs "Scans directories for files which have changed since the last time 'scan-dirs' or 'scan-files' was run; updates the dependency tracker with new/changed/deleted files. dirs is the collection of directories to scan, defaults to all directories on Clojure's classpath. Optional third argument is map of options: :platform Either clj (default) or cljs, both defined in conjure-deps.toolsnamespace.v0v3v1.clojure.tools.namespace.find, controls file extensions and reader options. :add-all? If true, assumes all extant files are modified regardless of filesystem timestamps." {:added "0.3.0"} ([tracker] (scan-dirs tracker nil nil)) ([tracker dirs] (scan-dirs tracker dirs nil)) ([tracker dirs {:keys [platform add-all?] :as options}] (let [ds (or (seq dirs) (classpath-directories))] (scan-files tracker (find-files ds platform) options)))) (defn scan "DEPRECATED: replaced by scan-dirs. Scans directories for Clojure (.clj, .cljc) source files which have changed since the last time 'scan' was run; update the dependency tracker with new/changed/deleted files. If no dirs given, defaults to all directories on the classpath." {:added "0.2.0" :deprecated "0.3.0"} [tracker & dirs] (scan-dirs tracker dirs {:platform find/clj})) (defn scan-all "DEPRECATED: replaced by scan-dirs. Scans directories for all Clojure source files and updates the dependency tracker to reload files. If no dirs given, defaults to all directories on the classpath." {:added "0.2.0" :deprecated "0.3.0"} [tracker & dirs] (scan-dirs tracker dirs {:platform find/clj :add-all? true}))
true
;; Copyright (c) PI:NAME:<NAME>END_PI, 2012. All rights reserved. The use and ;; distribution terms for this software are covered by the Eclipse ;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this ;; distribution. By using this software in any fashion, you are ;; agreeing to be bound by the terms of this license. You must not ;; remove this notice, or any other, from this software. (ns conjure-deps.toolsnamespace.v0v3v1.clojure.tools.namespace.dir (:require [conjure-deps.toolsnamespace.v0v3v1.clojure.tools.namespace.file :as file] [conjure-deps.toolsnamespace.v0v3v1.clojure.tools.namespace.find :as find] [conjure-deps.toolsnamespace.v0v3v1.clojure.tools.namespace.track :as track] [conjure-deps.javaclasspath.v0v3v0.clojure.java.classpath :refer [classpath-directories]] [clojure.java.io :as io] [clojure.set :as set] [clojure.string :as string]) (:import (java.io File) (java.util.regex Pattern))) (defn- find-files [dirs platform] (->> dirs (map io/file) (map #(.getCanonicalFile ^File %)) (filter #(.exists ^File %)) (mapcat #(find/find-sources-in-dir % platform)) (map #(.getCanonicalFile ^File %)))) (defn- modified-files [tracker files] (filter #(< (::time tracker 0) (.lastModified ^File %)) files)) (defn- deleted-files [tracker files] (set/difference (::files tracker #{}) (set files))) (defn- update-files [tracker deleted modified {:keys [read-opts]}] (let [now (System/currentTimeMillis)] (-> tracker (update-in [::files] #(if % (apply disj % deleted) #{})) (file/remove-files deleted) (update-in [::files] into modified) (file/add-files modified read-opts) (assoc ::time now)))) (defn scan-files "Scans files to find those which have changed since the last time 'scan-files' was run; updates the dependency tracker with new/changed/deleted files. files is the collection of files to scan. Optional third argument is map of options: :platform Either clj (default) or cljs, both defined in conjure-deps.toolsnamespace.v0v3v1.clojure.tools.namespace.find, controls reader options for parsing files. :add-all? If true, assumes all extant files are modified regardless of filesystem timestamps." {:added "0.3.0"} ([tracker files] (scan-files tracker files nil)) ([tracker files {:keys [platform add-all?]}] (let [deleted (seq (deleted-files tracker files)) modified (if add-all? files (seq (modified-files tracker files)))] (if (or deleted modified) (update-files tracker deleted modified platform) tracker)))) (defn scan-dirs "Scans directories for files which have changed since the last time 'scan-dirs' or 'scan-files' was run; updates the dependency tracker with new/changed/deleted files. dirs is the collection of directories to scan, defaults to all directories on Clojure's classpath. Optional third argument is map of options: :platform Either clj (default) or cljs, both defined in conjure-deps.toolsnamespace.v0v3v1.clojure.tools.namespace.find, controls file extensions and reader options. :add-all? If true, assumes all extant files are modified regardless of filesystem timestamps." {:added "0.3.0"} ([tracker] (scan-dirs tracker nil nil)) ([tracker dirs] (scan-dirs tracker dirs nil)) ([tracker dirs {:keys [platform add-all?] :as options}] (let [ds (or (seq dirs) (classpath-directories))] (scan-files tracker (find-files ds platform) options)))) (defn scan "DEPRECATED: replaced by scan-dirs. Scans directories for Clojure (.clj, .cljc) source files which have changed since the last time 'scan' was run; update the dependency tracker with new/changed/deleted files. If no dirs given, defaults to all directories on the classpath." {:added "0.2.0" :deprecated "0.3.0"} [tracker & dirs] (scan-dirs tracker dirs {:platform find/clj})) (defn scan-all "DEPRECATED: replaced by scan-dirs. Scans directories for all Clojure source files and updates the dependency tracker to reload files. If no dirs given, defaults to all directories on the classpath." {:added "0.2.0" :deprecated "0.3.0"} [tracker & dirs] (scan-dirs tracker dirs {:platform find/clj :add-all? true}))
[ { "context": "olving problems, what are we doing?\"\n :person \"Rich Hickey\"}\n {:text \"Good design has to account for all", "end": 302, "score": 0.9998913407325745, "start": 291, "tag": "NAME", "value": "Rich Hickey" }, { "context": "r all of the pieces, not just some.\"\n :person \"Stuart Halloway\"}\n {:text \"I’m never going back to a non-LISP", "end": 412, "score": 0.9998947381973267, "start": 397, "tag": "NAME", "value": "Stuart Halloway" }, { "context": "rammars with tons of special cases.\"\n :person \"Gene Kim\"}])\n\n(defn wrap-random-quote\n \"Provides a (pseud", "end": 565, "score": 0.9998486042022705, "start": 557, "tag": "NAME", "value": "Gene Kim" } ]
src/quotes/main.clj
justindbelanger/quotes
1
(ns quotes.main (:require [aleph.http] [hiccup.core] [hiccup.page] [juxt.clip.core :as clip] [reitit.ring] [riemann.client])) ;; * Quotes (def quotes [{:text "If we're not solving problems, what are we doing?" :person "Rich Hickey"} {:text "Good design has to account for all of the pieces, not just some." :person "Stuart Halloway"} {:text "I’m never going back to a non-LISP. Life is too short to learn fussy language grammars with tons of special cases." :person "Gene Kim"}]) (defn wrap-random-quote "Provides a (pseudo)randomized quote to display on the page." [handler] (fn [request] (handler (assoc request :quote (rand-nth quotes))))) ;; * Sending events to Riemann (defn make-riemann-client "Connects to a running Riemann instance via TCP. Uses the default host and port. Returns the Riemann client instance." [] (riemann.client/tcp-client {:host "0.0.0.0" :port 5555})) (defn wrap-riemann-service-time "Sends time to service each request to Riemann." [handler riemann-client] (fn [request] (let [start (System/nanoTime) response (handler request) end (System/nanoTime) duration (- end start)] (-> riemann-client (riemann.client/send-event {:service "quotes.http.index.service-time" :metric duration :state "ok"}) (deref 5000 ::timeout)) response))) ;; * HTTP handlers (defn index-page-handler "Serves an HTML page containing the inspirational `:quote` provided in the `request` map." [request] (let [{:keys [text person]} (:quote request)] {:status 200 :body (hiccup.core/html (hiccup.page/html5 [:head [:title "quotes"] [:meta {:charset "utf-8"}]] [:body [:h1 "Cool Quotes"] [:p [:span "\""] [:strong text] [:span "\""]] [:p [:span " - "] person]]))})) (defn make-app "Provides a Ring-compatible handler to serve the Quotes app. Sends metrics using the given `riemann-client`." [riemann-client] (reitit.ring/ring-handler (reitit.ring/router ["/" {:get index-page-handler :middleware [[wrap-riemann-service-time riemann-client] [wrap-random-quote]]}]) (reitit.ring/create-default-handler))) ;; * Clip config (defn make-system-config "Provides a Clip system config using the given HTTP `port`." [port] {:components {:riemann-client {:start `make-riemann-client} :app {:start `(make-app (clip/ref :riemann-client))} :server {:start `(aleph.http/start-server (clip/ref :app) {:port ~port})}}}) ;; * App entry point (def *system-config (atom nil)) (def *system (atom nil)) (defn start-all! [port] (let [system-config (make-system-config port) system (clip/start system-config)] (reset! *system system) (reset! *system-config system-config))) (defn stop-all! [] (clip/stop @*system-config @*system) (reset! *system nil) (reset! *system-config nil)) (defn -main [& {:keys [port] :or {port 8080}}] (println (str "Starting HTTP server on " port)) (start-all! port) (println (str "Started HTTP server")))
68590
(ns quotes.main (:require [aleph.http] [hiccup.core] [hiccup.page] [juxt.clip.core :as clip] [reitit.ring] [riemann.client])) ;; * Quotes (def quotes [{:text "If we're not solving problems, what are we doing?" :person "<NAME>"} {:text "Good design has to account for all of the pieces, not just some." :person "<NAME>"} {:text "I’m never going back to a non-LISP. Life is too short to learn fussy language grammars with tons of special cases." :person "<NAME>"}]) (defn wrap-random-quote "Provides a (pseudo)randomized quote to display on the page." [handler] (fn [request] (handler (assoc request :quote (rand-nth quotes))))) ;; * Sending events to Riemann (defn make-riemann-client "Connects to a running Riemann instance via TCP. Uses the default host and port. Returns the Riemann client instance." [] (riemann.client/tcp-client {:host "0.0.0.0" :port 5555})) (defn wrap-riemann-service-time "Sends time to service each request to Riemann." [handler riemann-client] (fn [request] (let [start (System/nanoTime) response (handler request) end (System/nanoTime) duration (- end start)] (-> riemann-client (riemann.client/send-event {:service "quotes.http.index.service-time" :metric duration :state "ok"}) (deref 5000 ::timeout)) response))) ;; * HTTP handlers (defn index-page-handler "Serves an HTML page containing the inspirational `:quote` provided in the `request` map." [request] (let [{:keys [text person]} (:quote request)] {:status 200 :body (hiccup.core/html (hiccup.page/html5 [:head [:title "quotes"] [:meta {:charset "utf-8"}]] [:body [:h1 "Cool Quotes"] [:p [:span "\""] [:strong text] [:span "\""]] [:p [:span " - "] person]]))})) (defn make-app "Provides a Ring-compatible handler to serve the Quotes app. Sends metrics using the given `riemann-client`." [riemann-client] (reitit.ring/ring-handler (reitit.ring/router ["/" {:get index-page-handler :middleware [[wrap-riemann-service-time riemann-client] [wrap-random-quote]]}]) (reitit.ring/create-default-handler))) ;; * Clip config (defn make-system-config "Provides a Clip system config using the given HTTP `port`." [port] {:components {:riemann-client {:start `make-riemann-client} :app {:start `(make-app (clip/ref :riemann-client))} :server {:start `(aleph.http/start-server (clip/ref :app) {:port ~port})}}}) ;; * App entry point (def *system-config (atom nil)) (def *system (atom nil)) (defn start-all! [port] (let [system-config (make-system-config port) system (clip/start system-config)] (reset! *system system) (reset! *system-config system-config))) (defn stop-all! [] (clip/stop @*system-config @*system) (reset! *system nil) (reset! *system-config nil)) (defn -main [& {:keys [port] :or {port 8080}}] (println (str "Starting HTTP server on " port)) (start-all! port) (println (str "Started HTTP server")))
true
(ns quotes.main (:require [aleph.http] [hiccup.core] [hiccup.page] [juxt.clip.core :as clip] [reitit.ring] [riemann.client])) ;; * Quotes (def quotes [{:text "If we're not solving problems, what are we doing?" :person "PI:NAME:<NAME>END_PI"} {:text "Good design has to account for all of the pieces, not just some." :person "PI:NAME:<NAME>END_PI"} {:text "I’m never going back to a non-LISP. Life is too short to learn fussy language grammars with tons of special cases." :person "PI:NAME:<NAME>END_PI"}]) (defn wrap-random-quote "Provides a (pseudo)randomized quote to display on the page." [handler] (fn [request] (handler (assoc request :quote (rand-nth quotes))))) ;; * Sending events to Riemann (defn make-riemann-client "Connects to a running Riemann instance via TCP. Uses the default host and port. Returns the Riemann client instance." [] (riemann.client/tcp-client {:host "0.0.0.0" :port 5555})) (defn wrap-riemann-service-time "Sends time to service each request to Riemann." [handler riemann-client] (fn [request] (let [start (System/nanoTime) response (handler request) end (System/nanoTime) duration (- end start)] (-> riemann-client (riemann.client/send-event {:service "quotes.http.index.service-time" :metric duration :state "ok"}) (deref 5000 ::timeout)) response))) ;; * HTTP handlers (defn index-page-handler "Serves an HTML page containing the inspirational `:quote` provided in the `request` map." [request] (let [{:keys [text person]} (:quote request)] {:status 200 :body (hiccup.core/html (hiccup.page/html5 [:head [:title "quotes"] [:meta {:charset "utf-8"}]] [:body [:h1 "Cool Quotes"] [:p [:span "\""] [:strong text] [:span "\""]] [:p [:span " - "] person]]))})) (defn make-app "Provides a Ring-compatible handler to serve the Quotes app. Sends metrics using the given `riemann-client`." [riemann-client] (reitit.ring/ring-handler (reitit.ring/router ["/" {:get index-page-handler :middleware [[wrap-riemann-service-time riemann-client] [wrap-random-quote]]}]) (reitit.ring/create-default-handler))) ;; * Clip config (defn make-system-config "Provides a Clip system config using the given HTTP `port`." [port] {:components {:riemann-client {:start `make-riemann-client} :app {:start `(make-app (clip/ref :riemann-client))} :server {:start `(aleph.http/start-server (clip/ref :app) {:port ~port})}}}) ;; * App entry point (def *system-config (atom nil)) (def *system (atom nil)) (defn start-all! [port] (let [system-config (make-system-config port) system (clip/start system-config)] (reset! *system system) (reset! *system-config system-config))) (defn stop-all! [] (clip/stop @*system-config @*system) (reset! *system nil) (reset! *system-config nil)) (defn -main [& {:keys [port] :or {port 8080}}] (println (str "Starting HTTP server on " port)) (start-all! port) (println (str "Started HTTP server")))
[ { "context": " :refer [split]]))\n\n(def artists [\n \"Alan Guitierrez\"\n \"Alan Lee\"\n \"Alan Pol", "end": 216, "score": 0.9998858571052551, "start": 201, "tag": "NAME", "value": "Alan Guitierrez" }, { "context": " [\n \"Alan Guitierrez\"\n \"Alan Lee\"\n \"Alan Pollack\"\n \"Alan", "end": 241, "score": 0.9998853206634521, "start": 233, "tag": "NAME", "value": "Alan Lee" }, { "context": "itierrez\"\n \"Alan Lee\"\n \"Alan Pollack\"\n \"Alan Rabinowitz\"\n \"A", "end": 270, "score": 0.9998840689659119, "start": 258, "tag": "NAME", "value": "Alan Pollack" }, { "context": " Lee\"\n \"Alan Pollack\"\n \"Alan Rabinowitz\"\n \"Alarie Tano\"\n \"Allen", "end": 302, "score": 0.999884307384491, "start": 287, "tag": "NAME", "value": "Alan Rabinowitz" }, { "context": "k\"\n \"Alan Rabinowitz\"\n \"Alarie Tano\"\n \"Allen G. Douglas\"\n \"", "end": 330, "score": 0.9998884201049805, "start": 319, "tag": "NAME", "value": "Alarie Tano" }, { "context": "owitz\"\n \"Alarie Tano\"\n \"Allen G. Douglas\"\n \"Ana Kusicka\"\n \"Ander", "end": 363, "score": 0.9998889565467834, "start": 347, "tag": "NAME", "value": "Allen G. Douglas" }, { "context": "\"\n \"Allen G. Douglas\"\n \"Ana Kusicka\"\n \"Anders Finer\"\n \"Andr", "end": 391, "score": 0.9998769760131836, "start": 380, "tag": "NAME", "value": "Ana Kusicka" }, { "context": "uglas\"\n \"Ana Kusicka\"\n \"Anders Finer\"\n \"Andrea Piparo\"\n \"And", "end": 420, "score": 0.9998743534088135, "start": 408, "tag": "NAME", "value": "Anders Finer" }, { "context": "icka\"\n \"Anders Finer\"\n \"Andrea Piparo\"\n \"Andreas Rocha\"\n \"And", "end": 450, "score": 0.999883770942688, "start": 437, "tag": "NAME", "value": "Andrea Piparo" }, { "context": "ner\"\n \"Andrea Piparo\"\n \"Andreas Rocha\"\n \"Andrew Goldhawk\"\n \"A", "end": 480, "score": 0.999887228012085, "start": 467, "tag": "NAME", "value": "Andreas Rocha" }, { "context": "aro\"\n \"Andreas Rocha\"\n \"Andrew Goldhawk\"\n \"Angel Falto\"\n \"Angel", "end": 512, "score": 0.9998797178268433, "start": 497, "tag": "NAME", "value": "Andrew Goldhawk" }, { "context": "a\"\n \"Andrew Goldhawk\"\n \"Angel Falto\"\n \"Angelo Michelucci\"\n ", "end": 540, "score": 0.9998663663864136, "start": 529, "tag": "NAME", "value": "Angel Falto" }, { "context": "dhawk\"\n \"Angel Falto\"\n \"Angelo Michelucci\"\n \"Angelo Montanini\"\n \"", "end": 574, "score": 0.9998748302459717, "start": 557, "tag": "NAME", "value": "Angelo Michelucci" }, { "context": "\n \"Angelo Michelucci\"\n \"Angelo Montanini\"\n \"Angus McBride\"\n \"Ank", "end": 607, "score": 0.9998667240142822, "start": 591, "tag": "NAME", "value": "Angelo Montanini" }, { "context": "\"\n \"Angelo Montanini\"\n \"Angus McBride\"\n \"Anke K. Eissmann\"\n \"", "end": 637, "score": 0.9998618364334106, "start": 624, "tag": "NAME", "value": "Angus McBride" }, { "context": "ini\"\n \"Angus McBride\"\n \"Anke K. Eissmann\"\n \"Annika Ritz\"\n \"April", "end": 670, "score": 0.9998723268508911, "start": 654, "tag": "NAME", "value": "Anke K. Eissmann" }, { "context": "\"\n \"Anke K. Eissmann\"\n \"Annika Ritz\"\n \"April Lee\"\n \"Arch St", "end": 698, "score": 0.999880850315094, "start": 687, "tag": "NAME", "value": "Annika Ritz" }, { "context": "smann\"\n \"Annika Ritz\"\n \"April Lee\"\n \"Arch Stanton\"\n \"Audr", "end": 724, "score": 0.9998601675033569, "start": 715, "tag": "NAME", "value": "April Lee" }, { "context": "ka Ritz\"\n \"April Lee\"\n \"Arch Stanton\"\n \"Audrey Corman\"\n \"Bar", "end": 753, "score": 0.9998731017112732, "start": 741, "tag": "NAME", "value": "Arch Stanton" }, { "context": " Lee\"\n \"Arch Stanton\"\n \"Audrey Corman\"\n \"Barbera E. de Jong\"\n ", "end": 783, "score": 0.9998685717582703, "start": 770, "tag": "NAME", "value": "Audrey Corman" }, { "context": "ton\"\n \"Audrey Corman\"\n \"Barbera E. de Jong\"\n \"Birthe Jabs\"\n \"Bob E", "end": 818, "score": 0.9998869895935059, "start": 800, "tag": "NAME", "value": "Barbera E. de Jong" }, { "context": " \"Barbera E. de Jong\"\n \"Birthe Jabs\"\n \"Bob Eggleton\"\n \"Brad", "end": 846, "score": 0.9998859167098999, "start": 835, "tag": "NAME", "value": "Birthe Jabs" }, { "context": " Jong\"\n \"Birthe Jabs\"\n \"Bob Eggleton\"\n \"Brad Williams\"\n \"Bra", "end": 875, "score": 0.9998636245727539, "start": 863, "tag": "NAME", "value": "Bob Eggleton" }, { "context": "Jabs\"\n \"Bob Eggleton\"\n \"Brad Williams\"\n \"Bradly van Camp\"\n \"B", "end": 905, "score": 0.999864399433136, "start": 892, "tag": "NAME", "value": "Brad Williams" }, { "context": "ton\"\n \"Brad Williams\"\n \"Bradly van Camp\"\n \"Brian Durfee\"\n \"Bria", "end": 937, "score": 0.9998747706413269, "start": 922, "tag": "NAME", "value": "Bradly van Camp" }, { "context": "s\"\n \"Bradly van Camp\"\n \"Brian Durfee\"\n \"Brian Snoddy\"\n \"Bria", "end": 966, "score": 0.9998607039451599, "start": 954, "tag": "NAME", "value": "Brian Durfee" }, { "context": "Camp\"\n \"Brian Durfee\"\n \"Brian Snoddy\"\n \"Brian T. Fox\"\n \"Brom", "end": 995, "score": 0.9998582601547241, "start": 983, "tag": "NAME", "value": "Brian Snoddy" }, { "context": "rfee\"\n \"Brian Snoddy\"\n \"Brian T. Fox\"\n \"Brom\"\n \"Carol Heyer\"", "end": 1024, "score": 0.9998700618743896, "start": 1012, "tag": "NAME", "value": "Brian T. Fox" }, { "context": "oddy\"\n \"Brian T. Fox\"\n \"Brom\"\n \"Carol Heyer\"\n \"Chris", "end": 1045, "score": 0.9998605251312256, "start": 1041, "tag": "NAME", "value": "Brom" }, { "context": "Brian T. Fox\"\n \"Brom\"\n \"Carol Heyer\"\n \"Chris Achilleos\"\n \"C", "end": 1073, "score": 0.9998515844345093, "start": 1062, "tag": "NAME", "value": "Carol Heyer" }, { "context": "\"Brom\"\n \"Carol Heyer\"\n \"Chris Achilleos\"\n \"Chris Cocozza\"\n \"Chr", "end": 1105, "score": 0.9998584389686584, "start": 1090, "tag": "NAME", "value": "Chris Achilleos" }, { "context": "r\"\n \"Chris Achilleos\"\n \"Chris Cocozza\"\n \"Chris Trevas\"\n \"Chri", "end": 1135, "score": 0.999862551689148, "start": 1122, "tag": "NAME", "value": "Chris Cocozza" }, { "context": "eos\"\n \"Chris Cocozza\"\n \"Chris Trevas\"\n \"Christina Wald\"\n \"Ch", "end": 1164, "score": 0.9998570084571838, "start": 1152, "tag": "NAME", "value": "Chris Trevas" }, { "context": "ozza\"\n \"Chris Trevas\"\n \"Christina Wald\"\n \"Christopher Miller\"\n ", "end": 1195, "score": 0.9998412132263184, "start": 1181, "tag": "NAME", "value": "Christina Wald" }, { "context": "as\"\n \"Christina Wald\"\n \"Christopher Miller\"\n \"Cortney Skinner\"\n \"D", "end": 1230, "score": 0.9998294115066528, "start": 1212, "tag": "NAME", "value": "Christopher Miller" }, { "context": " \"Christopher Miller\"\n \"Cortney Skinner\"\n \"Dameon Willich\"\n \"Da", "end": 1262, "score": 0.9998679757118225, "start": 1247, "tag": "NAME", "value": "Cortney Skinner" }, { "context": "r\"\n \"Cortney Skinner\"\n \"Dameon Willich\"\n \"Daniel Frazier\"\n \"Da", "end": 1293, "score": 0.9998696446418762, "start": 1279, "tag": "NAME", "value": "Dameon Willich" }, { "context": "er\"\n \"Dameon Willich\"\n \"Daniel Frazier\"\n \"Daniel Gelon\"\n \"Dani", "end": 1324, "score": 0.9998621940612793, "start": 1310, "tag": "NAME", "value": "Daniel Frazier" }, { "context": "ch\"\n \"Daniel Frazier\"\n \"Daniel Gelon\"\n \"Daniel Horne\"\n \"Dani", "end": 1353, "score": 0.9998626708984375, "start": 1341, "tag": "NAME", "value": "Daniel Gelon" }, { "context": "zier\"\n \"Daniel Gelon\"\n \"Daniel Horne\"\n \"Daniel Wikart\"\n \"Dar", "end": 1382, "score": 0.9998704195022583, "start": 1370, "tag": "NAME", "value": "Daniel Horne" }, { "context": "elon\"\n \"Daniel Horne\"\n \"Daniel Wikart\"\n \"Darrell Sweet\"\n \"Dar", "end": 1412, "score": 0.9998749494552612, "start": 1399, "tag": "NAME", "value": "Daniel Wikart" }, { "context": "rne\"\n \"Daniel Wikart\"\n \"Darrell Sweet\"\n \"Darryl Elliott\"\n \"Da", "end": 1442, "score": 0.9998761415481567, "start": 1429, "tag": "NAME", "value": "Darrell Sweet" }, { "context": "art\"\n \"Darrell Sweet\"\n \"Darryl Elliott\"\n \"David A. Cherry\"\n \"D", "end": 1473, "score": 0.9998777508735657, "start": 1459, "tag": "NAME", "value": "Darryl Elliott" }, { "context": "et\"\n \"Darryl Elliott\"\n \"David A. Cherry\"\n \"David Deitrick\"\n \"Da", "end": 1505, "score": 0.9998734593391418, "start": 1490, "tag": "NAME", "value": "David A. Cherry" }, { "context": "t\"\n \"David A. Cherry\"\n \"David Deitrick\"\n \"David Kooharian\"\n \"D", "end": 1536, "score": 0.9998657703399658, "start": 1522, "tag": "NAME", "value": "David Deitrick" }, { "context": "ry\"\n \"David Deitrick\"\n \"David Kooharian\"\n \"David Martin\"\n \"Davi", "end": 1568, "score": 0.9998780488967896, "start": 1553, "tag": "NAME", "value": "David Kooharian" }, { "context": "k\"\n \"David Kooharian\"\n \"David Martin\"\n \"David Monette\"\n \"Dav", "end": 1597, "score": 0.9998679757118225, "start": 1585, "tag": "NAME", "value": "David Martin" }, { "context": "rian\"\n \"David Martin\"\n \"David Monette\"\n \"David R. Seeley\"\n \"D", "end": 1627, "score": 0.9998667240142822, "start": 1614, "tag": "NAME", "value": "David Monette" }, { "context": "tin\"\n \"David Monette\"\n \"David R. Seeley\"\n \"David Sexton\"\n \"Davi", "end": 1659, "score": 0.9998704791069031, "start": 1644, "tag": "NAME", "value": "David R. Seeley" }, { "context": "e\"\n \"David R. Seeley\"\n \"David Sexton\"\n \"David T. Wenzel\"\n \"D", "end": 1688, "score": 0.9998598098754883, "start": 1676, "tag": "NAME", "value": "David Sexton" }, { "context": "eley\"\n \"David Sexton\"\n \"David T. Wenzel\"\n \"David Wyatt\"\n \"Debbi", "end": 1720, "score": 0.9998605251312256, "start": 1705, "tag": "NAME", "value": "David T. Wenzel" }, { "context": "n\"\n \"David T. Wenzel\"\n \"David Wyatt\"\n \"Debbie Hughes\"\n \"Den", "end": 1748, "score": 0.9998370409011841, "start": 1737, "tag": "NAME", "value": "David Wyatt" }, { "context": "enzel\"\n \"David Wyatt\"\n \"Debbie Hughes\"\n \"Dennis Gordeev\"\n \"De", "end": 1778, "score": 0.9998549818992615, "start": 1765, "tag": "NAME", "value": "Debbie Hughes" }, { "context": "att\"\n \"Debbie Hughes\"\n \"Dennis Gordeev\"\n \"Devon Cady-Lee\"\n \"Do", "end": 1809, "score": 0.999803900718689, "start": 1795, "tag": "NAME", "value": "Dennis Gordeev" }, { "context": "es\"\n \"Dennis Gordeev\"\n \"Devon Cady-Lee\"\n \"Donato Giancola\"\n \"D", "end": 1840, "score": 0.9998107552528381, "start": 1826, "tag": "NAME", "value": "Devon Cady-Lee" }, { "context": "ev\"\n \"Devon Cady-Lee\"\n \"Donato Giancola\"\n \"Doug Anderson\"\n \"Dou", "end": 1872, "score": 0.9998528361320496, "start": 1857, "tag": "NAME", "value": "Donato Giancola" }, { "context": "e\"\n \"Donato Giancola\"\n \"Doug Anderson\"\n \"Doug Kovacs\"\n \"Dougl", "end": 1902, "score": 0.9998224377632141, "start": 1889, "tag": "NAME", "value": "Doug Anderson" }, { "context": "ola\"\n \"Doug Anderson\"\n \"Doug Kovacs\"\n \"Douglas Beekman\"\n \"D", "end": 1930, "score": 0.9998841881752014, "start": 1919, "tag": "NAME", "value": "Doug Kovacs" }, { "context": "erson\"\n \"Doug Kovacs\"\n \"Douglas Beekman\"\n \"Douglas Shuler\"\n \"Do", "end": 1962, "score": 0.9998927712440491, "start": 1947, "tag": "NAME", "value": "Douglas Beekman" }, { "context": "s\"\n \"Douglas Beekman\"\n \"Douglas Shuler\"\n \"Douglass Chaffee\"\n \"", "end": 1993, "score": 0.9998921155929565, "start": 1979, "tag": "NAME", "value": "Douglas Shuler" }, { "context": "an\"\n \"Douglas Shuler\"\n \"Douglass Chaffee\"\n \"Drew Tucker\"\n \"Ebe K", "end": 2026, "score": 0.9998950362205505, "start": 2010, "tag": "NAME", "value": "Douglass Chaffee" }, { "context": "\"\n \"Douglass Chaffee\"\n \"Drew Tucker\"\n \"Ebe Kastein\"\n \"Edwar", "end": 2054, "score": 0.9998952150344849, "start": 2043, "tag": "NAME", "value": "Drew Tucker" }, { "context": "affee\"\n \"Drew Tucker\"\n \"Ebe Kastein\"\n \"Edward Beard, Jr.\"\n ", "end": 2082, "score": 0.9999022483825684, "start": 2071, "tag": "NAME", "value": "Ebe Kastein" }, { "context": "ucker\"\n \"Ebe Kastein\"\n \"Edward Beard, Jr.\"\n \"Elena Kukanova\"\n ", "end": 2111, "score": 0.9998911619186401, "start": 2099, "tag": "NAME", "value": "Edward Beard" }, { "context": "\n \"Edward Beard, Jr.\"\n \"Elena Kukanova\"\n \"Ellym Sirac\"\n \"Eric ", "end": 2147, "score": 0.9998964667320251, "start": 2133, "tag": "NAME", "value": "Elena Kukanova" }, { "context": "r.\"\n \"Elena Kukanova\"\n \"Ellym Sirac\"\n \"Eric David Anderson\"\n ", "end": 2175, "score": 0.9999001622200012, "start": 2164, "tag": "NAME", "value": "Ellym Sirac" }, { "context": "anova\"\n \"Ellym Sirac\"\n \"Eric David Anderson\"\n \"fel_x\"\n \"Felicia Can", "end": 2211, "score": 0.9998946189880371, "start": 2192, "tag": "NAME", "value": "Eric David Anderson" }, { "context": " \"Eric David Anderson\"\n \"fel_x\"\n \"Felicia Cano\"\n \"Flav", "end": 2233, "score": 0.9527722597122192, "start": 2232, "tag": "USERNAME", "value": "x" }, { "context": "id Anderson\"\n \"fel_x\"\n \"Felicia Cano\"\n \"Flavio Bolla\"\n \"Fran", "end": 2262, "score": 0.9998959302902222, "start": 2250, "tag": "NAME", "value": "Felicia Cano" }, { "context": "el_x\"\n \"Felicia Cano\"\n \"Flavio Bolla\"\n \"Frank Frazetta\"\n \"Fr", "end": 2291, "score": 0.999902069568634, "start": 2279, "tag": "NAME", "value": "Flavio Bolla" }, { "context": "Cano\"\n \"Flavio Bolla\"\n \"Frank Frazetta\"\n \"Frank Kelley Freas\"\n ", "end": 2322, "score": 0.9998920559883118, "start": 2308, "tag": "NAME", "value": "Frank Frazetta" }, { "context": "la\"\n \"Frank Frazetta\"\n \"Frank Kelley Freas\"\n \"FreakyGaming\"\n \"Fred", "end": 2357, "score": 0.9998950958251953, "start": 2339, "tag": "NAME", "value": "Frank Kelley Freas" }, { "context": " \"Frank Kelley Freas\"\n \"FreakyGaming\"\n \"Fredrik Högberg\"\n \"F", "end": 2386, "score": 0.9998777508735657, "start": 2374, "tag": "NAME", "value": "FreakyGaming" }, { "context": "reas\"\n \"FreakyGaming\"\n \"Fredrik Högberg\"\n \"Friedrich A. Haas\"\n ", "end": 2418, "score": 0.9998962879180908, "start": 2403, "tag": "NAME", "value": "Fredrik Högberg" }, { "context": "g\"\n \"Fredrik Högberg\"\n \"Friedrich A. Haas\"\n \"Fritz Haas\"\n \"Gail M", "end": 2452, "score": 0.9998858571052551, "start": 2435, "tag": "NAME", "value": "Friedrich A. Haas" }, { "context": "\n \"Friedrich A. Haas\"\n \"Fritz Haas\"\n \"Gail McIntosh\"\n \"Gre", "end": 2479, "score": 0.9998921155929565, "start": 2469, "tag": "NAME", "value": "Fritz Haas" }, { "context": ". Haas\"\n \"Fritz Haas\"\n \"Gail McIntosh\"\n \"Greg McPherson\"\n \"Gr", "end": 2509, "score": 0.999896228313446, "start": 2496, "tag": "NAME", "value": "Gail McIntosh" }, { "context": "aas\"\n \"Gail McIntosh\"\n \"Greg McPherson\"\n \"Grzegorz Rutkowski\"\n ", "end": 2540, "score": 0.9999022483825684, "start": 2526, "tag": "NAME", "value": "Greg McPherson" }, { "context": "sh\"\n \"Greg McPherson\"\n \"Grzegorz Rutkowski\"\n \"Gyula Pozsgay\"\n \"Han", "end": 2575, "score": 0.9998750686645508, "start": 2557, "tag": "NAME", "value": "Grzegorz Rutkowski" }, { "context": " \"Grzegorz Rutkowski\"\n \"Gyula Pozsgay\"\n \"Hanna Lehmusto\"\n \"Ha", "end": 2605, "score": 0.9998932480812073, "start": 2592, "tag": "NAME", "value": "Gyula Pozsgay" }, { "context": "ski\"\n \"Gyula Pozsgay\"\n \"Hanna Lehmusto\"\n \"Hannibal King\"\n \"Har", "end": 2636, "score": 0.9998904466629028, "start": 2622, "tag": "NAME", "value": "Hanna Lehmusto" }, { "context": "ay\"\n \"Hanna Lehmusto\"\n \"Hannibal King\"\n \"Harry Quinn\"\n \"Heath", "end": 2666, "score": 0.9998887777328491, "start": 2653, "tag": "NAME", "value": "Hannibal King" }, { "context": "sto\"\n \"Hannibal King\"\n \"Harry Quinn\"\n \"Heather Hudson\"\n \"He", "end": 2694, "score": 0.9998766183853149, "start": 2683, "tag": "NAME", "value": "Harry Quinn" }, { "context": " King\"\n \"Harry Quinn\"\n \"Heather Hudson\"\n \"Henning Janssen\"\n \"H", "end": 2725, "score": 0.9998884201049805, "start": 2711, "tag": "NAME", "value": "Heather Hudson" }, { "context": "nn\"\n \"Heather Hudson\"\n \"Henning Janssen\"\n \"Hope Hoover\"\n \"Inger", "end": 2757, "score": 0.9998819231987, "start": 2742, "tag": "NAME", "value": "Henning Janssen" }, { "context": "n\"\n \"Henning Janssen\"\n \"Hope Hoover\"\n \"Inger Edelfeldt\"\n \"J", "end": 2785, "score": 0.9998919367790222, "start": 2774, "tag": "NAME", "value": "Hope Hoover" }, { "context": "nssen\"\n \"Hope Hoover\"\n \"Inger Edelfeldt\"\n \"J. Wallace Jones\"\n \"", "end": 2817, "score": 0.9998835325241089, "start": 2802, "tag": "NAME", "value": "Inger Edelfeldt" }, { "context": "r\"\n \"Inger Edelfeldt\"\n \"J. Wallace Jones\"\n \"Jacek Kopalski\"\n \"Ja", "end": 2850, "score": 0.9998862743377686, "start": 2834, "tag": "NAME", "value": "J. Wallace Jones" }, { "context": "\"\n \"J. Wallace Jones\"\n \"Jacek Kopalski\"\n \"Jan Pospíšil\"\n \"Jaso", "end": 2881, "score": 0.9998770356178284, "start": 2867, "tag": "NAME", "value": "Jacek Kopalski" }, { "context": "es\"\n \"Jacek Kopalski\"\n \"Jan Pospíšil\"\n \"Jason Manley\"\n \"Jean", "end": 2910, "score": 0.9998852610588074, "start": 2898, "tag": "NAME", "value": "Jan Pospíšil" }, { "context": "lski\"\n \"Jan Pospíšil\"\n \"Jason Manley\"\n \"Jean Pierre Reol\"\n \"", "end": 2939, "score": 0.9998791217803955, "start": 2927, "tag": "NAME", "value": "Jason Manley" }, { "context": "íšil\"\n \"Jason Manley\"\n \"Jean Pierre Reol\"\n \"Jeffery G. Reitz\"\n \"", "end": 2972, "score": 0.9998844861984253, "start": 2956, "tag": "NAME", "value": "Jean Pierre Reol" }, { "context": "\"\n \"Jean Pierre Reol\"\n \"Jeffery G. Reitz\"\n \"Jenny Dolfen\"\n \"Jo H", "end": 3005, "score": 0.9998760223388672, "start": 2989, "tag": "NAME", "value": "Jeffery G. Reitz" }, { "context": "\"\n \"Jeffery G. Reitz\"\n \"Jenny Dolfen\"\n \"Jo Hartwig\"\n \"John C", "end": 3034, "score": 0.9998908638954163, "start": 3022, "tag": "NAME", "value": "Jenny Dolfen" }, { "context": "eitz\"\n \"Jenny Dolfen\"\n \"Jo Hartwig\"\n \"John C. Duke\"\n \"John", "end": 3061, "score": 0.9998875856399536, "start": 3051, "tag": "NAME", "value": "Jo Hartwig" }, { "context": "Dolfen\"\n \"Jo Hartwig\"\n \"John C. Duke\"\n \"John Howe\"\n \"John Lu", "end": 3090, "score": 0.9998825788497925, "start": 3078, "tag": "NAME", "value": "John C. Duke" }, { "context": "twig\"\n \"John C. Duke\"\n \"John Howe\"\n \"John Luck\"\n \"John Mo", "end": 3116, "score": 0.9998855590820312, "start": 3107, "tag": "NAME", "value": "John Howe" }, { "context": "C. Duke\"\n \"John Howe\"\n \"John Luck\"\n \"John Monteleone\"\n \"J", "end": 3142, "score": 0.9998884201049805, "start": 3133, "tag": "NAME", "value": "John Luck" }, { "context": "hn Howe\"\n \"John Luck\"\n \"John Monteleone\"\n \"Jon Foster\"\n \"Jonas ", "end": 3174, "score": 0.9998935461044312, "start": 3159, "tag": "NAME", "value": "John Monteleone" }, { "context": "k\"\n \"John Monteleone\"\n \"Jon Foster\"\n \"Jonas Jakobsson\"\n \"J", "end": 3201, "score": 0.9998788237571716, "start": 3191, "tag": "NAME", "value": "Jon Foster" }, { "context": "eleone\"\n \"Jon Foster\"\n \"Jonas Jakobsson\"\n \"Jonas Jensen\"\n \"Jorg", "end": 3233, "score": 0.9998735785484314, "start": 3218, "tag": "NAME", "value": "Jonas Jakobsson" }, { "context": "r\"\n \"Jonas Jakobsson\"\n \"Jonas Jensen\"\n \"Jorge Jacinto\"\n \"Jos", "end": 3262, "score": 0.9998952150344849, "start": 3250, "tag": "NAME", "value": "Jonas Jensen" }, { "context": "sson\"\n \"Jonas Jensen\"\n \"Jorge Jacinto\"\n \"Jos van Zijl\"\n \"Jugr", "end": 3292, "score": 0.9998955130577087, "start": 3279, "tag": "NAME", "value": "Jorge Jacinto" }, { "context": "sen\"\n \"Jorge Jacinto\"\n \"Jos van Zijl\"\n \"Jugra\"\n \"Juhani Joki", "end": 3321, "score": 0.9998717308044434, "start": 3309, "tag": "NAME", "value": "Jos van Zijl" }, { "context": "into\"\n \"Jos van Zijl\"\n \"Jugra\"\n \"Juhani Jokinen\"\n \"Ju", "end": 3343, "score": 0.9998424649238586, "start": 3338, "tag": "NAME", "value": "Jugra" }, { "context": "os van Zijl\"\n \"Jugra\"\n \"Juhani Jokinen\"\n \"Julia Alekseeva\"\n \"J", "end": 3374, "score": 0.9998953938484192, "start": 3360, "tag": "NAME", "value": "Juhani Jokinen" }, { "context": "ra\"\n \"Juhani Jokinen\"\n \"Julia Alekseeva\"\n \"Julie Freeman\"\n \"Jus", "end": 3406, "score": 0.9998895525932312, "start": 3391, "tag": "NAME", "value": "Julia Alekseeva" }, { "context": "n\"\n \"Julia Alekseeva\"\n \"Julie Freeman\"\n \"Justin Sweet\"\n \"Kaja", "end": 3436, "score": 0.9998709559440613, "start": 3423, "tag": "NAME", "value": "Julie Freeman" }, { "context": "eva\"\n \"Julie Freeman\"\n \"Justin Sweet\"\n \"Kaja Foglio\"\n \"Kalen", "end": 3465, "score": 0.9998825788497925, "start": 3453, "tag": "NAME", "value": "Justin Sweet" }, { "context": "eman\"\n \"Justin Sweet\"\n \"Kaja Foglio\"\n \"Kalen Chock\"\n \"Kate ", "end": 3493, "score": 0.999896228313446, "start": 3482, "tag": "NAME", "value": "Kaja Foglio" }, { "context": "Sweet\"\n \"Kaja Foglio\"\n \"Kalen Chock\"\n \"Kate Pfeilschiefter\"\n ", "end": 3521, "score": 0.999886691570282, "start": 3510, "tag": "NAME", "value": "Kalen Chock" }, { "context": "oglio\"\n \"Kalen Chock\"\n \"Kate Pfeilschiefter\"\n \"Keith Parkinson\"\n \"K", "end": 3557, "score": 0.9998737573623657, "start": 3538, "tag": "NAME", "value": "Kate Pfeilschiefter" }, { "context": " \"Kate Pfeilschiefter\"\n \"Keith Parkinson\"\n \"Ken Meyer, Jr.\"\n \"Ke", "end": 3589, "score": 0.9998764991760254, "start": 3574, "tag": "NAME", "value": "Keith Parkinson" }, { "context": "r\"\n \"Keith Parkinson\"\n \"Ken Meyer, Jr.\"\n \"Kevin Ward\"\n \"K", "end": 3615, "score": 0.9998704195022583, "start": 3606, "tag": "NAME", "value": "Ken Meyer" }, { "context": "on\"\n \"Ken Meyer, Jr.\"\n \"Kevin Ward\"\n \"Kim Demulder\"\n \"Kimb", "end": 3647, "score": 0.999762237071991, "start": 3637, "tag": "NAME", "value": "Kevin Ward" }, { "context": "r, Jr.\"\n \"Kevin Ward\"\n \"Kim Demulder\"\n \"Kimberly80\"\n \"Kirk Q", "end": 3676, "score": 0.9998650550842285, "start": 3664, "tag": "NAME", "value": "Kim Demulder" }, { "context": "Ward\"\n \"Kim Demulder\"\n \"Kimberly80\"\n \"Kirk Quilaquil\"\n \"Ky", "end": 3703, "score": 0.9943280816078186, "start": 3693, "tag": "NAME", "value": "Kimberly80" }, { "context": "mulder\"\n \"Kimberly80\"\n \"Kirk Quilaquil\"\n \"Kyle Anderson\"\n \"Lar", "end": 3734, "score": 0.9998743534088135, "start": 3720, "tag": "NAME", "value": "Kirk Quilaquil" }, { "context": "80\"\n \"Kirk Quilaquil\"\n \"Kyle Anderson\"\n \"Larry Elmore\"\n \"Larr", "end": 3764, "score": 0.9998209476470947, "start": 3751, "tag": "NAME", "value": "Kyle Anderson" }, { "context": "uil\"\n \"Kyle Anderson\"\n \"Larry Elmore\"\n \"Larry Forcella\"\n \"Le", "end": 3793, "score": 0.9998921155929565, "start": 3781, "tag": "NAME", "value": "Larry Elmore" }, { "context": "rson\"\n \"Larry Elmore\"\n \"Larry Forcella\"\n \"Lee Seed\"\n \"Leo Wins", "end": 3824, "score": 0.9998947381973267, "start": 3810, "tag": "NAME", "value": "Larry Forcella" }, { "context": "re\"\n \"Larry Forcella\"\n \"Lee Seed\"\n \"Leo Winstead\"\n \"Leon", "end": 3849, "score": 0.9988629221916199, "start": 3841, "tag": "NAME", "value": "Lee Seed" }, { "context": "Forcella\"\n \"Lee Seed\"\n \"Leo Winstead\"\n \"Leonid Kozienko\"\n \"L", "end": 3878, "score": 0.9998580813407898, "start": 3866, "tag": "NAME", "value": "Leo Winstead" }, { "context": "Seed\"\n \"Leo Winstead\"\n \"Leonid Kozienko\"\n \"Lĩga Kļaviņa\"\n \"Lisa", "end": 3910, "score": 0.9998928904533386, "start": 3895, "tag": "NAME", "value": "Leonid Kozienko" }, { "context": "d\"\n \"Leonid Kozienko\"\n \"Lĩga Kļaviņa\"\n \"Lisa Hunt\"\n ", "end": 3928, "score": 0.8190503120422363, "start": 3927, "tag": "NAME", "value": "L" }, { "context": "\n \"Leonid Kozienko\"\n \"Lĩga Kļaviņa\"\n \"Lisa Hunt\"\n \"L", "end": 3933, "score": 0.956331729888916, "start": 3929, "tag": "NAME", "value": "ga K" }, { "context": "enko\"\n \"Lĩga Kļaviņa\"\n \"Lisa Hunt\"\n \"Lissanne Lake\"\n \"Liz", "end": 3965, "score": 0.9998661279678345, "start": 3956, "tag": "NAME", "value": "Lisa Hunt" }, { "context": "Kļaviņa\"\n \"Lisa Hunt\"\n \"Lissanne Lake\"\n \"Liz Danforth\"\n \"Lori", "end": 3995, "score": 0.9983533024787903, "start": 3982, "tag": "NAME", "value": "Lissanne Lake" }, { "context": "unt\"\n \"Lissanne Lake\"\n \"Liz Danforth\"\n \"Lori Deitrick\"\n \"Lub", "end": 4024, "score": 0.9998862147331238, "start": 4012, "tag": "NAME", "value": "Liz Danforth" }, { "context": "Lake\"\n \"Liz Danforth\"\n \"Lori Deitrick\"\n \"Lubov\"\n \"Lucas Alcan", "end": 4054, "score": 0.999895453453064, "start": 4041, "tag": "NAME", "value": "Lori Deitrick" }, { "context": "rth\"\n \"Lori Deitrick\"\n \"Lubov\"\n \"Lucas Alcantara\"\n \"L", "end": 4076, "score": 0.9849252700805664, "start": 4071, "tag": "NAME", "value": "Lubov" }, { "context": "ri Deitrick\"\n \"Lubov\"\n \"Lucas Alcantara\"\n \"Luis Royo\"\n \"Margare", "end": 4108, "score": 0.9998944997787476, "start": 4093, "tag": "NAME", "value": "Lucas Alcantara" }, { "context": "v\"\n \"Lucas Alcantara\"\n \"Luis Royo\"\n \"Margaret Organ-Kean\"\n ", "end": 4134, "score": 0.9998987317085266, "start": 4125, "tag": "NAME", "value": "Luis Royo" }, { "context": "cantara\"\n \"Luis Royo\"\n \"Margaret Organ-Kean\"\n \"Maria & Elena Gubina\"\n ", "end": 4170, "score": 0.9969958066940308, "start": 4151, "tag": "NAME", "value": "Margaret Organ-Kean" }, { "context": " \"Margaret Organ-Kean\"\n \"Maria & Elena Gubina\"\n \"Mark Forrer\"\n ", "end": 4192, "score": 0.9998112916946411, "start": 4187, "tag": "NAME", "value": "Maria" }, { "context": " \"Margaret Organ-Kean\"\n \"Maria & Elena Gubina\"\n \"Mark Forrer\"\n \"Mark ", "end": 4207, "score": 0.9996485114097595, "start": 4195, "tag": "NAME", "value": "Elena Gubina" }, { "context": " \"Maria & Elena Gubina\"\n \"Mark Forrer\"\n \"Mark Maxwell\"\n \"Mark", "end": 4235, "score": 0.9998946189880371, "start": 4224, "tag": "NAME", "value": "Mark Forrer" }, { "context": "ubina\"\n \"Mark Forrer\"\n \"Mark Maxwell\"\n \"Mark Molchan\"\n \"Mark", "end": 4264, "score": 0.9998952746391296, "start": 4252, "tag": "NAME", "value": "Mark Maxwell" }, { "context": "rrer\"\n \"Mark Maxwell\"\n \"Mark Molchan\"\n \"Mark Poole\"\n \"Matt S", "end": 4293, "score": 0.9998959898948669, "start": 4281, "tag": "NAME", "value": "Mark Molchan" }, { "context": "well\"\n \"Mark Molchan\"\n \"Mark Poole\"\n \"Matt Steward\"\n \"Matt", "end": 4320, "score": 0.9998769760131836, "start": 4310, "tag": "NAME", "value": "Mark Poole" }, { "context": "olchan\"\n \"Mark Poole\"\n \"Matt Steward\"\n \"Matt Stewart\"\n \"Matt", "end": 4349, "score": 0.9998871088027954, "start": 4337, "tag": "NAME", "value": "Matt Steward" }, { "context": "oole\"\n \"Matt Steward\"\n \"Matt Stewart\"\n \"Matthew Bradbury\"\n \"", "end": 4378, "score": 0.9998866319656372, "start": 4366, "tag": "NAME", "value": "Matt Stewart" }, { "context": "ward\"\n \"Matt Stewart\"\n \"Matthew Bradbury\"\n \"Matthew Innis\"\n \"Mat", "end": 4411, "score": 0.9998936653137207, "start": 4395, "tag": "NAME", "value": "Matthew Bradbury" }, { "context": "\"\n \"Matthew Bradbury\"\n \"Matthew Innis\"\n \"Matthew Stawicki\"\n \"", "end": 4441, "score": 0.999879002571106, "start": 4428, "tag": "NAME", "value": "Matthew Innis" }, { "context": "ury\"\n \"Matthew Innis\"\n \"Matthew Stawicki\"\n \"Melissa Benson\"\n \"Me", "end": 4474, "score": 0.9998872876167297, "start": 4458, "tag": "NAME", "value": "Matthew Stawicki" }, { "context": "\"\n \"Matthew Stawicki\"\n \"Melissa Benson\"\n \"Melissa Brown\"\n \"Mia", "end": 4505, "score": 0.9998850226402283, "start": 4491, "tag": "NAME", "value": "Melissa Benson" }, { "context": "ki\"\n \"Melissa Benson\"\n \"Melissa Brown\"\n \"Mia Steingraeber\"\n \"", "end": 4535, "score": 0.9998857378959656, "start": 4522, "tag": "NAME", "value": "Melissa Brown" }, { "context": "son\"\n \"Melissa Brown\"\n \"Mia Steingraeber\"\n \"Mia Tavonatti\"\n \"Mic", "end": 4568, "score": 0.9998822808265686, "start": 4552, "tag": "NAME", "value": "Mia Steingraeber" }, { "context": "\"\n \"Mia Steingraeber\"\n \"Mia Tavonatti\"\n \"Michael Apice\"\n \"Mic", "end": 4598, "score": 0.9998644590377808, "start": 4585, "tag": "NAME", "value": "Mia Tavonatti" }, { "context": "ber\"\n \"Mia Tavonatti\"\n \"Michael Apice\"\n \"Michael Astrachan\"\n ", "end": 4628, "score": 0.9998881816864014, "start": 4615, "tag": "NAME", "value": "Michael Apice" }, { "context": "tti\"\n \"Michael Apice\"\n \"Michael Astrachan\"\n \"Michael Hague\"\n \"Mic", "end": 4662, "score": 0.99988853931427, "start": 4645, "tag": "NAME", "value": "Michael Astrachan" }, { "context": "\n \"Michael Astrachan\"\n \"Michael Hague\"\n \"Michael Kaluta\"\n \"Mi", "end": 4692, "score": 0.9998759627342224, "start": 4679, "tag": "NAME", "value": "Michael Hague" }, { "context": "han\"\n \"Michael Hague\"\n \"Michael Kaluta\"\n \"Michael Komarck\"\n \"M", "end": 4723, "score": 0.9998882412910461, "start": 4709, "tag": "NAME", "value": "Michael Kaluta" }, { "context": "ue\"\n \"Michael Kaluta\"\n \"Michael Komarck\"\n \"Michael Kucharski\"\n ", "end": 4755, "score": 0.9998916387557983, "start": 4740, "tag": "NAME", "value": "Michael Komarck" }, { "context": "a\"\n \"Michael Komarck\"\n \"Michael Kucharski\"\n \"Miguel Coimbra\"\n \"Mi", "end": 4789, "score": 0.9998780488967896, "start": 4772, "tag": "NAME", "value": "Michael Kucharski" }, { "context": "\n \"Michael Kucharski\"\n \"Miguel Coimbra\"\n \"Miika Karmitsa\"\n \"Mi", "end": 4820, "score": 0.9998833537101746, "start": 4806, "tag": "NAME", "value": "Miguel Coimbra" }, { "context": "ki\"\n \"Miguel Coimbra\"\n \"Miika Karmitsa\"\n \"Milivoj Ceran\"\n \"N. ", "end": 4851, "score": 0.9998860359191895, "start": 4837, "tag": "NAME", "value": "Miika Karmitsa" }, { "context": "ra\"\n \"Miika Karmitsa\"\n \"Milivoj Ceran\"\n \"N. Taylor Blanchard\"\n ", "end": 4881, "score": 0.999896228313446, "start": 4868, "tag": "NAME", "value": "Milivoj Ceran" }, { "context": "tsa\"\n \"Milivoj Ceran\"\n \"N. Taylor Blanchard\"\n \"Nathalie Hertz\"\n \"Ni", "end": 4917, "score": 0.9998452067375183, "start": 4898, "tag": "NAME", "value": "N. Taylor Blanchard" }, { "context": " \"N. Taylor Blanchard\"\n \"Nathalie Hertz\"\n \"Nicholas Jainschigg\"\n ", "end": 4948, "score": 0.9998835325241089, "start": 4934, "tag": "NAME", "value": "Nathalie Hertz" }, { "context": "rd\"\n \"Nathalie Hertz\"\n \"Nicholas Jainschigg\"\n \"Nick Deligaris\"\n \"No", "end": 4984, "score": 0.9998971223831177, "start": 4965, "tag": "NAME", "value": "Nicholas Jainschigg" }, { "context": " \"Nicholas Jainschigg\"\n \"Nick Deligaris\"\n \"Noah Bradley\"\n \"Oliv", "end": 5015, "score": 0.9998838901519775, "start": 5001, "tag": "NAME", "value": "Nick Deligaris" }, { "context": "gg\"\n \"Nick Deligaris\"\n \"Noah Bradley\"\n \"Olivier Frot\"\n \"Omar", "end": 5044, "score": 0.9998877644538879, "start": 5032, "tag": "NAME", "value": "Noah Bradley" }, { "context": "aris\"\n \"Noah Bradley\"\n \"Olivier Frot\"\n \"Omar Rayyan\"\n \"Pamel", "end": 5073, "score": 0.999893069267273, "start": 5061, "tag": "NAME", "value": "Olivier Frot" }, { "context": "dley\"\n \"Olivier Frot\"\n \"Omar Rayyan\"\n \"Pamela Shanteau\"\n \"P", "end": 5101, "score": 0.9998934864997864, "start": 5090, "tag": "NAME", "value": "Omar Rayyan" }, { "context": " Frot\"\n \"Omar Rayyan\"\n \"Pamela Shanteau\"\n \"Pascal Yung\"\n \"Pat M", "end": 5133, "score": 0.9998931884765625, "start": 5118, "tag": "NAME", "value": "Pamela Shanteau" }, { "context": "n\"\n \"Pamela Shanteau\"\n \"Pascal Yung\"\n \"Pat Morrissey\"\n \"Pau", "end": 5161, "score": 0.9998902082443237, "start": 5150, "tag": "NAME", "value": "Pascal Yung" }, { "context": "nteau\"\n \"Pascal Yung\"\n \"Pat Morrissey\"\n \"Paul Gregory\"\n \"Paul", "end": 5191, "score": 0.9998941421508789, "start": 5178, "tag": "NAME", "value": "Pat Morrissey" }, { "context": "ung\"\n \"Pat Morrissey\"\n \"Paul Gregory\"\n \"Paul Laleine\"\n \"Paul", "end": 5220, "score": 0.9998953938484192, "start": 5208, "tag": "NAME", "value": "Paul Gregory" }, { "context": "ssey\"\n \"Paul Gregory\"\n \"Paul Laleine\"\n \"Paul Lasaine\"\n \"Per ", "end": 5249, "score": 0.999890148639679, "start": 5237, "tag": "NAME", "value": "Paul Laleine" }, { "context": "gory\"\n \"Paul Laleine\"\n \"Paul Lasaine\"\n \"Per Sjögren\"\n \"Pete ", "end": 5278, "score": 0.9998966455459595, "start": 5266, "tag": "NAME", "value": "Paul Lasaine" }, { "context": "eine\"\n \"Paul Lasaine\"\n \"Per Sjögren\"\n \"Pete Fenlon\"\n \"Peter", "end": 5306, "score": 0.9998989105224609, "start": 5295, "tag": "NAME", "value": "Per Sjögren" }, { "context": "saine\"\n \"Per Sjögren\"\n \"Pete Fenlon\"\n \"Peter X. Price\"\n \"Qu", "end": 5334, "score": 0.9998781085014343, "start": 5323, "tag": "NAME", "value": "Pete Fenlon" }, { "context": "ögren\"\n \"Pete Fenlon\"\n \"Peter X. Price\"\n \"Quinton Hoover\"\n \"R.", "end": 5365, "score": 0.9998852610588074, "start": 5351, "tag": "NAME", "value": "Peter X. Price" }, { "context": "on\"\n \"Peter X. Price\"\n \"Quinton Hoover\"\n \"R. Ward Shipman\"\n \"R", "end": 5396, "score": 0.9999015927314758, "start": 5382, "tag": "NAME", "value": "Quinton Hoover" }, { "context": "ce\"\n \"Quinton Hoover\"\n \"R. Ward Shipman\"\n \"Rafal Hrynkiewicz\"\n ", "end": 5428, "score": 0.9998865723609924, "start": 5413, "tag": "NAME", "value": "R. Ward Shipman" }, { "context": "r\"\n \"R. Ward Shipman\"\n \"Rafal Hrynkiewicz\"\n \"Randy Asplund-Faith\"\n ", "end": 5462, "score": 0.9998809099197388, "start": 5445, "tag": "NAME", "value": "Rafal Hrynkiewicz" }, { "context": "\n \"Rafal Hrynkiewicz\"\n \"Randy Asplund-Faith\"\n \"Randy Gallegos\"\n \"Ra", "end": 5498, "score": 0.9998888969421387, "start": 5479, "tag": "NAME", "value": "Randy Asplund-Faith" }, { "context": " \"Randy Asplund-Faith\"\n \"Randy Gallegos\"\n \"Raphaël Lacoste\"\n \"R", "end": 5529, "score": 0.9998790621757507, "start": 5515, "tag": "NAME", "value": "Randy Gallegos" }, { "context": "th\"\n \"Randy Gallegos\"\n \"Raphaël Lacoste\"\n \"Rebecca Guay\"\n \"Reto", "end": 5561, "score": 0.9998765587806702, "start": 5546, "tag": "NAME", "value": "Raphaël Lacoste" }, { "context": "s\"\n \"Raphaël Lacoste\"\n \"Rebecca Guay\"\n \"Reto Kaul\"\n \"Richard", "end": 5590, "score": 0.9998806118965149, "start": 5578, "tag": "NAME", "value": "Rebecca Guay" }, { "context": "oste\"\n \"Rebecca Guay\"\n \"Reto Kaul\"\n \"Richard Hook\"\n \"Rob ", "end": 5616, "score": 0.9998829960823059, "start": 5607, "tag": "NAME", "value": "Reto Kaul" }, { "context": "ca Guay\"\n \"Reto Kaul\"\n \"Richard Hook\"\n \"Rob Alexander\"\n \"Rob", "end": 5645, "score": 0.999868631362915, "start": 5633, "tag": "NAME", "value": "Richard Hook" }, { "context": "Kaul\"\n \"Richard Hook\"\n \"Rob Alexander\"\n \"Robin Wood\"\n \"Rodney", "end": 5675, "score": 0.9998649954795837, "start": 5662, "tag": "NAME", "value": "Rob Alexander" }, { "context": "ook\"\n \"Rob Alexander\"\n \"Robin Wood\"\n \"Rodney Matthews\"\n \"R", "end": 5702, "score": 0.9998908042907715, "start": 5692, "tag": "NAME", "value": "Robin Wood" }, { "context": "xander\"\n \"Robin Wood\"\n \"Rodney Matthews\"\n \"Roger Garland\"\n \"Rom", "end": 5734, "score": 0.9998900294303894, "start": 5719, "tag": "NAME", "value": "Rodney Matthews" }, { "context": "d\"\n \"Rodney Matthews\"\n \"Roger Garland\"\n \"Romas Kukalis\"\n \"Ron", "end": 5764, "score": 0.9998919367790222, "start": 5751, "tag": "NAME", "value": "Roger Garland" }, { "context": "ews\"\n \"Roger Garland\"\n \"Romas Kukalis\"\n \"Ron Miller\"\n \"Ron Ro", "end": 5794, "score": 0.9998977780342102, "start": 5781, "tag": "NAME", "value": "Romas Kukalis" }, { "context": "and\"\n \"Romas Kukalis\"\n \"Ron Miller\"\n \"Ron Rousselle II\"\n \"", "end": 5821, "score": 0.9998955726623535, "start": 5811, "tag": "NAME", "value": "Ron Miller" }, { "context": "ukalis\"\n \"Ron Miller\"\n \"Ron Rousselle II\"\n \"Ron Spencer\"\n \"Ron W", "end": 5854, "score": 0.9998818039894104, "start": 5838, "tag": "NAME", "value": "Ron Rousselle II" }, { "context": "\"\n \"Ron Rousselle II\"\n \"Ron Spencer\"\n \"Ron Walotsky\"\n \"Rona", "end": 5882, "score": 0.9998842477798462, "start": 5871, "tag": "NAME", "value": "Ron Spencer" }, { "context": "le II\"\n \"Ron Spencer\"\n \"Ron Walotsky\"\n \"Ronald Chironna\"\n \"R", "end": 5911, "score": 0.9998897910118103, "start": 5899, "tag": "NAME", "value": "Ron Walotsky" }, { "context": "ncer\"\n \"Ron Walotsky\"\n \"Ronald Chironna\"\n \"Ronald Shuey\"\n \"Sand", "end": 5943, "score": 0.9998969435691833, "start": 5928, "tag": "NAME", "value": "Ronald Chironna" }, { "context": "y\"\n \"Ronald Chironna\"\n \"Ronald Shuey\"\n \"Sandrine Gestin\"\n \"S", "end": 5972, "score": 0.9998964667320251, "start": 5960, "tag": "NAME", "value": "Ronald Shuey" }, { "context": "onna\"\n \"Ronald Shuey\"\n \"Sandrine Gestin\"\n \"Santiago Iborra\"\n \"S", "end": 6004, "score": 0.9998930096626282, "start": 5989, "tag": "NAME", "value": "Sandrine Gestin" }, { "context": "y\"\n \"Sandrine Gestin\"\n \"Santiago Iborra\"\n \"Sarel Theron\"\n \"Seba", "end": 6036, "score": 0.9998984336853027, "start": 6021, "tag": "NAME", "value": "Santiago Iborra" }, { "context": "n\"\n \"Santiago Iborra\"\n \"Sarel Theron\"\n \"Sebastian Wagner\"\n \"", "end": 6065, "score": 0.9998990893363953, "start": 6053, "tag": "NAME", "value": "Sarel Theron" }, { "context": "orra\"\n \"Sarel Theron\"\n \"Sebastian Wagner\"\n \"Sedone Thongvilay\"\n ", "end": 6098, "score": 0.9999004006385803, "start": 6082, "tag": "NAME", "value": "Sebastian Wagner" }, { "context": "\"\n \"Sebastian Wagner\"\n \"Sedone Thongvilay\"\n \"Sérgio Artigas\"\n \"St", "end": 6132, "score": 0.9999027848243713, "start": 6115, "tag": "NAME", "value": "Sedone Thongvilay" }, { "context": "\n \"Sedone Thongvilay\"\n \"Sérgio Artigas\"\n \"Stacey K. Kite\"\n \"St", "end": 6163, "score": 0.9999006986618042, "start": 6149, "tag": "NAME", "value": "Sérgio Artigas" }, { "context": "ay\"\n \"Sérgio Artigas\"\n \"Stacey K. Kite\"\n \"Stefano Baldo\"\n \"Ste", "end": 6194, "score": 0.9998922348022461, "start": 6180, "tag": "NAME", "value": "Stacey K. Kite" }, { "context": "as\"\n \"Stacey K. Kite\"\n \"Stefano Baldo\"\n \"Stephen A. Daniele\"\n ", "end": 6224, "score": 0.9998823404312134, "start": 6211, "tag": "NAME", "value": "Stefano Baldo" }, { "context": "ite\"\n \"Stefano Baldo\"\n \"Stephen A. Daniele\"\n \"Stephen F. Schwartz\"\n ", "end": 6259, "score": 0.9998825192451477, "start": 6241, "tag": "NAME", "value": "Stephen A. Daniele" }, { "context": " \"Stephen A. Daniele\"\n \"Stephen F. Schwartz\"\n \"Stephen Graham Walsh\"\n ", "end": 6295, "score": 0.9998723864555359, "start": 6276, "tag": "NAME", "value": "Stephen F. Schwartz" }, { "context": " \"Stephen F. Schwartz\"\n \"Stephen Graham Walsh\"\n \"Stephen Hickman\"\n \"S", "end": 6332, "score": 0.9998771548271179, "start": 6312, "tag": "NAME", "value": "Stephen Graham Walsh" }, { "context": " \"Stephen Graham Walsh\"\n \"Stephen Hickman\"\n \"Stephen King\"\n \"Step", "end": 6364, "score": 0.9998733401298523, "start": 6349, "tag": "NAME", "value": "Stephen Hickman" }, { "context": "h\"\n \"Stephen Hickman\"\n \"Stephen King\"\n \"Stephen Schwartz\"\n \"", "end": 6393, "score": 0.9998685717582703, "start": 6381, "tag": "NAME", "value": "Stephen King" }, { "context": "kman\"\n \"Stephen King\"\n \"Stephen Schwartz\"\n \"Steve Argyle\"\n \"Stev", "end": 6426, "score": 0.9998694658279419, "start": 6410, "tag": "NAME", "value": "Stephen Schwartz" }, { "context": "\"\n \"Stephen Schwartz\"\n \"Steve Argyle\"\n \"Steve Luke\"\n \"Steve ", "end": 6455, "score": 0.9998509883880615, "start": 6443, "tag": "NAME", "value": "Steve Argyle" }, { "context": "artz\"\n \"Steve Argyle\"\n \"Steve Luke\"\n \"Steve Otis\"\n \"Steven", "end": 6482, "score": 0.9998499751091003, "start": 6472, "tag": "NAME", "value": "Steve Luke" }, { "context": "Argyle\"\n \"Steve Luke\"\n \"Steve Otis\"\n \"Steven Cavallo\"\n \"St", "end": 6509, "score": 0.9998688697814941, "start": 6499, "tag": "NAME", "value": "Steve Otis" }, { "context": "e Luke\"\n \"Steve Otis\"\n \"Steven Cavallo\"\n \"Storn Cook\"\n \"Susan ", "end": 6540, "score": 0.9998723864555359, "start": 6526, "tag": "NAME", "value": "Steven Cavallo" }, { "context": "is\"\n \"Steven Cavallo\"\n \"Storn Cook\"\n \"Susan Van Camp\"\n \"Te", "end": 6567, "score": 0.9998416304588318, "start": 6557, "tag": "NAME", "value": "Storn Cook" }, { "context": "avallo\"\n \"Storn Cook\"\n \"Susan Van Camp\"\n \"Ted Nasmith\"\n \"Thoma", "end": 6598, "score": 0.9998676776885986, "start": 6584, "tag": "NAME", "value": "Susan Van Camp" }, { "context": "ok\"\n \"Susan Van Camp\"\n \"Ted Nasmith\"\n \"Thomas Gianni\"\n \"Tim", "end": 6626, "score": 0.999876856803894, "start": 6615, "tag": "NAME", "value": "Ted Nasmith" }, { "context": " Camp\"\n \"Ted Nasmith\"\n \"Thomas Gianni\"\n \"Tim Baker\"\n \"Tim Kir", "end": 6656, "score": 0.9998709559440613, "start": 6643, "tag": "NAME", "value": "Thomas Gianni" }, { "context": "ith\"\n \"Thomas Gianni\"\n \"Tim Baker\"\n \"Tim Kirk\"\n \"Timo Vih", "end": 6682, "score": 0.9998746514320374, "start": 6673, "tag": "NAME", "value": "Tim Baker" }, { "context": " Gianni\"\n \"Tim Baker\"\n \"Tim Kirk\"\n \"Timo Vihola\"\n \"Todd ", "end": 6707, "score": 0.9998660087585449, "start": 6699, "tag": "NAME", "value": "Tim Kirk" }, { "context": "im Baker\"\n \"Tim Kirk\"\n \"Timo Vihola\"\n \"Todd Lockwood\"\n \"Tom", "end": 6735, "score": 0.9998846054077148, "start": 6724, "tag": "NAME", "value": "Timo Vihola" }, { "context": " Kirk\"\n \"Timo Vihola\"\n \"Todd Lockwood\"\n \"Tom Cross\"\n \"Tom Dow", "end": 6765, "score": 0.9998846054077148, "start": 6752, "tag": "NAME", "value": "Todd Lockwood" }, { "context": "ola\"\n \"Todd Lockwood\"\n \"Tom Cross\"\n \"Tom Dow\"\n \"Tom Kidd\"", "end": 6791, "score": 0.9998470544815063, "start": 6782, "tag": "NAME", "value": "Tom Cross" }, { "context": "ockwood\"\n \"Tom Cross\"\n \"Tom Dow\"\n \"Tom Kidd\"\n \"Tom Simo", "end": 6815, "score": 0.9998546242713928, "start": 6808, "tag": "NAME", "value": "Tom Dow" }, { "context": "Tom Cross\"\n \"Tom Dow\"\n \"Tom Kidd\"\n \"Tom Simonton\"\n \"Toni", "end": 6840, "score": 0.9998824000358582, "start": 6832, "tag": "NAME", "value": "Tom Kidd" }, { "context": "\"Tom Dow\"\n \"Tom Kidd\"\n \"Tom Simonton\"\n \"Toni Galuidi\"\n \"Turb", "end": 6869, "score": 0.9998868703842163, "start": 6857, "tag": "NAME", "value": "Tom Simonton" }, { "context": "Kidd\"\n \"Tom Simonton\"\n \"Toni Galuidi\"\n \"Turbine LotRO\"\n \"Tur", "end": 6898, "score": 0.9998544454574585, "start": 6886, "tag": "NAME", "value": "Toni Galuidi" }, { "context": "idi\"\n \"Turbine LotRO\"\n \"Turner Mohan\"\n \"Val Mayerik\"\n \"Vince", "end": 6957, "score": 0.9998687505722046, "start": 6945, "tag": "NAME", "value": "Turner Mohan" }, { "context": "otRO\"\n \"Turner Mohan\"\n \"Val Mayerik\"\n \"Vincens Luján\"\n \"Vin", "end": 6985, "score": 0.9998862743377686, "start": 6974, "tag": "NAME", "value": "Val Mayerik" }, { "context": "Mohan\"\n \"Val Mayerik\"\n \"Vincens Luján\"\n \"Vincent Dutrait\"\n \"W", "end": 7015, "score": 0.9998728632926941, "start": 7002, "tag": "NAME", "value": "Vincens Luján" }, { "context": "rik\"\n \"Vincens Luján\"\n \"Vincent Dutrait\"\n \"William O'Connor\"\n \"", "end": 7047, "score": 0.9998721480369568, "start": 7032, "tag": "NAME", "value": "Vincent Dutrait" }, { "context": "n\"\n \"Vincent Dutrait\"\n \"William O'Connor\"\n \"winterkeep\"\n \"Wouter", "end": 7080, "score": 0.999891459941864, "start": 7064, "tag": "NAME", "value": "William O'Connor" }, { "context": "Connor\"\n \"winterkeep\"\n \"Wouter Florusse\"\n \"Zina Saunders\"\n ])", "end": 7139, "score": 0.9998807311058044, "start": 7124, "tag": "NAME", "value": "Wouter Florusse" }, { "context": "p\"\n \"Wouter Florusse\"\n \"Zina Saunders\"\n ])", "end": 7169, "score": 0.9998839497566223, "start": 7156, "tag": "NAME", "value": "Zina Saunders" } ]
src/cljs/meccg/artists.cljs
rezwits/carncode
15
(ns meccg.artists (:require [om.core :as om :include-macros true] [sablono.core :as sab :include-macros true] [clojure.string :refer [split]])) (def artists [ "Alan Guitierrez" "Alan Lee" "Alan Pollack" "Alan Rabinowitz" "Alarie Tano" "Allen G. Douglas" "Ana Kusicka" "Anders Finer" "Andrea Piparo" "Andreas Rocha" "Andrew Goldhawk" "Angel Falto" "Angelo Michelucci" "Angelo Montanini" "Angus McBride" "Anke K. Eissmann" "Annika Ritz" "April Lee" "Arch Stanton" "Audrey Corman" "Barbera E. de Jong" "Birthe Jabs" "Bob Eggleton" "Brad Williams" "Bradly van Camp" "Brian Durfee" "Brian Snoddy" "Brian T. Fox" "Brom" "Carol Heyer" "Chris Achilleos" "Chris Cocozza" "Chris Trevas" "Christina Wald" "Christopher Miller" "Cortney Skinner" "Dameon Willich" "Daniel Frazier" "Daniel Gelon" "Daniel Horne" "Daniel Wikart" "Darrell Sweet" "Darryl Elliott" "David A. Cherry" "David Deitrick" "David Kooharian" "David Martin" "David Monette" "David R. Seeley" "David Sexton" "David T. Wenzel" "David Wyatt" "Debbie Hughes" "Dennis Gordeev" "Devon Cady-Lee" "Donato Giancola" "Doug Anderson" "Doug Kovacs" "Douglas Beekman" "Douglas Shuler" "Douglass Chaffee" "Drew Tucker" "Ebe Kastein" "Edward Beard, Jr." "Elena Kukanova" "Ellym Sirac" "Eric David Anderson" "fel_x" "Felicia Cano" "Flavio Bolla" "Frank Frazetta" "Frank Kelley Freas" "FreakyGaming" "Fredrik Högberg" "Friedrich A. Haas" "Fritz Haas" "Gail McIntosh" "Greg McPherson" "Grzegorz Rutkowski" "Gyula Pozsgay" "Hanna Lehmusto" "Hannibal King" "Harry Quinn" "Heather Hudson" "Henning Janssen" "Hope Hoover" "Inger Edelfeldt" "J. Wallace Jones" "Jacek Kopalski" "Jan Pospíšil" "Jason Manley" "Jean Pierre Reol" "Jeffery G. Reitz" "Jenny Dolfen" "Jo Hartwig" "John C. Duke" "John Howe" "John Luck" "John Monteleone" "Jon Foster" "Jonas Jakobsson" "Jonas Jensen" "Jorge Jacinto" "Jos van Zijl" "Jugra" "Juhani Jokinen" "Julia Alekseeva" "Julie Freeman" "Justin Sweet" "Kaja Foglio" "Kalen Chock" "Kate Pfeilschiefter" "Keith Parkinson" "Ken Meyer, Jr." "Kevin Ward" "Kim Demulder" "Kimberly80" "Kirk Quilaquil" "Kyle Anderson" "Larry Elmore" "Larry Forcella" "Lee Seed" "Leo Winstead" "Leonid Kozienko" "Lĩga Kļaviņa" "Lisa Hunt" "Lissanne Lake" "Liz Danforth" "Lori Deitrick" "Lubov" "Lucas Alcantara" "Luis Royo" "Margaret Organ-Kean" "Maria & Elena Gubina" "Mark Forrer" "Mark Maxwell" "Mark Molchan" "Mark Poole" "Matt Steward" "Matt Stewart" "Matthew Bradbury" "Matthew Innis" "Matthew Stawicki" "Melissa Benson" "Melissa Brown" "Mia Steingraeber" "Mia Tavonatti" "Michael Apice" "Michael Astrachan" "Michael Hague" "Michael Kaluta" "Michael Komarck" "Michael Kucharski" "Miguel Coimbra" "Miika Karmitsa" "Milivoj Ceran" "N. Taylor Blanchard" "Nathalie Hertz" "Nicholas Jainschigg" "Nick Deligaris" "Noah Bradley" "Olivier Frot" "Omar Rayyan" "Pamela Shanteau" "Pascal Yung" "Pat Morrissey" "Paul Gregory" "Paul Laleine" "Paul Lasaine" "Per Sjögren" "Pete Fenlon" "Peter X. Price" "Quinton Hoover" "R. Ward Shipman" "Rafal Hrynkiewicz" "Randy Asplund-Faith" "Randy Gallegos" "Raphaël Lacoste" "Rebecca Guay" "Reto Kaul" "Richard Hook" "Rob Alexander" "Robin Wood" "Rodney Matthews" "Roger Garland" "Romas Kukalis" "Ron Miller" "Ron Rousselle II" "Ron Spencer" "Ron Walotsky" "Ronald Chironna" "Ronald Shuey" "Sandrine Gestin" "Santiago Iborra" "Sarel Theron" "Sebastian Wagner" "Sedone Thongvilay" "Sérgio Artigas" "Stacey K. Kite" "Stefano Baldo" "Stephen A. Daniele" "Stephen F. Schwartz" "Stephen Graham Walsh" "Stephen Hickman" "Stephen King" "Stephen Schwartz" "Steve Argyle" "Steve Luke" "Steve Otis" "Steven Cavallo" "Storn Cook" "Susan Van Camp" "Ted Nasmith" "Thomas Gianni" "Tim Baker" "Tim Kirk" "Timo Vihola" "Todd Lockwood" "Tom Cross" "Tom Dow" "Tom Kidd" "Tom Simonton" "Toni Galuidi" "Turbine LotRO" "Turner Mohan" "Val Mayerik" "Vincens Luján" "Vincent Dutrait" "William O'Connor" "winterkeep" "Wouter Florusse" "Zina Saunders" ])
107659
(ns meccg.artists (:require [om.core :as om :include-macros true] [sablono.core :as sab :include-macros true] [clojure.string :refer [split]])) (def artists [ "<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>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>, Jr." "<NAME>" "<NAME>" "<NAME>" "fel_x" "<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>, Jr." "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>ĩ<NAME>ļaviņa" "<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>" "<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>" "Turbine LotRO" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "winterkeep" "<NAME>" "<NAME>" ])
true
(ns meccg.artists (:require [om.core :as om :include-macros true] [sablono.core :as sab :include-macros true] [clojure.string :refer [split]])) (def artists [ "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" "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, Jr." "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "fel_x" "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, Jr." "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ļaviņa" "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" "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" "Turbine LotRO" "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" "winterkeep" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" ])
[ { "context": " \"inputs/aoc_2015/day-13.txt\"))\n\n(def test-input \"Alice would gain 54 happiness units by sitting next to ", "end": 266, "score": 0.9936507940292358, "start": 261, "tag": "NAME", "value": "Alice" }, { "context": "e would gain 54 happiness units by sitting next to Bob.\\nAlice would lose 79 happiness units by sitting ", "end": 319, "score": 0.9872235059738159, "start": 316, "tag": "NAME", "value": "Bob" }, { "context": " gain 54 happiness units by sitting next to Bob.\\nAlice would lose 79 happiness units by sitting next to ", "end": 327, "score": 0.9930585622787476, "start": 322, "tag": "NAME", "value": "Alice" }, { "context": "e would lose 79 happiness units by sitting next to Carol.\\nAlice would lose 2 happiness units by sitting n", "end": 382, "score": 0.9492063522338867, "start": 377, "tag": "NAME", "value": "Carol" }, { "context": "ose 79 happiness units by sitting next to Carol.\\nAlice would lose 2 happiness units by sitting next to D", "end": 390, "score": 0.9865254163742065, "start": 385, "tag": "NAME", "value": "Alice" }, { "context": "ce would lose 2 happiness units by sitting next to David.\\nBob would gain 83 happiness units by sitting ne", "end": 444, "score": 0.988784670829773, "start": 439, "tag": "NAME", "value": "David" }, { "context": "lose 2 happiness units by sitting next to David.\\nBob would gain 83 happiness units by sitting next to ", "end": 450, "score": 0.9865161180496216, "start": 447, "tag": "NAME", "value": "Bob" }, { "context": "b would gain 83 happiness units by sitting next to Alice.\\nBob would lose 7 happiness units by sitting nex", "end": 505, "score": 0.977719783782959, "start": 500, "tag": "NAME", "value": "Alice" }, { "context": "ain 83 happiness units by sitting next to Alice.\\nBob would lose 7 happiness units by sitting next to C", "end": 511, "score": 0.9750824570655823, "start": 508, "tag": "NAME", "value": "Bob" }, { "context": "ob would lose 7 happiness units by sitting next to Carol.\\nBob would lose 63 happiness units by sitting ne", "end": 565, "score": 0.9158284664154053, "start": 560, "tag": "NAME", "value": "Carol" }, { "context": "lose 7 happiness units by sitting next to Carol.\\nBob would lose 63 happiness units by sitting next to ", "end": 571, "score": 0.9563765525817871, "start": 568, "tag": "NAME", "value": "Bob" }, { "context": "b would lose 63 happiness units by sitting next to David.\\nCarol would lose 62 happiness units by sitting ", "end": 626, "score": 0.9767048358917236, "start": 621, "tag": "NAME", "value": "David" }, { "context": "ose 63 happiness units by sitting next to David.\\nCarol would lose 62 happiness units by sitting next to ", "end": 634, "score": 0.9392434358596802, "start": 629, "tag": "NAME", "value": "Carol" }, { "context": "l would lose 62 happiness units by sitting next to Alice.\\nCarol would gain 60 happiness units by sitting ", "end": 689, "score": 0.9862467050552368, "start": 684, "tag": "NAME", "value": "Alice" }, { "context": "ose 62 happiness units by sitting next to Alice.\\nCarol would gain 60 happiness units by sitting next to ", "end": 697, "score": 0.8686693906784058, "start": 692, "tag": "NAME", "value": "Carol" }, { "context": "l would gain 60 happiness units by sitting next to Bob.\\nCarol would gain 55 happiness units by sitting ", "end": 750, "score": 0.9699931144714355, "start": 747, "tag": "NAME", "value": "Bob" }, { "context": " gain 60 happiness units by sitting next to Bob.\\nCarol would gain 55 happiness units by sitting next to ", "end": 758, "score": 0.8778544664382935, "start": 753, "tag": "NAME", "value": "Carol" }, { "context": "l would gain 55 happiness units by sitting next to David.\\nDavid would gain 46 happiness units by sitting ", "end": 813, "score": 0.9788132905960083, "start": 808, "tag": "NAME", "value": "David" }, { "context": "ain 55 happiness units by sitting next to David.\\nDavid would gain 46 happiness units by sitting next to ", "end": 821, "score": 0.9849129319190979, "start": 816, "tag": "NAME", "value": "David" }, { "context": "d would gain 46 happiness units by sitting next to Alice.\\nDavid would lose 7 happiness units by sitting n", "end": 876, "score": 0.976376473903656, "start": 871, "tag": "NAME", "value": "Alice" }, { "context": "ain 46 happiness units by sitting next to Alice.\\nDavid would lose 7 happiness units by sitting next to B", "end": 884, "score": 0.9731767177581787, "start": 879, "tag": "NAME", "value": "David" }, { "context": "id would lose 7 happiness units by sitting next to Bob.\\nDavid would gain 41 happiness units by sitting ", "end": 936, "score": 0.967059850692749, "start": 933, "tag": "NAME", "value": "Bob" }, { "context": "d lose 7 happiness units by sitting next to Bob.\\nDavid would gain 41 happiness units by sitting next to ", "end": 944, "score": 0.9743821620941162, "start": 939, "tag": "NAME", "value": "David" }, { "context": "d would gain 41 happiness units by sitting next to Carol.\")\n\n\n(defn parse-line\n [line]\n (let [[_ name op", "end": 999, "score": 0.9033775329589844, "start": 994, "tag": "NAME", "value": "Carol" } ]
src/clojure/aoc_2015/day_13.clj
NPException/advent-of-code
0
(ns aoc-2015.day-13 (:require [clojure.string :as string] [aoc-utils :as u])) ;; --- Day 13: Knights of the Dinner Table --- https://adventofcode.com/2015/day/13 (def task-input (u/slurp-resource "inputs/aoc_2015/day-13.txt")) (def test-input "Alice would gain 54 happiness units by sitting next to Bob.\nAlice would lose 79 happiness units by sitting next to Carol.\nAlice would lose 2 happiness units by sitting next to David.\nBob would gain 83 happiness units by sitting next to Alice.\nBob would lose 7 happiness units by sitting next to Carol.\nBob would lose 63 happiness units by sitting next to David.\nCarol would lose 62 happiness units by sitting next to Alice.\nCarol would gain 60 happiness units by sitting next to Bob.\nCarol would gain 55 happiness units by sitting next to David.\nDavid would gain 46 happiness units by sitting next to Alice.\nDavid would lose 7 happiness units by sitting next to Bob.\nDavid would gain 41 happiness units by sitting next to Carol.") (defn parse-line [line] (let [[_ name op n name-2] (re-matches #"(\w+) would (gain|lose) (\d+) happiness units by sitting next to (\w+)\." line) n (parse-long n)] {name {name-2 (if (= op "gain") n (- n))}})) (defn parse-input [input] (->> (string/split-lines input) (map parse-line) (apply merge-with merge))) (defn calculate-happiness [preferences seating-order] (->> (conj (vec seating-order) (first seating-order)) (partition 2 1) (reduce #(+ %1 (get-in preferences %2) (get-in preferences (reverse %2))) 0))) (defn optimal-seating-score [preferences] (->> (keys preferences) u/permutations (map (partial calculate-happiness preferences)) (apply max))) (defn part-1 [input] (optimal-seating-score (parse-input input))) (defn part-2 [input] (let [preferences (parse-input input)] (-> (apply merge-with merge preferences (map #(hash-map % {"NPE" 0}) (keys preferences))) (assoc "NPE" (->> (keys preferences) (map #(vector % 0)) (into {}))) optimal-seating-score))) (comment ;; Part 1 (part-1 test-input) ; => 330 (part-1 task-input) ; => 709 ;; Part 2 (part-2 test-input) ; => 286 (part-2 task-input) ; => 668 )
29388
(ns aoc-2015.day-13 (:require [clojure.string :as string] [aoc-utils :as u])) ;; --- Day 13: Knights of the Dinner Table --- https://adventofcode.com/2015/day/13 (def task-input (u/slurp-resource "inputs/aoc_2015/day-13.txt")) (def test-input "<NAME> would gain 54 happiness units by sitting next to <NAME>.\n<NAME> would lose 79 happiness units by sitting next to <NAME>.\n<NAME> would lose 2 happiness units by sitting next to <NAME>.\n<NAME> would gain 83 happiness units by sitting next to <NAME>.\n<NAME> would lose 7 happiness units by sitting next to <NAME>.\n<NAME> would lose 63 happiness units by sitting next to <NAME>.\n<NAME> would lose 62 happiness units by sitting next to <NAME>.\n<NAME> would gain 60 happiness units by sitting next to <NAME>.\n<NAME> would gain 55 happiness units by sitting next to <NAME>.\n<NAME> would gain 46 happiness units by sitting next to <NAME>.\n<NAME> would lose 7 happiness units by sitting next to <NAME>.\n<NAME> would gain 41 happiness units by sitting next to <NAME>.") (defn parse-line [line] (let [[_ name op n name-2] (re-matches #"(\w+) would (gain|lose) (\d+) happiness units by sitting next to (\w+)\." line) n (parse-long n)] {name {name-2 (if (= op "gain") n (- n))}})) (defn parse-input [input] (->> (string/split-lines input) (map parse-line) (apply merge-with merge))) (defn calculate-happiness [preferences seating-order] (->> (conj (vec seating-order) (first seating-order)) (partition 2 1) (reduce #(+ %1 (get-in preferences %2) (get-in preferences (reverse %2))) 0))) (defn optimal-seating-score [preferences] (->> (keys preferences) u/permutations (map (partial calculate-happiness preferences)) (apply max))) (defn part-1 [input] (optimal-seating-score (parse-input input))) (defn part-2 [input] (let [preferences (parse-input input)] (-> (apply merge-with merge preferences (map #(hash-map % {"NPE" 0}) (keys preferences))) (assoc "NPE" (->> (keys preferences) (map #(vector % 0)) (into {}))) optimal-seating-score))) (comment ;; Part 1 (part-1 test-input) ; => 330 (part-1 task-input) ; => 709 ;; Part 2 (part-2 test-input) ; => 286 (part-2 task-input) ; => 668 )
true
(ns aoc-2015.day-13 (:require [clojure.string :as string] [aoc-utils :as u])) ;; --- Day 13: Knights of the Dinner Table --- https://adventofcode.com/2015/day/13 (def task-input (u/slurp-resource "inputs/aoc_2015/day-13.txt")) (def test-input "PI:NAME:<NAME>END_PI would gain 54 happiness units by sitting next to PI:NAME:<NAME>END_PI.\nPI:NAME:<NAME>END_PI would lose 79 happiness units by sitting next to PI:NAME:<NAME>END_PI.\nPI:NAME:<NAME>END_PI would lose 2 happiness units by sitting next to PI:NAME:<NAME>END_PI.\nPI:NAME:<NAME>END_PI would gain 83 happiness units by sitting next to PI:NAME:<NAME>END_PI.\nPI:NAME:<NAME>END_PI would lose 7 happiness units by sitting next to PI:NAME:<NAME>END_PI.\nPI:NAME:<NAME>END_PI would lose 63 happiness units by sitting next to PI:NAME:<NAME>END_PI.\nPI:NAME:<NAME>END_PI would lose 62 happiness units by sitting next to PI:NAME:<NAME>END_PI.\nPI:NAME:<NAME>END_PI would gain 60 happiness units by sitting next to PI:NAME:<NAME>END_PI.\nPI:NAME:<NAME>END_PI would gain 55 happiness units by sitting next to PI:NAME:<NAME>END_PI.\nPI:NAME:<NAME>END_PI would gain 46 happiness units by sitting next to PI:NAME:<NAME>END_PI.\nPI:NAME:<NAME>END_PI would lose 7 happiness units by sitting next to PI:NAME:<NAME>END_PI.\nPI:NAME:<NAME>END_PI would gain 41 happiness units by sitting next to PI:NAME:<NAME>END_PI.") (defn parse-line [line] (let [[_ name op n name-2] (re-matches #"(\w+) would (gain|lose) (\d+) happiness units by sitting next to (\w+)\." line) n (parse-long n)] {name {name-2 (if (= op "gain") n (- n))}})) (defn parse-input [input] (->> (string/split-lines input) (map parse-line) (apply merge-with merge))) (defn calculate-happiness [preferences seating-order] (->> (conj (vec seating-order) (first seating-order)) (partition 2 1) (reduce #(+ %1 (get-in preferences %2) (get-in preferences (reverse %2))) 0))) (defn optimal-seating-score [preferences] (->> (keys preferences) u/permutations (map (partial calculate-happiness preferences)) (apply max))) (defn part-1 [input] (optimal-seating-score (parse-input input))) (defn part-2 [input] (let [preferences (parse-input input)] (-> (apply merge-with merge preferences (map #(hash-map % {"NPE" 0}) (keys preferences))) (assoc "NPE" (->> (keys preferences) (map #(vector % 0)) (into {}))) optimal-seating-score))) (comment ;; Part 1 (part-1 test-input) ; => 330 (part-1 task-input) ; => 709 ;; Part 2 (part-2 test-input) ; => 286 (part-2 task-input) ; => 668 )
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 29, "score": 0.9998736381530762, "start": 18, "tag": "NAME", "value": "Rich Hickey" }, { "context": "tice, or any other, from this software.\n\n;;Author: Frantisek Sodomka\n\n(ns clojure.test-clojure.atoms\n (:use clojure.t", "end": 491, "score": 0.9998918771743774, "start": 474, "tag": "NAME", "value": "Frantisek Sodomka" } ]
Clojure/clojure/test_clojure/atoms.clj
AydarLukmanov/ArcadiaGodot
328
; Copyright (c) Rich Hickey. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. ;;Author: Frantisek Sodomka (ns clojure.test-clojure.atoms (:use clojure.test)) ; http://clojure.org/atoms ; atom ; deref, @-reader-macro ; swap! reset! ; compare-and-set! (deftest swap-vals-returns-old-value (let [a (atom 0)] (is (= [0 1] (swap-vals! a inc))) (is (= [1 2] (swap-vals! a inc))) (is (= 2 @a)))) (deftest deref-swap-arities (binding [*warn-on-reflection* true] (let [a (atom 0)] (is (= [0 1] (swap-vals! a + 1))) (is (= [1 3] (swap-vals! a + 1 1))) (is (= [3 6] (swap-vals! a + 1 1 1))) (is (= [6 10] (swap-vals! a + 1 1 1 1))) (is (= 10 @a))))) (deftest deref-reset-returns-old-value (let [a (atom 0)] (is (= [0 :b] (reset-vals! a :b))) (is (= [:b 45M] (reset-vals! a 45M))) (is (= 45M @a)))) (deftest reset-on-deref-reset-equality (let [a (atom :usual-value)] (is (= :usual-value (reset! a (first (reset-vals! a :almost-never-seen-value)))))))
40169
; Copyright (c) <NAME>. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. ;;Author: <NAME> (ns clojure.test-clojure.atoms (:use clojure.test)) ; http://clojure.org/atoms ; atom ; deref, @-reader-macro ; swap! reset! ; compare-and-set! (deftest swap-vals-returns-old-value (let [a (atom 0)] (is (= [0 1] (swap-vals! a inc))) (is (= [1 2] (swap-vals! a inc))) (is (= 2 @a)))) (deftest deref-swap-arities (binding [*warn-on-reflection* true] (let [a (atom 0)] (is (= [0 1] (swap-vals! a + 1))) (is (= [1 3] (swap-vals! a + 1 1))) (is (= [3 6] (swap-vals! a + 1 1 1))) (is (= [6 10] (swap-vals! a + 1 1 1 1))) (is (= 10 @a))))) (deftest deref-reset-returns-old-value (let [a (atom 0)] (is (= [0 :b] (reset-vals! a :b))) (is (= [:b 45M] (reset-vals! a 45M))) (is (= 45M @a)))) (deftest reset-on-deref-reset-equality (let [a (atom :usual-value)] (is (= :usual-value (reset! a (first (reset-vals! a :almost-never-seen-value)))))))
true
; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. ;;Author: PI:NAME:<NAME>END_PI (ns clojure.test-clojure.atoms (:use clojure.test)) ; http://clojure.org/atoms ; atom ; deref, @-reader-macro ; swap! reset! ; compare-and-set! (deftest swap-vals-returns-old-value (let [a (atom 0)] (is (= [0 1] (swap-vals! a inc))) (is (= [1 2] (swap-vals! a inc))) (is (= 2 @a)))) (deftest deref-swap-arities (binding [*warn-on-reflection* true] (let [a (atom 0)] (is (= [0 1] (swap-vals! a + 1))) (is (= [1 3] (swap-vals! a + 1 1))) (is (= [3 6] (swap-vals! a + 1 1 1))) (is (= [6 10] (swap-vals! a + 1 1 1 1))) (is (= 10 @a))))) (deftest deref-reset-returns-old-value (let [a (atom 0)] (is (= [0 :b] (reset-vals! a :b))) (is (= [:b 45M] (reset-vals! a 45M))) (is (= 45M @a)))) (deftest reset-on-deref-reset-equality (let [a (atom :usual-value)] (is (= :usual-value (reset! a (first (reset-vals! a :almost-never-seen-value)))))))
[ { "context": "ass))\n\n;; logic c/o tomash, cf https://github.com/UlanaXY/BowlOfSoup/pull/1\n(defn fullsize-asset-url [url]\n", "end": 569, "score": 0.9995539784431458, "start": 562, "tag": "USERNAME", "value": "UlanaXY" }, { "context": "en asset-id\n :let [in-key (format \"soup/%s/assets/%s/%s\" soup prefix asset-id)\n ", "end": 12492, "score": 0.5461463928222656, "start": 12491, "tag": "KEY", "value": "%" }, { "context": "d\n :let [in-key (format \"soup/%s/assets/%s/%s\" soup prefix asset-id)\n out-", "end": 12502, "score": 0.6578349471092224, "start": 12501, "tag": "KEY", "value": "%" }, { "context": " :let [in-key (format \"soup/%s/assets/%s/%s\" soup prefix asset-id)\n out-file", "end": 12506, "score": 0.5803323984146118, "start": 12504, "tag": "KEY", "value": "%s" } ]
src/soupscraper/core.clj
nathell/soupscraper
19
(ns soupscraper.core (:require [cheshire.core :as json] [clojure.core.async :as async] [clojure.java.io :as io] [clojure.string :as string] [clojure.tools.cli :as cli] [java-time] [skyscraper.cache :as cache] [skyscraper.core :as core :refer [defprocessor]] [skyscraper.context :as context] [taoensso.timbre :as log :refer [warnf]] [taoensso.timbre.appenders.core :as appenders]) (:gen-class)) ;; logic c/o tomash, cf https://github.com/UlanaXY/BowlOfSoup/pull/1 (defn fullsize-asset-url [url] (when url (if-let [[_ a b c ext] (re-find #"^https://asset.soup.io/asset/(\d+)/([0-9a-f]+)_([0-9a-f]+)_[0-9]+\.(.*)$" url)] (format "http://asset.soup.io/asset/%s/%s_%s.%s" a b c ext) (string/replace url "https://" "http://")))) (defn asset-info [type url] (let [url (fullsize-asset-url url) [_ prefix asset-id ext] (re-find #"^http://asset.soup.io/asset/(\d+)/([0-9a-f_]+)\.(.*)$" url)] {:type type :prefix prefix :asset-id asset-id :ext ext :url url :processor :asset})) (let [formatter (-> (java-time/formatter "MMM dd yyyy HH:mm:ss z") (.withLocale java.util.Locale/ENGLISH))] (defn parse-post-date [date] (try (java-time/java-date (java-time/instant formatter date)) (catch Exception e (warnf "Could not parse date: %s" date) nil)))) (defn parse-user-container [span] (or (reaver/text (reaver/select span ".name")) (reaver/attr (reaver/select span "a img") :title))) (defn parse-reaction [li] {:user (parse-user-container (reaver/select li ".toggle1 .user_container")) :link (reaver/attr (reaver/select li ".original_link") :href) :type (string/trim (reaver/text (reaver/select li ".toggle1 .info")))}) (defn parse-tag [a] (reaver/text a)) (defn parse-post [div] (if-let [content (reaver/select div ".content")] (let [imagebox (reaver/select content "a.lightbox") imagedirect (reaver/select content ".imagecontainer > img") body (reaver/select content ".body") cite (reaver/select content ".content > cite") description (reaver/select content ".description") h3 (reaver/select content ".content > h3") video (reaver/select content ".embed video") id (subs (reaver/attr div :id) 4) time (reaver/select div ".time > abbr") reactions (reaver/select div ".reactions li") reposts (reaver/select div ".reposted_by .user_container") tags (reaver/select div ".tags a") tv (reaver/select div ".post_video > .content-container .tv_promo") link (reaver/select div ".post_link > .content-container .content h3 a")] (merge {:id id :post div :date (when time (parse-post-date (reaver/attr time :title))) :reactions (mapv parse-reaction reactions) :reposts (mapv parse-user-container reposts) :tags (mapv parse-tag tags)} (cond tv {:type :video, :url (str "/tv/show?id=" id), :processor :tv} video (if-let [src-url (reaver/attr video :src)] (asset-info :video src-url) (do (warnf "[parse-post] no video src: %s" video) {:type :unable-to-parse, :post div})) link {:type :link, :link-title (reaver/text link), :link-url (reaver/attr link :href)} imagebox (asset-info :image (reaver/attr imagebox :href)) imagedirect (asset-info :image (reaver/attr imagedirect :src)) body {:type :text} :otherwise nil) (when h3 {:title (reaver/text h3)}) (when cite {:cite (.html cite)}) (when description {:content (.html description)}) (when body {:content (.html body)}) (when (reaver/select div ".ad-marker") {:sponsored true}))) (do (warnf "[parse-post] no content: %s", div) {:type :unable-to-parse, :post div}))) (def months ["January" "February" "March" "April" "May" "June" "July" "August" "September" "October" "November" "December"]) (defn yyyymmdd [h2] (format "%s-%02d-%s" (reaver/text (reaver/select h2 ".y")) (inc (.indexOf months (reaver/text (reaver/select h2 ".m")))) (reaver/text (reaver/select h2 ".d")))) (defn matches? [selector element] (and (instance? org.jsoup.nodes.Element element) (= (first (reaver/select element selector)) element))) (defn date->yyyy-mm-dd [date] (some-> date java-time/instant str (subs 0 10))) (defn propagate "Given a key `k` and a seq of maps `s`, goes through `s` and if an element doesn't contain `k`, assocs it to the last-seen value. (propagate :b [{:a 1 :b 2} {:a 2} {:a 3} {:a 4 :b 5}]) ;=> [{:a 1 :b 2} {:a 2 :b 2} {:a 3 :b 2} {:a 4 :b 5}]" [k [fst & rst :as s]] (loop [acc [fst] to-go rst seen? (contains? fst k) last-val (get fst k)] (if-not (seq to-go) acc (let [[fst & rst] to-go has? (contains? fst k)] (recur (conj acc (if (or has? (not seen?)) fst (assoc fst k last-val))) rst (or seen? (contains? fst k)) (if has? (get fst k) last-val)))))) (def as-far-as (atom nil)) (def total-assets (atom 0)) (defn matches? [selector element] (and (instance? org.jsoup.nodes.Element element) (= (first (reaver/select element selector)) element))) (defn parse-post-or-date [node] (condp matches? node "h2.date" {:date-from-header (yyyymmdd node)} "div.post" (parse-post node) nil)) (defn fixup-date [post] (if (:date post) post (assoc post :date (clojure.instant/read-instant-date (:date-from-header post))))) (defn parse-posts-and-dates [document] (when-let [nodes (some-> (reaver/select document "#first_batch") first .childNodes)] (->> nodes (map parse-post-or-date) (remove nil?) (propagate :date-from-header) (filter :type) (map fixup-date) (map-indexed #(assoc %2 :num-on-page (- %1)))))) (defn parse-json [headers body] (json/parse-string (core/parse-string headers body) true)) (defprocessor :soup :cache-template "soup/:soup/list/:since" :process-fn (fn [document {:keys [earliest pages-only] :as context}] (let [posts (parse-posts-and-dates document) earliest-on-page (->> posts (map :date) sort first date->yyyy-mm-dd) moar (-> (reaver/select document "#load_more a") (reaver/attr :href))] (when pages-only (swap! total-assets + (count (filter #(= (:processor %) :asset) posts)))) (swap! as-far-as #(or earliest-on-page %)) (concat (when (and moar (or (not earliest) (>= (compare earliest-on-page earliest) 0))) (let [since (second (re-find #"/since/(\d+)" moar))] [{:processor :soup, :since since, :url moar}])) (when-not pages-only posts))))) (defprocessor :tv :cache-template "soup/:soup/tv/:id" :parse-fn parse-json :process-fn (fn [document context] (try (let [[type id] (string/split (-> document first second) #":")] {:tv-type type, :tv-id id}) (catch Exception _ {:type :unable-to-parse, :tv-data document})))) (defprocessor :asset :cache-template "soup/:soup/assets/:prefix/:asset-id" :parse-fn (fn [headers body] body) :process-fn (fn [document context] {:downloaded true})) (defn download-error-handler [error options context] (let [{:keys [status]} (ex-data error) retry? (or (nil? status) (>= status 500) (= status 429))] (cond (= status 404) (do (warnf "[download] %s 404'd, dumping in empty file" (:url context)) (core/respond-with {:headers {"content-type" "text/plain"} :body (byte-array 0)} options context)) retry? (do (if (= status 429) (do (warnf "[download] Unexpected error %s, retrying after a nap" error) (Thread/sleep 5000)) (warnf "[download] Unexpected error %s, retrying" error)) [context]) :otherwise (do (warnf "[download] Unexpected error %s, giving up" error) (core/signal-error error context))))) (defn seed [{:keys [soup earliest pages-only]}] [{:url (format "https://%s.soup.io" soup), :soup soup, :since "latest", :processor :soup, :earliest earliest, :pages-only pages-only}]) (defn scrape-args [opts] [(seed opts) :parse-fn core/parse-reaver :parallelism 1 ;; :max-connections 1 :html-cache true :download-error-handler download-error-handler :sleep (:sleep opts) :http-options {:redirect-strategy :lax :as :byte-array :connection-timeout (:connection-timeout opts) :socket-timeout (:socket-timeout opts)} :item-chan (:item-chan opts)]) (defn scrape [opts] (apply core/scrape (scrape-args opts))) (defn scrape! [opts] (apply core/scrape! (scrape-args opts))) (def cli-options [["-e" "--earliest DATE" "Skip posts older than DATE, in YYYY-MM-DD format"] ["-o" "--output-dir DIRECTORY" "Save soup data in DIRECTORY" :default "soup"] [nil "--connection-timeout MS" "Connection timeout in milliseconds" :default 60000 :parse-fn #(Long/parseLong %) :validate [pos? "Must be a positive number"]] [nil "--socket-timeout MS" "Socket timeout in milliseconds" :default 60000 :parse-fn #(Long/parseLong %) :validate [pos? "Must be a positive number"]]]) (log/set-level! :info) (log/merge-config! {:appenders {:println {:enabled? false} :spit (appenders/spit-appender {:fname "log/skyscraper.log"})}}) ;; some touching of Skyscraper internals here; you're not supposed to understand this (defn pages-reporter [item-chan] (async/thread (loop [i 1] (when-let [items (async/<!! item-chan)] (let [item (first items)] (if (and item (= (::core/stage item) `core/split-handler)) (do (printf "\r%d pages fetched, going back as far as %s" i @as-far-as) (flush) (recur (inc i))) (recur i))))))) (defn assets-reporter [item-chan] (async/thread (loop [i 1] (when-let [items (async/<!! item-chan)] (let [item (first items)] (if (and item (= (::core/stage item) `core/split-handler) (= (:processor item) :asset)) (do (printf "\r%d/%d assets fetched" i @total-assets) (flush) (recur (inc i))) (recur i))))))) (defn print-usage [summary] (printf "Save your Soup from eternal damnation. Usage: clojure -A:run [options] soup-name-or-url OR: java -Djdk.tls.client.protocols=TLSv1,TLSv1.1,TLSv1.2 -jar soupscraper-0.1.0.jar [options] soup-name-or-url Options: %s" summary) (println)) (defn soup-data [orig-posts] (let [posts (->> orig-posts (sort-by (juxt :date :since :num-on-page) (comp - compare)) (map #(select-keys % [:asset-id :cite :content :date :ext :id :prefix :reactions :reposts :sponsored :tags :title :type :tv-id :tv-type :link-title :link-url])) distinct)] {:soup-name (-> orig-posts first :soup) :posts posts})) (defn generate-local-copy [{:keys [output-dir] :as opts} posts] (let [json-file (str output-dir "/soup.json") js-file (str output-dir "/soup.js") index-file (str output-dir "/index.html") cache (cache/fs core/html-cache-dir)] (io/make-parents (io/file json-file)) (println "Saving assets (this may take a while)...") (doseq [{:keys [soup asset-id prefix ext]} posts :when asset-id :let [in-key (format "soup/%s/assets/%s/%s" soup prefix asset-id) out-file (format "%s/assets/%s/%s.%s" output-dir prefix asset-id ext) {:keys [blob]} (cache/load-blob cache in-key)]] (io/make-parents out-file) (with-open [in (io/input-stream blob)] (with-open [out (io/output-stream out-file)] (io/copy in out)))) (println "Generating viewable soup...") (let [json (json/generate-string (soup-data posts))] (spit json-file json) (spit js-file (str "window.soup=" json)) (with-open [in (io/input-stream (io/resource "assets/index.html"))] (with-open [out (io/output-stream index-file)] (io/copy in out)))))) (defn download-soup [opts] (println "Downloading infiniscroll pages...") (let [item-chan (async/chan)] (pages-reporter item-chan) (scrape! (assoc opts :sleep 1000 :item-chan item-chan :pages-only true))) (println "\nDownloading assets...") (let [item-chan (async/chan)] (assets-reporter item-chan) (scrape! (assoc opts :item-chan item-chan))) (println "\nGenerating local copy...") (generate-local-copy opts (scrape opts))) (defn sanitize-soup [soup-name-or-url] (when soup-name-or-url (or (last (re-find #"^(https?://)?([^.]+)\.soup\.io" soup-name-or-url)) soup-name-or-url))) (defn validate-args [args] (let [{:keys [options arguments errors summary] :as res} (cli/parse-opts args cli-options) soup (sanitize-soup (first arguments))] (cond errors (println (string/join "\n" errors)) soup (assoc options :soup soup) :else (print-usage summary)))) (defn -main [& args] (println "This is Soupscraper v0.1.0") (when-let [opts (validate-args args)] (download-soup opts)) (System/exit 0))
43505
(ns soupscraper.core (:require [cheshire.core :as json] [clojure.core.async :as async] [clojure.java.io :as io] [clojure.string :as string] [clojure.tools.cli :as cli] [java-time] [skyscraper.cache :as cache] [skyscraper.core :as core :refer [defprocessor]] [skyscraper.context :as context] [taoensso.timbre :as log :refer [warnf]] [taoensso.timbre.appenders.core :as appenders]) (:gen-class)) ;; logic c/o tomash, cf https://github.com/UlanaXY/BowlOfSoup/pull/1 (defn fullsize-asset-url [url] (when url (if-let [[_ a b c ext] (re-find #"^https://asset.soup.io/asset/(\d+)/([0-9a-f]+)_([0-9a-f]+)_[0-9]+\.(.*)$" url)] (format "http://asset.soup.io/asset/%s/%s_%s.%s" a b c ext) (string/replace url "https://" "http://")))) (defn asset-info [type url] (let [url (fullsize-asset-url url) [_ prefix asset-id ext] (re-find #"^http://asset.soup.io/asset/(\d+)/([0-9a-f_]+)\.(.*)$" url)] {:type type :prefix prefix :asset-id asset-id :ext ext :url url :processor :asset})) (let [formatter (-> (java-time/formatter "MMM dd yyyy HH:mm:ss z") (.withLocale java.util.Locale/ENGLISH))] (defn parse-post-date [date] (try (java-time/java-date (java-time/instant formatter date)) (catch Exception e (warnf "Could not parse date: %s" date) nil)))) (defn parse-user-container [span] (or (reaver/text (reaver/select span ".name")) (reaver/attr (reaver/select span "a img") :title))) (defn parse-reaction [li] {:user (parse-user-container (reaver/select li ".toggle1 .user_container")) :link (reaver/attr (reaver/select li ".original_link") :href) :type (string/trim (reaver/text (reaver/select li ".toggle1 .info")))}) (defn parse-tag [a] (reaver/text a)) (defn parse-post [div] (if-let [content (reaver/select div ".content")] (let [imagebox (reaver/select content "a.lightbox") imagedirect (reaver/select content ".imagecontainer > img") body (reaver/select content ".body") cite (reaver/select content ".content > cite") description (reaver/select content ".description") h3 (reaver/select content ".content > h3") video (reaver/select content ".embed video") id (subs (reaver/attr div :id) 4) time (reaver/select div ".time > abbr") reactions (reaver/select div ".reactions li") reposts (reaver/select div ".reposted_by .user_container") tags (reaver/select div ".tags a") tv (reaver/select div ".post_video > .content-container .tv_promo") link (reaver/select div ".post_link > .content-container .content h3 a")] (merge {:id id :post div :date (when time (parse-post-date (reaver/attr time :title))) :reactions (mapv parse-reaction reactions) :reposts (mapv parse-user-container reposts) :tags (mapv parse-tag tags)} (cond tv {:type :video, :url (str "/tv/show?id=" id), :processor :tv} video (if-let [src-url (reaver/attr video :src)] (asset-info :video src-url) (do (warnf "[parse-post] no video src: %s" video) {:type :unable-to-parse, :post div})) link {:type :link, :link-title (reaver/text link), :link-url (reaver/attr link :href)} imagebox (asset-info :image (reaver/attr imagebox :href)) imagedirect (asset-info :image (reaver/attr imagedirect :src)) body {:type :text} :otherwise nil) (when h3 {:title (reaver/text h3)}) (when cite {:cite (.html cite)}) (when description {:content (.html description)}) (when body {:content (.html body)}) (when (reaver/select div ".ad-marker") {:sponsored true}))) (do (warnf "[parse-post] no content: %s", div) {:type :unable-to-parse, :post div}))) (def months ["January" "February" "March" "April" "May" "June" "July" "August" "September" "October" "November" "December"]) (defn yyyymmdd [h2] (format "%s-%02d-%s" (reaver/text (reaver/select h2 ".y")) (inc (.indexOf months (reaver/text (reaver/select h2 ".m")))) (reaver/text (reaver/select h2 ".d")))) (defn matches? [selector element] (and (instance? org.jsoup.nodes.Element element) (= (first (reaver/select element selector)) element))) (defn date->yyyy-mm-dd [date] (some-> date java-time/instant str (subs 0 10))) (defn propagate "Given a key `k` and a seq of maps `s`, goes through `s` and if an element doesn't contain `k`, assocs it to the last-seen value. (propagate :b [{:a 1 :b 2} {:a 2} {:a 3} {:a 4 :b 5}]) ;=> [{:a 1 :b 2} {:a 2 :b 2} {:a 3 :b 2} {:a 4 :b 5}]" [k [fst & rst :as s]] (loop [acc [fst] to-go rst seen? (contains? fst k) last-val (get fst k)] (if-not (seq to-go) acc (let [[fst & rst] to-go has? (contains? fst k)] (recur (conj acc (if (or has? (not seen?)) fst (assoc fst k last-val))) rst (or seen? (contains? fst k)) (if has? (get fst k) last-val)))))) (def as-far-as (atom nil)) (def total-assets (atom 0)) (defn matches? [selector element] (and (instance? org.jsoup.nodes.Element element) (= (first (reaver/select element selector)) element))) (defn parse-post-or-date [node] (condp matches? node "h2.date" {:date-from-header (yyyymmdd node)} "div.post" (parse-post node) nil)) (defn fixup-date [post] (if (:date post) post (assoc post :date (clojure.instant/read-instant-date (:date-from-header post))))) (defn parse-posts-and-dates [document] (when-let [nodes (some-> (reaver/select document "#first_batch") first .childNodes)] (->> nodes (map parse-post-or-date) (remove nil?) (propagate :date-from-header) (filter :type) (map fixup-date) (map-indexed #(assoc %2 :num-on-page (- %1)))))) (defn parse-json [headers body] (json/parse-string (core/parse-string headers body) true)) (defprocessor :soup :cache-template "soup/:soup/list/:since" :process-fn (fn [document {:keys [earliest pages-only] :as context}] (let [posts (parse-posts-and-dates document) earliest-on-page (->> posts (map :date) sort first date->yyyy-mm-dd) moar (-> (reaver/select document "#load_more a") (reaver/attr :href))] (when pages-only (swap! total-assets + (count (filter #(= (:processor %) :asset) posts)))) (swap! as-far-as #(or earliest-on-page %)) (concat (when (and moar (or (not earliest) (>= (compare earliest-on-page earliest) 0))) (let [since (second (re-find #"/since/(\d+)" moar))] [{:processor :soup, :since since, :url moar}])) (when-not pages-only posts))))) (defprocessor :tv :cache-template "soup/:soup/tv/:id" :parse-fn parse-json :process-fn (fn [document context] (try (let [[type id] (string/split (-> document first second) #":")] {:tv-type type, :tv-id id}) (catch Exception _ {:type :unable-to-parse, :tv-data document})))) (defprocessor :asset :cache-template "soup/:soup/assets/:prefix/:asset-id" :parse-fn (fn [headers body] body) :process-fn (fn [document context] {:downloaded true})) (defn download-error-handler [error options context] (let [{:keys [status]} (ex-data error) retry? (or (nil? status) (>= status 500) (= status 429))] (cond (= status 404) (do (warnf "[download] %s 404'd, dumping in empty file" (:url context)) (core/respond-with {:headers {"content-type" "text/plain"} :body (byte-array 0)} options context)) retry? (do (if (= status 429) (do (warnf "[download] Unexpected error %s, retrying after a nap" error) (Thread/sleep 5000)) (warnf "[download] Unexpected error %s, retrying" error)) [context]) :otherwise (do (warnf "[download] Unexpected error %s, giving up" error) (core/signal-error error context))))) (defn seed [{:keys [soup earliest pages-only]}] [{:url (format "https://%s.soup.io" soup), :soup soup, :since "latest", :processor :soup, :earliest earliest, :pages-only pages-only}]) (defn scrape-args [opts] [(seed opts) :parse-fn core/parse-reaver :parallelism 1 ;; :max-connections 1 :html-cache true :download-error-handler download-error-handler :sleep (:sleep opts) :http-options {:redirect-strategy :lax :as :byte-array :connection-timeout (:connection-timeout opts) :socket-timeout (:socket-timeout opts)} :item-chan (:item-chan opts)]) (defn scrape [opts] (apply core/scrape (scrape-args opts))) (defn scrape! [opts] (apply core/scrape! (scrape-args opts))) (def cli-options [["-e" "--earliest DATE" "Skip posts older than DATE, in YYYY-MM-DD format"] ["-o" "--output-dir DIRECTORY" "Save soup data in DIRECTORY" :default "soup"] [nil "--connection-timeout MS" "Connection timeout in milliseconds" :default 60000 :parse-fn #(Long/parseLong %) :validate [pos? "Must be a positive number"]] [nil "--socket-timeout MS" "Socket timeout in milliseconds" :default 60000 :parse-fn #(Long/parseLong %) :validate [pos? "Must be a positive number"]]]) (log/set-level! :info) (log/merge-config! {:appenders {:println {:enabled? false} :spit (appenders/spit-appender {:fname "log/skyscraper.log"})}}) ;; some touching of Skyscraper internals here; you're not supposed to understand this (defn pages-reporter [item-chan] (async/thread (loop [i 1] (when-let [items (async/<!! item-chan)] (let [item (first items)] (if (and item (= (::core/stage item) `core/split-handler)) (do (printf "\r%d pages fetched, going back as far as %s" i @as-far-as) (flush) (recur (inc i))) (recur i))))))) (defn assets-reporter [item-chan] (async/thread (loop [i 1] (when-let [items (async/<!! item-chan)] (let [item (first items)] (if (and item (= (::core/stage item) `core/split-handler) (= (:processor item) :asset)) (do (printf "\r%d/%d assets fetched" i @total-assets) (flush) (recur (inc i))) (recur i))))))) (defn print-usage [summary] (printf "Save your Soup from eternal damnation. Usage: clojure -A:run [options] soup-name-or-url OR: java -Djdk.tls.client.protocols=TLSv1,TLSv1.1,TLSv1.2 -jar soupscraper-0.1.0.jar [options] soup-name-or-url Options: %s" summary) (println)) (defn soup-data [orig-posts] (let [posts (->> orig-posts (sort-by (juxt :date :since :num-on-page) (comp - compare)) (map #(select-keys % [:asset-id :cite :content :date :ext :id :prefix :reactions :reposts :sponsored :tags :title :type :tv-id :tv-type :link-title :link-url])) distinct)] {:soup-name (-> orig-posts first :soup) :posts posts})) (defn generate-local-copy [{:keys [output-dir] :as opts} posts] (let [json-file (str output-dir "/soup.json") js-file (str output-dir "/soup.js") index-file (str output-dir "/index.html") cache (cache/fs core/html-cache-dir)] (io/make-parents (io/file json-file)) (println "Saving assets (this may take a while)...") (doseq [{:keys [soup asset-id prefix ext]} posts :when asset-id :let [in-key (format "soup/<KEY>s/assets/<KEY>s/<KEY>" soup prefix asset-id) out-file (format "%s/assets/%s/%s.%s" output-dir prefix asset-id ext) {:keys [blob]} (cache/load-blob cache in-key)]] (io/make-parents out-file) (with-open [in (io/input-stream blob)] (with-open [out (io/output-stream out-file)] (io/copy in out)))) (println "Generating viewable soup...") (let [json (json/generate-string (soup-data posts))] (spit json-file json) (spit js-file (str "window.soup=" json)) (with-open [in (io/input-stream (io/resource "assets/index.html"))] (with-open [out (io/output-stream index-file)] (io/copy in out)))))) (defn download-soup [opts] (println "Downloading infiniscroll pages...") (let [item-chan (async/chan)] (pages-reporter item-chan) (scrape! (assoc opts :sleep 1000 :item-chan item-chan :pages-only true))) (println "\nDownloading assets...") (let [item-chan (async/chan)] (assets-reporter item-chan) (scrape! (assoc opts :item-chan item-chan))) (println "\nGenerating local copy...") (generate-local-copy opts (scrape opts))) (defn sanitize-soup [soup-name-or-url] (when soup-name-or-url (or (last (re-find #"^(https?://)?([^.]+)\.soup\.io" soup-name-or-url)) soup-name-or-url))) (defn validate-args [args] (let [{:keys [options arguments errors summary] :as res} (cli/parse-opts args cli-options) soup (sanitize-soup (first arguments))] (cond errors (println (string/join "\n" errors)) soup (assoc options :soup soup) :else (print-usage summary)))) (defn -main [& args] (println "This is Soupscraper v0.1.0") (when-let [opts (validate-args args)] (download-soup opts)) (System/exit 0))
true
(ns soupscraper.core (:require [cheshire.core :as json] [clojure.core.async :as async] [clojure.java.io :as io] [clojure.string :as string] [clojure.tools.cli :as cli] [java-time] [skyscraper.cache :as cache] [skyscraper.core :as core :refer [defprocessor]] [skyscraper.context :as context] [taoensso.timbre :as log :refer [warnf]] [taoensso.timbre.appenders.core :as appenders]) (:gen-class)) ;; logic c/o tomash, cf https://github.com/UlanaXY/BowlOfSoup/pull/1 (defn fullsize-asset-url [url] (when url (if-let [[_ a b c ext] (re-find #"^https://asset.soup.io/asset/(\d+)/([0-9a-f]+)_([0-9a-f]+)_[0-9]+\.(.*)$" url)] (format "http://asset.soup.io/asset/%s/%s_%s.%s" a b c ext) (string/replace url "https://" "http://")))) (defn asset-info [type url] (let [url (fullsize-asset-url url) [_ prefix asset-id ext] (re-find #"^http://asset.soup.io/asset/(\d+)/([0-9a-f_]+)\.(.*)$" url)] {:type type :prefix prefix :asset-id asset-id :ext ext :url url :processor :asset})) (let [formatter (-> (java-time/formatter "MMM dd yyyy HH:mm:ss z") (.withLocale java.util.Locale/ENGLISH))] (defn parse-post-date [date] (try (java-time/java-date (java-time/instant formatter date)) (catch Exception e (warnf "Could not parse date: %s" date) nil)))) (defn parse-user-container [span] (or (reaver/text (reaver/select span ".name")) (reaver/attr (reaver/select span "a img") :title))) (defn parse-reaction [li] {:user (parse-user-container (reaver/select li ".toggle1 .user_container")) :link (reaver/attr (reaver/select li ".original_link") :href) :type (string/trim (reaver/text (reaver/select li ".toggle1 .info")))}) (defn parse-tag [a] (reaver/text a)) (defn parse-post [div] (if-let [content (reaver/select div ".content")] (let [imagebox (reaver/select content "a.lightbox") imagedirect (reaver/select content ".imagecontainer > img") body (reaver/select content ".body") cite (reaver/select content ".content > cite") description (reaver/select content ".description") h3 (reaver/select content ".content > h3") video (reaver/select content ".embed video") id (subs (reaver/attr div :id) 4) time (reaver/select div ".time > abbr") reactions (reaver/select div ".reactions li") reposts (reaver/select div ".reposted_by .user_container") tags (reaver/select div ".tags a") tv (reaver/select div ".post_video > .content-container .tv_promo") link (reaver/select div ".post_link > .content-container .content h3 a")] (merge {:id id :post div :date (when time (parse-post-date (reaver/attr time :title))) :reactions (mapv parse-reaction reactions) :reposts (mapv parse-user-container reposts) :tags (mapv parse-tag tags)} (cond tv {:type :video, :url (str "/tv/show?id=" id), :processor :tv} video (if-let [src-url (reaver/attr video :src)] (asset-info :video src-url) (do (warnf "[parse-post] no video src: %s" video) {:type :unable-to-parse, :post div})) link {:type :link, :link-title (reaver/text link), :link-url (reaver/attr link :href)} imagebox (asset-info :image (reaver/attr imagebox :href)) imagedirect (asset-info :image (reaver/attr imagedirect :src)) body {:type :text} :otherwise nil) (when h3 {:title (reaver/text h3)}) (when cite {:cite (.html cite)}) (when description {:content (.html description)}) (when body {:content (.html body)}) (when (reaver/select div ".ad-marker") {:sponsored true}))) (do (warnf "[parse-post] no content: %s", div) {:type :unable-to-parse, :post div}))) (def months ["January" "February" "March" "April" "May" "June" "July" "August" "September" "October" "November" "December"]) (defn yyyymmdd [h2] (format "%s-%02d-%s" (reaver/text (reaver/select h2 ".y")) (inc (.indexOf months (reaver/text (reaver/select h2 ".m")))) (reaver/text (reaver/select h2 ".d")))) (defn matches? [selector element] (and (instance? org.jsoup.nodes.Element element) (= (first (reaver/select element selector)) element))) (defn date->yyyy-mm-dd [date] (some-> date java-time/instant str (subs 0 10))) (defn propagate "Given a key `k` and a seq of maps `s`, goes through `s` and if an element doesn't contain `k`, assocs it to the last-seen value. (propagate :b [{:a 1 :b 2} {:a 2} {:a 3} {:a 4 :b 5}]) ;=> [{:a 1 :b 2} {:a 2 :b 2} {:a 3 :b 2} {:a 4 :b 5}]" [k [fst & rst :as s]] (loop [acc [fst] to-go rst seen? (contains? fst k) last-val (get fst k)] (if-not (seq to-go) acc (let [[fst & rst] to-go has? (contains? fst k)] (recur (conj acc (if (or has? (not seen?)) fst (assoc fst k last-val))) rst (or seen? (contains? fst k)) (if has? (get fst k) last-val)))))) (def as-far-as (atom nil)) (def total-assets (atom 0)) (defn matches? [selector element] (and (instance? org.jsoup.nodes.Element element) (= (first (reaver/select element selector)) element))) (defn parse-post-or-date [node] (condp matches? node "h2.date" {:date-from-header (yyyymmdd node)} "div.post" (parse-post node) nil)) (defn fixup-date [post] (if (:date post) post (assoc post :date (clojure.instant/read-instant-date (:date-from-header post))))) (defn parse-posts-and-dates [document] (when-let [nodes (some-> (reaver/select document "#first_batch") first .childNodes)] (->> nodes (map parse-post-or-date) (remove nil?) (propagate :date-from-header) (filter :type) (map fixup-date) (map-indexed #(assoc %2 :num-on-page (- %1)))))) (defn parse-json [headers body] (json/parse-string (core/parse-string headers body) true)) (defprocessor :soup :cache-template "soup/:soup/list/:since" :process-fn (fn [document {:keys [earliest pages-only] :as context}] (let [posts (parse-posts-and-dates document) earliest-on-page (->> posts (map :date) sort first date->yyyy-mm-dd) moar (-> (reaver/select document "#load_more a") (reaver/attr :href))] (when pages-only (swap! total-assets + (count (filter #(= (:processor %) :asset) posts)))) (swap! as-far-as #(or earliest-on-page %)) (concat (when (and moar (or (not earliest) (>= (compare earliest-on-page earliest) 0))) (let [since (second (re-find #"/since/(\d+)" moar))] [{:processor :soup, :since since, :url moar}])) (when-not pages-only posts))))) (defprocessor :tv :cache-template "soup/:soup/tv/:id" :parse-fn parse-json :process-fn (fn [document context] (try (let [[type id] (string/split (-> document first second) #":")] {:tv-type type, :tv-id id}) (catch Exception _ {:type :unable-to-parse, :tv-data document})))) (defprocessor :asset :cache-template "soup/:soup/assets/:prefix/:asset-id" :parse-fn (fn [headers body] body) :process-fn (fn [document context] {:downloaded true})) (defn download-error-handler [error options context] (let [{:keys [status]} (ex-data error) retry? (or (nil? status) (>= status 500) (= status 429))] (cond (= status 404) (do (warnf "[download] %s 404'd, dumping in empty file" (:url context)) (core/respond-with {:headers {"content-type" "text/plain"} :body (byte-array 0)} options context)) retry? (do (if (= status 429) (do (warnf "[download] Unexpected error %s, retrying after a nap" error) (Thread/sleep 5000)) (warnf "[download] Unexpected error %s, retrying" error)) [context]) :otherwise (do (warnf "[download] Unexpected error %s, giving up" error) (core/signal-error error context))))) (defn seed [{:keys [soup earliest pages-only]}] [{:url (format "https://%s.soup.io" soup), :soup soup, :since "latest", :processor :soup, :earliest earliest, :pages-only pages-only}]) (defn scrape-args [opts] [(seed opts) :parse-fn core/parse-reaver :parallelism 1 ;; :max-connections 1 :html-cache true :download-error-handler download-error-handler :sleep (:sleep opts) :http-options {:redirect-strategy :lax :as :byte-array :connection-timeout (:connection-timeout opts) :socket-timeout (:socket-timeout opts)} :item-chan (:item-chan opts)]) (defn scrape [opts] (apply core/scrape (scrape-args opts))) (defn scrape! [opts] (apply core/scrape! (scrape-args opts))) (def cli-options [["-e" "--earliest DATE" "Skip posts older than DATE, in YYYY-MM-DD format"] ["-o" "--output-dir DIRECTORY" "Save soup data in DIRECTORY" :default "soup"] [nil "--connection-timeout MS" "Connection timeout in milliseconds" :default 60000 :parse-fn #(Long/parseLong %) :validate [pos? "Must be a positive number"]] [nil "--socket-timeout MS" "Socket timeout in milliseconds" :default 60000 :parse-fn #(Long/parseLong %) :validate [pos? "Must be a positive number"]]]) (log/set-level! :info) (log/merge-config! {:appenders {:println {:enabled? false} :spit (appenders/spit-appender {:fname "log/skyscraper.log"})}}) ;; some touching of Skyscraper internals here; you're not supposed to understand this (defn pages-reporter [item-chan] (async/thread (loop [i 1] (when-let [items (async/<!! item-chan)] (let [item (first items)] (if (and item (= (::core/stage item) `core/split-handler)) (do (printf "\r%d pages fetched, going back as far as %s" i @as-far-as) (flush) (recur (inc i))) (recur i))))))) (defn assets-reporter [item-chan] (async/thread (loop [i 1] (when-let [items (async/<!! item-chan)] (let [item (first items)] (if (and item (= (::core/stage item) `core/split-handler) (= (:processor item) :asset)) (do (printf "\r%d/%d assets fetched" i @total-assets) (flush) (recur (inc i))) (recur i))))))) (defn print-usage [summary] (printf "Save your Soup from eternal damnation. Usage: clojure -A:run [options] soup-name-or-url OR: java -Djdk.tls.client.protocols=TLSv1,TLSv1.1,TLSv1.2 -jar soupscraper-0.1.0.jar [options] soup-name-or-url Options: %s" summary) (println)) (defn soup-data [orig-posts] (let [posts (->> orig-posts (sort-by (juxt :date :since :num-on-page) (comp - compare)) (map #(select-keys % [:asset-id :cite :content :date :ext :id :prefix :reactions :reposts :sponsored :tags :title :type :tv-id :tv-type :link-title :link-url])) distinct)] {:soup-name (-> orig-posts first :soup) :posts posts})) (defn generate-local-copy [{:keys [output-dir] :as opts} posts] (let [json-file (str output-dir "/soup.json") js-file (str output-dir "/soup.js") index-file (str output-dir "/index.html") cache (cache/fs core/html-cache-dir)] (io/make-parents (io/file json-file)) (println "Saving assets (this may take a while)...") (doseq [{:keys [soup asset-id prefix ext]} posts :when asset-id :let [in-key (format "soup/PI:KEY:<KEY>END_PIs/assets/PI:KEY:<KEY>END_PIs/PI:KEY:<KEY>END_PI" soup prefix asset-id) out-file (format "%s/assets/%s/%s.%s" output-dir prefix asset-id ext) {:keys [blob]} (cache/load-blob cache in-key)]] (io/make-parents out-file) (with-open [in (io/input-stream blob)] (with-open [out (io/output-stream out-file)] (io/copy in out)))) (println "Generating viewable soup...") (let [json (json/generate-string (soup-data posts))] (spit json-file json) (spit js-file (str "window.soup=" json)) (with-open [in (io/input-stream (io/resource "assets/index.html"))] (with-open [out (io/output-stream index-file)] (io/copy in out)))))) (defn download-soup [opts] (println "Downloading infiniscroll pages...") (let [item-chan (async/chan)] (pages-reporter item-chan) (scrape! (assoc opts :sleep 1000 :item-chan item-chan :pages-only true))) (println "\nDownloading assets...") (let [item-chan (async/chan)] (assets-reporter item-chan) (scrape! (assoc opts :item-chan item-chan))) (println "\nGenerating local copy...") (generate-local-copy opts (scrape opts))) (defn sanitize-soup [soup-name-or-url] (when soup-name-or-url (or (last (re-find #"^(https?://)?([^.]+)\.soup\.io" soup-name-or-url)) soup-name-or-url))) (defn validate-args [args] (let [{:keys [options arguments errors summary] :as res} (cli/parse-opts args cli-options) soup (sanitize-soup (first arguments))] (cond errors (println (string/join "\n" errors)) soup (assoc options :soup soup) :else (print-usage summary)))) (defn -main [& args] (println "This is Soupscraper v0.1.0") (when-let [opts (validate-args args)] (download-soup opts)) (System/exit 0))
[ { "context": "h `token` keyword instead.\n\n (split-on-token \\\"ABxCxD\\\" \\\"x\\\" :x) ;; -> [\\\"AB\\\" :x \\\"CxD\\\"]\"\n [^String", "end": 775, "score": 0.7684056758880615, "start": 769, "tag": "KEY", "value": "ABxCxD" } ]
c#-metabase/src/metabase/driver/common/parameters/parse.clj
hanakhry/Crime_Admin
0
(ns metabase.driver.common.parameters.parse (:require [clojure.string :as str] [clojure.tools.logging :as log] [metabase.driver.common.parameters :as i] [metabase.query-processor.error-type :as error-type] [metabase.util :as u] [metabase.util.i18n :refer [tru]] [schema.core :as s]) (:import [metabase.driver.common.parameters Optional Param])) (def ^:private StringOrToken (s/cond-pre s/Str (s/enum :optional-begin :param-begin :optional-end :param-end))) (def ^:private ParsedToken (s/cond-pre s/Str Param Optional)) (defn- split-on-token-string "Split string `s` once when substring `token-str` is encountered; replace `token-str` with `token` keyword instead. (split-on-token \"ABxCxD\" \"x\" :x) ;; -> [\"AB\" :x \"CxD\"]" [^String s token-str token] (when-let [index (str/index-of s token-str)] (let [before (.substring s 0 index) after (.substring s (+ index (count token-str)) (count s))] [before token after]))) (defn- split-on-token-pattern "Like `split-on-token-string`, but splits on a regular expression instead, replacing the matched group with `token`. The pattern match an entire query, and return 3 groups — everything before the match; the match itself; and everything after the match." [s re token] (when-let [[_ before _ after] (re-matches re s)] [before token after])) (defn- split-on-token [s token-str token] ((if (string? token-str) split-on-token-string split-on-token-pattern) s token-str token)) (defn- tokenize-one [s token-str token] (loop [acc [], s s] (if (empty? s) acc (if-let [[before token after] (split-on-token s token-str token)] (recur (into acc [before token]) after) (conj acc s))))) (s/defn ^:private tokenize :- [StringOrToken] [s :- s/Str] (reduce (fn [strs [token-str token]] (filter (some-fn keyword? seq) (mapcat (fn [s] (if-not (string? s) [s] (tokenize-one s token-str token))) strs))) [s] [["[[" :optional-begin] ["]]" :optional-end] ;; param-begin should only match the last two opening brackets in a sequence of > 2, e.g. ;; [{$match: {{{x}}, field: 1}}] should parse to ["[$match: {" (param "x") ", field: 1}}]"] [#"(?s)(.*?)(\{\{(?!\{))(.*)" :param-begin] ["}}" :param-end]])) (defn- param [& [k & more]] (when (or (seq more) (not (string? k))) (throw (ex-info (tru "Invalid '{{...}}' clause: expected a param name") {:type error-type/invalid-query}))) (let [k (str/trim k)] (when (empty? k) (throw (ex-info (tru "'{{...}}' clauses cannot be empty.") {:type error-type/invalid-query}))) (i/->Param k))) (defn- optional [& parsed] (when-not (some i/Param? parsed) (throw (ex-info (tru "'[[...]]' clauses must contain at least one '{{...}}' clause.") {:type error-type/invalid-query}))) (i/->Optional parsed)) (s/defn ^:private parse-tokens* :- [(s/one [ParsedToken] "parsed tokens") (s/one [StringOrToken] "remaining tokens")] [tokens :- [StringOrToken], level :- s/Int] (loop [acc [], [token & more] tokens] (condp = token nil (if (pos? level) (throw (ex-info (tru "Invalid query: found '[[' or '{{' with no matching ']]' or '}}'") {:type error-type/invalid-query})) [acc nil]) :optional-begin (let [[parsed more] (parse-tokens* more (inc level))] (recur (conj acc (apply optional parsed)) more)) :param-begin (let [[parsed more] (parse-tokens* more (inc level))] (recur (conj acc (apply param parsed)) more)) :optional-end (if (pos? level) [acc more] [(conj acc "]]" more)]) :param-end (if (pos? level) [acc more] [(conj acc "}}") more]) (recur (conj acc token) more)))) (s/defn ^:private parse-tokens :- [ParsedToken] [tokens :- [StringOrToken]] (let [[parsed remaining] (parse-tokens* tokens 0) parsed (concat parsed (when (seq remaining) (parse-tokens remaining)))] ;; now loop over everything in `parsed`, and if we see 2 strings next to each other put them back together ;; e.g. [:token "x" "}}"] -> [:token "x}}"] (loop [acc [], last (first parsed), [x & more] (rest parsed)] (cond (not x) (conj acc last) (and (string? last) (string? x)) (recur acc (str last x) more) :else (recur (conj acc last) x more))))) (s/defn parse :- [(s/cond-pre s/Str Param Optional)] "Attempts to parse parameters in string `s`. Parses any optional clauses or parameters found, and returns a sequence of non-parameter string fragments (possibly) interposed with `Param` or `Optional` instances." [s :- s/Str] (let [tokenized (tokenize s)] (if (= [s] tokenized) [s] (do (log/tracef "Tokenized native query ->\n%s" (u/pprint-to-str tokenized)) (u/prog1 (parse-tokens tokenized) (log/tracef "Parsed native query ->\n%s" (u/pprint-to-str <>)))))))
27303
(ns metabase.driver.common.parameters.parse (:require [clojure.string :as str] [clojure.tools.logging :as log] [metabase.driver.common.parameters :as i] [metabase.query-processor.error-type :as error-type] [metabase.util :as u] [metabase.util.i18n :refer [tru]] [schema.core :as s]) (:import [metabase.driver.common.parameters Optional Param])) (def ^:private StringOrToken (s/cond-pre s/Str (s/enum :optional-begin :param-begin :optional-end :param-end))) (def ^:private ParsedToken (s/cond-pre s/Str Param Optional)) (defn- split-on-token-string "Split string `s` once when substring `token-str` is encountered; replace `token-str` with `token` keyword instead. (split-on-token \"<KEY>\" \"x\" :x) ;; -> [\"AB\" :x \"CxD\"]" [^String s token-str token] (when-let [index (str/index-of s token-str)] (let [before (.substring s 0 index) after (.substring s (+ index (count token-str)) (count s))] [before token after]))) (defn- split-on-token-pattern "Like `split-on-token-string`, but splits on a regular expression instead, replacing the matched group with `token`. The pattern match an entire query, and return 3 groups — everything before the match; the match itself; and everything after the match." [s re token] (when-let [[_ before _ after] (re-matches re s)] [before token after])) (defn- split-on-token [s token-str token] ((if (string? token-str) split-on-token-string split-on-token-pattern) s token-str token)) (defn- tokenize-one [s token-str token] (loop [acc [], s s] (if (empty? s) acc (if-let [[before token after] (split-on-token s token-str token)] (recur (into acc [before token]) after) (conj acc s))))) (s/defn ^:private tokenize :- [StringOrToken] [s :- s/Str] (reduce (fn [strs [token-str token]] (filter (some-fn keyword? seq) (mapcat (fn [s] (if-not (string? s) [s] (tokenize-one s token-str token))) strs))) [s] [["[[" :optional-begin] ["]]" :optional-end] ;; param-begin should only match the last two opening brackets in a sequence of > 2, e.g. ;; [{$match: {{{x}}, field: 1}}] should parse to ["[$match: {" (param "x") ", field: 1}}]"] [#"(?s)(.*?)(\{\{(?!\{))(.*)" :param-begin] ["}}" :param-end]])) (defn- param [& [k & more]] (when (or (seq more) (not (string? k))) (throw (ex-info (tru "Invalid '{{...}}' clause: expected a param name") {:type error-type/invalid-query}))) (let [k (str/trim k)] (when (empty? k) (throw (ex-info (tru "'{{...}}' clauses cannot be empty.") {:type error-type/invalid-query}))) (i/->Param k))) (defn- optional [& parsed] (when-not (some i/Param? parsed) (throw (ex-info (tru "'[[...]]' clauses must contain at least one '{{...}}' clause.") {:type error-type/invalid-query}))) (i/->Optional parsed)) (s/defn ^:private parse-tokens* :- [(s/one [ParsedToken] "parsed tokens") (s/one [StringOrToken] "remaining tokens")] [tokens :- [StringOrToken], level :- s/Int] (loop [acc [], [token & more] tokens] (condp = token nil (if (pos? level) (throw (ex-info (tru "Invalid query: found '[[' or '{{' with no matching ']]' or '}}'") {:type error-type/invalid-query})) [acc nil]) :optional-begin (let [[parsed more] (parse-tokens* more (inc level))] (recur (conj acc (apply optional parsed)) more)) :param-begin (let [[parsed more] (parse-tokens* more (inc level))] (recur (conj acc (apply param parsed)) more)) :optional-end (if (pos? level) [acc more] [(conj acc "]]" more)]) :param-end (if (pos? level) [acc more] [(conj acc "}}") more]) (recur (conj acc token) more)))) (s/defn ^:private parse-tokens :- [ParsedToken] [tokens :- [StringOrToken]] (let [[parsed remaining] (parse-tokens* tokens 0) parsed (concat parsed (when (seq remaining) (parse-tokens remaining)))] ;; now loop over everything in `parsed`, and if we see 2 strings next to each other put them back together ;; e.g. [:token "x" "}}"] -> [:token "x}}"] (loop [acc [], last (first parsed), [x & more] (rest parsed)] (cond (not x) (conj acc last) (and (string? last) (string? x)) (recur acc (str last x) more) :else (recur (conj acc last) x more))))) (s/defn parse :- [(s/cond-pre s/Str Param Optional)] "Attempts to parse parameters in string `s`. Parses any optional clauses or parameters found, and returns a sequence of non-parameter string fragments (possibly) interposed with `Param` or `Optional` instances." [s :- s/Str] (let [tokenized (tokenize s)] (if (= [s] tokenized) [s] (do (log/tracef "Tokenized native query ->\n%s" (u/pprint-to-str tokenized)) (u/prog1 (parse-tokens tokenized) (log/tracef "Parsed native query ->\n%s" (u/pprint-to-str <>)))))))
true
(ns metabase.driver.common.parameters.parse (:require [clojure.string :as str] [clojure.tools.logging :as log] [metabase.driver.common.parameters :as i] [metabase.query-processor.error-type :as error-type] [metabase.util :as u] [metabase.util.i18n :refer [tru]] [schema.core :as s]) (:import [metabase.driver.common.parameters Optional Param])) (def ^:private StringOrToken (s/cond-pre s/Str (s/enum :optional-begin :param-begin :optional-end :param-end))) (def ^:private ParsedToken (s/cond-pre s/Str Param Optional)) (defn- split-on-token-string "Split string `s` once when substring `token-str` is encountered; replace `token-str` with `token` keyword instead. (split-on-token \"PI:KEY:<KEY>END_PI\" \"x\" :x) ;; -> [\"AB\" :x \"CxD\"]" [^String s token-str token] (when-let [index (str/index-of s token-str)] (let [before (.substring s 0 index) after (.substring s (+ index (count token-str)) (count s))] [before token after]))) (defn- split-on-token-pattern "Like `split-on-token-string`, but splits on a regular expression instead, replacing the matched group with `token`. The pattern match an entire query, and return 3 groups — everything before the match; the match itself; and everything after the match." [s re token] (when-let [[_ before _ after] (re-matches re s)] [before token after])) (defn- split-on-token [s token-str token] ((if (string? token-str) split-on-token-string split-on-token-pattern) s token-str token)) (defn- tokenize-one [s token-str token] (loop [acc [], s s] (if (empty? s) acc (if-let [[before token after] (split-on-token s token-str token)] (recur (into acc [before token]) after) (conj acc s))))) (s/defn ^:private tokenize :- [StringOrToken] [s :- s/Str] (reduce (fn [strs [token-str token]] (filter (some-fn keyword? seq) (mapcat (fn [s] (if-not (string? s) [s] (tokenize-one s token-str token))) strs))) [s] [["[[" :optional-begin] ["]]" :optional-end] ;; param-begin should only match the last two opening brackets in a sequence of > 2, e.g. ;; [{$match: {{{x}}, field: 1}}] should parse to ["[$match: {" (param "x") ", field: 1}}]"] [#"(?s)(.*?)(\{\{(?!\{))(.*)" :param-begin] ["}}" :param-end]])) (defn- param [& [k & more]] (when (or (seq more) (not (string? k))) (throw (ex-info (tru "Invalid '{{...}}' clause: expected a param name") {:type error-type/invalid-query}))) (let [k (str/trim k)] (when (empty? k) (throw (ex-info (tru "'{{...}}' clauses cannot be empty.") {:type error-type/invalid-query}))) (i/->Param k))) (defn- optional [& parsed] (when-not (some i/Param? parsed) (throw (ex-info (tru "'[[...]]' clauses must contain at least one '{{...}}' clause.") {:type error-type/invalid-query}))) (i/->Optional parsed)) (s/defn ^:private parse-tokens* :- [(s/one [ParsedToken] "parsed tokens") (s/one [StringOrToken] "remaining tokens")] [tokens :- [StringOrToken], level :- s/Int] (loop [acc [], [token & more] tokens] (condp = token nil (if (pos? level) (throw (ex-info (tru "Invalid query: found '[[' or '{{' with no matching ']]' or '}}'") {:type error-type/invalid-query})) [acc nil]) :optional-begin (let [[parsed more] (parse-tokens* more (inc level))] (recur (conj acc (apply optional parsed)) more)) :param-begin (let [[parsed more] (parse-tokens* more (inc level))] (recur (conj acc (apply param parsed)) more)) :optional-end (if (pos? level) [acc more] [(conj acc "]]" more)]) :param-end (if (pos? level) [acc more] [(conj acc "}}") more]) (recur (conj acc token) more)))) (s/defn ^:private parse-tokens :- [ParsedToken] [tokens :- [StringOrToken]] (let [[parsed remaining] (parse-tokens* tokens 0) parsed (concat parsed (when (seq remaining) (parse-tokens remaining)))] ;; now loop over everything in `parsed`, and if we see 2 strings next to each other put them back together ;; e.g. [:token "x" "}}"] -> [:token "x}}"] (loop [acc [], last (first parsed), [x & more] (rest parsed)] (cond (not x) (conj acc last) (and (string? last) (string? x)) (recur acc (str last x) more) :else (recur (conj acc last) x more))))) (s/defn parse :- [(s/cond-pre s/Str Param Optional)] "Attempts to parse parameters in string `s`. Parses any optional clauses or parameters found, and returns a sequence of non-parameter string fragments (possibly) interposed with `Param` or `Optional` instances." [s :- s/Str] (let [tokenized (tokenize s)] (if (= [s] tokenized) [s] (do (log/tracef "Tokenized native query ->\n%s" (u/pprint-to-str tokenized)) (u/prog1 (parse-tokens tokenized) (log/tracef "Parsed native query ->\n%s" (u/pprint-to-str <>)))))))
[ { "context": " [:h3 character \":\"] [:blockquote text]]))\n\n(defui Harry\n static om/IQuery\n (query [this]\n '[[:dish/n", "end": 288, "score": 0.9492866396903992, "start": 283, "tag": "NAME", "value": "Harry" }, { "context": "number 3]])\n Object\n (render [this]\n (guest \"Harry\" (om/props this))))\n\n(def harry (om/factory Harry", "end": 392, "score": 0.9982421398162842, "start": 387, "tag": "NAME", "value": "Harry" }, { "context": "Vanilla\"]])\n Object\n (render [this]\n (guest \"Sally\" (om/props this))))\n\n(def sally (om/factory Sally", "end": 627, "score": 0.994715690612793, "start": 622, "tag": "NAME", "value": "Sally" } ]
src/om_next_dataflow/components.cljs
codebeige/om-next-dataflow
7
(ns om-next-dataflow.components (:require [cljs.pprint :refer [pprint]] [om.next :as om :refer-macros [defui]] [sablono.core :refer-macros [html]])) (defn guest [character {:keys [text]}] (html [:.person [:h3 character ":"] [:blockquote text]])) (defui Harry static om/IQuery (query [this] '[[:dish/number 3]]) Object (render [this] (guest "Harry" (om/props this)))) (def harry (om/factory Harry)) (defui Sally static om/IQuery (query [this] '[([:dish/name "Chef Salad"] {:aside [:oil :vinegar]}) [:dish/name "Vanilla"]]) Object (render [this] (guest "Sally" (om/props this)))) (def sally (om/factory Sally)) (defui Diner static om/IQuery (query [this] (into [] (concat (om/get-query Harry) (om/get-query Sally)))) Object (render [this] (html [:#diner [:h2 "Hi, what can I get ya?"] (harry {:text "I'll have a number three."}) (sally {:text "I'd like the chef salad please with the oil and vinegar on the side and the vanilla."}) [:h2 "Your order:"] [:pre (with-out-str (pprint (om/props this)))]])))
806
(ns om-next-dataflow.components (:require [cljs.pprint :refer [pprint]] [om.next :as om :refer-macros [defui]] [sablono.core :refer-macros [html]])) (defn guest [character {:keys [text]}] (html [:.person [:h3 character ":"] [:blockquote text]])) (defui <NAME> static om/IQuery (query [this] '[[:dish/number 3]]) Object (render [this] (guest "<NAME>" (om/props this)))) (def harry (om/factory Harry)) (defui Sally static om/IQuery (query [this] '[([:dish/name "Chef Salad"] {:aside [:oil :vinegar]}) [:dish/name "Vanilla"]]) Object (render [this] (guest "<NAME>" (om/props this)))) (def sally (om/factory Sally)) (defui Diner static om/IQuery (query [this] (into [] (concat (om/get-query Harry) (om/get-query Sally)))) Object (render [this] (html [:#diner [:h2 "Hi, what can I get ya?"] (harry {:text "I'll have a number three."}) (sally {:text "I'd like the chef salad please with the oil and vinegar on the side and the vanilla."}) [:h2 "Your order:"] [:pre (with-out-str (pprint (om/props this)))]])))
true
(ns om-next-dataflow.components (:require [cljs.pprint :refer [pprint]] [om.next :as om :refer-macros [defui]] [sablono.core :refer-macros [html]])) (defn guest [character {:keys [text]}] (html [:.person [:h3 character ":"] [:blockquote text]])) (defui PI:NAME:<NAME>END_PI static om/IQuery (query [this] '[[:dish/number 3]]) Object (render [this] (guest "PI:NAME:<NAME>END_PI" (om/props this)))) (def harry (om/factory Harry)) (defui Sally static om/IQuery (query [this] '[([:dish/name "Chef Salad"] {:aside [:oil :vinegar]}) [:dish/name "Vanilla"]]) Object (render [this] (guest "PI:NAME:<NAME>END_PI" (om/props this)))) (def sally (om/factory Sally)) (defui Diner static om/IQuery (query [this] (into [] (concat (om/get-query Harry) (om/get-query Sally)))) Object (render [this] (html [:#diner [:h2 "Hi, what can I get ya?"] (harry {:text "I'll have a number three."}) (sally {:text "I'd like the chef salad please with the oil and vinegar on the side and the vanilla."}) [:h2 "Your order:"] [:pre (with-out-str (pprint (om/props this)))]])))
[ { "context": ";; Copyright (c) Andrey Antukh <niwi@niwi.nz>\n;; All rights reserved.\n;;\n;; Redi", "end": 30, "score": 0.9998836517333984, "start": 17, "tag": "NAME", "value": "Andrey Antukh" }, { "context": ";; Copyright (c) Andrey Antukh <niwi@niwi.nz>\n;; All rights reserved.\n;;\n;; Redistribution and", "end": 44, "score": 0.9999326467514038, "start": 32, "tag": "EMAIL", "value": "niwi@niwi.nz" } ]
src/datoteka/core.clj
funcool/datoteka
55
;; Copyright (c) Andrey Antukh <niwi@niwi.nz> ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are met: ;; ;; * Redistributions of source code must retain the above copyright notice, this ;; list of conditions and the following disclaimer. ;; ;; * Redistributions in binary form must reproduce the above copyright notice, ;; this list of conditions and the following disclaimer in the documentation ;; and/or other materials provided with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE ;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (ns datoteka.core "File System helpers." (:refer-clojure :exclude [name with-open]) (:require [datoteka.proto :as pt] [clojure.java.io :as io] [clojure.core :as c]) (:import java.io.Writer java.io.File java.io.InputStream java.net.URL java.net.URI java.io.ByteArrayInputStream java.io.ByteArrayOutputStream java.nio.file.Path java.nio.file.Paths java.nio.file.Files java.nio.file.LinkOption java.nio.file.OpenOption java.nio.file.CopyOption java.nio.file.StandardOpenOption java.nio.file.StandardCopyOption java.nio.file.SimpleFileVisitor java.nio.file.FileVisitResult java.nio.file.attribute.FileAttribute java.nio.file.attribute.PosixFilePermissions)) (def ^:private empty-string-array (make-array String 0)) (extend-type String pt/IPath (-path [v] (Paths/get v empty-string-array))) (def ^:dynamic *cwd* (pt/-path (.getCanonicalPath (java.io.File. ".")))) (def ^:dynamic *sep* (System/getProperty "file.separator")) (def ^:dynamic *home* (pt/-path (System/getProperty "user.home"))) (def ^:dynamic *tmp-dir* (pt/-path (System/getProperty "java.io.tmpdir"))) (def ^:dynamic *os-name* (System/getProperty "os.name")) (def ^:dynamic *system* (if (.startsWith *os-name* "Windows") :dos :unix)) (defn path "Create path from string or more than one string." ([fst] (pt/-path fst)) ([fst & more] (pt/-path (cons fst more)))) (def ^:private open-opts-map {:truncate StandardOpenOption/TRUNCATE_EXISTING :create StandardOpenOption/CREATE :append StandardOpenOption/APPEND :create-new StandardOpenOption/CREATE_NEW :delete-on-close StandardOpenOption/DELETE_ON_CLOSE :dsync StandardOpenOption/DSYNC :read StandardOpenOption/READ :write StandardOpenOption/WRITE :sparse StandardOpenOption/SPARSE :sync StandardOpenOption/SYNC}) (def ^:private copy-opts-map {:atomic StandardCopyOption/ATOMIC_MOVE :replace StandardCopyOption/REPLACE_EXISTING :copy-attributes StandardCopyOption/COPY_ATTRIBUTES}) (defn- link-opts ^"[Ljava.nio.file.LinkOption;" [{:keys [nofollow-links]}] (if nofollow-links (into-array LinkOption [LinkOption/NOFOLLOW_LINKS]) (into-array LinkOption []))) (defn- interpret-open-opts [opts] {:pre [(every? open-opts-map opts)]} (->> (map open-opts-map opts) (into-array OpenOption))) (defn- interpret-copy-opts [opts] {:pre [(every? copy-opts-map opts)]} (->> (map copy-opts-map opts) (into-array CopyOption))) (defn make-permissions "Generate a array of `FileAttribute` instances generated from `rwxr-xr-x` kind of expressions." [^String expr] (let [perms (PosixFilePermissions/fromString expr) attr (PosixFilePermissions/asFileAttribute perms)] (into-array FileAttribute [attr]))) (defn path? "Return `true` if provided value is an instance of Path." [v] (instance? Path v)) (defn file? "Check if `v` is an instance of java.io.File" [v] (instance? File v)) (defn absolute? "Checks if the provided path is absolute." [path] (let [^Path path (pt/-path path)] (.isAbsolute path))) (defn relative? "Check if the provided path is relative." [path] (not (absolute? path))) (defn executable? "Checks if the provided path is executable." [path] (Files/isExecutable ^Path (pt/-path path))) (defn exists? "Check if the provided path exists." ([path] (exists? path nil)) ([path params] (let [^Path path (pt/-path path)] (Files/exists path (link-opts params))))) (defn directory? "Checks if the provided path is a directory." ([path] (directory? path nil)) ([path params] (let [^Path path (pt/-path path)] (Files/isDirectory path (link-opts params))))) (defn regular-file? "Checks if the provided path is a plain file." ([path] (regular-file? path nil)) ([path params] (Files/isRegularFile (pt/-path path) (link-opts params)))) (defn link? "Checks if the provided path is a link." [path] (Files/isSymbolicLink (pt/-path path))) (defn hidden? "Check if the provided path is hidden." [path] (Files/isHidden (pt/-path path))) (defn readable? "Check if the provided path is readable." [path] (Files/isReadable (pt/-path path))) (defn writable? "Check if the provided path is writable." [path] (Files/isWritable (pt/-path path))) (defn permissions "Returns the string representation of the permissions of the provided path." ([path] (permissions path nil)) ([path params] (let [^Path path (pt/-path path)] (->> (Files/getPosixFilePermissions path (link-opts params)) (PosixFilePermissions/toString))))) (defn ^Path real "Converts f into real path via Path#toRealPath." ([path] (real path nil)) ([path params] (.toRealPath (pt/-path path) (link-opts params)))) (defn absolute "Return absolute path." [path] (.toAbsolutePath (pt/-path path))) (defn parent "Get parent path if it exists." [path] (.getParent ^Path (pt/-path path))) (defn name "Return a path representing the name of the file or directory, or null if this path has zero elements." [path] (str (.getFileName ^Path (pt/-path path)))) (defn split-ext "Returns a vector of `[^String name ^String extension]`." [path] (let [^Path path (pt/-path path) ^String path-str (.toString path) i (.lastIndexOf path-str ".")] (if (pos? i) [(subs path-str 0 i) (subs path-str i)] [path-str nil]))) (defn ext "Return the extension part of a file." [path] (some-> (last (split-ext path)) (subs 1))) (defn base "Return the base part of a file." [path] (first (split-ext path))) (defn normalize "Normalize the path." [path] (let [^String path (str (.normalize ^Path (pt/-path path)))] (cond (= path "~") (pt/-path *home*) (.startsWith path (str "~" *sep*)) (pt/-path (.replace path "~" ^String (.toString ^Object *home*))) (not (.startsWith path *sep*)) (pt/-path (str *cwd* *sep* path)) :else (pt/-path path)))) (defn join "Resolve path on top of an other path." ([base path] (let [^Path base (pt/-path base) ^Path path (pt/-path path)] (-> (.resolve base path) (.normalize)))) ([base path & more] (reduce join base (cons path more)))) (defn relativize "Returns the relationship between two paths." [base other] (.relativize ^Path (pt/-path other) ^Path (pt/-path base))) (defn file "Converts the path to a java.io.File instance." [path] (.toFile ^Path (pt/-path path))) (defn- list-dir-lazy-seq ([stream] (list-dir-lazy-seq stream (seq stream))) ([stream s] (lazy-seq (let [p1 (first s) p2 (rest s)] (if (seq p2) (cons p1 (list-dir-lazy-seq stream p2)) (do (.close stream) (cons p1 nil))))))) (defn list-dir "Return a lazy seq of files and directories found under the provided directory. The order of files is not guarrantied. NOTE: the seq should be fully realized in order to properly release all acquired resources for this operation. Converting it to vector is an option for do it." ([path] (let [path (pt/-path path) stream (Files/newDirectoryStream path)] (list-dir-lazy-seq stream))) ([path ^String glob] (let [path (pt/-path path) stream (Files/newDirectoryStream path glob)] (list-dir-lazy-seq stream)))) (defn create-tempdir "Creates a temp directory on the filesystem." ([] (create-tempdir "")) ([prefix] (Files/createTempDirectory prefix (make-array FileAttribute 0)))) (defn create-dir "Create a new directory." ([path] (create-dir path "rwxr-xr-x")) ([path perms] {:pre [(string? perms)]} (let [^Path path (pt/-path path) attrs (make-permissions perms)] (Files/createDirectories path attrs)))) (defn- delete-recursive [^Path path] (->> (proxy [SimpleFileVisitor] [] (visitFile [file attrs] (Files/delete file) FileVisitResult/CONTINUE) (postVisitDirectory [dir exc] (Files/delete dir) FileVisitResult/CONTINUE)) (Files/walkFileTree path))) (defn delete "Delete recursiverly a directory or file." [path] (let [^Path path (pt/-path path)] (if (regular-file? path) (Files/deleteIfExists path) (delete-recursive path)))) (defn move "Move or rename a file to a target file. By default, this method attempts to move the file to the target file, failing if the target file exists except if the source and target are the same file, in which case this method has no effect. If the file is a symbolic link then the symbolic link itself, not the target of the link, is moved. This method may be invoked to move an empty directory. When invoked to move a directory that is not empty then the directory is moved if it does not require moving the entries in the directory. For example, renaming a directory on the same FileStore will usually not require moving the entries in the directory. When moving a directory requires that its entries be moved then this method fails (by throwing an IOException)." ([src dst] (move src dst #{:atomic :replace})) ([src dst flags] (let [^Path src (pt/-path src) ^Path dst (pt/-path dst) opts (interpret-copy-opts flags)] (Files/move src dst opts)))) (defn create-tempfile "Create a temporal file." [& {:keys [suffix prefix]}] (->> (make-permissions "rwxr-xr-x") (Files/createTempFile prefix suffix))) (defn slurp-bytes [input] (c/with-open [input (io/input-stream (path input)) output (ByteArrayOutputStream. (.available input))] (io/copy input output) (.toByteArray output))) ;; --- Implementation (defmethod print-method Path [^Path v ^Writer w] (.write w (str "#path \"" (.toString v) "\""))) (defmethod print-method File [^File v ^Writer w] (.write w (str "#file \"" (.toString v) "\""))) (extend-protocol pt/IUri URI (-uri [v] v) String (-uri [v] (URI. v))) (extend-protocol pt/IPath Path (-path [v] v) java.io.File (-path [v] (.toPath v)) URI (-path [v] (Paths/get v)) URL (-path [v] (Paths/get (.toURI v))) clojure.lang.Sequential (-path [v] (reduce #(.resolve %1 %2) (pt/-path (first v)) (map pt/-path (rest v))))) (extend-protocol io/Coercions Path (as-file [it] (.toFile it)) (as-url [it] (io/as-url (.toFile it)))) (defn- path->input-stream [^Path path] (let [opts (interpret-open-opts #{:read})] (Files/newInputStream path opts))) (defn- path->output-stream [^Path path] (let [opts (interpret-open-opts #{:truncate :create :write})] (Files/newOutputStream path opts))) (extend-type Path io/IOFactory (make-reader [path opts] (let [^InputStream is (path->input-stream path)] (io/make-reader is opts))) (make-writer [path opts] (let [^OutputStream os (path->output-stream path)] (io/make-writer os opts))) (make-input-stream [path opts] (let [^InputStream is (path->input-stream path)] (io/make-input-stream is opts))) (make-output-stream [path opts] (let [^OutputStream os (path->output-stream path)] (io/make-output-stream os opts))))
115916
;; Copyright (c) <NAME> <<EMAIL>> ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are met: ;; ;; * Redistributions of source code must retain the above copyright notice, this ;; list of conditions and the following disclaimer. ;; ;; * Redistributions in binary form must reproduce the above copyright notice, ;; this list of conditions and the following disclaimer in the documentation ;; and/or other materials provided with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE ;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (ns datoteka.core "File System helpers." (:refer-clojure :exclude [name with-open]) (:require [datoteka.proto :as pt] [clojure.java.io :as io] [clojure.core :as c]) (:import java.io.Writer java.io.File java.io.InputStream java.net.URL java.net.URI java.io.ByteArrayInputStream java.io.ByteArrayOutputStream java.nio.file.Path java.nio.file.Paths java.nio.file.Files java.nio.file.LinkOption java.nio.file.OpenOption java.nio.file.CopyOption java.nio.file.StandardOpenOption java.nio.file.StandardCopyOption java.nio.file.SimpleFileVisitor java.nio.file.FileVisitResult java.nio.file.attribute.FileAttribute java.nio.file.attribute.PosixFilePermissions)) (def ^:private empty-string-array (make-array String 0)) (extend-type String pt/IPath (-path [v] (Paths/get v empty-string-array))) (def ^:dynamic *cwd* (pt/-path (.getCanonicalPath (java.io.File. ".")))) (def ^:dynamic *sep* (System/getProperty "file.separator")) (def ^:dynamic *home* (pt/-path (System/getProperty "user.home"))) (def ^:dynamic *tmp-dir* (pt/-path (System/getProperty "java.io.tmpdir"))) (def ^:dynamic *os-name* (System/getProperty "os.name")) (def ^:dynamic *system* (if (.startsWith *os-name* "Windows") :dos :unix)) (defn path "Create path from string or more than one string." ([fst] (pt/-path fst)) ([fst & more] (pt/-path (cons fst more)))) (def ^:private open-opts-map {:truncate StandardOpenOption/TRUNCATE_EXISTING :create StandardOpenOption/CREATE :append StandardOpenOption/APPEND :create-new StandardOpenOption/CREATE_NEW :delete-on-close StandardOpenOption/DELETE_ON_CLOSE :dsync StandardOpenOption/DSYNC :read StandardOpenOption/READ :write StandardOpenOption/WRITE :sparse StandardOpenOption/SPARSE :sync StandardOpenOption/SYNC}) (def ^:private copy-opts-map {:atomic StandardCopyOption/ATOMIC_MOVE :replace StandardCopyOption/REPLACE_EXISTING :copy-attributes StandardCopyOption/COPY_ATTRIBUTES}) (defn- link-opts ^"[Ljava.nio.file.LinkOption;" [{:keys [nofollow-links]}] (if nofollow-links (into-array LinkOption [LinkOption/NOFOLLOW_LINKS]) (into-array LinkOption []))) (defn- interpret-open-opts [opts] {:pre [(every? open-opts-map opts)]} (->> (map open-opts-map opts) (into-array OpenOption))) (defn- interpret-copy-opts [opts] {:pre [(every? copy-opts-map opts)]} (->> (map copy-opts-map opts) (into-array CopyOption))) (defn make-permissions "Generate a array of `FileAttribute` instances generated from `rwxr-xr-x` kind of expressions." [^String expr] (let [perms (PosixFilePermissions/fromString expr) attr (PosixFilePermissions/asFileAttribute perms)] (into-array FileAttribute [attr]))) (defn path? "Return `true` if provided value is an instance of Path." [v] (instance? Path v)) (defn file? "Check if `v` is an instance of java.io.File" [v] (instance? File v)) (defn absolute? "Checks if the provided path is absolute." [path] (let [^Path path (pt/-path path)] (.isAbsolute path))) (defn relative? "Check if the provided path is relative." [path] (not (absolute? path))) (defn executable? "Checks if the provided path is executable." [path] (Files/isExecutable ^Path (pt/-path path))) (defn exists? "Check if the provided path exists." ([path] (exists? path nil)) ([path params] (let [^Path path (pt/-path path)] (Files/exists path (link-opts params))))) (defn directory? "Checks if the provided path is a directory." ([path] (directory? path nil)) ([path params] (let [^Path path (pt/-path path)] (Files/isDirectory path (link-opts params))))) (defn regular-file? "Checks if the provided path is a plain file." ([path] (regular-file? path nil)) ([path params] (Files/isRegularFile (pt/-path path) (link-opts params)))) (defn link? "Checks if the provided path is a link." [path] (Files/isSymbolicLink (pt/-path path))) (defn hidden? "Check if the provided path is hidden." [path] (Files/isHidden (pt/-path path))) (defn readable? "Check if the provided path is readable." [path] (Files/isReadable (pt/-path path))) (defn writable? "Check if the provided path is writable." [path] (Files/isWritable (pt/-path path))) (defn permissions "Returns the string representation of the permissions of the provided path." ([path] (permissions path nil)) ([path params] (let [^Path path (pt/-path path)] (->> (Files/getPosixFilePermissions path (link-opts params)) (PosixFilePermissions/toString))))) (defn ^Path real "Converts f into real path via Path#toRealPath." ([path] (real path nil)) ([path params] (.toRealPath (pt/-path path) (link-opts params)))) (defn absolute "Return absolute path." [path] (.toAbsolutePath (pt/-path path))) (defn parent "Get parent path if it exists." [path] (.getParent ^Path (pt/-path path))) (defn name "Return a path representing the name of the file or directory, or null if this path has zero elements." [path] (str (.getFileName ^Path (pt/-path path)))) (defn split-ext "Returns a vector of `[^String name ^String extension]`." [path] (let [^Path path (pt/-path path) ^String path-str (.toString path) i (.lastIndexOf path-str ".")] (if (pos? i) [(subs path-str 0 i) (subs path-str i)] [path-str nil]))) (defn ext "Return the extension part of a file." [path] (some-> (last (split-ext path)) (subs 1))) (defn base "Return the base part of a file." [path] (first (split-ext path))) (defn normalize "Normalize the path." [path] (let [^String path (str (.normalize ^Path (pt/-path path)))] (cond (= path "~") (pt/-path *home*) (.startsWith path (str "~" *sep*)) (pt/-path (.replace path "~" ^String (.toString ^Object *home*))) (not (.startsWith path *sep*)) (pt/-path (str *cwd* *sep* path)) :else (pt/-path path)))) (defn join "Resolve path on top of an other path." ([base path] (let [^Path base (pt/-path base) ^Path path (pt/-path path)] (-> (.resolve base path) (.normalize)))) ([base path & more] (reduce join base (cons path more)))) (defn relativize "Returns the relationship between two paths." [base other] (.relativize ^Path (pt/-path other) ^Path (pt/-path base))) (defn file "Converts the path to a java.io.File instance." [path] (.toFile ^Path (pt/-path path))) (defn- list-dir-lazy-seq ([stream] (list-dir-lazy-seq stream (seq stream))) ([stream s] (lazy-seq (let [p1 (first s) p2 (rest s)] (if (seq p2) (cons p1 (list-dir-lazy-seq stream p2)) (do (.close stream) (cons p1 nil))))))) (defn list-dir "Return a lazy seq of files and directories found under the provided directory. The order of files is not guarrantied. NOTE: the seq should be fully realized in order to properly release all acquired resources for this operation. Converting it to vector is an option for do it." ([path] (let [path (pt/-path path) stream (Files/newDirectoryStream path)] (list-dir-lazy-seq stream))) ([path ^String glob] (let [path (pt/-path path) stream (Files/newDirectoryStream path glob)] (list-dir-lazy-seq stream)))) (defn create-tempdir "Creates a temp directory on the filesystem." ([] (create-tempdir "")) ([prefix] (Files/createTempDirectory prefix (make-array FileAttribute 0)))) (defn create-dir "Create a new directory." ([path] (create-dir path "rwxr-xr-x")) ([path perms] {:pre [(string? perms)]} (let [^Path path (pt/-path path) attrs (make-permissions perms)] (Files/createDirectories path attrs)))) (defn- delete-recursive [^Path path] (->> (proxy [SimpleFileVisitor] [] (visitFile [file attrs] (Files/delete file) FileVisitResult/CONTINUE) (postVisitDirectory [dir exc] (Files/delete dir) FileVisitResult/CONTINUE)) (Files/walkFileTree path))) (defn delete "Delete recursiverly a directory or file." [path] (let [^Path path (pt/-path path)] (if (regular-file? path) (Files/deleteIfExists path) (delete-recursive path)))) (defn move "Move or rename a file to a target file. By default, this method attempts to move the file to the target file, failing if the target file exists except if the source and target are the same file, in which case this method has no effect. If the file is a symbolic link then the symbolic link itself, not the target of the link, is moved. This method may be invoked to move an empty directory. When invoked to move a directory that is not empty then the directory is moved if it does not require moving the entries in the directory. For example, renaming a directory on the same FileStore will usually not require moving the entries in the directory. When moving a directory requires that its entries be moved then this method fails (by throwing an IOException)." ([src dst] (move src dst #{:atomic :replace})) ([src dst flags] (let [^Path src (pt/-path src) ^Path dst (pt/-path dst) opts (interpret-copy-opts flags)] (Files/move src dst opts)))) (defn create-tempfile "Create a temporal file." [& {:keys [suffix prefix]}] (->> (make-permissions "rwxr-xr-x") (Files/createTempFile prefix suffix))) (defn slurp-bytes [input] (c/with-open [input (io/input-stream (path input)) output (ByteArrayOutputStream. (.available input))] (io/copy input output) (.toByteArray output))) ;; --- Implementation (defmethod print-method Path [^Path v ^Writer w] (.write w (str "#path \"" (.toString v) "\""))) (defmethod print-method File [^File v ^Writer w] (.write w (str "#file \"" (.toString v) "\""))) (extend-protocol pt/IUri URI (-uri [v] v) String (-uri [v] (URI. v))) (extend-protocol pt/IPath Path (-path [v] v) java.io.File (-path [v] (.toPath v)) URI (-path [v] (Paths/get v)) URL (-path [v] (Paths/get (.toURI v))) clojure.lang.Sequential (-path [v] (reduce #(.resolve %1 %2) (pt/-path (first v)) (map pt/-path (rest v))))) (extend-protocol io/Coercions Path (as-file [it] (.toFile it)) (as-url [it] (io/as-url (.toFile it)))) (defn- path->input-stream [^Path path] (let [opts (interpret-open-opts #{:read})] (Files/newInputStream path opts))) (defn- path->output-stream [^Path path] (let [opts (interpret-open-opts #{:truncate :create :write})] (Files/newOutputStream path opts))) (extend-type Path io/IOFactory (make-reader [path opts] (let [^InputStream is (path->input-stream path)] (io/make-reader is opts))) (make-writer [path opts] (let [^OutputStream os (path->output-stream path)] (io/make-writer os opts))) (make-input-stream [path opts] (let [^InputStream is (path->input-stream path)] (io/make-input-stream is opts))) (make-output-stream [path opts] (let [^OutputStream os (path->output-stream path)] (io/make-output-stream os opts))))
true
;; Copyright (c) PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are met: ;; ;; * Redistributions of source code must retain the above copyright notice, this ;; list of conditions and the following disclaimer. ;; ;; * Redistributions in binary form must reproduce the above copyright notice, ;; this list of conditions and the following disclaimer in the documentation ;; and/or other materials provided with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE ;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (ns datoteka.core "File System helpers." (:refer-clojure :exclude [name with-open]) (:require [datoteka.proto :as pt] [clojure.java.io :as io] [clojure.core :as c]) (:import java.io.Writer java.io.File java.io.InputStream java.net.URL java.net.URI java.io.ByteArrayInputStream java.io.ByteArrayOutputStream java.nio.file.Path java.nio.file.Paths java.nio.file.Files java.nio.file.LinkOption java.nio.file.OpenOption java.nio.file.CopyOption java.nio.file.StandardOpenOption java.nio.file.StandardCopyOption java.nio.file.SimpleFileVisitor java.nio.file.FileVisitResult java.nio.file.attribute.FileAttribute java.nio.file.attribute.PosixFilePermissions)) (def ^:private empty-string-array (make-array String 0)) (extend-type String pt/IPath (-path [v] (Paths/get v empty-string-array))) (def ^:dynamic *cwd* (pt/-path (.getCanonicalPath (java.io.File. ".")))) (def ^:dynamic *sep* (System/getProperty "file.separator")) (def ^:dynamic *home* (pt/-path (System/getProperty "user.home"))) (def ^:dynamic *tmp-dir* (pt/-path (System/getProperty "java.io.tmpdir"))) (def ^:dynamic *os-name* (System/getProperty "os.name")) (def ^:dynamic *system* (if (.startsWith *os-name* "Windows") :dos :unix)) (defn path "Create path from string or more than one string." ([fst] (pt/-path fst)) ([fst & more] (pt/-path (cons fst more)))) (def ^:private open-opts-map {:truncate StandardOpenOption/TRUNCATE_EXISTING :create StandardOpenOption/CREATE :append StandardOpenOption/APPEND :create-new StandardOpenOption/CREATE_NEW :delete-on-close StandardOpenOption/DELETE_ON_CLOSE :dsync StandardOpenOption/DSYNC :read StandardOpenOption/READ :write StandardOpenOption/WRITE :sparse StandardOpenOption/SPARSE :sync StandardOpenOption/SYNC}) (def ^:private copy-opts-map {:atomic StandardCopyOption/ATOMIC_MOVE :replace StandardCopyOption/REPLACE_EXISTING :copy-attributes StandardCopyOption/COPY_ATTRIBUTES}) (defn- link-opts ^"[Ljava.nio.file.LinkOption;" [{:keys [nofollow-links]}] (if nofollow-links (into-array LinkOption [LinkOption/NOFOLLOW_LINKS]) (into-array LinkOption []))) (defn- interpret-open-opts [opts] {:pre [(every? open-opts-map opts)]} (->> (map open-opts-map opts) (into-array OpenOption))) (defn- interpret-copy-opts [opts] {:pre [(every? copy-opts-map opts)]} (->> (map copy-opts-map opts) (into-array CopyOption))) (defn make-permissions "Generate a array of `FileAttribute` instances generated from `rwxr-xr-x` kind of expressions." [^String expr] (let [perms (PosixFilePermissions/fromString expr) attr (PosixFilePermissions/asFileAttribute perms)] (into-array FileAttribute [attr]))) (defn path? "Return `true` if provided value is an instance of Path." [v] (instance? Path v)) (defn file? "Check if `v` is an instance of java.io.File" [v] (instance? File v)) (defn absolute? "Checks if the provided path is absolute." [path] (let [^Path path (pt/-path path)] (.isAbsolute path))) (defn relative? "Check if the provided path is relative." [path] (not (absolute? path))) (defn executable? "Checks if the provided path is executable." [path] (Files/isExecutable ^Path (pt/-path path))) (defn exists? "Check if the provided path exists." ([path] (exists? path nil)) ([path params] (let [^Path path (pt/-path path)] (Files/exists path (link-opts params))))) (defn directory? "Checks if the provided path is a directory." ([path] (directory? path nil)) ([path params] (let [^Path path (pt/-path path)] (Files/isDirectory path (link-opts params))))) (defn regular-file? "Checks if the provided path is a plain file." ([path] (regular-file? path nil)) ([path params] (Files/isRegularFile (pt/-path path) (link-opts params)))) (defn link? "Checks if the provided path is a link." [path] (Files/isSymbolicLink (pt/-path path))) (defn hidden? "Check if the provided path is hidden." [path] (Files/isHidden (pt/-path path))) (defn readable? "Check if the provided path is readable." [path] (Files/isReadable (pt/-path path))) (defn writable? "Check if the provided path is writable." [path] (Files/isWritable (pt/-path path))) (defn permissions "Returns the string representation of the permissions of the provided path." ([path] (permissions path nil)) ([path params] (let [^Path path (pt/-path path)] (->> (Files/getPosixFilePermissions path (link-opts params)) (PosixFilePermissions/toString))))) (defn ^Path real "Converts f into real path via Path#toRealPath." ([path] (real path nil)) ([path params] (.toRealPath (pt/-path path) (link-opts params)))) (defn absolute "Return absolute path." [path] (.toAbsolutePath (pt/-path path))) (defn parent "Get parent path if it exists." [path] (.getParent ^Path (pt/-path path))) (defn name "Return a path representing the name of the file or directory, or null if this path has zero elements." [path] (str (.getFileName ^Path (pt/-path path)))) (defn split-ext "Returns a vector of `[^String name ^String extension]`." [path] (let [^Path path (pt/-path path) ^String path-str (.toString path) i (.lastIndexOf path-str ".")] (if (pos? i) [(subs path-str 0 i) (subs path-str i)] [path-str nil]))) (defn ext "Return the extension part of a file." [path] (some-> (last (split-ext path)) (subs 1))) (defn base "Return the base part of a file." [path] (first (split-ext path))) (defn normalize "Normalize the path." [path] (let [^String path (str (.normalize ^Path (pt/-path path)))] (cond (= path "~") (pt/-path *home*) (.startsWith path (str "~" *sep*)) (pt/-path (.replace path "~" ^String (.toString ^Object *home*))) (not (.startsWith path *sep*)) (pt/-path (str *cwd* *sep* path)) :else (pt/-path path)))) (defn join "Resolve path on top of an other path." ([base path] (let [^Path base (pt/-path base) ^Path path (pt/-path path)] (-> (.resolve base path) (.normalize)))) ([base path & more] (reduce join base (cons path more)))) (defn relativize "Returns the relationship between two paths." [base other] (.relativize ^Path (pt/-path other) ^Path (pt/-path base))) (defn file "Converts the path to a java.io.File instance." [path] (.toFile ^Path (pt/-path path))) (defn- list-dir-lazy-seq ([stream] (list-dir-lazy-seq stream (seq stream))) ([stream s] (lazy-seq (let [p1 (first s) p2 (rest s)] (if (seq p2) (cons p1 (list-dir-lazy-seq stream p2)) (do (.close stream) (cons p1 nil))))))) (defn list-dir "Return a lazy seq of files and directories found under the provided directory. The order of files is not guarrantied. NOTE: the seq should be fully realized in order to properly release all acquired resources for this operation. Converting it to vector is an option for do it." ([path] (let [path (pt/-path path) stream (Files/newDirectoryStream path)] (list-dir-lazy-seq stream))) ([path ^String glob] (let [path (pt/-path path) stream (Files/newDirectoryStream path glob)] (list-dir-lazy-seq stream)))) (defn create-tempdir "Creates a temp directory on the filesystem." ([] (create-tempdir "")) ([prefix] (Files/createTempDirectory prefix (make-array FileAttribute 0)))) (defn create-dir "Create a new directory." ([path] (create-dir path "rwxr-xr-x")) ([path perms] {:pre [(string? perms)]} (let [^Path path (pt/-path path) attrs (make-permissions perms)] (Files/createDirectories path attrs)))) (defn- delete-recursive [^Path path] (->> (proxy [SimpleFileVisitor] [] (visitFile [file attrs] (Files/delete file) FileVisitResult/CONTINUE) (postVisitDirectory [dir exc] (Files/delete dir) FileVisitResult/CONTINUE)) (Files/walkFileTree path))) (defn delete "Delete recursiverly a directory or file." [path] (let [^Path path (pt/-path path)] (if (regular-file? path) (Files/deleteIfExists path) (delete-recursive path)))) (defn move "Move or rename a file to a target file. By default, this method attempts to move the file to the target file, failing if the target file exists except if the source and target are the same file, in which case this method has no effect. If the file is a symbolic link then the symbolic link itself, not the target of the link, is moved. This method may be invoked to move an empty directory. When invoked to move a directory that is not empty then the directory is moved if it does not require moving the entries in the directory. For example, renaming a directory on the same FileStore will usually not require moving the entries in the directory. When moving a directory requires that its entries be moved then this method fails (by throwing an IOException)." ([src dst] (move src dst #{:atomic :replace})) ([src dst flags] (let [^Path src (pt/-path src) ^Path dst (pt/-path dst) opts (interpret-copy-opts flags)] (Files/move src dst opts)))) (defn create-tempfile "Create a temporal file." [& {:keys [suffix prefix]}] (->> (make-permissions "rwxr-xr-x") (Files/createTempFile prefix suffix))) (defn slurp-bytes [input] (c/with-open [input (io/input-stream (path input)) output (ByteArrayOutputStream. (.available input))] (io/copy input output) (.toByteArray output))) ;; --- Implementation (defmethod print-method Path [^Path v ^Writer w] (.write w (str "#path \"" (.toString v) "\""))) (defmethod print-method File [^File v ^Writer w] (.write w (str "#file \"" (.toString v) "\""))) (extend-protocol pt/IUri URI (-uri [v] v) String (-uri [v] (URI. v))) (extend-protocol pt/IPath Path (-path [v] v) java.io.File (-path [v] (.toPath v)) URI (-path [v] (Paths/get v)) URL (-path [v] (Paths/get (.toURI v))) clojure.lang.Sequential (-path [v] (reduce #(.resolve %1 %2) (pt/-path (first v)) (map pt/-path (rest v))))) (extend-protocol io/Coercions Path (as-file [it] (.toFile it)) (as-url [it] (io/as-url (.toFile it)))) (defn- path->input-stream [^Path path] (let [opts (interpret-open-opts #{:read})] (Files/newInputStream path opts))) (defn- path->output-stream [^Path path] (let [opts (interpret-open-opts #{:truncate :create :write})] (Files/newOutputStream path opts))) (extend-type Path io/IOFactory (make-reader [path opts] (let [^InputStream is (path->input-stream path)] (io/make-reader is opts))) (make-writer [path opts] (let [^OutputStream os (path->output-stream path)] (io/make-writer os opts))) (make-input-stream [path opts] (let [^InputStream is (path->input-stream path)] (io/make-input-stream is opts))) (make-output-stream [path opts] (let [^OutputStream os (path->output-stream path)] (io/make-output-stream os opts))))
[ { "context": "m/sets/1/challenges/1\"\n (let [challenge-input \"49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d\"\n challenge-output \"SSdtIGtpbGxpbmcgeW91", "end": 363, "score": 0.9967663288116455, "start": 267, "tag": "KEY", "value": "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d" } ]
test/matasano_crypto/core_test.clj
kgxsz/matasano-crypto
0
(ns matasano-crypto.core-test (:require [clojure.test :refer :all] [matasano-crypto.core :as core])) (deftest test-challenge-one (testing "it satisfies the conditions outlined at: http://cryptopals.com/sets/1/challenges/1" (let [challenge-input "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d" challenge-output "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"] (is (= challenge-output (core/challenge-one challenge-input)))))) (deftest test-challenge-two (testing "it satisfies the conditions outlined at: http://cryptopals.com/sets/1/challenges/2" (let [challenge-input-a "1c0111001f010100061a024b53535009181c" challenge-input-b "686974207468652062756c6c277320657965" challenge-output "746865206b696420646f6e277420706c6179"] (is (= challenge-output (core/challenge-two challenge-input-a challenge-input-b)))))) (deftest test-challenge-three (testing "it satisfies the conditions outlined at: http://cryptopals.com/sets/1/challenges/3" (let [challenge-input "1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736" challenge-output "Cooking MC's like a pound of bacon"] (is (= challenge-output (core/challenge-three challenge-input)))))) (deftest test-challenge-four (testing "it satisfies the conditions outlined at: http://cryptopals.com/sets/1/challenges/4" (let [challenge-output "Now that the party is jumping\n"] (is (= challenge-output (core/challenge-four)))))) (deftest test-challenge-five (testing "it satisfies the conditions outlined at: http://cryptopals.com/sets/1/challenges/5" (let [challenge-input-key "ICE" challenge-input-plaintext "Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a cymbal" challenge-output "0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f"] (is (= challenge-output (core/challenge-five challenge-input-key challenge-input-plaintext)))))) (deftest test-challenge-six (testing "it satisfies the conditions outlined at: http://cryptopals.com/sets/1/challenges/6" (let [challenge-output (slurp "resources/challenge-six-output.txt")] (is (= challenge-output (core/challenge-six)))))) (deftest test-challenge-seven (testing "it satisfies the conditions outlined at: http://cryptopals.com/sets/1/challenges/7" (let [challenge-output (slurp "resources/challenge-seven-output.txt")] (is (= challenge-output (core/challenge-seven)))))) (deftest test-challenge-seven (testing "it satisfies the conditions outlined at: http://cryptopals.com/sets/1/challenges/8" (let [challenge-output (slurp "resources/challenge-eight-output.txt")] (is (= challenge-output (core/challenge-eight))))))
116398
(ns matasano-crypto.core-test (:require [clojure.test :refer :all] [matasano-crypto.core :as core])) (deftest test-challenge-one (testing "it satisfies the conditions outlined at: http://cryptopals.com/sets/1/challenges/1" (let [challenge-input "<KEY>" challenge-output "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"] (is (= challenge-output (core/challenge-one challenge-input)))))) (deftest test-challenge-two (testing "it satisfies the conditions outlined at: http://cryptopals.com/sets/1/challenges/2" (let [challenge-input-a "1c0111001f010100061a024b53535009181c" challenge-input-b "686974207468652062756c6c277320657965" challenge-output "746865206b696420646f6e277420706c6179"] (is (= challenge-output (core/challenge-two challenge-input-a challenge-input-b)))))) (deftest test-challenge-three (testing "it satisfies the conditions outlined at: http://cryptopals.com/sets/1/challenges/3" (let [challenge-input "1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736" challenge-output "Cooking MC's like a pound of bacon"] (is (= challenge-output (core/challenge-three challenge-input)))))) (deftest test-challenge-four (testing "it satisfies the conditions outlined at: http://cryptopals.com/sets/1/challenges/4" (let [challenge-output "Now that the party is jumping\n"] (is (= challenge-output (core/challenge-four)))))) (deftest test-challenge-five (testing "it satisfies the conditions outlined at: http://cryptopals.com/sets/1/challenges/5" (let [challenge-input-key "ICE" challenge-input-plaintext "Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a cymbal" challenge-output "0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f"] (is (= challenge-output (core/challenge-five challenge-input-key challenge-input-plaintext)))))) (deftest test-challenge-six (testing "it satisfies the conditions outlined at: http://cryptopals.com/sets/1/challenges/6" (let [challenge-output (slurp "resources/challenge-six-output.txt")] (is (= challenge-output (core/challenge-six)))))) (deftest test-challenge-seven (testing "it satisfies the conditions outlined at: http://cryptopals.com/sets/1/challenges/7" (let [challenge-output (slurp "resources/challenge-seven-output.txt")] (is (= challenge-output (core/challenge-seven)))))) (deftest test-challenge-seven (testing "it satisfies the conditions outlined at: http://cryptopals.com/sets/1/challenges/8" (let [challenge-output (slurp "resources/challenge-eight-output.txt")] (is (= challenge-output (core/challenge-eight))))))
true
(ns matasano-crypto.core-test (:require [clojure.test :refer :all] [matasano-crypto.core :as core])) (deftest test-challenge-one (testing "it satisfies the conditions outlined at: http://cryptopals.com/sets/1/challenges/1" (let [challenge-input "PI:KEY:<KEY>END_PI" challenge-output "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"] (is (= challenge-output (core/challenge-one challenge-input)))))) (deftest test-challenge-two (testing "it satisfies the conditions outlined at: http://cryptopals.com/sets/1/challenges/2" (let [challenge-input-a "1c0111001f010100061a024b53535009181c" challenge-input-b "686974207468652062756c6c277320657965" challenge-output "746865206b696420646f6e277420706c6179"] (is (= challenge-output (core/challenge-two challenge-input-a challenge-input-b)))))) (deftest test-challenge-three (testing "it satisfies the conditions outlined at: http://cryptopals.com/sets/1/challenges/3" (let [challenge-input "1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736" challenge-output "Cooking MC's like a pound of bacon"] (is (= challenge-output (core/challenge-three challenge-input)))))) (deftest test-challenge-four (testing "it satisfies the conditions outlined at: http://cryptopals.com/sets/1/challenges/4" (let [challenge-output "Now that the party is jumping\n"] (is (= challenge-output (core/challenge-four)))))) (deftest test-challenge-five (testing "it satisfies the conditions outlined at: http://cryptopals.com/sets/1/challenges/5" (let [challenge-input-key "ICE" challenge-input-plaintext "Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a cymbal" challenge-output "0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f"] (is (= challenge-output (core/challenge-five challenge-input-key challenge-input-plaintext)))))) (deftest test-challenge-six (testing "it satisfies the conditions outlined at: http://cryptopals.com/sets/1/challenges/6" (let [challenge-output (slurp "resources/challenge-six-output.txt")] (is (= challenge-output (core/challenge-six)))))) (deftest test-challenge-seven (testing "it satisfies the conditions outlined at: http://cryptopals.com/sets/1/challenges/7" (let [challenge-output (slurp "resources/challenge-seven-output.txt")] (is (= challenge-output (core/challenge-seven)))))) (deftest test-challenge-seven (testing "it satisfies the conditions outlined at: http://cryptopals.com/sets/1/challenges/8" (let [challenge-output (slurp "resources/challenge-eight-output.txt")] (is (= challenge-output (core/challenge-eight))))))
[ { "context": "----------------------------\n;; Copyright (c) 2011 Basho Technologies, Inc. All Rights Reserved.\n;;\n;; This file is pr", "end": 111, "score": 0.9002294540405273, "start": 93, "tag": "NAME", "value": "Basho Technologies" } ]
src/knockbox/sets/two_phase.clj
reiddraper/knockbox
34
;; ------------------------------------------------------------------- ;; Copyright (c) 2011 Basho Technologies, Inc. All Rights Reserved. ;; ;; This file is provided to you under the Apache License, ;; Version 2.0 (the "License"); you may not use this file ;; except in compliance with the License. You may obtain ;; a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, ;; software distributed under the License is distributed on an ;; "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ;; KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations ;; under the License. ;; ;; ------------------------------------------------------------------- (in-ns 'knockbox.sets) (defn twop-minus-deletes [adds dels] (clojure.set/difference adds dels)) (deftype TwoPhaseSet [^IPersistentSet adds ^IPersistentSet dels] IPersistentSet (disjoin [this k] (if (contains? adds k) (TwoPhaseSet. adds (conj dels k)) ;; TODO: ;; should this return nil or this? this)) (cons [this k] (TwoPhaseSet. (conj adds k) dels)) (empty [this] (TwoPhaseSet. #{} #{})) (equiv [this other] (.equals this other)) (get [this k] (if (get dels k) nil (get adds k))) (seq [this] (seq (twop-minus-deletes adds dels))) (count [this] (count (seq this))) IObj (meta [this] (.meta ^IObj adds)) (withMeta [this m] (TwoPhaseSet. (.withMeta ^IObj adds m) dels)) Object (hashCode [this] (hash (twop-minus-deletes adds dels))) (equals [this other] (or (identical? this other) (and (instance? Set other) (let [^Set o (cast Set other)] (and (= (count this) (count o)) (every? #(contains? o %) (seq this))))))) (toString [this] (.toString (twop-minus-deletes adds dels))) Set (contains [this k] (boolean (get this k))) (containsAll [this ks] (every? identity (map #(contains? this %) ks))) (size [this] (count this)) (isEmpty [this] (= 0 (count this))) (toArray [this] (RT/seqToArray (seq this))) (toArray [this dest] (reduce (fn [idx item] (aset dest idx item) (inc idx)) 0, (seq this)) dest) ;; this is just here to mark ;; the object as serializable Serializable IFn (invoke [this k] (get this k)) java.lang.Iterable (iterator [this] (clojure.lang.SeqIterator. (seq this))) Resolvable (resolve [this other] (let [new-adds (clojure.set/union adds (.adds other)) new-dels (clojure.set/union dels (.dels other))] (TwoPhaseSet. new-adds new-dels))) (gc [this gc-max-seconds gc-max-items] this) cheshire.custom/JSONable (to-json [this jsongen] (let [m {:type "2p-set"} a (vec adds) r (vec dels) m (-> m (assoc :a a) (assoc :r r))] (.writeRaw jsongen (cheshire.core/generate-string m))))) (defn two-phase [] (TwoPhaseSet. #{} #{})) (defmethod knockbox.core/handle-json-structure "2p-set" ;TODO ;need to figure out ;how to deal with ;strings vs. keywords [obj] (let [a (set (map keyword (:a obj))) r (set (map keyword (:r obj)))] (TwoPhaseSet. a r))) (defmethod print-dup knockbox.sets.TwoPhaseSet [o w] (.write w (str "#=(" (.getName ^Class (class o)) ". " (.adds o) " " (.dels o) ")")))
100763
;; ------------------------------------------------------------------- ;; Copyright (c) 2011 <NAME>, Inc. All Rights Reserved. ;; ;; This file is provided to you under the Apache License, ;; Version 2.0 (the "License"); you may not use this file ;; except in compliance with the License. You may obtain ;; a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, ;; software distributed under the License is distributed on an ;; "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ;; KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations ;; under the License. ;; ;; ------------------------------------------------------------------- (in-ns 'knockbox.sets) (defn twop-minus-deletes [adds dels] (clojure.set/difference adds dels)) (deftype TwoPhaseSet [^IPersistentSet adds ^IPersistentSet dels] IPersistentSet (disjoin [this k] (if (contains? adds k) (TwoPhaseSet. adds (conj dels k)) ;; TODO: ;; should this return nil or this? this)) (cons [this k] (TwoPhaseSet. (conj adds k) dels)) (empty [this] (TwoPhaseSet. #{} #{})) (equiv [this other] (.equals this other)) (get [this k] (if (get dels k) nil (get adds k))) (seq [this] (seq (twop-minus-deletes adds dels))) (count [this] (count (seq this))) IObj (meta [this] (.meta ^IObj adds)) (withMeta [this m] (TwoPhaseSet. (.withMeta ^IObj adds m) dels)) Object (hashCode [this] (hash (twop-minus-deletes adds dels))) (equals [this other] (or (identical? this other) (and (instance? Set other) (let [^Set o (cast Set other)] (and (= (count this) (count o)) (every? #(contains? o %) (seq this))))))) (toString [this] (.toString (twop-minus-deletes adds dels))) Set (contains [this k] (boolean (get this k))) (containsAll [this ks] (every? identity (map #(contains? this %) ks))) (size [this] (count this)) (isEmpty [this] (= 0 (count this))) (toArray [this] (RT/seqToArray (seq this))) (toArray [this dest] (reduce (fn [idx item] (aset dest idx item) (inc idx)) 0, (seq this)) dest) ;; this is just here to mark ;; the object as serializable Serializable IFn (invoke [this k] (get this k)) java.lang.Iterable (iterator [this] (clojure.lang.SeqIterator. (seq this))) Resolvable (resolve [this other] (let [new-adds (clojure.set/union adds (.adds other)) new-dels (clojure.set/union dels (.dels other))] (TwoPhaseSet. new-adds new-dels))) (gc [this gc-max-seconds gc-max-items] this) cheshire.custom/JSONable (to-json [this jsongen] (let [m {:type "2p-set"} a (vec adds) r (vec dels) m (-> m (assoc :a a) (assoc :r r))] (.writeRaw jsongen (cheshire.core/generate-string m))))) (defn two-phase [] (TwoPhaseSet. #{} #{})) (defmethod knockbox.core/handle-json-structure "2p-set" ;TODO ;need to figure out ;how to deal with ;strings vs. keywords [obj] (let [a (set (map keyword (:a obj))) r (set (map keyword (:r obj)))] (TwoPhaseSet. a r))) (defmethod print-dup knockbox.sets.TwoPhaseSet [o w] (.write w (str "#=(" (.getName ^Class (class o)) ". " (.adds o) " " (.dels o) ")")))
true
;; ------------------------------------------------------------------- ;; Copyright (c) 2011 PI:NAME:<NAME>END_PI, Inc. All Rights Reserved. ;; ;; This file is provided to you under the Apache License, ;; Version 2.0 (the "License"); you may not use this file ;; except in compliance with the License. You may obtain ;; a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, ;; software distributed under the License is distributed on an ;; "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ;; KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations ;; under the License. ;; ;; ------------------------------------------------------------------- (in-ns 'knockbox.sets) (defn twop-minus-deletes [adds dels] (clojure.set/difference adds dels)) (deftype TwoPhaseSet [^IPersistentSet adds ^IPersistentSet dels] IPersistentSet (disjoin [this k] (if (contains? adds k) (TwoPhaseSet. adds (conj dels k)) ;; TODO: ;; should this return nil or this? this)) (cons [this k] (TwoPhaseSet. (conj adds k) dels)) (empty [this] (TwoPhaseSet. #{} #{})) (equiv [this other] (.equals this other)) (get [this k] (if (get dels k) nil (get adds k))) (seq [this] (seq (twop-minus-deletes adds dels))) (count [this] (count (seq this))) IObj (meta [this] (.meta ^IObj adds)) (withMeta [this m] (TwoPhaseSet. (.withMeta ^IObj adds m) dels)) Object (hashCode [this] (hash (twop-minus-deletes adds dels))) (equals [this other] (or (identical? this other) (and (instance? Set other) (let [^Set o (cast Set other)] (and (= (count this) (count o)) (every? #(contains? o %) (seq this))))))) (toString [this] (.toString (twop-minus-deletes adds dels))) Set (contains [this k] (boolean (get this k))) (containsAll [this ks] (every? identity (map #(contains? this %) ks))) (size [this] (count this)) (isEmpty [this] (= 0 (count this))) (toArray [this] (RT/seqToArray (seq this))) (toArray [this dest] (reduce (fn [idx item] (aset dest idx item) (inc idx)) 0, (seq this)) dest) ;; this is just here to mark ;; the object as serializable Serializable IFn (invoke [this k] (get this k)) java.lang.Iterable (iterator [this] (clojure.lang.SeqIterator. (seq this))) Resolvable (resolve [this other] (let [new-adds (clojure.set/union adds (.adds other)) new-dels (clojure.set/union dels (.dels other))] (TwoPhaseSet. new-adds new-dels))) (gc [this gc-max-seconds gc-max-items] this) cheshire.custom/JSONable (to-json [this jsongen] (let [m {:type "2p-set"} a (vec adds) r (vec dels) m (-> m (assoc :a a) (assoc :r r))] (.writeRaw jsongen (cheshire.core/generate-string m))))) (defn two-phase [] (TwoPhaseSet. #{} #{})) (defmethod knockbox.core/handle-json-structure "2p-set" ;TODO ;need to figure out ;how to deal with ;strings vs. keywords [obj] (let [a (set (map keyword (:a obj))) r (set (map keyword (:r obj)))] (TwoPhaseSet. a r))) (defmethod print-dup knockbox.sets.TwoPhaseSet [o w] (.write w (str "#=(" (.getName ^Class (class o)) ". " (.adds o) " " (.dels o) ")")))
[ { "context": "y-policy.com/\n ; See also: https://github.com/pedestal/pedestal/issues/499\n ;::http/secure-headers {:c", "end": 1517, "score": 0.9996326565742493, "start": 1509, "tag": "USERNAME", "value": "pedestal" }, { "context": "in_provider\n ::http/type :jetty\n ::http/host \"0.0.0.0\"\n ::http/port 8080\n ; Options to pass to the ", "end": 2190, "score": 0.9991437792778015, "start": 2183, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": "ystore \"test/hp/keystore.jks\"\n ;:key-password \"password\"\n ;:ssl-port 8443\n :ssl? false\n ; Altern", "end": 2382, "score": 0.9806092977523804, "start": 2374, "tag": "PASSWORD", "value": "password" } ]
src/name_service/delivery/server/service.clj
IwoHerka/name-microservice
0
(ns name-service.delivery.server.service "Pedestal server config." (:require [io.pedestal.http :as http] [name-service.delivery.server.append :as append] [name-service.delivery.server.delete :as delete] [name-service.delivery.server.get :as get] [name-service.delivery.server.update :as update])) (def routes #{["/:key" :get get/dispatch :route-name :get-binding] ["/" :post append/dispatch :route-name :post-binding] ["/" :patch update/dispatch :route-name :patch-binding] ["/" :delete delete/dispatch :route-name :delete-binding]}) ; Consumed by name-service.server/create-server ; See http/default-interceptors for additional options you can configure (def service {:env :prod ; You can bring your own non-default interceptors. Make ; sure you include routing and set it up right for ; dev-mode. If you do, many other keys for configuring ; default interceptors will be ignored. ; ::http/interceptors [] ::http/routes routes ; Uncomment next line to enable CORS support, add ; string(s) specifying scheme, host and port for ; allowed source(s): ; ; "http://localhost:8080" ; ;::http/allowed-origins ["scheme://host:port"] ; Tune the Secure Headers ; and specifically the Content Security Policy appropriate to your service/application ; For more information, see: https://content-security-policy.com/ ; See also: https://github.com/pedestal/pedestal/issues/499 ;::http/secure-headers {:content-security-policy-settings {:object-src "'none'" ; :script-src "'unsafe-inline' 'unsafe-eval' 'strict-dynamic' https: http:" ; :frame-ancestors "'none'"}} ; Root for resource interceptor that is available by default. ::http/resource-path "/public" ; Either :jetty, :immutant or :tomcat (see comments in project.clj) ; This can also be your own chain provider/server-fn -- http://pedestal.io/reference/architecture-overview#_chain_provider ::http/type :jetty ::http/host "0.0.0.0" ::http/port 8080 ; Options to pass to the container (Jetty) ::http/container-options {:h2c? true :h2? false ;:keystore "test/hp/keystore.jks" ;:key-password "password" ;:ssl-port 8443 :ssl? false ; Alternatively, You can specify you're own Jetty HTTPConfiguration ; via the `:io.pedestal.http.jetty/http-configuration` container option. ;:io.pedestal.http.jetty/http-configuration (org.eclipse.jetty.server.HttpConfiguration.) }})
44231
(ns name-service.delivery.server.service "Pedestal server config." (:require [io.pedestal.http :as http] [name-service.delivery.server.append :as append] [name-service.delivery.server.delete :as delete] [name-service.delivery.server.get :as get] [name-service.delivery.server.update :as update])) (def routes #{["/:key" :get get/dispatch :route-name :get-binding] ["/" :post append/dispatch :route-name :post-binding] ["/" :patch update/dispatch :route-name :patch-binding] ["/" :delete delete/dispatch :route-name :delete-binding]}) ; Consumed by name-service.server/create-server ; See http/default-interceptors for additional options you can configure (def service {:env :prod ; You can bring your own non-default interceptors. Make ; sure you include routing and set it up right for ; dev-mode. If you do, many other keys for configuring ; default interceptors will be ignored. ; ::http/interceptors [] ::http/routes routes ; Uncomment next line to enable CORS support, add ; string(s) specifying scheme, host and port for ; allowed source(s): ; ; "http://localhost:8080" ; ;::http/allowed-origins ["scheme://host:port"] ; Tune the Secure Headers ; and specifically the Content Security Policy appropriate to your service/application ; For more information, see: https://content-security-policy.com/ ; See also: https://github.com/pedestal/pedestal/issues/499 ;::http/secure-headers {:content-security-policy-settings {:object-src "'none'" ; :script-src "'unsafe-inline' 'unsafe-eval' 'strict-dynamic' https: http:" ; :frame-ancestors "'none'"}} ; Root for resource interceptor that is available by default. ::http/resource-path "/public" ; Either :jetty, :immutant or :tomcat (see comments in project.clj) ; This can also be your own chain provider/server-fn -- http://pedestal.io/reference/architecture-overview#_chain_provider ::http/type :jetty ::http/host "0.0.0.0" ::http/port 8080 ; Options to pass to the container (Jetty) ::http/container-options {:h2c? true :h2? false ;:keystore "test/hp/keystore.jks" ;:key-password "<PASSWORD>" ;:ssl-port 8443 :ssl? false ; Alternatively, You can specify you're own Jetty HTTPConfiguration ; via the `:io.pedestal.http.jetty/http-configuration` container option. ;:io.pedestal.http.jetty/http-configuration (org.eclipse.jetty.server.HttpConfiguration.) }})
true
(ns name-service.delivery.server.service "Pedestal server config." (:require [io.pedestal.http :as http] [name-service.delivery.server.append :as append] [name-service.delivery.server.delete :as delete] [name-service.delivery.server.get :as get] [name-service.delivery.server.update :as update])) (def routes #{["/:key" :get get/dispatch :route-name :get-binding] ["/" :post append/dispatch :route-name :post-binding] ["/" :patch update/dispatch :route-name :patch-binding] ["/" :delete delete/dispatch :route-name :delete-binding]}) ; Consumed by name-service.server/create-server ; See http/default-interceptors for additional options you can configure (def service {:env :prod ; You can bring your own non-default interceptors. Make ; sure you include routing and set it up right for ; dev-mode. If you do, many other keys for configuring ; default interceptors will be ignored. ; ::http/interceptors [] ::http/routes routes ; Uncomment next line to enable CORS support, add ; string(s) specifying scheme, host and port for ; allowed source(s): ; ; "http://localhost:8080" ; ;::http/allowed-origins ["scheme://host:port"] ; Tune the Secure Headers ; and specifically the Content Security Policy appropriate to your service/application ; For more information, see: https://content-security-policy.com/ ; See also: https://github.com/pedestal/pedestal/issues/499 ;::http/secure-headers {:content-security-policy-settings {:object-src "'none'" ; :script-src "'unsafe-inline' 'unsafe-eval' 'strict-dynamic' https: http:" ; :frame-ancestors "'none'"}} ; Root for resource interceptor that is available by default. ::http/resource-path "/public" ; Either :jetty, :immutant or :tomcat (see comments in project.clj) ; This can also be your own chain provider/server-fn -- http://pedestal.io/reference/architecture-overview#_chain_provider ::http/type :jetty ::http/host "0.0.0.0" ::http/port 8080 ; Options to pass to the container (Jetty) ::http/container-options {:h2c? true :h2? false ;:keystore "test/hp/keystore.jks" ;:key-password "PI:PASSWORD:<PASSWORD>END_PI" ;:ssl-port 8443 :ssl? false ; Alternatively, You can specify you're own Jetty HTTPConfiguration ; via the `:io.pedestal.http.jetty/http-configuration` container option. ;:io.pedestal.http.jetty/http-configuration (org.eclipse.jetty.server.HttpConfiguration.) }})
[ { "context": "crapes taken often enough. E-mail <a href='mailto:kentilton@gmail.com'>Kenny</a> if they seem stopped.\"\n \"RFEs welc", "end": 2239, "score": 0.9999200105667114, "start": 2220, "tag": "EMAIL", "value": "kentilton@gmail.com" }, { "context": "ough. E-mail <a href='mailto:kentilton@gmail.com'>Kenny</a> if they seem stopped.\"\n \"RFEs welcome and", "end": 2246, "score": 0.8421974182128906, "start": 2241, "tag": "NAME", "value": "Kenny" }, { "context": "ome and can be raised <a href='https://github.com/kennytilton/whoshiring/issues'>here</a>. \"\n \"Built with <", "end": 2350, "score": 0.9995883703231812, "start": 2339, "tag": "USERNAME", "value": "kennytilton" }, { "context": ">. \"\n \"Built with <a href='https://github.com/kennytilton/matrix/blob/master/js/matrix/readme.md'>Matrix In", "end": 2438, "score": 0.9997261166572571, "start": 2427, "tag": "USERNAME", "value": "kennytilton" }, { "context": "ain <a href='https://news.ycombinator.com/user?id=kennytilton'>kennytilton</a>'s.\"\n \"Graphic design by <a h", "end": 2696, "score": 0.9981580972671509, "start": 2685, "tag": "USERNAME", "value": "kennytilton" }, { "context": "c design by <a href='https://www.mloboscoart.com'>Michael Lobosco</a>.\"]))\n\n(defn app-banner []\n (let [helping (r/", "end": 2795, "score": 0.9683054089546204, "start": 2780, "tag": "NAME", "value": "Michael Lobosco" } ]
src/aghire/core.cljs
kennytilton/hiringagency
0
(ns aghire.core (:require [reagent.core :as r] [aghire.utility :as utl] [aghire.sorting :as sort] [aghire.month-loader :as mld] [aghire.month-loader-ui :as mlv] [aghire.job-list :as jlst] [aghire.memo :as unt] [aghire.job-list-control-bar :as jlcb] [aghire.regex-ui :as rgxui] [aghire.filtering :as flt])) (declare mount-root landing-page app-banner) ;;; --- main ------------------------------------------------ (defn init! [] (sort/sort-initialize) (unt/job-memos-load) ;; annotations of several kinds I make per story (mld/app-month-startup) ;; load the latest month be default (mount-root)) (defn mount-root [] (r/render [landing-page] (.getElementById js/document "app"))) ;; ------------------------- ;; Landing-page (defn landing-page [] [:div [app-banner] [:div {:style {:margin 0 :background "#ffb57d"}} ;; we default to the current month and let the user explore ;; a couple of earlier months. Left as an exercise is loading ;; all the months and not restricting search by month boundary. [mlv/pick-a-month] ;; A hidden iframe used to load HN pages for scraping. ;; Left as an exercise is scraping once in a utility to ;; generate EDN used by this app -- except HN has an ;; API on the way that will elim scraping altogether! [mld/job-listing-loader] ;; the control panel... [:div {:style {:background "#ffb57d"}} [utl/open-shut-case :show-filters "Filters" flt/mk-title-selects flt/mk-user-selects] [rgxui/mk-regex-search] [sort/sort-bar] [jlcb/job-listing-control-bar]] ;; the jobs... [jlst/job-list]]]) ;;; --- app help -------------------------------------------------------------- ;;; We sneak in the banner here instead of breaking it out into its own file. (def app-help-entry (map identity ["Click any job header to show or hide the full listing." "Double-click job description to open listing on HN in new tab." "All filters are ANDed except as you direct within RegExp fields." "Your edits are kept in local storage, so stick to one browser." "Works off page scrapes taken often enough. E-mail <a href='mailto:kentilton@gmail.com'>Kenny</a> if they seem stopped." "RFEs welcome and can be raised <a href='https://github.com/kennytilton/whoshiring/issues'>here</a>. " "Built with <a href='https://github.com/kennytilton/matrix/blob/master/js/matrix/readme.md'>Matrix Inside</a>&trade;." "This page is not affiliated with Hacker News, but..." "..thanks to the HN crew for their assistance. All screw-ups remain <a href='https://news.ycombinator.com/user?id=kennytilton'>kennytilton</a>'s." "Graphic design by <a href='https://www.mloboscoart.com'>Michael Lobosco</a>."])) (defn app-banner [] (let [helping (r/atom false)] (fn [] [:div {:style {:background "PAPAYAWHIP"}} [:header [:div.about { :title "Usage hints, and credit where due." :on-click #(swap! helping not)} "Pro Tips"] [:div.headermain [:span.askhn "Ask HN:"] [:span.who "Who Is Hiring?"]]] [utl/help-list app-help-entry helping]])))
103144
(ns aghire.core (:require [reagent.core :as r] [aghire.utility :as utl] [aghire.sorting :as sort] [aghire.month-loader :as mld] [aghire.month-loader-ui :as mlv] [aghire.job-list :as jlst] [aghire.memo :as unt] [aghire.job-list-control-bar :as jlcb] [aghire.regex-ui :as rgxui] [aghire.filtering :as flt])) (declare mount-root landing-page app-banner) ;;; --- main ------------------------------------------------ (defn init! [] (sort/sort-initialize) (unt/job-memos-load) ;; annotations of several kinds I make per story (mld/app-month-startup) ;; load the latest month be default (mount-root)) (defn mount-root [] (r/render [landing-page] (.getElementById js/document "app"))) ;; ------------------------- ;; Landing-page (defn landing-page [] [:div [app-banner] [:div {:style {:margin 0 :background "#ffb57d"}} ;; we default to the current month and let the user explore ;; a couple of earlier months. Left as an exercise is loading ;; all the months and not restricting search by month boundary. [mlv/pick-a-month] ;; A hidden iframe used to load HN pages for scraping. ;; Left as an exercise is scraping once in a utility to ;; generate EDN used by this app -- except HN has an ;; API on the way that will elim scraping altogether! [mld/job-listing-loader] ;; the control panel... [:div {:style {:background "#ffb57d"}} [utl/open-shut-case :show-filters "Filters" flt/mk-title-selects flt/mk-user-selects] [rgxui/mk-regex-search] [sort/sort-bar] [jlcb/job-listing-control-bar]] ;; the jobs... [jlst/job-list]]]) ;;; --- app help -------------------------------------------------------------- ;;; We sneak in the banner here instead of breaking it out into its own file. (def app-help-entry (map identity ["Click any job header to show or hide the full listing." "Double-click job description to open listing on HN in new tab." "All filters are ANDed except as you direct within RegExp fields." "Your edits are kept in local storage, so stick to one browser." "Works off page scrapes taken often enough. E-mail <a href='mailto:<EMAIL>'><NAME></a> if they seem stopped." "RFEs welcome and can be raised <a href='https://github.com/kennytilton/whoshiring/issues'>here</a>. " "Built with <a href='https://github.com/kennytilton/matrix/blob/master/js/matrix/readme.md'>Matrix Inside</a>&trade;." "This page is not affiliated with Hacker News, but..." "..thanks to the HN crew for their assistance. All screw-ups remain <a href='https://news.ycombinator.com/user?id=kennytilton'>kennytilton</a>'s." "Graphic design by <a href='https://www.mloboscoart.com'><NAME></a>."])) (defn app-banner [] (let [helping (r/atom false)] (fn [] [:div {:style {:background "PAPAYAWHIP"}} [:header [:div.about { :title "Usage hints, and credit where due." :on-click #(swap! helping not)} "Pro Tips"] [:div.headermain [:span.askhn "Ask HN:"] [:span.who "Who Is Hiring?"]]] [utl/help-list app-help-entry helping]])))
true
(ns aghire.core (:require [reagent.core :as r] [aghire.utility :as utl] [aghire.sorting :as sort] [aghire.month-loader :as mld] [aghire.month-loader-ui :as mlv] [aghire.job-list :as jlst] [aghire.memo :as unt] [aghire.job-list-control-bar :as jlcb] [aghire.regex-ui :as rgxui] [aghire.filtering :as flt])) (declare mount-root landing-page app-banner) ;;; --- main ------------------------------------------------ (defn init! [] (sort/sort-initialize) (unt/job-memos-load) ;; annotations of several kinds I make per story (mld/app-month-startup) ;; load the latest month be default (mount-root)) (defn mount-root [] (r/render [landing-page] (.getElementById js/document "app"))) ;; ------------------------- ;; Landing-page (defn landing-page [] [:div [app-banner] [:div {:style {:margin 0 :background "#ffb57d"}} ;; we default to the current month and let the user explore ;; a couple of earlier months. Left as an exercise is loading ;; all the months and not restricting search by month boundary. [mlv/pick-a-month] ;; A hidden iframe used to load HN pages for scraping. ;; Left as an exercise is scraping once in a utility to ;; generate EDN used by this app -- except HN has an ;; API on the way that will elim scraping altogether! [mld/job-listing-loader] ;; the control panel... [:div {:style {:background "#ffb57d"}} [utl/open-shut-case :show-filters "Filters" flt/mk-title-selects flt/mk-user-selects] [rgxui/mk-regex-search] [sort/sort-bar] [jlcb/job-listing-control-bar]] ;; the jobs... [jlst/job-list]]]) ;;; --- app help -------------------------------------------------------------- ;;; We sneak in the banner here instead of breaking it out into its own file. (def app-help-entry (map identity ["Click any job header to show or hide the full listing." "Double-click job description to open listing on HN in new tab." "All filters are ANDed except as you direct within RegExp fields." "Your edits are kept in local storage, so stick to one browser." "Works off page scrapes taken often enough. E-mail <a href='mailto:PI:EMAIL:<EMAIL>END_PI'>PI:NAME:<NAME>END_PI</a> if they seem stopped." "RFEs welcome and can be raised <a href='https://github.com/kennytilton/whoshiring/issues'>here</a>. " "Built with <a href='https://github.com/kennytilton/matrix/blob/master/js/matrix/readme.md'>Matrix Inside</a>&trade;." "This page is not affiliated with Hacker News, but..." "..thanks to the HN crew for their assistance. All screw-ups remain <a href='https://news.ycombinator.com/user?id=kennytilton'>kennytilton</a>'s." "Graphic design by <a href='https://www.mloboscoart.com'>PI:NAME:<NAME>END_PI</a>."])) (defn app-banner [] (let [helping (r/atom false)] (fn [] [:div {:style {:background "PAPAYAWHIP"}} [:header [:div.about { :title "Usage hints, and credit where due." :on-click #(swap! helping not)} "Pro Tips"] [:div.headermain [:span.askhn "Ask HN:"] [:span.who "Who Is Hiring?"]]] [utl/help-list app-help-entry helping]])))
[ { "context": " :value 1}]}))\n\n(defcard \"Adam: Compulsive Hacker\"\n {:events [{:event :pre-star", "end": 4449, "score": 0.9247944355010986, "start": 4445, "tag": "NAME", "value": "Adam" }, { "context": "tart-next-phase state side eid))))}]})\n\n(defcard \"Akiko Nisei: Head Case\"\n {:events [{:event :breach-server\n ", "end": 7347, "score": 0.9852975010871887, "start": 7336, "tag": "NAME", "value": "Akiko Nisei" }, { "context": " (effect-completed eid))}}}]})\n\n(defcard \"Alice Merchant: Clan Agitator\"\n {:events [{:event :successful-r", "end": 7733, "score": 0.9326393604278564, "start": 7719, "tag": "NAME", "value": "Alice Merchant" }, { "context": "t-completed eid))}}}]})\n\n(defcard \"Alice Merchant: Clan Agitator\"\n {:events [{:event :successful-run\n ", "end": 7739, "score": 0.5417999625205994, "start": 7735, "tag": "NAME", "value": "Clan" }, { "context": "eted eid))}}}]})\n\n(defcard \"Alice Merchant: Clan Agitator\"\n {:events [{:event :successful-run\n ", "end": 7744, "score": 0.5304678082466125, "start": 7741, "tag": "NAME", "value": "git" }, { "context": "{:unboostable true :card card}))))}]})\n\n(defcard \"Armand \\\"Geist\\\" Walker: Tech Lord\"\n {:events [{:event ", "end": 10406, "score": 0.9989504814147949, "start": 10400, "tag": "NAME", "value": "Armand" }, { "context": "able true :card card}))))}]})\n\n(defcard \"Armand \\\"Geist\\\" Walker: Tech Lord\"\n {:events [{:event :runner-", "end": 10414, "score": 0.9460078477859497, "start": 10409, "tag": "NAME", "value": "Geist" }, { "context": "ue :card card}))))}]})\n\n(defcard \"Armand \\\"Geist\\\" Walker: Tech Lord\"\n {:events [{:event :runner-trash\n ", "end": 10423, "score": 0.9462465047836304, "start": 10417, "tag": "NAME", "value": "Walker" }, { "context": " card nil)))}]})\n\n(defcard \"Ayla \\\"Bios\\\" Rahim: Simulant Specialist\"\n {:abilitie", "end": 11872, "score": 0.9968374967575073, "start": 11868, "tag": "NAME", "value": "Ayla" }, { "context": " card nil)))}]})\n\n(defcard \"Ayla \\\"Bios\\\" Rahim: Simulant Specialist\"\n {:abilities [{:la", "end": 11879, "score": 0.817822277545929, "start": 11875, "tag": "NAME", "value": "Bios" }, { "context": " card nil)))}]})\n\n(defcard \"Ayla \\\"Bios\\\" Rahim: Simulant Specialist\"\n {:abilities [{:label \"Add", "end": 11887, "score": 0.8289572596549988, "start": 11882, "tag": "NAME", "value": "Rahim" }, { "context": "eid (rez-cost state side target)))}]})\n\n(defcard \"Boris \\\"Syfr\\\" Kovac: Crafty Veteran\"\n {:events [{:event :pre-start-g", "end": 16141, "score": 0.899099588394165, "start": 16121, "tag": "NAME", "value": "Boris \\\"Syfr\\\" Kovac" }, { "context": " :effect flip-effect}]}))\n\n(defcard \"Edward Kim: Humanity's Hammer\"\n {:events [{:event :access\n ", "end": 21990, "score": 0.9997245669364929, "start": 21980, "tag": "NAME", "value": "Edward Kim" }, { "context": " (str \"uses Edward Kim: Humanity's Hammer to\"\n ", "end": 22682, "score": 0.9973061680793762, "start": 22672, "tag": "NAME", "value": "Edward Kim" }, { "context": " :effect (effect (draw eid 1))}]})\n\n(defcard \"Freedom Khumalo: Crypto-Anarchist\"\n {:interactions\n {:access-a", "end": 23576, "score": 0.996638298034668, "start": 23561, "tag": "NAME", "value": "Freedom Khumalo" }, { "context": "advance-counter 1 {:placed true}))}]})\n\n(defcard \"Gabriel Santiago: Consummate Professional\"\n {:events [{:event :su", "end": 26094, "score": 0.9998576045036316, "start": 26078, "tag": "NAME", "value": "Gabriel Santiago" }, { "context": " :effect (effect (update-all-ice))})\n\n(defcard \"Harishchandra Ent.: Where You're the Star\"\n (letfn [(format-gr", "end": 30888, "score": 0.9800034165382385, "start": 30875, "tag": "NAME", "value": "Harishchandra" }, { "context": " (gain :runner :agenda-point-req 1))})\n\n(defcard \"Hayley Kaplan: Universal Scholar\"\n {:events [{:event :runner-i", "end": 32900, "score": 0.9996827244758606, "start": 32887, "tag": "NAME", "value": "Hayley Kaplan" }, { "context": "\n card nil))}]})\n\n(defcard \"Hoshiko Shiro: Untold Protagonist\"\n (let [flip-effect (req (up", "end": 34520, "score": 0.9993041753768921, "start": 34507, "tag": "NAME", "value": "Hoshiko Shiro" }, { "context": " (assoc inf :event :agenda-stolen)])})\n\n(defcard \"Jamie \\\"Bzzz\\\" Micken: Techno Savant\"\n {:events [{:eve", "end": 40152, "score": 0.9941338896751404, "start": 40147, "tag": "NAME", "value": "Jamie" }, { "context": " :req (req (and (has-most-faction? state :runner \"Shaper\")\n (first-event? state", "end": 40367, "score": 0.9445140957832336, "start": 40361, "tag": "USERNAME", "value": "Shaper" }, { "context": " :effect (effect (draw eid 1))}]})\n\n(defcard \"Jemison Astronautics: Sacrifice. Audacity. Success.\"\n {:events [{:", "end": 40603, "score": 0.7626761198043823, "start": 40586, "tag": "NAME", "value": "Jemison Astronaut" }, { "context": "e}))})\n card nil))}]})\n\n(defcard \"Jesminder Sareen: Girl Behind the Curtain\"\n {:flags {:forced-to-a", "end": 41405, "score": 0.9991130828857422, "start": 41389, "tag": "NAME", "value": "Jesminder Sareen" }, { "context": " {:cost-bonus -1}))}]})\n\n(defcard \"Kate \\\"Mac\\\" McCaffrey: Digital Tinker\"\n ;; Effect marks Kate's ability", "end": 48920, "score": 0.7118532061576843, "start": 48911, "tag": "NAME", "value": "McCaffrey" }, { "context": "auto-lat \"Lat: Ethical Freelancer\")]})\n\n(defcard \"Leela Patel: Trained Pragmatist\"\n (let [leela {:interactive ", "end": 53260, "score": 0.9997422099113464, "start": 53249, "tag": "NAME", "value": "Leela Patel" }, { "context": " :value true}]}))\n\n(defcard \"Mti Mwekundu: Life Improved\"\n {:events [{:event :a", "end": 59452, "score": 0.6845613121986389, "start": 59451, "tag": "NAME", "value": "M" }, { "context": " card nil)))}]})\n\n(defcard \"Nasir Meidan: Cyber Explorer\"\n {:events [{:event :approach-ic", "end": 62029, "score": 0.9994135499000549, "start": 62017, "tag": "NAME", "value": "Nasir Meidan" }, { "context": "its state :runner eid cost)))}])))}]})\n\n(defcard \"Nathaniel \\\"Gnat\\\" Hall: One-of-a-Kind\"\n (let [ability {:l", "end": 63013, "score": 0.9992358684539795, "start": 63004, "tag": "NAME", "value": "Nathaniel" }, { "context": "unner eid cost)))}])))}]})\n\n(defcard \"Nathaniel \\\"Gnat\\\" Hall: One-of-a-Kind\"\n (let [ability {:label \"G", "end": 63020, "score": 0.950468897819519, "start": 63016, "tag": "NAME", "value": "Gnat" }, { "context": "ase, there should be no gameplay implications. -nbkelly, 2022\n (register-events\n", "end": 66928, "score": 0.5583692789077759, "start": 66923, "tag": "NAME", "value": "kelly" }, { "context": "ffect-completed state side eid))))}]})\n\n(defcard \"Nero Severn: Information Broker\"\n {:events [{:event :encount", "end": 67459, "score": 0.7986711859703064, "start": 67448, "tag": "NAME", "value": "Nero Severn" }, { "context": "d target {:unpreventable true}))}}}]})\n\n(defcard \"Omar Keung: Conspiracy Theorist\"\n {:abilities [{:cost [:cli", "end": 72069, "score": 0.7608017325401306, "start": 72059, "tag": "NAME", "value": "Omar Keung" }, { "context": "repeatable false}) :once :per-turn)]})\n\n(defcard \"Reina Roja: Freedom Fighter\"\n (letfn [(not-triggered? [stat", "end": 73676, "score": 0.9831417798995972, "start": 73666, "tag": "NAME", "value": "Reina Roja" }, { "context": "card context)) \" by 1 [Credits]\")}]}))\n\n(defcard \"René \\\"Loup\\\" Arcemont: Party Animal\"\n {:events [{:ev", "end": 74312, "score": 0.9948056936264038, "start": 74308, "tag": "NAME", "value": "René" }, { "context": "ntext)) \" by 1 [Credits]\")}]}))\n\n(defcard \"René \\\"Loup\\\" Arcemont: Party Animal\"\n {:events [{:event :ru", "end": 74319, "score": 0.809303343296051, "start": 74315, "tag": "NAME", "value": "Loup" }, { "context": ") \" by 1 [Credits]\")}]}))\n\n(defcard \"René \\\"Loup\\\" Arcemont: Party Animal\"\n {:events [{:event :runner-trash\n", "end": 74330, "score": 0.7716748714447021, "start": 74322, "tag": "NAME", "value": "Arcemont" }, { "context": "ain-credits state :runner eid 1)))}]})\n\n(defcard \"Rielle \\\"Kit\\\" Peddler: Transhuman\"\n {:events [{:event ", "end": 74860, "score": 0.9963805079460144, "start": 74854, "tag": "NAME", "value": "Rielle" }, { "context": "ts state :runner eid 1)))}]})\n\n(defcard \"Rielle \\\"Kit\\\" Peddler: Transhuman\"\n {:events [{:event :encou", "end": 74866, "score": 0.43705224990844727, "start": 74863, "tag": "NAME", "value": "Kit" }, { "context": "ate :runner eid 1)))}]})\n\n(defcard \"Rielle \\\"Kit\\\" Peddler: Transhuman\"\n {:events [{:event :encounter-ice\n ", "end": 74876, "score": 0.8135685920715332, "start": 74869, "tag": "NAME", "value": "Peddler" }, { "context": " :value \"Code Gate\"})))}]})\n\n(defcard \"Saraswati Mnemonics: Endless Exploration\"\n (letfn [(ins", "end": 75481, "score": 0.7042718529701233, "start": 75475, "tag": "NAME", "value": "Sarasw" }, { "context": "[(set-autoresolve :auto-sso \"SSO\")]}))\n\n(defcard \"Steve Cambridge: Master Grifter\"\n {:events [{:event :successful-", "end": 82760, "score": 0.9991564750671387, "start": 82745, "tag": "NAME", "value": "Steve Cambridge" }, { "context": " (shuffle! :corp :deck))}]})\n\n(defcard \"Sunny Lebeau: Security Specialist\"\n ;; No special implementat", "end": 85565, "score": 0.9997172355651855, "start": 85553, "tag": "NAME", "value": "Sunny Lebeau" }, { "context": "state (:card context)) :agenda 1))}]})\n\n(defcard \"Valencia Estevez: The Angel of Cayambe\"\n {:events [{:event :pre-s", "end": 91663, "score": 0.94428551197052, "start": 91647, "tag": "NAME", "value": "Valencia Estevez" }, { "context": "rigger-event :searched-stack nil))}]})\n\n(defcard \"Zahya Sadeghi: Versatile Smuggler\"\n {:events [{:event :run-end", "end": 94681, "score": 0.9831981658935547, "start": 94668, "tag": "NAME", "value": "Zahya Sadeghi" } ]
src/clj/game/cards/identities.clj
lf94/netrunner
0
(ns game.cards.identities (:require [game.core :refer :all] [game.utils :refer :all] [jinteki.utils :refer :all] [clojure.string :as string])) ;;; Helper functions for Draft cards (def draft-points-target "Set each side's agenda points target at 6, per draft format rules" (req (swap! state assoc-in [:runner :agenda-point-req] 6) (swap! state assoc-in [:corp :agenda-point-req] 6))) (defn- has-most-faction? "Checks if the faction has a plurality of rezzed / installed cards" [state side fc] (let [card-list (all-active-installed state side) faction-freq (frequencies (map :faction card-list)) reducer (fn [{:keys [max-count] :as acc} faction count] (cond ;; Has plurality update best-faction (> count max-count) {:max-count count :max-faction faction} ;; Lost plurality (= count max-count) (dissoc acc :max-faction) ;; Count is not more, do not change the accumulator map :else acc)) best-faction (:max-faction (reduce-kv reducer {:max-count 0 :max-faction nil} faction-freq))] (= fc best-faction))) ;; Card definitions (defcard "419: Amoral Scammer" {:events [{:event :corp-install :async true :req (req (and (first-event? state :corp :corp-install) (pos? (:turn @state)) (not (rezzed? (:card context))) (not (#{:rezzed-no-cost :rezzed-no-rez-cost :rezzed :face-up} (:install-state context))))) :waiting-prompt "Runner to choose an option" :effect (effect (continue-ability {:optional {:prompt "Expose installed card unless Corp pays 1 [Credits]?" :player :runner :autoresolve (get-autoresolve :auto-419) :no-ability {:effect (req (clear-wait-prompt state :corp))} :yes-ability {:async true :effect (req (if (not (can-pay? state :corp eid card nil :credit 1)) (do (toast state :corp "Cannot afford to pay 1 [Credit] to block card exposure" "info") (expose state :runner eid (:card context))) (continue-ability state side {:optional {:waiting-prompt "Corp to choose an option" :prompt "Pay 1 [Credits] to prevent exposure of installed card?" :player :corp :no-ability {:async true :effect (effect (expose :runner eid (:card context)))} :yes-ability {:async true :effect (req (wait-for (pay state :corp (make-eid state eid) card [:credit 1]) (system-msg state :corp (str (:msg async-result) " to prevent " " card from being exposed")) (effect-completed state side eid)))}}} card targets)))}}} card targets))}] :abilities [(set-autoresolve :auto-419 "419")]}) (defcard "Acme Consulting: The Truth You Need" (letfn [(outermost? [state ice] (let [server-ice (:ices (card->server state ice))] (same-card? ice (last server-ice))))] {:constant-effects [{:type :tags :req (req (and (get-current-encounter state) (rezzed? current-ice) (outermost? state current-ice))) :value 1}]})) (defcard "Adam: Compulsive Hacker" {:events [{:event :pre-start-game :req (req (= side :runner)) :async true :waiting-prompt "Runner to make a decision" :effect (req (let [directives (->> (server-cards) (filter #(has-subtype? % "Directive")) (map make-card) (map #(assoc % :zone [:play-area])) (into []))] ;; Add directives to :play-area - assumed to be empty (swap! state assoc-in [:runner :play-area] directives) (continue-ability state side {:prompt (str "Choose 3 starting directives") :choices {:max 3 :all true :card #(and (runner? %) (in-play-area? %))} :effect (req (doseq [c targets] (runner-install state side (make-eid state eid) c {:ignore-all-cost true :custom-message (fn [_] (str "starts with " (:title c) " in play"))})) (swap! state assoc-in [:runner :play-area] []))} card nil)))}]}) (defcard "AgInfusion: New Miracles for a New World" {:abilities [{:label "Trash a piece of ice to choose another server- the runner is now running that server" :once :per-turn :async true :req (req (and run (= :approach-ice (:phase run)) (not (rezzed? current-ice)))) :prompt "Choose another server and redirect the run to its outermost position" :choices (req (cancellable (remove #{(-> @state :run :server central->name)} servers))) :msg (msg "trash the approached piece of ice. The Runner is now running on " target) :effect (req (let [dest (server->zone state target) ice (count (get-in corp (conj dest :ices))) phase (if (pos? ice) :encounter-ice :movement)] (wait-for (trash state side (make-eid state eid) current-ice {:unpreventable true}) (redirect-run state side target phase) (start-next-phase state side eid))))}]}) (defcard "Akiko Nisei: Head Case" {:events [{:event :breach-server :interactive (req true) :psi {:req (req (= target :rd)) :player :runner :equal {:msg "access 1 additional card" :effect (effect (access-bonus :rd 1) (effect-completed eid))}}}]}) (defcard "Alice Merchant: Clan Agitator" {:events [{:event :successful-run :interactive (req true) :req (req (and (= :archives (target-server context)) (first-successful-run-on-server? state :archives) (not-empty (:hand corp)))) :waiting-prompt "Corp to make a decision" :prompt "Choose a card in HQ to discard" :player :corp :choices {:all true :card #(and (in-hand? %) (corp? %))} :msg "force the Corp to trash 1 card from HQ" :async true :effect (effect (trash :corp eid target nil))}]}) (defcard "Andromeda: Dispossessed Ristie" {:events [{:event :pre-start-game :req (req (= side :runner)) :async true :effect (effect (draw eid 4 {:suppress-event true}))}] :mulligan (effect (draw eid 4 {:suppress-event true}))}) (defcard "Apex: Invasive Predator" (let [ability {:prompt "Choose a card to install facedown" :label "Install a card facedown (start of turn)" :once :per-turn :choices {:max 1 :card #(and (runner? %) (in-hand? %))} :req (req (and (pos? (count (:hand runner))) (:runner-phase-12 @state))) :async true :msg "install a card facedown" :effect (effect (runner-install (assoc eid :source card :source-type :runner-install) target {:facedown true :no-msg true}))}] {:implementation "Install restriction not enforced" :events [(assoc ability :event :runner-turn-begins)] :flags {:runner-phase-12 (req true)} :abilities [ability]})) (defcard "Argus Security: Protection Guaranteed" {:events [{:event :agenda-stolen :prompt "Take 1 tag or suffer 2 meat damage?" :async true :choices ["1 tag" "2 meat damage"] :player :runner :msg "make the Runner take 1 tag or suffer 2 meat damage" :effect (req (if (= target "1 tag") (do (system-msg state side "chooses to take 1 tag") (gain-tags state :runner eid 1)) (do (system-msg state side "chooses to suffer 2 meat damage") (damage state :runner eid :meat 2 {:unboostable true :card card}))))}]}) (defcard "Armand \"Geist\" Walker: Tech Lord" {:events [{:event :runner-trash :async true :interactive (req true) :req (req (and (= side :runner) (= :ability-cost (:cause target)))) :msg "draw a card" :effect (effect (draw eid 1))}]}) (defcard "Asa Group: Security Through Vigilance" {:events [{:event :corp-install :async true :req (req (first-event? state :corp :corp-install)) :effect (req (let [installed-card (:card context) z (butlast (get-zone installed-card))] (continue-ability state side {:prompt (str "Choose a " (if (is-remote? z) "non-agenda" "piece of ice") " in HQ to install") :choices {:card #(and (in-hand? %) (corp? %) (corp-installable-type? %) (not (agenda? %)))} :async true :effect (effect (corp-install eid target (zone->name z) nil))} card nil)))}]}) (defcard "Ayla \"Bios\" Rahim: Simulant Specialist" {:abilities [{:label "Add 1 hosted card to your grip" :cost [:click 1] :async true :prompt "Choose a hosted card" :choices (req (cancellable (:hosted card))) :msg "move a hosted card to their Grip" :effect (effect (move target :hand) (effect-completed eid))}] :events [{:event :pre-start-game :req (req (= side :runner)) :async true :waiting-prompt "Runner to make a decision" :effect (req (doseq [c (take 6 (:deck runner))] (move state side c :play-area)) (continue-ability state side {:prompt "Choose 4 cards to be hosted" :choices {:max 4 :all true :card #(and (runner? %) (in-play-area? %))} :effect (req (doseq [c targets] (host state side (get-card state card) c {:facedown true})) (doseq [c (get-in @state [:runner :play-area])] (move state side c :deck)) (shuffle! state side :deck))} card nil))}]}) (defcard "Az McCaffrey: Mechanical Prodigy" ;; Effect marks Az's ability as "used" if it has already met it's trigger condition this turn (letfn [(az-type? [card] (or (hardware? card) (and (resource? card) (or (has-subtype? card "Job") (has-subtype? card "Connection"))))) (not-triggered? [state] (no-event? state :runner :runner-install #(az-type? (:card (first %)))))] {:constant-effects [{:type :install-cost :req (req (and (az-type? target) (not-triggered? state))) :value -1}] :events [{:event :runner-install :req (req (and (az-type? (:card context)) (not-triggered? state))) :silent (req true) :msg (msg "reduce the install cost of " (:title (:card context)) " by 1 [Credits]")}]})) (defcard "Azmari EdTech: Shaping the Future" {:events [{:event :corp-turn-ends :prompt "Name a card type" :choices ["Event" "Resource" "Program" "Hardware" "None"] :effect (effect (update! (assoc card :card-target (if (= "None" target) nil target))) (system-msg (str "uses Azmari EdTech: Shaping the Future to name " target)))} {:event :runner-install :req (req (and (:card-target card) (is-type? (:card context) (:card-target card)) (not (:facedown context)))) :async true :effect (effect (gain-credits :corp eid 2)) :once :per-turn :msg (msg "gain 2 [Credits] from " (:card-target card))} {:event :play-event :req (req (and (:card-target card) (is-type? (:card context) (:card-target card)))) :async true :effect (effect (gain-credits :corp eid 2)) :once :per-turn :msg (msg "gain 2 [Credits] from " (:card-target card))}]}) (defcard "Blue Sun: Powering the Future" {:flags {:corp-phase-12 (req (and (not (:disabled card)) (some rezzed? (all-installed state :corp))))} :abilities [{:choices {:card rezzed?} :label "Add 1 rezzed card to HQ and gain credits equal to its rez cost" :msg (msg "add " (:title target) " to HQ and gain " (rez-cost state side target) " [Credits]") :async true :effect (effect (move target :hand) (gain-credits eid (rez-cost state side target)))}]}) (defcard "Boris \"Syfr\" Kovac: Crafty Veteran" {:events [{:event :pre-start-game :effect draft-points-target} {:event :runner-turn-begins :req (req (and (has-most-faction? state :runner "Criminal") (pos? (get-in runner [:tag :base])))) :msg "remove 1 tag" :async true :effect (effect (lose-tags eid 1))}]}) (defcard "Cerebral Imaging: Infinite Frontiers" {:constant-effects [(corp-hand-size+ (req (:credit corp)))] :effect (req (swap! state assoc-in [:corp :hand-size :base] 0)) :leave-play (req (swap! state assoc-in [:corp :hand-size :base] 5))}) (defcard "Chaos Theory: Wünderkind" {:constant-effects [(mu+ 1)]}) (defcard "Chronos Protocol: Selective Mind-mapping" {:req (req (empty? (filter #(= :net (:damage-type (first %))) (turn-events state :runner :damage)))) :effect (effect (enable-corp-damage-choice)) :leave-play (req (swap! state update-in [:damage] dissoc :damage-choose-corp)) :events [{:event :corp-phase-12 :effect (effect (enable-corp-damage-choice))} {:event :runner-phase-12 :effect (effect (enable-corp-damage-choice))} {:event :pre-resolve-damage :optional {:player :corp :req (req (and (= target :net) (corp-can-choose-damage? state) (pos? (last targets)) (empty? (filter #(= :net (:damage-type (first %))) (turn-events state :runner :damage))) (pos? (count (:hand runner))))) :waiting-prompt "Corp to make a decision" :prompt "Use Chronos Protocol to choose the first card trashed?" :yes-ability {:async true :msg (msg "look at the Runner's Grip ( " (string/join ", " (map :title (sort-by :title (:hand runner)))) " ) and choose the card that is trashed") :effect (effect (continue-ability {:prompt "Choose a card to trash" :choices (req (:hand runner)) :not-distinct true :msg (msg "choose " (:title target) " to trash") :effect (req (chosen-damage state :corp target))} card nil))} :no-ability {:effect (req (system-msg state :corp "declines to use Chronos Protocol"))}}}]}) (defcard "Cybernetics Division: Humanity Upgraded" {:constant-effects [(hand-size+ -1)]}) (defcard "Earth Station: SEA Headquarters" (let [flip-effect (effect (update! (if (:flipped card) (do (system-msg state :corp "flipped their identity to Earth Station: SEA Headquarters") (assoc card :flipped false :face :front :code (subs (:code card) 0 5))) (assoc card :flipped true :face :back :code (str (subs (:code card) 0 5) "flip")))))] {:events [{:event :pre-first-turn :req (req (= side :corp)) :effect (effect (update! (assoc card :flipped false :face :front)))} {:event :successful-run :req (req (and (= :hq (target-server context)) (:flipped card))) :effect flip-effect}] :constant-effects [{:type :run-additional-cost :req (req (or (and (not (:flipped card)) (= :hq (:server (second targets)))) (and (:flipped card) (in-coll? (keys (get-remotes state)) (:server (second targets)))))) :value (req [:credit (if (:flipped card) 6 1)])}] :async true ; This effect will be resolved when the ID is reenabled after Strike / Direct Access :effect (effect (continue-ability {:req (req (< 1 (count (get-remotes state)))) :prompt "Choose a server to be saved from the rules apocalypse" :choices (req (get-remote-names state)) :async true :effect (req (let [to-be-trashed (remove #(in-coll? ["Archives" "R&D" "HQ" target] (zone->name (second (get-zone %)))) (all-installed state :corp))] (system-msg state side (str "chooses " target " to be saved from the rules apocalypse and trashes " (quantify (count to-be-trashed) "card"))) ; these cards get trashed by the game and not by players (trash-cards state side eid to-be-trashed {:unpreventable true :game-trash true})))} card nil)) :abilities [{:label "Flip identity to Earth Station: Ascending to Orbit" :req (req (not (:flipped card))) :cost [:click 1] :msg "flip their identity to Earth Station: Ascending to Orbit" :effect flip-effect} {:label "Manually flip identity to Earth Station: SEA Headquarters" :req (req (:flipped card)) :effect flip-effect}]})) (defcard "Edward Kim: Humanity's Hammer" {:events [{:event :access :once :per-turn :req (req (and (operation? target) (first-event? state side :access #(operation? (first %))))) :async true :effect (req (if (in-discard? target) (effect-completed state side eid) (do (when run (swap! state assoc-in [:run :did-trash] true)) (swap! state assoc-in [:runner :register :trashed-card] true) (system-msg state :runner (str "uses Edward Kim: Humanity's Hammer to" " trash " (:title target) " at no cost")) (trash state side eid target nil))))}]}) (defcard "Ele \"Smoke\" Scovak: Cynosure of the Net" {:recurring 1 :interactions {:pay-credits {:req (req (and (= :ability (:source-type eid)) (has-subtype? target "Icebreaker"))) :type :recurring}}}) (defcard "Exile: Streethawk" {:flags {:runner-install-draw true} :events [{:event :runner-install :async true :req (req (and (program? (:card context)) (some #{:discard} (:previous-zone (:card context))))) :msg "draw a card" :effect (effect (draw eid 1))}]}) (defcard "Freedom Khumalo: Crypto-Anarchist" {:interactions {:access-ability {:async true :once :per-turn :label "Trash card" :req (req (and (not (:disabled card)) (not (agenda? target)) (<= (play-cost state side target) (number-of-runner-virus-counters state)))) :waiting-prompt "Runner to make a decision" :effect (req (let [accessed-card target play-or-rez (:cost target)] (if (zero? play-or-rez) (continue-ability state side {:async true :msg (msg "trash " (:title accessed-card) " at no cost") :effect (effect (trash eid (assoc accessed-card :seen true) {:accessed true}))} card nil) (wait-for (resolve-ability state side (pick-virus-counters-to-spend play-or-rez) card nil) (if-let [msg (:msg async-result)] (do (system-msg state :runner (str "uses Freedom Khumalo: Crypto-Anarchist to" " trash " (:title accessed-card) " at no cost, spending " msg)) (trash state side eid (assoc accessed-card :seen true) {:accessed true})) ;; Player cancelled ability (do (swap! state dissoc-in [:per-turn (:cid card)]) (access-non-agenda state side eid accessed-card :skip-trigger-event true)))))))}}}) (defcard "Fringe Applications: Tomorrow, Today" {:events [{:event :pre-start-game :effect draft-points-target} {:event :runner-turn-begins :player :corp :req (req (and (not (:disabled card)) (has-most-faction? state :corp "Weyland Consortium") (some ice? (all-installed state side)))) :prompt "Choose a piece of ice to place 1 advancement token on" :choices {:card #(and (installed? %) (ice? %))} :msg (msg "place 1 advancement token on " (card-str state target)) :effect (req (add-prop state :corp target :advance-counter 1 {:placed true}))}]}) (defcard "Gabriel Santiago: Consummate Professional" {:events [{:event :successful-run :silent (req true) :req (req (and (= :hq (target-server context)) (first-successful-run-on-server? state :hq))) :msg "gain 2 [Credits]" :async true :effect (effect (gain-credits eid 2))}]}) (defcard "Gagarin Deep Space: Expanding the Horizon" {:events [{:event :pre-access-card :req (req (is-remote? (second (get-zone target)))) :effect (effect (access-cost-bonus [:credit 1])) :msg "make the Runner spend 1 [Credits] to access"}]}) (defcard "GameNET: Where Dreams are Real" (let [gamenet-ability {:req (req (and (:run @state) (= (:side (:source eid)) "Corp") (or (and (not= (:source-type eid) :runner-trash-corp-cards) (not= (:source-type eid) :runner-steal)) (some (fn [[cost source]] (and (some #(or (= (cost-name %) :credit) (= (cost-name %) :x-credits)) (merge-costs cost)) (= (:side (:source source)) "Corp"))) (:additional-costs eid))))) :async true :msg "gain 1 [Credits]" :effect (effect (gain-credits :corp eid 1))}] {:events [(assoc gamenet-ability :event :runner-credit-loss) (assoc gamenet-ability :event :runner-spent-credits)]})) (defcard "GRNDL: Power Unleashed" {:events [{:event :pre-start-game :req (req (= :corp side)) :async true :effect (req (wait-for (gain-credits state :corp 5) (if (zero? (count-bad-pub state)) (gain-bad-publicity state :corp eid 1) (effect-completed state side eid))))}]}) (defcard "Haarpsichord Studios: Entertainment Unleashed" {:constant-effects [{:type :cannot-steal :value (req (pos? (event-count state side :agenda-stolen)))}] :events [{:event :access :req (req (and (agenda? target) (pos? (event-count state side :agenda-stolen)))) :effect (effect (toast :runner "Cannot steal due to Haarpsichord Studios." "warning"))}]}) (defcard "Haas-Bioroid: Architects of Tomorrow" {:events [{:event :pass-ice :req (req (and (rezzed? (:ice context)) (has-subtype? (:ice context) "Bioroid") (first-event? state :runner :pass-ice (fn [targets] (let [context (first targets) ice (:ice context)] (and (rezzed? ice) (installed? ice) (has-subtype? ice "Bioroid"))))))) :waiting-prompt "Corp to make a decision" :prompt "Choose a Bioroid to rez" :player :corp :choices {:req (req (and (has-subtype? target "Bioroid") (not (rezzed? target)) (can-pay? state side (assoc eid :source card :source-type :rez) target nil [:credit (rez-cost state side target {:cost-bonus -4})])))} :msg (msg "rez " (:title target)) :async true :effect (effect (rez eid target {:cost-bonus -4}))}]}) (defcard "Haas-Bioroid: Engineering the Future" {:events [{:event :corp-install :req (req (first-event? state corp :corp-install)) :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits eid 1))}]}) (defcard "Haas-Bioroid: Precision Design" {:constant-effects [(corp-hand-size+ 1)] :events [{:event :agenda-scored :interactive (req true) :optional {:prompt "Add card from Archives to HQ?" :autoresolve (get-autoresolve :auto-precision-design) :yes-ability (corp-recur)}}] :abilities [(set-autoresolve :auto-precision-design "add card from Archives to HQ")]}) (defcard "Haas-Bioroid: Stronger Together" {:constant-effects [{:type :ice-strength :req (req (has-subtype? target "Bioroid")) :value 1}] :leave-play (effect (update-all-ice)) :effect (effect (update-all-ice))}) (defcard "Harishchandra Ent.: Where You're the Star" (letfn [(format-grip [runner] (if (pos? (count (:hand runner))) (string/join ", " (map :title (sort-by :title (:hand runner)))) "no cards"))] {:events [{:event :post-runner-draw :req (req (is-tagged? state)) :msg (msg "see that the Runner drew: " (string/join ", " (map :title runner-currently-drawing)))} {:event :tags-changed :effect (req (if (is-tagged? state) (when-not (get-in @state [:runner :openhand]) (system-msg state :corp (str "uses " (get-title card) " make the Runner play with their grip revealed")) (system-msg state :corp (str "uses " (get-title card) " to see that the Runner currently has " (format-grip runner) " in their grip")) (reveal-hand state :runner)) (when (get-in @state [:runner :openhand]) (system-msg state :corp (str "uses " (get-title card) " stop making the Runner play with their grip revealed")) (system-msg state :corp (str "uses " (get-title card) " to see that the Runner had " (format-grip runner) " in their grip before it was concealed")) (conceal-hand state :runner))))}] :effect (req (when (is-tagged? state) (reveal-hand state :runner))) :leave-play (req (when (is-tagged? state) (conceal-hand state :runner)))})) (defcard "Harmony Medtech: Biomedical Pioneer" {:effect (effect (lose :agenda-point-req 1) (lose :runner :agenda-point-req 1)) :leave-play (effect (gain :agenda-point-req 1) (gain :runner :agenda-point-req 1))}) (defcard "Hayley Kaplan: Universal Scholar" {:events [{:event :runner-install :silent (req (not (and (first-event? state side :runner-install) (some #(is-type? % (:type (:card context))) (:hand runner))))) :req (req (and (first-event? state side :runner-install) (not (:facedown context)))) :once :per-turn :async true :waiting-prompt "Runner to make a decision" :effect (effect (continue-ability (let [itarget (:card context) card-type (:type itarget)] (if (some #(is-type? % (:type itarget)) (:hand runner)) {:optional {:prompt (str "Install another " card-type " from your Grip?") :yes-ability {:prompt (str "Choose another " card-type " to install from your Grip") :choices {:card #(and (is-type? % card-type) (in-hand? %))} :msg (msg "install " (:title target)) :async true :effect (effect (runner-install (assoc eid :source card :source-type :runner-install) target nil))}}} {:prompt (str "You have no " card-type "s in hand") :choices ["Carry on!"] :prompt-type :bogus})) card nil))}]}) (defcard "Hoshiko Shiro: Untold Protagonist" (let [flip-effect (req (update! state side (if (:flipped card) (assoc card :flipped false :face :front :code (subs (:code card) 0 5) :subtype "Natural") (assoc card :flipped true :face :back :code (str (subs (:code card) 0 5) "flip") :subtype "Digital"))) (update-link state))] {:constant-effects [(link+ (req (:flipped card)) 1) {:type :gain-subtype :req (req (and (same-card? card target) (:flipped card))) :value "Digital"} {:type :lose-subtype :req (req (and (same-card? card target) (:flipped card))) :value "Natural"}] :events [{:event :pre-first-turn :req (req (= side :runner)) :effect (effect (update! (assoc card :flipped false :face :front)))} {:event :runner-turn-ends :interactive (req true) :async true :effect (req (cond (and (:flipped card) (not (:accessed-cards runner-reg))) (do (system-msg state :runner "flips their identity to Hoshiko Shiro: Untold Protagonist") (continue-ability state :runner {:effect flip-effect} card nil)) (and (not (:flipped card)) (:accessed-cards runner-reg)) (wait-for (gain-credits state :runner 2) (system-msg state :runner "gains 2 [Credits] and flips their identity to Hoshiko Shiro: Mahou Shoujo") (continue-ability state :runner {:effect flip-effect} card nil)) :else (effect-completed state side eid)))} {:event :runner-turn-begins :req (req (:flipped card)) :async true :effect (req (wait-for (draw state :runner 1) (wait-for (lose-credits state :runner (make-eid state eid) 1) (system-msg state :runner "uses Hoshiko Shiro: Mahou Shoujo to draw 1 card and lose 1 [Credits]") (effect-completed state side eid))))}] :abilities [{:label "flip ID" :msg "flip their ID manually" :effect flip-effect}]})) (defcard "Hyoubu Institute: Absolute Clarity" {:events [{:event :corp-reveal :once :per-turn :req (req (first-event? state side :corp-reveal #(pos? (count %)))) :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits eid 1))}] :abilities [{:cost [:click 1] :label "Reveal the top card of the Stack" :async true :effect (req (if-let [revealed-card (-> runner :deck first)] (do (system-msg state side (str "uses Hyoubu Institute: Absolute Clarity to reveal " (:title revealed-card) " from the top of the Stack")) (reveal state side eid revealed-card)) (effect-completed state side eid)))} {:cost [:click 1] :label "Reveal a random card from the Grip" :async true :effect (req (if-let [revealed-card (-> runner :hand shuffle first)] (do (system-msg state side (str "uses Hyoubu Institute: Absolute Clarity to reveal " (:title revealed-card) " from the Grip")) (reveal state side eid revealed-card)) (effect-completed state side eid)))}]}) (defcard "Iain Stirling: Retired Spook" (let [ability {:req (req (> (:agenda-point corp) (:agenda-point runner))) :once :per-turn :msg "gain 2 [Credits]" :async true :effect (effect (gain-credits eid 2))}] {:flags {:drip-economy true} :events [(assoc ability :event :runner-turn-begins)] :abilities [ability]})) (defcard "Industrial Genomics: Growing Solutions" {:constant-effects [{:type :trash-cost :value (req (count (remove :seen (:discard corp))))}]}) (defcard "Information Dynamics: All You Need To Know" {:events (let [inf {:req (req (and (not (:disabled card)) (has-most-faction? state :corp "NBN"))) :msg "give the Runner 1 tag" :async true :effect (effect (gain-tags :corp eid 1))}] [{:event :pre-start-game :effect draft-points-target} (assoc inf :event :agenda-scored) (assoc inf :event :agenda-stolen)])}) (defcard "Jamie \"Bzzz\" Micken: Techno Savant" {:events [{:event :pre-start-game :effect draft-points-target} {:event :runner-install :req (req (and (has-most-faction? state :runner "Shaper") (first-event? state side :runner-install))) :msg "draw 1 card" :once :per-turn :async true :effect (effect (draw eid 1))}]}) (defcard "Jemison Astronautics: Sacrifice. Audacity. Success." {:events [{:event :corp-forfeit-agenda :async true :waiting-prompt "Corp to make a decision" :effect (effect (continue-ability (let [p (inc (get-agenda-points (:card context)))] {:prompt (str "Choose a card to place advancement tokens on with " (:title card)) :choices {:card #(and (installed? %) (corp? %))} :msg (msg "place " (quantify p "advancement token") " on " (card-str state target)) :effect (effect (add-prop :corp target :advance-counter p {:placed true}))}) card nil))}]}) (defcard "Jesminder Sareen: Girl Behind the Curtain" {:flags {:forced-to-avoid-tag true} :events [{:event :pre-tag :async true :once :per-run :req (req (:run @state)) :msg "avoid the first tag during this run" :effect (effect (tag-prevent :runner eid 1))}]}) (defcard "Jinteki Biotech: Life Imagined" {:events [{:event :pre-first-turn :req (req (= side :corp)) :prompt "Choose a copy of Jinteki Biotech to use this game" :choices ["The Brewery" "The Tank" "The Greenhouse"] :effect (effect (update! (assoc card :biotech-target target :face :front)) (system-msg (str "has chosen a copy of Jinteki Biotech for this game")))}] :abilities [{:label "Check chosen flip identity" :effect (req (case (:biotech-target card) "The Brewery" (toast state :corp "Flip to: The Brewery (Do 2 net damage)" "info") "The Tank" (toast state :corp "Flip to: The Tank (Shuffle Archives into R&D)" "info") "The Greenhouse" (toast state :corp "Flip to: The Greenhouse (Place 4 advancement tokens on a card)" "info") ;; default case (toast state :corp "No flip identity specified" "info")))} {:cost [:click 3] :req (req (not (:biotech-used card))) :label "Flip this identity" :async true :effect (req (let [flip (:biotech-target card)] (update! state side (assoc (get-card state card) :biotech-used true)) (case flip "The Brewery" (do (system-msg state side "uses The Brewery to do 2 net damage") (update! state side (assoc card :code "brewery" :face :brewery)) (damage state side eid :net 2 {:card card})) "The Tank" (do (system-msg state side "uses The Tank to shuffle Archives into R&D") (shuffle-into-deck state side :discard) (update! state side (assoc card :code "tank" :face :tank)) (effect-completed state side eid)) "The Greenhouse" (do (system-msg state side (str "uses The Greenhouse to place 4 advancement tokens " "on a card that can be advanced")) (update! state side (assoc card :code "greenhouse" :face :greenhouse)) (continue-ability state side {:prompt "Choose a card that can be advanced" :choices {:card can-be-advanced?} :effect (effect (add-prop target :advance-counter 4 {:placed true}))} card nil)) (toast state :corp (str "Unknown Jinteki Biotech: Life Imagined card: " flip) "error"))))}]}) (defcard "Jinteki: Personal Evolution" (let [ability {:async true :req (req (not (:winner @state))) :msg "do 1 net damage" :effect (effect (damage eid :net 1 {:card card}))}] {:events [(assoc ability :event :agenda-scored :interactive (req true)) (assoc ability :event :agenda-stolen)]})) (defcard "Jinteki: Potential Unleashed" {:events [{:async true :event :pre-resolve-damage :req (req (and (-> @state :corp :disable-id not) (= target :net) (pos? (last targets)))) :effect (req (let [c (first (get-in @state [:runner :deck]))] (system-msg state :corp (str "uses Jinteki: Potential Unleashed to trash " (:title c) " from the top of the Runner's Stack")) (mill state :corp eid :runner 1)))}]}) (defcard "Jinteki: Replicating Perfection" {:events [{:event :runner-phase-12 :effect (req (apply prevent-run-on-server state card (map first (get-remotes state))))} {:event :run :once :per-turn :req (req (is-central? (:server target))) :effect (req (apply enable-run-on-server state card (map first (get-remotes state))))}] :req (req (empty? (let [successes (turn-events state side :successful-run)] (filter is-central? (map :server successes))))) :effect (req (apply prevent-run-on-server state card (map first (get-remotes state)))) :leave-play (req (apply enable-run-on-server state card (map first (get-remotes state))))}) (defcard "Jinteki: Restoring Humanity" {:events [{:event :corp-turn-ends :req (req (pos? (count (remove :seen (:discard corp))))) :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits :corp eid 1))}]}) (defcard "Kabonesa Wu: Netspace Thrillseeker" {:abilities [{:label "Install a non-virus program from your stack, lowering the cost by 1 [Credit]" :cost [:click 1] :prompt "Choose a program" :choices (req (cancellable (filter #(and (program? %) (not (has-subtype? % "Virus")) (can-pay? state :runner (assoc eid :source card :source-type :runner-install) % nil [:credit (install-cost state side % {:cost-bonus -1})])) (:deck runner)))) :msg (msg "install " (:title target) " from the stack, lowering the cost by 1 [Credit]") :async true :effect (effect (trigger-event :searched-stack nil) (shuffle! :deck) (register-events card [{:event :runner-turn-ends :interactive (req true) :duration :end-of-turn :req (req (some #(get-in % [:special :kabonesa]) (all-installed state :runner))) :msg (msg "remove " (:title target) " from the game") :effect (req (doseq [program (filter #(get-in % [:special :kabonesa]) (all-installed state :runner))] (move state side program :rfg)))}]) (runner-install (assoc eid :source card :source-type :runner-install) (assoc-in target [:special :kabonesa] true) {:cost-bonus -1}))}]}) (defcard "Kate \"Mac\" McCaffrey: Digital Tinker" ;; Effect marks Kate's ability as "used" if it has already met it's trigger condition this turn (letfn [(kate-type? [card] (or (hardware? card) (program? card))) (not-triggered? [state card] (no-event? state :runner :runner-install #(kate-type? (:card (first %)))))] {:constant-effects [{:type :install-cost :req (req (and (kate-type? target) (not-triggered? state card))) :value -1}] :events [{:event :runner-install :req (req (and (kate-type? (:card context)) (not-triggered? state card))) :silent (req true) :msg (msg "reduce the install cost of " (:title (:card context)) " by 1 [Credits]")}]})) (defcard "Ken \"Express\" Tenma: Disappeared Clone" {:events [{:event :play-event :req (req (and (has-subtype? (:card context) "Run") (first-event? state :runner :play-event #(has-subtype? (:card (first %)) "Run")))) :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits eid 1))}]}) (defcard "Khan: Savvy Skiptracer" {:events [{:event :pass-ice :req (req (first-event? state :runner :pass-ice)) :async true :interactive (req true) :effect (effect (continue-ability (when (some #(and (has-subtype? % "Icebreaker") (can-pay? state side (assoc eid :source card :source-type :runner-install) % nil [:credit (install-cost state side % {:cost-bonus -1})])) (:hand runner)) {:prompt "Choose an icebreaker to install from your Grip" :choices {:req (req (and (in-hand? target) (has-subtype? target "Icebreaker") (can-pay? state side (assoc eid :source card :source-type :runner-install) target nil [:credit (install-cost state side target {:cost-bonus -1})])))} :async true :msg (msg "install " (:title target) ", lowering the cost by 1 [Credits]") :effect (effect (runner-install eid target {:cost-bonus -1}))}) card nil))}]}) (defcard "Laramy Fisk: Savvy Investor" {:events [{:event :successful-run :async true :interactive (get-autoresolve :auto-fisk (complement never?)) :silent (get-autoresolve :auto-fisk never?) :optional {:req (req (and (is-central? (:server context)) (first-event? state side :successful-run (fn [targets] (let [context (first targets)] (is-central? (:server context))))))) :autoresolve (get-autoresolve :auto-fisk) :prompt "Force the Corp to draw a card?" :yes-ability {:msg "force the Corp to draw 1 card" :async true :effect (effect (draw :corp eid 1))} :no-ability {:effect (effect (system-msg "declines to use Laramy Fisk: Savvy Investor"))}}}] :abilities [(set-autoresolve :auto-fisk "force Corp draw")]}) (defcard "Lat: Ethical Freelancer" {:events [{:event :runner-turn-ends :optional {:req (req (= (count (:hand runner)) (count (:hand corp)))) :autoresolve (get-autoresolve :auto-lat) :prompt "Draw 1 card?" :yes-ability {:async true :msg "draw 1 card" :effect (effect (draw :runner eid 1))} :no-ability {:effect (effect (system-msg "declines to use Lat: Ethical Freelancer"))}}}] :abilities [(set-autoresolve :auto-lat "Lat: Ethical Freelancer")]}) (defcard "Leela Patel: Trained Pragmatist" (let [leela {:interactive (req true) :prompt "Choose an unrezzed card to return to HQ" :choices {:card #(and (not (rezzed? %)) (installed? %) (corp? %))} :msg (msg "add " (card-str state target) " to HQ") :effect (effect (move :corp target :hand))}] {:events [(assoc leela :event :agenda-scored) (assoc leela :event :agenda-stolen)]})) (defcard "Liza Talking Thunder: Prominent Legislator" {:events [{:event :successful-run :async true :interactive (req true) :msg "draw 2 cards and take 1 tag" :req (req (and (is-central? (:server context)) (first-event? state side :successful-run (fn [targets] (let [context (first targets)] (is-central? (:server context))))))) :effect (req (wait-for (gain-tags state :runner 1) (draw state :runner eid 2)))}]}) (defcard "Los: Data Hijacker" {:events [{:event :rez :once :per-turn :req (req (ice? (:card context))) :msg "gain 2 [Credits]" :async true :effect (effect (gain-credits :runner eid 2))}]}) (defcard "MaxX: Maximum Punk Rock" (let [ability {:msg (msg (let [deck (:deck runner)] (if (pos? (count deck)) (str "trash " (string/join ", " (map :title (take 2 deck))) " from their Stack and draw 1 card") "trash the top 2 cards from their Stack and draw 1 card - but their Stack is empty"))) :label "trash and draw cards" :once :per-turn :async true :effect (req (wait-for (mill state :runner :runner 2) (draw state :runner eid 1)))}] {:flags {:runner-turn-draw true :runner-phase-12 (req (and (not (:disabled card)) (some #(card-flag? % :runner-turn-draw true) (all-active-installed state :runner))))} :events [(assoc ability :event :runner-turn-begins)] :abilities [ability]})) (defcard "MirrorMorph: Endless Iteration" (let [mm-clear {:prompt "Manually fix Mirrormorph" :msg (msg "manually clear Mirrormorph flags") :effect (effect (update! (assoc-in card [:special :mm-actions] [])) (update! (assoc-in (get-card state card) [:special :mm-click] false)))} mm-ability {:prompt "Gain [Click] or gain 1 [Credits]" :choices ["Gain [Click]" "Gain 1 [Credits]"] :msg (msg (decapitalize target)) :once :per-turn :label "Manually trigger ability" :async true :effect (req (if (= "Gain [Click]" target) (do (gain-clicks state side 1) (update! state side (assoc-in (get-card state card) [:special :mm-click] true)) (effect-completed state side eid)) (gain-credits state side eid 1)))}] {:implementation "Does not work with terminal Operations" :abilities [mm-ability mm-clear] :events [{:event :corp-spent-click :async true :effect (req (let [cid (first target) ability-idx (:ability-idx (:source-info eid)) bac-cid (get-in @state [:corp :basic-action-card :cid]) cause (if (keyword? (first target)) (case (first target) :play-instant [bac-cid 3] :corp-click-install [bac-cid 2] (first target)) ; in clojure there's: (= [1 2 3] '(1 2 3)) [cid ability-idx]) prev-actions (get-in card [:special :mm-actions] []) actions (conj prev-actions cause)] (update! state side (assoc-in card [:special :mm-actions] actions)) (update! state side (assoc-in (get-card state card) [:special :mm-click] false)) (if (and (= 3 (count actions)) (= 3 (count (distinct actions)))) (continue-ability state side mm-ability (get-card state card) nil) (effect-completed state side eid))))} {:event :runner-turn-begins :effect (effect (update! (assoc-in card [:special :mm-actions] [])) (update! (assoc-in (get-card state card) [:special :mm-click] false)))} {:event :corp-turn-ends :effect (effect (update! (assoc-in card [:special :mm-actions] [])) (update! (assoc-in (get-card state card) [:special :mm-click] false)))}] :constant-effects [{:type :prevent-paid-ability :req (req (and (get-in card [:special :mm-click]) (let [cid (:cid target) ability-idx (nth targets 2 nil) cause [cid ability-idx] prev-actions (get-in card [:special :mm-actions] []) actions (conj prev-actions cause)] (not (and (= 4 (count actions)) (= 4 (count (distinct actions)))))))) :value true}]})) (defcard "Mti Mwekundu: Life Improved" {:events [{:event :approach-server :async true :interactive (req true) :waiting "Corp to make a decision" :req (req (and (pos? (count (:hand corp))) (not (used-this-turn? (:cid card) state)))) :effect (req (if (some ice? (:hand corp)) (continue-ability state side {:optional {:prompt "Install a piece of ice?" :once :per-turn :yes-ability {:prompt "Choose a piece of ice to install from HQ" :choices {:card #(and (ice? %) (in-hand? %))} :async true :msg "install a piece of ice at the innermost position of this server. Runner is now approaching that piece of ice" :effect (req (wait-for (corp-install state side target (zone->name (target-server run)) {:ignore-all-cost true :front true}) (swap! state assoc-in [:run :position] 1) (set-next-phase state :approach-ice) (update-all-ice state side) (update-all-icebreakers state side) (continue-ability state side (offer-jack-out {:req (req (:approached-ice? (:run @state)))}) card nil)))}}} card nil) ;; bogus prompt so Runner cannot infer the Corp has no ice in hand (continue-ability state :corp {:async true :prompt "No ice to install" :choices ["Carry on!"] :prompt-type :bogus :effect (effect (effect-completed eid))} card nil)))}]}) (defcard "Nasir Meidan: Cyber Explorer" {:events [{:event :approach-ice :req (req (not (rezzed? (:ice context)))) :effect (effect (register-events card (let [ice (:ice context) cost (rez-cost state side ice)] [{:event :encounter-ice :duration :end-of-encounter :unregister-once-resolved true :req (req (same-card? (:ice context) ice)) :msg (msg "lose all credits and gain " cost " [Credits] from the rez of " (:title ice)) :async true :effect (req (wait-for (lose-credits state :runner (make-eid state eid) :all) (gain-credits state :runner eid cost)))}])))}]}) (defcard "Nathaniel \"Gnat\" Hall: One-of-a-Kind" (let [ability {:label "Gain 1 [Credits] (start of turn)" :once :per-turn :interactive (req true) :async true :effect (req (if (and (> 3 (count (:hand runner))) (:runner-phase-12 @state)) (do (system-msg state :runner (str "uses " (:title card) " to gain 1 [Credits]")) (gain-credits state :runner eid 1)) (effect-completed state side eid)))}] {:flags {:drip-economy true :runner-phase-12 (req (and (not (:disabled card)) (some #(card-flag? % :runner-turn-draw true) (all-active-installed state :runner))))} :abilities [ability] :events [(assoc ability :event :runner-turn-begins)]})) (defcard "NBN: Controlling the Message" {:events [{:event :runner-trash :interactive (req true) :once-per-instance true :optional {:player :corp :req (req (and (some #(and (corp? (:card %)) (installed? (:card %))) targets) (first-event? state side :runner-trash (fn [targets] (some #(and (installed? (:card %)) (corp? (:card %))) targets))))) :waiting-prompt "Corp to make a decision" :prompt "Trace the Runner with NBN: Controlling the Message?" :autoresolve (get-autoresolve :auto-ctm) :yes-ability {:trace {:base 4 :successful {:msg "give the Runner 1 tag" :async true :effect (effect (gain-tags :corp eid 1 {:unpreventable true}))}}}}}] :abilities [(set-autoresolve :auto-ctm "CtM")]}) (defcard "NBN: Making News" {:recurring 2 :interactions {:pay-credits {:req (req (= :trace (:source-type eid))) :type :recurring}}}) (defcard "NBN: Reality Plus" {:events [{:event :runner-gain-tag :req (req (first-event? state :runner :runner-gain-tag)) :player :corp :async true :waiting-prompt "Corp to choose an option" :prompt "Choose option" :choices ["Gain 2 [Credits]" "Draw 2 cards"] :msg (msg (decapitalize target)) :effect (req (if (= target "Gain 2 [Credits]") (gain-credits state :corp eid 2) (draw state :corp eid 2)))}]}) (defcard "NBN: The World is Yours*" {:constant-effects [(corp-hand-size+ 1)]}) (defcard "Near-Earth Hub: Broadcast Center" {:events [{:event :server-created :req (req (first-event? state :corp :server-created)) :async true :msg "draw 1 card" :effect (req (if-not (some #(= % :deck) (:zone target)) (draw state :corp eid 1) (do ;; Register the draw to go off when the card is finished installing - ;; this is after the checkpoint when it should go off, but is needed to ;; fix the interaction between architect (and any future install from R&D ;; cards) and NEH, where the card would get drawn before the install, ;; fizzling it in a confusing manner. Because we only do it in this ;; special case, there should be no gameplay implications. -nbkelly, 2022 (register-events state side card [{:event :corp-install :interactive (req true) :duration (req true) :unregister-once-resolved true :async true :effect (effect (draw :corp eid 1))}]) (effect-completed state side eid))))}]}) (defcard "Nero Severn: Information Broker" {:events [{:event :encounter-ice :optional (:optional (offer-jack-out {:req (req (has-subtype? (:ice context) "Sentry")) :once :per-turn}))}]}) (defcard "New Angeles Sol: Your News" (let [nasol {:optional {:prompt "Play a Current?" :player :corp :req (req (some #(has-subtype? % "Current") (concat (:hand corp) (:discard corp) (:current corp)))) :yes-ability {:prompt "Choose a Current to play from HQ or Archives" :show-discard true :async true :choices {:card #(and (has-subtype? % "Current") (corp? %) (or (in-hand? %) (in-discard? %)))} :msg (msg "play a current from " (name-zone "Corp" (get-zone target))) :effect (effect (play-instant eid target))}}}] {:events [(assoc nasol :event :agenda-scored) (assoc nasol :event :agenda-stolen)]})) (defcard "NEXT Design: Guarding the Net" (let [ndhelper (fn nd [n] {:prompt (str "When finished, click NEXT Design: Guarding the Net to draw back up to 5 cards in HQ. " "Choose a piece of ice in HQ to install:") :choices {:card #(and (corp? %) (ice? %) (in-hand? %))} :effect (req (wait-for (corp-install state side target nil nil) (continue-ability state side (when (< n 3) (nd (inc n))) card nil)))})] {:events [{:event :pre-first-turn :req (req (= side :corp)) :msg "install up to 3 pieces of ice and draw back up to 5 cards" :async true :effect (req (wait-for (resolve-ability state side (ndhelper 1) card nil) (update! state side (assoc card :fill-hq true)) (effect-completed state side eid)))}] :abilities [{:req (req (:fill-hq card)) :label "draw remaining cards" :msg (msg "draw " (- 5 (count (:hand corp))) " cards") :async true :effect (req (wait-for (draw state side (- 5 (count (:hand corp))) {:suppress-event true}) (update! state side (dissoc card :fill-hq)) (swap! state assoc :turn-events nil) (effect-completed state side eid)))}]})) (defcard "Nisei Division: The Next Generation" {:events [{:event :reveal-spent-credits :req (req (and (some? (first targets)) (some? (second targets)))) :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits :corp eid 1))}]}) (defcard "Noise: Hacker Extraordinaire" {:events [{:async true :event :runner-install :req (req (has-subtype? (:card context) "Virus")) :msg "force the Corp to trash the top card of R&D" :effect (effect (mill :corp eid :corp 1))}]}) (defcard "Null: Whistleblower" {:events [{:event :encounter-ice :optional {:req (req (pos? (count (:hand runner)))) :prompt "Trash a card in grip to lower ice strength by 2?" :once :per-turn :yes-ability {:prompt "Choose a card in your Grip to trash" :choices {:card in-hand?} :msg (msg "trash " (:title target) " and reduce the strength of " (:title current-ice) " by 2 for the remainder of the run") :async true :effect (effect (register-floating-effect card (let [ice current-ice] {:type :ice-strength :duration :end-of-run :req (req (same-card? target ice)) :value -2})) (update-all-ice) (trash eid target {:unpreventable true}))}}}]}) (defcard "Omar Keung: Conspiracy Theorist" {:abilities [{:cost [:click 1] :msg "make a run on Archives" :once :per-turn :makes-run true :async true :effect (effect (update! (assoc-in card [:special :omar-run] true)) (make-run eid :archives (get-card state card)))}] :events [{:event :pre-successful-run :interactive (req true) :req (req (and (get-in card [:special :omar-run]) (= :archives (-> run :server first)))) :prompt "Treat as a successful run on which server?" :choices ["HQ" "R&D"] :effect (req (let [target-server (if (= target "HQ") :hq :rd)] (swap! state assoc-in [:run :server] [target-server]) (trigger-event state :corp :no-action) (system-msg state side (str "uses Omar Keung: Conspiracy Theorist to make a successful run on " target))))} {:event :run-ends :effect (effect (update! (dissoc-in card [:special :omar-run])))}]}) (defcard "Pālanā Foods: Sustainable Growth" {:events [{:event :runner-draw :req (req (and (first-event? state :corp :runner-draw) (pos? (:count target)))) :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits :corp eid 1))}]}) (defcard "Quetzal: Free Spirit" {:abilities [(assoc (break-sub nil 1 "Barrier" {:repeatable false}) :once :per-turn)]}) (defcard "Reina Roja: Freedom Fighter" (letfn [(not-triggered? [state] (no-event? state :runner :rez #(ice? (:card (first %)))))] {:constant-effects [{:type :rez-cost :req (req (and (ice? target) (not (rezzed? target)) (not-triggered? state))) :value 1}] :events [{:event :rez :req (req (and (ice? (:card context)) (not-triggered? state))) :msg (msg "increased the rez cost of " (:title (:card context)) " by 1 [Credits]")}]})) (defcard "René \"Loup\" Arcemont: Party Animal" {:events [{:event :runner-trash :req (req (and (:accessed context) (first-event? state side :runner-trash (fn [targets] (some #(:accessed %) targets))))) :async true :msg "gain 1 [Credits] and draw 1 card" :effect (req (wait-for (draw state :runner 1) (gain-credits state :runner eid 1)))}]}) (defcard "Rielle \"Kit\" Peddler: Transhuman" {:events [{:event :encounter-ice :once :per-turn :msg (msg "make " (:title (:ice context)) " gain Code Gate until the end of the run") :effect (effect (register-floating-effect card (let [ice (:ice context)] {:type :gain-subtype :duration :end-of-run :req (req (same-card? ice target)) :value "Code Gate"})))}]}) (defcard "Saraswati Mnemonics: Endless Exploration" (letfn [(install-card [chosen] {:prompt "Choose a remote server" :choices (req (conj (vec (get-remote-names state)) "New remote")) :async true :effect (req (let [tgtcid (:cid chosen)] (register-persistent-flag! state side card :can-rez (fn [state _ card] (if (= (:cid card) tgtcid) ((constantly false) (toast state :corp "Cannot rez due to Saraswati Mnemonics: Endless Exploration." "warning")) true))) (register-turn-flag! state side card :can-score (fn [state side card] (if (and (= (:cid card) tgtcid) (<= (get-advancement-requirement card) (get-counters card :advancement))) ((constantly false) (toast state :corp "Cannot score due to Saraswati Mnemonics: Endless Exploration." "warning")) true)))) (wait-for (corp-install state side chosen target nil) (add-prop state :corp (find-latest state chosen) :advance-counter 1 {:placed true}) (effect-completed state side eid)))})] {:abilities [{:async true :label "Install a card from HQ" :cost [:click 1 :credit 1] :prompt "Choose a card to install from HQ" :choices {:card #(and (or (asset? %) (agenda? %) (upgrade? %)) (corp? %) (in-hand? %))} :msg (msg "install a card in a remote server and place 1 advancement token on it") :effect (effect (continue-ability (install-card target) card nil))}] :events [{:event :corp-turn-begins :effect (req (clear-persistent-flag! state side card :can-rez))}]})) (defcard "Seidr Laboratories: Destiny Defined" {:implementation "Manually triggered" :abilities [{:req (req (and run (seq (:discard corp)))) :label "add card from Archives to R&D during a run" :once :per-turn :prompt "Choose a card to add to the top of R&D" :show-discard true :choices {:card #(and (corp? %) (in-discard? %))} :effect (effect (move target :deck {:front true})) :msg (msg "add " (if (:seen target) (:title target) "a card") " to the top of R&D")}]}) (defcard "Silhouette: Stealth Operative" {:events [{:event :successful-run :interactive (req (some #(not (rezzed? %)) (all-installed state :corp))) :async true :req (req (and (= :hq (target-server context)) (first-successful-run-on-server? state :hq))) :choices {:card #(and (installed? %) (not (rezzed? %)))} :msg "expose 1 card" :effect (effect (expose eid target))}]}) (defcard "Skorpios Defense Systems: Persuasive Power" {:implementation "Manually triggered, no restriction on which cards in Heap can be targeted. Cannot use on in progress run event" :abilities [{:label "Remove a card in the Heap that was just trashed from the game" :waiting-prompt "Corp to make a decision" :prompt "Choose a card in the Runner's Heap that was just trashed" :once :per-turn :choices (req (cancellable (:discard runner))) :msg (msg "remove " (:title target) " from the game") :effect (req (move state :runner target :rfg))}]}) (defcard "Spark Agency: Worldswide Reach" {:events [{:event :rez :req (req (and (has-subtype? (:card context) "Advertisement") (first-event? state :corp :rez #(has-subtype? (:card (first %)) "Advertisement")))) :async true :effect (effect (lose-credits :runner eid 1)) :msg "make the Runner lose 1 [Credits] by rezzing an Advertisement"}]}) (defcard "Sportsmetal: Go Big or Go Home" (let [ab {:prompt "Gain 2 [Credits] or draw 2 cards?" :player :corp :choices ["Gain 2 [Credits]" "Draw 2 cards"] :msg (msg (if (= target "Gain 2 [Credits]") "gain 2 [Credits]" "draw 2 cards")) :async true :interactive (req true) :effect (req (if (= target "Gain 2 [Credits]") (gain-credits state :corp eid 2) (draw state :corp eid 2)))}] {:events [(assoc ab :event :agenda-scored) (assoc ab :event :agenda-stolen)]})) (defcard "SSO Industries: Fueling Innovation" (letfn [(installed-faceup-agendas [state] (->> (all-installed state :corp) (filter agenda?) (filter faceup?))) (selectable-ice? [card] (and (ice? card) (installed? card) (zero? (get-counters card :advancement)))) (ice-with-no-advancement-tokens [state] (->> (all-installed state :corp) (filter selectable-ice?)))] {:events [{:event :corp-turn-ends :optional {:req (req (and (not-empty (installed-faceup-agendas state)) (not-empty (ice-with-no-advancement-tokens state)))) :waiting-prompt "Corp to make a decision" :prompt "Place advancement tokens?" :autoresolve (get-autoresolve :auto-sso) :yes-ability {:async true :effect (req (let [agendas (installed-faceup-agendas state) agenda-points (->> agendas (map :agendapoints) (reduce +)) ice (ice-with-no-advancement-tokens state)] (continue-ability state side {:prompt (str "Choose a piece of ice with no advancement tokens to place " (quantify agenda-points "advancement token") " on") :choices {:card #(selectable-ice? %)} :msg (msg "place " (quantify agenda-points "advancement token") " on " (card-str state target)) :effect (effect (add-prop target :advance-counter agenda-points {:placed true}))} card nil)))}}}] :abilities [(set-autoresolve :auto-sso "SSO")]})) (defcard "Steve Cambridge: Master Grifter" {:events [{:event :successful-run :optional {:req (req (and (= :hq (target-server context)) (first-successful-run-on-server? state :hq) (<= 2 (count (:discard runner))) (not (zone-locked? state :runner :discard)))) :prompt "Use Steve Cambridge ability?" :yes-ability {:interactive (req true) :async true :prompt "Choose 2 cards in your Heap" :show-discard true :choices {:max 2 :all true :card #(and (in-discard? %) (runner? %))} :effect (effect (continue-ability (let [c1 (first targets) c2 (second targets)] {:waiting-prompt "Corp to make a decision" :prompt "Choose which card to remove from the game" :player :corp :choices [c1 c2] :msg (msg (let [[chosen other](if (= target c1) [c1 c2] [c2 c1])] (str "add " (:title other) " to their grip." " Corp removes " (:title chosen) " from the game"))) :effect (req (let [[chosen other] (if (= target c1) [c1 c2] [c2 c1])] (move state :runner chosen :rfg) (move state :runner other :hand)))}) card nil))}}}]}) (defcard "Strategic Innovations: Future Forward" {:events [{:event :pre-start-game :effect draft-points-target} {:event :runner-turn-ends :req (req (and (not (:disabled card)) (has-most-faction? state :corp "Haas-Bioroid") (pos? (count (:discard corp))))) :prompt "Choose a card in Archives to shuffle into R&D" :choices {:card #(and (corp? %) (in-discard? %))} :player :corp :show-discard true :msg (msg "shuffle " (if (:seen target) (:title target) "a card") " into R&D") :effect (effect (move :corp target :deck) (shuffle! :corp :deck))}]}) (defcard "Sunny Lebeau: Security Specialist" ;; No special implementation {}) (defcard "SYNC: Everything, Everywhere" {:constant-effects [{:type :card-ability-additional-cost :req (req (let [targetcard (first targets) target (second targets)] (and (not (:sync-flipped card)) (same-card? targetcard (:basic-action-card runner)) (= "Remove 1 tag" (:label target))))) :value [:credit 1]} {:type :card-ability-additional-cost :req (req (let [targetcard (first targets) target (second targets)] (and (:sync-flipped card) (same-card? targetcard (:basic-action-card corp)) (= "Trash 1 resource if the Runner is tagged" (:label target))))) :value [:credit -2]}] :abilities [{:cost [:click 1] :effect (req (if (:sync-flipped card) (update! state side (-> card (assoc :sync-flipped false :face :front :code "09001"))) (update! state side (-> card (assoc :sync-flipped true :face :back :code "sync"))))) :label "Flip this identity" :msg "flip their ID"}]}) (defcard "Synthetic Systems: The World Re-imagined" {:events [{:event :pre-start-game :effect draft-points-target}] :flags {:corp-phase-12 (req (and (not (:disabled (get-card state card))) (has-most-faction? state :corp "Jinteki") (<= 2 (count (filter ice? (all-installed state :corp))))))} :abilities [{:prompt "Choose two pieces of installed ice to swap" :label "swap two pieces of installed ice" :choices {:card #(and (installed? %) (ice? %)) :max 2 :all true} :once :per-turn :effect (req (apply swap-ice state side targets)) :msg (msg "swap the positions of " (card-str state (first targets)) " and " (card-str state (second targets)))}]}) (defcard "Tāo Salonga: Telepresence Magician" (let [swap-ability {:interactive (req true) :optional {:req (req (<= 2 (count (filter ice? (all-installed state :corp))))) :prompt "Swap ice with Tāo Salonga's ability?" :waiting-prompt "the Runner to swap ice." :yes-ability {:prompt "Choose 2 ice" :choices {:req (req (and (installed? target) (ice? target))) :max 2 :all true} :msg (msg "swap the positions of " (card-str state (first targets)) " and " (card-str state (second targets))) :effect (req (swap-ice state side (first targets) (second targets)))} :no-ability {:effect (effect (system-msg "declines to use Tāo Salonga: Telepresence Magician"))}}}] {:events [(assoc swap-ability :event :agenda-scored) (assoc swap-ability :event :agenda-stolen)]})) (defcard "Tennin Institute: The Secrets Within" {:flags {:corp-phase-12 (req (and (not (:disabled (get-card state card))) (not-last-turn? state :runner :successful-run)))} :abilities [{:msg (msg "place 1 advancement token on " (card-str state target)) :label "Place 1 advancement token on a card if the Runner did not make a successful run last turn" :choices {:card installed?} :req (req (and (:corp-phase-12 @state) (not-last-turn? state :runner :successful-run))) :once :per-turn :effect (effect (add-prop target :advance-counter 1 {:placed true}))}]}) (defcard "The Catalyst: Convention Breaker" ;; No special implementation {}) (defcard "The Foundry: Refining the Process" {:events [{:event :rez :optional {:prompt "Add another copy to HQ?" :req (req (and (ice? (:card context)) (first-event? state :runner :rez #(ice? (:card (first %)))))) :yes-ability {:effect (req (if-let [found-card (some #(when (= (:title %) (:title (:card context))) %) (concat (:deck corp) (:play-area corp)))] (do (move state side found-card :hand) (system-msg state side (str "uses The Foundry to add a copy of " (:title found-card) " to HQ, and shuffles their deck")) (shuffle! state side :deck)) (do (system-msg state side (str "fails to find a target for The Foundry, and shuffles their deck")) (shuffle! state side :deck))))}}}]}) (defcard "The Masque: Cyber General" {:events [{:event :pre-start-game :effect draft-points-target}]}) (defcard "The Outfit: Family Owned and Operated" {:events [{:event :corp-gain-bad-publicity :msg "gain 3 [Credit]" :async true :effect (effect (gain-credits eid 3))}]}) (defcard "The Professor: Keeper of Knowledge" ;; No special implementation {}) (defcard "The Shadow: Pulling the Strings" {:events [{:event :pre-start-game :effect draft-points-target}]}) (defcard "The Syndicate: Profit over Principle" ;; No special implementation {}) (defcard "Titan Transnational: Investing In Your Future" {:events [{:event :agenda-scored :msg (msg "place 1 agenda counter on " (:title (:card context))) :effect (effect (add-counter (get-card state (:card context)) :agenda 1))}]}) (defcard "Valencia Estevez: The Angel of Cayambe" {:events [{:event :pre-start-game :req (req (and (= side :runner) (zero? (count-bad-pub state)))) ;; This doesn't use `gain-bad-publicity` to avoid the event :effect (effect (gain :corp :bad-publicity 1))}]}) (defcard "Weyland Consortium: Because We Built It" {:recurring 1 :interactions {:pay-credits {:req (req (= :advance (:source-type eid))) :type :recurring}}}) (defcard "Weyland Consortium: Builder of Nations" {:implementation "Erratum: The first time an encounter with a piece of ice with at least 1 advancement token ends each turn, do 1 meat damage." :events [{:event :end-of-encounter :async true :req (req (and (rezzed? (:ice context)) (pos? (get-counters (:ice context) :advancement)) (first-event? state :runner :end-of-encounter (fn [targets] (let [context (first targets)] (and (rezzed? (:ice context)) (pos? (get-counters (:ice context) :advancement)))))))) :msg "do 1 meat damage" :effect (effect (damage eid :meat 1 {:card card}))}]}) (defcard "Weyland Consortium: Building a Better World" {:events [{:event :play-operation :req (req (has-subtype? (:card context) "Transaction")) :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits eid 1))}]}) (defcard "Weyland Consortium: Built to Last" {:events [{:event :advance :async true :req (req ((complement pos?) (- (get-counters target :advancement) (:amount (second targets) 0)))) :msg "gain 2 [Credits]" :effect (req (gain-credits state :corp eid 2))}]}) (defcard "Whizzard: Master Gamer" {:recurring 3 :interactions {:pay-credits {:req (req (and (= :runner-trash-corp-cards (:source-type eid)) (corp? target))) :type :recurring}}}) (defcard "Wyvern: Chemically Enhanced" {:events [{:event :pre-start-game :effect draft-points-target} {:event :runner-trash :interactive (req true) :req (req (and (has-most-faction? state :runner "Anarch") (corp? (:card target)) (pos? (count (:discard runner))) (not (zone-locked? state :runner :discard)))) :msg (msg "shuffle " (:title (last (:discard runner))) " into their Stack") :effect (effect (move :runner (last (:discard runner)) :deck) (shuffle! :runner :deck) (trigger-event :searched-stack nil))}]}) (defcard "Zahya Sadeghi: Versatile Smuggler" {:events [{:event :run-ends :optional {:req (req (and (#{:hq :rd} (target-server context)) (pos? (total-cards-accessed context)))) :prompt "Gain 1 [Credits] for each card you accessed?" :async true :once :per-turn :yes-ability {:msg (msg "gain " (total-cards-accessed context) " [Credits]") :once :per-turn :async true :effect (req (gain-credits state :runner eid (total-cards-accessed context)))}}}]})
47482
(ns game.cards.identities (:require [game.core :refer :all] [game.utils :refer :all] [jinteki.utils :refer :all] [clojure.string :as string])) ;;; Helper functions for Draft cards (def draft-points-target "Set each side's agenda points target at 6, per draft format rules" (req (swap! state assoc-in [:runner :agenda-point-req] 6) (swap! state assoc-in [:corp :agenda-point-req] 6))) (defn- has-most-faction? "Checks if the faction has a plurality of rezzed / installed cards" [state side fc] (let [card-list (all-active-installed state side) faction-freq (frequencies (map :faction card-list)) reducer (fn [{:keys [max-count] :as acc} faction count] (cond ;; Has plurality update best-faction (> count max-count) {:max-count count :max-faction faction} ;; Lost plurality (= count max-count) (dissoc acc :max-faction) ;; Count is not more, do not change the accumulator map :else acc)) best-faction (:max-faction (reduce-kv reducer {:max-count 0 :max-faction nil} faction-freq))] (= fc best-faction))) ;; Card definitions (defcard "419: Amoral Scammer" {:events [{:event :corp-install :async true :req (req (and (first-event? state :corp :corp-install) (pos? (:turn @state)) (not (rezzed? (:card context))) (not (#{:rezzed-no-cost :rezzed-no-rez-cost :rezzed :face-up} (:install-state context))))) :waiting-prompt "Runner to choose an option" :effect (effect (continue-ability {:optional {:prompt "Expose installed card unless Corp pays 1 [Credits]?" :player :runner :autoresolve (get-autoresolve :auto-419) :no-ability {:effect (req (clear-wait-prompt state :corp))} :yes-ability {:async true :effect (req (if (not (can-pay? state :corp eid card nil :credit 1)) (do (toast state :corp "Cannot afford to pay 1 [Credit] to block card exposure" "info") (expose state :runner eid (:card context))) (continue-ability state side {:optional {:waiting-prompt "Corp to choose an option" :prompt "Pay 1 [Credits] to prevent exposure of installed card?" :player :corp :no-ability {:async true :effect (effect (expose :runner eid (:card context)))} :yes-ability {:async true :effect (req (wait-for (pay state :corp (make-eid state eid) card [:credit 1]) (system-msg state :corp (str (:msg async-result) " to prevent " " card from being exposed")) (effect-completed state side eid)))}}} card targets)))}}} card targets))}] :abilities [(set-autoresolve :auto-419 "419")]}) (defcard "Acme Consulting: The Truth You Need" (letfn [(outermost? [state ice] (let [server-ice (:ices (card->server state ice))] (same-card? ice (last server-ice))))] {:constant-effects [{:type :tags :req (req (and (get-current-encounter state) (rezzed? current-ice) (outermost? state current-ice))) :value 1}]})) (defcard "<NAME>: Compulsive Hacker" {:events [{:event :pre-start-game :req (req (= side :runner)) :async true :waiting-prompt "Runner to make a decision" :effect (req (let [directives (->> (server-cards) (filter #(has-subtype? % "Directive")) (map make-card) (map #(assoc % :zone [:play-area])) (into []))] ;; Add directives to :play-area - assumed to be empty (swap! state assoc-in [:runner :play-area] directives) (continue-ability state side {:prompt (str "Choose 3 starting directives") :choices {:max 3 :all true :card #(and (runner? %) (in-play-area? %))} :effect (req (doseq [c targets] (runner-install state side (make-eid state eid) c {:ignore-all-cost true :custom-message (fn [_] (str "starts with " (:title c) " in play"))})) (swap! state assoc-in [:runner :play-area] []))} card nil)))}]}) (defcard "AgInfusion: New Miracles for a New World" {:abilities [{:label "Trash a piece of ice to choose another server- the runner is now running that server" :once :per-turn :async true :req (req (and run (= :approach-ice (:phase run)) (not (rezzed? current-ice)))) :prompt "Choose another server and redirect the run to its outermost position" :choices (req (cancellable (remove #{(-> @state :run :server central->name)} servers))) :msg (msg "trash the approached piece of ice. The Runner is now running on " target) :effect (req (let [dest (server->zone state target) ice (count (get-in corp (conj dest :ices))) phase (if (pos? ice) :encounter-ice :movement)] (wait-for (trash state side (make-eid state eid) current-ice {:unpreventable true}) (redirect-run state side target phase) (start-next-phase state side eid))))}]}) (defcard "<NAME>: Head Case" {:events [{:event :breach-server :interactive (req true) :psi {:req (req (= target :rd)) :player :runner :equal {:msg "access 1 additional card" :effect (effect (access-bonus :rd 1) (effect-completed eid))}}}]}) (defcard "<NAME>: <NAME> A<NAME>ator" {:events [{:event :successful-run :interactive (req true) :req (req (and (= :archives (target-server context)) (first-successful-run-on-server? state :archives) (not-empty (:hand corp)))) :waiting-prompt "Corp to make a decision" :prompt "Choose a card in HQ to discard" :player :corp :choices {:all true :card #(and (in-hand? %) (corp? %))} :msg "force the Corp to trash 1 card from HQ" :async true :effect (effect (trash :corp eid target nil))}]}) (defcard "Andromeda: Dispossessed Ristie" {:events [{:event :pre-start-game :req (req (= side :runner)) :async true :effect (effect (draw eid 4 {:suppress-event true}))}] :mulligan (effect (draw eid 4 {:suppress-event true}))}) (defcard "Apex: Invasive Predator" (let [ability {:prompt "Choose a card to install facedown" :label "Install a card facedown (start of turn)" :once :per-turn :choices {:max 1 :card #(and (runner? %) (in-hand? %))} :req (req (and (pos? (count (:hand runner))) (:runner-phase-12 @state))) :async true :msg "install a card facedown" :effect (effect (runner-install (assoc eid :source card :source-type :runner-install) target {:facedown true :no-msg true}))}] {:implementation "Install restriction not enforced" :events [(assoc ability :event :runner-turn-begins)] :flags {:runner-phase-12 (req true)} :abilities [ability]})) (defcard "Argus Security: Protection Guaranteed" {:events [{:event :agenda-stolen :prompt "Take 1 tag or suffer 2 meat damage?" :async true :choices ["1 tag" "2 meat damage"] :player :runner :msg "make the Runner take 1 tag or suffer 2 meat damage" :effect (req (if (= target "1 tag") (do (system-msg state side "chooses to take 1 tag") (gain-tags state :runner eid 1)) (do (system-msg state side "chooses to suffer 2 meat damage") (damage state :runner eid :meat 2 {:unboostable true :card card}))))}]}) (defcard "<NAME> \"<NAME>\" <NAME>: Tech Lord" {:events [{:event :runner-trash :async true :interactive (req true) :req (req (and (= side :runner) (= :ability-cost (:cause target)))) :msg "draw a card" :effect (effect (draw eid 1))}]}) (defcard "Asa Group: Security Through Vigilance" {:events [{:event :corp-install :async true :req (req (first-event? state :corp :corp-install)) :effect (req (let [installed-card (:card context) z (butlast (get-zone installed-card))] (continue-ability state side {:prompt (str "Choose a " (if (is-remote? z) "non-agenda" "piece of ice") " in HQ to install") :choices {:card #(and (in-hand? %) (corp? %) (corp-installable-type? %) (not (agenda? %)))} :async true :effect (effect (corp-install eid target (zone->name z) nil))} card nil)))}]}) (defcard "<NAME> \"<NAME>\" <NAME>: Simulant Specialist" {:abilities [{:label "Add 1 hosted card to your grip" :cost [:click 1] :async true :prompt "Choose a hosted card" :choices (req (cancellable (:hosted card))) :msg "move a hosted card to their Grip" :effect (effect (move target :hand) (effect-completed eid))}] :events [{:event :pre-start-game :req (req (= side :runner)) :async true :waiting-prompt "Runner to make a decision" :effect (req (doseq [c (take 6 (:deck runner))] (move state side c :play-area)) (continue-ability state side {:prompt "Choose 4 cards to be hosted" :choices {:max 4 :all true :card #(and (runner? %) (in-play-area? %))} :effect (req (doseq [c targets] (host state side (get-card state card) c {:facedown true})) (doseq [c (get-in @state [:runner :play-area])] (move state side c :deck)) (shuffle! state side :deck))} card nil))}]}) (defcard "Az McCaffrey: Mechanical Prodigy" ;; Effect marks Az's ability as "used" if it has already met it's trigger condition this turn (letfn [(az-type? [card] (or (hardware? card) (and (resource? card) (or (has-subtype? card "Job") (has-subtype? card "Connection"))))) (not-triggered? [state] (no-event? state :runner :runner-install #(az-type? (:card (first %)))))] {:constant-effects [{:type :install-cost :req (req (and (az-type? target) (not-triggered? state))) :value -1}] :events [{:event :runner-install :req (req (and (az-type? (:card context)) (not-triggered? state))) :silent (req true) :msg (msg "reduce the install cost of " (:title (:card context)) " by 1 [Credits]")}]})) (defcard "Azmari EdTech: Shaping the Future" {:events [{:event :corp-turn-ends :prompt "Name a card type" :choices ["Event" "Resource" "Program" "Hardware" "None"] :effect (effect (update! (assoc card :card-target (if (= "None" target) nil target))) (system-msg (str "uses Azmari EdTech: Shaping the Future to name " target)))} {:event :runner-install :req (req (and (:card-target card) (is-type? (:card context) (:card-target card)) (not (:facedown context)))) :async true :effect (effect (gain-credits :corp eid 2)) :once :per-turn :msg (msg "gain 2 [Credits] from " (:card-target card))} {:event :play-event :req (req (and (:card-target card) (is-type? (:card context) (:card-target card)))) :async true :effect (effect (gain-credits :corp eid 2)) :once :per-turn :msg (msg "gain 2 [Credits] from " (:card-target card))}]}) (defcard "Blue Sun: Powering the Future" {:flags {:corp-phase-12 (req (and (not (:disabled card)) (some rezzed? (all-installed state :corp))))} :abilities [{:choices {:card rezzed?} :label "Add 1 rezzed card to HQ and gain credits equal to its rez cost" :msg (msg "add " (:title target) " to HQ and gain " (rez-cost state side target) " [Credits]") :async true :effect (effect (move target :hand) (gain-credits eid (rez-cost state side target)))}]}) (defcard "<NAME>: Crafty Veteran" {:events [{:event :pre-start-game :effect draft-points-target} {:event :runner-turn-begins :req (req (and (has-most-faction? state :runner "Criminal") (pos? (get-in runner [:tag :base])))) :msg "remove 1 tag" :async true :effect (effect (lose-tags eid 1))}]}) (defcard "Cerebral Imaging: Infinite Frontiers" {:constant-effects [(corp-hand-size+ (req (:credit corp)))] :effect (req (swap! state assoc-in [:corp :hand-size :base] 0)) :leave-play (req (swap! state assoc-in [:corp :hand-size :base] 5))}) (defcard "Chaos Theory: Wünderkind" {:constant-effects [(mu+ 1)]}) (defcard "Chronos Protocol: Selective Mind-mapping" {:req (req (empty? (filter #(= :net (:damage-type (first %))) (turn-events state :runner :damage)))) :effect (effect (enable-corp-damage-choice)) :leave-play (req (swap! state update-in [:damage] dissoc :damage-choose-corp)) :events [{:event :corp-phase-12 :effect (effect (enable-corp-damage-choice))} {:event :runner-phase-12 :effect (effect (enable-corp-damage-choice))} {:event :pre-resolve-damage :optional {:player :corp :req (req (and (= target :net) (corp-can-choose-damage? state) (pos? (last targets)) (empty? (filter #(= :net (:damage-type (first %))) (turn-events state :runner :damage))) (pos? (count (:hand runner))))) :waiting-prompt "Corp to make a decision" :prompt "Use Chronos Protocol to choose the first card trashed?" :yes-ability {:async true :msg (msg "look at the Runner's Grip ( " (string/join ", " (map :title (sort-by :title (:hand runner)))) " ) and choose the card that is trashed") :effect (effect (continue-ability {:prompt "Choose a card to trash" :choices (req (:hand runner)) :not-distinct true :msg (msg "choose " (:title target) " to trash") :effect (req (chosen-damage state :corp target))} card nil))} :no-ability {:effect (req (system-msg state :corp "declines to use Chronos Protocol"))}}}]}) (defcard "Cybernetics Division: Humanity Upgraded" {:constant-effects [(hand-size+ -1)]}) (defcard "Earth Station: SEA Headquarters" (let [flip-effect (effect (update! (if (:flipped card) (do (system-msg state :corp "flipped their identity to Earth Station: SEA Headquarters") (assoc card :flipped false :face :front :code (subs (:code card) 0 5))) (assoc card :flipped true :face :back :code (str (subs (:code card) 0 5) "flip")))))] {:events [{:event :pre-first-turn :req (req (= side :corp)) :effect (effect (update! (assoc card :flipped false :face :front)))} {:event :successful-run :req (req (and (= :hq (target-server context)) (:flipped card))) :effect flip-effect}] :constant-effects [{:type :run-additional-cost :req (req (or (and (not (:flipped card)) (= :hq (:server (second targets)))) (and (:flipped card) (in-coll? (keys (get-remotes state)) (:server (second targets)))))) :value (req [:credit (if (:flipped card) 6 1)])}] :async true ; This effect will be resolved when the ID is reenabled after Strike / Direct Access :effect (effect (continue-ability {:req (req (< 1 (count (get-remotes state)))) :prompt "Choose a server to be saved from the rules apocalypse" :choices (req (get-remote-names state)) :async true :effect (req (let [to-be-trashed (remove #(in-coll? ["Archives" "R&D" "HQ" target] (zone->name (second (get-zone %)))) (all-installed state :corp))] (system-msg state side (str "chooses " target " to be saved from the rules apocalypse and trashes " (quantify (count to-be-trashed) "card"))) ; these cards get trashed by the game and not by players (trash-cards state side eid to-be-trashed {:unpreventable true :game-trash true})))} card nil)) :abilities [{:label "Flip identity to Earth Station: Ascending to Orbit" :req (req (not (:flipped card))) :cost [:click 1] :msg "flip their identity to Earth Station: Ascending to Orbit" :effect flip-effect} {:label "Manually flip identity to Earth Station: SEA Headquarters" :req (req (:flipped card)) :effect flip-effect}]})) (defcard "<NAME>: Humanity's Hammer" {:events [{:event :access :once :per-turn :req (req (and (operation? target) (first-event? state side :access #(operation? (first %))))) :async true :effect (req (if (in-discard? target) (effect-completed state side eid) (do (when run (swap! state assoc-in [:run :did-trash] true)) (swap! state assoc-in [:runner :register :trashed-card] true) (system-msg state :runner (str "uses <NAME>: Humanity's Hammer to" " trash " (:title target) " at no cost")) (trash state side eid target nil))))}]}) (defcard "Ele \"Smoke\" Scovak: Cynosure of the Net" {:recurring 1 :interactions {:pay-credits {:req (req (and (= :ability (:source-type eid)) (has-subtype? target "Icebreaker"))) :type :recurring}}}) (defcard "Exile: Streethawk" {:flags {:runner-install-draw true} :events [{:event :runner-install :async true :req (req (and (program? (:card context)) (some #{:discard} (:previous-zone (:card context))))) :msg "draw a card" :effect (effect (draw eid 1))}]}) (defcard "<NAME>: Crypto-Anarchist" {:interactions {:access-ability {:async true :once :per-turn :label "Trash card" :req (req (and (not (:disabled card)) (not (agenda? target)) (<= (play-cost state side target) (number-of-runner-virus-counters state)))) :waiting-prompt "Runner to make a decision" :effect (req (let [accessed-card target play-or-rez (:cost target)] (if (zero? play-or-rez) (continue-ability state side {:async true :msg (msg "trash " (:title accessed-card) " at no cost") :effect (effect (trash eid (assoc accessed-card :seen true) {:accessed true}))} card nil) (wait-for (resolve-ability state side (pick-virus-counters-to-spend play-or-rez) card nil) (if-let [msg (:msg async-result)] (do (system-msg state :runner (str "uses Freedom Khumalo: Crypto-Anarchist to" " trash " (:title accessed-card) " at no cost, spending " msg)) (trash state side eid (assoc accessed-card :seen true) {:accessed true})) ;; Player cancelled ability (do (swap! state dissoc-in [:per-turn (:cid card)]) (access-non-agenda state side eid accessed-card :skip-trigger-event true)))))))}}}) (defcard "Fringe Applications: Tomorrow, Today" {:events [{:event :pre-start-game :effect draft-points-target} {:event :runner-turn-begins :player :corp :req (req (and (not (:disabled card)) (has-most-faction? state :corp "Weyland Consortium") (some ice? (all-installed state side)))) :prompt "Choose a piece of ice to place 1 advancement token on" :choices {:card #(and (installed? %) (ice? %))} :msg (msg "place 1 advancement token on " (card-str state target)) :effect (req (add-prop state :corp target :advance-counter 1 {:placed true}))}]}) (defcard "<NAME>: Consummate Professional" {:events [{:event :successful-run :silent (req true) :req (req (and (= :hq (target-server context)) (first-successful-run-on-server? state :hq))) :msg "gain 2 [Credits]" :async true :effect (effect (gain-credits eid 2))}]}) (defcard "Gagarin Deep Space: Expanding the Horizon" {:events [{:event :pre-access-card :req (req (is-remote? (second (get-zone target)))) :effect (effect (access-cost-bonus [:credit 1])) :msg "make the Runner spend 1 [Credits] to access"}]}) (defcard "GameNET: Where Dreams are Real" (let [gamenet-ability {:req (req (and (:run @state) (= (:side (:source eid)) "Corp") (or (and (not= (:source-type eid) :runner-trash-corp-cards) (not= (:source-type eid) :runner-steal)) (some (fn [[cost source]] (and (some #(or (= (cost-name %) :credit) (= (cost-name %) :x-credits)) (merge-costs cost)) (= (:side (:source source)) "Corp"))) (:additional-costs eid))))) :async true :msg "gain 1 [Credits]" :effect (effect (gain-credits :corp eid 1))}] {:events [(assoc gamenet-ability :event :runner-credit-loss) (assoc gamenet-ability :event :runner-spent-credits)]})) (defcard "GRNDL: Power Unleashed" {:events [{:event :pre-start-game :req (req (= :corp side)) :async true :effect (req (wait-for (gain-credits state :corp 5) (if (zero? (count-bad-pub state)) (gain-bad-publicity state :corp eid 1) (effect-completed state side eid))))}]}) (defcard "Haarpsichord Studios: Entertainment Unleashed" {:constant-effects [{:type :cannot-steal :value (req (pos? (event-count state side :agenda-stolen)))}] :events [{:event :access :req (req (and (agenda? target) (pos? (event-count state side :agenda-stolen)))) :effect (effect (toast :runner "Cannot steal due to Haarpsichord Studios." "warning"))}]}) (defcard "Haas-Bioroid: Architects of Tomorrow" {:events [{:event :pass-ice :req (req (and (rezzed? (:ice context)) (has-subtype? (:ice context) "Bioroid") (first-event? state :runner :pass-ice (fn [targets] (let [context (first targets) ice (:ice context)] (and (rezzed? ice) (installed? ice) (has-subtype? ice "Bioroid"))))))) :waiting-prompt "Corp to make a decision" :prompt "Choose a Bioroid to rez" :player :corp :choices {:req (req (and (has-subtype? target "Bioroid") (not (rezzed? target)) (can-pay? state side (assoc eid :source card :source-type :rez) target nil [:credit (rez-cost state side target {:cost-bonus -4})])))} :msg (msg "rez " (:title target)) :async true :effect (effect (rez eid target {:cost-bonus -4}))}]}) (defcard "Haas-Bioroid: Engineering the Future" {:events [{:event :corp-install :req (req (first-event? state corp :corp-install)) :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits eid 1))}]}) (defcard "Haas-Bioroid: Precision Design" {:constant-effects [(corp-hand-size+ 1)] :events [{:event :agenda-scored :interactive (req true) :optional {:prompt "Add card from Archives to HQ?" :autoresolve (get-autoresolve :auto-precision-design) :yes-ability (corp-recur)}}] :abilities [(set-autoresolve :auto-precision-design "add card from Archives to HQ")]}) (defcard "Haas-Bioroid: Stronger Together" {:constant-effects [{:type :ice-strength :req (req (has-subtype? target "Bioroid")) :value 1}] :leave-play (effect (update-all-ice)) :effect (effect (update-all-ice))}) (defcard "<NAME> Ent.: Where You're the Star" (letfn [(format-grip [runner] (if (pos? (count (:hand runner))) (string/join ", " (map :title (sort-by :title (:hand runner)))) "no cards"))] {:events [{:event :post-runner-draw :req (req (is-tagged? state)) :msg (msg "see that the Runner drew: " (string/join ", " (map :title runner-currently-drawing)))} {:event :tags-changed :effect (req (if (is-tagged? state) (when-not (get-in @state [:runner :openhand]) (system-msg state :corp (str "uses " (get-title card) " make the Runner play with their grip revealed")) (system-msg state :corp (str "uses " (get-title card) " to see that the Runner currently has " (format-grip runner) " in their grip")) (reveal-hand state :runner)) (when (get-in @state [:runner :openhand]) (system-msg state :corp (str "uses " (get-title card) " stop making the Runner play with their grip revealed")) (system-msg state :corp (str "uses " (get-title card) " to see that the Runner had " (format-grip runner) " in their grip before it was concealed")) (conceal-hand state :runner))))}] :effect (req (when (is-tagged? state) (reveal-hand state :runner))) :leave-play (req (when (is-tagged? state) (conceal-hand state :runner)))})) (defcard "Harmony Medtech: Biomedical Pioneer" {:effect (effect (lose :agenda-point-req 1) (lose :runner :agenda-point-req 1)) :leave-play (effect (gain :agenda-point-req 1) (gain :runner :agenda-point-req 1))}) (defcard "<NAME>: Universal Scholar" {:events [{:event :runner-install :silent (req (not (and (first-event? state side :runner-install) (some #(is-type? % (:type (:card context))) (:hand runner))))) :req (req (and (first-event? state side :runner-install) (not (:facedown context)))) :once :per-turn :async true :waiting-prompt "Runner to make a decision" :effect (effect (continue-ability (let [itarget (:card context) card-type (:type itarget)] (if (some #(is-type? % (:type itarget)) (:hand runner)) {:optional {:prompt (str "Install another " card-type " from your Grip?") :yes-ability {:prompt (str "Choose another " card-type " to install from your Grip") :choices {:card #(and (is-type? % card-type) (in-hand? %))} :msg (msg "install " (:title target)) :async true :effect (effect (runner-install (assoc eid :source card :source-type :runner-install) target nil))}}} {:prompt (str "You have no " card-type "s in hand") :choices ["Carry on!"] :prompt-type :bogus})) card nil))}]}) (defcard "<NAME>: Untold Protagonist" (let [flip-effect (req (update! state side (if (:flipped card) (assoc card :flipped false :face :front :code (subs (:code card) 0 5) :subtype "Natural") (assoc card :flipped true :face :back :code (str (subs (:code card) 0 5) "flip") :subtype "Digital"))) (update-link state))] {:constant-effects [(link+ (req (:flipped card)) 1) {:type :gain-subtype :req (req (and (same-card? card target) (:flipped card))) :value "Digital"} {:type :lose-subtype :req (req (and (same-card? card target) (:flipped card))) :value "Natural"}] :events [{:event :pre-first-turn :req (req (= side :runner)) :effect (effect (update! (assoc card :flipped false :face :front)))} {:event :runner-turn-ends :interactive (req true) :async true :effect (req (cond (and (:flipped card) (not (:accessed-cards runner-reg))) (do (system-msg state :runner "flips their identity to Hoshiko Shiro: Untold Protagonist") (continue-ability state :runner {:effect flip-effect} card nil)) (and (not (:flipped card)) (:accessed-cards runner-reg)) (wait-for (gain-credits state :runner 2) (system-msg state :runner "gains 2 [Credits] and flips their identity to Hoshiko Shiro: Mahou Shoujo") (continue-ability state :runner {:effect flip-effect} card nil)) :else (effect-completed state side eid)))} {:event :runner-turn-begins :req (req (:flipped card)) :async true :effect (req (wait-for (draw state :runner 1) (wait-for (lose-credits state :runner (make-eid state eid) 1) (system-msg state :runner "uses Hoshiko Shiro: Mahou Shoujo to draw 1 card and lose 1 [Credits]") (effect-completed state side eid))))}] :abilities [{:label "flip ID" :msg "flip their ID manually" :effect flip-effect}]})) (defcard "Hyoubu Institute: Absolute Clarity" {:events [{:event :corp-reveal :once :per-turn :req (req (first-event? state side :corp-reveal #(pos? (count %)))) :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits eid 1))}] :abilities [{:cost [:click 1] :label "Reveal the top card of the Stack" :async true :effect (req (if-let [revealed-card (-> runner :deck first)] (do (system-msg state side (str "uses Hyoubu Institute: Absolute Clarity to reveal " (:title revealed-card) " from the top of the Stack")) (reveal state side eid revealed-card)) (effect-completed state side eid)))} {:cost [:click 1] :label "Reveal a random card from the Grip" :async true :effect (req (if-let [revealed-card (-> runner :hand shuffle first)] (do (system-msg state side (str "uses Hyoubu Institute: Absolute Clarity to reveal " (:title revealed-card) " from the Grip")) (reveal state side eid revealed-card)) (effect-completed state side eid)))}]}) (defcard "Iain Stirling: Retired Spook" (let [ability {:req (req (> (:agenda-point corp) (:agenda-point runner))) :once :per-turn :msg "gain 2 [Credits]" :async true :effect (effect (gain-credits eid 2))}] {:flags {:drip-economy true} :events [(assoc ability :event :runner-turn-begins)] :abilities [ability]})) (defcard "Industrial Genomics: Growing Solutions" {:constant-effects [{:type :trash-cost :value (req (count (remove :seen (:discard corp))))}]}) (defcard "Information Dynamics: All You Need To Know" {:events (let [inf {:req (req (and (not (:disabled card)) (has-most-faction? state :corp "NBN"))) :msg "give the Runner 1 tag" :async true :effect (effect (gain-tags :corp eid 1))}] [{:event :pre-start-game :effect draft-points-target} (assoc inf :event :agenda-scored) (assoc inf :event :agenda-stolen)])}) (defcard "<NAME> \"Bzzz\" Micken: Techno Savant" {:events [{:event :pre-start-game :effect draft-points-target} {:event :runner-install :req (req (and (has-most-faction? state :runner "Shaper") (first-event? state side :runner-install))) :msg "draw 1 card" :once :per-turn :async true :effect (effect (draw eid 1))}]}) (defcard "<NAME>ics: Sacrifice. Audacity. Success." {:events [{:event :corp-forfeit-agenda :async true :waiting-prompt "Corp to make a decision" :effect (effect (continue-ability (let [p (inc (get-agenda-points (:card context)))] {:prompt (str "Choose a card to place advancement tokens on with " (:title card)) :choices {:card #(and (installed? %) (corp? %))} :msg (msg "place " (quantify p "advancement token") " on " (card-str state target)) :effect (effect (add-prop :corp target :advance-counter p {:placed true}))}) card nil))}]}) (defcard "<NAME>: Girl Behind the Curtain" {:flags {:forced-to-avoid-tag true} :events [{:event :pre-tag :async true :once :per-run :req (req (:run @state)) :msg "avoid the first tag during this run" :effect (effect (tag-prevent :runner eid 1))}]}) (defcard "Jinteki Biotech: Life Imagined" {:events [{:event :pre-first-turn :req (req (= side :corp)) :prompt "Choose a copy of Jinteki Biotech to use this game" :choices ["The Brewery" "The Tank" "The Greenhouse"] :effect (effect (update! (assoc card :biotech-target target :face :front)) (system-msg (str "has chosen a copy of Jinteki Biotech for this game")))}] :abilities [{:label "Check chosen flip identity" :effect (req (case (:biotech-target card) "The Brewery" (toast state :corp "Flip to: The Brewery (Do 2 net damage)" "info") "The Tank" (toast state :corp "Flip to: The Tank (Shuffle Archives into R&D)" "info") "The Greenhouse" (toast state :corp "Flip to: The Greenhouse (Place 4 advancement tokens on a card)" "info") ;; default case (toast state :corp "No flip identity specified" "info")))} {:cost [:click 3] :req (req (not (:biotech-used card))) :label "Flip this identity" :async true :effect (req (let [flip (:biotech-target card)] (update! state side (assoc (get-card state card) :biotech-used true)) (case flip "The Brewery" (do (system-msg state side "uses The Brewery to do 2 net damage") (update! state side (assoc card :code "brewery" :face :brewery)) (damage state side eid :net 2 {:card card})) "The Tank" (do (system-msg state side "uses The Tank to shuffle Archives into R&D") (shuffle-into-deck state side :discard) (update! state side (assoc card :code "tank" :face :tank)) (effect-completed state side eid)) "The Greenhouse" (do (system-msg state side (str "uses The Greenhouse to place 4 advancement tokens " "on a card that can be advanced")) (update! state side (assoc card :code "greenhouse" :face :greenhouse)) (continue-ability state side {:prompt "Choose a card that can be advanced" :choices {:card can-be-advanced?} :effect (effect (add-prop target :advance-counter 4 {:placed true}))} card nil)) (toast state :corp (str "Unknown Jinteki Biotech: Life Imagined card: " flip) "error"))))}]}) (defcard "Jinteki: Personal Evolution" (let [ability {:async true :req (req (not (:winner @state))) :msg "do 1 net damage" :effect (effect (damage eid :net 1 {:card card}))}] {:events [(assoc ability :event :agenda-scored :interactive (req true)) (assoc ability :event :agenda-stolen)]})) (defcard "Jinteki: Potential Unleashed" {:events [{:async true :event :pre-resolve-damage :req (req (and (-> @state :corp :disable-id not) (= target :net) (pos? (last targets)))) :effect (req (let [c (first (get-in @state [:runner :deck]))] (system-msg state :corp (str "uses Jinteki: Potential Unleashed to trash " (:title c) " from the top of the Runner's Stack")) (mill state :corp eid :runner 1)))}]}) (defcard "Jinteki: Replicating Perfection" {:events [{:event :runner-phase-12 :effect (req (apply prevent-run-on-server state card (map first (get-remotes state))))} {:event :run :once :per-turn :req (req (is-central? (:server target))) :effect (req (apply enable-run-on-server state card (map first (get-remotes state))))}] :req (req (empty? (let [successes (turn-events state side :successful-run)] (filter is-central? (map :server successes))))) :effect (req (apply prevent-run-on-server state card (map first (get-remotes state)))) :leave-play (req (apply enable-run-on-server state card (map first (get-remotes state))))}) (defcard "Jinteki: Restoring Humanity" {:events [{:event :corp-turn-ends :req (req (pos? (count (remove :seen (:discard corp))))) :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits :corp eid 1))}]}) (defcard "Kabonesa Wu: Netspace Thrillseeker" {:abilities [{:label "Install a non-virus program from your stack, lowering the cost by 1 [Credit]" :cost [:click 1] :prompt "Choose a program" :choices (req (cancellable (filter #(and (program? %) (not (has-subtype? % "Virus")) (can-pay? state :runner (assoc eid :source card :source-type :runner-install) % nil [:credit (install-cost state side % {:cost-bonus -1})])) (:deck runner)))) :msg (msg "install " (:title target) " from the stack, lowering the cost by 1 [Credit]") :async true :effect (effect (trigger-event :searched-stack nil) (shuffle! :deck) (register-events card [{:event :runner-turn-ends :interactive (req true) :duration :end-of-turn :req (req (some #(get-in % [:special :kabonesa]) (all-installed state :runner))) :msg (msg "remove " (:title target) " from the game") :effect (req (doseq [program (filter #(get-in % [:special :kabonesa]) (all-installed state :runner))] (move state side program :rfg)))}]) (runner-install (assoc eid :source card :source-type :runner-install) (assoc-in target [:special :kabonesa] true) {:cost-bonus -1}))}]}) (defcard "Kate \"Mac\" <NAME>: Digital Tinker" ;; Effect marks Kate's ability as "used" if it has already met it's trigger condition this turn (letfn [(kate-type? [card] (or (hardware? card) (program? card))) (not-triggered? [state card] (no-event? state :runner :runner-install #(kate-type? (:card (first %)))))] {:constant-effects [{:type :install-cost :req (req (and (kate-type? target) (not-triggered? state card))) :value -1}] :events [{:event :runner-install :req (req (and (kate-type? (:card context)) (not-triggered? state card))) :silent (req true) :msg (msg "reduce the install cost of " (:title (:card context)) " by 1 [Credits]")}]})) (defcard "Ken \"Express\" Tenma: Disappeared Clone" {:events [{:event :play-event :req (req (and (has-subtype? (:card context) "Run") (first-event? state :runner :play-event #(has-subtype? (:card (first %)) "Run")))) :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits eid 1))}]}) (defcard "Khan: Savvy Skiptracer" {:events [{:event :pass-ice :req (req (first-event? state :runner :pass-ice)) :async true :interactive (req true) :effect (effect (continue-ability (when (some #(and (has-subtype? % "Icebreaker") (can-pay? state side (assoc eid :source card :source-type :runner-install) % nil [:credit (install-cost state side % {:cost-bonus -1})])) (:hand runner)) {:prompt "Choose an icebreaker to install from your Grip" :choices {:req (req (and (in-hand? target) (has-subtype? target "Icebreaker") (can-pay? state side (assoc eid :source card :source-type :runner-install) target nil [:credit (install-cost state side target {:cost-bonus -1})])))} :async true :msg (msg "install " (:title target) ", lowering the cost by 1 [Credits]") :effect (effect (runner-install eid target {:cost-bonus -1}))}) card nil))}]}) (defcard "Laramy Fisk: Savvy Investor" {:events [{:event :successful-run :async true :interactive (get-autoresolve :auto-fisk (complement never?)) :silent (get-autoresolve :auto-fisk never?) :optional {:req (req (and (is-central? (:server context)) (first-event? state side :successful-run (fn [targets] (let [context (first targets)] (is-central? (:server context))))))) :autoresolve (get-autoresolve :auto-fisk) :prompt "Force the Corp to draw a card?" :yes-ability {:msg "force the Corp to draw 1 card" :async true :effect (effect (draw :corp eid 1))} :no-ability {:effect (effect (system-msg "declines to use Laramy Fisk: Savvy Investor"))}}}] :abilities [(set-autoresolve :auto-fisk "force Corp draw")]}) (defcard "Lat: Ethical Freelancer" {:events [{:event :runner-turn-ends :optional {:req (req (= (count (:hand runner)) (count (:hand corp)))) :autoresolve (get-autoresolve :auto-lat) :prompt "Draw 1 card?" :yes-ability {:async true :msg "draw 1 card" :effect (effect (draw :runner eid 1))} :no-ability {:effect (effect (system-msg "declines to use Lat: Ethical Freelancer"))}}}] :abilities [(set-autoresolve :auto-lat "Lat: Ethical Freelancer")]}) (defcard "<NAME>: Trained Pragmatist" (let [leela {:interactive (req true) :prompt "Choose an unrezzed card to return to HQ" :choices {:card #(and (not (rezzed? %)) (installed? %) (corp? %))} :msg (msg "add " (card-str state target) " to HQ") :effect (effect (move :corp target :hand))}] {:events [(assoc leela :event :agenda-scored) (assoc leela :event :agenda-stolen)]})) (defcard "Liza Talking Thunder: Prominent Legislator" {:events [{:event :successful-run :async true :interactive (req true) :msg "draw 2 cards and take 1 tag" :req (req (and (is-central? (:server context)) (first-event? state side :successful-run (fn [targets] (let [context (first targets)] (is-central? (:server context))))))) :effect (req (wait-for (gain-tags state :runner 1) (draw state :runner eid 2)))}]}) (defcard "Los: Data Hijacker" {:events [{:event :rez :once :per-turn :req (req (ice? (:card context))) :msg "gain 2 [Credits]" :async true :effect (effect (gain-credits :runner eid 2))}]}) (defcard "MaxX: Maximum Punk Rock" (let [ability {:msg (msg (let [deck (:deck runner)] (if (pos? (count deck)) (str "trash " (string/join ", " (map :title (take 2 deck))) " from their Stack and draw 1 card") "trash the top 2 cards from their Stack and draw 1 card - but their Stack is empty"))) :label "trash and draw cards" :once :per-turn :async true :effect (req (wait-for (mill state :runner :runner 2) (draw state :runner eid 1)))}] {:flags {:runner-turn-draw true :runner-phase-12 (req (and (not (:disabled card)) (some #(card-flag? % :runner-turn-draw true) (all-active-installed state :runner))))} :events [(assoc ability :event :runner-turn-begins)] :abilities [ability]})) (defcard "MirrorMorph: Endless Iteration" (let [mm-clear {:prompt "Manually fix Mirrormorph" :msg (msg "manually clear Mirrormorph flags") :effect (effect (update! (assoc-in card [:special :mm-actions] [])) (update! (assoc-in (get-card state card) [:special :mm-click] false)))} mm-ability {:prompt "Gain [Click] or gain 1 [Credits]" :choices ["Gain [Click]" "Gain 1 [Credits]"] :msg (msg (decapitalize target)) :once :per-turn :label "Manually trigger ability" :async true :effect (req (if (= "Gain [Click]" target) (do (gain-clicks state side 1) (update! state side (assoc-in (get-card state card) [:special :mm-click] true)) (effect-completed state side eid)) (gain-credits state side eid 1)))}] {:implementation "Does not work with terminal Operations" :abilities [mm-ability mm-clear] :events [{:event :corp-spent-click :async true :effect (req (let [cid (first target) ability-idx (:ability-idx (:source-info eid)) bac-cid (get-in @state [:corp :basic-action-card :cid]) cause (if (keyword? (first target)) (case (first target) :play-instant [bac-cid 3] :corp-click-install [bac-cid 2] (first target)) ; in clojure there's: (= [1 2 3] '(1 2 3)) [cid ability-idx]) prev-actions (get-in card [:special :mm-actions] []) actions (conj prev-actions cause)] (update! state side (assoc-in card [:special :mm-actions] actions)) (update! state side (assoc-in (get-card state card) [:special :mm-click] false)) (if (and (= 3 (count actions)) (= 3 (count (distinct actions)))) (continue-ability state side mm-ability (get-card state card) nil) (effect-completed state side eid))))} {:event :runner-turn-begins :effect (effect (update! (assoc-in card [:special :mm-actions] [])) (update! (assoc-in (get-card state card) [:special :mm-click] false)))} {:event :corp-turn-ends :effect (effect (update! (assoc-in card [:special :mm-actions] [])) (update! (assoc-in (get-card state card) [:special :mm-click] false)))}] :constant-effects [{:type :prevent-paid-ability :req (req (and (get-in card [:special :mm-click]) (let [cid (:cid target) ability-idx (nth targets 2 nil) cause [cid ability-idx] prev-actions (get-in card [:special :mm-actions] []) actions (conj prev-actions cause)] (not (and (= 4 (count actions)) (= 4 (count (distinct actions)))))))) :value true}]})) (defcard "<NAME>ti Mwekundu: Life Improved" {:events [{:event :approach-server :async true :interactive (req true) :waiting "Corp to make a decision" :req (req (and (pos? (count (:hand corp))) (not (used-this-turn? (:cid card) state)))) :effect (req (if (some ice? (:hand corp)) (continue-ability state side {:optional {:prompt "Install a piece of ice?" :once :per-turn :yes-ability {:prompt "Choose a piece of ice to install from HQ" :choices {:card #(and (ice? %) (in-hand? %))} :async true :msg "install a piece of ice at the innermost position of this server. Runner is now approaching that piece of ice" :effect (req (wait-for (corp-install state side target (zone->name (target-server run)) {:ignore-all-cost true :front true}) (swap! state assoc-in [:run :position] 1) (set-next-phase state :approach-ice) (update-all-ice state side) (update-all-icebreakers state side) (continue-ability state side (offer-jack-out {:req (req (:approached-ice? (:run @state)))}) card nil)))}}} card nil) ;; bogus prompt so Runner cannot infer the Corp has no ice in hand (continue-ability state :corp {:async true :prompt "No ice to install" :choices ["Carry on!"] :prompt-type :bogus :effect (effect (effect-completed eid))} card nil)))}]}) (defcard "<NAME>: Cyber Explorer" {:events [{:event :approach-ice :req (req (not (rezzed? (:ice context)))) :effect (effect (register-events card (let [ice (:ice context) cost (rez-cost state side ice)] [{:event :encounter-ice :duration :end-of-encounter :unregister-once-resolved true :req (req (same-card? (:ice context) ice)) :msg (msg "lose all credits and gain " cost " [Credits] from the rez of " (:title ice)) :async true :effect (req (wait-for (lose-credits state :runner (make-eid state eid) :all) (gain-credits state :runner eid cost)))}])))}]}) (defcard "<NAME> \"<NAME>\" Hall: One-of-a-Kind" (let [ability {:label "Gain 1 [Credits] (start of turn)" :once :per-turn :interactive (req true) :async true :effect (req (if (and (> 3 (count (:hand runner))) (:runner-phase-12 @state)) (do (system-msg state :runner (str "uses " (:title card) " to gain 1 [Credits]")) (gain-credits state :runner eid 1)) (effect-completed state side eid)))}] {:flags {:drip-economy true :runner-phase-12 (req (and (not (:disabled card)) (some #(card-flag? % :runner-turn-draw true) (all-active-installed state :runner))))} :abilities [ability] :events [(assoc ability :event :runner-turn-begins)]})) (defcard "NBN: Controlling the Message" {:events [{:event :runner-trash :interactive (req true) :once-per-instance true :optional {:player :corp :req (req (and (some #(and (corp? (:card %)) (installed? (:card %))) targets) (first-event? state side :runner-trash (fn [targets] (some #(and (installed? (:card %)) (corp? (:card %))) targets))))) :waiting-prompt "Corp to make a decision" :prompt "Trace the Runner with NBN: Controlling the Message?" :autoresolve (get-autoresolve :auto-ctm) :yes-ability {:trace {:base 4 :successful {:msg "give the Runner 1 tag" :async true :effect (effect (gain-tags :corp eid 1 {:unpreventable true}))}}}}}] :abilities [(set-autoresolve :auto-ctm "CtM")]}) (defcard "NBN: Making News" {:recurring 2 :interactions {:pay-credits {:req (req (= :trace (:source-type eid))) :type :recurring}}}) (defcard "NBN: Reality Plus" {:events [{:event :runner-gain-tag :req (req (first-event? state :runner :runner-gain-tag)) :player :corp :async true :waiting-prompt "Corp to choose an option" :prompt "Choose option" :choices ["Gain 2 [Credits]" "Draw 2 cards"] :msg (msg (decapitalize target)) :effect (req (if (= target "Gain 2 [Credits]") (gain-credits state :corp eid 2) (draw state :corp eid 2)))}]}) (defcard "NBN: The World is Yours*" {:constant-effects [(corp-hand-size+ 1)]}) (defcard "Near-Earth Hub: Broadcast Center" {:events [{:event :server-created :req (req (first-event? state :corp :server-created)) :async true :msg "draw 1 card" :effect (req (if-not (some #(= % :deck) (:zone target)) (draw state :corp eid 1) (do ;; Register the draw to go off when the card is finished installing - ;; this is after the checkpoint when it should go off, but is needed to ;; fix the interaction between architect (and any future install from R&D ;; cards) and NEH, where the card would get drawn before the install, ;; fizzling it in a confusing manner. Because we only do it in this ;; special case, there should be no gameplay implications. -nb<NAME>, 2022 (register-events state side card [{:event :corp-install :interactive (req true) :duration (req true) :unregister-once-resolved true :async true :effect (effect (draw :corp eid 1))}]) (effect-completed state side eid))))}]}) (defcard "<NAME>: Information Broker" {:events [{:event :encounter-ice :optional (:optional (offer-jack-out {:req (req (has-subtype? (:ice context) "Sentry")) :once :per-turn}))}]}) (defcard "New Angeles Sol: Your News" (let [nasol {:optional {:prompt "Play a Current?" :player :corp :req (req (some #(has-subtype? % "Current") (concat (:hand corp) (:discard corp) (:current corp)))) :yes-ability {:prompt "Choose a Current to play from HQ or Archives" :show-discard true :async true :choices {:card #(and (has-subtype? % "Current") (corp? %) (or (in-hand? %) (in-discard? %)))} :msg (msg "play a current from " (name-zone "Corp" (get-zone target))) :effect (effect (play-instant eid target))}}}] {:events [(assoc nasol :event :agenda-scored) (assoc nasol :event :agenda-stolen)]})) (defcard "NEXT Design: Guarding the Net" (let [ndhelper (fn nd [n] {:prompt (str "When finished, click NEXT Design: Guarding the Net to draw back up to 5 cards in HQ. " "Choose a piece of ice in HQ to install:") :choices {:card #(and (corp? %) (ice? %) (in-hand? %))} :effect (req (wait-for (corp-install state side target nil nil) (continue-ability state side (when (< n 3) (nd (inc n))) card nil)))})] {:events [{:event :pre-first-turn :req (req (= side :corp)) :msg "install up to 3 pieces of ice and draw back up to 5 cards" :async true :effect (req (wait-for (resolve-ability state side (ndhelper 1) card nil) (update! state side (assoc card :fill-hq true)) (effect-completed state side eid)))}] :abilities [{:req (req (:fill-hq card)) :label "draw remaining cards" :msg (msg "draw " (- 5 (count (:hand corp))) " cards") :async true :effect (req (wait-for (draw state side (- 5 (count (:hand corp))) {:suppress-event true}) (update! state side (dissoc card :fill-hq)) (swap! state assoc :turn-events nil) (effect-completed state side eid)))}]})) (defcard "Nisei Division: The Next Generation" {:events [{:event :reveal-spent-credits :req (req (and (some? (first targets)) (some? (second targets)))) :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits :corp eid 1))}]}) (defcard "Noise: Hacker Extraordinaire" {:events [{:async true :event :runner-install :req (req (has-subtype? (:card context) "Virus")) :msg "force the Corp to trash the top card of R&D" :effect (effect (mill :corp eid :corp 1))}]}) (defcard "Null: Whistleblower" {:events [{:event :encounter-ice :optional {:req (req (pos? (count (:hand runner)))) :prompt "Trash a card in grip to lower ice strength by 2?" :once :per-turn :yes-ability {:prompt "Choose a card in your Grip to trash" :choices {:card in-hand?} :msg (msg "trash " (:title target) " and reduce the strength of " (:title current-ice) " by 2 for the remainder of the run") :async true :effect (effect (register-floating-effect card (let [ice current-ice] {:type :ice-strength :duration :end-of-run :req (req (same-card? target ice)) :value -2})) (update-all-ice) (trash eid target {:unpreventable true}))}}}]}) (defcard "<NAME>: Conspiracy Theorist" {:abilities [{:cost [:click 1] :msg "make a run on Archives" :once :per-turn :makes-run true :async true :effect (effect (update! (assoc-in card [:special :omar-run] true)) (make-run eid :archives (get-card state card)))}] :events [{:event :pre-successful-run :interactive (req true) :req (req (and (get-in card [:special :omar-run]) (= :archives (-> run :server first)))) :prompt "Treat as a successful run on which server?" :choices ["HQ" "R&D"] :effect (req (let [target-server (if (= target "HQ") :hq :rd)] (swap! state assoc-in [:run :server] [target-server]) (trigger-event state :corp :no-action) (system-msg state side (str "uses Omar Keung: Conspiracy Theorist to make a successful run on " target))))} {:event :run-ends :effect (effect (update! (dissoc-in card [:special :omar-run])))}]}) (defcard "Pālanā Foods: Sustainable Growth" {:events [{:event :runner-draw :req (req (and (first-event? state :corp :runner-draw) (pos? (:count target)))) :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits :corp eid 1))}]}) (defcard "Quetzal: Free Spirit" {:abilities [(assoc (break-sub nil 1 "Barrier" {:repeatable false}) :once :per-turn)]}) (defcard "<NAME>: Freedom Fighter" (letfn [(not-triggered? [state] (no-event? state :runner :rez #(ice? (:card (first %)))))] {:constant-effects [{:type :rez-cost :req (req (and (ice? target) (not (rezzed? target)) (not-triggered? state))) :value 1}] :events [{:event :rez :req (req (and (ice? (:card context)) (not-triggered? state))) :msg (msg "increased the rez cost of " (:title (:card context)) " by 1 [Credits]")}]})) (defcard "<NAME> \"<NAME>\" <NAME>: Party Animal" {:events [{:event :runner-trash :req (req (and (:accessed context) (first-event? state side :runner-trash (fn [targets] (some #(:accessed %) targets))))) :async true :msg "gain 1 [Credits] and draw 1 card" :effect (req (wait-for (draw state :runner 1) (gain-credits state :runner eid 1)))}]}) (defcard "<NAME> \"<NAME>\" <NAME>: Transhuman" {:events [{:event :encounter-ice :once :per-turn :msg (msg "make " (:title (:ice context)) " gain Code Gate until the end of the run") :effect (effect (register-floating-effect card (let [ice (:ice context)] {:type :gain-subtype :duration :end-of-run :req (req (same-card? ice target)) :value "Code Gate"})))}]}) (defcard "<NAME>ati Mnemonics: Endless Exploration" (letfn [(install-card [chosen] {:prompt "Choose a remote server" :choices (req (conj (vec (get-remote-names state)) "New remote")) :async true :effect (req (let [tgtcid (:cid chosen)] (register-persistent-flag! state side card :can-rez (fn [state _ card] (if (= (:cid card) tgtcid) ((constantly false) (toast state :corp "Cannot rez due to Saraswati Mnemonics: Endless Exploration." "warning")) true))) (register-turn-flag! state side card :can-score (fn [state side card] (if (and (= (:cid card) tgtcid) (<= (get-advancement-requirement card) (get-counters card :advancement))) ((constantly false) (toast state :corp "Cannot score due to Saraswati Mnemonics: Endless Exploration." "warning")) true)))) (wait-for (corp-install state side chosen target nil) (add-prop state :corp (find-latest state chosen) :advance-counter 1 {:placed true}) (effect-completed state side eid)))})] {:abilities [{:async true :label "Install a card from HQ" :cost [:click 1 :credit 1] :prompt "Choose a card to install from HQ" :choices {:card #(and (or (asset? %) (agenda? %) (upgrade? %)) (corp? %) (in-hand? %))} :msg (msg "install a card in a remote server and place 1 advancement token on it") :effect (effect (continue-ability (install-card target) card nil))}] :events [{:event :corp-turn-begins :effect (req (clear-persistent-flag! state side card :can-rez))}]})) (defcard "Seidr Laboratories: Destiny Defined" {:implementation "Manually triggered" :abilities [{:req (req (and run (seq (:discard corp)))) :label "add card from Archives to R&D during a run" :once :per-turn :prompt "Choose a card to add to the top of R&D" :show-discard true :choices {:card #(and (corp? %) (in-discard? %))} :effect (effect (move target :deck {:front true})) :msg (msg "add " (if (:seen target) (:title target) "a card") " to the top of R&D")}]}) (defcard "Silhouette: Stealth Operative" {:events [{:event :successful-run :interactive (req (some #(not (rezzed? %)) (all-installed state :corp))) :async true :req (req (and (= :hq (target-server context)) (first-successful-run-on-server? state :hq))) :choices {:card #(and (installed? %) (not (rezzed? %)))} :msg "expose 1 card" :effect (effect (expose eid target))}]}) (defcard "Skorpios Defense Systems: Persuasive Power" {:implementation "Manually triggered, no restriction on which cards in Heap can be targeted. Cannot use on in progress run event" :abilities [{:label "Remove a card in the Heap that was just trashed from the game" :waiting-prompt "Corp to make a decision" :prompt "Choose a card in the Runner's Heap that was just trashed" :once :per-turn :choices (req (cancellable (:discard runner))) :msg (msg "remove " (:title target) " from the game") :effect (req (move state :runner target :rfg))}]}) (defcard "Spark Agency: Worldswide Reach" {:events [{:event :rez :req (req (and (has-subtype? (:card context) "Advertisement") (first-event? state :corp :rez #(has-subtype? (:card (first %)) "Advertisement")))) :async true :effect (effect (lose-credits :runner eid 1)) :msg "make the Runner lose 1 [Credits] by rezzing an Advertisement"}]}) (defcard "Sportsmetal: Go Big or Go Home" (let [ab {:prompt "Gain 2 [Credits] or draw 2 cards?" :player :corp :choices ["Gain 2 [Credits]" "Draw 2 cards"] :msg (msg (if (= target "Gain 2 [Credits]") "gain 2 [Credits]" "draw 2 cards")) :async true :interactive (req true) :effect (req (if (= target "Gain 2 [Credits]") (gain-credits state :corp eid 2) (draw state :corp eid 2)))}] {:events [(assoc ab :event :agenda-scored) (assoc ab :event :agenda-stolen)]})) (defcard "SSO Industries: Fueling Innovation" (letfn [(installed-faceup-agendas [state] (->> (all-installed state :corp) (filter agenda?) (filter faceup?))) (selectable-ice? [card] (and (ice? card) (installed? card) (zero? (get-counters card :advancement)))) (ice-with-no-advancement-tokens [state] (->> (all-installed state :corp) (filter selectable-ice?)))] {:events [{:event :corp-turn-ends :optional {:req (req (and (not-empty (installed-faceup-agendas state)) (not-empty (ice-with-no-advancement-tokens state)))) :waiting-prompt "Corp to make a decision" :prompt "Place advancement tokens?" :autoresolve (get-autoresolve :auto-sso) :yes-ability {:async true :effect (req (let [agendas (installed-faceup-agendas state) agenda-points (->> agendas (map :agendapoints) (reduce +)) ice (ice-with-no-advancement-tokens state)] (continue-ability state side {:prompt (str "Choose a piece of ice with no advancement tokens to place " (quantify agenda-points "advancement token") " on") :choices {:card #(selectable-ice? %)} :msg (msg "place " (quantify agenda-points "advancement token") " on " (card-str state target)) :effect (effect (add-prop target :advance-counter agenda-points {:placed true}))} card nil)))}}}] :abilities [(set-autoresolve :auto-sso "SSO")]})) (defcard "<NAME>: Master Grifter" {:events [{:event :successful-run :optional {:req (req (and (= :hq (target-server context)) (first-successful-run-on-server? state :hq) (<= 2 (count (:discard runner))) (not (zone-locked? state :runner :discard)))) :prompt "Use Steve Cambridge ability?" :yes-ability {:interactive (req true) :async true :prompt "Choose 2 cards in your Heap" :show-discard true :choices {:max 2 :all true :card #(and (in-discard? %) (runner? %))} :effect (effect (continue-ability (let [c1 (first targets) c2 (second targets)] {:waiting-prompt "Corp to make a decision" :prompt "Choose which card to remove from the game" :player :corp :choices [c1 c2] :msg (msg (let [[chosen other](if (= target c1) [c1 c2] [c2 c1])] (str "add " (:title other) " to their grip." " Corp removes " (:title chosen) " from the game"))) :effect (req (let [[chosen other] (if (= target c1) [c1 c2] [c2 c1])] (move state :runner chosen :rfg) (move state :runner other :hand)))}) card nil))}}}]}) (defcard "Strategic Innovations: Future Forward" {:events [{:event :pre-start-game :effect draft-points-target} {:event :runner-turn-ends :req (req (and (not (:disabled card)) (has-most-faction? state :corp "Haas-Bioroid") (pos? (count (:discard corp))))) :prompt "Choose a card in Archives to shuffle into R&D" :choices {:card #(and (corp? %) (in-discard? %))} :player :corp :show-discard true :msg (msg "shuffle " (if (:seen target) (:title target) "a card") " into R&D") :effect (effect (move :corp target :deck) (shuffle! :corp :deck))}]}) (defcard "<NAME>: Security Specialist" ;; No special implementation {}) (defcard "SYNC: Everything, Everywhere" {:constant-effects [{:type :card-ability-additional-cost :req (req (let [targetcard (first targets) target (second targets)] (and (not (:sync-flipped card)) (same-card? targetcard (:basic-action-card runner)) (= "Remove 1 tag" (:label target))))) :value [:credit 1]} {:type :card-ability-additional-cost :req (req (let [targetcard (first targets) target (second targets)] (and (:sync-flipped card) (same-card? targetcard (:basic-action-card corp)) (= "Trash 1 resource if the Runner is tagged" (:label target))))) :value [:credit -2]}] :abilities [{:cost [:click 1] :effect (req (if (:sync-flipped card) (update! state side (-> card (assoc :sync-flipped false :face :front :code "09001"))) (update! state side (-> card (assoc :sync-flipped true :face :back :code "sync"))))) :label "Flip this identity" :msg "flip their ID"}]}) (defcard "Synthetic Systems: The World Re-imagined" {:events [{:event :pre-start-game :effect draft-points-target}] :flags {:corp-phase-12 (req (and (not (:disabled (get-card state card))) (has-most-faction? state :corp "Jinteki") (<= 2 (count (filter ice? (all-installed state :corp))))))} :abilities [{:prompt "Choose two pieces of installed ice to swap" :label "swap two pieces of installed ice" :choices {:card #(and (installed? %) (ice? %)) :max 2 :all true} :once :per-turn :effect (req (apply swap-ice state side targets)) :msg (msg "swap the positions of " (card-str state (first targets)) " and " (card-str state (second targets)))}]}) (defcard "Tāo Salonga: Telepresence Magician" (let [swap-ability {:interactive (req true) :optional {:req (req (<= 2 (count (filter ice? (all-installed state :corp))))) :prompt "Swap ice with Tāo Salonga's ability?" :waiting-prompt "the Runner to swap ice." :yes-ability {:prompt "Choose 2 ice" :choices {:req (req (and (installed? target) (ice? target))) :max 2 :all true} :msg (msg "swap the positions of " (card-str state (first targets)) " and " (card-str state (second targets))) :effect (req (swap-ice state side (first targets) (second targets)))} :no-ability {:effect (effect (system-msg "declines to use Tāo Salonga: Telepresence Magician"))}}}] {:events [(assoc swap-ability :event :agenda-scored) (assoc swap-ability :event :agenda-stolen)]})) (defcard "Tennin Institute: The Secrets Within" {:flags {:corp-phase-12 (req (and (not (:disabled (get-card state card))) (not-last-turn? state :runner :successful-run)))} :abilities [{:msg (msg "place 1 advancement token on " (card-str state target)) :label "Place 1 advancement token on a card if the Runner did not make a successful run last turn" :choices {:card installed?} :req (req (and (:corp-phase-12 @state) (not-last-turn? state :runner :successful-run))) :once :per-turn :effect (effect (add-prop target :advance-counter 1 {:placed true}))}]}) (defcard "The Catalyst: Convention Breaker" ;; No special implementation {}) (defcard "The Foundry: Refining the Process" {:events [{:event :rez :optional {:prompt "Add another copy to HQ?" :req (req (and (ice? (:card context)) (first-event? state :runner :rez #(ice? (:card (first %)))))) :yes-ability {:effect (req (if-let [found-card (some #(when (= (:title %) (:title (:card context))) %) (concat (:deck corp) (:play-area corp)))] (do (move state side found-card :hand) (system-msg state side (str "uses The Foundry to add a copy of " (:title found-card) " to HQ, and shuffles their deck")) (shuffle! state side :deck)) (do (system-msg state side (str "fails to find a target for The Foundry, and shuffles their deck")) (shuffle! state side :deck))))}}}]}) (defcard "The Masque: Cyber General" {:events [{:event :pre-start-game :effect draft-points-target}]}) (defcard "The Outfit: Family Owned and Operated" {:events [{:event :corp-gain-bad-publicity :msg "gain 3 [Credit]" :async true :effect (effect (gain-credits eid 3))}]}) (defcard "The Professor: Keeper of Knowledge" ;; No special implementation {}) (defcard "The Shadow: Pulling the Strings" {:events [{:event :pre-start-game :effect draft-points-target}]}) (defcard "The Syndicate: Profit over Principle" ;; No special implementation {}) (defcard "Titan Transnational: Investing In Your Future" {:events [{:event :agenda-scored :msg (msg "place 1 agenda counter on " (:title (:card context))) :effect (effect (add-counter (get-card state (:card context)) :agenda 1))}]}) (defcard "<NAME>: The Angel of Cayambe" {:events [{:event :pre-start-game :req (req (and (= side :runner) (zero? (count-bad-pub state)))) ;; This doesn't use `gain-bad-publicity` to avoid the event :effect (effect (gain :corp :bad-publicity 1))}]}) (defcard "Weyland Consortium: Because We Built It" {:recurring 1 :interactions {:pay-credits {:req (req (= :advance (:source-type eid))) :type :recurring}}}) (defcard "Weyland Consortium: Builder of Nations" {:implementation "Erratum: The first time an encounter with a piece of ice with at least 1 advancement token ends each turn, do 1 meat damage." :events [{:event :end-of-encounter :async true :req (req (and (rezzed? (:ice context)) (pos? (get-counters (:ice context) :advancement)) (first-event? state :runner :end-of-encounter (fn [targets] (let [context (first targets)] (and (rezzed? (:ice context)) (pos? (get-counters (:ice context) :advancement)))))))) :msg "do 1 meat damage" :effect (effect (damage eid :meat 1 {:card card}))}]}) (defcard "Weyland Consortium: Building a Better World" {:events [{:event :play-operation :req (req (has-subtype? (:card context) "Transaction")) :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits eid 1))}]}) (defcard "Weyland Consortium: Built to Last" {:events [{:event :advance :async true :req (req ((complement pos?) (- (get-counters target :advancement) (:amount (second targets) 0)))) :msg "gain 2 [Credits]" :effect (req (gain-credits state :corp eid 2))}]}) (defcard "Whizzard: Master Gamer" {:recurring 3 :interactions {:pay-credits {:req (req (and (= :runner-trash-corp-cards (:source-type eid)) (corp? target))) :type :recurring}}}) (defcard "Wyvern: Chemically Enhanced" {:events [{:event :pre-start-game :effect draft-points-target} {:event :runner-trash :interactive (req true) :req (req (and (has-most-faction? state :runner "Anarch") (corp? (:card target)) (pos? (count (:discard runner))) (not (zone-locked? state :runner :discard)))) :msg (msg "shuffle " (:title (last (:discard runner))) " into their Stack") :effect (effect (move :runner (last (:discard runner)) :deck) (shuffle! :runner :deck) (trigger-event :searched-stack nil))}]}) (defcard "<NAME>: Versatile Smuggler" {:events [{:event :run-ends :optional {:req (req (and (#{:hq :rd} (target-server context)) (pos? (total-cards-accessed context)))) :prompt "Gain 1 [Credits] for each card you accessed?" :async true :once :per-turn :yes-ability {:msg (msg "gain " (total-cards-accessed context) " [Credits]") :once :per-turn :async true :effect (req (gain-credits state :runner eid (total-cards-accessed context)))}}}]})
true
(ns game.cards.identities (:require [game.core :refer :all] [game.utils :refer :all] [jinteki.utils :refer :all] [clojure.string :as string])) ;;; Helper functions for Draft cards (def draft-points-target "Set each side's agenda points target at 6, per draft format rules" (req (swap! state assoc-in [:runner :agenda-point-req] 6) (swap! state assoc-in [:corp :agenda-point-req] 6))) (defn- has-most-faction? "Checks if the faction has a plurality of rezzed / installed cards" [state side fc] (let [card-list (all-active-installed state side) faction-freq (frequencies (map :faction card-list)) reducer (fn [{:keys [max-count] :as acc} faction count] (cond ;; Has plurality update best-faction (> count max-count) {:max-count count :max-faction faction} ;; Lost plurality (= count max-count) (dissoc acc :max-faction) ;; Count is not more, do not change the accumulator map :else acc)) best-faction (:max-faction (reduce-kv reducer {:max-count 0 :max-faction nil} faction-freq))] (= fc best-faction))) ;; Card definitions (defcard "419: Amoral Scammer" {:events [{:event :corp-install :async true :req (req (and (first-event? state :corp :corp-install) (pos? (:turn @state)) (not (rezzed? (:card context))) (not (#{:rezzed-no-cost :rezzed-no-rez-cost :rezzed :face-up} (:install-state context))))) :waiting-prompt "Runner to choose an option" :effect (effect (continue-ability {:optional {:prompt "Expose installed card unless Corp pays 1 [Credits]?" :player :runner :autoresolve (get-autoresolve :auto-419) :no-ability {:effect (req (clear-wait-prompt state :corp))} :yes-ability {:async true :effect (req (if (not (can-pay? state :corp eid card nil :credit 1)) (do (toast state :corp "Cannot afford to pay 1 [Credit] to block card exposure" "info") (expose state :runner eid (:card context))) (continue-ability state side {:optional {:waiting-prompt "Corp to choose an option" :prompt "Pay 1 [Credits] to prevent exposure of installed card?" :player :corp :no-ability {:async true :effect (effect (expose :runner eid (:card context)))} :yes-ability {:async true :effect (req (wait-for (pay state :corp (make-eid state eid) card [:credit 1]) (system-msg state :corp (str (:msg async-result) " to prevent " " card from being exposed")) (effect-completed state side eid)))}}} card targets)))}}} card targets))}] :abilities [(set-autoresolve :auto-419 "419")]}) (defcard "Acme Consulting: The Truth You Need" (letfn [(outermost? [state ice] (let [server-ice (:ices (card->server state ice))] (same-card? ice (last server-ice))))] {:constant-effects [{:type :tags :req (req (and (get-current-encounter state) (rezzed? current-ice) (outermost? state current-ice))) :value 1}]})) (defcard "PI:NAME:<NAME>END_PI: Compulsive Hacker" {:events [{:event :pre-start-game :req (req (= side :runner)) :async true :waiting-prompt "Runner to make a decision" :effect (req (let [directives (->> (server-cards) (filter #(has-subtype? % "Directive")) (map make-card) (map #(assoc % :zone [:play-area])) (into []))] ;; Add directives to :play-area - assumed to be empty (swap! state assoc-in [:runner :play-area] directives) (continue-ability state side {:prompt (str "Choose 3 starting directives") :choices {:max 3 :all true :card #(and (runner? %) (in-play-area? %))} :effect (req (doseq [c targets] (runner-install state side (make-eid state eid) c {:ignore-all-cost true :custom-message (fn [_] (str "starts with " (:title c) " in play"))})) (swap! state assoc-in [:runner :play-area] []))} card nil)))}]}) (defcard "AgInfusion: New Miracles for a New World" {:abilities [{:label "Trash a piece of ice to choose another server- the runner is now running that server" :once :per-turn :async true :req (req (and run (= :approach-ice (:phase run)) (not (rezzed? current-ice)))) :prompt "Choose another server and redirect the run to its outermost position" :choices (req (cancellable (remove #{(-> @state :run :server central->name)} servers))) :msg (msg "trash the approached piece of ice. The Runner is now running on " target) :effect (req (let [dest (server->zone state target) ice (count (get-in corp (conj dest :ices))) phase (if (pos? ice) :encounter-ice :movement)] (wait-for (trash state side (make-eid state eid) current-ice {:unpreventable true}) (redirect-run state side target phase) (start-next-phase state side eid))))}]}) (defcard "PI:NAME:<NAME>END_PI: Head Case" {:events [{:event :breach-server :interactive (req true) :psi {:req (req (= target :rd)) :player :runner :equal {:msg "access 1 additional card" :effect (effect (access-bonus :rd 1) (effect-completed eid))}}}]}) (defcard "PI:NAME:<NAME>END_PI: PI:NAME:<NAME>END_PI API:NAME:<NAME>END_PIator" {:events [{:event :successful-run :interactive (req true) :req (req (and (= :archives (target-server context)) (first-successful-run-on-server? state :archives) (not-empty (:hand corp)))) :waiting-prompt "Corp to make a decision" :prompt "Choose a card in HQ to discard" :player :corp :choices {:all true :card #(and (in-hand? %) (corp? %))} :msg "force the Corp to trash 1 card from HQ" :async true :effect (effect (trash :corp eid target nil))}]}) (defcard "Andromeda: Dispossessed Ristie" {:events [{:event :pre-start-game :req (req (= side :runner)) :async true :effect (effect (draw eid 4 {:suppress-event true}))}] :mulligan (effect (draw eid 4 {:suppress-event true}))}) (defcard "Apex: Invasive Predator" (let [ability {:prompt "Choose a card to install facedown" :label "Install a card facedown (start of turn)" :once :per-turn :choices {:max 1 :card #(and (runner? %) (in-hand? %))} :req (req (and (pos? (count (:hand runner))) (:runner-phase-12 @state))) :async true :msg "install a card facedown" :effect (effect (runner-install (assoc eid :source card :source-type :runner-install) target {:facedown true :no-msg true}))}] {:implementation "Install restriction not enforced" :events [(assoc ability :event :runner-turn-begins)] :flags {:runner-phase-12 (req true)} :abilities [ability]})) (defcard "Argus Security: Protection Guaranteed" {:events [{:event :agenda-stolen :prompt "Take 1 tag or suffer 2 meat damage?" :async true :choices ["1 tag" "2 meat damage"] :player :runner :msg "make the Runner take 1 tag or suffer 2 meat damage" :effect (req (if (= target "1 tag") (do (system-msg state side "chooses to take 1 tag") (gain-tags state :runner eid 1)) (do (system-msg state side "chooses to suffer 2 meat damage") (damage state :runner eid :meat 2 {:unboostable true :card card}))))}]}) (defcard "PI:NAME:<NAME>END_PI \"PI:NAME:<NAME>END_PI\" PI:NAME:<NAME>END_PI: Tech Lord" {:events [{:event :runner-trash :async true :interactive (req true) :req (req (and (= side :runner) (= :ability-cost (:cause target)))) :msg "draw a card" :effect (effect (draw eid 1))}]}) (defcard "Asa Group: Security Through Vigilance" {:events [{:event :corp-install :async true :req (req (first-event? state :corp :corp-install)) :effect (req (let [installed-card (:card context) z (butlast (get-zone installed-card))] (continue-ability state side {:prompt (str "Choose a " (if (is-remote? z) "non-agenda" "piece of ice") " in HQ to install") :choices {:card #(and (in-hand? %) (corp? %) (corp-installable-type? %) (not (agenda? %)))} :async true :effect (effect (corp-install eid target (zone->name z) nil))} card nil)))}]}) (defcard "PI:NAME:<NAME>END_PI \"PI:NAME:<NAME>END_PI\" PI:NAME:<NAME>END_PI: Simulant Specialist" {:abilities [{:label "Add 1 hosted card to your grip" :cost [:click 1] :async true :prompt "Choose a hosted card" :choices (req (cancellable (:hosted card))) :msg "move a hosted card to their Grip" :effect (effect (move target :hand) (effect-completed eid))}] :events [{:event :pre-start-game :req (req (= side :runner)) :async true :waiting-prompt "Runner to make a decision" :effect (req (doseq [c (take 6 (:deck runner))] (move state side c :play-area)) (continue-ability state side {:prompt "Choose 4 cards to be hosted" :choices {:max 4 :all true :card #(and (runner? %) (in-play-area? %))} :effect (req (doseq [c targets] (host state side (get-card state card) c {:facedown true})) (doseq [c (get-in @state [:runner :play-area])] (move state side c :deck)) (shuffle! state side :deck))} card nil))}]}) (defcard "Az McCaffrey: Mechanical Prodigy" ;; Effect marks Az's ability as "used" if it has already met it's trigger condition this turn (letfn [(az-type? [card] (or (hardware? card) (and (resource? card) (or (has-subtype? card "Job") (has-subtype? card "Connection"))))) (not-triggered? [state] (no-event? state :runner :runner-install #(az-type? (:card (first %)))))] {:constant-effects [{:type :install-cost :req (req (and (az-type? target) (not-triggered? state))) :value -1}] :events [{:event :runner-install :req (req (and (az-type? (:card context)) (not-triggered? state))) :silent (req true) :msg (msg "reduce the install cost of " (:title (:card context)) " by 1 [Credits]")}]})) (defcard "Azmari EdTech: Shaping the Future" {:events [{:event :corp-turn-ends :prompt "Name a card type" :choices ["Event" "Resource" "Program" "Hardware" "None"] :effect (effect (update! (assoc card :card-target (if (= "None" target) nil target))) (system-msg (str "uses Azmari EdTech: Shaping the Future to name " target)))} {:event :runner-install :req (req (and (:card-target card) (is-type? (:card context) (:card-target card)) (not (:facedown context)))) :async true :effect (effect (gain-credits :corp eid 2)) :once :per-turn :msg (msg "gain 2 [Credits] from " (:card-target card))} {:event :play-event :req (req (and (:card-target card) (is-type? (:card context) (:card-target card)))) :async true :effect (effect (gain-credits :corp eid 2)) :once :per-turn :msg (msg "gain 2 [Credits] from " (:card-target card))}]}) (defcard "Blue Sun: Powering the Future" {:flags {:corp-phase-12 (req (and (not (:disabled card)) (some rezzed? (all-installed state :corp))))} :abilities [{:choices {:card rezzed?} :label "Add 1 rezzed card to HQ and gain credits equal to its rez cost" :msg (msg "add " (:title target) " to HQ and gain " (rez-cost state side target) " [Credits]") :async true :effect (effect (move target :hand) (gain-credits eid (rez-cost state side target)))}]}) (defcard "PI:NAME:<NAME>END_PI: Crafty Veteran" {:events [{:event :pre-start-game :effect draft-points-target} {:event :runner-turn-begins :req (req (and (has-most-faction? state :runner "Criminal") (pos? (get-in runner [:tag :base])))) :msg "remove 1 tag" :async true :effect (effect (lose-tags eid 1))}]}) (defcard "Cerebral Imaging: Infinite Frontiers" {:constant-effects [(corp-hand-size+ (req (:credit corp)))] :effect (req (swap! state assoc-in [:corp :hand-size :base] 0)) :leave-play (req (swap! state assoc-in [:corp :hand-size :base] 5))}) (defcard "Chaos Theory: Wünderkind" {:constant-effects [(mu+ 1)]}) (defcard "Chronos Protocol: Selective Mind-mapping" {:req (req (empty? (filter #(= :net (:damage-type (first %))) (turn-events state :runner :damage)))) :effect (effect (enable-corp-damage-choice)) :leave-play (req (swap! state update-in [:damage] dissoc :damage-choose-corp)) :events [{:event :corp-phase-12 :effect (effect (enable-corp-damage-choice))} {:event :runner-phase-12 :effect (effect (enable-corp-damage-choice))} {:event :pre-resolve-damage :optional {:player :corp :req (req (and (= target :net) (corp-can-choose-damage? state) (pos? (last targets)) (empty? (filter #(= :net (:damage-type (first %))) (turn-events state :runner :damage))) (pos? (count (:hand runner))))) :waiting-prompt "Corp to make a decision" :prompt "Use Chronos Protocol to choose the first card trashed?" :yes-ability {:async true :msg (msg "look at the Runner's Grip ( " (string/join ", " (map :title (sort-by :title (:hand runner)))) " ) and choose the card that is trashed") :effect (effect (continue-ability {:prompt "Choose a card to trash" :choices (req (:hand runner)) :not-distinct true :msg (msg "choose " (:title target) " to trash") :effect (req (chosen-damage state :corp target))} card nil))} :no-ability {:effect (req (system-msg state :corp "declines to use Chronos Protocol"))}}}]}) (defcard "Cybernetics Division: Humanity Upgraded" {:constant-effects [(hand-size+ -1)]}) (defcard "Earth Station: SEA Headquarters" (let [flip-effect (effect (update! (if (:flipped card) (do (system-msg state :corp "flipped their identity to Earth Station: SEA Headquarters") (assoc card :flipped false :face :front :code (subs (:code card) 0 5))) (assoc card :flipped true :face :back :code (str (subs (:code card) 0 5) "flip")))))] {:events [{:event :pre-first-turn :req (req (= side :corp)) :effect (effect (update! (assoc card :flipped false :face :front)))} {:event :successful-run :req (req (and (= :hq (target-server context)) (:flipped card))) :effect flip-effect}] :constant-effects [{:type :run-additional-cost :req (req (or (and (not (:flipped card)) (= :hq (:server (second targets)))) (and (:flipped card) (in-coll? (keys (get-remotes state)) (:server (second targets)))))) :value (req [:credit (if (:flipped card) 6 1)])}] :async true ; This effect will be resolved when the ID is reenabled after Strike / Direct Access :effect (effect (continue-ability {:req (req (< 1 (count (get-remotes state)))) :prompt "Choose a server to be saved from the rules apocalypse" :choices (req (get-remote-names state)) :async true :effect (req (let [to-be-trashed (remove #(in-coll? ["Archives" "R&D" "HQ" target] (zone->name (second (get-zone %)))) (all-installed state :corp))] (system-msg state side (str "chooses " target " to be saved from the rules apocalypse and trashes " (quantify (count to-be-trashed) "card"))) ; these cards get trashed by the game and not by players (trash-cards state side eid to-be-trashed {:unpreventable true :game-trash true})))} card nil)) :abilities [{:label "Flip identity to Earth Station: Ascending to Orbit" :req (req (not (:flipped card))) :cost [:click 1] :msg "flip their identity to Earth Station: Ascending to Orbit" :effect flip-effect} {:label "Manually flip identity to Earth Station: SEA Headquarters" :req (req (:flipped card)) :effect flip-effect}]})) (defcard "PI:NAME:<NAME>END_PI: Humanity's Hammer" {:events [{:event :access :once :per-turn :req (req (and (operation? target) (first-event? state side :access #(operation? (first %))))) :async true :effect (req (if (in-discard? target) (effect-completed state side eid) (do (when run (swap! state assoc-in [:run :did-trash] true)) (swap! state assoc-in [:runner :register :trashed-card] true) (system-msg state :runner (str "uses PI:NAME:<NAME>END_PI: Humanity's Hammer to" " trash " (:title target) " at no cost")) (trash state side eid target nil))))}]}) (defcard "Ele \"Smoke\" Scovak: Cynosure of the Net" {:recurring 1 :interactions {:pay-credits {:req (req (and (= :ability (:source-type eid)) (has-subtype? target "Icebreaker"))) :type :recurring}}}) (defcard "Exile: Streethawk" {:flags {:runner-install-draw true} :events [{:event :runner-install :async true :req (req (and (program? (:card context)) (some #{:discard} (:previous-zone (:card context))))) :msg "draw a card" :effect (effect (draw eid 1))}]}) (defcard "PI:NAME:<NAME>END_PI: Crypto-Anarchist" {:interactions {:access-ability {:async true :once :per-turn :label "Trash card" :req (req (and (not (:disabled card)) (not (agenda? target)) (<= (play-cost state side target) (number-of-runner-virus-counters state)))) :waiting-prompt "Runner to make a decision" :effect (req (let [accessed-card target play-or-rez (:cost target)] (if (zero? play-or-rez) (continue-ability state side {:async true :msg (msg "trash " (:title accessed-card) " at no cost") :effect (effect (trash eid (assoc accessed-card :seen true) {:accessed true}))} card nil) (wait-for (resolve-ability state side (pick-virus-counters-to-spend play-or-rez) card nil) (if-let [msg (:msg async-result)] (do (system-msg state :runner (str "uses Freedom Khumalo: Crypto-Anarchist to" " trash " (:title accessed-card) " at no cost, spending " msg)) (trash state side eid (assoc accessed-card :seen true) {:accessed true})) ;; Player cancelled ability (do (swap! state dissoc-in [:per-turn (:cid card)]) (access-non-agenda state side eid accessed-card :skip-trigger-event true)))))))}}}) (defcard "Fringe Applications: Tomorrow, Today" {:events [{:event :pre-start-game :effect draft-points-target} {:event :runner-turn-begins :player :corp :req (req (and (not (:disabled card)) (has-most-faction? state :corp "Weyland Consortium") (some ice? (all-installed state side)))) :prompt "Choose a piece of ice to place 1 advancement token on" :choices {:card #(and (installed? %) (ice? %))} :msg (msg "place 1 advancement token on " (card-str state target)) :effect (req (add-prop state :corp target :advance-counter 1 {:placed true}))}]}) (defcard "PI:NAME:<NAME>END_PI: Consummate Professional" {:events [{:event :successful-run :silent (req true) :req (req (and (= :hq (target-server context)) (first-successful-run-on-server? state :hq))) :msg "gain 2 [Credits]" :async true :effect (effect (gain-credits eid 2))}]}) (defcard "Gagarin Deep Space: Expanding the Horizon" {:events [{:event :pre-access-card :req (req (is-remote? (second (get-zone target)))) :effect (effect (access-cost-bonus [:credit 1])) :msg "make the Runner spend 1 [Credits] to access"}]}) (defcard "GameNET: Where Dreams are Real" (let [gamenet-ability {:req (req (and (:run @state) (= (:side (:source eid)) "Corp") (or (and (not= (:source-type eid) :runner-trash-corp-cards) (not= (:source-type eid) :runner-steal)) (some (fn [[cost source]] (and (some #(or (= (cost-name %) :credit) (= (cost-name %) :x-credits)) (merge-costs cost)) (= (:side (:source source)) "Corp"))) (:additional-costs eid))))) :async true :msg "gain 1 [Credits]" :effect (effect (gain-credits :corp eid 1))}] {:events [(assoc gamenet-ability :event :runner-credit-loss) (assoc gamenet-ability :event :runner-spent-credits)]})) (defcard "GRNDL: Power Unleashed" {:events [{:event :pre-start-game :req (req (= :corp side)) :async true :effect (req (wait-for (gain-credits state :corp 5) (if (zero? (count-bad-pub state)) (gain-bad-publicity state :corp eid 1) (effect-completed state side eid))))}]}) (defcard "Haarpsichord Studios: Entertainment Unleashed" {:constant-effects [{:type :cannot-steal :value (req (pos? (event-count state side :agenda-stolen)))}] :events [{:event :access :req (req (and (agenda? target) (pos? (event-count state side :agenda-stolen)))) :effect (effect (toast :runner "Cannot steal due to Haarpsichord Studios." "warning"))}]}) (defcard "Haas-Bioroid: Architects of Tomorrow" {:events [{:event :pass-ice :req (req (and (rezzed? (:ice context)) (has-subtype? (:ice context) "Bioroid") (first-event? state :runner :pass-ice (fn [targets] (let [context (first targets) ice (:ice context)] (and (rezzed? ice) (installed? ice) (has-subtype? ice "Bioroid"))))))) :waiting-prompt "Corp to make a decision" :prompt "Choose a Bioroid to rez" :player :corp :choices {:req (req (and (has-subtype? target "Bioroid") (not (rezzed? target)) (can-pay? state side (assoc eid :source card :source-type :rez) target nil [:credit (rez-cost state side target {:cost-bonus -4})])))} :msg (msg "rez " (:title target)) :async true :effect (effect (rez eid target {:cost-bonus -4}))}]}) (defcard "Haas-Bioroid: Engineering the Future" {:events [{:event :corp-install :req (req (first-event? state corp :corp-install)) :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits eid 1))}]}) (defcard "Haas-Bioroid: Precision Design" {:constant-effects [(corp-hand-size+ 1)] :events [{:event :agenda-scored :interactive (req true) :optional {:prompt "Add card from Archives to HQ?" :autoresolve (get-autoresolve :auto-precision-design) :yes-ability (corp-recur)}}] :abilities [(set-autoresolve :auto-precision-design "add card from Archives to HQ")]}) (defcard "Haas-Bioroid: Stronger Together" {:constant-effects [{:type :ice-strength :req (req (has-subtype? target "Bioroid")) :value 1}] :leave-play (effect (update-all-ice)) :effect (effect (update-all-ice))}) (defcard "PI:NAME:<NAME>END_PI Ent.: Where You're the Star" (letfn [(format-grip [runner] (if (pos? (count (:hand runner))) (string/join ", " (map :title (sort-by :title (:hand runner)))) "no cards"))] {:events [{:event :post-runner-draw :req (req (is-tagged? state)) :msg (msg "see that the Runner drew: " (string/join ", " (map :title runner-currently-drawing)))} {:event :tags-changed :effect (req (if (is-tagged? state) (when-not (get-in @state [:runner :openhand]) (system-msg state :corp (str "uses " (get-title card) " make the Runner play with their grip revealed")) (system-msg state :corp (str "uses " (get-title card) " to see that the Runner currently has " (format-grip runner) " in their grip")) (reveal-hand state :runner)) (when (get-in @state [:runner :openhand]) (system-msg state :corp (str "uses " (get-title card) " stop making the Runner play with their grip revealed")) (system-msg state :corp (str "uses " (get-title card) " to see that the Runner had " (format-grip runner) " in their grip before it was concealed")) (conceal-hand state :runner))))}] :effect (req (when (is-tagged? state) (reveal-hand state :runner))) :leave-play (req (when (is-tagged? state) (conceal-hand state :runner)))})) (defcard "Harmony Medtech: Biomedical Pioneer" {:effect (effect (lose :agenda-point-req 1) (lose :runner :agenda-point-req 1)) :leave-play (effect (gain :agenda-point-req 1) (gain :runner :agenda-point-req 1))}) (defcard "PI:NAME:<NAME>END_PI: Universal Scholar" {:events [{:event :runner-install :silent (req (not (and (first-event? state side :runner-install) (some #(is-type? % (:type (:card context))) (:hand runner))))) :req (req (and (first-event? state side :runner-install) (not (:facedown context)))) :once :per-turn :async true :waiting-prompt "Runner to make a decision" :effect (effect (continue-ability (let [itarget (:card context) card-type (:type itarget)] (if (some #(is-type? % (:type itarget)) (:hand runner)) {:optional {:prompt (str "Install another " card-type " from your Grip?") :yes-ability {:prompt (str "Choose another " card-type " to install from your Grip") :choices {:card #(and (is-type? % card-type) (in-hand? %))} :msg (msg "install " (:title target)) :async true :effect (effect (runner-install (assoc eid :source card :source-type :runner-install) target nil))}}} {:prompt (str "You have no " card-type "s in hand") :choices ["Carry on!"] :prompt-type :bogus})) card nil))}]}) (defcard "PI:NAME:<NAME>END_PI: Untold Protagonist" (let [flip-effect (req (update! state side (if (:flipped card) (assoc card :flipped false :face :front :code (subs (:code card) 0 5) :subtype "Natural") (assoc card :flipped true :face :back :code (str (subs (:code card) 0 5) "flip") :subtype "Digital"))) (update-link state))] {:constant-effects [(link+ (req (:flipped card)) 1) {:type :gain-subtype :req (req (and (same-card? card target) (:flipped card))) :value "Digital"} {:type :lose-subtype :req (req (and (same-card? card target) (:flipped card))) :value "Natural"}] :events [{:event :pre-first-turn :req (req (= side :runner)) :effect (effect (update! (assoc card :flipped false :face :front)))} {:event :runner-turn-ends :interactive (req true) :async true :effect (req (cond (and (:flipped card) (not (:accessed-cards runner-reg))) (do (system-msg state :runner "flips their identity to Hoshiko Shiro: Untold Protagonist") (continue-ability state :runner {:effect flip-effect} card nil)) (and (not (:flipped card)) (:accessed-cards runner-reg)) (wait-for (gain-credits state :runner 2) (system-msg state :runner "gains 2 [Credits] and flips their identity to Hoshiko Shiro: Mahou Shoujo") (continue-ability state :runner {:effect flip-effect} card nil)) :else (effect-completed state side eid)))} {:event :runner-turn-begins :req (req (:flipped card)) :async true :effect (req (wait-for (draw state :runner 1) (wait-for (lose-credits state :runner (make-eid state eid) 1) (system-msg state :runner "uses Hoshiko Shiro: Mahou Shoujo to draw 1 card and lose 1 [Credits]") (effect-completed state side eid))))}] :abilities [{:label "flip ID" :msg "flip their ID manually" :effect flip-effect}]})) (defcard "Hyoubu Institute: Absolute Clarity" {:events [{:event :corp-reveal :once :per-turn :req (req (first-event? state side :corp-reveal #(pos? (count %)))) :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits eid 1))}] :abilities [{:cost [:click 1] :label "Reveal the top card of the Stack" :async true :effect (req (if-let [revealed-card (-> runner :deck first)] (do (system-msg state side (str "uses Hyoubu Institute: Absolute Clarity to reveal " (:title revealed-card) " from the top of the Stack")) (reveal state side eid revealed-card)) (effect-completed state side eid)))} {:cost [:click 1] :label "Reveal a random card from the Grip" :async true :effect (req (if-let [revealed-card (-> runner :hand shuffle first)] (do (system-msg state side (str "uses Hyoubu Institute: Absolute Clarity to reveal " (:title revealed-card) " from the Grip")) (reveal state side eid revealed-card)) (effect-completed state side eid)))}]}) (defcard "Iain Stirling: Retired Spook" (let [ability {:req (req (> (:agenda-point corp) (:agenda-point runner))) :once :per-turn :msg "gain 2 [Credits]" :async true :effect (effect (gain-credits eid 2))}] {:flags {:drip-economy true} :events [(assoc ability :event :runner-turn-begins)] :abilities [ability]})) (defcard "Industrial Genomics: Growing Solutions" {:constant-effects [{:type :trash-cost :value (req (count (remove :seen (:discard corp))))}]}) (defcard "Information Dynamics: All You Need To Know" {:events (let [inf {:req (req (and (not (:disabled card)) (has-most-faction? state :corp "NBN"))) :msg "give the Runner 1 tag" :async true :effect (effect (gain-tags :corp eid 1))}] [{:event :pre-start-game :effect draft-points-target} (assoc inf :event :agenda-scored) (assoc inf :event :agenda-stolen)])}) (defcard "PI:NAME:<NAME>END_PI \"Bzzz\" Micken: Techno Savant" {:events [{:event :pre-start-game :effect draft-points-target} {:event :runner-install :req (req (and (has-most-faction? state :runner "Shaper") (first-event? state side :runner-install))) :msg "draw 1 card" :once :per-turn :async true :effect (effect (draw eid 1))}]}) (defcard "PI:NAME:<NAME>END_PIics: Sacrifice. Audacity. Success." {:events [{:event :corp-forfeit-agenda :async true :waiting-prompt "Corp to make a decision" :effect (effect (continue-ability (let [p (inc (get-agenda-points (:card context)))] {:prompt (str "Choose a card to place advancement tokens on with " (:title card)) :choices {:card #(and (installed? %) (corp? %))} :msg (msg "place " (quantify p "advancement token") " on " (card-str state target)) :effect (effect (add-prop :corp target :advance-counter p {:placed true}))}) card nil))}]}) (defcard "PI:NAME:<NAME>END_PI: Girl Behind the Curtain" {:flags {:forced-to-avoid-tag true} :events [{:event :pre-tag :async true :once :per-run :req (req (:run @state)) :msg "avoid the first tag during this run" :effect (effect (tag-prevent :runner eid 1))}]}) (defcard "Jinteki Biotech: Life Imagined" {:events [{:event :pre-first-turn :req (req (= side :corp)) :prompt "Choose a copy of Jinteki Biotech to use this game" :choices ["The Brewery" "The Tank" "The Greenhouse"] :effect (effect (update! (assoc card :biotech-target target :face :front)) (system-msg (str "has chosen a copy of Jinteki Biotech for this game")))}] :abilities [{:label "Check chosen flip identity" :effect (req (case (:biotech-target card) "The Brewery" (toast state :corp "Flip to: The Brewery (Do 2 net damage)" "info") "The Tank" (toast state :corp "Flip to: The Tank (Shuffle Archives into R&D)" "info") "The Greenhouse" (toast state :corp "Flip to: The Greenhouse (Place 4 advancement tokens on a card)" "info") ;; default case (toast state :corp "No flip identity specified" "info")))} {:cost [:click 3] :req (req (not (:biotech-used card))) :label "Flip this identity" :async true :effect (req (let [flip (:biotech-target card)] (update! state side (assoc (get-card state card) :biotech-used true)) (case flip "The Brewery" (do (system-msg state side "uses The Brewery to do 2 net damage") (update! state side (assoc card :code "brewery" :face :brewery)) (damage state side eid :net 2 {:card card})) "The Tank" (do (system-msg state side "uses The Tank to shuffle Archives into R&D") (shuffle-into-deck state side :discard) (update! state side (assoc card :code "tank" :face :tank)) (effect-completed state side eid)) "The Greenhouse" (do (system-msg state side (str "uses The Greenhouse to place 4 advancement tokens " "on a card that can be advanced")) (update! state side (assoc card :code "greenhouse" :face :greenhouse)) (continue-ability state side {:prompt "Choose a card that can be advanced" :choices {:card can-be-advanced?} :effect (effect (add-prop target :advance-counter 4 {:placed true}))} card nil)) (toast state :corp (str "Unknown Jinteki Biotech: Life Imagined card: " flip) "error"))))}]}) (defcard "Jinteki: Personal Evolution" (let [ability {:async true :req (req (not (:winner @state))) :msg "do 1 net damage" :effect (effect (damage eid :net 1 {:card card}))}] {:events [(assoc ability :event :agenda-scored :interactive (req true)) (assoc ability :event :agenda-stolen)]})) (defcard "Jinteki: Potential Unleashed" {:events [{:async true :event :pre-resolve-damage :req (req (and (-> @state :corp :disable-id not) (= target :net) (pos? (last targets)))) :effect (req (let [c (first (get-in @state [:runner :deck]))] (system-msg state :corp (str "uses Jinteki: Potential Unleashed to trash " (:title c) " from the top of the Runner's Stack")) (mill state :corp eid :runner 1)))}]}) (defcard "Jinteki: Replicating Perfection" {:events [{:event :runner-phase-12 :effect (req (apply prevent-run-on-server state card (map first (get-remotes state))))} {:event :run :once :per-turn :req (req (is-central? (:server target))) :effect (req (apply enable-run-on-server state card (map first (get-remotes state))))}] :req (req (empty? (let [successes (turn-events state side :successful-run)] (filter is-central? (map :server successes))))) :effect (req (apply prevent-run-on-server state card (map first (get-remotes state)))) :leave-play (req (apply enable-run-on-server state card (map first (get-remotes state))))}) (defcard "Jinteki: Restoring Humanity" {:events [{:event :corp-turn-ends :req (req (pos? (count (remove :seen (:discard corp))))) :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits :corp eid 1))}]}) (defcard "Kabonesa Wu: Netspace Thrillseeker" {:abilities [{:label "Install a non-virus program from your stack, lowering the cost by 1 [Credit]" :cost [:click 1] :prompt "Choose a program" :choices (req (cancellable (filter #(and (program? %) (not (has-subtype? % "Virus")) (can-pay? state :runner (assoc eid :source card :source-type :runner-install) % nil [:credit (install-cost state side % {:cost-bonus -1})])) (:deck runner)))) :msg (msg "install " (:title target) " from the stack, lowering the cost by 1 [Credit]") :async true :effect (effect (trigger-event :searched-stack nil) (shuffle! :deck) (register-events card [{:event :runner-turn-ends :interactive (req true) :duration :end-of-turn :req (req (some #(get-in % [:special :kabonesa]) (all-installed state :runner))) :msg (msg "remove " (:title target) " from the game") :effect (req (doseq [program (filter #(get-in % [:special :kabonesa]) (all-installed state :runner))] (move state side program :rfg)))}]) (runner-install (assoc eid :source card :source-type :runner-install) (assoc-in target [:special :kabonesa] true) {:cost-bonus -1}))}]}) (defcard "Kate \"Mac\" PI:NAME:<NAME>END_PI: Digital Tinker" ;; Effect marks Kate's ability as "used" if it has already met it's trigger condition this turn (letfn [(kate-type? [card] (or (hardware? card) (program? card))) (not-triggered? [state card] (no-event? state :runner :runner-install #(kate-type? (:card (first %)))))] {:constant-effects [{:type :install-cost :req (req (and (kate-type? target) (not-triggered? state card))) :value -1}] :events [{:event :runner-install :req (req (and (kate-type? (:card context)) (not-triggered? state card))) :silent (req true) :msg (msg "reduce the install cost of " (:title (:card context)) " by 1 [Credits]")}]})) (defcard "Ken \"Express\" Tenma: Disappeared Clone" {:events [{:event :play-event :req (req (and (has-subtype? (:card context) "Run") (first-event? state :runner :play-event #(has-subtype? (:card (first %)) "Run")))) :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits eid 1))}]}) (defcard "Khan: Savvy Skiptracer" {:events [{:event :pass-ice :req (req (first-event? state :runner :pass-ice)) :async true :interactive (req true) :effect (effect (continue-ability (when (some #(and (has-subtype? % "Icebreaker") (can-pay? state side (assoc eid :source card :source-type :runner-install) % nil [:credit (install-cost state side % {:cost-bonus -1})])) (:hand runner)) {:prompt "Choose an icebreaker to install from your Grip" :choices {:req (req (and (in-hand? target) (has-subtype? target "Icebreaker") (can-pay? state side (assoc eid :source card :source-type :runner-install) target nil [:credit (install-cost state side target {:cost-bonus -1})])))} :async true :msg (msg "install " (:title target) ", lowering the cost by 1 [Credits]") :effect (effect (runner-install eid target {:cost-bonus -1}))}) card nil))}]}) (defcard "Laramy Fisk: Savvy Investor" {:events [{:event :successful-run :async true :interactive (get-autoresolve :auto-fisk (complement never?)) :silent (get-autoresolve :auto-fisk never?) :optional {:req (req (and (is-central? (:server context)) (first-event? state side :successful-run (fn [targets] (let [context (first targets)] (is-central? (:server context))))))) :autoresolve (get-autoresolve :auto-fisk) :prompt "Force the Corp to draw a card?" :yes-ability {:msg "force the Corp to draw 1 card" :async true :effect (effect (draw :corp eid 1))} :no-ability {:effect (effect (system-msg "declines to use Laramy Fisk: Savvy Investor"))}}}] :abilities [(set-autoresolve :auto-fisk "force Corp draw")]}) (defcard "Lat: Ethical Freelancer" {:events [{:event :runner-turn-ends :optional {:req (req (= (count (:hand runner)) (count (:hand corp)))) :autoresolve (get-autoresolve :auto-lat) :prompt "Draw 1 card?" :yes-ability {:async true :msg "draw 1 card" :effect (effect (draw :runner eid 1))} :no-ability {:effect (effect (system-msg "declines to use Lat: Ethical Freelancer"))}}}] :abilities [(set-autoresolve :auto-lat "Lat: Ethical Freelancer")]}) (defcard "PI:NAME:<NAME>END_PI: Trained Pragmatist" (let [leela {:interactive (req true) :prompt "Choose an unrezzed card to return to HQ" :choices {:card #(and (not (rezzed? %)) (installed? %) (corp? %))} :msg (msg "add " (card-str state target) " to HQ") :effect (effect (move :corp target :hand))}] {:events [(assoc leela :event :agenda-scored) (assoc leela :event :agenda-stolen)]})) (defcard "Liza Talking Thunder: Prominent Legislator" {:events [{:event :successful-run :async true :interactive (req true) :msg "draw 2 cards and take 1 tag" :req (req (and (is-central? (:server context)) (first-event? state side :successful-run (fn [targets] (let [context (first targets)] (is-central? (:server context))))))) :effect (req (wait-for (gain-tags state :runner 1) (draw state :runner eid 2)))}]}) (defcard "Los: Data Hijacker" {:events [{:event :rez :once :per-turn :req (req (ice? (:card context))) :msg "gain 2 [Credits]" :async true :effect (effect (gain-credits :runner eid 2))}]}) (defcard "MaxX: Maximum Punk Rock" (let [ability {:msg (msg (let [deck (:deck runner)] (if (pos? (count deck)) (str "trash " (string/join ", " (map :title (take 2 deck))) " from their Stack and draw 1 card") "trash the top 2 cards from their Stack and draw 1 card - but their Stack is empty"))) :label "trash and draw cards" :once :per-turn :async true :effect (req (wait-for (mill state :runner :runner 2) (draw state :runner eid 1)))}] {:flags {:runner-turn-draw true :runner-phase-12 (req (and (not (:disabled card)) (some #(card-flag? % :runner-turn-draw true) (all-active-installed state :runner))))} :events [(assoc ability :event :runner-turn-begins)] :abilities [ability]})) (defcard "MirrorMorph: Endless Iteration" (let [mm-clear {:prompt "Manually fix Mirrormorph" :msg (msg "manually clear Mirrormorph flags") :effect (effect (update! (assoc-in card [:special :mm-actions] [])) (update! (assoc-in (get-card state card) [:special :mm-click] false)))} mm-ability {:prompt "Gain [Click] or gain 1 [Credits]" :choices ["Gain [Click]" "Gain 1 [Credits]"] :msg (msg (decapitalize target)) :once :per-turn :label "Manually trigger ability" :async true :effect (req (if (= "Gain [Click]" target) (do (gain-clicks state side 1) (update! state side (assoc-in (get-card state card) [:special :mm-click] true)) (effect-completed state side eid)) (gain-credits state side eid 1)))}] {:implementation "Does not work with terminal Operations" :abilities [mm-ability mm-clear] :events [{:event :corp-spent-click :async true :effect (req (let [cid (first target) ability-idx (:ability-idx (:source-info eid)) bac-cid (get-in @state [:corp :basic-action-card :cid]) cause (if (keyword? (first target)) (case (first target) :play-instant [bac-cid 3] :corp-click-install [bac-cid 2] (first target)) ; in clojure there's: (= [1 2 3] '(1 2 3)) [cid ability-idx]) prev-actions (get-in card [:special :mm-actions] []) actions (conj prev-actions cause)] (update! state side (assoc-in card [:special :mm-actions] actions)) (update! state side (assoc-in (get-card state card) [:special :mm-click] false)) (if (and (= 3 (count actions)) (= 3 (count (distinct actions)))) (continue-ability state side mm-ability (get-card state card) nil) (effect-completed state side eid))))} {:event :runner-turn-begins :effect (effect (update! (assoc-in card [:special :mm-actions] [])) (update! (assoc-in (get-card state card) [:special :mm-click] false)))} {:event :corp-turn-ends :effect (effect (update! (assoc-in card [:special :mm-actions] [])) (update! (assoc-in (get-card state card) [:special :mm-click] false)))}] :constant-effects [{:type :prevent-paid-ability :req (req (and (get-in card [:special :mm-click]) (let [cid (:cid target) ability-idx (nth targets 2 nil) cause [cid ability-idx] prev-actions (get-in card [:special :mm-actions] []) actions (conj prev-actions cause)] (not (and (= 4 (count actions)) (= 4 (count (distinct actions)))))))) :value true}]})) (defcard "PI:NAME:<NAME>END_PIti Mwekundu: Life Improved" {:events [{:event :approach-server :async true :interactive (req true) :waiting "Corp to make a decision" :req (req (and (pos? (count (:hand corp))) (not (used-this-turn? (:cid card) state)))) :effect (req (if (some ice? (:hand corp)) (continue-ability state side {:optional {:prompt "Install a piece of ice?" :once :per-turn :yes-ability {:prompt "Choose a piece of ice to install from HQ" :choices {:card #(and (ice? %) (in-hand? %))} :async true :msg "install a piece of ice at the innermost position of this server. Runner is now approaching that piece of ice" :effect (req (wait-for (corp-install state side target (zone->name (target-server run)) {:ignore-all-cost true :front true}) (swap! state assoc-in [:run :position] 1) (set-next-phase state :approach-ice) (update-all-ice state side) (update-all-icebreakers state side) (continue-ability state side (offer-jack-out {:req (req (:approached-ice? (:run @state)))}) card nil)))}}} card nil) ;; bogus prompt so Runner cannot infer the Corp has no ice in hand (continue-ability state :corp {:async true :prompt "No ice to install" :choices ["Carry on!"] :prompt-type :bogus :effect (effect (effect-completed eid))} card nil)))}]}) (defcard "PI:NAME:<NAME>END_PI: Cyber Explorer" {:events [{:event :approach-ice :req (req (not (rezzed? (:ice context)))) :effect (effect (register-events card (let [ice (:ice context) cost (rez-cost state side ice)] [{:event :encounter-ice :duration :end-of-encounter :unregister-once-resolved true :req (req (same-card? (:ice context) ice)) :msg (msg "lose all credits and gain " cost " [Credits] from the rez of " (:title ice)) :async true :effect (req (wait-for (lose-credits state :runner (make-eid state eid) :all) (gain-credits state :runner eid cost)))}])))}]}) (defcard "PI:NAME:<NAME>END_PI \"PI:NAME:<NAME>END_PI\" Hall: One-of-a-Kind" (let [ability {:label "Gain 1 [Credits] (start of turn)" :once :per-turn :interactive (req true) :async true :effect (req (if (and (> 3 (count (:hand runner))) (:runner-phase-12 @state)) (do (system-msg state :runner (str "uses " (:title card) " to gain 1 [Credits]")) (gain-credits state :runner eid 1)) (effect-completed state side eid)))}] {:flags {:drip-economy true :runner-phase-12 (req (and (not (:disabled card)) (some #(card-flag? % :runner-turn-draw true) (all-active-installed state :runner))))} :abilities [ability] :events [(assoc ability :event :runner-turn-begins)]})) (defcard "NBN: Controlling the Message" {:events [{:event :runner-trash :interactive (req true) :once-per-instance true :optional {:player :corp :req (req (and (some #(and (corp? (:card %)) (installed? (:card %))) targets) (first-event? state side :runner-trash (fn [targets] (some #(and (installed? (:card %)) (corp? (:card %))) targets))))) :waiting-prompt "Corp to make a decision" :prompt "Trace the Runner with NBN: Controlling the Message?" :autoresolve (get-autoresolve :auto-ctm) :yes-ability {:trace {:base 4 :successful {:msg "give the Runner 1 tag" :async true :effect (effect (gain-tags :corp eid 1 {:unpreventable true}))}}}}}] :abilities [(set-autoresolve :auto-ctm "CtM")]}) (defcard "NBN: Making News" {:recurring 2 :interactions {:pay-credits {:req (req (= :trace (:source-type eid))) :type :recurring}}}) (defcard "NBN: Reality Plus" {:events [{:event :runner-gain-tag :req (req (first-event? state :runner :runner-gain-tag)) :player :corp :async true :waiting-prompt "Corp to choose an option" :prompt "Choose option" :choices ["Gain 2 [Credits]" "Draw 2 cards"] :msg (msg (decapitalize target)) :effect (req (if (= target "Gain 2 [Credits]") (gain-credits state :corp eid 2) (draw state :corp eid 2)))}]}) (defcard "NBN: The World is Yours*" {:constant-effects [(corp-hand-size+ 1)]}) (defcard "Near-Earth Hub: Broadcast Center" {:events [{:event :server-created :req (req (first-event? state :corp :server-created)) :async true :msg "draw 1 card" :effect (req (if-not (some #(= % :deck) (:zone target)) (draw state :corp eid 1) (do ;; Register the draw to go off when the card is finished installing - ;; this is after the checkpoint when it should go off, but is needed to ;; fix the interaction between architect (and any future install from R&D ;; cards) and NEH, where the card would get drawn before the install, ;; fizzling it in a confusing manner. Because we only do it in this ;; special case, there should be no gameplay implications. -nbPI:NAME:<NAME>END_PI, 2022 (register-events state side card [{:event :corp-install :interactive (req true) :duration (req true) :unregister-once-resolved true :async true :effect (effect (draw :corp eid 1))}]) (effect-completed state side eid))))}]}) (defcard "PI:NAME:<NAME>END_PI: Information Broker" {:events [{:event :encounter-ice :optional (:optional (offer-jack-out {:req (req (has-subtype? (:ice context) "Sentry")) :once :per-turn}))}]}) (defcard "New Angeles Sol: Your News" (let [nasol {:optional {:prompt "Play a Current?" :player :corp :req (req (some #(has-subtype? % "Current") (concat (:hand corp) (:discard corp) (:current corp)))) :yes-ability {:prompt "Choose a Current to play from HQ or Archives" :show-discard true :async true :choices {:card #(and (has-subtype? % "Current") (corp? %) (or (in-hand? %) (in-discard? %)))} :msg (msg "play a current from " (name-zone "Corp" (get-zone target))) :effect (effect (play-instant eid target))}}}] {:events [(assoc nasol :event :agenda-scored) (assoc nasol :event :agenda-stolen)]})) (defcard "NEXT Design: Guarding the Net" (let [ndhelper (fn nd [n] {:prompt (str "When finished, click NEXT Design: Guarding the Net to draw back up to 5 cards in HQ. " "Choose a piece of ice in HQ to install:") :choices {:card #(and (corp? %) (ice? %) (in-hand? %))} :effect (req (wait-for (corp-install state side target nil nil) (continue-ability state side (when (< n 3) (nd (inc n))) card nil)))})] {:events [{:event :pre-first-turn :req (req (= side :corp)) :msg "install up to 3 pieces of ice and draw back up to 5 cards" :async true :effect (req (wait-for (resolve-ability state side (ndhelper 1) card nil) (update! state side (assoc card :fill-hq true)) (effect-completed state side eid)))}] :abilities [{:req (req (:fill-hq card)) :label "draw remaining cards" :msg (msg "draw " (- 5 (count (:hand corp))) " cards") :async true :effect (req (wait-for (draw state side (- 5 (count (:hand corp))) {:suppress-event true}) (update! state side (dissoc card :fill-hq)) (swap! state assoc :turn-events nil) (effect-completed state side eid)))}]})) (defcard "Nisei Division: The Next Generation" {:events [{:event :reveal-spent-credits :req (req (and (some? (first targets)) (some? (second targets)))) :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits :corp eid 1))}]}) (defcard "Noise: Hacker Extraordinaire" {:events [{:async true :event :runner-install :req (req (has-subtype? (:card context) "Virus")) :msg "force the Corp to trash the top card of R&D" :effect (effect (mill :corp eid :corp 1))}]}) (defcard "Null: Whistleblower" {:events [{:event :encounter-ice :optional {:req (req (pos? (count (:hand runner)))) :prompt "Trash a card in grip to lower ice strength by 2?" :once :per-turn :yes-ability {:prompt "Choose a card in your Grip to trash" :choices {:card in-hand?} :msg (msg "trash " (:title target) " and reduce the strength of " (:title current-ice) " by 2 for the remainder of the run") :async true :effect (effect (register-floating-effect card (let [ice current-ice] {:type :ice-strength :duration :end-of-run :req (req (same-card? target ice)) :value -2})) (update-all-ice) (trash eid target {:unpreventable true}))}}}]}) (defcard "PI:NAME:<NAME>END_PI: Conspiracy Theorist" {:abilities [{:cost [:click 1] :msg "make a run on Archives" :once :per-turn :makes-run true :async true :effect (effect (update! (assoc-in card [:special :omar-run] true)) (make-run eid :archives (get-card state card)))}] :events [{:event :pre-successful-run :interactive (req true) :req (req (and (get-in card [:special :omar-run]) (= :archives (-> run :server first)))) :prompt "Treat as a successful run on which server?" :choices ["HQ" "R&D"] :effect (req (let [target-server (if (= target "HQ") :hq :rd)] (swap! state assoc-in [:run :server] [target-server]) (trigger-event state :corp :no-action) (system-msg state side (str "uses Omar Keung: Conspiracy Theorist to make a successful run on " target))))} {:event :run-ends :effect (effect (update! (dissoc-in card [:special :omar-run])))}]}) (defcard "Pālanā Foods: Sustainable Growth" {:events [{:event :runner-draw :req (req (and (first-event? state :corp :runner-draw) (pos? (:count target)))) :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits :corp eid 1))}]}) (defcard "Quetzal: Free Spirit" {:abilities [(assoc (break-sub nil 1 "Barrier" {:repeatable false}) :once :per-turn)]}) (defcard "PI:NAME:<NAME>END_PI: Freedom Fighter" (letfn [(not-triggered? [state] (no-event? state :runner :rez #(ice? (:card (first %)))))] {:constant-effects [{:type :rez-cost :req (req (and (ice? target) (not (rezzed? target)) (not-triggered? state))) :value 1}] :events [{:event :rez :req (req (and (ice? (:card context)) (not-triggered? state))) :msg (msg "increased the rez cost of " (:title (:card context)) " by 1 [Credits]")}]})) (defcard "PI:NAME:<NAME>END_PI \"PI:NAME:<NAME>END_PI\" PI:NAME:<NAME>END_PI: Party Animal" {:events [{:event :runner-trash :req (req (and (:accessed context) (first-event? state side :runner-trash (fn [targets] (some #(:accessed %) targets))))) :async true :msg "gain 1 [Credits] and draw 1 card" :effect (req (wait-for (draw state :runner 1) (gain-credits state :runner eid 1)))}]}) (defcard "PI:NAME:<NAME>END_PI \"PI:NAME:<NAME>END_PI\" PI:NAME:<NAME>END_PI: Transhuman" {:events [{:event :encounter-ice :once :per-turn :msg (msg "make " (:title (:ice context)) " gain Code Gate until the end of the run") :effect (effect (register-floating-effect card (let [ice (:ice context)] {:type :gain-subtype :duration :end-of-run :req (req (same-card? ice target)) :value "Code Gate"})))}]}) (defcard "PI:NAME:<NAME>END_PIati Mnemonics: Endless Exploration" (letfn [(install-card [chosen] {:prompt "Choose a remote server" :choices (req (conj (vec (get-remote-names state)) "New remote")) :async true :effect (req (let [tgtcid (:cid chosen)] (register-persistent-flag! state side card :can-rez (fn [state _ card] (if (= (:cid card) tgtcid) ((constantly false) (toast state :corp "Cannot rez due to Saraswati Mnemonics: Endless Exploration." "warning")) true))) (register-turn-flag! state side card :can-score (fn [state side card] (if (and (= (:cid card) tgtcid) (<= (get-advancement-requirement card) (get-counters card :advancement))) ((constantly false) (toast state :corp "Cannot score due to Saraswati Mnemonics: Endless Exploration." "warning")) true)))) (wait-for (corp-install state side chosen target nil) (add-prop state :corp (find-latest state chosen) :advance-counter 1 {:placed true}) (effect-completed state side eid)))})] {:abilities [{:async true :label "Install a card from HQ" :cost [:click 1 :credit 1] :prompt "Choose a card to install from HQ" :choices {:card #(and (or (asset? %) (agenda? %) (upgrade? %)) (corp? %) (in-hand? %))} :msg (msg "install a card in a remote server and place 1 advancement token on it") :effect (effect (continue-ability (install-card target) card nil))}] :events [{:event :corp-turn-begins :effect (req (clear-persistent-flag! state side card :can-rez))}]})) (defcard "Seidr Laboratories: Destiny Defined" {:implementation "Manually triggered" :abilities [{:req (req (and run (seq (:discard corp)))) :label "add card from Archives to R&D during a run" :once :per-turn :prompt "Choose a card to add to the top of R&D" :show-discard true :choices {:card #(and (corp? %) (in-discard? %))} :effect (effect (move target :deck {:front true})) :msg (msg "add " (if (:seen target) (:title target) "a card") " to the top of R&D")}]}) (defcard "Silhouette: Stealth Operative" {:events [{:event :successful-run :interactive (req (some #(not (rezzed? %)) (all-installed state :corp))) :async true :req (req (and (= :hq (target-server context)) (first-successful-run-on-server? state :hq))) :choices {:card #(and (installed? %) (not (rezzed? %)))} :msg "expose 1 card" :effect (effect (expose eid target))}]}) (defcard "Skorpios Defense Systems: Persuasive Power" {:implementation "Manually triggered, no restriction on which cards in Heap can be targeted. Cannot use on in progress run event" :abilities [{:label "Remove a card in the Heap that was just trashed from the game" :waiting-prompt "Corp to make a decision" :prompt "Choose a card in the Runner's Heap that was just trashed" :once :per-turn :choices (req (cancellable (:discard runner))) :msg (msg "remove " (:title target) " from the game") :effect (req (move state :runner target :rfg))}]}) (defcard "Spark Agency: Worldswide Reach" {:events [{:event :rez :req (req (and (has-subtype? (:card context) "Advertisement") (first-event? state :corp :rez #(has-subtype? (:card (first %)) "Advertisement")))) :async true :effect (effect (lose-credits :runner eid 1)) :msg "make the Runner lose 1 [Credits] by rezzing an Advertisement"}]}) (defcard "Sportsmetal: Go Big or Go Home" (let [ab {:prompt "Gain 2 [Credits] or draw 2 cards?" :player :corp :choices ["Gain 2 [Credits]" "Draw 2 cards"] :msg (msg (if (= target "Gain 2 [Credits]") "gain 2 [Credits]" "draw 2 cards")) :async true :interactive (req true) :effect (req (if (= target "Gain 2 [Credits]") (gain-credits state :corp eid 2) (draw state :corp eid 2)))}] {:events [(assoc ab :event :agenda-scored) (assoc ab :event :agenda-stolen)]})) (defcard "SSO Industries: Fueling Innovation" (letfn [(installed-faceup-agendas [state] (->> (all-installed state :corp) (filter agenda?) (filter faceup?))) (selectable-ice? [card] (and (ice? card) (installed? card) (zero? (get-counters card :advancement)))) (ice-with-no-advancement-tokens [state] (->> (all-installed state :corp) (filter selectable-ice?)))] {:events [{:event :corp-turn-ends :optional {:req (req (and (not-empty (installed-faceup-agendas state)) (not-empty (ice-with-no-advancement-tokens state)))) :waiting-prompt "Corp to make a decision" :prompt "Place advancement tokens?" :autoresolve (get-autoresolve :auto-sso) :yes-ability {:async true :effect (req (let [agendas (installed-faceup-agendas state) agenda-points (->> agendas (map :agendapoints) (reduce +)) ice (ice-with-no-advancement-tokens state)] (continue-ability state side {:prompt (str "Choose a piece of ice with no advancement tokens to place " (quantify agenda-points "advancement token") " on") :choices {:card #(selectable-ice? %)} :msg (msg "place " (quantify agenda-points "advancement token") " on " (card-str state target)) :effect (effect (add-prop target :advance-counter agenda-points {:placed true}))} card nil)))}}}] :abilities [(set-autoresolve :auto-sso "SSO")]})) (defcard "PI:NAME:<NAME>END_PI: Master Grifter" {:events [{:event :successful-run :optional {:req (req (and (= :hq (target-server context)) (first-successful-run-on-server? state :hq) (<= 2 (count (:discard runner))) (not (zone-locked? state :runner :discard)))) :prompt "Use Steve Cambridge ability?" :yes-ability {:interactive (req true) :async true :prompt "Choose 2 cards in your Heap" :show-discard true :choices {:max 2 :all true :card #(and (in-discard? %) (runner? %))} :effect (effect (continue-ability (let [c1 (first targets) c2 (second targets)] {:waiting-prompt "Corp to make a decision" :prompt "Choose which card to remove from the game" :player :corp :choices [c1 c2] :msg (msg (let [[chosen other](if (= target c1) [c1 c2] [c2 c1])] (str "add " (:title other) " to their grip." " Corp removes " (:title chosen) " from the game"))) :effect (req (let [[chosen other] (if (= target c1) [c1 c2] [c2 c1])] (move state :runner chosen :rfg) (move state :runner other :hand)))}) card nil))}}}]}) (defcard "Strategic Innovations: Future Forward" {:events [{:event :pre-start-game :effect draft-points-target} {:event :runner-turn-ends :req (req (and (not (:disabled card)) (has-most-faction? state :corp "Haas-Bioroid") (pos? (count (:discard corp))))) :prompt "Choose a card in Archives to shuffle into R&D" :choices {:card #(and (corp? %) (in-discard? %))} :player :corp :show-discard true :msg (msg "shuffle " (if (:seen target) (:title target) "a card") " into R&D") :effect (effect (move :corp target :deck) (shuffle! :corp :deck))}]}) (defcard "PI:NAME:<NAME>END_PI: Security Specialist" ;; No special implementation {}) (defcard "SYNC: Everything, Everywhere" {:constant-effects [{:type :card-ability-additional-cost :req (req (let [targetcard (first targets) target (second targets)] (and (not (:sync-flipped card)) (same-card? targetcard (:basic-action-card runner)) (= "Remove 1 tag" (:label target))))) :value [:credit 1]} {:type :card-ability-additional-cost :req (req (let [targetcard (first targets) target (second targets)] (and (:sync-flipped card) (same-card? targetcard (:basic-action-card corp)) (= "Trash 1 resource if the Runner is tagged" (:label target))))) :value [:credit -2]}] :abilities [{:cost [:click 1] :effect (req (if (:sync-flipped card) (update! state side (-> card (assoc :sync-flipped false :face :front :code "09001"))) (update! state side (-> card (assoc :sync-flipped true :face :back :code "sync"))))) :label "Flip this identity" :msg "flip their ID"}]}) (defcard "Synthetic Systems: The World Re-imagined" {:events [{:event :pre-start-game :effect draft-points-target}] :flags {:corp-phase-12 (req (and (not (:disabled (get-card state card))) (has-most-faction? state :corp "Jinteki") (<= 2 (count (filter ice? (all-installed state :corp))))))} :abilities [{:prompt "Choose two pieces of installed ice to swap" :label "swap two pieces of installed ice" :choices {:card #(and (installed? %) (ice? %)) :max 2 :all true} :once :per-turn :effect (req (apply swap-ice state side targets)) :msg (msg "swap the positions of " (card-str state (first targets)) " and " (card-str state (second targets)))}]}) (defcard "Tāo Salonga: Telepresence Magician" (let [swap-ability {:interactive (req true) :optional {:req (req (<= 2 (count (filter ice? (all-installed state :corp))))) :prompt "Swap ice with Tāo Salonga's ability?" :waiting-prompt "the Runner to swap ice." :yes-ability {:prompt "Choose 2 ice" :choices {:req (req (and (installed? target) (ice? target))) :max 2 :all true} :msg (msg "swap the positions of " (card-str state (first targets)) " and " (card-str state (second targets))) :effect (req (swap-ice state side (first targets) (second targets)))} :no-ability {:effect (effect (system-msg "declines to use Tāo Salonga: Telepresence Magician"))}}}] {:events [(assoc swap-ability :event :agenda-scored) (assoc swap-ability :event :agenda-stolen)]})) (defcard "Tennin Institute: The Secrets Within" {:flags {:corp-phase-12 (req (and (not (:disabled (get-card state card))) (not-last-turn? state :runner :successful-run)))} :abilities [{:msg (msg "place 1 advancement token on " (card-str state target)) :label "Place 1 advancement token on a card if the Runner did not make a successful run last turn" :choices {:card installed?} :req (req (and (:corp-phase-12 @state) (not-last-turn? state :runner :successful-run))) :once :per-turn :effect (effect (add-prop target :advance-counter 1 {:placed true}))}]}) (defcard "The Catalyst: Convention Breaker" ;; No special implementation {}) (defcard "The Foundry: Refining the Process" {:events [{:event :rez :optional {:prompt "Add another copy to HQ?" :req (req (and (ice? (:card context)) (first-event? state :runner :rez #(ice? (:card (first %)))))) :yes-ability {:effect (req (if-let [found-card (some #(when (= (:title %) (:title (:card context))) %) (concat (:deck corp) (:play-area corp)))] (do (move state side found-card :hand) (system-msg state side (str "uses The Foundry to add a copy of " (:title found-card) " to HQ, and shuffles their deck")) (shuffle! state side :deck)) (do (system-msg state side (str "fails to find a target for The Foundry, and shuffles their deck")) (shuffle! state side :deck))))}}}]}) (defcard "The Masque: Cyber General" {:events [{:event :pre-start-game :effect draft-points-target}]}) (defcard "The Outfit: Family Owned and Operated" {:events [{:event :corp-gain-bad-publicity :msg "gain 3 [Credit]" :async true :effect (effect (gain-credits eid 3))}]}) (defcard "The Professor: Keeper of Knowledge" ;; No special implementation {}) (defcard "The Shadow: Pulling the Strings" {:events [{:event :pre-start-game :effect draft-points-target}]}) (defcard "The Syndicate: Profit over Principle" ;; No special implementation {}) (defcard "Titan Transnational: Investing In Your Future" {:events [{:event :agenda-scored :msg (msg "place 1 agenda counter on " (:title (:card context))) :effect (effect (add-counter (get-card state (:card context)) :agenda 1))}]}) (defcard "PI:NAME:<NAME>END_PI: The Angel of Cayambe" {:events [{:event :pre-start-game :req (req (and (= side :runner) (zero? (count-bad-pub state)))) ;; This doesn't use `gain-bad-publicity` to avoid the event :effect (effect (gain :corp :bad-publicity 1))}]}) (defcard "Weyland Consortium: Because We Built It" {:recurring 1 :interactions {:pay-credits {:req (req (= :advance (:source-type eid))) :type :recurring}}}) (defcard "Weyland Consortium: Builder of Nations" {:implementation "Erratum: The first time an encounter with a piece of ice with at least 1 advancement token ends each turn, do 1 meat damage." :events [{:event :end-of-encounter :async true :req (req (and (rezzed? (:ice context)) (pos? (get-counters (:ice context) :advancement)) (first-event? state :runner :end-of-encounter (fn [targets] (let [context (first targets)] (and (rezzed? (:ice context)) (pos? (get-counters (:ice context) :advancement)))))))) :msg "do 1 meat damage" :effect (effect (damage eid :meat 1 {:card card}))}]}) (defcard "Weyland Consortium: Building a Better World" {:events [{:event :play-operation :req (req (has-subtype? (:card context) "Transaction")) :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits eid 1))}]}) (defcard "Weyland Consortium: Built to Last" {:events [{:event :advance :async true :req (req ((complement pos?) (- (get-counters target :advancement) (:amount (second targets) 0)))) :msg "gain 2 [Credits]" :effect (req (gain-credits state :corp eid 2))}]}) (defcard "Whizzard: Master Gamer" {:recurring 3 :interactions {:pay-credits {:req (req (and (= :runner-trash-corp-cards (:source-type eid)) (corp? target))) :type :recurring}}}) (defcard "Wyvern: Chemically Enhanced" {:events [{:event :pre-start-game :effect draft-points-target} {:event :runner-trash :interactive (req true) :req (req (and (has-most-faction? state :runner "Anarch") (corp? (:card target)) (pos? (count (:discard runner))) (not (zone-locked? state :runner :discard)))) :msg (msg "shuffle " (:title (last (:discard runner))) " into their Stack") :effect (effect (move :runner (last (:discard runner)) :deck) (shuffle! :runner :deck) (trigger-event :searched-stack nil))}]}) (defcard "PI:NAME:<NAME>END_PI: Versatile Smuggler" {:events [{:event :run-ends :optional {:req (req (and (#{:hq :rd} (target-server context)) (pos? (total-cards-accessed context)))) :prompt "Gain 1 [Credits] for each card you accessed?" :async true :once :per-turn :yes-ability {:msg (msg "gain " (total-cards-accessed context) " [Credits]") :once :per-turn :async true :effect (req (gain-credits state :runner eid (total-cards-accessed context)))}}}]})
[ { "context": "(ns ^{:author \"Adam Berger\"} ulvm.cli\n (:require [clojure.tools.cli :as cli", "end": 26, "score": 0.9998694062232971, "start": 15, "tag": "NAME", "value": "Adam Berger" } ]
src/ulvm/cli.clj
abrgr/ulvm
0
(ns ^{:author "Adam Berger"} ulvm.cli (:require [clojure.tools.cli :as cli] [clojure.string :as string] [clojure.spec.test :as st] [clojure.edn :as edn] [ulvm.compiler :as cmpl])) (def cli-opts [["-d" "--dir DIR" "Directory" :default "."] ["-i" "--instrument" "Instrument"] ["-e" "--env" "Initial environment"] ["-h" "--help"]]) (defn- usage ([summary] (usage summary [])) ([summary errors] (string/join \newline (conj errors summary)))) (defn- validate-opts [{:keys [errors summary options]}] (cond (some? errors) {:msg (usage summary errors), :exit-with 2} (:help options) {:msg (usage summary), :exit-with 0} :else {:opts options})) (defn- run-compiler [opts] (when (:instrument opts) (st/instrument (st/instrumentable-syms 'ulvm))) (let [dir (:dir opts) cmd-line-env (edn/read-string (:env opts)) prj (cmpl/ulvm-compile cmd-line-env dir)] (println prj))) (defn- exit [msg status] (println msg) (System/exit status)) (defn -main [& args] (let [{:keys [msg opts exit-with]} (-> (cli/parse-opts args cli-opts) (validate-opts))] (cond (some? exit-with) (exit msg exit-with) :else (run-compiler opts))))
33344
(ns ^{:author "<NAME>"} ulvm.cli (:require [clojure.tools.cli :as cli] [clojure.string :as string] [clojure.spec.test :as st] [clojure.edn :as edn] [ulvm.compiler :as cmpl])) (def cli-opts [["-d" "--dir DIR" "Directory" :default "."] ["-i" "--instrument" "Instrument"] ["-e" "--env" "Initial environment"] ["-h" "--help"]]) (defn- usage ([summary] (usage summary [])) ([summary errors] (string/join \newline (conj errors summary)))) (defn- validate-opts [{:keys [errors summary options]}] (cond (some? errors) {:msg (usage summary errors), :exit-with 2} (:help options) {:msg (usage summary), :exit-with 0} :else {:opts options})) (defn- run-compiler [opts] (when (:instrument opts) (st/instrument (st/instrumentable-syms 'ulvm))) (let [dir (:dir opts) cmd-line-env (edn/read-string (:env opts)) prj (cmpl/ulvm-compile cmd-line-env dir)] (println prj))) (defn- exit [msg status] (println msg) (System/exit status)) (defn -main [& args] (let [{:keys [msg opts exit-with]} (-> (cli/parse-opts args cli-opts) (validate-opts))] (cond (some? exit-with) (exit msg exit-with) :else (run-compiler opts))))
true
(ns ^{:author "PI:NAME:<NAME>END_PI"} ulvm.cli (:require [clojure.tools.cli :as cli] [clojure.string :as string] [clojure.spec.test :as st] [clojure.edn :as edn] [ulvm.compiler :as cmpl])) (def cli-opts [["-d" "--dir DIR" "Directory" :default "."] ["-i" "--instrument" "Instrument"] ["-e" "--env" "Initial environment"] ["-h" "--help"]]) (defn- usage ([summary] (usage summary [])) ([summary errors] (string/join \newline (conj errors summary)))) (defn- validate-opts [{:keys [errors summary options]}] (cond (some? errors) {:msg (usage summary errors), :exit-with 2} (:help options) {:msg (usage summary), :exit-with 0} :else {:opts options})) (defn- run-compiler [opts] (when (:instrument opts) (st/instrument (st/instrumentable-syms 'ulvm))) (let [dir (:dir opts) cmd-line-env (edn/read-string (:env opts)) prj (cmpl/ulvm-compile cmd-line-env dir)] (println prj))) (defn- exit [msg status] (println msg) (System/exit status)) (defn -main [& args] (let [{:keys [msg opts exit-with]} (-> (cli/parse-opts args cli-opts) (validate-opts))] (cond (some? exit-with) (exit msg exit-with) :else (run-compiler opts))))
[ { "context": "}})\n\n(def people\n (->>\n [#:person{:nick-name \"Levi\"\n :display-name \"Levi Tan Ong\"\n ", "end": 1116, "score": 0.9996014833450317, "start": 1112, "tag": "NAME", "value": "Levi" }, { "context": "on{:nick-name \"Levi\"\n :display-name \"Levi Tan Ong\"\n :roles [:cof :dev :des]\n ", "end": 1159, "score": 0.9998397827148438, "start": 1147, "tag": "NAME", "value": "Levi Tan Ong" }, { "context": ":dev :des]\n :link \"http://github.com/levitanong\"}\n #:person{:nick-name \"Phi\"\n :d", "end": 1248, "score": 0.9997222423553467, "start": 1238, "tag": "USERNAME", "value": "levitanong" }, { "context": "github.com/levitanong\"}\n #:person{:nick-name \"Phi\"\n :display-name \"Philip Cheang\"\n ", "end": 1280, "score": 0.9998762011528015, "start": 1277, "tag": "NAME", "value": "Phi" }, { "context": "son{:nick-name \"Phi\"\n :display-name \"Philip Cheang\"\n :roles [:cof :dev :des :mkt]\n ", "end": 1324, "score": 0.9998267889022827, "start": 1311, "tag": "NAME", "value": "Philip Cheang" }, { "context": " :link \"http://phi.ph\"}\n #:person{:nick-name \"Rodz\"\n :display-name \"Rodrick Tan\"\n ", "end": 1436, "score": 0.9997552037239075, "start": 1432, "tag": "NAME", "value": "Rodz" }, { "context": "on{:nick-name \"Rodz\"\n :display-name \"Rodrick Tan\"\n :roles [:cof :biz :pm]}\n #:per", "end": 1478, "score": 0.9998265504837036, "start": 1467, "tag": "NAME", "value": "Rodrick Tan" }, { "context": ":roles [:cof :biz :pm]}\n #:person{:nick-name \"Kenneth\"\n :display-name \"Kenneth Yu\"\n ", "end": 1551, "score": 0.9998395442962646, "start": 1544, "tag": "NAME", "value": "Kenneth" }, { "context": ":nick-name \"Kenneth\"\n :display-name \"Kenneth Yu\"\n :roles [:cof :biz :pm]\n ", "end": 1592, "score": 0.9998461604118347, "start": 1582, "tag": "NAME", "value": "Kenneth Yu" }, { "context": ":biz :pm]\n :link \"http://twitter.com/kennethgyu\"}\n #:person{:nick-name \"Wil\"\n :d", "end": 1681, "score": 0.9997326135635376, "start": 1671, "tag": "USERNAME", "value": "kennethgyu" }, { "context": "witter.com/kennethgyu\"}\n #:person{:nick-name \"Wil\"\n :display-name \"Wilhansen Li\"\n ", "end": 1713, "score": 0.9997390508651733, "start": 1710, "tag": "NAME", "value": "Wil" }, { "context": "son{:nick-name \"Wil\"\n :display-name \"Wilhansen Li\"\n :roles [:cof :dev]\n :", "end": 1756, "score": 0.9998254179954529, "start": 1744, "tag": "NAME", "value": "Wilhansen Li" }, { "context": " \"http://wilhansen.li\"}\n #:person{:nick-name \"Pepe\"\n :display-name \"Pepe Bawagan\"\n ", "end": 1864, "score": 0.9997363090515137, "start": 1860, "tag": "NAME", "value": "Pepe" }, { "context": "on{:nick-name \"Pepe\"\n :display-name \"Pepe Bawagan\"\n :roles [:dev]\n :link ", "end": 1907, "score": 0.9998282790184021, "start": 1895, "tag": "NAME", "value": "Pepe Bawagan" }, { "context": " \"http://syk0saje.com\"}\n #:person{:nick-name \"Albert\"\n :display-name \"Albert Dizon\"\n ", "end": 2012, "score": 0.9998222589492798, "start": 2006, "tag": "NAME", "value": "Albert" }, { "context": "{:nick-name \"Albert\"\n :display-name \"Albert Dizon\"\n :roles [:dev]}\n #:person{:nick", "end": 2055, "score": 0.9998453259468079, "start": 2043, "tag": "NAME", "value": "Albert Dizon" }, { "context": " :roles [:dev]}\n #:person{:nick-name \"Sesky\"\n :display-name \"Jonathan Sescon\"\n ", "end": 2117, "score": 0.999779462814331, "start": 2112, "tag": "NAME", "value": "Sesky" }, { "context": "n{:nick-name \"Sesky\"\n :display-name \"Jonathan Sescon\"\n :roles [:dev]\n :link ", "end": 2163, "score": 0.9998623132705688, "start": 2148, "tag": "NAME", "value": "Jonathan Sescon" }, { "context": "es [:dev]\n :link \"https://github.com/jrsescon\"}\n #:person{:nick-name \"Patsy\"\n ", "end": 2241, "score": 0.999661922454834, "start": 2233, "tag": "USERNAME", "value": "jrsescon" }, { "context": "//github.com/jrsescon\"}\n #:person{:nick-name \"Patsy\"\n :display-name \"Patricia Lascano\"\n ", "end": 2275, "score": 0.9998536705970764, "start": 2270, "tag": "NAME", "value": "Patsy" }, { "context": "n{:nick-name \"Patsy\"\n :display-name \"Patricia Lascano\"\n :roles [:des]}\n #:person{:nick", "end": 2322, "score": 0.9998543858528137, "start": 2306, "tag": "NAME", "value": "Patricia Lascano" }, { "context": " :roles [:des]}\n #:person{:nick-name \"Alvin\"\n :display-name \"Alvin Dumalus\"\n ", "end": 2384, "score": 0.9998393058776855, "start": 2379, "tag": "NAME", "value": "Alvin" }, { "context": "n{:nick-name \"Alvin\"\n :display-name \"Alvin Dumalus\"\n :roles [:dev]\n :link ", "end": 2428, "score": 0.9998443722724915, "start": 2415, "tag": "NAME", "value": "Alvin Dumalus" }, { "context": "es [:dev]\n :link \"https://github.com/alvinfrancis\"}\n #:person{:nick-name \"Thomas\"\n ", "end": 2510, "score": 0.9994938969612122, "start": 2498, "tag": "USERNAME", "value": "alvinfrancis" }, { "context": "thub.com/alvinfrancis\"}\n #:person{:nick-name \"Thomas\"\n :display-name \"Thomas Dy\"\n ", "end": 2545, "score": 0.9998054504394531, "start": 2539, "tag": "NAME", "value": "Thomas" }, { "context": "{:nick-name \"Thomas\"\n :display-name \"Thomas Dy\"\n :roles [:dev]\n :link ", "end": 2585, "score": 0.9998117685317993, "start": 2576, "tag": "NAME", "value": "Thomas Dy" }, { "context": "leasantprogrammer.com\"}\n #:person{:nick-name \"Jim\"\n :display-name \"James Choa\"\n ", "end": 2697, "score": 0.9998729825019836, "start": 2694, "tag": "NAME", "value": "Jim" }, { "context": "son{:nick-name \"Jim\"\n :display-name \"James Choa\"\n :roles [:dev]\n :link ", "end": 2738, "score": 0.9998223185539246, "start": 2728, "tag": "NAME", "value": "James Choa" }, { "context": "es [:dev]\n :link \"https://github.com/trigger-happy\"}\n #:person{:nick-name \"Enzo\"\n :", "end": 2821, "score": 0.9941337704658508, "start": 2808, "tag": "USERNAME", "value": "trigger-happy" }, { "context": "hub.com/trigger-happy\"}\n #:person{:nick-name \"Enzo\"\n :display-name \"Lorenzo Vergara\"\n ", "end": 2854, "score": 0.9998434782028198, "start": 2850, "tag": "NAME", "value": "Enzo" }, { "context": "on{:nick-name \"Enzo\"\n :display-name \"Lorenzo Vergara\"\n :roles [:dev]}\n #:person{:nick", "end": 2900, "score": 0.9998400211334229, "start": 2885, "tag": "NAME", "value": "Lorenzo Vergara" }, { "context": " :roles [:dev]}\n #:person{:nick-name \"J\"\n :display-name \"John Ugalino\"\n ", "end": 2958, "score": 0.9998869895935059, "start": 2957, "tag": "NAME", "value": "J" }, { "context": "erson{:nick-name \"J\"\n :display-name \"John Ugalino\"\n :roles [:dev]}]\n (map-indexed\n ", "end": 3001, "score": 0.9998546242713928, "start": 2989, "tag": "NAME", "value": "John Ugalino" } ]
data/train/clojure/0f638d6815597d8a75c10bfb01ac919c122ac172data.cljc
harshp8l/deep-learning-lang-detection
84
(ns bahay.data) (def asset-url "http://assets.byimplication.com/site/") (def roles {:cof #:role{:id :cof :label "Co-Founder"} :dev #:role{:id :dev :label "Developer" :icon-id "developer" :reqs ["Any language" "Ideally familiar with functional programming" "Bonus if involved in open source projects"]} :des #:role{:id :des :label "Designer" :icon-id "designer" :reqs ["UI/UX" "Preferably comfy with code"]} :biz #:role{:id :biz :label "Business Analyst"} :mkt #:role{:id :mkt :label "Marketer" :icon-id "marketer" :reqs ["Can manage social media accounts" "Can handle marketing efforts for multiple projects"]} :pm #:role{:id :pm :label "Project Manager" :icon-id "manager" :reqs ["Can direct projects" "Can get things done"]}}) (def people (->> [#:person{:nick-name "Levi" :display-name "Levi Tan Ong" :roles [:cof :dev :des] :link "http://github.com/levitanong"} #:person{:nick-name "Phi" :display-name "Philip Cheang" :roles [:cof :dev :des :mkt] :link "http://phi.ph"} #:person{:nick-name "Rodz" :display-name "Rodrick Tan" :roles [:cof :biz :pm]} #:person{:nick-name "Kenneth" :display-name "Kenneth Yu" :roles [:cof :biz :pm] :link "http://twitter.com/kennethgyu"} #:person{:nick-name "Wil" :display-name "Wilhansen Li" :roles [:cof :dev] :link "http://wilhansen.li"} #:person{:nick-name "Pepe" :display-name "Pepe Bawagan" :roles [:dev] :link "http://syk0saje.com"} #:person{:nick-name "Albert" :display-name "Albert Dizon" :roles [:dev]} #:person{:nick-name "Sesky" :display-name "Jonathan Sescon" :roles [:dev] :link "https://github.com/jrsescon"} #:person{:nick-name "Patsy" :display-name "Patricia Lascano" :roles [:des]} #:person{:nick-name "Alvin" :display-name "Alvin Dumalus" :roles [:dev] :link "https://github.com/alvinfrancis"} #:person{:nick-name "Thomas" :display-name "Thomas Dy" :roles [:dev] :link "http://pleasantprogrammer.com"} #:person{:nick-name "Jim" :display-name "James Choa" :roles [:dev] :link "https://github.com/trigger-happy"} #:person{:nick-name "Enzo" :display-name "Lorenzo Vergara" :roles [:dev]} #:person{:nick-name "J" :display-name "John Ugalino" :roles [:dev]}] (map-indexed (fn [index person] (-> person (assoc :person/id index :person/image-url (str asset-url "people/" (:person/nick-name person) ".png")) (update :person/roles (partial mapv roles))))) (vec))) (def services {:ui #:service{:id :ui :label "UI/UX" :icon-id "design" :writeup "We not only think about what the product looks like, but how it will work."} :dev #:service{:id :dev :label "Development" :icon-id "development" :writeup "We use cutting edge techniques in building fast, fully featured apps."} :dir #:service{:id :dir :label "Business Direction" :icon-id "business" :writeup "Our business specialists ensure that products make sense."} :big #:service{:id :big :label "Big Data" :icon-id "big-data" :writeup "Our data scientists are able to create sophisticated models."}}) (def projects [#:project{:id :sakay :label "Sakay" :ownership :in-house :services [(services :dev) (services :ui) (services :big)] :featured true :accent "#2a6d45" :image-url (str asset-url "projects/sakay/sakay-timedate-mockup.jpg")} #:project{:id :openrecon :label "Open Reconstruction" :ownership :client :services [(services :dev) (services :ui)]} #:project{:id :storylark :label "Storylark" :ownership :in-house :services [(services :dev) (services :ui)]} #_{:project/id :wildfire :project/name "Wildfire"}])
41862
(ns bahay.data) (def asset-url "http://assets.byimplication.com/site/") (def roles {:cof #:role{:id :cof :label "Co-Founder"} :dev #:role{:id :dev :label "Developer" :icon-id "developer" :reqs ["Any language" "Ideally familiar with functional programming" "Bonus if involved in open source projects"]} :des #:role{:id :des :label "Designer" :icon-id "designer" :reqs ["UI/UX" "Preferably comfy with code"]} :biz #:role{:id :biz :label "Business Analyst"} :mkt #:role{:id :mkt :label "Marketer" :icon-id "marketer" :reqs ["Can manage social media accounts" "Can handle marketing efforts for multiple projects"]} :pm #:role{:id :pm :label "Project Manager" :icon-id "manager" :reqs ["Can direct projects" "Can get things done"]}}) (def people (->> [#:person{:nick-name "<NAME>" :display-name "<NAME>" :roles [:cof :dev :des] :link "http://github.com/levitanong"} #:person{:nick-name "<NAME>" :display-name "<NAME>" :roles [:cof :dev :des :mkt] :link "http://phi.ph"} #:person{:nick-name "<NAME>" :display-name "<NAME>" :roles [:cof :biz :pm]} #:person{:nick-name "<NAME>" :display-name "<NAME>" :roles [:cof :biz :pm] :link "http://twitter.com/kennethgyu"} #:person{:nick-name "<NAME>" :display-name "<NAME>" :roles [:cof :dev] :link "http://wilhansen.li"} #:person{:nick-name "<NAME>" :display-name "<NAME>" :roles [:dev] :link "http://syk0saje.com"} #:person{:nick-name "<NAME>" :display-name "<NAME>" :roles [:dev]} #:person{:nick-name "<NAME>" :display-name "<NAME>" :roles [:dev] :link "https://github.com/jrsescon"} #:person{:nick-name "<NAME>" :display-name "<NAME>" :roles [:des]} #:person{:nick-name "<NAME>" :display-name "<NAME>" :roles [:dev] :link "https://github.com/alvinfrancis"} #:person{:nick-name "<NAME>" :display-name "<NAME>" :roles [:dev] :link "http://pleasantprogrammer.com"} #:person{:nick-name "<NAME>" :display-name "<NAME>" :roles [:dev] :link "https://github.com/trigger-happy"} #:person{:nick-name "<NAME>" :display-name "<NAME>" :roles [:dev]} #:person{:nick-name "<NAME>" :display-name "<NAME>" :roles [:dev]}] (map-indexed (fn [index person] (-> person (assoc :person/id index :person/image-url (str asset-url "people/" (:person/nick-name person) ".png")) (update :person/roles (partial mapv roles))))) (vec))) (def services {:ui #:service{:id :ui :label "UI/UX" :icon-id "design" :writeup "We not only think about what the product looks like, but how it will work."} :dev #:service{:id :dev :label "Development" :icon-id "development" :writeup "We use cutting edge techniques in building fast, fully featured apps."} :dir #:service{:id :dir :label "Business Direction" :icon-id "business" :writeup "Our business specialists ensure that products make sense."} :big #:service{:id :big :label "Big Data" :icon-id "big-data" :writeup "Our data scientists are able to create sophisticated models."}}) (def projects [#:project{:id :sakay :label "Sakay" :ownership :in-house :services [(services :dev) (services :ui) (services :big)] :featured true :accent "#2a6d45" :image-url (str asset-url "projects/sakay/sakay-timedate-mockup.jpg")} #:project{:id :openrecon :label "Open Reconstruction" :ownership :client :services [(services :dev) (services :ui)]} #:project{:id :storylark :label "Storylark" :ownership :in-house :services [(services :dev) (services :ui)]} #_{:project/id :wildfire :project/name "Wildfire"}])
true
(ns bahay.data) (def asset-url "http://assets.byimplication.com/site/") (def roles {:cof #:role{:id :cof :label "Co-Founder"} :dev #:role{:id :dev :label "Developer" :icon-id "developer" :reqs ["Any language" "Ideally familiar with functional programming" "Bonus if involved in open source projects"]} :des #:role{:id :des :label "Designer" :icon-id "designer" :reqs ["UI/UX" "Preferably comfy with code"]} :biz #:role{:id :biz :label "Business Analyst"} :mkt #:role{:id :mkt :label "Marketer" :icon-id "marketer" :reqs ["Can manage social media accounts" "Can handle marketing efforts for multiple projects"]} :pm #:role{:id :pm :label "Project Manager" :icon-id "manager" :reqs ["Can direct projects" "Can get things done"]}}) (def people (->> [#:person{:nick-name "PI:NAME:<NAME>END_PI" :display-name "PI:NAME:<NAME>END_PI" :roles [:cof :dev :des] :link "http://github.com/levitanong"} #:person{:nick-name "PI:NAME:<NAME>END_PI" :display-name "PI:NAME:<NAME>END_PI" :roles [:cof :dev :des :mkt] :link "http://phi.ph"} #:person{:nick-name "PI:NAME:<NAME>END_PI" :display-name "PI:NAME:<NAME>END_PI" :roles [:cof :biz :pm]} #:person{:nick-name "PI:NAME:<NAME>END_PI" :display-name "PI:NAME:<NAME>END_PI" :roles [:cof :biz :pm] :link "http://twitter.com/kennethgyu"} #:person{:nick-name "PI:NAME:<NAME>END_PI" :display-name "PI:NAME:<NAME>END_PI" :roles [:cof :dev] :link "http://wilhansen.li"} #:person{:nick-name "PI:NAME:<NAME>END_PI" :display-name "PI:NAME:<NAME>END_PI" :roles [:dev] :link "http://syk0saje.com"} #:person{:nick-name "PI:NAME:<NAME>END_PI" :display-name "PI:NAME:<NAME>END_PI" :roles [:dev]} #:person{:nick-name "PI:NAME:<NAME>END_PI" :display-name "PI:NAME:<NAME>END_PI" :roles [:dev] :link "https://github.com/jrsescon"} #:person{:nick-name "PI:NAME:<NAME>END_PI" :display-name "PI:NAME:<NAME>END_PI" :roles [:des]} #:person{:nick-name "PI:NAME:<NAME>END_PI" :display-name "PI:NAME:<NAME>END_PI" :roles [:dev] :link "https://github.com/alvinfrancis"} #:person{:nick-name "PI:NAME:<NAME>END_PI" :display-name "PI:NAME:<NAME>END_PI" :roles [:dev] :link "http://pleasantprogrammer.com"} #:person{:nick-name "PI:NAME:<NAME>END_PI" :display-name "PI:NAME:<NAME>END_PI" :roles [:dev] :link "https://github.com/trigger-happy"} #:person{:nick-name "PI:NAME:<NAME>END_PI" :display-name "PI:NAME:<NAME>END_PI" :roles [:dev]} #:person{:nick-name "PI:NAME:<NAME>END_PI" :display-name "PI:NAME:<NAME>END_PI" :roles [:dev]}] (map-indexed (fn [index person] (-> person (assoc :person/id index :person/image-url (str asset-url "people/" (:person/nick-name person) ".png")) (update :person/roles (partial mapv roles))))) (vec))) (def services {:ui #:service{:id :ui :label "UI/UX" :icon-id "design" :writeup "We not only think about what the product looks like, but how it will work."} :dev #:service{:id :dev :label "Development" :icon-id "development" :writeup "We use cutting edge techniques in building fast, fully featured apps."} :dir #:service{:id :dir :label "Business Direction" :icon-id "business" :writeup "Our business specialists ensure that products make sense."} :big #:service{:id :big :label "Big Data" :icon-id "big-data" :writeup "Our data scientists are able to create sophisticated models."}}) (def projects [#:project{:id :sakay :label "Sakay" :ownership :in-house :services [(services :dev) (services :ui) (services :big)] :featured true :accent "#2a6d45" :image-url (str asset-url "projects/sakay/sakay-timedate-mockup.jpg")} #:project{:id :openrecon :label "Open Reconstruction" :ownership :client :services [(services :dev) (services :ui)]} #:project{:id :storylark :label "Storylark" :ownership :in-house :services [(services :dev) (services :ui)]} #_{:project/id :wildfire :project/name "Wildfire"}])
[ { "context": " :author-id nil, :text nil})\n\n(def user {:password nil, :name nil, :nickname nil, :id nil, :avatar nil})", "end": 133, "score": 0.9783006310462952, "start": 130, "tag": "PASSWORD", "value": "nil" } ]
server/src/chatroom_server/schema.cljs
TopixIM/chatroom
0
(ns chatroom-server.schema ) (def message {:time nil, :id nil, :topic-id nil, :author-id nil, :text nil}) (def user {:password nil, :name nil, :nickname nil, :id nil, :avatar nil}) (def database {:states {}, :topics {}, :users {}}) (def state {:router {:name :home, :data nil}, :nickname nil, :user-id nil, :notifications [], :id nil}) (def router {:router nil, :name nil, :title nil, :data {}}) (def notification {:id nil, :kind nil, :text nil}) (def topic {:time nil, :title nil, :messages {}, :id nil, :author-id nil})
124020
(ns chatroom-server.schema ) (def message {:time nil, :id nil, :topic-id nil, :author-id nil, :text nil}) (def user {:password <PASSWORD>, :name nil, :nickname nil, :id nil, :avatar nil}) (def database {:states {}, :topics {}, :users {}}) (def state {:router {:name :home, :data nil}, :nickname nil, :user-id nil, :notifications [], :id nil}) (def router {:router nil, :name nil, :title nil, :data {}}) (def notification {:id nil, :kind nil, :text nil}) (def topic {:time nil, :title nil, :messages {}, :id nil, :author-id nil})
true
(ns chatroom-server.schema ) (def message {:time nil, :id nil, :topic-id nil, :author-id nil, :text nil}) (def user {:password PI:PASSWORD:<PASSWORD>END_PI, :name nil, :nickname nil, :id nil, :avatar nil}) (def database {:states {}, :topics {}, :users {}}) (def state {:router {:name :home, :data nil}, :nickname nil, :user-id nil, :notifications [], :id nil}) (def router {:router nil, :name nil, :title nil, :data {}}) (def notification {:id nil, :kind nil, :text nil}) (def topic {:time nil, :title nil, :messages {}, :id nil, :author-id nil})
[ { "context": "5 \"Kyle's Low-Carb Grill\"]\n [342 \"Kyle's Low-Carb Grill\"]\n [417 \"Kyle's L", "end": 663, "score": 0.5216861963272095, "start": 660, "tag": "NAME", "value": "yle" }, { "context": "eographical-tips\n ;; Let's get all the tips Kyle posted on Twitter sorted by tip.venue.name\n ", "end": 1346, "score": 0.6431243419647217, "start": 1345, "tag": "NAME", "value": "K" }, { "context": " (is (= [[446\n {:mentions [\"@cams_mexican_gastro_pub\"], :tags [\"#mexican\" \"#gastro\" \"#pub\"], :service ", "end": 1468, "score": 0.8676813244819641, "start": 1444, "tag": "USERNAME", "value": "@cams_mexican_gastro_pub" }, { "context": "\"#gastro\" \"#pub\"], :service \"twitter\", :username \"kyle\"}\n \"Cam's Mexican Gastro Pub is a", "end": 1544, "score": 0.9991133213043213, "start": 1540, "tag": "USERNAME", "value": "kyle" }, { "context": " [230\n {:mentions [\"@haight_european_grill\"], :tags [\"#european\" \"#grill\"], :service \"twitte", "end": 2201, "score": 0.9991905093193054, "start": 2179, "tag": "USERNAME", "value": "@haight_european_grill" }, { "context": "ropean\" \"#grill\"], :service \"twitter\", :username \"kyle\"}\n \"Haight European Grill is a ho", "end": 2270, "score": 0.999534010887146, "start": 2266, "tag": "USERNAME", "value": "kyle" }, { "context": "\"#food\" \"#stand\"], :service \"twitter\", :username \"kyle\"}\n \"Haight Soul Food Pop-Up Food ", "end": 3006, "score": 0.999588131904602, "start": 3002, "tag": "USERNAME", "value": "kyle" }, { "context": "range\" \"#eatery\"], :service \"twitter\", :username \"kyle\"}\n \"Pacific Heights Free-Range Ea", "end": 3765, "score": 0.9996157884597778, "start": 3761, "tag": "USERNAME", "value": "kyle" }, { "context": " [:= $tips.source.username \"kyle\"]]\n :order-by [[:asc $tips.ven", "end": 4596, "score": 0.9996837377548218, "start": 4592, "tag": "USERNAME", "value": "kyle" }, { "context": "]\n [\"biggie\" 11]\n [\"bob\" 20]]\n (mt/formatted-rows [str int]", "end": 6072, "score": 0.9852590560913086, "start": 6069, "tag": "NAME", "value": "bob" }, { "context": "[[\"Lucky's Gluten-Free Café\"]\n [\"Joe's Homestyle Eatery\"]\n [\"Lower Pac ", "end": 6599, "score": 0.7170671820640564, "start": 6598, "tag": "NAME", "value": "e" }, { "context": " [\"Sunset Homestyle Grill\"]\n [\"Kyle's Low-Carb Grill\"]\n [\"Mission Home", "end": 6886, "score": 0.9669896364212036, "start": 6882, "tag": "NAME", "value": "Kyle" }, { "context": " [\"Mission Homestyle Churros\"]\n [\"Sameer's Pizza Liquor Store\"]]\n (mt/rows", "end": 6974, "score": 0.5917495489120483, "start": 6970, "tag": "NAME", "value": "Same" }, { "context": " (mt/dataset geographical-tips\n (is (= [[\"jane\" 4]\n [\"kyle\" 5", "end": 7416, "score": 0.998418390750885, "start": 7412, "tag": "NAME", "value": "jane" }, { "context": " (is (= [[\"jane\" 4]\n [\"kyle\" 5]\n [\"tupac\" 5", "end": 7453, "score": 0.9986907243728638, "start": 7449, "tag": "NAME", "value": "kyle" }, { "context": " [\"kyle\" 5]\n [\"tupac\" 5]\n [\"jessica\" 6]", "end": 7491, "score": 0.9886142611503601, "start": 7486, "tag": "NAME", "value": "tupac" }, { "context": " [\"tupac\" 5]\n [\"jessica\" 6]\n [\"bob\" 7]\n ", "end": 7530, "score": 0.997860848903656, "start": 7523, "tag": "NAME", "value": "jessica" }, { "context": " [\"jessica\" 6]\n [\"bob\" 7]\n [\"lucky_pigeon\" ", "end": 7563, "score": 0.997490644454956, "start": 7560, "tag": "NAME", "value": "bob" }, { "context": " [\"bob\" 7]\n [\"lucky_pigeon\" 7]\n [\"joe\" 8]\n ", "end": 7609, "score": 0.9962048530578613, "start": 7597, "tag": "USERNAME", "value": "lucky_pigeon" }, { "context": " [\"lucky_pigeon\" 7]\n [\"joe\" 8]\n [\"mandy\" ", "end": 7637, "score": 0.9951807260513306, "start": 7634, "tag": "NAME", "value": "joe" }, { "context": " [\"joe\" 8]\n [\"mandy\" 8]\n [\"amy\" 9]", "end": 7676, "score": 0.9971693754196167, "start": 7671, "tag": "NAME", "value": "mandy" }, { "context": " [\"mandy\" 8]\n [\"amy\" 9]\n [\"biggie\" ", "end": 7711, "score": 0.9974203705787659, "start": 7708, "tag": "NAME", "value": "amy" }, { "context": " [\"amy\" 9]\n [\"biggie\" 9]\n [\"sameer\" ", "end": 7748, "score": 0.7278767824172974, "start": 7745, "tag": "NAME", "value": "big" }, { "context": " [\"amy\" 9]\n [\"biggie\" 9]\n [\"sameer\" 9]\n", "end": 7751, "score": 0.7371408939361572, "start": 7748, "tag": "USERNAME", "value": "gie" }, { "context": " [\"biggie\" 9]\n [\"sameer\" 9]\n [\"cam_saul\" 10]\n", "end": 7788, "score": 0.9839315414428711, "start": 7782, "tag": "NAME", "value": "sameer" }, { "context": " [\"sameer\" 9]\n [\"cam_saul\" 10]\n [\"rasta_toucan\" 13]\n ", "end": 7827, "score": 0.9274900555610657, "start": 7819, "tag": "USERNAME", "value": "cam_saul" }, { "context": " [\"cam_saul\" 10]\n [\"rasta_toucan\" 13]\n [nil 400]]\n ", "end": 7868, "score": 0.9783288836479187, "start": 7856, "tag": "USERNAME", "value": "rasta_toucan" } ]
c#-metabase/test/metabase/query_processor_test/nested_field_test.clj
hanakhry/Crime_Admin
0
(ns metabase.query-processor-test.nested-field-test "Tests for nested field access." (:require [clojure.test :refer :all] [metabase.test :as mt])) (deftest filter-test (mt/test-drivers (mt/normal-drivers-with-feature :nested-fields) (testing "Nested Field in FILTER" (mt/dataset geographical-tips ;; Get the first 10 tips where tip.venue.name == "Kyle's Low-Carb Grill" (is (= [[8 "Kyle's Low-Carb Grill"] [67 "Kyle's Low-Carb Grill"] [80 "Kyle's Low-Carb Grill"] [83 "Kyle's Low-Carb Grill"] [295 "Kyle's Low-Carb Grill"] [342 "Kyle's Low-Carb Grill"] [417 "Kyle's Low-Carb Grill"] [426 "Kyle's Low-Carb Grill"] [470 "Kyle's Low-Carb Grill"]] (mapv (fn [[id _ _ _ {venue-name :name}]] [id venue-name]) (mt/rows (mt/run-mbql-query tips {:filter [:= $tips.venue.name "Kyle's Low-Carb Grill"] :order-by [[:asc $id]] :limit 10}))))))))) (deftest order-by-test (mt/test-drivers (mt/normal-drivers-with-feature :nested-fields) (testing "Nested Field in ORDER-BY" (mt/dataset geographical-tips ;; Let's get all the tips Kyle posted on Twitter sorted by tip.venue.name (is (= [[446 {:mentions ["@cams_mexican_gastro_pub"], :tags ["#mexican" "#gastro" "#pub"], :service "twitter", :username "kyle"} "Cam's Mexican Gastro Pub is a historical and underappreciated place to conduct a business meeting with friends." {:large "http://cloudfront.net/6e3a5256-275f-4056-b61a-25990b4bb484/large.jpg", :medium "http://cloudfront.net/6e3a5256-275f-4056-b61a-25990b4bb484/med.jpg", :small "http://cloudfront.net/6e3a5256-275f-4056-b61a-25990b4bb484/small.jpg"} {:phone "415-320-9123", :name "Cam's Mexican Gastro Pub", :categories ["Mexican" "Gastro Pub"], :id "bb958ac5-758e-4f42-b984-6b0e13f25194"}] [230 {:mentions ["@haight_european_grill"], :tags ["#european" "#grill"], :service "twitter", :username "kyle"} "Haight European Grill is a horrible and amazing place to have a birthday party during winter." {:large "http://cloudfront.net/1dcef7de-a1c4-405b-a9e1-69c92d686ef1/large.jpg", :medium "http://cloudfront.net/1dcef7de-a1c4-405b-a9e1-69c92d686ef1/med.jpg", :small "http://cloudfront.net/1dcef7de-a1c4-405b-a9e1-69c92d686ef1/small.jpg"} {:phone "415-191-2778", :name "Haight European Grill", :categories ["European" "Grill"], :id "7e6281f7-5b17-4056-ada0-85453247bc8f"}] [319 {:mentions ["@haight_soul_food_pop_up_food_stand"], :tags ["#soul" "#food" "#pop-up" "#food" "#stand"], :service "twitter", :username "kyle"} "Haight Soul Food Pop-Up Food Stand is a underground and modern place to have breakfast on a Tuesday afternoon." {:large "http://cloudfront.net/8f613909-550f-4d79-96f6-dc498ff65d1b/large.jpg", :medium "http://cloudfront.net/8f613909-550f-4d79-96f6-dc498ff65d1b/med.jpg", :small "http://cloudfront.net/8f613909-550f-4d79-96f6-dc498ff65d1b/small.jpg"} {:phone "415-741-8726", :name "Haight Soul Food Pop-Up Food Stand", :categories ["Soul Food" "Pop-Up Food Stand"], :id "9735184b-1299-410f-a98e-10d9c548af42"}] [224 {:mentions ["@pacific_heights_free_range_eatery"], :tags ["#free-range" "#eatery"], :service "twitter", :username "kyle"} "Pacific Heights Free-Range Eatery is a wonderful and modern place to take visiting friends and relatives Friday nights." {:large "http://cloudfront.net/cedd4221-dbdb-46c3-95a9-935cce6b3fe5/large.jpg", :medium "http://cloudfront.net/cedd4221-dbdb-46c3-95a9-935cce6b3fe5/med.jpg", :small "http://cloudfront.net/cedd4221-dbdb-46c3-95a9-935cce6b3fe5/small.jpg"} {:phone "415-901-6541", :name "Pacific Heights Free-Range Eatery", :categories ["Free-Range" "Eatery"], :id "88b361c8-ce69-4b2e-b0f2-9deedd574af6"}]] (mt/rows (mt/run-mbql-query tips {:filter [:and [:= $tips.source.service "twitter"] [:= $tips.source.username "kyle"]] :order-by [[:asc $tips.venue.name]]})))))))) (deftest aggregation-test (mt/test-drivers (mt/normal-drivers-with-feature :nested-fields) (testing "Nested Field in AGGREGATION" (mt/dataset geographical-tips (testing ":distinct aggregation" ;; Let's see how many *distinct* venue names are mentioned (is (= [99] (mt/first-row (mt/run-mbql-query tips {:aggregation [[:distinct $tips.venue.name]]}))))) (testing ":count aggregation" ;; Now let's just get the regular count (is (= [500] (mt/first-row (mt/run-mbql-query tips {:aggregation [[:count $tips.venue.name]]}))))))))) (deftest breakout-test (mt/test-drivers (mt/normal-drivers-with-feature :nested-fields) (testing "Nested Field in BREAKOUT" ;; Let's see how many tips we have by source.service (mt/dataset geographical-tips (is (= [["facebook" 107] ["flare" 105] ["foursquare" 100] ["twitter" 98] ["yelp" 90]] (mt/formatted-rows [str int] (mt/run-mbql-query tips {:aggregation [[:count]] :breakout [$tips.source.service]})))) (is (= [[nil 297] ["amy" 20] ["biggie" 11] ["bob" 20]] (mt/formatted-rows [str int] (mt/run-mbql-query tips {:aggregation [[:count]] :breakout [$tips.source.username] :limit 4})))))))) (deftest fields-test (mt/test-drivers (mt/normal-drivers-with-feature :nested-fields) (testing "Nested Field in FIELDS" (mt/dataset geographical-tips ;; Return the first 10 tips with just tip.venue.name (is (= [["Lucky's Gluten-Free Café"] ["Joe's Homestyle Eatery"] ["Lower Pac Heights Cage-Free Coffee House"] ["Oakland European Liquor Store"] ["Tenderloin Gormet Restaurant"] ["Marina Modern Sushi"] ["Sunset Homestyle Grill"] ["Kyle's Low-Carb Grill"] ["Mission Homestyle Churros"] ["Sameer's Pizza Liquor Store"]] (mt/rows (mt/run-mbql-query tips {:fields [$tips.venue.name] :order-by [[:asc $id]] :limit 10})))))))) (deftest order-by-aggregation-test (mt/test-drivers (mt/normal-drivers-with-feature :nested-fields) (testing "Nested Field w/ ordering by aggregation" (mt/dataset geographical-tips (is (= [["jane" 4] ["kyle" 5] ["tupac" 5] ["jessica" 6] ["bob" 7] ["lucky_pigeon" 7] ["joe" 8] ["mandy" 8] ["amy" 9] ["biggie" 9] ["sameer" 9] ["cam_saul" 10] ["rasta_toucan" 13] [nil 400]] (mt/formatted-rows [identity int] (mt/run-mbql-query tips {:aggregation [[:count]] :breakout [$tips.source.mayor] :order-by [[:asc [:aggregation 0]]]}))))))))
71509
(ns metabase.query-processor-test.nested-field-test "Tests for nested field access." (:require [clojure.test :refer :all] [metabase.test :as mt])) (deftest filter-test (mt/test-drivers (mt/normal-drivers-with-feature :nested-fields) (testing "Nested Field in FILTER" (mt/dataset geographical-tips ;; Get the first 10 tips where tip.venue.name == "Kyle's Low-Carb Grill" (is (= [[8 "Kyle's Low-Carb Grill"] [67 "Kyle's Low-Carb Grill"] [80 "Kyle's Low-Carb Grill"] [83 "Kyle's Low-Carb Grill"] [295 "Kyle's Low-Carb Grill"] [342 "K<NAME>'s Low-Carb Grill"] [417 "Kyle's Low-Carb Grill"] [426 "Kyle's Low-Carb Grill"] [470 "Kyle's Low-Carb Grill"]] (mapv (fn [[id _ _ _ {venue-name :name}]] [id venue-name]) (mt/rows (mt/run-mbql-query tips {:filter [:= $tips.venue.name "Kyle's Low-Carb Grill"] :order-by [[:asc $id]] :limit 10}))))))))) (deftest order-by-test (mt/test-drivers (mt/normal-drivers-with-feature :nested-fields) (testing "Nested Field in ORDER-BY" (mt/dataset geographical-tips ;; Let's get all the tips <NAME>yle posted on Twitter sorted by tip.venue.name (is (= [[446 {:mentions ["@cams_mexican_gastro_pub"], :tags ["#mexican" "#gastro" "#pub"], :service "twitter", :username "kyle"} "Cam's Mexican Gastro Pub is a historical and underappreciated place to conduct a business meeting with friends." {:large "http://cloudfront.net/6e3a5256-275f-4056-b61a-25990b4bb484/large.jpg", :medium "http://cloudfront.net/6e3a5256-275f-4056-b61a-25990b4bb484/med.jpg", :small "http://cloudfront.net/6e3a5256-275f-4056-b61a-25990b4bb484/small.jpg"} {:phone "415-320-9123", :name "Cam's Mexican Gastro Pub", :categories ["Mexican" "Gastro Pub"], :id "bb958ac5-758e-4f42-b984-6b0e13f25194"}] [230 {:mentions ["@haight_european_grill"], :tags ["#european" "#grill"], :service "twitter", :username "kyle"} "Haight European Grill is a horrible and amazing place to have a birthday party during winter." {:large "http://cloudfront.net/1dcef7de-a1c4-405b-a9e1-69c92d686ef1/large.jpg", :medium "http://cloudfront.net/1dcef7de-a1c4-405b-a9e1-69c92d686ef1/med.jpg", :small "http://cloudfront.net/1dcef7de-a1c4-405b-a9e1-69c92d686ef1/small.jpg"} {:phone "415-191-2778", :name "Haight European Grill", :categories ["European" "Grill"], :id "7e6281f7-5b17-4056-ada0-85453247bc8f"}] [319 {:mentions ["@haight_soul_food_pop_up_food_stand"], :tags ["#soul" "#food" "#pop-up" "#food" "#stand"], :service "twitter", :username "kyle"} "Haight Soul Food Pop-Up Food Stand is a underground and modern place to have breakfast on a Tuesday afternoon." {:large "http://cloudfront.net/8f613909-550f-4d79-96f6-dc498ff65d1b/large.jpg", :medium "http://cloudfront.net/8f613909-550f-4d79-96f6-dc498ff65d1b/med.jpg", :small "http://cloudfront.net/8f613909-550f-4d79-96f6-dc498ff65d1b/small.jpg"} {:phone "415-741-8726", :name "Haight Soul Food Pop-Up Food Stand", :categories ["Soul Food" "Pop-Up Food Stand"], :id "9735184b-1299-410f-a98e-10d9c548af42"}] [224 {:mentions ["@pacific_heights_free_range_eatery"], :tags ["#free-range" "#eatery"], :service "twitter", :username "kyle"} "Pacific Heights Free-Range Eatery is a wonderful and modern place to take visiting friends and relatives Friday nights." {:large "http://cloudfront.net/cedd4221-dbdb-46c3-95a9-935cce6b3fe5/large.jpg", :medium "http://cloudfront.net/cedd4221-dbdb-46c3-95a9-935cce6b3fe5/med.jpg", :small "http://cloudfront.net/cedd4221-dbdb-46c3-95a9-935cce6b3fe5/small.jpg"} {:phone "415-901-6541", :name "Pacific Heights Free-Range Eatery", :categories ["Free-Range" "Eatery"], :id "88b361c8-ce69-4b2e-b0f2-9deedd574af6"}]] (mt/rows (mt/run-mbql-query tips {:filter [:and [:= $tips.source.service "twitter"] [:= $tips.source.username "kyle"]] :order-by [[:asc $tips.venue.name]]})))))))) (deftest aggregation-test (mt/test-drivers (mt/normal-drivers-with-feature :nested-fields) (testing "Nested Field in AGGREGATION" (mt/dataset geographical-tips (testing ":distinct aggregation" ;; Let's see how many *distinct* venue names are mentioned (is (= [99] (mt/first-row (mt/run-mbql-query tips {:aggregation [[:distinct $tips.venue.name]]}))))) (testing ":count aggregation" ;; Now let's just get the regular count (is (= [500] (mt/first-row (mt/run-mbql-query tips {:aggregation [[:count $tips.venue.name]]}))))))))) (deftest breakout-test (mt/test-drivers (mt/normal-drivers-with-feature :nested-fields) (testing "Nested Field in BREAKOUT" ;; Let's see how many tips we have by source.service (mt/dataset geographical-tips (is (= [["facebook" 107] ["flare" 105] ["foursquare" 100] ["twitter" 98] ["yelp" 90]] (mt/formatted-rows [str int] (mt/run-mbql-query tips {:aggregation [[:count]] :breakout [$tips.source.service]})))) (is (= [[nil 297] ["amy" 20] ["biggie" 11] ["<NAME>" 20]] (mt/formatted-rows [str int] (mt/run-mbql-query tips {:aggregation [[:count]] :breakout [$tips.source.username] :limit 4})))))))) (deftest fields-test (mt/test-drivers (mt/normal-drivers-with-feature :nested-fields) (testing "Nested Field in FIELDS" (mt/dataset geographical-tips ;; Return the first 10 tips with just tip.venue.name (is (= [["Lucky's Gluten-Free Café"] ["Jo<NAME>'s Homestyle Eatery"] ["Lower Pac Heights Cage-Free Coffee House"] ["Oakland European Liquor Store"] ["Tenderloin Gormet Restaurant"] ["Marina Modern Sushi"] ["Sunset Homestyle Grill"] ["<NAME>'s Low-Carb Grill"] ["Mission Homestyle Churros"] ["<NAME>er's Pizza Liquor Store"]] (mt/rows (mt/run-mbql-query tips {:fields [$tips.venue.name] :order-by [[:asc $id]] :limit 10})))))))) (deftest order-by-aggregation-test (mt/test-drivers (mt/normal-drivers-with-feature :nested-fields) (testing "Nested Field w/ ordering by aggregation" (mt/dataset geographical-tips (is (= [["<NAME>" 4] ["<NAME>" 5] ["<NAME>" 5] ["<NAME>" 6] ["<NAME>" 7] ["lucky_pigeon" 7] ["<NAME>" 8] ["<NAME>" 8] ["<NAME>" 9] ["<NAME>gie" 9] ["<NAME>" 9] ["cam_saul" 10] ["rasta_toucan" 13] [nil 400]] (mt/formatted-rows [identity int] (mt/run-mbql-query tips {:aggregation [[:count]] :breakout [$tips.source.mayor] :order-by [[:asc [:aggregation 0]]]}))))))))
true
(ns metabase.query-processor-test.nested-field-test "Tests for nested field access." (:require [clojure.test :refer :all] [metabase.test :as mt])) (deftest filter-test (mt/test-drivers (mt/normal-drivers-with-feature :nested-fields) (testing "Nested Field in FILTER" (mt/dataset geographical-tips ;; Get the first 10 tips where tip.venue.name == "Kyle's Low-Carb Grill" (is (= [[8 "Kyle's Low-Carb Grill"] [67 "Kyle's Low-Carb Grill"] [80 "Kyle's Low-Carb Grill"] [83 "Kyle's Low-Carb Grill"] [295 "Kyle's Low-Carb Grill"] [342 "KPI:NAME:<NAME>END_PI's Low-Carb Grill"] [417 "Kyle's Low-Carb Grill"] [426 "Kyle's Low-Carb Grill"] [470 "Kyle's Low-Carb Grill"]] (mapv (fn [[id _ _ _ {venue-name :name}]] [id venue-name]) (mt/rows (mt/run-mbql-query tips {:filter [:= $tips.venue.name "Kyle's Low-Carb Grill"] :order-by [[:asc $id]] :limit 10}))))))))) (deftest order-by-test (mt/test-drivers (mt/normal-drivers-with-feature :nested-fields) (testing "Nested Field in ORDER-BY" (mt/dataset geographical-tips ;; Let's get all the tips PI:NAME:<NAME>END_PIyle posted on Twitter sorted by tip.venue.name (is (= [[446 {:mentions ["@cams_mexican_gastro_pub"], :tags ["#mexican" "#gastro" "#pub"], :service "twitter", :username "kyle"} "Cam's Mexican Gastro Pub is a historical and underappreciated place to conduct a business meeting with friends." {:large "http://cloudfront.net/6e3a5256-275f-4056-b61a-25990b4bb484/large.jpg", :medium "http://cloudfront.net/6e3a5256-275f-4056-b61a-25990b4bb484/med.jpg", :small "http://cloudfront.net/6e3a5256-275f-4056-b61a-25990b4bb484/small.jpg"} {:phone "415-320-9123", :name "Cam's Mexican Gastro Pub", :categories ["Mexican" "Gastro Pub"], :id "bb958ac5-758e-4f42-b984-6b0e13f25194"}] [230 {:mentions ["@haight_european_grill"], :tags ["#european" "#grill"], :service "twitter", :username "kyle"} "Haight European Grill is a horrible and amazing place to have a birthday party during winter." {:large "http://cloudfront.net/1dcef7de-a1c4-405b-a9e1-69c92d686ef1/large.jpg", :medium "http://cloudfront.net/1dcef7de-a1c4-405b-a9e1-69c92d686ef1/med.jpg", :small "http://cloudfront.net/1dcef7de-a1c4-405b-a9e1-69c92d686ef1/small.jpg"} {:phone "415-191-2778", :name "Haight European Grill", :categories ["European" "Grill"], :id "7e6281f7-5b17-4056-ada0-85453247bc8f"}] [319 {:mentions ["@haight_soul_food_pop_up_food_stand"], :tags ["#soul" "#food" "#pop-up" "#food" "#stand"], :service "twitter", :username "kyle"} "Haight Soul Food Pop-Up Food Stand is a underground and modern place to have breakfast on a Tuesday afternoon." {:large "http://cloudfront.net/8f613909-550f-4d79-96f6-dc498ff65d1b/large.jpg", :medium "http://cloudfront.net/8f613909-550f-4d79-96f6-dc498ff65d1b/med.jpg", :small "http://cloudfront.net/8f613909-550f-4d79-96f6-dc498ff65d1b/small.jpg"} {:phone "415-741-8726", :name "Haight Soul Food Pop-Up Food Stand", :categories ["Soul Food" "Pop-Up Food Stand"], :id "9735184b-1299-410f-a98e-10d9c548af42"}] [224 {:mentions ["@pacific_heights_free_range_eatery"], :tags ["#free-range" "#eatery"], :service "twitter", :username "kyle"} "Pacific Heights Free-Range Eatery is a wonderful and modern place to take visiting friends and relatives Friday nights." {:large "http://cloudfront.net/cedd4221-dbdb-46c3-95a9-935cce6b3fe5/large.jpg", :medium "http://cloudfront.net/cedd4221-dbdb-46c3-95a9-935cce6b3fe5/med.jpg", :small "http://cloudfront.net/cedd4221-dbdb-46c3-95a9-935cce6b3fe5/small.jpg"} {:phone "415-901-6541", :name "Pacific Heights Free-Range Eatery", :categories ["Free-Range" "Eatery"], :id "88b361c8-ce69-4b2e-b0f2-9deedd574af6"}]] (mt/rows (mt/run-mbql-query tips {:filter [:and [:= $tips.source.service "twitter"] [:= $tips.source.username "kyle"]] :order-by [[:asc $tips.venue.name]]})))))))) (deftest aggregation-test (mt/test-drivers (mt/normal-drivers-with-feature :nested-fields) (testing "Nested Field in AGGREGATION" (mt/dataset geographical-tips (testing ":distinct aggregation" ;; Let's see how many *distinct* venue names are mentioned (is (= [99] (mt/first-row (mt/run-mbql-query tips {:aggregation [[:distinct $tips.venue.name]]}))))) (testing ":count aggregation" ;; Now let's just get the regular count (is (= [500] (mt/first-row (mt/run-mbql-query tips {:aggregation [[:count $tips.venue.name]]}))))))))) (deftest breakout-test (mt/test-drivers (mt/normal-drivers-with-feature :nested-fields) (testing "Nested Field in BREAKOUT" ;; Let's see how many tips we have by source.service (mt/dataset geographical-tips (is (= [["facebook" 107] ["flare" 105] ["foursquare" 100] ["twitter" 98] ["yelp" 90]] (mt/formatted-rows [str int] (mt/run-mbql-query tips {:aggregation [[:count]] :breakout [$tips.source.service]})))) (is (= [[nil 297] ["amy" 20] ["biggie" 11] ["PI:NAME:<NAME>END_PI" 20]] (mt/formatted-rows [str int] (mt/run-mbql-query tips {:aggregation [[:count]] :breakout [$tips.source.username] :limit 4})))))))) (deftest fields-test (mt/test-drivers (mt/normal-drivers-with-feature :nested-fields) (testing "Nested Field in FIELDS" (mt/dataset geographical-tips ;; Return the first 10 tips with just tip.venue.name (is (= [["Lucky's Gluten-Free Café"] ["JoPI:NAME:<NAME>END_PI's Homestyle Eatery"] ["Lower Pac Heights Cage-Free Coffee House"] ["Oakland European Liquor Store"] ["Tenderloin Gormet Restaurant"] ["Marina Modern Sushi"] ["Sunset Homestyle Grill"] ["PI:NAME:<NAME>END_PI's Low-Carb Grill"] ["Mission Homestyle Churros"] ["PI:NAME:<NAME>END_PIer's Pizza Liquor Store"]] (mt/rows (mt/run-mbql-query tips {:fields [$tips.venue.name] :order-by [[:asc $id]] :limit 10})))))))) (deftest order-by-aggregation-test (mt/test-drivers (mt/normal-drivers-with-feature :nested-fields) (testing "Nested Field w/ ordering by aggregation" (mt/dataset geographical-tips (is (= [["PI:NAME:<NAME>END_PI" 4] ["PI:NAME:<NAME>END_PI" 5] ["PI:NAME:<NAME>END_PI" 5] ["PI:NAME:<NAME>END_PI" 6] ["PI:NAME:<NAME>END_PI" 7] ["lucky_pigeon" 7] ["PI:NAME:<NAME>END_PI" 8] ["PI:NAME:<NAME>END_PI" 8] ["PI:NAME:<NAME>END_PI" 9] ["PI:NAME:<NAME>END_PIgie" 9] ["PI:NAME:<NAME>END_PI" 9] ["cam_saul" 10] ["rasta_toucan" 13] [nil 400]] (mt/formatted-rows [identity int] (mt/run-mbql-query tips {:aggregation [[:count]] :breakout [$tips.source.mayor] :order-by [[:asc [:aggregation 0]]]}))))))))
[ { "context": "remote \"simple-oauth2\"))\n\n(def flowdock-app-id\n \"79b2bd6aaca74a2b0d93bf933e338e97dc6336552876202f73e81fffcf1ba8f3\")\n\n(def secret\n \"0e1cf579e7b4efb5ea617301bf429e4", "end": 313, "score": 0.9879267811775208, "start": 249, "tag": "KEY", "value": "79b2bd6aaca74a2b0d93bf933e338e97dc6336552876202f73e81fffcf1ba8f3" }, { "context": "c6336552876202f73e81fffcf1ba8f3\")\n\n(def secret\n \"0e1cf579e7b4efb5ea617301bf429e4b070a8296637f25cfc408b730a32b1ebe\")\n\n(def flowdock-oauth\n {\n :clientID \"79b2bd6a", "end": 396, "score": 0.9997101426124573, "start": 332, "tag": "KEY", "value": "0e1cf579e7b4efb5ea617301bf429e4b070a8296637f25cfc408b730a32b1ebe" }, { "context": "a32b1ebe\")\n\n(def flowdock-oauth\n {\n :clientID \"79b2bd6aaca74a2b0d93bf933e338e97dc6336552876202f73e81fffcf1ba8f3\"\n :clientSecret \"0e1cf579e7b4efb5ea617301bf429e", "end": 502, "score": 0.9994003772735596, "start": 438, "tag": "KEY", "value": "79b2bd6aaca74a2b0d93bf933e338e97dc6336552876202f73e81fffcf1ba8f3" }, { "context": "6336552876202f73e81fffcf1ba8f3\"\n :clientSecret \"0e1cf579e7b4efb5ea617301bf429e4b070a8296637f25cfc408b730a32b1ebe\"\n :site \"https://api.flowdock.com/\"\n :tokenPa", "end": 586, "score": 0.9997231960296631, "start": 522, "tag": "KEY", "value": "0e1cf579e7b4efb5ea617301bf429e4b070a8296637f25cfc408b730a32b1ebe" } ]
data/train/clojure/00b69b751cde3a2bf5dc84b8bca375ce79da5521flowdock_api.cljs
harshp8l/deep-learning-lang-detection
84
(ns flowdock_api (:require [webfunctions :as wf])) (enable-console-print!) (defonce remote (js/require "remote")) (defonce request (.require remote "request")) (defonce client-oauth2 (.require remote "simple-oauth2")) (def flowdock-app-id "79b2bd6aaca74a2b0d93bf933e338e97dc6336552876202f73e81fffcf1ba8f3") (def secret "0e1cf579e7b4efb5ea617301bf429e4b070a8296637f25cfc408b730a32b1ebe") (def flowdock-oauth { :clientID "79b2bd6aaca74a2b0d93bf933e338e97dc6336552876202f73e81fffcf1ba8f3" :clientSecret "0e1cf579e7b4efb5ea617301bf429e4b070a8296637f25cfc408b730a32b1ebe" :site "https://api.flowdock.com/" :tokenPath "oauth/authorize" :authorizationPath "oauth/token" :redirect_uri (wf/fullroute "/auth") :scope ["flow","private","manage","profile"] :state "MyTotallyUnguessableString" }) (defn opts [m keys] (clj->js (select-keys m keys))) (defn oauth2 [auth-map] (let [client-opts (opts auth-map [:clientID :clientSecret :site :tokenPath]) auth-opts (opts auth-map [:redirect_uri :scope :state]) client (client-oauth2. client-opts)] (-> auth-map (assoc :client client) (assoc :authorizationUri (.authorizeURL (.-authCode client) auth-opts))))) (defn flowauth [] (oauth2 flowdock-oauth)) (defn code-url [oauth] (:authorizationUri oauth)) (defn create-token [oauth callback result] (let [token (-> oauth :client .-accessToken (.create result))] (println token) (callback token))) (defn get-token [oauth code callback] (let [authCode (.-authCode (:client oauth)) authCodeOpts (clj->js {:code code})] (.getToken authCode authCodeOpts (partial create-token oauth callback))))
5926
(ns flowdock_api (:require [webfunctions :as wf])) (enable-console-print!) (defonce remote (js/require "remote")) (defonce request (.require remote "request")) (defonce client-oauth2 (.require remote "simple-oauth2")) (def flowdock-app-id "<KEY>") (def secret "<KEY>") (def flowdock-oauth { :clientID "<KEY>" :clientSecret "<KEY>" :site "https://api.flowdock.com/" :tokenPath "oauth/authorize" :authorizationPath "oauth/token" :redirect_uri (wf/fullroute "/auth") :scope ["flow","private","manage","profile"] :state "MyTotallyUnguessableString" }) (defn opts [m keys] (clj->js (select-keys m keys))) (defn oauth2 [auth-map] (let [client-opts (opts auth-map [:clientID :clientSecret :site :tokenPath]) auth-opts (opts auth-map [:redirect_uri :scope :state]) client (client-oauth2. client-opts)] (-> auth-map (assoc :client client) (assoc :authorizationUri (.authorizeURL (.-authCode client) auth-opts))))) (defn flowauth [] (oauth2 flowdock-oauth)) (defn code-url [oauth] (:authorizationUri oauth)) (defn create-token [oauth callback result] (let [token (-> oauth :client .-accessToken (.create result))] (println token) (callback token))) (defn get-token [oauth code callback] (let [authCode (.-authCode (:client oauth)) authCodeOpts (clj->js {:code code})] (.getToken authCode authCodeOpts (partial create-token oauth callback))))
true
(ns flowdock_api (:require [webfunctions :as wf])) (enable-console-print!) (defonce remote (js/require "remote")) (defonce request (.require remote "request")) (defonce client-oauth2 (.require remote "simple-oauth2")) (def flowdock-app-id "PI:KEY:<KEY>END_PI") (def secret "PI:KEY:<KEY>END_PI") (def flowdock-oauth { :clientID "PI:KEY:<KEY>END_PI" :clientSecret "PI:KEY:<KEY>END_PI" :site "https://api.flowdock.com/" :tokenPath "oauth/authorize" :authorizationPath "oauth/token" :redirect_uri (wf/fullroute "/auth") :scope ["flow","private","manage","profile"] :state "MyTotallyUnguessableString" }) (defn opts [m keys] (clj->js (select-keys m keys))) (defn oauth2 [auth-map] (let [client-opts (opts auth-map [:clientID :clientSecret :site :tokenPath]) auth-opts (opts auth-map [:redirect_uri :scope :state]) client (client-oauth2. client-opts)] (-> auth-map (assoc :client client) (assoc :authorizationUri (.authorizeURL (.-authCode client) auth-opts))))) (defn flowauth [] (oauth2 flowdock-oauth)) (defn code-url [oauth] (:authorizationUri oauth)) (defn create-token [oauth callback result] (let [token (-> oauth :client .-accessToken (.create result))] (println token) (callback token))) (defn get-token [oauth code callback] (let [authCode (.-authCode (:client oauth)) authCodeOpts (clj->js {:code code})] (.getToken authCode authCodeOpts (partial create-token oauth callback))))
[ { "context": "; Copyright 2017 Frederic Merizen\n;\n; Licensed under the Apache License, Version 2.", "end": 33, "score": 0.9998564720153809, "start": 17, "tag": "NAME", "value": "Frederic Merizen" } ]
src/plumula/diff/util.clj
plumula/diff
1
; Copyright 2017 Frederic Merizen ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns plumula.diff.util) (defmacro set-field! "set! the `field` of the `object` to `value`, and return `object`." [object field value] `(let [object# ~object] (set! (. object# ~field) ~value) object#))
120892
; Copyright 2017 <NAME> ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns plumula.diff.util) (defmacro set-field! "set! the `field` of the `object` to `value`, and return `object`." [object field value] `(let [object# ~object] (set! (. object# ~field) ~value) object#))
true
; Copyright 2017 PI:NAME:<NAME>END_PI ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns plumula.diff.util) (defmacro set-field! "set! the `field` of the `object` to `value`, and return `object`." [object field value] `(let [object# ~object] (set! (. object# ~field) ~value) object#))
[ { "context": " (grant :all-users :read)\n (grant {:email \\\"foo@example.com\\\"} :full-control)\n (revoke {:email \\\"bar@exa", "end": 25753, "score": 0.9986171722412109, "start": 25738, "tag": "EMAIL", "value": "foo@example.com" }, { "context": "ple.com\\\"} :full-control)\n (revoke {:email \\\"bar@example.com\\\"} :write))\"\n [cred ^String bucket & funcs]\n (l", "end": 25811, "score": 0.997307300567627, "start": 25796, "tag": "EMAIL", "value": "bar@example.com" } ]
s3/src/s3/s3.clj
jrosti/ontrail
1
(ns s3.s3 "Functions to access the Amazon S3 storage service. Each function takes a map of credentials as its first argument. The credentials map should contain an :access-key key and a :secret-key key, optionally an :endpoint key to denote an AWS endpoint and optionally a :proxy key to define a HTTP proxy to go through. The :proxy key must contain keys for :host and :port, and may contain keys for :user, :password, :domain and :workstation." (:require [clojure.string :as str] [clj-time.core :as t] [clj-time.coerce :as coerce] [clojure.walk :as walk]) (:import com.amazonaws.auth.BasicAWSCredentials com.amazonaws.auth.BasicSessionCredentials com.amazonaws.services.s3.AmazonS3Client com.amazonaws.AmazonServiceException com.amazonaws.ClientConfiguration com.amazonaws.HttpMethod com.amazonaws.services.s3.model.AccessControlList com.amazonaws.services.s3.model.Bucket com.amazonaws.services.s3.model.Grant com.amazonaws.services.s3.model.CanonicalGrantee com.amazonaws.services.s3.model.CopyObjectResult com.amazonaws.services.s3.model.EmailAddressGrantee com.amazonaws.services.s3.model.GetObjectRequest com.amazonaws.services.s3.model.GetObjectMetadataRequest com.amazonaws.services.s3.model.Grant com.amazonaws.services.s3.model.GroupGrantee com.amazonaws.services.s3.model.ListObjectsRequest com.amazonaws.services.s3.model.ListVersionsRequest com.amazonaws.services.s3.model.Owner com.amazonaws.services.s3.model.ObjectMetadata com.amazonaws.services.s3.model.ObjectListing com.amazonaws.services.s3.model.Permission com.amazonaws.services.s3.model.PutObjectRequest com.amazonaws.services.s3.model.S3Object com.amazonaws.services.s3.model.S3ObjectSummary com.amazonaws.services.s3.model.S3VersionSummary com.amazonaws.services.s3.model.VersionListing com.amazonaws.services.s3.model.InitiateMultipartUploadRequest com.amazonaws.services.s3.model.AbortMultipartUploadRequest com.amazonaws.services.s3.model.CompleteMultipartUploadRequest com.amazonaws.services.s3.model.UploadPartRequest java.util.concurrent.Executors java.io.ByteArrayInputStream java.io.File java.io.InputStream java.nio.charset.Charset)) (defn- s3-client* [cred] (let [client-configuration (ClientConfiguration.)] (when-let [conn-timeout (:conn-timeout cred)] (.setConnectionTimeout client-configuration conn-timeout)) (when-let [socket-timeout (:socket-timeout cred)] (.setSocketTimeout client-configuration socket-timeout)) (when-let [max-retries (:max-retries cred)] (.setMaxErrorRetry client-configuration max-retries)) (when-let [max-conns (:max-conns cred)] (.setMaxConnections client-configuration max-conns)) (when-let [proxy-host (get-in cred [:proxy :host])] (.setProxyHost client-configuration proxy-host)) (when-let [proxy-port (get-in cred [:proxy :port])] (.setProxyPort client-configuration proxy-port)) (when-let [proxy-user (get-in cred [:proxy :user])] (.setProxyUsername client-configuration proxy-user)) (when-let [proxy-pass (get-in cred [:proxy :password])] (.setProxyPassword client-configuration proxy-pass)) (when-let [proxy-domain (get-in cred [:proxy :domain])] (.setProxyDomain client-configuration proxy-domain)) (when-let [proxy-workstation (get-in cred [:proxy :workstation])] (.setProxyWorkstation client-configuration proxy-workstation)) (let [aws-creds (if (:token cred) (BasicSessionCredentials. (:access-key cred) (:secret-key cred) (:token cred)) (BasicAWSCredentials. (:access-key cred) (:secret-key cred))) client (AmazonS3Client. aws-creds client-configuration)] (when-let [endpoint (:endpoint cred)] (.setEndpoint client endpoint)) client))) (def ^{:private true :tag AmazonS3Client} s3-client (memoize s3-client*)) (defprotocol ^{:no-doc true} Mappable "Convert a value into a Clojure map." (^{:no-doc true} to-map [x] "Return a map of the value.")) (extend-protocol Mappable Bucket (to-map [bucket] {:name (.getName bucket) :creation-date (.getCreationDate bucket) :owner (to-map (.getOwner bucket))}) Owner (to-map [owner] {:id (.getId owner) :display-name (.getDisplayName owner)}) nil (to-map [_] nil)) (defn bucket-exists? "Returns true if the supplied bucket name already exists in S3." [cred name] (.doesBucketExist (s3-client cred) name)) (defn create-bucket "Create a new S3 bucket with the supplied name." [cred ^String name] (to-map (.createBucket (s3-client cred) name))) (defn delete-bucket "Delete the S3 bucket with the supplied name." [cred ^String name] (.deleteBucket (s3-client cred) name)) (defn list-buckets "List all the S3 buckets for the supplied credentials. The buckets will be returned as a seq of maps with the following keys: :name - the bucket name :creation-date - the date when the bucket was created :owner - the owner of the bucket" [cred] (map to-map (.listBuckets (s3-client cred)))) (defprotocol ^{:no-doc true} ToPutRequest "A protocol for constructing a map that represents an S3 put request." (^{:no-doc true} put-request [x] "Convert a value into a put request.")) (extend-protocol ToPutRequest InputStream (put-request [is] {:input-stream is}) File (put-request [f] {:file f}) String (put-request [s] (let [bytes (.getBytes s)] {:input-stream (ByteArrayInputStream. bytes) :content-length (count bytes) :content-type (str "text/plain; charset=" (.name (Charset/defaultCharset)))}))) (defmacro set-attr "Set an attribute on an object if not nil." {:private true} [object setter value] `(if-let [v# ~value] (~setter ~object v#))) (defn- maybe-int [x] (if x (int x))) (defn- map->ObjectMetadata "Convert a map of object metadata into a ObjectMetadata instance." [metadata] (doto (ObjectMetadata.) (set-attr .setCacheControl (:cache-control metadata)) (set-attr .setContentDisposition (:content-disposition metadata)) (set-attr .setContentEncoding (:content-encoding metadata)) (set-attr .setContentLength (:content-length metadata)) (set-attr .setContentMD5 (:content-md5 metadata)) (set-attr .setContentType (:content-type metadata)) (set-attr .setServerSideEncryption (:server-side-encryption metadata)) (set-attr .setUserMetadata (walk/stringify-keys (dissoc metadata :cache-control :content-disposition :content-encoding :content-length :content-md5 :content-type :server-side-encryption))))) (defn- ^PutObjectRequest ->PutObjectRequest "Create a PutObjectRequest instance from a bucket name, key and put request map." [^String bucket ^String key request] (cond (:file request) (let [put-obj-req (PutObjectRequest. bucket key ^java.io.File (:file request))] (.setMetadata put-obj-req (map->ObjectMetadata (dissoc request :file))) put-obj-req) (:input-stream request) (PutObjectRequest. bucket key (:input-stream request) (map->ObjectMetadata (dissoc request :input-stream))))) (declare create-acl) ; used by put-object (defn put-object "Put a value into an S3 bucket at the specified key. The value can be a String, InputStream or File (or anything that implements the ToPutRequest protocol). An optional map of metadata may also be supplied that can include any of the following keys: :cache-control - the cache-control header (see RFC 2616) :content-disposition - how the content should be downloaded by browsers :content-encoding - the encoding of the content (e.g. gzip) :content-length - the length of the content in bytes :content-md5 - the MD5 sum of the content :content-type - the mime type of the content :server-side-encryption - set to AES256 if SSE is required An optional list of grant functions can be provided after metadata. These functions will be applied to a clear ACL and the result will be the ACL for the newly created object." [cred bucket key value & [metadata & permissions]] (let [req (->> (merge (put-request value) metadata) (->PutObjectRequest bucket key))] (when permissions (.setAccessControlList req (create-acl permissions))) (.putObject (s3-client cred) req))) (defn- initiate-multipart-upload [cred bucket key] (.getUploadId (.initiateMultipartUpload (s3-client cred) (InitiateMultipartUploadRequest. bucket key)))) (defn- abort-multipart-upload [{cred :cred bucket :bucket key :key upload-id :upload-id}] (.abortMultipartUpload (s3-client cred) (AbortMultipartUploadRequest. bucket key upload-id))) (defn- complete-multipart-upload [{cred :cred bucket :bucket key :key upload-id :upload-id e-tags :e-tags}] (.completeMultipartUpload (s3-client cred) (CompleteMultipartUploadRequest. bucket key upload-id e-tags))) (defn- upload-part [{cred :cred bucket :bucket key :key upload-id :upload-id part-size :part-size offset :offset ^java.io.File file :file}] (.getPartETag (.uploadPart (s3-client cred) (doto (UploadPartRequest.) (.setBucketName bucket) (.setKey key) (.setUploadId upload-id) (.setPartNumber (+ 1 (/ offset part-size))) (.setFileOffset offset) (.setPartSize ^long (min part-size (- (.length file) offset))) (.setFile file))))) (defn put-multipart-object "Do a multipart upload of a file into a S3 bucket at the specified key. The value must be a java.io.File object. The entire file is uploaded or not at all. If an exception happens at any time the upload is aborted and the exception is rethrown. The size of the parts and the number of threads uploading the parts can be configured in the last argument as a map with the following keys: :part-size - the size in bytes of each part of the file. Must be 5mb or larger. Defaults to 5mb :threads - the number of threads that will upload parts concurrently. Defaults to 16." [cred bucket key ^java.io.File file & [{:keys [part-size threads] :or {part-size (* 5 1024 1024) threads 16}}]] (let [upload-id (initiate-multipart-upload cred bucket key) upload {:upload-id upload-id :cred cred :bucket bucket :key key :file file} pool (Executors/newFixedThreadPool threads) offsets (range 0 (.length file) part-size) tasks (map #(fn [] (upload-part (assoc upload :offset % :part-size part-size))) offsets)] (try (complete-multipart-upload (assoc upload :e-tags (map #(.get ^java.util.concurrent.Future %) (.invokeAll pool tasks)))) (catch Exception ex (abort-multipart-upload upload) (.shutdown pool) (throw ex)) (finally (.shutdown pool))))) (extend-protocol Mappable S3Object (to-map [object] {:content (.getObjectContent object) :metadata (to-map (.getObjectMetadata object)) :bucket (.getBucketName object) :key (.getKey object)}) ObjectMetadata (to-map [metadata] {:cache-control (.getCacheControl metadata) :content-disposition (.getContentDisposition metadata) :content-encoding (.getContentEncoding metadata) :content-length (.getContentLength metadata) :content-md5 (.getContentMD5 metadata) :content-type (.getContentType metadata) :etag (.getETag metadata) :last-modified (.getLastModified metadata) :server-side-encryption (.getServerSideEncryption metadata) :user (walk/keywordize-keys (into {} (.getUserMetadata metadata))) :version-id (.getVersionId metadata)}) ObjectListing (to-map [listing] {:bucket (.getBucketName listing) :objects (map to-map (.getObjectSummaries listing)) :prefix (.getPrefix listing) :common-prefixes (seq (.getCommonPrefixes listing)) :truncated? (.isTruncated listing) :max-keys (.getMaxKeys listing) :marker (.getMarker listing) :next-marker (.getNextMarker listing)}) S3ObjectSummary (to-map [summary] {:metadata {:content-length (.getSize summary) :etag (.getETag summary) :last-modified (.getLastModified summary)} :bucket (.getBucketName summary) :key (.getKey summary)}) S3VersionSummary (to-map [summary] {:metadata {:content-length (.getSize summary) :etag (.getETag summary) :last-modified (.getLastModified summary)} :version-id (.getVersionId summary) :latest? (.isLatest summary) :delete-marker? (.isDeleteMarker summary) :bucket (.getBucketName summary) :key (.getKey summary)}) VersionListing (to-map [listing] {:bucket (.getBucketName listing) :versions (map to-map (.getVersionSummaries listing)) :prefix (.getPrefix listing) :common-prefixes (seq (.getCommonPrefixes listing)) :delimiter (.getDelimiter listing) :truncated? (.isTruncated listing) :max-results (maybe-int (.getMaxKeys listing)) ; AWS API is inconsistent, should be .getMaxResults :key-marker (.getKeyMarker listing) :next-key-marker (.getNextKeyMarker listing) :next-version-id-marker (.getNextVersionIdMarker listing) :version-id-marker (.getVersionIdMarker listing)}) CopyObjectResult (to-map [result] {:etag (.getETag result) :expiration-time (.getExpirationTime result) :expiration-time-rule-id (.getExpirationTimeRuleId result) :last-modified-date (.getLastModifiedDate result) :server-side-encryption (.getServerSideEncryption result)})) (defn get-object "Get an object from an S3 bucket. The object is returned as a map with the following keys: :content - an InputStream to the content :metadata - a map of the object's metadata :bucket - the name of the bucket :key - the object's key Be extremely careful when using this method; the :content value in the returned map contains a direct stream of data from the HTTP connection. The underlying HTTP connection cannot be closed until the user finishes reading the data and closes the stream. Therefore: * Use the data from the :content input stream as soon as possible * Close the :content input stream as soon as possible If these rules are not followed, the client can run out of resources by allocating too many open, but unused, HTTP connections." ([cred ^String bucket ^String key] (to-map (.getObject (s3-client cred) bucket key))) ([cred ^String bucket ^String key ^String version-id] (to-map (.getObject (s3-client cred) (GetObjectRequest. bucket key version-id))))) (defn- map->GetObjectMetadataRequest "Create a ListObjectsRequest instance from a map of values." [request] (GetObjectMetadataRequest. (:bucket request) (:key request) (:version-id request))) (defn get-object-metadata "Get an object's metadata from a bucket. A optional map of options may be supplied. Available options are: :version-id - the version of the object The metadata is a map with the following keys: :cache-control - the CacheControl HTTP header :content-disposition - the ContentDisposition HTTP header :content-encoding - the character encoding of the content :content-length - the length of the content in bytes :content-md5 - the MD5 hash of the content :content-type - the mime-type of the content :etag - the HTTP ETag header :last-modified - the last modified date :server-side-encryption - the server-side encryption algorithm" [cred bucket key & [options]] (to-map (.getObjectMetadata (s3-client cred) (map->GetObjectMetadataRequest (merge {:bucket bucket :key key} options))))) (defn- map->ListObjectsRequest "Create a ListObjectsRequest instance from a map of values." ^ListObjectsRequest [request] (doto (ListObjectsRequest.) (set-attr .setBucketName (:bucket request)) (set-attr .setDelimiter (:delimiter request)) (set-attr .setMarker (:marker request)) (set-attr .setMaxKeys (maybe-int (:max-keys request))) (set-attr .setPrefix (:prefix request)))) (defn- http-method [method] (-> method name str/upper-case HttpMethod/valueOf)) (defn generate-presigned-url "Return a presigned URL for an S3 object. Accepts the following options: :expires - the date at which the URL will expire (defaults to 1 day from now) :http-method - the HTTP method for the URL (defaults to :get)" [cred bucket key & [options]] (.toString (.generatePresignedUrl (s3-client cred) bucket key (coerce/to-date (:expires options (-> 1 t/days t/from-now))) (http-method (:http-method options :get))))) (defn list-objects "List the objects in an S3 bucket. A optional map of options may be supplied. Available options are: :delimiter - read only keys up to the next delimiter (such as a '/') :marker - read objects after this key :max-keys - read only this many objects :prefix - read only objects with this prefix The object listing will be returned as a map containing the following keys: :bucket - the name of the bucket :prefix - the supplied prefix (or nil if none supplied) :objects - a list of objects :common-prefixes - the common prefixes of keys omitted by the delimiter :max-keys - the maximum number of objects to be returned :truncated? - true if the list of objects was truncated :marker - the marker of the listing :next-marker - the next marker of the listing" [cred bucket & [options]] (to-map (.listObjects (s3-client cred) (map->ListObjectsRequest (merge {:bucket bucket} options))))) (defn delete-object "Delete an object from an S3 bucket." [cred bucket key] (.deleteObject (s3-client cred) bucket key)) (defn object-exists? "Returns true if an object exists in the supplied bucket and key." [cred bucket key] (try (get-object-metadata cred bucket key) true (catch AmazonServiceException e (if (= 404 (.getStatusCode e)) false (throw e))))) (defn copy-object "Copy an existing S3 object to another key. Returns a map containing the data returned from S3" ([cred bucket src-key dest-key] (copy-object cred bucket src-key bucket dest-key)) ([cred src-bucket src-key dest-bucket dest-key] (to-map (.copyObject (s3-client cred) src-bucket src-key dest-bucket dest-key)))) (defn- map->ListVersionsRequest "Create a ListVersionsRequest instance from a map of values." [request] (doto (ListVersionsRequest.) (set-attr .setBucketName (:bucket request)) (set-attr .setDelimiter (:delimiter request)) (set-attr .setKeyMarker (:key-marker request)) (set-attr .setMaxResults (maybe-int (:max-results request))) (set-attr .setPrefix (:prefix request)) (set-attr .setVersionIdMarker (:version-id-marker request)))) (defn list-versions "List the versions in an S3 bucket. A optional map of options may be supplied. Available options are: :delimiter - the delimiter used in prefix (such as a '/') :key-marker - read versions from the sorted list of all versions starting at this marker. :max-results - read only this many versions :prefix - read only versions with keys having this prefix :version-id-marker - read objects after this version id The version listing will be returned as a map containing the following versions: :bucket - the name of the bucket :prefix - the supplied prefix (or nil if none supplied) :versions - a sorted list of versions, newest first, each version has: :version-id - the unique version id :latest? - is this the latest version for that key? :delete-marker? - is this a delete-marker? :common-prefixes - the common prefixes of keys omitted by the delimiter :max-results - the maximum number of results to be returned :truncated? - true if the results were truncated :key-marker - the key marker of the listing :next-version-id-marker - the version ID marker to use in the next listVersions request in order to obtain the next page of results. :version-id-marker - the version id marker of the listing" [cred bucket & [options]] (to-map (.listVersions (s3-client cred) (map->ListVersionsRequest (merge {:bucket bucket} options))))) (defn delete-version "Deletes a specific version of the specified object in the specified bucket." [cred bucket key version-id] (.deleteVersion (s3-client cred) bucket key version-id)) (defprotocol ^{:no-doc true} ToClojure "Convert an object into an idiomatic Clojure value." (^{:no-doc true} to-clojure [x] "Turn the object into a Clojure value.")) (extend-protocol ToClojure CanonicalGrantee (to-clojure [grantee] {:id (.getIdentifier grantee) :display-name (.getDisplayName grantee)}) EmailAddressGrantee (to-clojure [grantee] {:email (.getIdentifier grantee)}) GroupGrantee (to-clojure [grantee] (condp = grantee GroupGrantee/AllUsers :all-users GroupGrantee/AuthenticatedUsers :authenticated-users GroupGrantee/LogDelivery :log-delivery)) Permission (to-clojure [permission] (condp = permission Permission/FullControl :full-control Permission/Read :read Permission/ReadAcp :read-acp Permission/Write :write Permission/WriteAcp :write-acp))) (extend-protocol Mappable Grant (to-map [grant] {:grantee (to-clojure (.getGrantee grant)) :permission (to-clojure (.getPermission grant))}) AccessControlList (to-map [acl] {:grants (set (map to-map (.getGrants acl))) :owner (to-map (.getOwner acl))})) (defn get-bucket-acl "Get the access control list (ACL) for the supplied bucket. The ACL is a map containing two keys: :owner - the owner of the ACL :grants - a set of access permissions granted The grants themselves are maps with keys: :grantee - the individual or group being granted access :permission - the type of permission (:read, :write, :read-acp, :write-acp or :full-control)." [cred ^String bucket] (to-map (.getBucketAcl (s3-client cred) bucket))) (defn get-object-acl "Get the access control list (ACL) for the supplied object. See get-bucket-acl for a detailed description of the return value." [cred bucket key] (to-map (.getObjectAcl (s3-client cred) bucket key))) (defn- permission [perm] (case perm :full-control Permission/FullControl :read Permission/Read :read-acp Permission/ReadAcp :write Permission/Write :write-acp Permission/WriteAcp)) (defn- grantee [grantee] (cond (keyword? grantee) (case grantee :all-users GroupGrantee/AllUsers :authenticated-users GroupGrantee/AuthenticatedUsers :log-delivery GroupGrantee/LogDelivery) (:id grantee) (CanonicalGrantee. (:id grantee)) (:email grantee) (EmailAddressGrantee. (:email grantee)))) (defn- clear-acl [^AccessControlList acl] (doseq [grantee (->> (.getGrants acl) (map #(.getGrantee ^Grant %)) (set))] (.revokeAllPermissions acl grantee))) (defn- add-acl-grants [^AccessControlList acl grants] (doseq [g grants] (.grantPermission acl (grantee (:grantee g)) (permission (:permission g))))) (defn- update-acl [^AccessControlList acl funcs] (let [grants (:grants (to-map acl)) update (apply comp (reverse funcs))] (clear-acl acl) (add-acl-grants acl (update grants)))) (defn- create-acl [permissions] (doto (AccessControlList.) (update-acl permissions))) (defn update-bucket-acl "Update the access control list (ACL) for the named bucket using functions that update a set of grants (see get-bucket-acl). This function is often used with the grant and revoke functions, e.g. (update-bucket-acl cred bucket (grant :all-users :read) (grant {:email \"foo@example.com\"} :full-control) (revoke {:email \"bar@example.com\"} :write))" [cred ^String bucket & funcs] (let [acl (.getBucketAcl (s3-client cred) bucket)] (update-acl acl funcs) (.setBucketAcl (s3-client cred) bucket acl))) (defn update-object-acl "Updates the access control list (ACL) for the supplied object using functions that update a set of grants (see update-bucket-acl for more details)." [cred ^String bucket ^String key & funcs] (let [acl (.getObjectAcl (s3-client cred) bucket key)] (update-acl acl funcs) (.setObjectAcl (s3-client cred) bucket key acl))) (defn grant "Returns a function that adds a new grant map to a set of grants. See update-bucket-acl." [grantee permission] #(conj % {:grantee grantee :permission permission})) (defn revoke "Returns a function that removes a grant map from a set of grants. See update-bucket-acl." [grantee permission] #(disj % {:grantee grantee :permission permission}))
2555
(ns s3.s3 "Functions to access the Amazon S3 storage service. Each function takes a map of credentials as its first argument. The credentials map should contain an :access-key key and a :secret-key key, optionally an :endpoint key to denote an AWS endpoint and optionally a :proxy key to define a HTTP proxy to go through. The :proxy key must contain keys for :host and :port, and may contain keys for :user, :password, :domain and :workstation." (:require [clojure.string :as str] [clj-time.core :as t] [clj-time.coerce :as coerce] [clojure.walk :as walk]) (:import com.amazonaws.auth.BasicAWSCredentials com.amazonaws.auth.BasicSessionCredentials com.amazonaws.services.s3.AmazonS3Client com.amazonaws.AmazonServiceException com.amazonaws.ClientConfiguration com.amazonaws.HttpMethod com.amazonaws.services.s3.model.AccessControlList com.amazonaws.services.s3.model.Bucket com.amazonaws.services.s3.model.Grant com.amazonaws.services.s3.model.CanonicalGrantee com.amazonaws.services.s3.model.CopyObjectResult com.amazonaws.services.s3.model.EmailAddressGrantee com.amazonaws.services.s3.model.GetObjectRequest com.amazonaws.services.s3.model.GetObjectMetadataRequest com.amazonaws.services.s3.model.Grant com.amazonaws.services.s3.model.GroupGrantee com.amazonaws.services.s3.model.ListObjectsRequest com.amazonaws.services.s3.model.ListVersionsRequest com.amazonaws.services.s3.model.Owner com.amazonaws.services.s3.model.ObjectMetadata com.amazonaws.services.s3.model.ObjectListing com.amazonaws.services.s3.model.Permission com.amazonaws.services.s3.model.PutObjectRequest com.amazonaws.services.s3.model.S3Object com.amazonaws.services.s3.model.S3ObjectSummary com.amazonaws.services.s3.model.S3VersionSummary com.amazonaws.services.s3.model.VersionListing com.amazonaws.services.s3.model.InitiateMultipartUploadRequest com.amazonaws.services.s3.model.AbortMultipartUploadRequest com.amazonaws.services.s3.model.CompleteMultipartUploadRequest com.amazonaws.services.s3.model.UploadPartRequest java.util.concurrent.Executors java.io.ByteArrayInputStream java.io.File java.io.InputStream java.nio.charset.Charset)) (defn- s3-client* [cred] (let [client-configuration (ClientConfiguration.)] (when-let [conn-timeout (:conn-timeout cred)] (.setConnectionTimeout client-configuration conn-timeout)) (when-let [socket-timeout (:socket-timeout cred)] (.setSocketTimeout client-configuration socket-timeout)) (when-let [max-retries (:max-retries cred)] (.setMaxErrorRetry client-configuration max-retries)) (when-let [max-conns (:max-conns cred)] (.setMaxConnections client-configuration max-conns)) (when-let [proxy-host (get-in cred [:proxy :host])] (.setProxyHost client-configuration proxy-host)) (when-let [proxy-port (get-in cred [:proxy :port])] (.setProxyPort client-configuration proxy-port)) (when-let [proxy-user (get-in cred [:proxy :user])] (.setProxyUsername client-configuration proxy-user)) (when-let [proxy-pass (get-in cred [:proxy :password])] (.setProxyPassword client-configuration proxy-pass)) (when-let [proxy-domain (get-in cred [:proxy :domain])] (.setProxyDomain client-configuration proxy-domain)) (when-let [proxy-workstation (get-in cred [:proxy :workstation])] (.setProxyWorkstation client-configuration proxy-workstation)) (let [aws-creds (if (:token cred) (BasicSessionCredentials. (:access-key cred) (:secret-key cred) (:token cred)) (BasicAWSCredentials. (:access-key cred) (:secret-key cred))) client (AmazonS3Client. aws-creds client-configuration)] (when-let [endpoint (:endpoint cred)] (.setEndpoint client endpoint)) client))) (def ^{:private true :tag AmazonS3Client} s3-client (memoize s3-client*)) (defprotocol ^{:no-doc true} Mappable "Convert a value into a Clojure map." (^{:no-doc true} to-map [x] "Return a map of the value.")) (extend-protocol Mappable Bucket (to-map [bucket] {:name (.getName bucket) :creation-date (.getCreationDate bucket) :owner (to-map (.getOwner bucket))}) Owner (to-map [owner] {:id (.getId owner) :display-name (.getDisplayName owner)}) nil (to-map [_] nil)) (defn bucket-exists? "Returns true if the supplied bucket name already exists in S3." [cred name] (.doesBucketExist (s3-client cred) name)) (defn create-bucket "Create a new S3 bucket with the supplied name." [cred ^String name] (to-map (.createBucket (s3-client cred) name))) (defn delete-bucket "Delete the S3 bucket with the supplied name." [cred ^String name] (.deleteBucket (s3-client cred) name)) (defn list-buckets "List all the S3 buckets for the supplied credentials. The buckets will be returned as a seq of maps with the following keys: :name - the bucket name :creation-date - the date when the bucket was created :owner - the owner of the bucket" [cred] (map to-map (.listBuckets (s3-client cred)))) (defprotocol ^{:no-doc true} ToPutRequest "A protocol for constructing a map that represents an S3 put request." (^{:no-doc true} put-request [x] "Convert a value into a put request.")) (extend-protocol ToPutRequest InputStream (put-request [is] {:input-stream is}) File (put-request [f] {:file f}) String (put-request [s] (let [bytes (.getBytes s)] {:input-stream (ByteArrayInputStream. bytes) :content-length (count bytes) :content-type (str "text/plain; charset=" (.name (Charset/defaultCharset)))}))) (defmacro set-attr "Set an attribute on an object if not nil." {:private true} [object setter value] `(if-let [v# ~value] (~setter ~object v#))) (defn- maybe-int [x] (if x (int x))) (defn- map->ObjectMetadata "Convert a map of object metadata into a ObjectMetadata instance." [metadata] (doto (ObjectMetadata.) (set-attr .setCacheControl (:cache-control metadata)) (set-attr .setContentDisposition (:content-disposition metadata)) (set-attr .setContentEncoding (:content-encoding metadata)) (set-attr .setContentLength (:content-length metadata)) (set-attr .setContentMD5 (:content-md5 metadata)) (set-attr .setContentType (:content-type metadata)) (set-attr .setServerSideEncryption (:server-side-encryption metadata)) (set-attr .setUserMetadata (walk/stringify-keys (dissoc metadata :cache-control :content-disposition :content-encoding :content-length :content-md5 :content-type :server-side-encryption))))) (defn- ^PutObjectRequest ->PutObjectRequest "Create a PutObjectRequest instance from a bucket name, key and put request map." [^String bucket ^String key request] (cond (:file request) (let [put-obj-req (PutObjectRequest. bucket key ^java.io.File (:file request))] (.setMetadata put-obj-req (map->ObjectMetadata (dissoc request :file))) put-obj-req) (:input-stream request) (PutObjectRequest. bucket key (:input-stream request) (map->ObjectMetadata (dissoc request :input-stream))))) (declare create-acl) ; used by put-object (defn put-object "Put a value into an S3 bucket at the specified key. The value can be a String, InputStream or File (or anything that implements the ToPutRequest protocol). An optional map of metadata may also be supplied that can include any of the following keys: :cache-control - the cache-control header (see RFC 2616) :content-disposition - how the content should be downloaded by browsers :content-encoding - the encoding of the content (e.g. gzip) :content-length - the length of the content in bytes :content-md5 - the MD5 sum of the content :content-type - the mime type of the content :server-side-encryption - set to AES256 if SSE is required An optional list of grant functions can be provided after metadata. These functions will be applied to a clear ACL and the result will be the ACL for the newly created object." [cred bucket key value & [metadata & permissions]] (let [req (->> (merge (put-request value) metadata) (->PutObjectRequest bucket key))] (when permissions (.setAccessControlList req (create-acl permissions))) (.putObject (s3-client cred) req))) (defn- initiate-multipart-upload [cred bucket key] (.getUploadId (.initiateMultipartUpload (s3-client cred) (InitiateMultipartUploadRequest. bucket key)))) (defn- abort-multipart-upload [{cred :cred bucket :bucket key :key upload-id :upload-id}] (.abortMultipartUpload (s3-client cred) (AbortMultipartUploadRequest. bucket key upload-id))) (defn- complete-multipart-upload [{cred :cred bucket :bucket key :key upload-id :upload-id e-tags :e-tags}] (.completeMultipartUpload (s3-client cred) (CompleteMultipartUploadRequest. bucket key upload-id e-tags))) (defn- upload-part [{cred :cred bucket :bucket key :key upload-id :upload-id part-size :part-size offset :offset ^java.io.File file :file}] (.getPartETag (.uploadPart (s3-client cred) (doto (UploadPartRequest.) (.setBucketName bucket) (.setKey key) (.setUploadId upload-id) (.setPartNumber (+ 1 (/ offset part-size))) (.setFileOffset offset) (.setPartSize ^long (min part-size (- (.length file) offset))) (.setFile file))))) (defn put-multipart-object "Do a multipart upload of a file into a S3 bucket at the specified key. The value must be a java.io.File object. The entire file is uploaded or not at all. If an exception happens at any time the upload is aborted and the exception is rethrown. The size of the parts and the number of threads uploading the parts can be configured in the last argument as a map with the following keys: :part-size - the size in bytes of each part of the file. Must be 5mb or larger. Defaults to 5mb :threads - the number of threads that will upload parts concurrently. Defaults to 16." [cred bucket key ^java.io.File file & [{:keys [part-size threads] :or {part-size (* 5 1024 1024) threads 16}}]] (let [upload-id (initiate-multipart-upload cred bucket key) upload {:upload-id upload-id :cred cred :bucket bucket :key key :file file} pool (Executors/newFixedThreadPool threads) offsets (range 0 (.length file) part-size) tasks (map #(fn [] (upload-part (assoc upload :offset % :part-size part-size))) offsets)] (try (complete-multipart-upload (assoc upload :e-tags (map #(.get ^java.util.concurrent.Future %) (.invokeAll pool tasks)))) (catch Exception ex (abort-multipart-upload upload) (.shutdown pool) (throw ex)) (finally (.shutdown pool))))) (extend-protocol Mappable S3Object (to-map [object] {:content (.getObjectContent object) :metadata (to-map (.getObjectMetadata object)) :bucket (.getBucketName object) :key (.getKey object)}) ObjectMetadata (to-map [metadata] {:cache-control (.getCacheControl metadata) :content-disposition (.getContentDisposition metadata) :content-encoding (.getContentEncoding metadata) :content-length (.getContentLength metadata) :content-md5 (.getContentMD5 metadata) :content-type (.getContentType metadata) :etag (.getETag metadata) :last-modified (.getLastModified metadata) :server-side-encryption (.getServerSideEncryption metadata) :user (walk/keywordize-keys (into {} (.getUserMetadata metadata))) :version-id (.getVersionId metadata)}) ObjectListing (to-map [listing] {:bucket (.getBucketName listing) :objects (map to-map (.getObjectSummaries listing)) :prefix (.getPrefix listing) :common-prefixes (seq (.getCommonPrefixes listing)) :truncated? (.isTruncated listing) :max-keys (.getMaxKeys listing) :marker (.getMarker listing) :next-marker (.getNextMarker listing)}) S3ObjectSummary (to-map [summary] {:metadata {:content-length (.getSize summary) :etag (.getETag summary) :last-modified (.getLastModified summary)} :bucket (.getBucketName summary) :key (.getKey summary)}) S3VersionSummary (to-map [summary] {:metadata {:content-length (.getSize summary) :etag (.getETag summary) :last-modified (.getLastModified summary)} :version-id (.getVersionId summary) :latest? (.isLatest summary) :delete-marker? (.isDeleteMarker summary) :bucket (.getBucketName summary) :key (.getKey summary)}) VersionListing (to-map [listing] {:bucket (.getBucketName listing) :versions (map to-map (.getVersionSummaries listing)) :prefix (.getPrefix listing) :common-prefixes (seq (.getCommonPrefixes listing)) :delimiter (.getDelimiter listing) :truncated? (.isTruncated listing) :max-results (maybe-int (.getMaxKeys listing)) ; AWS API is inconsistent, should be .getMaxResults :key-marker (.getKeyMarker listing) :next-key-marker (.getNextKeyMarker listing) :next-version-id-marker (.getNextVersionIdMarker listing) :version-id-marker (.getVersionIdMarker listing)}) CopyObjectResult (to-map [result] {:etag (.getETag result) :expiration-time (.getExpirationTime result) :expiration-time-rule-id (.getExpirationTimeRuleId result) :last-modified-date (.getLastModifiedDate result) :server-side-encryption (.getServerSideEncryption result)})) (defn get-object "Get an object from an S3 bucket. The object is returned as a map with the following keys: :content - an InputStream to the content :metadata - a map of the object's metadata :bucket - the name of the bucket :key - the object's key Be extremely careful when using this method; the :content value in the returned map contains a direct stream of data from the HTTP connection. The underlying HTTP connection cannot be closed until the user finishes reading the data and closes the stream. Therefore: * Use the data from the :content input stream as soon as possible * Close the :content input stream as soon as possible If these rules are not followed, the client can run out of resources by allocating too many open, but unused, HTTP connections." ([cred ^String bucket ^String key] (to-map (.getObject (s3-client cred) bucket key))) ([cred ^String bucket ^String key ^String version-id] (to-map (.getObject (s3-client cred) (GetObjectRequest. bucket key version-id))))) (defn- map->GetObjectMetadataRequest "Create a ListObjectsRequest instance from a map of values." [request] (GetObjectMetadataRequest. (:bucket request) (:key request) (:version-id request))) (defn get-object-metadata "Get an object's metadata from a bucket. A optional map of options may be supplied. Available options are: :version-id - the version of the object The metadata is a map with the following keys: :cache-control - the CacheControl HTTP header :content-disposition - the ContentDisposition HTTP header :content-encoding - the character encoding of the content :content-length - the length of the content in bytes :content-md5 - the MD5 hash of the content :content-type - the mime-type of the content :etag - the HTTP ETag header :last-modified - the last modified date :server-side-encryption - the server-side encryption algorithm" [cred bucket key & [options]] (to-map (.getObjectMetadata (s3-client cred) (map->GetObjectMetadataRequest (merge {:bucket bucket :key key} options))))) (defn- map->ListObjectsRequest "Create a ListObjectsRequest instance from a map of values." ^ListObjectsRequest [request] (doto (ListObjectsRequest.) (set-attr .setBucketName (:bucket request)) (set-attr .setDelimiter (:delimiter request)) (set-attr .setMarker (:marker request)) (set-attr .setMaxKeys (maybe-int (:max-keys request))) (set-attr .setPrefix (:prefix request)))) (defn- http-method [method] (-> method name str/upper-case HttpMethod/valueOf)) (defn generate-presigned-url "Return a presigned URL for an S3 object. Accepts the following options: :expires - the date at which the URL will expire (defaults to 1 day from now) :http-method - the HTTP method for the URL (defaults to :get)" [cred bucket key & [options]] (.toString (.generatePresignedUrl (s3-client cred) bucket key (coerce/to-date (:expires options (-> 1 t/days t/from-now))) (http-method (:http-method options :get))))) (defn list-objects "List the objects in an S3 bucket. A optional map of options may be supplied. Available options are: :delimiter - read only keys up to the next delimiter (such as a '/') :marker - read objects after this key :max-keys - read only this many objects :prefix - read only objects with this prefix The object listing will be returned as a map containing the following keys: :bucket - the name of the bucket :prefix - the supplied prefix (or nil if none supplied) :objects - a list of objects :common-prefixes - the common prefixes of keys omitted by the delimiter :max-keys - the maximum number of objects to be returned :truncated? - true if the list of objects was truncated :marker - the marker of the listing :next-marker - the next marker of the listing" [cred bucket & [options]] (to-map (.listObjects (s3-client cred) (map->ListObjectsRequest (merge {:bucket bucket} options))))) (defn delete-object "Delete an object from an S3 bucket." [cred bucket key] (.deleteObject (s3-client cred) bucket key)) (defn object-exists? "Returns true if an object exists in the supplied bucket and key." [cred bucket key] (try (get-object-metadata cred bucket key) true (catch AmazonServiceException e (if (= 404 (.getStatusCode e)) false (throw e))))) (defn copy-object "Copy an existing S3 object to another key. Returns a map containing the data returned from S3" ([cred bucket src-key dest-key] (copy-object cred bucket src-key bucket dest-key)) ([cred src-bucket src-key dest-bucket dest-key] (to-map (.copyObject (s3-client cred) src-bucket src-key dest-bucket dest-key)))) (defn- map->ListVersionsRequest "Create a ListVersionsRequest instance from a map of values." [request] (doto (ListVersionsRequest.) (set-attr .setBucketName (:bucket request)) (set-attr .setDelimiter (:delimiter request)) (set-attr .setKeyMarker (:key-marker request)) (set-attr .setMaxResults (maybe-int (:max-results request))) (set-attr .setPrefix (:prefix request)) (set-attr .setVersionIdMarker (:version-id-marker request)))) (defn list-versions "List the versions in an S3 bucket. A optional map of options may be supplied. Available options are: :delimiter - the delimiter used in prefix (such as a '/') :key-marker - read versions from the sorted list of all versions starting at this marker. :max-results - read only this many versions :prefix - read only versions with keys having this prefix :version-id-marker - read objects after this version id The version listing will be returned as a map containing the following versions: :bucket - the name of the bucket :prefix - the supplied prefix (or nil if none supplied) :versions - a sorted list of versions, newest first, each version has: :version-id - the unique version id :latest? - is this the latest version for that key? :delete-marker? - is this a delete-marker? :common-prefixes - the common prefixes of keys omitted by the delimiter :max-results - the maximum number of results to be returned :truncated? - true if the results were truncated :key-marker - the key marker of the listing :next-version-id-marker - the version ID marker to use in the next listVersions request in order to obtain the next page of results. :version-id-marker - the version id marker of the listing" [cred bucket & [options]] (to-map (.listVersions (s3-client cred) (map->ListVersionsRequest (merge {:bucket bucket} options))))) (defn delete-version "Deletes a specific version of the specified object in the specified bucket." [cred bucket key version-id] (.deleteVersion (s3-client cred) bucket key version-id)) (defprotocol ^{:no-doc true} ToClojure "Convert an object into an idiomatic Clojure value." (^{:no-doc true} to-clojure [x] "Turn the object into a Clojure value.")) (extend-protocol ToClojure CanonicalGrantee (to-clojure [grantee] {:id (.getIdentifier grantee) :display-name (.getDisplayName grantee)}) EmailAddressGrantee (to-clojure [grantee] {:email (.getIdentifier grantee)}) GroupGrantee (to-clojure [grantee] (condp = grantee GroupGrantee/AllUsers :all-users GroupGrantee/AuthenticatedUsers :authenticated-users GroupGrantee/LogDelivery :log-delivery)) Permission (to-clojure [permission] (condp = permission Permission/FullControl :full-control Permission/Read :read Permission/ReadAcp :read-acp Permission/Write :write Permission/WriteAcp :write-acp))) (extend-protocol Mappable Grant (to-map [grant] {:grantee (to-clojure (.getGrantee grant)) :permission (to-clojure (.getPermission grant))}) AccessControlList (to-map [acl] {:grants (set (map to-map (.getGrants acl))) :owner (to-map (.getOwner acl))})) (defn get-bucket-acl "Get the access control list (ACL) for the supplied bucket. The ACL is a map containing two keys: :owner - the owner of the ACL :grants - a set of access permissions granted The grants themselves are maps with keys: :grantee - the individual or group being granted access :permission - the type of permission (:read, :write, :read-acp, :write-acp or :full-control)." [cred ^String bucket] (to-map (.getBucketAcl (s3-client cred) bucket))) (defn get-object-acl "Get the access control list (ACL) for the supplied object. See get-bucket-acl for a detailed description of the return value." [cred bucket key] (to-map (.getObjectAcl (s3-client cred) bucket key))) (defn- permission [perm] (case perm :full-control Permission/FullControl :read Permission/Read :read-acp Permission/ReadAcp :write Permission/Write :write-acp Permission/WriteAcp)) (defn- grantee [grantee] (cond (keyword? grantee) (case grantee :all-users GroupGrantee/AllUsers :authenticated-users GroupGrantee/AuthenticatedUsers :log-delivery GroupGrantee/LogDelivery) (:id grantee) (CanonicalGrantee. (:id grantee)) (:email grantee) (EmailAddressGrantee. (:email grantee)))) (defn- clear-acl [^AccessControlList acl] (doseq [grantee (->> (.getGrants acl) (map #(.getGrantee ^Grant %)) (set))] (.revokeAllPermissions acl grantee))) (defn- add-acl-grants [^AccessControlList acl grants] (doseq [g grants] (.grantPermission acl (grantee (:grantee g)) (permission (:permission g))))) (defn- update-acl [^AccessControlList acl funcs] (let [grants (:grants (to-map acl)) update (apply comp (reverse funcs))] (clear-acl acl) (add-acl-grants acl (update grants)))) (defn- create-acl [permissions] (doto (AccessControlList.) (update-acl permissions))) (defn update-bucket-acl "Update the access control list (ACL) for the named bucket using functions that update a set of grants (see get-bucket-acl). This function is often used with the grant and revoke functions, e.g. (update-bucket-acl cred bucket (grant :all-users :read) (grant {:email \"<EMAIL>\"} :full-control) (revoke {:email \"<EMAIL>\"} :write))" [cred ^String bucket & funcs] (let [acl (.getBucketAcl (s3-client cred) bucket)] (update-acl acl funcs) (.setBucketAcl (s3-client cred) bucket acl))) (defn update-object-acl "Updates the access control list (ACL) for the supplied object using functions that update a set of grants (see update-bucket-acl for more details)." [cred ^String bucket ^String key & funcs] (let [acl (.getObjectAcl (s3-client cred) bucket key)] (update-acl acl funcs) (.setObjectAcl (s3-client cred) bucket key acl))) (defn grant "Returns a function that adds a new grant map to a set of grants. See update-bucket-acl." [grantee permission] #(conj % {:grantee grantee :permission permission})) (defn revoke "Returns a function that removes a grant map from a set of grants. See update-bucket-acl." [grantee permission] #(disj % {:grantee grantee :permission permission}))
true
(ns s3.s3 "Functions to access the Amazon S3 storage service. Each function takes a map of credentials as its first argument. The credentials map should contain an :access-key key and a :secret-key key, optionally an :endpoint key to denote an AWS endpoint and optionally a :proxy key to define a HTTP proxy to go through. The :proxy key must contain keys for :host and :port, and may contain keys for :user, :password, :domain and :workstation." (:require [clojure.string :as str] [clj-time.core :as t] [clj-time.coerce :as coerce] [clojure.walk :as walk]) (:import com.amazonaws.auth.BasicAWSCredentials com.amazonaws.auth.BasicSessionCredentials com.amazonaws.services.s3.AmazonS3Client com.amazonaws.AmazonServiceException com.amazonaws.ClientConfiguration com.amazonaws.HttpMethod com.amazonaws.services.s3.model.AccessControlList com.amazonaws.services.s3.model.Bucket com.amazonaws.services.s3.model.Grant com.amazonaws.services.s3.model.CanonicalGrantee com.amazonaws.services.s3.model.CopyObjectResult com.amazonaws.services.s3.model.EmailAddressGrantee com.amazonaws.services.s3.model.GetObjectRequest com.amazonaws.services.s3.model.GetObjectMetadataRequest com.amazonaws.services.s3.model.Grant com.amazonaws.services.s3.model.GroupGrantee com.amazonaws.services.s3.model.ListObjectsRequest com.amazonaws.services.s3.model.ListVersionsRequest com.amazonaws.services.s3.model.Owner com.amazonaws.services.s3.model.ObjectMetadata com.amazonaws.services.s3.model.ObjectListing com.amazonaws.services.s3.model.Permission com.amazonaws.services.s3.model.PutObjectRequest com.amazonaws.services.s3.model.S3Object com.amazonaws.services.s3.model.S3ObjectSummary com.amazonaws.services.s3.model.S3VersionSummary com.amazonaws.services.s3.model.VersionListing com.amazonaws.services.s3.model.InitiateMultipartUploadRequest com.amazonaws.services.s3.model.AbortMultipartUploadRequest com.amazonaws.services.s3.model.CompleteMultipartUploadRequest com.amazonaws.services.s3.model.UploadPartRequest java.util.concurrent.Executors java.io.ByteArrayInputStream java.io.File java.io.InputStream java.nio.charset.Charset)) (defn- s3-client* [cred] (let [client-configuration (ClientConfiguration.)] (when-let [conn-timeout (:conn-timeout cred)] (.setConnectionTimeout client-configuration conn-timeout)) (when-let [socket-timeout (:socket-timeout cred)] (.setSocketTimeout client-configuration socket-timeout)) (when-let [max-retries (:max-retries cred)] (.setMaxErrorRetry client-configuration max-retries)) (when-let [max-conns (:max-conns cred)] (.setMaxConnections client-configuration max-conns)) (when-let [proxy-host (get-in cred [:proxy :host])] (.setProxyHost client-configuration proxy-host)) (when-let [proxy-port (get-in cred [:proxy :port])] (.setProxyPort client-configuration proxy-port)) (when-let [proxy-user (get-in cred [:proxy :user])] (.setProxyUsername client-configuration proxy-user)) (when-let [proxy-pass (get-in cred [:proxy :password])] (.setProxyPassword client-configuration proxy-pass)) (when-let [proxy-domain (get-in cred [:proxy :domain])] (.setProxyDomain client-configuration proxy-domain)) (when-let [proxy-workstation (get-in cred [:proxy :workstation])] (.setProxyWorkstation client-configuration proxy-workstation)) (let [aws-creds (if (:token cred) (BasicSessionCredentials. (:access-key cred) (:secret-key cred) (:token cred)) (BasicAWSCredentials. (:access-key cred) (:secret-key cred))) client (AmazonS3Client. aws-creds client-configuration)] (when-let [endpoint (:endpoint cred)] (.setEndpoint client endpoint)) client))) (def ^{:private true :tag AmazonS3Client} s3-client (memoize s3-client*)) (defprotocol ^{:no-doc true} Mappable "Convert a value into a Clojure map." (^{:no-doc true} to-map [x] "Return a map of the value.")) (extend-protocol Mappable Bucket (to-map [bucket] {:name (.getName bucket) :creation-date (.getCreationDate bucket) :owner (to-map (.getOwner bucket))}) Owner (to-map [owner] {:id (.getId owner) :display-name (.getDisplayName owner)}) nil (to-map [_] nil)) (defn bucket-exists? "Returns true if the supplied bucket name already exists in S3." [cred name] (.doesBucketExist (s3-client cred) name)) (defn create-bucket "Create a new S3 bucket with the supplied name." [cred ^String name] (to-map (.createBucket (s3-client cred) name))) (defn delete-bucket "Delete the S3 bucket with the supplied name." [cred ^String name] (.deleteBucket (s3-client cred) name)) (defn list-buckets "List all the S3 buckets for the supplied credentials. The buckets will be returned as a seq of maps with the following keys: :name - the bucket name :creation-date - the date when the bucket was created :owner - the owner of the bucket" [cred] (map to-map (.listBuckets (s3-client cred)))) (defprotocol ^{:no-doc true} ToPutRequest "A protocol for constructing a map that represents an S3 put request." (^{:no-doc true} put-request [x] "Convert a value into a put request.")) (extend-protocol ToPutRequest InputStream (put-request [is] {:input-stream is}) File (put-request [f] {:file f}) String (put-request [s] (let [bytes (.getBytes s)] {:input-stream (ByteArrayInputStream. bytes) :content-length (count bytes) :content-type (str "text/plain; charset=" (.name (Charset/defaultCharset)))}))) (defmacro set-attr "Set an attribute on an object if not nil." {:private true} [object setter value] `(if-let [v# ~value] (~setter ~object v#))) (defn- maybe-int [x] (if x (int x))) (defn- map->ObjectMetadata "Convert a map of object metadata into a ObjectMetadata instance." [metadata] (doto (ObjectMetadata.) (set-attr .setCacheControl (:cache-control metadata)) (set-attr .setContentDisposition (:content-disposition metadata)) (set-attr .setContentEncoding (:content-encoding metadata)) (set-attr .setContentLength (:content-length metadata)) (set-attr .setContentMD5 (:content-md5 metadata)) (set-attr .setContentType (:content-type metadata)) (set-attr .setServerSideEncryption (:server-side-encryption metadata)) (set-attr .setUserMetadata (walk/stringify-keys (dissoc metadata :cache-control :content-disposition :content-encoding :content-length :content-md5 :content-type :server-side-encryption))))) (defn- ^PutObjectRequest ->PutObjectRequest "Create a PutObjectRequest instance from a bucket name, key and put request map." [^String bucket ^String key request] (cond (:file request) (let [put-obj-req (PutObjectRequest. bucket key ^java.io.File (:file request))] (.setMetadata put-obj-req (map->ObjectMetadata (dissoc request :file))) put-obj-req) (:input-stream request) (PutObjectRequest. bucket key (:input-stream request) (map->ObjectMetadata (dissoc request :input-stream))))) (declare create-acl) ; used by put-object (defn put-object "Put a value into an S3 bucket at the specified key. The value can be a String, InputStream or File (or anything that implements the ToPutRequest protocol). An optional map of metadata may also be supplied that can include any of the following keys: :cache-control - the cache-control header (see RFC 2616) :content-disposition - how the content should be downloaded by browsers :content-encoding - the encoding of the content (e.g. gzip) :content-length - the length of the content in bytes :content-md5 - the MD5 sum of the content :content-type - the mime type of the content :server-side-encryption - set to AES256 if SSE is required An optional list of grant functions can be provided after metadata. These functions will be applied to a clear ACL and the result will be the ACL for the newly created object." [cred bucket key value & [metadata & permissions]] (let [req (->> (merge (put-request value) metadata) (->PutObjectRequest bucket key))] (when permissions (.setAccessControlList req (create-acl permissions))) (.putObject (s3-client cred) req))) (defn- initiate-multipart-upload [cred bucket key] (.getUploadId (.initiateMultipartUpload (s3-client cred) (InitiateMultipartUploadRequest. bucket key)))) (defn- abort-multipart-upload [{cred :cred bucket :bucket key :key upload-id :upload-id}] (.abortMultipartUpload (s3-client cred) (AbortMultipartUploadRequest. bucket key upload-id))) (defn- complete-multipart-upload [{cred :cred bucket :bucket key :key upload-id :upload-id e-tags :e-tags}] (.completeMultipartUpload (s3-client cred) (CompleteMultipartUploadRequest. bucket key upload-id e-tags))) (defn- upload-part [{cred :cred bucket :bucket key :key upload-id :upload-id part-size :part-size offset :offset ^java.io.File file :file}] (.getPartETag (.uploadPart (s3-client cred) (doto (UploadPartRequest.) (.setBucketName bucket) (.setKey key) (.setUploadId upload-id) (.setPartNumber (+ 1 (/ offset part-size))) (.setFileOffset offset) (.setPartSize ^long (min part-size (- (.length file) offset))) (.setFile file))))) (defn put-multipart-object "Do a multipart upload of a file into a S3 bucket at the specified key. The value must be a java.io.File object. The entire file is uploaded or not at all. If an exception happens at any time the upload is aborted and the exception is rethrown. The size of the parts and the number of threads uploading the parts can be configured in the last argument as a map with the following keys: :part-size - the size in bytes of each part of the file. Must be 5mb or larger. Defaults to 5mb :threads - the number of threads that will upload parts concurrently. Defaults to 16." [cred bucket key ^java.io.File file & [{:keys [part-size threads] :or {part-size (* 5 1024 1024) threads 16}}]] (let [upload-id (initiate-multipart-upload cred bucket key) upload {:upload-id upload-id :cred cred :bucket bucket :key key :file file} pool (Executors/newFixedThreadPool threads) offsets (range 0 (.length file) part-size) tasks (map #(fn [] (upload-part (assoc upload :offset % :part-size part-size))) offsets)] (try (complete-multipart-upload (assoc upload :e-tags (map #(.get ^java.util.concurrent.Future %) (.invokeAll pool tasks)))) (catch Exception ex (abort-multipart-upload upload) (.shutdown pool) (throw ex)) (finally (.shutdown pool))))) (extend-protocol Mappable S3Object (to-map [object] {:content (.getObjectContent object) :metadata (to-map (.getObjectMetadata object)) :bucket (.getBucketName object) :key (.getKey object)}) ObjectMetadata (to-map [metadata] {:cache-control (.getCacheControl metadata) :content-disposition (.getContentDisposition metadata) :content-encoding (.getContentEncoding metadata) :content-length (.getContentLength metadata) :content-md5 (.getContentMD5 metadata) :content-type (.getContentType metadata) :etag (.getETag metadata) :last-modified (.getLastModified metadata) :server-side-encryption (.getServerSideEncryption metadata) :user (walk/keywordize-keys (into {} (.getUserMetadata metadata))) :version-id (.getVersionId metadata)}) ObjectListing (to-map [listing] {:bucket (.getBucketName listing) :objects (map to-map (.getObjectSummaries listing)) :prefix (.getPrefix listing) :common-prefixes (seq (.getCommonPrefixes listing)) :truncated? (.isTruncated listing) :max-keys (.getMaxKeys listing) :marker (.getMarker listing) :next-marker (.getNextMarker listing)}) S3ObjectSummary (to-map [summary] {:metadata {:content-length (.getSize summary) :etag (.getETag summary) :last-modified (.getLastModified summary)} :bucket (.getBucketName summary) :key (.getKey summary)}) S3VersionSummary (to-map [summary] {:metadata {:content-length (.getSize summary) :etag (.getETag summary) :last-modified (.getLastModified summary)} :version-id (.getVersionId summary) :latest? (.isLatest summary) :delete-marker? (.isDeleteMarker summary) :bucket (.getBucketName summary) :key (.getKey summary)}) VersionListing (to-map [listing] {:bucket (.getBucketName listing) :versions (map to-map (.getVersionSummaries listing)) :prefix (.getPrefix listing) :common-prefixes (seq (.getCommonPrefixes listing)) :delimiter (.getDelimiter listing) :truncated? (.isTruncated listing) :max-results (maybe-int (.getMaxKeys listing)) ; AWS API is inconsistent, should be .getMaxResults :key-marker (.getKeyMarker listing) :next-key-marker (.getNextKeyMarker listing) :next-version-id-marker (.getNextVersionIdMarker listing) :version-id-marker (.getVersionIdMarker listing)}) CopyObjectResult (to-map [result] {:etag (.getETag result) :expiration-time (.getExpirationTime result) :expiration-time-rule-id (.getExpirationTimeRuleId result) :last-modified-date (.getLastModifiedDate result) :server-side-encryption (.getServerSideEncryption result)})) (defn get-object "Get an object from an S3 bucket. The object is returned as a map with the following keys: :content - an InputStream to the content :metadata - a map of the object's metadata :bucket - the name of the bucket :key - the object's key Be extremely careful when using this method; the :content value in the returned map contains a direct stream of data from the HTTP connection. The underlying HTTP connection cannot be closed until the user finishes reading the data and closes the stream. Therefore: * Use the data from the :content input stream as soon as possible * Close the :content input stream as soon as possible If these rules are not followed, the client can run out of resources by allocating too many open, but unused, HTTP connections." ([cred ^String bucket ^String key] (to-map (.getObject (s3-client cred) bucket key))) ([cred ^String bucket ^String key ^String version-id] (to-map (.getObject (s3-client cred) (GetObjectRequest. bucket key version-id))))) (defn- map->GetObjectMetadataRequest "Create a ListObjectsRequest instance from a map of values." [request] (GetObjectMetadataRequest. (:bucket request) (:key request) (:version-id request))) (defn get-object-metadata "Get an object's metadata from a bucket. A optional map of options may be supplied. Available options are: :version-id - the version of the object The metadata is a map with the following keys: :cache-control - the CacheControl HTTP header :content-disposition - the ContentDisposition HTTP header :content-encoding - the character encoding of the content :content-length - the length of the content in bytes :content-md5 - the MD5 hash of the content :content-type - the mime-type of the content :etag - the HTTP ETag header :last-modified - the last modified date :server-side-encryption - the server-side encryption algorithm" [cred bucket key & [options]] (to-map (.getObjectMetadata (s3-client cred) (map->GetObjectMetadataRequest (merge {:bucket bucket :key key} options))))) (defn- map->ListObjectsRequest "Create a ListObjectsRequest instance from a map of values." ^ListObjectsRequest [request] (doto (ListObjectsRequest.) (set-attr .setBucketName (:bucket request)) (set-attr .setDelimiter (:delimiter request)) (set-attr .setMarker (:marker request)) (set-attr .setMaxKeys (maybe-int (:max-keys request))) (set-attr .setPrefix (:prefix request)))) (defn- http-method [method] (-> method name str/upper-case HttpMethod/valueOf)) (defn generate-presigned-url "Return a presigned URL for an S3 object. Accepts the following options: :expires - the date at which the URL will expire (defaults to 1 day from now) :http-method - the HTTP method for the URL (defaults to :get)" [cred bucket key & [options]] (.toString (.generatePresignedUrl (s3-client cred) bucket key (coerce/to-date (:expires options (-> 1 t/days t/from-now))) (http-method (:http-method options :get))))) (defn list-objects "List the objects in an S3 bucket. A optional map of options may be supplied. Available options are: :delimiter - read only keys up to the next delimiter (such as a '/') :marker - read objects after this key :max-keys - read only this many objects :prefix - read only objects with this prefix The object listing will be returned as a map containing the following keys: :bucket - the name of the bucket :prefix - the supplied prefix (or nil if none supplied) :objects - a list of objects :common-prefixes - the common prefixes of keys omitted by the delimiter :max-keys - the maximum number of objects to be returned :truncated? - true if the list of objects was truncated :marker - the marker of the listing :next-marker - the next marker of the listing" [cred bucket & [options]] (to-map (.listObjects (s3-client cred) (map->ListObjectsRequest (merge {:bucket bucket} options))))) (defn delete-object "Delete an object from an S3 bucket." [cred bucket key] (.deleteObject (s3-client cred) bucket key)) (defn object-exists? "Returns true if an object exists in the supplied bucket and key." [cred bucket key] (try (get-object-metadata cred bucket key) true (catch AmazonServiceException e (if (= 404 (.getStatusCode e)) false (throw e))))) (defn copy-object "Copy an existing S3 object to another key. Returns a map containing the data returned from S3" ([cred bucket src-key dest-key] (copy-object cred bucket src-key bucket dest-key)) ([cred src-bucket src-key dest-bucket dest-key] (to-map (.copyObject (s3-client cred) src-bucket src-key dest-bucket dest-key)))) (defn- map->ListVersionsRequest "Create a ListVersionsRequest instance from a map of values." [request] (doto (ListVersionsRequest.) (set-attr .setBucketName (:bucket request)) (set-attr .setDelimiter (:delimiter request)) (set-attr .setKeyMarker (:key-marker request)) (set-attr .setMaxResults (maybe-int (:max-results request))) (set-attr .setPrefix (:prefix request)) (set-attr .setVersionIdMarker (:version-id-marker request)))) (defn list-versions "List the versions in an S3 bucket. A optional map of options may be supplied. Available options are: :delimiter - the delimiter used in prefix (such as a '/') :key-marker - read versions from the sorted list of all versions starting at this marker. :max-results - read only this many versions :prefix - read only versions with keys having this prefix :version-id-marker - read objects after this version id The version listing will be returned as a map containing the following versions: :bucket - the name of the bucket :prefix - the supplied prefix (or nil if none supplied) :versions - a sorted list of versions, newest first, each version has: :version-id - the unique version id :latest? - is this the latest version for that key? :delete-marker? - is this a delete-marker? :common-prefixes - the common prefixes of keys omitted by the delimiter :max-results - the maximum number of results to be returned :truncated? - true if the results were truncated :key-marker - the key marker of the listing :next-version-id-marker - the version ID marker to use in the next listVersions request in order to obtain the next page of results. :version-id-marker - the version id marker of the listing" [cred bucket & [options]] (to-map (.listVersions (s3-client cred) (map->ListVersionsRequest (merge {:bucket bucket} options))))) (defn delete-version "Deletes a specific version of the specified object in the specified bucket." [cred bucket key version-id] (.deleteVersion (s3-client cred) bucket key version-id)) (defprotocol ^{:no-doc true} ToClojure "Convert an object into an idiomatic Clojure value." (^{:no-doc true} to-clojure [x] "Turn the object into a Clojure value.")) (extend-protocol ToClojure CanonicalGrantee (to-clojure [grantee] {:id (.getIdentifier grantee) :display-name (.getDisplayName grantee)}) EmailAddressGrantee (to-clojure [grantee] {:email (.getIdentifier grantee)}) GroupGrantee (to-clojure [grantee] (condp = grantee GroupGrantee/AllUsers :all-users GroupGrantee/AuthenticatedUsers :authenticated-users GroupGrantee/LogDelivery :log-delivery)) Permission (to-clojure [permission] (condp = permission Permission/FullControl :full-control Permission/Read :read Permission/ReadAcp :read-acp Permission/Write :write Permission/WriteAcp :write-acp))) (extend-protocol Mappable Grant (to-map [grant] {:grantee (to-clojure (.getGrantee grant)) :permission (to-clojure (.getPermission grant))}) AccessControlList (to-map [acl] {:grants (set (map to-map (.getGrants acl))) :owner (to-map (.getOwner acl))})) (defn get-bucket-acl "Get the access control list (ACL) for the supplied bucket. The ACL is a map containing two keys: :owner - the owner of the ACL :grants - a set of access permissions granted The grants themselves are maps with keys: :grantee - the individual or group being granted access :permission - the type of permission (:read, :write, :read-acp, :write-acp or :full-control)." [cred ^String bucket] (to-map (.getBucketAcl (s3-client cred) bucket))) (defn get-object-acl "Get the access control list (ACL) for the supplied object. See get-bucket-acl for a detailed description of the return value." [cred bucket key] (to-map (.getObjectAcl (s3-client cred) bucket key))) (defn- permission [perm] (case perm :full-control Permission/FullControl :read Permission/Read :read-acp Permission/ReadAcp :write Permission/Write :write-acp Permission/WriteAcp)) (defn- grantee [grantee] (cond (keyword? grantee) (case grantee :all-users GroupGrantee/AllUsers :authenticated-users GroupGrantee/AuthenticatedUsers :log-delivery GroupGrantee/LogDelivery) (:id grantee) (CanonicalGrantee. (:id grantee)) (:email grantee) (EmailAddressGrantee. (:email grantee)))) (defn- clear-acl [^AccessControlList acl] (doseq [grantee (->> (.getGrants acl) (map #(.getGrantee ^Grant %)) (set))] (.revokeAllPermissions acl grantee))) (defn- add-acl-grants [^AccessControlList acl grants] (doseq [g grants] (.grantPermission acl (grantee (:grantee g)) (permission (:permission g))))) (defn- update-acl [^AccessControlList acl funcs] (let [grants (:grants (to-map acl)) update (apply comp (reverse funcs))] (clear-acl acl) (add-acl-grants acl (update grants)))) (defn- create-acl [permissions] (doto (AccessControlList.) (update-acl permissions))) (defn update-bucket-acl "Update the access control list (ACL) for the named bucket using functions that update a set of grants (see get-bucket-acl). This function is often used with the grant and revoke functions, e.g. (update-bucket-acl cred bucket (grant :all-users :read) (grant {:email \"PI:EMAIL:<EMAIL>END_PI\"} :full-control) (revoke {:email \"PI:EMAIL:<EMAIL>END_PI\"} :write))" [cred ^String bucket & funcs] (let [acl (.getBucketAcl (s3-client cred) bucket)] (update-acl acl funcs) (.setBucketAcl (s3-client cred) bucket acl))) (defn update-object-acl "Updates the access control list (ACL) for the supplied object using functions that update a set of grants (see update-bucket-acl for more details)." [cred ^String bucket ^String key & funcs] (let [acl (.getObjectAcl (s3-client cred) bucket key)] (update-acl acl funcs) (.setObjectAcl (s3-client cred) bucket key acl))) (defn grant "Returns a function that adds a new grant map to a set of grants. See update-bucket-acl." [grantee permission] #(conj % {:grantee grantee :permission permission})) (defn revoke "Returns a function that removes a grant map from a set of grants. See update-bucket-acl." [grantee permission] #(disj % {:grantee grantee :permission permission}))
[ { "context": "ector}\n {:members\n [{:name \"B\"\n :namespace nil\n :operator", "end": 2753, "score": 0.9309828877449036, "start": 2752, "tag": "NAME", "value": "B" }, { "context": "ector}\n {:members\n [{:name \"B\"\n :namespace nil\n :operator", "end": 2986, "score": 0.875822126865387, "start": 2985, "tag": "NAME", "value": "B" }, { "context": "ector}\n {:members\n [{:name \"B\"\n :namespace nil\n :operator", "end": 3220, "score": 0.8541665077209473, "start": 3219, "tag": "NAME", "value": "B" }, { "context": "ector}\n {:members\n [{:name \"B\"\n :namespace nil\n :operator", "end": 3454, "score": 0.8422619700431824, "start": 3453, "tag": "NAME", "value": "B" }, { "context": "ector}\n {:members\n [{:name \"B\"\n :namespace nil\n :operator", "end": 3688, "score": 0.9467445015907288, "start": 3687, "tag": "NAME", "value": "B" } ]
test/clj_ph_css/core_test.clj
Panthevm/clj-ph-css
0
(ns clj-ph-css.core-test (:require [clj-ph-css.core :as sut] [clojure.test :refer :all])) (defmacro deftransform-match "schema -> string = string -> schema" [& args] (let [stylesheet (apply str (drop-last args)) schema (last args)] `(do (testing "schema" (is (= ~schema (sut/string->schema ~stylesheet)))) (testing "object" (is (= ~stylesheet (sut/schema->string ~schema))))))) (deftest transform-test (testing "universal selector" ;; https://www.w3.org/TR/2018/REC-selectors-3-20181106/#universal-selector (deftransform-match "ns|*," "*|*," "|*," "*" "{}" [{:selectors [{:members [{:group :type :value "ns|" :type :member-simple} {:group :type :value "*" :type :member-simple}] :type :selector} {:members [{:group :type :value "*|" :type :member-simple} {:group :type :value "*" :type :member-simple}] :type :selector} {:members [{:group :type :value "|" :type :member-simple} {:group :type :value "*" :type :member-simple}] :type :selector} {:members [{:group :type :value "*" :type :member-simple}] :type :selector}] :declarations [] :type :style-rule}])) (testing "type selector" ;; https://www.w3.org/TR/2018/REC-selectors-3-20181106/#type-selectors (deftransform-match "A," "|A," "*|A," "ns|A" "{}" [{:type :style-rule :selectors [{:members [{:group :type :value "A" :type :member-simple}] :type :selector} {:members [{:group :type :value "|" :type :member-simple} {:group :type :value "A" :type :member-simple}] :type :selector} {:members [{:group :type :value "*|" :type :member-simple} {:group :type :value "A" :type :member-simple}] :type :selector} {:members [{:group :type :value "ns|" :type :member-simple} {:group :type :value "A" :type :member-simple}] :type :selector}] :declarations []}])) (testing "attribute selectors" ;; https://www.w3.org/TR/2018/REC-selectors-3-20181106/#attribute-selectors (deftransform-match "[B]," "[B=C]," "[B~=C]," "[B^=C]," "[B$=C]," "[B*=C]," "[B|=C]" "{}" [{:type :style-rule :selectors [{:members [{:name "B" :operator nil :namespace nil :attribute nil :type :selector-attribute}] :type :selector} {:members [{:name "B" :namespace nil :operator {:name "=" :type :attribute-operator} :attribute "C" :type :selector-attribute}] :type :selector} {:members [{:name "B" :namespace nil :operator {:name "~=" :type :attribute-operator} :attribute "C" :type :selector-attribute}] :type :selector} {:members [{:name "B" :namespace nil :operator {:name "^=" :type :attribute-operator} :attribute "C" :type :selector-attribute}] :type :selector} {:members [{:name "B" :namespace nil :operator {:name "$=" :type :attribute-operator} :attribute "C" :type :selector-attribute}] :type :selector} {:members [{:name "B" :namespace nil :operator {:name "*=" :type :attribute-operator} :attribute "C" :type :selector-attribute}] :type :selector} {:members [{:name "B" :namespace nil :operator {:name "|=" :type :attribute-operator} :attribute "C" :type :selector-attribute}] :type :selector}] :declarations []}])) (testing "pseudo-classes" ;; https://www.w3.org/TR/2018/REC-selectors-3-20181106/#structural-pseudos (deftransform-match ":root," "::after" "{}" [{:type :style-rule :selectors [{:members [{:group :pseudo :value ":root" :type :member-simple}] :type :selector} {:members [{:group :pseudo :value "::after" :type :member-simple}] :type :selector}] :declarations []}])) (testing "classes" ;; https://www.w3.org/TR/2018/REC-selectors-3-20181106/#class-html (deftransform-match ".A," "*.A," "A.B" "{}" [{:type :style-rule :selectors [{:members [{:group :class :value ".A" :type :member-simple}] :type :selector} {:members [{:group :type :value "*" :type :member-simple} {:group :class :value ".A" :type :member-simple}] :type :selector} {:members [{:group :type :value "A" :type :member-simple} {:group :class :value ".B" :type :member-simple}] :type :selector}] :declarations []}])) (testing "id selectors" ;; https://www.w3.org/TR/2018/REC-selectors-3-20181106/#id-selectors (deftransform-match "#A," "A#B," "*#A" "{}" [{:type :style-rule :selectors [{:members [{:group :identifier :value "#A" :type :member-simple}] :type :selector} {:members [{:group :type :value "A" :type :member-simple} {:group :identifier :value "#B" :type :member-simple}] :type :selector} {:members [{:group :type :value "*" :type :member-simple} {:group :identifier :value "#A" :type :member-simple}] :type :selector}] :declarations []}])) (testing "negation" ;; https://www.w3.org/TR/2018/REC-selectors-3-20181106/#negation (deftransform-match ":not(A)," "A:not(B)," "A|B:not(C):not(D)" "{}" [{:type :style-rule :selectors [{:members [{:selectors [{:members [{:group :type :value "A" :type :member-simple}] :type :selector}] :type :member-not}] :type :selector} {:members [{:group :type :value "A" :type :member-simple} {:selectors [{:members [{:group :type :value "B" :type :member-simple}] :type :selector}] :type :member-not}] :type :selector} {:members [{:group :type :value "A|" :type :member-simple} {:group :type :value "B" :type :member-simple} {:selectors [{:members [{:group :type :value "C" :type :member-simple}] :type :selector}] :type :member-not} {:selectors [{:members [{:group :type :value "D" :type :member-simple}] :type :selector}] :type :member-not}] :type :selector}] :declarations []}])) (testing "combinators" (deftransform-match "A B," "A>B," "A+B," "A~B" "{}" [{:type :style-rule :selectors [{:members [{:group :type :value "A" :type :member-simple} {:name " " :type :selector-combinator} {:group :type :value "B" :type :member-simple}] :type :selector} {:members [{:group :type :value "A" :type :member-simple} {:name ">" :type :selector-combinator} {:group :type :value "B" :type :member-simple}] :type :selector} {:members [{:group :type :value "A" :type :member-simple} {:name "+" :type :selector-combinator} {:group :type :value "B" :type :member-simple}] :type :selector} {:members [{:group :type :value "A" :type :member-simple} {:name "~" :type :selector-combinator} {:group :type :value "B" :type :member-simple}] :type :selector}] :declarations []}])) (testing "functions" (deftransform-match ":lang(en){}" [{:selectors [{:members [{:name ":lang(" :expression "en" :type :member-function}] :type :selector}] :declarations [] :type :style-rule}])) (testing "media-rule" (testing "query" (deftransform-match "@media screen{}" "@media not screen{}" "@media only screen{}" [{:rules [] :queries [{:not? false :only? false :medium "screen" :expressions [] :type :media-query}] :type :media-rule} {:rules [] :queries [{:not? true :only? false :medium "screen" :expressions [] :type :media-query}] :type :media-rule} {:rules [] :queries [{:not? false :only? true :medium "screen" :expressions [] :type :media-query}] :type :media-rule}])) (testing "expression" (deftransform-match "@media (min-width:100px){}" [{:rules [] :queries [{:not? false :only? false :medium nil :expressions [{:value "100px" :feature "min-width" :type :media-expression}] :type :media-query}] :type :media-rule}])) (testing "rules" (deftransform-match "@media screen{A{}}" "@media screen{@media screen{A{}}}" [{:rules [{:type :style-rule :selectors [{:members [{:group :type :value "A" :type :member-simple}], :type :selector}] :declarations []}] :queries [{:not? false :only? false :medium "screen" :expressions [] :type :media-query}] :type :media-rule} {:rules [{:rules [{:type :style-rule :selectors [{:members [{:group :type :value "A" :type :member-simple}] :type :selector}] :declarations []}] :queries [{:not? false :only? false :medium "screen" :expressions [] :type :media-query}] :type :media-rule}] :queries [{:not? false :only? false :medium "screen" :expressions [] :type :media-query}] :type :media-rule}]))) (testing "keyframes rule" (deftransform-match "@keyframes foo{from{}50%{}20%,80%{}to{}}" [{:declaration "@keyframes" :name "foo" :blocks [{:type :keyframes-block :selectors ["from"] :declarations []} {:type :keyframes-block :selectors ["50%"] :declarations []} {:type :keyframes-block :selectors ["20%" "80%"] :declarations []} {:type :keyframes-block :selectors ["to"] :declarations []}] :type :keyframes-rule}])) (testing "font-face-rule" (deftransform-match "@font-face{a:b}" [{:name "@font-face" :declarations [{:property "a" :expression "b" :important? false :type :declaration}] :type :font-face-rule}])) (testing "import rule" (deftransform-match "@import url(foo.css);\n" [{:location "foo.css" :queries [] :type :import-rule}]) (deftransform-match "@import url(foo.css) screen;\n" [{:location "foo.css" :queries [{:not? false :only? false :medium "screen" :expressions [] :type :media-query}] :type :import-rule}])) (testing "namespace rule" (deftransform-match "@namespace foo url(bar);\n" [{:prefix "foo" :url "bar" :type :namespace-rule}]) (deftransform-match "@namespace url(bar);\n" [{:prefix nil :url "bar" :type :namespace-rule}])) (testing "viewport rule" (deftransform-match "@viewport{a:b}" [{:name "@viewport" :declarations [{:property "a" :expression "b" :important? false :type :declaration}] :type :viewport-rule}])) (testing "page rule" (deftransform-match "@page :first{a:b}" [{:selectors [":first"] :declarations [{:property "a" :expression "b" :important? false :type :declaration}] :type :page-rule}])) (testing "support rule" (deftransform-match "@supports (a:b){A{c:d}}" [{:members [{:declaration {:property "a" :expression "b" :important? false :type :declaration} :type :condition-declaration}] :rules [{:selectors [{:members [{:value "A" :group :type :type :member-simple}] :type :selector}] :declarations [{:property "c" :expression "d" :important? false :type :declaration}] :type :style-rule}] :type :support-rule}]) (testing "negation" (deftransform-match "@supports not (a:b){A{c:d}}" [{:members [{:member {:declaration {:property "a" :expression "b" :important? false :type :declaration} :type :condition-declaration} :type :condition-negation}] :rules [{:selectors [{:members [{:value "A" :group :type :type :member-simple}] :type :selector}] :declarations [{:property "c" :expression "d" :important? false :type :declaration}] :type :style-rule}] :type :support-rule}])) (testing "nested" (deftransform-match "@supports ((a:b) or (c:d)){A{e:f}}" [{:members [{:members [{:declaration {:property "a" :expression "b" :important? false :type :declaration} :type :condition-declaration} {:name "or" :type :condition-operator} {:declaration {:property "c" :expression "d" :important? false :type :declaration} :type :condition-declaration}] :type :condition-nested}] :rules [{:selectors [{:members [{:value "A" :group :type :type :member-simple}] :type :selector}] :declarations [{:property "e" :expression "f" :important? false :type :declaration}] :type :style-rule}] :type :support-rule}]))))
18873
(ns clj-ph-css.core-test (:require [clj-ph-css.core :as sut] [clojure.test :refer :all])) (defmacro deftransform-match "schema -> string = string -> schema" [& args] (let [stylesheet (apply str (drop-last args)) schema (last args)] `(do (testing "schema" (is (= ~schema (sut/string->schema ~stylesheet)))) (testing "object" (is (= ~stylesheet (sut/schema->string ~schema))))))) (deftest transform-test (testing "universal selector" ;; https://www.w3.org/TR/2018/REC-selectors-3-20181106/#universal-selector (deftransform-match "ns|*," "*|*," "|*," "*" "{}" [{:selectors [{:members [{:group :type :value "ns|" :type :member-simple} {:group :type :value "*" :type :member-simple}] :type :selector} {:members [{:group :type :value "*|" :type :member-simple} {:group :type :value "*" :type :member-simple}] :type :selector} {:members [{:group :type :value "|" :type :member-simple} {:group :type :value "*" :type :member-simple}] :type :selector} {:members [{:group :type :value "*" :type :member-simple}] :type :selector}] :declarations [] :type :style-rule}])) (testing "type selector" ;; https://www.w3.org/TR/2018/REC-selectors-3-20181106/#type-selectors (deftransform-match "A," "|A," "*|A," "ns|A" "{}" [{:type :style-rule :selectors [{:members [{:group :type :value "A" :type :member-simple}] :type :selector} {:members [{:group :type :value "|" :type :member-simple} {:group :type :value "A" :type :member-simple}] :type :selector} {:members [{:group :type :value "*|" :type :member-simple} {:group :type :value "A" :type :member-simple}] :type :selector} {:members [{:group :type :value "ns|" :type :member-simple} {:group :type :value "A" :type :member-simple}] :type :selector}] :declarations []}])) (testing "attribute selectors" ;; https://www.w3.org/TR/2018/REC-selectors-3-20181106/#attribute-selectors (deftransform-match "[B]," "[B=C]," "[B~=C]," "[B^=C]," "[B$=C]," "[B*=C]," "[B|=C]" "{}" [{:type :style-rule :selectors [{:members [{:name "B" :operator nil :namespace nil :attribute nil :type :selector-attribute}] :type :selector} {:members [{:name "<NAME>" :namespace nil :operator {:name "=" :type :attribute-operator} :attribute "C" :type :selector-attribute}] :type :selector} {:members [{:name "<NAME>" :namespace nil :operator {:name "~=" :type :attribute-operator} :attribute "C" :type :selector-attribute}] :type :selector} {:members [{:name "<NAME>" :namespace nil :operator {:name "^=" :type :attribute-operator} :attribute "C" :type :selector-attribute}] :type :selector} {:members [{:name "<NAME>" :namespace nil :operator {:name "$=" :type :attribute-operator} :attribute "C" :type :selector-attribute}] :type :selector} {:members [{:name "<NAME>" :namespace nil :operator {:name "*=" :type :attribute-operator} :attribute "C" :type :selector-attribute}] :type :selector} {:members [{:name "B" :namespace nil :operator {:name "|=" :type :attribute-operator} :attribute "C" :type :selector-attribute}] :type :selector}] :declarations []}])) (testing "pseudo-classes" ;; https://www.w3.org/TR/2018/REC-selectors-3-20181106/#structural-pseudos (deftransform-match ":root," "::after" "{}" [{:type :style-rule :selectors [{:members [{:group :pseudo :value ":root" :type :member-simple}] :type :selector} {:members [{:group :pseudo :value "::after" :type :member-simple}] :type :selector}] :declarations []}])) (testing "classes" ;; https://www.w3.org/TR/2018/REC-selectors-3-20181106/#class-html (deftransform-match ".A," "*.A," "A.B" "{}" [{:type :style-rule :selectors [{:members [{:group :class :value ".A" :type :member-simple}] :type :selector} {:members [{:group :type :value "*" :type :member-simple} {:group :class :value ".A" :type :member-simple}] :type :selector} {:members [{:group :type :value "A" :type :member-simple} {:group :class :value ".B" :type :member-simple}] :type :selector}] :declarations []}])) (testing "id selectors" ;; https://www.w3.org/TR/2018/REC-selectors-3-20181106/#id-selectors (deftransform-match "#A," "A#B," "*#A" "{}" [{:type :style-rule :selectors [{:members [{:group :identifier :value "#A" :type :member-simple}] :type :selector} {:members [{:group :type :value "A" :type :member-simple} {:group :identifier :value "#B" :type :member-simple}] :type :selector} {:members [{:group :type :value "*" :type :member-simple} {:group :identifier :value "#A" :type :member-simple}] :type :selector}] :declarations []}])) (testing "negation" ;; https://www.w3.org/TR/2018/REC-selectors-3-20181106/#negation (deftransform-match ":not(A)," "A:not(B)," "A|B:not(C):not(D)" "{}" [{:type :style-rule :selectors [{:members [{:selectors [{:members [{:group :type :value "A" :type :member-simple}] :type :selector}] :type :member-not}] :type :selector} {:members [{:group :type :value "A" :type :member-simple} {:selectors [{:members [{:group :type :value "B" :type :member-simple}] :type :selector}] :type :member-not}] :type :selector} {:members [{:group :type :value "A|" :type :member-simple} {:group :type :value "B" :type :member-simple} {:selectors [{:members [{:group :type :value "C" :type :member-simple}] :type :selector}] :type :member-not} {:selectors [{:members [{:group :type :value "D" :type :member-simple}] :type :selector}] :type :member-not}] :type :selector}] :declarations []}])) (testing "combinators" (deftransform-match "A B," "A>B," "A+B," "A~B" "{}" [{:type :style-rule :selectors [{:members [{:group :type :value "A" :type :member-simple} {:name " " :type :selector-combinator} {:group :type :value "B" :type :member-simple}] :type :selector} {:members [{:group :type :value "A" :type :member-simple} {:name ">" :type :selector-combinator} {:group :type :value "B" :type :member-simple}] :type :selector} {:members [{:group :type :value "A" :type :member-simple} {:name "+" :type :selector-combinator} {:group :type :value "B" :type :member-simple}] :type :selector} {:members [{:group :type :value "A" :type :member-simple} {:name "~" :type :selector-combinator} {:group :type :value "B" :type :member-simple}] :type :selector}] :declarations []}])) (testing "functions" (deftransform-match ":lang(en){}" [{:selectors [{:members [{:name ":lang(" :expression "en" :type :member-function}] :type :selector}] :declarations [] :type :style-rule}])) (testing "media-rule" (testing "query" (deftransform-match "@media screen{}" "@media not screen{}" "@media only screen{}" [{:rules [] :queries [{:not? false :only? false :medium "screen" :expressions [] :type :media-query}] :type :media-rule} {:rules [] :queries [{:not? true :only? false :medium "screen" :expressions [] :type :media-query}] :type :media-rule} {:rules [] :queries [{:not? false :only? true :medium "screen" :expressions [] :type :media-query}] :type :media-rule}])) (testing "expression" (deftransform-match "@media (min-width:100px){}" [{:rules [] :queries [{:not? false :only? false :medium nil :expressions [{:value "100px" :feature "min-width" :type :media-expression}] :type :media-query}] :type :media-rule}])) (testing "rules" (deftransform-match "@media screen{A{}}" "@media screen{@media screen{A{}}}" [{:rules [{:type :style-rule :selectors [{:members [{:group :type :value "A" :type :member-simple}], :type :selector}] :declarations []}] :queries [{:not? false :only? false :medium "screen" :expressions [] :type :media-query}] :type :media-rule} {:rules [{:rules [{:type :style-rule :selectors [{:members [{:group :type :value "A" :type :member-simple}] :type :selector}] :declarations []}] :queries [{:not? false :only? false :medium "screen" :expressions [] :type :media-query}] :type :media-rule}] :queries [{:not? false :only? false :medium "screen" :expressions [] :type :media-query}] :type :media-rule}]))) (testing "keyframes rule" (deftransform-match "@keyframes foo{from{}50%{}20%,80%{}to{}}" [{:declaration "@keyframes" :name "foo" :blocks [{:type :keyframes-block :selectors ["from"] :declarations []} {:type :keyframes-block :selectors ["50%"] :declarations []} {:type :keyframes-block :selectors ["20%" "80%"] :declarations []} {:type :keyframes-block :selectors ["to"] :declarations []}] :type :keyframes-rule}])) (testing "font-face-rule" (deftransform-match "@font-face{a:b}" [{:name "@font-face" :declarations [{:property "a" :expression "b" :important? false :type :declaration}] :type :font-face-rule}])) (testing "import rule" (deftransform-match "@import url(foo.css);\n" [{:location "foo.css" :queries [] :type :import-rule}]) (deftransform-match "@import url(foo.css) screen;\n" [{:location "foo.css" :queries [{:not? false :only? false :medium "screen" :expressions [] :type :media-query}] :type :import-rule}])) (testing "namespace rule" (deftransform-match "@namespace foo url(bar);\n" [{:prefix "foo" :url "bar" :type :namespace-rule}]) (deftransform-match "@namespace url(bar);\n" [{:prefix nil :url "bar" :type :namespace-rule}])) (testing "viewport rule" (deftransform-match "@viewport{a:b}" [{:name "@viewport" :declarations [{:property "a" :expression "b" :important? false :type :declaration}] :type :viewport-rule}])) (testing "page rule" (deftransform-match "@page :first{a:b}" [{:selectors [":first"] :declarations [{:property "a" :expression "b" :important? false :type :declaration}] :type :page-rule}])) (testing "support rule" (deftransform-match "@supports (a:b){A{c:d}}" [{:members [{:declaration {:property "a" :expression "b" :important? false :type :declaration} :type :condition-declaration}] :rules [{:selectors [{:members [{:value "A" :group :type :type :member-simple}] :type :selector}] :declarations [{:property "c" :expression "d" :important? false :type :declaration}] :type :style-rule}] :type :support-rule}]) (testing "negation" (deftransform-match "@supports not (a:b){A{c:d}}" [{:members [{:member {:declaration {:property "a" :expression "b" :important? false :type :declaration} :type :condition-declaration} :type :condition-negation}] :rules [{:selectors [{:members [{:value "A" :group :type :type :member-simple}] :type :selector}] :declarations [{:property "c" :expression "d" :important? false :type :declaration}] :type :style-rule}] :type :support-rule}])) (testing "nested" (deftransform-match "@supports ((a:b) or (c:d)){A{e:f}}" [{:members [{:members [{:declaration {:property "a" :expression "b" :important? false :type :declaration} :type :condition-declaration} {:name "or" :type :condition-operator} {:declaration {:property "c" :expression "d" :important? false :type :declaration} :type :condition-declaration}] :type :condition-nested}] :rules [{:selectors [{:members [{:value "A" :group :type :type :member-simple}] :type :selector}] :declarations [{:property "e" :expression "f" :important? false :type :declaration}] :type :style-rule}] :type :support-rule}]))))
true
(ns clj-ph-css.core-test (:require [clj-ph-css.core :as sut] [clojure.test :refer :all])) (defmacro deftransform-match "schema -> string = string -> schema" [& args] (let [stylesheet (apply str (drop-last args)) schema (last args)] `(do (testing "schema" (is (= ~schema (sut/string->schema ~stylesheet)))) (testing "object" (is (= ~stylesheet (sut/schema->string ~schema))))))) (deftest transform-test (testing "universal selector" ;; https://www.w3.org/TR/2018/REC-selectors-3-20181106/#universal-selector (deftransform-match "ns|*," "*|*," "|*," "*" "{}" [{:selectors [{:members [{:group :type :value "ns|" :type :member-simple} {:group :type :value "*" :type :member-simple}] :type :selector} {:members [{:group :type :value "*|" :type :member-simple} {:group :type :value "*" :type :member-simple}] :type :selector} {:members [{:group :type :value "|" :type :member-simple} {:group :type :value "*" :type :member-simple}] :type :selector} {:members [{:group :type :value "*" :type :member-simple}] :type :selector}] :declarations [] :type :style-rule}])) (testing "type selector" ;; https://www.w3.org/TR/2018/REC-selectors-3-20181106/#type-selectors (deftransform-match "A," "|A," "*|A," "ns|A" "{}" [{:type :style-rule :selectors [{:members [{:group :type :value "A" :type :member-simple}] :type :selector} {:members [{:group :type :value "|" :type :member-simple} {:group :type :value "A" :type :member-simple}] :type :selector} {:members [{:group :type :value "*|" :type :member-simple} {:group :type :value "A" :type :member-simple}] :type :selector} {:members [{:group :type :value "ns|" :type :member-simple} {:group :type :value "A" :type :member-simple}] :type :selector}] :declarations []}])) (testing "attribute selectors" ;; https://www.w3.org/TR/2018/REC-selectors-3-20181106/#attribute-selectors (deftransform-match "[B]," "[B=C]," "[B~=C]," "[B^=C]," "[B$=C]," "[B*=C]," "[B|=C]" "{}" [{:type :style-rule :selectors [{:members [{:name "B" :operator nil :namespace nil :attribute nil :type :selector-attribute}] :type :selector} {:members [{:name "PI:NAME:<NAME>END_PI" :namespace nil :operator {:name "=" :type :attribute-operator} :attribute "C" :type :selector-attribute}] :type :selector} {:members [{:name "PI:NAME:<NAME>END_PI" :namespace nil :operator {:name "~=" :type :attribute-operator} :attribute "C" :type :selector-attribute}] :type :selector} {:members [{:name "PI:NAME:<NAME>END_PI" :namespace nil :operator {:name "^=" :type :attribute-operator} :attribute "C" :type :selector-attribute}] :type :selector} {:members [{:name "PI:NAME:<NAME>END_PI" :namespace nil :operator {:name "$=" :type :attribute-operator} :attribute "C" :type :selector-attribute}] :type :selector} {:members [{:name "PI:NAME:<NAME>END_PI" :namespace nil :operator {:name "*=" :type :attribute-operator} :attribute "C" :type :selector-attribute}] :type :selector} {:members [{:name "B" :namespace nil :operator {:name "|=" :type :attribute-operator} :attribute "C" :type :selector-attribute}] :type :selector}] :declarations []}])) (testing "pseudo-classes" ;; https://www.w3.org/TR/2018/REC-selectors-3-20181106/#structural-pseudos (deftransform-match ":root," "::after" "{}" [{:type :style-rule :selectors [{:members [{:group :pseudo :value ":root" :type :member-simple}] :type :selector} {:members [{:group :pseudo :value "::after" :type :member-simple}] :type :selector}] :declarations []}])) (testing "classes" ;; https://www.w3.org/TR/2018/REC-selectors-3-20181106/#class-html (deftransform-match ".A," "*.A," "A.B" "{}" [{:type :style-rule :selectors [{:members [{:group :class :value ".A" :type :member-simple}] :type :selector} {:members [{:group :type :value "*" :type :member-simple} {:group :class :value ".A" :type :member-simple}] :type :selector} {:members [{:group :type :value "A" :type :member-simple} {:group :class :value ".B" :type :member-simple}] :type :selector}] :declarations []}])) (testing "id selectors" ;; https://www.w3.org/TR/2018/REC-selectors-3-20181106/#id-selectors (deftransform-match "#A," "A#B," "*#A" "{}" [{:type :style-rule :selectors [{:members [{:group :identifier :value "#A" :type :member-simple}] :type :selector} {:members [{:group :type :value "A" :type :member-simple} {:group :identifier :value "#B" :type :member-simple}] :type :selector} {:members [{:group :type :value "*" :type :member-simple} {:group :identifier :value "#A" :type :member-simple}] :type :selector}] :declarations []}])) (testing "negation" ;; https://www.w3.org/TR/2018/REC-selectors-3-20181106/#negation (deftransform-match ":not(A)," "A:not(B)," "A|B:not(C):not(D)" "{}" [{:type :style-rule :selectors [{:members [{:selectors [{:members [{:group :type :value "A" :type :member-simple}] :type :selector}] :type :member-not}] :type :selector} {:members [{:group :type :value "A" :type :member-simple} {:selectors [{:members [{:group :type :value "B" :type :member-simple}] :type :selector}] :type :member-not}] :type :selector} {:members [{:group :type :value "A|" :type :member-simple} {:group :type :value "B" :type :member-simple} {:selectors [{:members [{:group :type :value "C" :type :member-simple}] :type :selector}] :type :member-not} {:selectors [{:members [{:group :type :value "D" :type :member-simple}] :type :selector}] :type :member-not}] :type :selector}] :declarations []}])) (testing "combinators" (deftransform-match "A B," "A>B," "A+B," "A~B" "{}" [{:type :style-rule :selectors [{:members [{:group :type :value "A" :type :member-simple} {:name " " :type :selector-combinator} {:group :type :value "B" :type :member-simple}] :type :selector} {:members [{:group :type :value "A" :type :member-simple} {:name ">" :type :selector-combinator} {:group :type :value "B" :type :member-simple}] :type :selector} {:members [{:group :type :value "A" :type :member-simple} {:name "+" :type :selector-combinator} {:group :type :value "B" :type :member-simple}] :type :selector} {:members [{:group :type :value "A" :type :member-simple} {:name "~" :type :selector-combinator} {:group :type :value "B" :type :member-simple}] :type :selector}] :declarations []}])) (testing "functions" (deftransform-match ":lang(en){}" [{:selectors [{:members [{:name ":lang(" :expression "en" :type :member-function}] :type :selector}] :declarations [] :type :style-rule}])) (testing "media-rule" (testing "query" (deftransform-match "@media screen{}" "@media not screen{}" "@media only screen{}" [{:rules [] :queries [{:not? false :only? false :medium "screen" :expressions [] :type :media-query}] :type :media-rule} {:rules [] :queries [{:not? true :only? false :medium "screen" :expressions [] :type :media-query}] :type :media-rule} {:rules [] :queries [{:not? false :only? true :medium "screen" :expressions [] :type :media-query}] :type :media-rule}])) (testing "expression" (deftransform-match "@media (min-width:100px){}" [{:rules [] :queries [{:not? false :only? false :medium nil :expressions [{:value "100px" :feature "min-width" :type :media-expression}] :type :media-query}] :type :media-rule}])) (testing "rules" (deftransform-match "@media screen{A{}}" "@media screen{@media screen{A{}}}" [{:rules [{:type :style-rule :selectors [{:members [{:group :type :value "A" :type :member-simple}], :type :selector}] :declarations []}] :queries [{:not? false :only? false :medium "screen" :expressions [] :type :media-query}] :type :media-rule} {:rules [{:rules [{:type :style-rule :selectors [{:members [{:group :type :value "A" :type :member-simple}] :type :selector}] :declarations []}] :queries [{:not? false :only? false :medium "screen" :expressions [] :type :media-query}] :type :media-rule}] :queries [{:not? false :only? false :medium "screen" :expressions [] :type :media-query}] :type :media-rule}]))) (testing "keyframes rule" (deftransform-match "@keyframes foo{from{}50%{}20%,80%{}to{}}" [{:declaration "@keyframes" :name "foo" :blocks [{:type :keyframes-block :selectors ["from"] :declarations []} {:type :keyframes-block :selectors ["50%"] :declarations []} {:type :keyframes-block :selectors ["20%" "80%"] :declarations []} {:type :keyframes-block :selectors ["to"] :declarations []}] :type :keyframes-rule}])) (testing "font-face-rule" (deftransform-match "@font-face{a:b}" [{:name "@font-face" :declarations [{:property "a" :expression "b" :important? false :type :declaration}] :type :font-face-rule}])) (testing "import rule" (deftransform-match "@import url(foo.css);\n" [{:location "foo.css" :queries [] :type :import-rule}]) (deftransform-match "@import url(foo.css) screen;\n" [{:location "foo.css" :queries [{:not? false :only? false :medium "screen" :expressions [] :type :media-query}] :type :import-rule}])) (testing "namespace rule" (deftransform-match "@namespace foo url(bar);\n" [{:prefix "foo" :url "bar" :type :namespace-rule}]) (deftransform-match "@namespace url(bar);\n" [{:prefix nil :url "bar" :type :namespace-rule}])) (testing "viewport rule" (deftransform-match "@viewport{a:b}" [{:name "@viewport" :declarations [{:property "a" :expression "b" :important? false :type :declaration}] :type :viewport-rule}])) (testing "page rule" (deftransform-match "@page :first{a:b}" [{:selectors [":first"] :declarations [{:property "a" :expression "b" :important? false :type :declaration}] :type :page-rule}])) (testing "support rule" (deftransform-match "@supports (a:b){A{c:d}}" [{:members [{:declaration {:property "a" :expression "b" :important? false :type :declaration} :type :condition-declaration}] :rules [{:selectors [{:members [{:value "A" :group :type :type :member-simple}] :type :selector}] :declarations [{:property "c" :expression "d" :important? false :type :declaration}] :type :style-rule}] :type :support-rule}]) (testing "negation" (deftransform-match "@supports not (a:b){A{c:d}}" [{:members [{:member {:declaration {:property "a" :expression "b" :important? false :type :declaration} :type :condition-declaration} :type :condition-negation}] :rules [{:selectors [{:members [{:value "A" :group :type :type :member-simple}] :type :selector}] :declarations [{:property "c" :expression "d" :important? false :type :declaration}] :type :style-rule}] :type :support-rule}])) (testing "nested" (deftransform-match "@supports ((a:b) or (c:d)){A{e:f}}" [{:members [{:members [{:declaration {:property "a" :expression "b" :important? false :type :declaration} :type :condition-declaration} {:name "or" :type :condition-operator} {:declaration {:property "c" :expression "d" :important? false :type :declaration} :type :condition-declaration}] :type :condition-nested}] :rules [{:selectors [{:members [{:value "A" :group :type :type :member-simple}] :type :selector}] :declarations [{:property "e" :expression "f" :important? false :type :declaration}] :type :style-rule}] :type :support-rule}]))))
[ { "context": "deftest users-api-test\n (let [new-user {:userid \"david\"\n :email \"d@av.id\"\n ", "end": 423, "score": 0.9976547956466675, "start": 418, "tag": "USERNAME", "value": "david" }, { "context": "w-user {:userid \"david\"\n :email \"d@av.id\"\n :name \"David Newuser\"}\n ", "end": 458, "score": 0.999864935874939, "start": 451, "tag": "EMAIL", "value": "d@av.id" }, { "context": " :email \"d@av.id\"\n :name \"David Newuser\"}\n userid (:userid new-user)]\n (testing", "end": 498, "score": 0.9997053146362305, "start": 485, "tag": "NAME", "value": "David Newuser" }, { "context": " assert-response-is-ok)\n (is (= {:userid \"david\"\n :email \"d@av.id\"\n :na", "end": 809, "score": 0.9958524107933044, "start": 804, "tag": "USERNAME", "value": "david" }, { "context": " (is (= {:userid \"david\"\n :email \"d@av.id\"\n :name \"David Newuser\"} (users/get-", "end": 840, "score": 0.9997290372848511, "start": 833, "tag": "EMAIL", "value": "d@av.id" }, { "context": " :email \"d@av.id\"\n :name \"David Newuser\"} (users/get-user userid))))\n\n (testing \"updat", "end": 876, "score": 0.9996946454048157, "start": 863, "tag": "NAME", "value": "David Newuser" }, { "context": " assert-response-is-ok)\n (is (= {:userid \"david\"\n :email \"new email\"\n :", "end": 1256, "score": 0.9649899005889893, "start": 1251, "tag": "USERNAME", "value": "david" }, { "context": "\"))\n (json-body {:userid \"test1\"\n :email \"tes", "end": 2148, "score": 0.9988020658493042, "start": 2143, "tag": "USERNAME", "value": "test1" }, { "context": "st1\"\n :email \"test1@example.com\"\n :name \"Test", "end": 2212, "score": 0.9999248385429382, "start": 2195, "tag": "EMAIL", "value": "test1@example.com" }, { "context": ".com\"\n :name \"Test 1\"})\n handler)]\n (is", "end": 2264, "score": 0.9987828731536865, "start": 2258, "tag": "NAME", "value": "Test 1" }, { "context": "\"))\n (json-body {:userid \"test1\"\n :email \"tes", "end": 2596, "score": 0.9980635643005371, "start": 2591, "tag": "USERNAME", "value": "test1" }, { "context": "st1\"\n :email \"test1@example.com\"\n :name \"Test", "end": 2660, "score": 0.9999253153800964, "start": 2643, "tag": "EMAIL", "value": "test1@example.com" }, { "context": ".com\"\n :name \"Test 1\"})\n (authenticate \"42\" \"a", "end": 2712, "score": 0.998643159866333, "start": 2706, "tag": "NAME", "value": "Test 1" }, { "context": "pi/users/create\"))\n (json-body {:userid \"test1\"\n :email \"test1@example.com\"", "end": 3178, "score": 0.9987773895263672, "start": 3173, "tag": "USERNAME", "value": "test1" }, { "context": "dy {:userid \"test1\"\n :email \"test1@example.com\"\n :name \"Test 1\"})\n ", "end": 3227, "score": 0.999924898147583, "start": 3210, "tag": "EMAIL", "value": "test1@example.com" }, { "context": " \"test1@example.com\"\n :name \"Test 1\"})\n (authenticate \"42\" \"user-owner\")\n ", "end": 3264, "score": 0.9988739490509033, "start": 3258, "tag": "NAME", "value": "Test 1" }, { "context": "pi/users/create\"))\n (json-body {:userid \"test2\"\n :email \"test2@example.com\"", "end": 3557, "score": 0.9942489862442017, "start": 3552, "tag": "USERNAME", "value": "test2" }, { "context": "dy {:userid \"test2\"\n :email \"test2@example.com\"\n :name \"Test 2\"})\n ", "end": 3606, "score": 0.9999257922172546, "start": 3589, "tag": "EMAIL", "value": "test2@example.com" }, { "context": " \"test2@example.com\"\n :name \"Test 2\"})\n (authenticate \"42\" \"user-owner\")\n ", "end": 3643, "score": 0.9989852905273438, "start": 3637, "tag": "NAME", "value": "Test 2" } ]
test/clj/rems/api/test_users.clj
juholehtonen/rems
0
(ns ^:integration rems.api.test-users (:require [clojure.test :refer :all] [rems.db.api-key :as api-key] [rems.db.roles :as roles] [rems.db.users :as users] [rems.handler :refer [handler]] [rems.api.testing :refer :all] [ring.mock.request :refer :all])) (use-fixtures :once api-fixture) (deftest users-api-test (let [new-user {:userid "david" :email "d@av.id" :name "David Newuser"} userid (:userid new-user)] (testing "create" (is (= nil (:name (users/get-user userid)))) (-> (request :post (str "/api/users/create")) (json-body new-user) (authenticate "42" "owner") handler assert-response-is-ok) (is (= {:userid "david" :email "d@av.id" :name "David Newuser"} (users/get-user userid)))) (testing "update (or, create is idempotent)" (-> (request :post (str "/api/users/create")) (json-body (assoc new-user :email "new email" :name "new name")) (authenticate "42" "owner") handler assert-response-is-ok) (is (= {:userid "david" :email "new email" :name "new name"} (users/get-user userid))))) (testing "create user with organization, without email" (let [userid "user-with-org"] (is (= nil (:name (users/get-user userid)))) (-> (request :post (str "/api/users/create")) (json-body {:userid userid :name "User Org" :email nil :organization "org"}) (authenticate "42" "owner") handler assert-response-is-ok) (is (= {:userid userid :email nil :name "User Org" :organization "org"} (users/get-user userid)))))) (deftest users-api-security-test (testing "without authentication" (testing "create" (let [response (-> (request :post (str "/api/users/create")) (json-body {:userid "test1" :email "test1@example.com" :name "Test 1"}) handler)] (is (response-is-unauthorized? response)) (is (= "Invalid anti-forgery token" (read-body response)))))) (testing "without owner role" (testing "create" (let [response (-> (request :post (str "/api/users/create")) (json-body {:userid "test1" :email "test1@example.com" :name "Test 1"}) (authenticate "42" "alice") handler)] (is (response-is-forbidden? response)) (is (= "forbidden" (read-body response)))))) (testing "user with user-owner role" (users/add-user! "user-owner" {:eppn "user-owner"}) (roles/add-role! "user-owner" :user-owner) (testing "with api key with all roles" (-> (request :post (str "/api/users/create")) (json-body {:userid "test1" :email "test1@example.com" :name "Test 1"}) (authenticate "42" "user-owner") handler assert-response-is-ok)) (testing "with api key with only user-owner role" (api-key/add-api-key! "999" "" [:user-owner]) (-> (request :post (str "/api/users/create")) (json-body {:userid "test2" :email "test2@example.com" :name "Test 2"}) (authenticate "42" "user-owner") handler assert-response-is-ok))))
108992
(ns ^:integration rems.api.test-users (:require [clojure.test :refer :all] [rems.db.api-key :as api-key] [rems.db.roles :as roles] [rems.db.users :as users] [rems.handler :refer [handler]] [rems.api.testing :refer :all] [ring.mock.request :refer :all])) (use-fixtures :once api-fixture) (deftest users-api-test (let [new-user {:userid "david" :email "<EMAIL>" :name "<NAME>"} userid (:userid new-user)] (testing "create" (is (= nil (:name (users/get-user userid)))) (-> (request :post (str "/api/users/create")) (json-body new-user) (authenticate "42" "owner") handler assert-response-is-ok) (is (= {:userid "david" :email "<EMAIL>" :name "<NAME>"} (users/get-user userid)))) (testing "update (or, create is idempotent)" (-> (request :post (str "/api/users/create")) (json-body (assoc new-user :email "new email" :name "new name")) (authenticate "42" "owner") handler assert-response-is-ok) (is (= {:userid "david" :email "new email" :name "new name"} (users/get-user userid))))) (testing "create user with organization, without email" (let [userid "user-with-org"] (is (= nil (:name (users/get-user userid)))) (-> (request :post (str "/api/users/create")) (json-body {:userid userid :name "User Org" :email nil :organization "org"}) (authenticate "42" "owner") handler assert-response-is-ok) (is (= {:userid userid :email nil :name "User Org" :organization "org"} (users/get-user userid)))))) (deftest users-api-security-test (testing "without authentication" (testing "create" (let [response (-> (request :post (str "/api/users/create")) (json-body {:userid "test1" :email "<EMAIL>" :name "<NAME>"}) handler)] (is (response-is-unauthorized? response)) (is (= "Invalid anti-forgery token" (read-body response)))))) (testing "without owner role" (testing "create" (let [response (-> (request :post (str "/api/users/create")) (json-body {:userid "test1" :email "<EMAIL>" :name "<NAME>"}) (authenticate "42" "alice") handler)] (is (response-is-forbidden? response)) (is (= "forbidden" (read-body response)))))) (testing "user with user-owner role" (users/add-user! "user-owner" {:eppn "user-owner"}) (roles/add-role! "user-owner" :user-owner) (testing "with api key with all roles" (-> (request :post (str "/api/users/create")) (json-body {:userid "test1" :email "<EMAIL>" :name "<NAME>"}) (authenticate "42" "user-owner") handler assert-response-is-ok)) (testing "with api key with only user-owner role" (api-key/add-api-key! "999" "" [:user-owner]) (-> (request :post (str "/api/users/create")) (json-body {:userid "test2" :email "<EMAIL>" :name "<NAME>"}) (authenticate "42" "user-owner") handler assert-response-is-ok))))
true
(ns ^:integration rems.api.test-users (:require [clojure.test :refer :all] [rems.db.api-key :as api-key] [rems.db.roles :as roles] [rems.db.users :as users] [rems.handler :refer [handler]] [rems.api.testing :refer :all] [ring.mock.request :refer :all])) (use-fixtures :once api-fixture) (deftest users-api-test (let [new-user {:userid "david" :email "PI:EMAIL:<EMAIL>END_PI" :name "PI:NAME:<NAME>END_PI"} userid (:userid new-user)] (testing "create" (is (= nil (:name (users/get-user userid)))) (-> (request :post (str "/api/users/create")) (json-body new-user) (authenticate "42" "owner") handler assert-response-is-ok) (is (= {:userid "david" :email "PI:EMAIL:<EMAIL>END_PI" :name "PI:NAME:<NAME>END_PI"} (users/get-user userid)))) (testing "update (or, create is idempotent)" (-> (request :post (str "/api/users/create")) (json-body (assoc new-user :email "new email" :name "new name")) (authenticate "42" "owner") handler assert-response-is-ok) (is (= {:userid "david" :email "new email" :name "new name"} (users/get-user userid))))) (testing "create user with organization, without email" (let [userid "user-with-org"] (is (= nil (:name (users/get-user userid)))) (-> (request :post (str "/api/users/create")) (json-body {:userid userid :name "User Org" :email nil :organization "org"}) (authenticate "42" "owner") handler assert-response-is-ok) (is (= {:userid userid :email nil :name "User Org" :organization "org"} (users/get-user userid)))))) (deftest users-api-security-test (testing "without authentication" (testing "create" (let [response (-> (request :post (str "/api/users/create")) (json-body {:userid "test1" :email "PI:EMAIL:<EMAIL>END_PI" :name "PI:NAME:<NAME>END_PI"}) handler)] (is (response-is-unauthorized? response)) (is (= "Invalid anti-forgery token" (read-body response)))))) (testing "without owner role" (testing "create" (let [response (-> (request :post (str "/api/users/create")) (json-body {:userid "test1" :email "PI:EMAIL:<EMAIL>END_PI" :name "PI:NAME:<NAME>END_PI"}) (authenticate "42" "alice") handler)] (is (response-is-forbidden? response)) (is (= "forbidden" (read-body response)))))) (testing "user with user-owner role" (users/add-user! "user-owner" {:eppn "user-owner"}) (roles/add-role! "user-owner" :user-owner) (testing "with api key with all roles" (-> (request :post (str "/api/users/create")) (json-body {:userid "test1" :email "PI:EMAIL:<EMAIL>END_PI" :name "PI:NAME:<NAME>END_PI"}) (authenticate "42" "user-owner") handler assert-response-is-ok)) (testing "with api key with only user-owner role" (api-key/add-api-key! "999" "" [:user-owner]) (-> (request :post (str "/api/users/create")) (json-body {:userid "test2" :email "PI:EMAIL:<EMAIL>END_PI" :name "PI:NAME:<NAME>END_PI"}) (authenticate "42" "user-owner") handler assert-response-is-ok))))
[ { "context": "-in? false})\n\n(def initial-fun-people\n [{:name \"Bill\" :reason \"he likes to party\"}\n {:name \"Billy\" ", "end": 786, "score": 0.999817430973053, "start": 782, "tag": "NAME", "value": "Bill" }, { "context": "e \"Bill\" :reason \"he likes to party\"}\n {:name \"Billy\" :reason \"he parties harder than Bill\"}\n {:nam", "end": 834, "score": 0.9964926242828369, "start": 829, "tag": "NAME", "value": "Billy" }, { "context": " {:name \"Billy\" :reason \"he parties harder than Bill\"}\n {:name \"William\" :reason \"he doesn't party ", "end": 872, "score": 0.9997636079788208, "start": 868, "tag": "NAME", "value": "Bill" }, { "context": "reason \"he parties harder than Bill\"}\n {:name \"William\" :reason \"he doesn't party at all\"}])\n\n(def initi", "end": 894, "score": 0.9957935810089111, "start": 887, "tag": "NAME", "value": "William" } ]
src-cljs/com/oakmac/react_state_examples/root.cljs
oakmac/react-state-examples
2
(ns com.oakmac.react-state-examples.root (:require [com.oakmac.react-state-examples.fun-people :as fun-people :refer [FunPeople]] [com.oakmac.react-state-examples.hello-react :as hello-react :refer [HelloReact]] [com.oakmac.react-state-examples.login-form :as login-form :refer [LoginForm]] [com.oakmac.react-state-examples.lorem-ipsum :as lorem-ipsum :refer [LoremIpsum]] [com.oakmac.react-state-examples.tabs :as tabs :refer [Tabs]] [re-frame.core :as rf] [taoensso.timbre :as timbre])) ;; ----------------------------------------------------------------------------- ;; App Db (def initial-login-form {:error-msg nil :info-msg nil :loading? false :password "" :username "" :logged-in? false}) (def initial-fun-people [{:name "Bill" :reason "he likes to party"} {:name "Billy" :reason "he parties harder than Bill"} {:name "William" :reason "he doesn't party at all"}]) (def initial-app-db {; :active-tab-id "TAB_HELLO_REACT" :login-form initial-login-form :fun-people initial-fun-people :reason-field "" :name-field ""}) ;; ----------------------------------------------------------------------------- ;; Events (rf/reg-event-fx :global-init (fn [_ _] {:db initial-app-db :fx [[:dispatch [::tabs/init]] [:dispatch [::lorem-ipsum/init]]]})) ; [:dispatch [::login-form/init]] ; [:dispatch [::fun-people/init]]]})) ;; TODO: clock component ; (defn Clock [] ; [:section.content ; [:h1.title "Clock"] ; [:div.box ; "09:12:24"]]) ;; ----------------------------------------------------------------------------- ;; Views (defn App "the Root component" [] (let [active-tab-id @(rf/subscribe [::tabs/active-tab-id])] [:section.section [:div.container [Tabs] (case active-tab-id "TAB_HELLO_REACT" [HelloReact] "TAB_LOREM_IPSUM" [LoremIpsum] ; "TAB_CLOCK" [Clock] "TAB_LOGIN_FORM" [LoginForm] "TAB_FUN_PEOPLE" [FunPeople] (timbre/warn "Unknown tab-id:" active-tab-id))]]))
123928
(ns com.oakmac.react-state-examples.root (:require [com.oakmac.react-state-examples.fun-people :as fun-people :refer [FunPeople]] [com.oakmac.react-state-examples.hello-react :as hello-react :refer [HelloReact]] [com.oakmac.react-state-examples.login-form :as login-form :refer [LoginForm]] [com.oakmac.react-state-examples.lorem-ipsum :as lorem-ipsum :refer [LoremIpsum]] [com.oakmac.react-state-examples.tabs :as tabs :refer [Tabs]] [re-frame.core :as rf] [taoensso.timbre :as timbre])) ;; ----------------------------------------------------------------------------- ;; App Db (def initial-login-form {:error-msg nil :info-msg nil :loading? false :password "" :username "" :logged-in? false}) (def initial-fun-people [{:name "<NAME>" :reason "he likes to party"} {:name "<NAME>" :reason "he parties harder than <NAME>"} {:name "<NAME>" :reason "he doesn't party at all"}]) (def initial-app-db {; :active-tab-id "TAB_HELLO_REACT" :login-form initial-login-form :fun-people initial-fun-people :reason-field "" :name-field ""}) ;; ----------------------------------------------------------------------------- ;; Events (rf/reg-event-fx :global-init (fn [_ _] {:db initial-app-db :fx [[:dispatch [::tabs/init]] [:dispatch [::lorem-ipsum/init]]]})) ; [:dispatch [::login-form/init]] ; [:dispatch [::fun-people/init]]]})) ;; TODO: clock component ; (defn Clock [] ; [:section.content ; [:h1.title "Clock"] ; [:div.box ; "09:12:24"]]) ;; ----------------------------------------------------------------------------- ;; Views (defn App "the Root component" [] (let [active-tab-id @(rf/subscribe [::tabs/active-tab-id])] [:section.section [:div.container [Tabs] (case active-tab-id "TAB_HELLO_REACT" [HelloReact] "TAB_LOREM_IPSUM" [LoremIpsum] ; "TAB_CLOCK" [Clock] "TAB_LOGIN_FORM" [LoginForm] "TAB_FUN_PEOPLE" [FunPeople] (timbre/warn "Unknown tab-id:" active-tab-id))]]))
true
(ns com.oakmac.react-state-examples.root (:require [com.oakmac.react-state-examples.fun-people :as fun-people :refer [FunPeople]] [com.oakmac.react-state-examples.hello-react :as hello-react :refer [HelloReact]] [com.oakmac.react-state-examples.login-form :as login-form :refer [LoginForm]] [com.oakmac.react-state-examples.lorem-ipsum :as lorem-ipsum :refer [LoremIpsum]] [com.oakmac.react-state-examples.tabs :as tabs :refer [Tabs]] [re-frame.core :as rf] [taoensso.timbre :as timbre])) ;; ----------------------------------------------------------------------------- ;; App Db (def initial-login-form {:error-msg nil :info-msg nil :loading? false :password "" :username "" :logged-in? false}) (def initial-fun-people [{:name "PI:NAME:<NAME>END_PI" :reason "he likes to party"} {:name "PI:NAME:<NAME>END_PI" :reason "he parties harder than PI:NAME:<NAME>END_PI"} {:name "PI:NAME:<NAME>END_PI" :reason "he doesn't party at all"}]) (def initial-app-db {; :active-tab-id "TAB_HELLO_REACT" :login-form initial-login-form :fun-people initial-fun-people :reason-field "" :name-field ""}) ;; ----------------------------------------------------------------------------- ;; Events (rf/reg-event-fx :global-init (fn [_ _] {:db initial-app-db :fx [[:dispatch [::tabs/init]] [:dispatch [::lorem-ipsum/init]]]})) ; [:dispatch [::login-form/init]] ; [:dispatch [::fun-people/init]]]})) ;; TODO: clock component ; (defn Clock [] ; [:section.content ; [:h1.title "Clock"] ; [:div.box ; "09:12:24"]]) ;; ----------------------------------------------------------------------------- ;; Views (defn App "the Root component" [] (let [active-tab-id @(rf/subscribe [::tabs/active-tab-id])] [:section.section [:div.container [Tabs] (case active-tab-id "TAB_HELLO_REACT" [HelloReact] "TAB_LOREM_IPSUM" [LoremIpsum] ; "TAB_CLOCK" [Clock] "TAB_LOGIN_FORM" [LoginForm] "TAB_FUN_PEOPLE" [FunPeople] (timbre/warn "Unknown tab-id:" active-tab-id))]]))
[ { "context": "t can be done on two expressions.\"\n :author \"Sean Dawson\"}\n nanoweave.parsers.binary-other\n (:require [bl", "end": 108, "score": 0.9998310208320618, "start": 97, "tag": "NAME", "value": "Sean Dawson" } ]
src/nanoweave/parsers/binary_other.clj
NoxHarmonium/nanoweave
0
(ns ^{:doc "Parses miscellaneous operations that can be done on two expressions." :author "Sean Dawson"} nanoweave.parsers.binary-other (:require [blancas.kern.core :refer [bind <?> return]] [blancas.kern.lexer.java-style :refer [dot token]] [nanoweave.ast.binary-other :refer [->DotOp ->ConcatOp ->OpenRangeOp ->ClosedRangeOp]])) ; Other Binary Operators (def dot-op "Access operator: extract value from object." (<?> (bind [_ dot] (return ->DotOp)) "property accessor (.)")) (def concat-op "Parses one of the relational operators." (<?> (bind [_ (token "++")] (return ->ConcatOp)) "concat operator (++)")) (def open-range-op "Parses an open range expression." (<?> (bind [_ (token "until")] (return ->OpenRangeOp)) "open range expression (until)")) (def closed-range-op "Parses an closed range expression." (<?> (bind [_ (token "to")] (return ->ClosedRangeOp)) "closed range expression (to)"))
97758
(ns ^{:doc "Parses miscellaneous operations that can be done on two expressions." :author "<NAME>"} nanoweave.parsers.binary-other (:require [blancas.kern.core :refer [bind <?> return]] [blancas.kern.lexer.java-style :refer [dot token]] [nanoweave.ast.binary-other :refer [->DotOp ->ConcatOp ->OpenRangeOp ->ClosedRangeOp]])) ; Other Binary Operators (def dot-op "Access operator: extract value from object." (<?> (bind [_ dot] (return ->DotOp)) "property accessor (.)")) (def concat-op "Parses one of the relational operators." (<?> (bind [_ (token "++")] (return ->ConcatOp)) "concat operator (++)")) (def open-range-op "Parses an open range expression." (<?> (bind [_ (token "until")] (return ->OpenRangeOp)) "open range expression (until)")) (def closed-range-op "Parses an closed range expression." (<?> (bind [_ (token "to")] (return ->ClosedRangeOp)) "closed range expression (to)"))
true
(ns ^{:doc "Parses miscellaneous operations that can be done on two expressions." :author "PI:NAME:<NAME>END_PI"} nanoweave.parsers.binary-other (:require [blancas.kern.core :refer [bind <?> return]] [blancas.kern.lexer.java-style :refer [dot token]] [nanoweave.ast.binary-other :refer [->DotOp ->ConcatOp ->OpenRangeOp ->ClosedRangeOp]])) ; Other Binary Operators (def dot-op "Access operator: extract value from object." (<?> (bind [_ dot] (return ->DotOp)) "property accessor (.)")) (def concat-op "Parses one of the relational operators." (<?> (bind [_ (token "++")] (return ->ConcatOp)) "concat operator (++)")) (def open-range-op "Parses an open range expression." (<?> (bind [_ (token "until")] (return ->OpenRangeOp)) "open range expression (until)")) (def closed-range-op "Parses an closed range expression." (<?> (bind [_ (token "to")] (return ->ClosedRangeOp)) "closed range expression (to)"))
[ { "context": "r-root-name \"admin\")\r\n(def manager-root-password \"test\")\r\n\r\n(def web-http-url (str host \"/\"))\r\n(def web-", "end": 372, "score": 0.9993201494216919, "start": 368, "tag": "PASSWORD", "value": "test" }, { "context": "orm-params {:login_name user-name :login_password en-password :csrf csrf}\r\n :cookie-store ", "end": 1338, "score": 0.9378741383552551, "start": 1336, "tag": "PASSWORD", "value": "en" }, { "context": "gin manager-root-name (str manager-root-password \"1\"))]\r\n (fact \"Login Request?\"\r\n ", "end": 1785, "score": 0.9972758889198303, "start": 1784, "tag": "PASSWORD", "value": "1" } ]
test/kaleido/core_test.clj
PranceCloud/Kaleido
0
(ns kaleido.core-test (:use midje.sweet digest) (:require [clojure.test :refer :all] [kaleido.core :refer :all] [cheshire.core :refer :all] [kaleido.setting :refer :all] [clj-http.client :as client])) (def host "http://127.0.0.1:3000") (def manager-root-name "admin") (def manager-root-password "test") (def web-http-url (str host "/")) (def web-csrf-url (str host "/csrf")) (def manager-test-url (str host manager-url)) (def manager-auth-test-url (str host manager-url "/auth/login")) (def project-test-url (str host manager-url "/projects")) (deftest web-http-test (fact (str "Web Server " web-http-url) (let [g (client/get web-http-url)] (:status g) => 200))) (defn get-csrf [c] (let [c (client/get web-csrf-url {:cookie-store c})] (:csrf (parse-string (:body c) true)))) (defn parse-json-string [s] (parse-string s true)) (defn system-auth-login [user-name user-password] (let [my-cs (clj-http.cookies/cookie-store) csrf (get-csrf my-cs) en-password (digest/md5 (str (digest/md5 user-password) csrf)) g (client/post manager-auth-test-url {:headers {"X-CSRF-Token" csrf} :form-params {:login_name user-name :login_password en-password :csrf csrf} :cookie-store my-cs})] g)) (deftest csrf-test (let [my-cs (clj-http.cookies/cookie-store) csrf (get-csrf my-cs)] (is (> (count (str csrf)) 10)))) (deftest manager-auth-test (fact "Manager Auth Login" (let [right-login (system-auth-login manager-root-name manager-root-password) bad-login (system-auth-login manager-root-name (str manager-root-password "1"))] (fact "Login Request?" (:status right-login) => 200 => true) (fact "Login Right Success?" (:status (parse-json-string (:body right-login))) => true) (fact "Login Bad Success?" (:status (parse-json-string (:body bad-login))) => false) ))) (deftest manager-test (fact (str "Manager Root " manager-test-url) (let [g (client/get manager-test-url)] (:status g) => 200))) (deftest project-test (fact (str "Project Root " host project-test-url) (let [g (client/get project-test-url)] (:status g) => 200)))
8400
(ns kaleido.core-test (:use midje.sweet digest) (:require [clojure.test :refer :all] [kaleido.core :refer :all] [cheshire.core :refer :all] [kaleido.setting :refer :all] [clj-http.client :as client])) (def host "http://127.0.0.1:3000") (def manager-root-name "admin") (def manager-root-password "<PASSWORD>") (def web-http-url (str host "/")) (def web-csrf-url (str host "/csrf")) (def manager-test-url (str host manager-url)) (def manager-auth-test-url (str host manager-url "/auth/login")) (def project-test-url (str host manager-url "/projects")) (deftest web-http-test (fact (str "Web Server " web-http-url) (let [g (client/get web-http-url)] (:status g) => 200))) (defn get-csrf [c] (let [c (client/get web-csrf-url {:cookie-store c})] (:csrf (parse-string (:body c) true)))) (defn parse-json-string [s] (parse-string s true)) (defn system-auth-login [user-name user-password] (let [my-cs (clj-http.cookies/cookie-store) csrf (get-csrf my-cs) en-password (digest/md5 (str (digest/md5 user-password) csrf)) g (client/post manager-auth-test-url {:headers {"X-CSRF-Token" csrf} :form-params {:login_name user-name :login_password <PASSWORD>-password :csrf csrf} :cookie-store my-cs})] g)) (deftest csrf-test (let [my-cs (clj-http.cookies/cookie-store) csrf (get-csrf my-cs)] (is (> (count (str csrf)) 10)))) (deftest manager-auth-test (fact "Manager Auth Login" (let [right-login (system-auth-login manager-root-name manager-root-password) bad-login (system-auth-login manager-root-name (str manager-root-password "<PASSWORD>"))] (fact "Login Request?" (:status right-login) => 200 => true) (fact "Login Right Success?" (:status (parse-json-string (:body right-login))) => true) (fact "Login Bad Success?" (:status (parse-json-string (:body bad-login))) => false) ))) (deftest manager-test (fact (str "Manager Root " manager-test-url) (let [g (client/get manager-test-url)] (:status g) => 200))) (deftest project-test (fact (str "Project Root " host project-test-url) (let [g (client/get project-test-url)] (:status g) => 200)))
true
(ns kaleido.core-test (:use midje.sweet digest) (:require [clojure.test :refer :all] [kaleido.core :refer :all] [cheshire.core :refer :all] [kaleido.setting :refer :all] [clj-http.client :as client])) (def host "http://127.0.0.1:3000") (def manager-root-name "admin") (def manager-root-password "PI:PASSWORD:<PASSWORD>END_PI") (def web-http-url (str host "/")) (def web-csrf-url (str host "/csrf")) (def manager-test-url (str host manager-url)) (def manager-auth-test-url (str host manager-url "/auth/login")) (def project-test-url (str host manager-url "/projects")) (deftest web-http-test (fact (str "Web Server " web-http-url) (let [g (client/get web-http-url)] (:status g) => 200))) (defn get-csrf [c] (let [c (client/get web-csrf-url {:cookie-store c})] (:csrf (parse-string (:body c) true)))) (defn parse-json-string [s] (parse-string s true)) (defn system-auth-login [user-name user-password] (let [my-cs (clj-http.cookies/cookie-store) csrf (get-csrf my-cs) en-password (digest/md5 (str (digest/md5 user-password) csrf)) g (client/post manager-auth-test-url {:headers {"X-CSRF-Token" csrf} :form-params {:login_name user-name :login_password PI:PASSWORD:<PASSWORD>END_PI-password :csrf csrf} :cookie-store my-cs})] g)) (deftest csrf-test (let [my-cs (clj-http.cookies/cookie-store) csrf (get-csrf my-cs)] (is (> (count (str csrf)) 10)))) (deftest manager-auth-test (fact "Manager Auth Login" (let [right-login (system-auth-login manager-root-name manager-root-password) bad-login (system-auth-login manager-root-name (str manager-root-password "PI:PASSWORD:<PASSWORD>END_PI"))] (fact "Login Request?" (:status right-login) => 200 => true) (fact "Login Right Success?" (:status (parse-json-string (:body right-login))) => true) (fact "Login Bad Success?" (:status (parse-json-string (:body bad-login))) => false) ))) (deftest manager-test (fact (str "Manager Root " manager-test-url) (let [g (client/get manager-test-url)] (:status g) => 200))) (deftest project-test (fact (str "Project Root " host project-test-url) (let [g (client/get project-test-url)] (:status g) => 200)))
[ { "context": " })\n\n(def card {\n :name \"Google Docs Assist\",\n\n\n :header {\n ", "end": 1413, "score": 0.8418382406234741, "start": 1395, "tag": "NAME", "value": "Google Docs Assist" } ]
hub-google-docs-connector/src/main/resources/config.clj
vmware/connectors-workspace-one
17
;; Copyright © 2020 VMware, Inc. All Rights Reserved. ;; SPDX-License-Identifier: BSD-2-Clause (def input identity) (defn get-collaborators-string [rec] (def collaborators (get rec "users" [])) (clojure.string/join ", " collaborators)) (defn get_author_name [rec] (def author (get rec "author")) (get author "displayName")) (def tenant-admin-filter (fn [x] true)) (def output { :updated-at (fn* [p1__1009#] (get p1__1009# "modifiedDate")), :doc-title (fn* [p1__1008#] (get p1__1008# "fileTitle")), :doc-link (fn* [p1__1011#] (get p1__1011# "link")), :updated-by get_author_name, :collaborators get-collaborators-string, :reply-url (fn* [p1__1012#] (format "/comment/%s/reply" (get p1__1012# "commentId"))), :post-comment-url (fn* [p1__1014#] (format "/doc/%s/appendText" (get p1__1014# "docId"))), :id (fn* [p1__1005#] (get p1__1005# "uniqueId")), :comment (fn* [p1__1010#] (get p1__1010# "content")), :add-user-url (fn* [p1__1013#] (format "/doc/%s/addUser" (get p1__1013# "docId"))), :doc-id (fn* [p1__1007#] (get p1__1007# "docId")), :comment-id (fn* [p1__1006#] (get p1__1006# "commentId")) }) (def card { :name "Google Docs Assist", :header { :title "Google Doc - New mention", :subtitle ["You have been mentioned in" :doc-title], :links {:title "", :subtitle ["" :doc-link] } }, :backend_id :id, :image_url "https://vmw-mf-assets.s3.amazonaws.com/connector-images/hub-google-docs.png", :body [ [:comment "Comment"] [:updated-by "From"] [:updated-at "Date"] [:doc-title "File Name"] [:doc-id "Document ID"] [:collaborators "Collaborators"] ], :actions [{:allow-repeated true, :remove-card-on-completion true, :completed-label "Replied", :http-type :post, :primary true, :mutually-exclusive-id "ACT_ON_REPLY", :label "Reply", :url :reply-url, :user-input-field {:water-mark "Enter the Reply Text", :min-length 1 }, :action-key "USER_INPUT", :request-params {"document" :entire}} {:allow-repeated true, :remove-card-on-completion true, :completed-label "User Added", :http-type :post, :primary false, :mutually-exclusive-id "ACT_ON_USER", :label "Invite collaborator", :url :add-user-url, :user-input-field {:water-mark "Enter the Invitee mail id", :min-length 1 }, :action-key "USER_INPUT", :request-params {"document" :entire}}], :all-actions [{:allow-repeated true, :remove-card-on-completion true, :completed-label "Replied", :http-type :post, :primary true, :mutually-exclusive-id "ACT_ON_REPLY", :label "Reply", :url :reply-url, :user-input-field {:water-mark "Enter the Reply Text", :min-length 1 }, :action-key "USER_INPUT", :request-params {"document" :entire}} {:allow-repeated false, :remove-card-on-completion true, :completed-label "User Added", :http-type :post, :primary true, :mutually-exclusive-id "ACT_ON_USER", :label "Add User", :url :add-user-url, :user-input-field {:water-mark "Enter the Invitee mail id", :min-length 1 }, :action-key "USER_INPUT", :request-params {"document" :entire} } ] } )
124953
;; Copyright © 2020 VMware, Inc. All Rights Reserved. ;; SPDX-License-Identifier: BSD-2-Clause (def input identity) (defn get-collaborators-string [rec] (def collaborators (get rec "users" [])) (clojure.string/join ", " collaborators)) (defn get_author_name [rec] (def author (get rec "author")) (get author "displayName")) (def tenant-admin-filter (fn [x] true)) (def output { :updated-at (fn* [p1__1009#] (get p1__1009# "modifiedDate")), :doc-title (fn* [p1__1008#] (get p1__1008# "fileTitle")), :doc-link (fn* [p1__1011#] (get p1__1011# "link")), :updated-by get_author_name, :collaborators get-collaborators-string, :reply-url (fn* [p1__1012#] (format "/comment/%s/reply" (get p1__1012# "commentId"))), :post-comment-url (fn* [p1__1014#] (format "/doc/%s/appendText" (get p1__1014# "docId"))), :id (fn* [p1__1005#] (get p1__1005# "uniqueId")), :comment (fn* [p1__1010#] (get p1__1010# "content")), :add-user-url (fn* [p1__1013#] (format "/doc/%s/addUser" (get p1__1013# "docId"))), :doc-id (fn* [p1__1007#] (get p1__1007# "docId")), :comment-id (fn* [p1__1006#] (get p1__1006# "commentId")) }) (def card { :name "<NAME>", :header { :title "Google Doc - New mention", :subtitle ["You have been mentioned in" :doc-title], :links {:title "", :subtitle ["" :doc-link] } }, :backend_id :id, :image_url "https://vmw-mf-assets.s3.amazonaws.com/connector-images/hub-google-docs.png", :body [ [:comment "Comment"] [:updated-by "From"] [:updated-at "Date"] [:doc-title "File Name"] [:doc-id "Document ID"] [:collaborators "Collaborators"] ], :actions [{:allow-repeated true, :remove-card-on-completion true, :completed-label "Replied", :http-type :post, :primary true, :mutually-exclusive-id "ACT_ON_REPLY", :label "Reply", :url :reply-url, :user-input-field {:water-mark "Enter the Reply Text", :min-length 1 }, :action-key "USER_INPUT", :request-params {"document" :entire}} {:allow-repeated true, :remove-card-on-completion true, :completed-label "User Added", :http-type :post, :primary false, :mutually-exclusive-id "ACT_ON_USER", :label "Invite collaborator", :url :add-user-url, :user-input-field {:water-mark "Enter the Invitee mail id", :min-length 1 }, :action-key "USER_INPUT", :request-params {"document" :entire}}], :all-actions [{:allow-repeated true, :remove-card-on-completion true, :completed-label "Replied", :http-type :post, :primary true, :mutually-exclusive-id "ACT_ON_REPLY", :label "Reply", :url :reply-url, :user-input-field {:water-mark "Enter the Reply Text", :min-length 1 }, :action-key "USER_INPUT", :request-params {"document" :entire}} {:allow-repeated false, :remove-card-on-completion true, :completed-label "User Added", :http-type :post, :primary true, :mutually-exclusive-id "ACT_ON_USER", :label "Add User", :url :add-user-url, :user-input-field {:water-mark "Enter the Invitee mail id", :min-length 1 }, :action-key "USER_INPUT", :request-params {"document" :entire} } ] } )
true
;; Copyright © 2020 VMware, Inc. All Rights Reserved. ;; SPDX-License-Identifier: BSD-2-Clause (def input identity) (defn get-collaborators-string [rec] (def collaborators (get rec "users" [])) (clojure.string/join ", " collaborators)) (defn get_author_name [rec] (def author (get rec "author")) (get author "displayName")) (def tenant-admin-filter (fn [x] true)) (def output { :updated-at (fn* [p1__1009#] (get p1__1009# "modifiedDate")), :doc-title (fn* [p1__1008#] (get p1__1008# "fileTitle")), :doc-link (fn* [p1__1011#] (get p1__1011# "link")), :updated-by get_author_name, :collaborators get-collaborators-string, :reply-url (fn* [p1__1012#] (format "/comment/%s/reply" (get p1__1012# "commentId"))), :post-comment-url (fn* [p1__1014#] (format "/doc/%s/appendText" (get p1__1014# "docId"))), :id (fn* [p1__1005#] (get p1__1005# "uniqueId")), :comment (fn* [p1__1010#] (get p1__1010# "content")), :add-user-url (fn* [p1__1013#] (format "/doc/%s/addUser" (get p1__1013# "docId"))), :doc-id (fn* [p1__1007#] (get p1__1007# "docId")), :comment-id (fn* [p1__1006#] (get p1__1006# "commentId")) }) (def card { :name "PI:NAME:<NAME>END_PI", :header { :title "Google Doc - New mention", :subtitle ["You have been mentioned in" :doc-title], :links {:title "", :subtitle ["" :doc-link] } }, :backend_id :id, :image_url "https://vmw-mf-assets.s3.amazonaws.com/connector-images/hub-google-docs.png", :body [ [:comment "Comment"] [:updated-by "From"] [:updated-at "Date"] [:doc-title "File Name"] [:doc-id "Document ID"] [:collaborators "Collaborators"] ], :actions [{:allow-repeated true, :remove-card-on-completion true, :completed-label "Replied", :http-type :post, :primary true, :mutually-exclusive-id "ACT_ON_REPLY", :label "Reply", :url :reply-url, :user-input-field {:water-mark "Enter the Reply Text", :min-length 1 }, :action-key "USER_INPUT", :request-params {"document" :entire}} {:allow-repeated true, :remove-card-on-completion true, :completed-label "User Added", :http-type :post, :primary false, :mutually-exclusive-id "ACT_ON_USER", :label "Invite collaborator", :url :add-user-url, :user-input-field {:water-mark "Enter the Invitee mail id", :min-length 1 }, :action-key "USER_INPUT", :request-params {"document" :entire}}], :all-actions [{:allow-repeated true, :remove-card-on-completion true, :completed-label "Replied", :http-type :post, :primary true, :mutually-exclusive-id "ACT_ON_REPLY", :label "Reply", :url :reply-url, :user-input-field {:water-mark "Enter the Reply Text", :min-length 1 }, :action-key "USER_INPUT", :request-params {"document" :entire}} {:allow-repeated false, :remove-card-on-completion true, :completed-label "User Added", :http-type :post, :primary true, :mutually-exclusive-id "ACT_ON_USER", :label "Add User", :url :add-user-url, :user-input-field {:water-mark "Enter the Invitee mail id", :min-length 1 }, :action-key "USER_INPUT", :request-params {"document" :entire} } ] } )
[ { "context": ";; Copyright (c) 2015, Dmitry Kozlov <kozlov.dmitry.a@gmail.com>\n;; Code is published ", "end": 36, "score": 0.9998695254325867, "start": 23, "tag": "NAME", "value": "Dmitry Kozlov" }, { "context": ";; Copyright (c) 2015, Dmitry Kozlov <kozlov.dmitry.a@gmail.com>\n;; Code is published under BSD 2-clause license.", "end": 63, "score": 0.9999323487281799, "start": 38, "tag": "EMAIL", "value": "kozlov.dmitry.a@gmail.com" } ]
src/illya/orientdb/schema.clj
dkz/illya
2
;; Copyright (c) 2015, Dmitry Kozlov <kozlov.dmitry.a@gmail.com> ;; Code is published under BSD 2-clause license. (ns illya.orientdb.schema (:require [cats.core :as cats] [illya.orientdb.dsl :as ograph] [illya.orientdb.migration :as migration])) (def configuration (migration/config ((migration/version 1) (cats/mlet [message (ograph/create-vertex-type! :Message {"created-date" :date "is-hidden" :boolean "number" :long "title" :string "contents" :string}) message-board (ograph/create-vertex-type! :MessageBoard {"name" :string "message-counter" :long}) message-thread (ograph/create-vertex-type! :MessageThread {"message" :link "board" :link "updated-date" :date})] (cats/>> (ograph/create-edge-type! :PostedOn {}) (ograph/create-edge-type! :PostedTo {}) (ograph/set-outgoing-edge! message :PostedTo) (ograph/set-incoming-edge! message-thread :PostedTo) (ograph/set-outgoing-edge! message-thread :PostedOn) (ograph/set-incoming-edge! message-board :PostedOn) (ograph/create-vertex! :MessageBoard {"name" "a" "message-counter" 0}) (ograph/create-vertex! :MessageBoard {"name" "c" "message-counter" 0})))) ((migration/version 2) (cats/mlet [message (ograph/vertex-type :Message) board (ograph/vertex-type :MessageBoard)] (cats/>> (ograph/create-edge-type! :BelongsTo {}) (ograph/set-outgoing-edge! message :BelongsTo) (ograph/set-incoming-edge! board :BelongsTo)))) ((migration/version 3) (cats/mlet [message (ograph/vertex-type :Message)] (ograph/create-properties! message {"ip" :string})))))
80311
;; Copyright (c) 2015, <NAME> <<EMAIL>> ;; Code is published under BSD 2-clause license. (ns illya.orientdb.schema (:require [cats.core :as cats] [illya.orientdb.dsl :as ograph] [illya.orientdb.migration :as migration])) (def configuration (migration/config ((migration/version 1) (cats/mlet [message (ograph/create-vertex-type! :Message {"created-date" :date "is-hidden" :boolean "number" :long "title" :string "contents" :string}) message-board (ograph/create-vertex-type! :MessageBoard {"name" :string "message-counter" :long}) message-thread (ograph/create-vertex-type! :MessageThread {"message" :link "board" :link "updated-date" :date})] (cats/>> (ograph/create-edge-type! :PostedOn {}) (ograph/create-edge-type! :PostedTo {}) (ograph/set-outgoing-edge! message :PostedTo) (ograph/set-incoming-edge! message-thread :PostedTo) (ograph/set-outgoing-edge! message-thread :PostedOn) (ograph/set-incoming-edge! message-board :PostedOn) (ograph/create-vertex! :MessageBoard {"name" "a" "message-counter" 0}) (ograph/create-vertex! :MessageBoard {"name" "c" "message-counter" 0})))) ((migration/version 2) (cats/mlet [message (ograph/vertex-type :Message) board (ograph/vertex-type :MessageBoard)] (cats/>> (ograph/create-edge-type! :BelongsTo {}) (ograph/set-outgoing-edge! message :BelongsTo) (ograph/set-incoming-edge! board :BelongsTo)))) ((migration/version 3) (cats/mlet [message (ograph/vertex-type :Message)] (ograph/create-properties! message {"ip" :string})))))
true
;; Copyright (c) 2015, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ;; Code is published under BSD 2-clause license. (ns illya.orientdb.schema (:require [cats.core :as cats] [illya.orientdb.dsl :as ograph] [illya.orientdb.migration :as migration])) (def configuration (migration/config ((migration/version 1) (cats/mlet [message (ograph/create-vertex-type! :Message {"created-date" :date "is-hidden" :boolean "number" :long "title" :string "contents" :string}) message-board (ograph/create-vertex-type! :MessageBoard {"name" :string "message-counter" :long}) message-thread (ograph/create-vertex-type! :MessageThread {"message" :link "board" :link "updated-date" :date})] (cats/>> (ograph/create-edge-type! :PostedOn {}) (ograph/create-edge-type! :PostedTo {}) (ograph/set-outgoing-edge! message :PostedTo) (ograph/set-incoming-edge! message-thread :PostedTo) (ograph/set-outgoing-edge! message-thread :PostedOn) (ograph/set-incoming-edge! message-board :PostedOn) (ograph/create-vertex! :MessageBoard {"name" "a" "message-counter" 0}) (ograph/create-vertex! :MessageBoard {"name" "c" "message-counter" 0})))) ((migration/version 2) (cats/mlet [message (ograph/vertex-type :Message) board (ograph/vertex-type :MessageBoard)] (cats/>> (ograph/create-edge-type! :BelongsTo {}) (ograph/set-outgoing-edge! message :BelongsTo) (ograph/set-incoming-edge! board :BelongsTo)))) ((migration/version 3) (cats/mlet [message (ograph/vertex-type :Message)] (ograph/create-properties! message {"ip" :string})))))
[ { "context": "1\n\n; get the second element\n(get [1 {:first-name \"Leandro\" :last-name \"TK\"} 2] 1) ; {:first-name \"Leandro\" ", "end": 192, "score": 0.9998169541358948, "start": 185, "tag": "NAME", "value": "Leandro" }, { "context": "lement\n(get [1 {:first-name \"Leandro\" :last-name \"TK\"} 2] 1) ; {:first-name \"Leandro\" :last-name \"TK\"}", "end": 208, "score": 0.994050920009613, "start": 206, "tag": "NAME", "value": "TK" }, { "context": " \"Leandro\" :last-name \"TK\"} 2] 1) ; {:first-name \"Leandro\" :last-name \"TK\"}\n\n; build a vector from elements", "end": 240, "score": 0.9998306035995483, "start": 233, "tag": "NAME", "value": "Leandro" }, { "context": " \"TK\"} 2] 1) ; {:first-name \"Leandro\" :last-name \"TK\"}\n\n; build a vector from elements\n(vector \"a\" \"ne", "end": 256, "score": 0.7096063494682312, "start": 254, "tag": "NAME", "value": "TK" } ]
language-learning/clojure/data_structures/vectors.clj
imteekay/programming-language-research
627
; "syntax" [1 2 3] ; [1 2 3] ; get the first element using index ([1 2 3] 0) ; 1 ; get the first element using get (get [1 2 3] 0) ; 1 ; get the second element (get [1 {:first-name "Leandro" :last-name "TK"} 2] 1) ; {:first-name "Leandro" :last-name "TK"} ; build a vector from elements (vector "a" "new" "vector" "of" "strings") ; ["a" "new" "vector" "of" "strings"] ; add a new element to the vector (conj [1 2 3] 4) ; [1 2 3 4] ; vectors evaluate each element before building [1 :x (+ 1 1)] ; [1 :x 2] ; (eval [1 :x (+ 1 1)]) ; [(eval 1) (eval :x) (eval (+ 1 1))] ; [1 :x 2]
52416
; "syntax" [1 2 3] ; [1 2 3] ; get the first element using index ([1 2 3] 0) ; 1 ; get the first element using get (get [1 2 3] 0) ; 1 ; get the second element (get [1 {:first-name "<NAME>" :last-name "<NAME>"} 2] 1) ; {:first-name "<NAME>" :last-name "<NAME>"} ; build a vector from elements (vector "a" "new" "vector" "of" "strings") ; ["a" "new" "vector" "of" "strings"] ; add a new element to the vector (conj [1 2 3] 4) ; [1 2 3 4] ; vectors evaluate each element before building [1 :x (+ 1 1)] ; [1 :x 2] ; (eval [1 :x (+ 1 1)]) ; [(eval 1) (eval :x) (eval (+ 1 1))] ; [1 :x 2]
true
; "syntax" [1 2 3] ; [1 2 3] ; get the first element using index ([1 2 3] 0) ; 1 ; get the first element using get (get [1 2 3] 0) ; 1 ; get the second element (get [1 {:first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"} 2] 1) ; {:first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"} ; build a vector from elements (vector "a" "new" "vector" "of" "strings") ; ["a" "new" "vector" "of" "strings"] ; add a new element to the vector (conj [1 2 3] 4) ; [1 2 3 4] ; vectors evaluate each element before building [1 :x (+ 1 1)] ; [1 :x 2] ; (eval [1 :x (+ 1 1)]) ; [(eval 1) (eval :x) (eval (+ 1 1))] ; [1 :x 2]
[ { "context": "1\\n65432 Musterstadt\"]\n (is (=\n [\"Max Muster\" \"Musterstr. 1\\n65432 Musterstadt\"]\n (", "end": 783, "score": 0.8883947730064392, "start": 773, "tag": "NAME", "value": "Max Muster" } ]
test/address_decoder/types/contact_test.clj
GuckesRohrkaGbR/address-decoder
1
(ns address-decoder.types.contact-test (:require [clojure.test :refer :all]) (:require [address-decoder.types.contact :as contact])) (deftest contact-creation-test (testing "empty contact creation" (let [{:keys [cont-name address phone]} (contact/make)] (is (= nil cont-name)) (is (= nil address)) (is (= nil phone)))) (testing "filled contact creation" (is (= "1" (:contact-name (contact/make "1" nil nil)))) (is (= "2" (:address (contact/make nil "2" nil)))) (is (= "3" (:phone (contact/make nil nil "3")))))) (deftest contact-parsing-test (testing "splitting-name-and-address" (let [simple-address "Max Muster\nMusterstr. 1\n65432 Musterstadt"] (is (= ["Max Muster" "Musterstr. 1\n65432 Musterstadt"] (#'contact/split-name-and-address simple-address))))))
43035
(ns address-decoder.types.contact-test (:require [clojure.test :refer :all]) (:require [address-decoder.types.contact :as contact])) (deftest contact-creation-test (testing "empty contact creation" (let [{:keys [cont-name address phone]} (contact/make)] (is (= nil cont-name)) (is (= nil address)) (is (= nil phone)))) (testing "filled contact creation" (is (= "1" (:contact-name (contact/make "1" nil nil)))) (is (= "2" (:address (contact/make nil "2" nil)))) (is (= "3" (:phone (contact/make nil nil "3")))))) (deftest contact-parsing-test (testing "splitting-name-and-address" (let [simple-address "Max Muster\nMusterstr. 1\n65432 Musterstadt"] (is (= ["<NAME>" "Musterstr. 1\n65432 Musterstadt"] (#'contact/split-name-and-address simple-address))))))
true
(ns address-decoder.types.contact-test (:require [clojure.test :refer :all]) (:require [address-decoder.types.contact :as contact])) (deftest contact-creation-test (testing "empty contact creation" (let [{:keys [cont-name address phone]} (contact/make)] (is (= nil cont-name)) (is (= nil address)) (is (= nil phone)))) (testing "filled contact creation" (is (= "1" (:contact-name (contact/make "1" nil nil)))) (is (= "2" (:address (contact/make nil "2" nil)))) (is (= "3" (:phone (contact/make nil nil "3")))))) (deftest contact-parsing-test (testing "splitting-name-and-address" (let [simple-address "Max Muster\nMusterstr. 1\n65432 Musterstadt"] (is (= ["PI:NAME:<NAME>END_PI" "Musterstr. 1\n65432 Musterstadt"] (#'contact/split-name-and-address simple-address))))))
[ { "context": " for anyone extending it).\"\n :author \"Chas Emerick\"}\n clojure.tools.nrepl.misc)\n\n(try\n (require", "end": 149, "score": 0.9998688697814941, "start": 137, "tag": "NAME", "value": "Chas Emerick" } ]
server/target/clojure/tools/nrepl/misc.clj
OctavioBR/healthcheck
14
(ns ^{:doc "Misc utilities used in nREPL's implementation (potentially also useful for anyone extending it)." :author "Chas Emerick"} clojure.tools.nrepl.misc) (try (require 'clojure.tools.logging) (defmacro log [& args] `(clojure.tools.logging/error ~@args)) (catch Throwable t ;(println "clojure.tools.logging not available, falling back to stdout/err") (defn log [ex & msgs] (let [ex (when (instance? Throwable ex) ex) msgs (if ex msgs (cons ex msgs))] (binding [*out* *err*] (apply println "ERROR:" msgs) (when ex (.printStackTrace ^Throwable ex))))))) (defmacro returning "Executes `body`, returning `x`." [x & body] `(let [x# ~x] ~@body x#)) (defn uuid "Returns a new UUID string." [] (str (java.util.UUID/randomUUID))) (defn response-for "Returns a map containing the :session and :id from the \"request\" `msg` as well as all entries specified in `response-data`, which can be one or more maps (which will be merged), *or* key-value pairs. (response-for msg :status :done :value \"5\") (response-for msg {:status :interrupted}) The :session value in `msg` may be any Clojure reference type (to accommodate likely implementations of sessions) that has an :id slot in its metadata, or a string." [{:keys [session id]} & response-data] {:pre [(seq response-data)]} (let [{:keys [status] :as response} (if (map? (first response-data)) (reduce merge response-data) (apply hash-map response-data)) response (if (not status) response (assoc response :status (if (coll? status) status #{status}))) basis (merge (when id {:id id}) ; AReference should make this suitable for any session implementation? (when session {:session (if (instance? clojure.lang.AReference session) (-> session meta :id) session)}))] (merge basis response)))
88189
(ns ^{:doc "Misc utilities used in nREPL's implementation (potentially also useful for anyone extending it)." :author "<NAME>"} clojure.tools.nrepl.misc) (try (require 'clojure.tools.logging) (defmacro log [& args] `(clojure.tools.logging/error ~@args)) (catch Throwable t ;(println "clojure.tools.logging not available, falling back to stdout/err") (defn log [ex & msgs] (let [ex (when (instance? Throwable ex) ex) msgs (if ex msgs (cons ex msgs))] (binding [*out* *err*] (apply println "ERROR:" msgs) (when ex (.printStackTrace ^Throwable ex))))))) (defmacro returning "Executes `body`, returning `x`." [x & body] `(let [x# ~x] ~@body x#)) (defn uuid "Returns a new UUID string." [] (str (java.util.UUID/randomUUID))) (defn response-for "Returns a map containing the :session and :id from the \"request\" `msg` as well as all entries specified in `response-data`, which can be one or more maps (which will be merged), *or* key-value pairs. (response-for msg :status :done :value \"5\") (response-for msg {:status :interrupted}) The :session value in `msg` may be any Clojure reference type (to accommodate likely implementations of sessions) that has an :id slot in its metadata, or a string." [{:keys [session id]} & response-data] {:pre [(seq response-data)]} (let [{:keys [status] :as response} (if (map? (first response-data)) (reduce merge response-data) (apply hash-map response-data)) response (if (not status) response (assoc response :status (if (coll? status) status #{status}))) basis (merge (when id {:id id}) ; AReference should make this suitable for any session implementation? (when session {:session (if (instance? clojure.lang.AReference session) (-> session meta :id) session)}))] (merge basis response)))
true
(ns ^{:doc "Misc utilities used in nREPL's implementation (potentially also useful for anyone extending it)." :author "PI:NAME:<NAME>END_PI"} clojure.tools.nrepl.misc) (try (require 'clojure.tools.logging) (defmacro log [& args] `(clojure.tools.logging/error ~@args)) (catch Throwable t ;(println "clojure.tools.logging not available, falling back to stdout/err") (defn log [ex & msgs] (let [ex (when (instance? Throwable ex) ex) msgs (if ex msgs (cons ex msgs))] (binding [*out* *err*] (apply println "ERROR:" msgs) (when ex (.printStackTrace ^Throwable ex))))))) (defmacro returning "Executes `body`, returning `x`." [x & body] `(let [x# ~x] ~@body x#)) (defn uuid "Returns a new UUID string." [] (str (java.util.UUID/randomUUID))) (defn response-for "Returns a map containing the :session and :id from the \"request\" `msg` as well as all entries specified in `response-data`, which can be one or more maps (which will be merged), *or* key-value pairs. (response-for msg :status :done :value \"5\") (response-for msg {:status :interrupted}) The :session value in `msg` may be any Clojure reference type (to accommodate likely implementations of sessions) that has an :id slot in its metadata, or a string." [{:keys [session id]} & response-data] {:pre [(seq response-data)]} (let [{:keys [status] :as response} (if (map? (first response-data)) (reduce merge response-data) (apply hash-map response-data)) response (if (not status) response (assoc response :status (if (coll? status) status #{status}))) basis (merge (when id {:id id}) ; AReference should make this suitable for any session implementation? (when session {:session (if (instance? clojure.lang.AReference session) (-> session meta :id) session)}))] (merge basis response)))
[ { "context": "-key (-> res :body :api_key))\n\n(def user {:email \"useremail@example.com\"\n :password \"pass\"})\n\n#_(-> (str auth-u", "end": 603, "score": 0.9999142289161682, "start": 582, "tag": "EMAIL", "value": "useremail@example.com" }, { "context": "ail \"useremail@example.com\"\n :password \"pass\"})\n\n#_(-> (str auth-url \"/user/signup\")\n (c/", "end": 631, "score": 0.9995365142822266, "start": 627, "tag": "PASSWORD", "value": "pass" } ]
dev/user.clj
entranceplus/link-server
0
(ns user (:require [snow.repl :as repl] [snow.client :as c] [snow.env :refer [profile]] [links.systems :as sys] [buddy.sign.jwt :as jwt] [shadow.cljs.devtools.server :as server] [shadow.cljs.devtools.api :as shadow])) (def auth-url "https://aviana.herokuapp.com") #_(def res (c/post (str auth-url "/app/signup") :body {:email (-> (profile) :aviana-email) :password (-> (profile) :aviana-password)})) #_(def api-key (-> res :body :api_key)) (def user {:email "useremail@example.com" :password "pass"}) #_(-> (str auth-url "/user/signup") (c/post :body user :headers {:app_key api-key}) :body) #_(def token (-> (str auth-url "/user/signin") (c/post :body user :headers {:app_key api-key}) :body :token)) #_(jwt/unsign token "secret") #_(repl/start! sys/system-config) #_(repl/stop!) (defn cljs-repl [] (cemerick.piggieback/cljs-repl :app)) (defn -main [& args] (println "Starting nrepl") ;; (repl/start-nrepl) (println "Starting clj systems") (repl/start! sys/system-config) (server/start!) (shadow/dev :app))
87436
(ns user (:require [snow.repl :as repl] [snow.client :as c] [snow.env :refer [profile]] [links.systems :as sys] [buddy.sign.jwt :as jwt] [shadow.cljs.devtools.server :as server] [shadow.cljs.devtools.api :as shadow])) (def auth-url "https://aviana.herokuapp.com") #_(def res (c/post (str auth-url "/app/signup") :body {:email (-> (profile) :aviana-email) :password (-> (profile) :aviana-password)})) #_(def api-key (-> res :body :api_key)) (def user {:email "<EMAIL>" :password "<PASSWORD>"}) #_(-> (str auth-url "/user/signup") (c/post :body user :headers {:app_key api-key}) :body) #_(def token (-> (str auth-url "/user/signin") (c/post :body user :headers {:app_key api-key}) :body :token)) #_(jwt/unsign token "secret") #_(repl/start! sys/system-config) #_(repl/stop!) (defn cljs-repl [] (cemerick.piggieback/cljs-repl :app)) (defn -main [& args] (println "Starting nrepl") ;; (repl/start-nrepl) (println "Starting clj systems") (repl/start! sys/system-config) (server/start!) (shadow/dev :app))
true
(ns user (:require [snow.repl :as repl] [snow.client :as c] [snow.env :refer [profile]] [links.systems :as sys] [buddy.sign.jwt :as jwt] [shadow.cljs.devtools.server :as server] [shadow.cljs.devtools.api :as shadow])) (def auth-url "https://aviana.herokuapp.com") #_(def res (c/post (str auth-url "/app/signup") :body {:email (-> (profile) :aviana-email) :password (-> (profile) :aviana-password)})) #_(def api-key (-> res :body :api_key)) (def user {:email "PI:EMAIL:<EMAIL>END_PI" :password "PI:PASSWORD:<PASSWORD>END_PI"}) #_(-> (str auth-url "/user/signup") (c/post :body user :headers {:app_key api-key}) :body) #_(def token (-> (str auth-url "/user/signin") (c/post :body user :headers {:app_key api-key}) :body :token)) #_(jwt/unsign token "secret") #_(repl/start! sys/system-config) #_(repl/stop!) (defn cljs-repl [] (cemerick.piggieback/cljs-repl :app)) (defn -main [& args] (println "Starting nrepl") ;; (repl/start-nrepl) (println "Starting clj systems") (repl/start! sys/system-config) (server/start!) (shadow/dev :app))
[ { "context": "epo\n :comments \"Copyright 2011-2022 Micah Martin All Rights Reserved.\"}\n\n :jar-exclusions [#\"\\.cl", "end": 335, "score": 0.999750018119812, "start": 323, "tag": "NAME", "value": "Micah Martin" }, { "context": " \"doc\"\n :source-uri \"https://github.com/slagyr/speclj/blob/{version}/{filepath}#L{line}\"}\n )\n", "end": 1136, "score": 0.9993703961372375, "start": 1130, "tag": "USERNAME", "value": "slagyr" } ]
project.clj
mdwhatcott/speclj
0
(defproject speclj "3.4.1" :description "speclj: Pronounced 'speckle', is a Behavior Driven Development framework for Clojure." :url "http://speclj.com" :license {:name "The MIT License" :url "file://LICENSE" :distribution :repo :comments "Copyright 2011-2022 Micah Martin All Rights Reserved."} :jar-exclusions [#"\.cljx|\.swp|\.swo|\.DS_Store"] :javac-options ["-target" "1.7" "-source" "1.7"] :source-paths ["src"] :test-paths ["spec" "dev"] :java-source-paths ["src"] :dependencies [[org.clojure/clojure "1.11.1"] [fresh "1.1.2"] [mmargs "1.2.0"] [trptcolin/versioneer "0.1.1"]] :profiles {:dev {:dependencies [[org.clojure/clojurescript "1.11.4"]]}} :plugins [[lein-codox "0.10.8"]] :prep-tasks ["javac" "compile"] :aliases {"cljs" ["do" "clean," "run" "-m" "speclj.dev.cljs"] "spec" ["do" "run" "-m" "speclj.dev.spec"] "ci" ["do" "spec," "cljs"]} :codox {;:namespaces [speclj.core] :output-path "doc" :source-uri "https://github.com/slagyr/speclj/blob/{version}/{filepath}#L{line}"} )
18480
(defproject speclj "3.4.1" :description "speclj: Pronounced 'speckle', is a Behavior Driven Development framework for Clojure." :url "http://speclj.com" :license {:name "The MIT License" :url "file://LICENSE" :distribution :repo :comments "Copyright 2011-2022 <NAME> All Rights Reserved."} :jar-exclusions [#"\.cljx|\.swp|\.swo|\.DS_Store"] :javac-options ["-target" "1.7" "-source" "1.7"] :source-paths ["src"] :test-paths ["spec" "dev"] :java-source-paths ["src"] :dependencies [[org.clojure/clojure "1.11.1"] [fresh "1.1.2"] [mmargs "1.2.0"] [trptcolin/versioneer "0.1.1"]] :profiles {:dev {:dependencies [[org.clojure/clojurescript "1.11.4"]]}} :plugins [[lein-codox "0.10.8"]] :prep-tasks ["javac" "compile"] :aliases {"cljs" ["do" "clean," "run" "-m" "speclj.dev.cljs"] "spec" ["do" "run" "-m" "speclj.dev.spec"] "ci" ["do" "spec," "cljs"]} :codox {;:namespaces [speclj.core] :output-path "doc" :source-uri "https://github.com/slagyr/speclj/blob/{version}/{filepath}#L{line}"} )
true
(defproject speclj "3.4.1" :description "speclj: Pronounced 'speckle', is a Behavior Driven Development framework for Clojure." :url "http://speclj.com" :license {:name "The MIT License" :url "file://LICENSE" :distribution :repo :comments "Copyright 2011-2022 PI:NAME:<NAME>END_PI All Rights Reserved."} :jar-exclusions [#"\.cljx|\.swp|\.swo|\.DS_Store"] :javac-options ["-target" "1.7" "-source" "1.7"] :source-paths ["src"] :test-paths ["spec" "dev"] :java-source-paths ["src"] :dependencies [[org.clojure/clojure "1.11.1"] [fresh "1.1.2"] [mmargs "1.2.0"] [trptcolin/versioneer "0.1.1"]] :profiles {:dev {:dependencies [[org.clojure/clojurescript "1.11.4"]]}} :plugins [[lein-codox "0.10.8"]] :prep-tasks ["javac" "compile"] :aliases {"cljs" ["do" "clean," "run" "-m" "speclj.dev.cljs"] "spec" ["do" "run" "-m" "speclj.dev.spec"] "ci" ["do" "spec," "cljs"]} :codox {;:namespaces [speclj.core] :output-path "doc" :source-uri "https://github.com/slagyr/speclj/blob/{version}/{filepath}#L{line}"} )
[ { "context": "ermissions sets (This was a \"\n \"bug @tom found where a group with no permissions would cau", "end": 1560, "score": 0.9939519166946411, "start": 1556, "tag": "USERNAME", "value": "@tom" }, { "context": " :password \"p@ssword1\"}))))\n\n(defn sent-emails\n \"Fetch the emails that", "end": 4953, "score": 0.9992431402206421, "start": 4944, "tag": "PASSWORD", "value": "p@ssword1" }, { "context": "email\n :password password}]\n (try\n (if google-auth?\n ", "end": 6477, "score": 0.9990967512130737, "start": 6469, "tag": "PASSWORD", "value": "password" }, { "context": "))))))\n\n(def ^:private default-invitor\n {:email \"crowberto@metabase.com\", :is_active true, :first_name \"Crowberto\"})\n\n;; ", "end": 6997, "score": 0.9999136328697205, "start": 6975, "tag": "EMAIL", "value": "crowberto@metabase.com" }, { "context": "erto@metabase.com\", :is_active true, :first_name \"Crowberto\"})\n\n;; admin shouldn't get email saying user join", "end": 7039, "score": 0.9997656345367432, "start": 7030, "tag": "NAME", "value": "Crowberto" }, { "context": "nvited to join Metabase's Metabase\"]\n \"crowberto@metabase.com\" [\"<New User> accepted their Metabase invite\"]}\n ", "end": 7589, "score": 0.9998814463615417, "start": 7567, "tag": "EMAIL", "value": "crowberto@metabase.com" }, { "context": "vitor)\n (select-keys [\"<New User>\" \"crowberto@metabase.com\"]))))\n\n (testing \"...including the site admin ", "end": 7783, "score": 0.9997008442878723, "start": 7761, "tag": "EMAIL", "value": "crowberto@metabase.com" }, { "context": " (mt/with-temporary-setting-values [admin-email \"cam2@metabase.com\"]\n (is (= {\"<New User>\" [\"You'", "end": 7921, "score": 0.9999205470085144, "start": 7904, "tag": "EMAIL", "value": "cam2@metabase.com" }, { "context": "ed to join Metabase's Metabase\"]\n \"crowberto@metabase.com\" [\"<New User> accepted their Metabase invite\"]\n ", "end": 8051, "score": 0.9999134540557861, "start": 8029, "tag": "EMAIL", "value": "crowberto@metabase.com" }, { "context": "accepted their Metabase invite\"]\n \"cam2@metabase.com\" [\"<New User> accepted their Metabase invite", "end": 8133, "score": 0.9999181628227234, "start": 8116, "tag": "EMAIL", "value": "cam2@metabase.com" }, { "context": "r)\n (select-keys [\"<New User>\" \"crowberto@metabase.com\" \"cam2@metabase.com\"])))))\n\n (testing \"... b", "end": 8340, "score": 0.9999037981033325, "start": 8318, "tag": "EMAIL", "value": "crowberto@metabase.com" }, { "context": "lect-keys [\"<New User>\" \"crowberto@metabase.com\" \"cam2@metabase.com\"])))))\n\n (testing \"... but if that admin is ", "end": 8360, "score": 0.9999129176139832, "start": 8343, "tag": "EMAIL", "value": "cam2@metabase.com" }, { "context": " to join Metabase's Metabase\"]\n \"crowberto@metabase.com\" [\"<New User> accepted their Metabase invite\"]}\n ", "end": 8662, "score": 0.9999021887779236, "start": 8640, "tag": "EMAIL", "value": "crowberto@metabase.com" }, { "context": "\n (select-keys [\"<New User>\" \"crowberto@metabase.com\" (:email inactive-admin)]))))))))\n\n (testing \"fo", "end": 8892, "score": 0.9998840689659119, "start": 8870, "tag": "EMAIL", "value": "crowberto@metabase.com" }, { "context": "mt/with-temp User [_ {:is_superuser true, :email \"some_other_admin@metabase.com\"}]\n (is (= {\"crowberto@metabase.com\" ", "end": 9076, "score": 0.9999116063117981, "start": 9047, "tag": "EMAIL", "value": "some_other_admin@metabase.com" }, { "context": " \"some_other_admin@metabase.com\"}]\n (is (= {\"crowberto@metabase.com\" [\"<New User> created a Metabase account\"]", "end": 9117, "score": 0.9999160766601562, "start": 9095, "tag": "EMAIL", "value": "crowberto@metabase.com" }, { "context": "User> created a Metabase account\"]\n \"some_other_admin@metabase.com\" [\"<New User> created a Metabase account\"]}\n ", "end": 9212, "score": 0.9999189376831055, "start": 9183, "tag": "EMAIL", "value": "some_other_admin@metabase.com" }, { "context": "oogle-auth? true)\n (select-keys [\"crowberto@metabase.com\" \"some_other_admin@metabase.com\"])))))\n\n (test", "end": 9387, "score": 0.9997994303703308, "start": 9365, "tag": "EMAIL", "value": "crowberto@metabase.com" }, { "context": " (select-keys [\"crowberto@metabase.com\" \"some_other_admin@metabase.com\"])))))\n\n (testing \"...including the site admin", "end": 9419, "score": 0.9998966455459595, "start": 9390, "tag": "EMAIL", "value": "some_other_admin@metabase.com" }, { "context": " (mt/with-temporary-setting-values [admin-email \"cam2@metabase.com\"]\n (mt/with-temp User [_ {:is_superuser tr", "end": 9558, "score": 0.9999179840087891, "start": 9541, "tag": "EMAIL", "value": "cam2@metabase.com" }, { "context": "mt/with-temp User [_ {:is_superuser true, :email \"some_other_admin@metabase.com\"}]\n (is (= {\"crowberto@metabase.com\" ", "end": 9649, "score": 0.9999170303344727, "start": 9620, "tag": "EMAIL", "value": "some_other_admin@metabase.com" }, { "context": "me_other_admin@metabase.com\"}]\n (is (= {\"crowberto@metabase.com\" [\"<New User> created a Metabase account\"]", "end": 9694, "score": 0.999915599822998, "start": 9672, "tag": "EMAIL", "value": "crowberto@metabase.com" }, { "context": "> created a Metabase account\"]\n \"some_other_admin@metabase.com\" [\"<New User> created a Metabase account\"]\n ", "end": 9793, "score": 0.9999186396598816, "start": 9764, "tag": "EMAIL", "value": "some_other_admin@metabase.com" }, { "context": "> created a Metabase account\"]\n \"cam2@metabase.com\" [\"<New User> created a Metabase acco", "end": 9873, "score": 0.9998302459716797, "start": 9856, "tag": "EMAIL", "value": "cam2@metabase.com" }, { "context": "e-auth? true)\n (select-keys [\"crowberto@metabase.com\" \"some_other_admin@metabase.com\" \"cam2@metabase.c", "end": 10068, "score": 0.9994118213653564, "start": 10046, "tag": "EMAIL", "value": "crowberto@metabase.com" }, { "context": " (select-keys [\"crowberto@metabase.com\" \"some_other_admin@metabase.com\" \"cam2@metabase.com\"]))))))\n\n (testing \"...u", "end": 10100, "score": 0.9997357130050659, "start": 10071, "tag": "EMAIL", "value": "some_other_admin@metabase.com" }, { "context": "to@metabase.com\" \"some_other_admin@metabase.com\" \"cam2@metabase.com\"]))))))\n\n (testing \"...unless they are inact", "end": 10120, "score": 0.9997056722640991, "start": 10103, "tag": "EMAIL", "value": "cam2@metabase.com" }, { "context": "ruser true, :is_active false}]\n (is (= {\"crowberto@metabase.com\" [\"<New User> created a Metabase account\"]}\n ", "end": 10289, "score": 0.9996936321258545, "start": 10267, "tag": "EMAIL", "value": "crowberto@metabase.com" }, { "context": "e-auth? true)\n (select-keys [\"crowberto@metabase.com\" (:email user)])))))))))\n\n(deftest ldap-user-pass", "end": 10472, "score": 0.8667864799499512, "start": 10450, "tag": "EMAIL", "value": "crowberto@metabase.com" }, { "context": " (user/create-new-ldap-auth-user! {:email \"ldaptest@metabase.com\"\n :first_n", "end": 10798, "score": 0.9998892545700073, "start": 10777, "tag": "EMAIL", "value": "ldaptest@metabase.com" }, { "context": " :password \"should be removed\"})\n (let [{:keys [password password_salt]} (", "end": 10997, "score": 0.9976139068603516, "start": 10980, "tag": "PASSWORD", "value": "should be removed" }, { "context": "elect-one [User :password :password_salt] :email \"ldaptest@metabase.com\")]\n (is (= false\n (u.passwor", "end": 11122, "score": 0.9999041557312012, "start": 11101, "tag": "EMAIL", "value": "ldaptest@metabase.com" }, { "context": " (u.password/verify-password \"should be removed\" password_salt password))))\n (finally\n ", "end": 11208, "score": 0.6821286678314209, "start": 11198, "tag": "PASSWORD", "value": "be removed" }, { "context": ")\n (finally\n (db/delete! User :email \"ldaptest@metabase.com\")))))\n\n(deftest new-admin-user-test\n (testing (s", "end": 11306, "score": 0.9998920559883118, "start": 11285, "tag": "EMAIL", "value": "ldaptest@metabase.com" }, { "context": "er/create-new-ldap-auth-user! {:email \"ldaptest@metabase.com\"\n :first_n", "end": 11927, "score": 0.9999194145202637, "start": 11906, "tag": "EMAIL", "value": "ldaptest@metabase.com" }, { "context": " :first_name \"Test\"\n :last_na", "end": 11992, "score": 0.9991699457168579, "start": 11988, "tag": "NAME", "value": "Test" }, { "context": " :last_name \"SomeLdapStuff\"\n :login_a", "end": 12066, "score": 0.9980015754699707, "start": 12053, "tag": "NAME", "value": "SomeLdapStuff" }, { "context": " :login_attributes {:local_birds [\"Steller's Jay\" \"Mountain Chickadee\"]}})\n (is (= {\"local_bi", "end": 12155, "score": 0.9684619903564453, "start": 12142, "tag": "NAME", "value": "Steller's Jay" }, { "context": "n_attributes {:local_birds [\"Steller's Jay\" \"Mountain Chickadee\"]}})\n (is (= {\"local_birds\" [\"Steller's Jay\"", "end": 12176, "score": 0.9550875425338745, "start": 12163, "tag": "NAME", "value": "ain Chickadee" }, { "context": "tain Chickadee\"]}})\n (is (= {\"local_birds\" [\"Steller's Jay\" \"Mountain Chickadee\"]}\n (db/sele", "end": 12221, "score": 0.8669870495796204, "start": 12212, "tag": "NAME", "value": "Steller's" }, { "context": "dee\"]}})\n (is (= {\"local_birds\" [\"Steller's Jay\" \"Mountain Chickadee\"]}\n (db/select-o", "end": 12225, "score": 0.685135006904602, "start": 12223, "tag": "NAME", "value": "ay" }, { "context": " (is (= {\"local_birds\" [\"Steller's Jay\" \"Mountain Chickadee\"]}\n (db/select-one-field :login_attri", "end": 12246, "score": 0.7035777568817139, "start": 12233, "tag": "NAME", "value": "ain Chickadee" }, { "context": "b/select-one-field :login_attributes User :email \"ldaptest@metabase.com\")))\n (finally\n (db/delete! User :emai", "end": 12336, "score": 0.9999192357063293, "start": 12315, "tag": "EMAIL", "value": "ldaptest@metabase.com" }, { "context": ")\n (finally\n (db/delete! User :email \"ldaptest@metabase.com\")))))\n\n\n;;; +------------------------------------", "end": 12410, "score": 0.9999203085899353, "start": 12389, "tag": "EMAIL", "value": "ldaptest@metabase.com" }, { "context": " (mt/with-temp User [{user-id :id} {:password \"ABC_DEF\"}]\n (letfn [(password [] (db/select-one-fi", "end": 20234, "score": 0.999147355556488, "start": 20227, "tag": "PASSWORD", "value": "ABC_DEF" }, { "context": ":id user-id))]\n (let [original-password (password)]\n (user/set-password! user-id \"p@ssw0", "end": 20361, "score": 0.5896857976913452, "start": 20353, "tag": "PASSWORD", "value": "password" }, { "context": "ssword)]\n (user/set-password! user-id \"p@ssw0rd\")\n (is (not= original-password\n ", "end": 20413, "score": 0.9950199723243713, "start": 20405, "tag": "PASSWORD", "value": "p@ssw0rd" }, { "context": " (mt/with-temp User [{user-id :id} {:reset_token \"ABC123\"}]\n (user/set-password! user-id \"p@ssw0rd\"", "end": 20610, "score": 0.9907873272895813, "start": 20604, "tag": "PASSWORD", "value": "ABC123" }, { "context": "n \"ABC123\"}]\n (user/set-password! user-id \"p@ssw0rd\")\n (is (= nil\n (db/select-on", "end": 20659, "score": 0.9962212443351746, "start": 20651, "tag": "PASSWORD", "value": "p@ssw0rd" }, { "context": "n-count)))\n (user/set-password! user-id \"p@ssw0rd\")\n (is (= 0\n (session-co", "end": 21211, "score": 0.9989924430847168, "start": 21203, "tag": "PASSWORD", "value": "p@ssw0rd" } ]
c#-metabase/test/metabase/models/user_test.clj
hanakhry/Crime_Admin
0
(ns metabase.models.user-test (:require [clojure.set :as set] [clojure.string :as str] [clojure.test :refer :all] [metabase.http-client :as http] [metabase.models.collection :as collection :refer [Collection]] [metabase.models.collection-test :as collection-test] [metabase.models.database :refer [Database]] [metabase.models.permissions :as perms] [metabase.models.permissions-group :as group :refer [PermissionsGroup]] [metabase.models.permissions-group-membership :refer [PermissionsGroupMembership]] [metabase.models.session :refer [Session]] [metabase.models.table :refer [Table]] [metabase.models.user :as user :refer [User]] [metabase.test :as mt] [metabase.test.data.users :as test-users] [metabase.util :as u] [metabase.util.password :as u.password] [toucan.db :as db] [toucan.hydrate :refer [hydrate]])) ;;; Tests for permissions-set (deftest check-test-users-have-valid-permissions-sets-test (testing "Make sure the test users have valid permissions sets" (doseq [user [:rasta :crowberto :lucky :trashbird]] (testing user (is (= true (perms/is-permissions-set? (user/permissions-set (mt/user->id user))))))))) (deftest group-with-no-permissions-test (testing (str "Adding a group with *no* permissions shouldn't suddenly break all the permissions sets (This was a " "bug @tom found where a group with no permissions would cause the permissions set to contain `nil`).") (mt/with-temp* [PermissionsGroup [{group-id :id}] PermissionsGroupMembership [_ {:group_id group-id, :user_id (mt/user->id :rasta)}]] (is (= true (perms/is-permissions-set? (user/permissions-set (mt/user->id :rasta)))))))) (defn- remove-non-collection-perms [perms-set] (set (for [perms-path perms-set :when (str/starts-with? perms-path "/collection/")] perms-path))) (deftest personal-collection-permissions-test (testing "Does permissions-set include permissions for my Personal Collection?" (mt/with-non-admin-groups-no-root-collection-perms (is (contains? (user/permissions-set (mt/user->id :lucky)) (perms/collection-readwrite-path (collection/user->personal-collection (mt/user->id :lucky))))) (testing "...and for any descendant Collections of my Personal Collection?" (mt/with-temp* [Collection [child-collection {:name "child" :location (collection/children-location (collection/user->personal-collection (mt/user->id :lucky)))}] Collection [grandchild-collection {:name "grandchild" :location (collection/children-location child-collection)}]] (is (set/subset? #{(perms/collection-readwrite-path (collection/user->personal-collection (mt/user->id :lucky))) "/collection/child/" "/collection/grandchild/"} (->> (user/permissions-set (mt/user->id :lucky)) remove-non-collection-perms (collection-test/perms-path-ids->names [child-collection grandchild-collection]))))))))) (deftest group-data-permissions-test (testing "If a User is a member of a Group with data permissions for an object, `permissions-set` should return the perms" (mt/with-temp* [Database [{db-id :id}] Table [table {:name "Round Table", :db_id db-id}] PermissionsGroup [{group-id :id}] PermissionsGroupMembership [_ {:group_id group-id, :user_id (mt/user->id :rasta)}]] (perms/revoke-permissions! (group/all-users) db-id (:schema table) (:id table)) (perms/grant-permissions! group-id (perms/table-read-path table)) (is (set/subset? #{(perms/table-read-path table)} (metabase.models.user/permissions-set (mt/user->id :rasta))))))) ;;; Tests for invite-user and create-new-google-auth-user! (defn- maybe-accept-invite! "Accept an invite if applicable. Look in the body of the content of the invite email for the reset token since this is the only place to get it (the token stored in the DB is an encrypted hash)." [new-user-email-address] (when-let [[{[{invite-email :content}] :body}] (get @mt/inbox new-user-email-address)] (let [[_ reset-token] (re-find #"/auth/reset_password/(\d+_[\w_-]+)#new" invite-email)] (http/client :post 200 "session/reset_password" {:token reset-token :password "p@ssword1"})))) (defn sent-emails "Fetch the emails that have been sent in the form of a map of email address -> sequence of email subjects. For test-writing convenience the random email and names assigned to the new user are replaced with `<New User>`." [new-user-email-address new-user-first-name new-user-last-name] (into {} (for [[address emails] @mt/inbox :let [address (if (= address new-user-email-address) "<New User>" address)]] [address (for [{subject :subject} emails] (str/replace subject (str new-user-first-name " " new-user-last-name) "<New User>"))]))) (defn- invite-user-accept-and-check-inboxes! "Create user by passing `invite-user-args` to `create-and-invite-user!` or `create-new-google-auth-user!`, and return a map of addresses emails were sent to to the email subjects." [& {:keys [google-auth? accept-invite? password invitor] :or {accept-invite? true}}] (mt/with-temporary-setting-values [site-name "Metabase"] (mt/with-fake-inbox (let [new-user-email (mt/random-email) new-user-first-name (mt/random-name) new-user-last-name (mt/random-name) new-user {:first_name new-user-first-name :last_name new-user-last-name :email new-user-email :password password}] (try (if google-auth? (user/create-new-google-auth-user! (dissoc new-user :password)) (user/create-and-invite-user! new-user invitor)) (when accept-invite? (maybe-accept-invite! new-user-email)) (sent-emails new-user-email new-user-first-name new-user-last-name) ;; Clean up after ourselves (finally (db/delete! User :email new-user-email))))))) (def ^:private default-invitor {:email "crowberto@metabase.com", :is_active true, :first_name "Crowberto"}) ;; admin shouldn't get email saying user joined until they accept the invite (i.e., reset their password) (deftest new-user-emails-test (testing "New user should get an invite email" (is (= {"<New User>" ["You're invited to join Metabase's Metabase"]} (invite-user-accept-and-check-inboxes! :invitor default-invitor, :accept-invite? false)))) (testing "admin should get an email when a new user joins..." (is (= {"<New User>" ["You're invited to join Metabase's Metabase"] "crowberto@metabase.com" ["<New User> accepted their Metabase invite"]} (-> (invite-user-accept-and-check-inboxes! :invitor default-invitor) (select-keys ["<New User>" "crowberto@metabase.com"])))) (testing "...including the site admin if it is set..." (mt/with-temporary-setting-values [admin-email "cam2@metabase.com"] (is (= {"<New User>" ["You're invited to join Metabase's Metabase"] "crowberto@metabase.com" ["<New User> accepted their Metabase invite"] "cam2@metabase.com" ["<New User> accepted their Metabase invite"]} (-> (invite-user-accept-and-check-inboxes! :invitor default-invitor) (select-keys ["<New User>" "crowberto@metabase.com" "cam2@metabase.com"]))))) (testing "... but if that admin is inactive they shouldn't get an email" (mt/with-temp User [inactive-admin {:is_superuser true, :is_active false}] (is (= {"<New User>" ["You're invited to join Metabase's Metabase"] "crowberto@metabase.com" ["<New User> accepted their Metabase invite"]} (-> (invite-user-accept-and-check-inboxes! :invitor (assoc inactive-admin :is_active false)) (select-keys ["<New User>" "crowberto@metabase.com" (:email inactive-admin)])))))))) (testing "for google auth, all admins should get an email..." (mt/with-temp User [_ {:is_superuser true, :email "some_other_admin@metabase.com"}] (is (= {"crowberto@metabase.com" ["<New User> created a Metabase account"] "some_other_admin@metabase.com" ["<New User> created a Metabase account"]} (-> (invite-user-accept-and-check-inboxes! :google-auth? true) (select-keys ["crowberto@metabase.com" "some_other_admin@metabase.com"]))))) (testing "...including the site admin if it is set..." (mt/with-temporary-setting-values [admin-email "cam2@metabase.com"] (mt/with-temp User [_ {:is_superuser true, :email "some_other_admin@metabase.com"}] (is (= {"crowberto@metabase.com" ["<New User> created a Metabase account"] "some_other_admin@metabase.com" ["<New User> created a Metabase account"] "cam2@metabase.com" ["<New User> created a Metabase account"]} (-> (invite-user-accept-and-check-inboxes! :google-auth? true) (select-keys ["crowberto@metabase.com" "some_other_admin@metabase.com" "cam2@metabase.com"])))))) (testing "...unless they are inactive" (mt/with-temp User [user {:is_superuser true, :is_active false}] (is (= {"crowberto@metabase.com" ["<New User> created a Metabase account"]} (-> (invite-user-accept-and-check-inboxes! :google-auth? true) (select-keys ["crowberto@metabase.com" (:email user)]))))))))) (deftest ldap-user-passwords-test (testing (str "LDAP users should not persist their passwords. Check that if somehow we get passed an LDAP user " "password, it gets swapped with something random") (try (user/create-new-ldap-auth-user! {:email "ldaptest@metabase.com" :first_name "Test" :last_name "SomeLdapStuff" :password "should be removed"}) (let [{:keys [password password_salt]} (db/select-one [User :password :password_salt] :email "ldaptest@metabase.com")] (is (= false (u.password/verify-password "should be removed" password_salt password)))) (finally (db/delete! User :email "ldaptest@metabase.com"))))) (deftest new-admin-user-test (testing (str "when you create a new user with `is_superuser` set to `true`, it should create a " "PermissionsGroupMembership object") (mt/with-temp User [user {:is_superuser true}] (is (= true (db/exists? PermissionsGroupMembership :user_id (u/the-id user), :group_id (u/the-id (group/admin)))))))) (deftest ldap-sequential-login-attributes-test (testing "You should be able to create a new LDAP user if some `login_attributes` are vectors (#10291)" (try (user/create-new-ldap-auth-user! {:email "ldaptest@metabase.com" :first_name "Test" :last_name "SomeLdapStuff" :login_attributes {:local_birds ["Steller's Jay" "Mountain Chickadee"]}}) (is (= {"local_birds" ["Steller's Jay" "Mountain Chickadee"]} (db/select-one-field :login_attributes User :email "ldaptest@metabase.com"))) (finally (db/delete! User :email "ldaptest@metabase.com"))))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | New Group IDs Functions | ;;; +----------------------------------------------------------------------------------------------------------------+ (defn group-names [groups-or-ids] (when (seq groups-or-ids) (db/select-field :name PermissionsGroup :id [:in (map u/the-id groups-or-ids)]))) (defn- do-with-group [group-properties group-members f] (mt/with-temp PermissionsGroup [group group-properties] (doseq [member group-members] (db/insert! PermissionsGroupMembership {:group_id (u/the-id group) :user_id (if (keyword? member) (mt/user->id member) (u/the-id member))})) (f group))) (defmacro ^:private with-groups [[group-binding group-properties members & more-groups] & body] (if (seq more-groups) `(with-groups [~group-binding ~group-properties ~members] (with-groups ~more-groups ~@body)) `(do-with-group ~group-properties ~members (fn [~group-binding] ~@body)))) (deftest group-ids-test (testing "the `group-ids` hydration function" (testing "should work as expected" (with-groups [_ {:name "Group 1"} #{:lucky :rasta} _ {:name "Group 2"} #{:lucky} _ {:name "Group 3"} #{}] (is (= #{"All Users" "Group 2" "Group 1"} (group-names (user/group-ids (mt/user->id :lucky))))))) (testing "should be a single DB call" (with-groups [_ {:name "Group 1"} #{:lucky} _ {:name "Group 2"} #{:lucky} _ {:name "Group 3"} #{}] (let [lucky-id (mt/user->id :lucky)] (db/with-call-counting [call-count] (user/group-ids lucky-id) (is (= 1 (call-count))))))) (testing "shouldn't barf if passed `nil`" (is (= nil (user/group-ids nil)))))) (deftest add-group-ids-test (testing "the `add-group-ids` hydration function" (testing "should do a batched hydate" (with-groups [_ {:name "Group 1"} #{:lucky :rasta} _ {:name "Group 2"} #{:lucky} _ {:name "Group 3"} #{}] (let [users (user/add-group-ids (map test-users/fetch-user [:lucky :rasta]))] (is (= {"Lucky" #{"All Users" "Group 1" "Group 2"} "Rasta" #{"All Users" "Group 1"}} (zipmap (map :first_name users) (map (comp group-names :group_ids) users))))))) (testing "should be the hydrate function for `:group_ids`" (with-redefs [user/group-ids (constantly '(user/group-ids <user>)) user/add-group-ids (fn [users] (for [user users] (assoc user :group_ids '(user/add-group-ids <users>))))] (testing "for a single User" (is (= '(user/add-group-ids <users>) (-> (hydrate (User (mt/user->id :lucky)) :group_ids) :group_ids)))) (testing "for multiple Users" (is (= '[(user/add-group-ids <users>) (user/add-group-ids <users>)] (as-> (map test-users/fetch-user [:rasta :lucky]) users (hydrate users :group_ids) (mapv :group_ids users))))))) (testing "should be done in a single DB call" (with-groups [_ {:name "Group 1"} #{:lucky :rasta} _ {:name "Group 2"} #{:lucky} _ {:name "Group 3"} #{}] (let [users (mapv test-users/fetch-user [:lucky :rasta])] (db/with-call-counting [call-count] (dorun (user/add-group-ids users)) (is (= 1 (call-count))))))) (testing "shouldn't barf if passed an empty seq" (is (= nil (user/add-group-ids [])))))) (defn user-group-names [user-or-id-or-kw] (group-names (user/group-ids (if (keyword? user-or-id-or-kw) (test-users/fetch-user user-or-id-or-kw) user-or-id-or-kw)))) (deftest set-permissions-groups-test (testing "set-permissions-groups!" (testing "should be able to add a User to new groups" (with-groups [group-1 {:name "Group 1"} #{} group-2 {:name "Group 2"} #{}] (user/set-permissions-groups! (mt/user->id :lucky) #{(group/all-users) group-1 group-2}) (is (= #{"All Users" "Group 1" "Group 2"} (user-group-names :lucky))))) (testing "should be able to remove a User from groups" (with-groups [group-1 {:name "Group 1"} #{:lucky} group-2 {:name "Group 2"} #{:lucky}] (user/set-permissions-groups! (mt/user->id :lucky) #{(group/all-users)}) (is (= #{"All Users"} (user-group-names :lucky))))) (testing "should be able to add & remove groups at the same time! :wow:" (with-groups [group-1 {:name "Group 1"} #{:lucky} group-2 {:name "Group 2"} #{}] (user/set-permissions-groups! (mt/user->id :lucky) #{(group/all-users) group-2}) (is (= #{"All Users" "Group 2"} (user-group-names :lucky))))) (testing "should throw an Exception if you attempt to remove someone from All Users" (with-groups [group-1 {:name "Group 1"} #{}] (is (thrown? Exception (user/set-permissions-groups! (mt/user->id :lucky) #{group-1}))))) (testing "should be able to add someone to the Admin group" (mt/with-temp User [user] (user/set-permissions-groups! user #{(group/all-users) (group/admin)}) (is (= #{"Administrators" "All Users"} (user-group-names user))) (testing "their is_superuser flag should be set to true" (is (= true (db/select-one-field :is_superuser User :id (u/the-id user))))))) (testing "should be able to remove someone from the Admin group" (mt/with-temp User [user {:is_superuser true}] (user/set-permissions-groups! user #{(group/all-users)}) (is (= #{"All Users"} (user-group-names user))) (testing "their is_superuser flag should be set to false" (is (= false (db/select-one-field :is_superuser User :id (u/the-id user))))))) (testing "should run all changes in a transaction -- if one set of changes fails, others should not be persisted" (testing "Invalid ADD operation" ;; User should not be removed from the admin group because the attempt to add them to the Integer/MAX_VALUE group ;; should fail, causing the entire transaction to fail (mt/with-temp User [user {:is_superuser true}] (u/ignore-exceptions (user/set-permissions-groups! user #{(group/all-users) Integer/MAX_VALUE})) (is (= true (db/select-one-field :is_superuser User :id (u/the-id user)))))) (testing "Invalid REMOVE operation" ;; Attempt to remove someone from All Users + add to a valid group at the same time -- neither should persist (mt/with-temp User [user] (with-groups [group {:name "Group"} {}] (u/ignore-exceptions (user/set-permissions-groups! (test-users/fetch-user :lucky) #{group}))) (is (= #{"All Users"} (user-group-names :lucky)) "If an INVALID REMOVE is attempted, valid adds should not be persisted")))))) (deftest set-password-test (testing "set-password!" (testing "should change the password" (mt/with-temp User [{user-id :id} {:password "ABC_DEF"}] (letfn [(password [] (db/select-one-field :password User :id user-id))] (let [original-password (password)] (user/set-password! user-id "p@ssw0rd") (is (not= original-password (password))))))) (testing "should clear out password reset token" (mt/with-temp User [{user-id :id} {:reset_token "ABC123"}] (user/set-password! user-id "p@ssw0rd") (is (= nil (db/select-one-field :reset_token User :id user-id))))) (testing "should clear out all existing Sessions" (mt/with-temp* [User [{user-id :id}] Session [_ {:id (str (java.util.UUID/randomUUID)), :user_id user-id}] Session [_ {:id (str (java.util.UUID/randomUUID)), :user_id user-id}]] (letfn [(session-count [] (db/count Session :user_id user-id))] (is (= 2 (session-count))) (user/set-password! user-id "p@ssw0rd") (is (= 0 (session-count)))))))) (deftest validate-locale-test (testing "`:locale` should be validated" (testing "creating a new User" (testing "valid locale" (mt/with-temp User [{user-id :id} {:locale "en_US"}] (is (= "en_US" (db/select-one-field :locale User :id user-id))))) (testing "invalid locale" (is (thrown? AssertionError (mt/with-temp User [{user-id :id} {:locale "en_XX"}]))))) (testing "updating a User" (mt/with-temp User [{user-id :id} {:locale "en_US"}] (testing "valid locale" (db/update! User user-id :locale "en_GB") (is (= "en_GB" (db/select-one-field :locale User :id user-id)))) (testing "invalid locale" (is (thrown? AssertionError (db/update! User user-id :locale "en_XX")))))))) (deftest normalize-locale-test (testing "`:locale` should be normalized" (mt/with-temp User [{user-id :id} {:locale "EN-us"}] (testing "creating a new User" (is (= "en_US" (db/select-one-field :locale User :id user-id)))) (testing "updating a User" (db/update! User user-id :locale "en-GB") (is (= "en_GB" (db/select-one-field :locale User :id user-id)))))))
105436
(ns metabase.models.user-test (:require [clojure.set :as set] [clojure.string :as str] [clojure.test :refer :all] [metabase.http-client :as http] [metabase.models.collection :as collection :refer [Collection]] [metabase.models.collection-test :as collection-test] [metabase.models.database :refer [Database]] [metabase.models.permissions :as perms] [metabase.models.permissions-group :as group :refer [PermissionsGroup]] [metabase.models.permissions-group-membership :refer [PermissionsGroupMembership]] [metabase.models.session :refer [Session]] [metabase.models.table :refer [Table]] [metabase.models.user :as user :refer [User]] [metabase.test :as mt] [metabase.test.data.users :as test-users] [metabase.util :as u] [metabase.util.password :as u.password] [toucan.db :as db] [toucan.hydrate :refer [hydrate]])) ;;; Tests for permissions-set (deftest check-test-users-have-valid-permissions-sets-test (testing "Make sure the test users have valid permissions sets" (doseq [user [:rasta :crowberto :lucky :trashbird]] (testing user (is (= true (perms/is-permissions-set? (user/permissions-set (mt/user->id user))))))))) (deftest group-with-no-permissions-test (testing (str "Adding a group with *no* permissions shouldn't suddenly break all the permissions sets (This was a " "bug @tom found where a group with no permissions would cause the permissions set to contain `nil`).") (mt/with-temp* [PermissionsGroup [{group-id :id}] PermissionsGroupMembership [_ {:group_id group-id, :user_id (mt/user->id :rasta)}]] (is (= true (perms/is-permissions-set? (user/permissions-set (mt/user->id :rasta)))))))) (defn- remove-non-collection-perms [perms-set] (set (for [perms-path perms-set :when (str/starts-with? perms-path "/collection/")] perms-path))) (deftest personal-collection-permissions-test (testing "Does permissions-set include permissions for my Personal Collection?" (mt/with-non-admin-groups-no-root-collection-perms (is (contains? (user/permissions-set (mt/user->id :lucky)) (perms/collection-readwrite-path (collection/user->personal-collection (mt/user->id :lucky))))) (testing "...and for any descendant Collections of my Personal Collection?" (mt/with-temp* [Collection [child-collection {:name "child" :location (collection/children-location (collection/user->personal-collection (mt/user->id :lucky)))}] Collection [grandchild-collection {:name "grandchild" :location (collection/children-location child-collection)}]] (is (set/subset? #{(perms/collection-readwrite-path (collection/user->personal-collection (mt/user->id :lucky))) "/collection/child/" "/collection/grandchild/"} (->> (user/permissions-set (mt/user->id :lucky)) remove-non-collection-perms (collection-test/perms-path-ids->names [child-collection grandchild-collection]))))))))) (deftest group-data-permissions-test (testing "If a User is a member of a Group with data permissions for an object, `permissions-set` should return the perms" (mt/with-temp* [Database [{db-id :id}] Table [table {:name "Round Table", :db_id db-id}] PermissionsGroup [{group-id :id}] PermissionsGroupMembership [_ {:group_id group-id, :user_id (mt/user->id :rasta)}]] (perms/revoke-permissions! (group/all-users) db-id (:schema table) (:id table)) (perms/grant-permissions! group-id (perms/table-read-path table)) (is (set/subset? #{(perms/table-read-path table)} (metabase.models.user/permissions-set (mt/user->id :rasta))))))) ;;; Tests for invite-user and create-new-google-auth-user! (defn- maybe-accept-invite! "Accept an invite if applicable. Look in the body of the content of the invite email for the reset token since this is the only place to get it (the token stored in the DB is an encrypted hash)." [new-user-email-address] (when-let [[{[{invite-email :content}] :body}] (get @mt/inbox new-user-email-address)] (let [[_ reset-token] (re-find #"/auth/reset_password/(\d+_[\w_-]+)#new" invite-email)] (http/client :post 200 "session/reset_password" {:token reset-token :password "<PASSWORD>"})))) (defn sent-emails "Fetch the emails that have been sent in the form of a map of email address -> sequence of email subjects. For test-writing convenience the random email and names assigned to the new user are replaced with `<New User>`." [new-user-email-address new-user-first-name new-user-last-name] (into {} (for [[address emails] @mt/inbox :let [address (if (= address new-user-email-address) "<New User>" address)]] [address (for [{subject :subject} emails] (str/replace subject (str new-user-first-name " " new-user-last-name) "<New User>"))]))) (defn- invite-user-accept-and-check-inboxes! "Create user by passing `invite-user-args` to `create-and-invite-user!` or `create-new-google-auth-user!`, and return a map of addresses emails were sent to to the email subjects." [& {:keys [google-auth? accept-invite? password invitor] :or {accept-invite? true}}] (mt/with-temporary-setting-values [site-name "Metabase"] (mt/with-fake-inbox (let [new-user-email (mt/random-email) new-user-first-name (mt/random-name) new-user-last-name (mt/random-name) new-user {:first_name new-user-first-name :last_name new-user-last-name :email new-user-email :password <PASSWORD>}] (try (if google-auth? (user/create-new-google-auth-user! (dissoc new-user :password)) (user/create-and-invite-user! new-user invitor)) (when accept-invite? (maybe-accept-invite! new-user-email)) (sent-emails new-user-email new-user-first-name new-user-last-name) ;; Clean up after ourselves (finally (db/delete! User :email new-user-email))))))) (def ^:private default-invitor {:email "<EMAIL>", :is_active true, :first_name "<NAME>"}) ;; admin shouldn't get email saying user joined until they accept the invite (i.e., reset their password) (deftest new-user-emails-test (testing "New user should get an invite email" (is (= {"<New User>" ["You're invited to join Metabase's Metabase"]} (invite-user-accept-and-check-inboxes! :invitor default-invitor, :accept-invite? false)))) (testing "admin should get an email when a new user joins..." (is (= {"<New User>" ["You're invited to join Metabase's Metabase"] "<EMAIL>" ["<New User> accepted their Metabase invite"]} (-> (invite-user-accept-and-check-inboxes! :invitor default-invitor) (select-keys ["<New User>" "<EMAIL>"])))) (testing "...including the site admin if it is set..." (mt/with-temporary-setting-values [admin-email "<EMAIL>"] (is (= {"<New User>" ["You're invited to join Metabase's Metabase"] "<EMAIL>" ["<New User> accepted their Metabase invite"] "<EMAIL>" ["<New User> accepted their Metabase invite"]} (-> (invite-user-accept-and-check-inboxes! :invitor default-invitor) (select-keys ["<New User>" "<EMAIL>" "<EMAIL>"]))))) (testing "... but if that admin is inactive they shouldn't get an email" (mt/with-temp User [inactive-admin {:is_superuser true, :is_active false}] (is (= {"<New User>" ["You're invited to join Metabase's Metabase"] "<EMAIL>" ["<New User> accepted their Metabase invite"]} (-> (invite-user-accept-and-check-inboxes! :invitor (assoc inactive-admin :is_active false)) (select-keys ["<New User>" "<EMAIL>" (:email inactive-admin)])))))))) (testing "for google auth, all admins should get an email..." (mt/with-temp User [_ {:is_superuser true, :email "<EMAIL>"}] (is (= {"<EMAIL>" ["<New User> created a Metabase account"] "<EMAIL>" ["<New User> created a Metabase account"]} (-> (invite-user-accept-and-check-inboxes! :google-auth? true) (select-keys ["<EMAIL>" "<EMAIL>"]))))) (testing "...including the site admin if it is set..." (mt/with-temporary-setting-values [admin-email "<EMAIL>"] (mt/with-temp User [_ {:is_superuser true, :email "<EMAIL>"}] (is (= {"<EMAIL>" ["<New User> created a Metabase account"] "<EMAIL>" ["<New User> created a Metabase account"] "<EMAIL>" ["<New User> created a Metabase account"]} (-> (invite-user-accept-and-check-inboxes! :google-auth? true) (select-keys ["<EMAIL>" "<EMAIL>" "<EMAIL>"])))))) (testing "...unless they are inactive" (mt/with-temp User [user {:is_superuser true, :is_active false}] (is (= {"<EMAIL>" ["<New User> created a Metabase account"]} (-> (invite-user-accept-and-check-inboxes! :google-auth? true) (select-keys ["<EMAIL>" (:email user)]))))))))) (deftest ldap-user-passwords-test (testing (str "LDAP users should not persist their passwords. Check that if somehow we get passed an LDAP user " "password, it gets swapped with something random") (try (user/create-new-ldap-auth-user! {:email "<EMAIL>" :first_name "Test" :last_name "SomeLdapStuff" :password "<PASSWORD>"}) (let [{:keys [password password_salt]} (db/select-one [User :password :password_salt] :email "<EMAIL>")] (is (= false (u.password/verify-password "should <PASSWORD>" password_salt password)))) (finally (db/delete! User :email "<EMAIL>"))))) (deftest new-admin-user-test (testing (str "when you create a new user with `is_superuser` set to `true`, it should create a " "PermissionsGroupMembership object") (mt/with-temp User [user {:is_superuser true}] (is (= true (db/exists? PermissionsGroupMembership :user_id (u/the-id user), :group_id (u/the-id (group/admin)))))))) (deftest ldap-sequential-login-attributes-test (testing "You should be able to create a new LDAP user if some `login_attributes` are vectors (#10291)" (try (user/create-new-ldap-auth-user! {:email "<EMAIL>" :first_name "<NAME>" :last_name "<NAME>" :login_attributes {:local_birds ["<NAME>" "Mount<NAME>"]}}) (is (= {"local_birds" ["<NAME> J<NAME>" "Mount<NAME>"]} (db/select-one-field :login_attributes User :email "<EMAIL>"))) (finally (db/delete! User :email "<EMAIL>"))))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | New Group IDs Functions | ;;; +----------------------------------------------------------------------------------------------------------------+ (defn group-names [groups-or-ids] (when (seq groups-or-ids) (db/select-field :name PermissionsGroup :id [:in (map u/the-id groups-or-ids)]))) (defn- do-with-group [group-properties group-members f] (mt/with-temp PermissionsGroup [group group-properties] (doseq [member group-members] (db/insert! PermissionsGroupMembership {:group_id (u/the-id group) :user_id (if (keyword? member) (mt/user->id member) (u/the-id member))})) (f group))) (defmacro ^:private with-groups [[group-binding group-properties members & more-groups] & body] (if (seq more-groups) `(with-groups [~group-binding ~group-properties ~members] (with-groups ~more-groups ~@body)) `(do-with-group ~group-properties ~members (fn [~group-binding] ~@body)))) (deftest group-ids-test (testing "the `group-ids` hydration function" (testing "should work as expected" (with-groups [_ {:name "Group 1"} #{:lucky :rasta} _ {:name "Group 2"} #{:lucky} _ {:name "Group 3"} #{}] (is (= #{"All Users" "Group 2" "Group 1"} (group-names (user/group-ids (mt/user->id :lucky))))))) (testing "should be a single DB call" (with-groups [_ {:name "Group 1"} #{:lucky} _ {:name "Group 2"} #{:lucky} _ {:name "Group 3"} #{}] (let [lucky-id (mt/user->id :lucky)] (db/with-call-counting [call-count] (user/group-ids lucky-id) (is (= 1 (call-count))))))) (testing "shouldn't barf if passed `nil`" (is (= nil (user/group-ids nil)))))) (deftest add-group-ids-test (testing "the `add-group-ids` hydration function" (testing "should do a batched hydate" (with-groups [_ {:name "Group 1"} #{:lucky :rasta} _ {:name "Group 2"} #{:lucky} _ {:name "Group 3"} #{}] (let [users (user/add-group-ids (map test-users/fetch-user [:lucky :rasta]))] (is (= {"Lucky" #{"All Users" "Group 1" "Group 2"} "Rasta" #{"All Users" "Group 1"}} (zipmap (map :first_name users) (map (comp group-names :group_ids) users))))))) (testing "should be the hydrate function for `:group_ids`" (with-redefs [user/group-ids (constantly '(user/group-ids <user>)) user/add-group-ids (fn [users] (for [user users] (assoc user :group_ids '(user/add-group-ids <users>))))] (testing "for a single User" (is (= '(user/add-group-ids <users>) (-> (hydrate (User (mt/user->id :lucky)) :group_ids) :group_ids)))) (testing "for multiple Users" (is (= '[(user/add-group-ids <users>) (user/add-group-ids <users>)] (as-> (map test-users/fetch-user [:rasta :lucky]) users (hydrate users :group_ids) (mapv :group_ids users))))))) (testing "should be done in a single DB call" (with-groups [_ {:name "Group 1"} #{:lucky :rasta} _ {:name "Group 2"} #{:lucky} _ {:name "Group 3"} #{}] (let [users (mapv test-users/fetch-user [:lucky :rasta])] (db/with-call-counting [call-count] (dorun (user/add-group-ids users)) (is (= 1 (call-count))))))) (testing "shouldn't barf if passed an empty seq" (is (= nil (user/add-group-ids [])))))) (defn user-group-names [user-or-id-or-kw] (group-names (user/group-ids (if (keyword? user-or-id-or-kw) (test-users/fetch-user user-or-id-or-kw) user-or-id-or-kw)))) (deftest set-permissions-groups-test (testing "set-permissions-groups!" (testing "should be able to add a User to new groups" (with-groups [group-1 {:name "Group 1"} #{} group-2 {:name "Group 2"} #{}] (user/set-permissions-groups! (mt/user->id :lucky) #{(group/all-users) group-1 group-2}) (is (= #{"All Users" "Group 1" "Group 2"} (user-group-names :lucky))))) (testing "should be able to remove a User from groups" (with-groups [group-1 {:name "Group 1"} #{:lucky} group-2 {:name "Group 2"} #{:lucky}] (user/set-permissions-groups! (mt/user->id :lucky) #{(group/all-users)}) (is (= #{"All Users"} (user-group-names :lucky))))) (testing "should be able to add & remove groups at the same time! :wow:" (with-groups [group-1 {:name "Group 1"} #{:lucky} group-2 {:name "Group 2"} #{}] (user/set-permissions-groups! (mt/user->id :lucky) #{(group/all-users) group-2}) (is (= #{"All Users" "Group 2"} (user-group-names :lucky))))) (testing "should throw an Exception if you attempt to remove someone from All Users" (with-groups [group-1 {:name "Group 1"} #{}] (is (thrown? Exception (user/set-permissions-groups! (mt/user->id :lucky) #{group-1}))))) (testing "should be able to add someone to the Admin group" (mt/with-temp User [user] (user/set-permissions-groups! user #{(group/all-users) (group/admin)}) (is (= #{"Administrators" "All Users"} (user-group-names user))) (testing "their is_superuser flag should be set to true" (is (= true (db/select-one-field :is_superuser User :id (u/the-id user))))))) (testing "should be able to remove someone from the Admin group" (mt/with-temp User [user {:is_superuser true}] (user/set-permissions-groups! user #{(group/all-users)}) (is (= #{"All Users"} (user-group-names user))) (testing "their is_superuser flag should be set to false" (is (= false (db/select-one-field :is_superuser User :id (u/the-id user))))))) (testing "should run all changes in a transaction -- if one set of changes fails, others should not be persisted" (testing "Invalid ADD operation" ;; User should not be removed from the admin group because the attempt to add them to the Integer/MAX_VALUE group ;; should fail, causing the entire transaction to fail (mt/with-temp User [user {:is_superuser true}] (u/ignore-exceptions (user/set-permissions-groups! user #{(group/all-users) Integer/MAX_VALUE})) (is (= true (db/select-one-field :is_superuser User :id (u/the-id user)))))) (testing "Invalid REMOVE operation" ;; Attempt to remove someone from All Users + add to a valid group at the same time -- neither should persist (mt/with-temp User [user] (with-groups [group {:name "Group"} {}] (u/ignore-exceptions (user/set-permissions-groups! (test-users/fetch-user :lucky) #{group}))) (is (= #{"All Users"} (user-group-names :lucky)) "If an INVALID REMOVE is attempted, valid adds should not be persisted")))))) (deftest set-password-test (testing "set-password!" (testing "should change the password" (mt/with-temp User [{user-id :id} {:password "<PASSWORD>"}] (letfn [(password [] (db/select-one-field :password User :id user-id))] (let [original-password (<PASSWORD>)] (user/set-password! user-id "<PASSWORD>") (is (not= original-password (password))))))) (testing "should clear out password reset token" (mt/with-temp User [{user-id :id} {:reset_token "<PASSWORD>"}] (user/set-password! user-id "<PASSWORD>") (is (= nil (db/select-one-field :reset_token User :id user-id))))) (testing "should clear out all existing Sessions" (mt/with-temp* [User [{user-id :id}] Session [_ {:id (str (java.util.UUID/randomUUID)), :user_id user-id}] Session [_ {:id (str (java.util.UUID/randomUUID)), :user_id user-id}]] (letfn [(session-count [] (db/count Session :user_id user-id))] (is (= 2 (session-count))) (user/set-password! user-id "<PASSWORD>") (is (= 0 (session-count)))))))) (deftest validate-locale-test (testing "`:locale` should be validated" (testing "creating a new User" (testing "valid locale" (mt/with-temp User [{user-id :id} {:locale "en_US"}] (is (= "en_US" (db/select-one-field :locale User :id user-id))))) (testing "invalid locale" (is (thrown? AssertionError (mt/with-temp User [{user-id :id} {:locale "en_XX"}]))))) (testing "updating a User" (mt/with-temp User [{user-id :id} {:locale "en_US"}] (testing "valid locale" (db/update! User user-id :locale "en_GB") (is (= "en_GB" (db/select-one-field :locale User :id user-id)))) (testing "invalid locale" (is (thrown? AssertionError (db/update! User user-id :locale "en_XX")))))))) (deftest normalize-locale-test (testing "`:locale` should be normalized" (mt/with-temp User [{user-id :id} {:locale "EN-us"}] (testing "creating a new User" (is (= "en_US" (db/select-one-field :locale User :id user-id)))) (testing "updating a User" (db/update! User user-id :locale "en-GB") (is (= "en_GB" (db/select-one-field :locale User :id user-id)))))))
true
(ns metabase.models.user-test (:require [clojure.set :as set] [clojure.string :as str] [clojure.test :refer :all] [metabase.http-client :as http] [metabase.models.collection :as collection :refer [Collection]] [metabase.models.collection-test :as collection-test] [metabase.models.database :refer [Database]] [metabase.models.permissions :as perms] [metabase.models.permissions-group :as group :refer [PermissionsGroup]] [metabase.models.permissions-group-membership :refer [PermissionsGroupMembership]] [metabase.models.session :refer [Session]] [metabase.models.table :refer [Table]] [metabase.models.user :as user :refer [User]] [metabase.test :as mt] [metabase.test.data.users :as test-users] [metabase.util :as u] [metabase.util.password :as u.password] [toucan.db :as db] [toucan.hydrate :refer [hydrate]])) ;;; Tests for permissions-set (deftest check-test-users-have-valid-permissions-sets-test (testing "Make sure the test users have valid permissions sets" (doseq [user [:rasta :crowberto :lucky :trashbird]] (testing user (is (= true (perms/is-permissions-set? (user/permissions-set (mt/user->id user))))))))) (deftest group-with-no-permissions-test (testing (str "Adding a group with *no* permissions shouldn't suddenly break all the permissions sets (This was a " "bug @tom found where a group with no permissions would cause the permissions set to contain `nil`).") (mt/with-temp* [PermissionsGroup [{group-id :id}] PermissionsGroupMembership [_ {:group_id group-id, :user_id (mt/user->id :rasta)}]] (is (= true (perms/is-permissions-set? (user/permissions-set (mt/user->id :rasta)))))))) (defn- remove-non-collection-perms [perms-set] (set (for [perms-path perms-set :when (str/starts-with? perms-path "/collection/")] perms-path))) (deftest personal-collection-permissions-test (testing "Does permissions-set include permissions for my Personal Collection?" (mt/with-non-admin-groups-no-root-collection-perms (is (contains? (user/permissions-set (mt/user->id :lucky)) (perms/collection-readwrite-path (collection/user->personal-collection (mt/user->id :lucky))))) (testing "...and for any descendant Collections of my Personal Collection?" (mt/with-temp* [Collection [child-collection {:name "child" :location (collection/children-location (collection/user->personal-collection (mt/user->id :lucky)))}] Collection [grandchild-collection {:name "grandchild" :location (collection/children-location child-collection)}]] (is (set/subset? #{(perms/collection-readwrite-path (collection/user->personal-collection (mt/user->id :lucky))) "/collection/child/" "/collection/grandchild/"} (->> (user/permissions-set (mt/user->id :lucky)) remove-non-collection-perms (collection-test/perms-path-ids->names [child-collection grandchild-collection]))))))))) (deftest group-data-permissions-test (testing "If a User is a member of a Group with data permissions for an object, `permissions-set` should return the perms" (mt/with-temp* [Database [{db-id :id}] Table [table {:name "Round Table", :db_id db-id}] PermissionsGroup [{group-id :id}] PermissionsGroupMembership [_ {:group_id group-id, :user_id (mt/user->id :rasta)}]] (perms/revoke-permissions! (group/all-users) db-id (:schema table) (:id table)) (perms/grant-permissions! group-id (perms/table-read-path table)) (is (set/subset? #{(perms/table-read-path table)} (metabase.models.user/permissions-set (mt/user->id :rasta))))))) ;;; Tests for invite-user and create-new-google-auth-user! (defn- maybe-accept-invite! "Accept an invite if applicable. Look in the body of the content of the invite email for the reset token since this is the only place to get it (the token stored in the DB is an encrypted hash)." [new-user-email-address] (when-let [[{[{invite-email :content}] :body}] (get @mt/inbox new-user-email-address)] (let [[_ reset-token] (re-find #"/auth/reset_password/(\d+_[\w_-]+)#new" invite-email)] (http/client :post 200 "session/reset_password" {:token reset-token :password "PI:PASSWORD:<PASSWORD>END_PI"})))) (defn sent-emails "Fetch the emails that have been sent in the form of a map of email address -> sequence of email subjects. For test-writing convenience the random email and names assigned to the new user are replaced with `<New User>`." [new-user-email-address new-user-first-name new-user-last-name] (into {} (for [[address emails] @mt/inbox :let [address (if (= address new-user-email-address) "<New User>" address)]] [address (for [{subject :subject} emails] (str/replace subject (str new-user-first-name " " new-user-last-name) "<New User>"))]))) (defn- invite-user-accept-and-check-inboxes! "Create user by passing `invite-user-args` to `create-and-invite-user!` or `create-new-google-auth-user!`, and return a map of addresses emails were sent to to the email subjects." [& {:keys [google-auth? accept-invite? password invitor] :or {accept-invite? true}}] (mt/with-temporary-setting-values [site-name "Metabase"] (mt/with-fake-inbox (let [new-user-email (mt/random-email) new-user-first-name (mt/random-name) new-user-last-name (mt/random-name) new-user {:first_name new-user-first-name :last_name new-user-last-name :email new-user-email :password PI:PASSWORD:<PASSWORD>END_PI}] (try (if google-auth? (user/create-new-google-auth-user! (dissoc new-user :password)) (user/create-and-invite-user! new-user invitor)) (when accept-invite? (maybe-accept-invite! new-user-email)) (sent-emails new-user-email new-user-first-name new-user-last-name) ;; Clean up after ourselves (finally (db/delete! User :email new-user-email))))))) (def ^:private default-invitor {:email "PI:EMAIL:<EMAIL>END_PI", :is_active true, :first_name "PI:NAME:<NAME>END_PI"}) ;; admin shouldn't get email saying user joined until they accept the invite (i.e., reset their password) (deftest new-user-emails-test (testing "New user should get an invite email" (is (= {"<New User>" ["You're invited to join Metabase's Metabase"]} (invite-user-accept-and-check-inboxes! :invitor default-invitor, :accept-invite? false)))) (testing "admin should get an email when a new user joins..." (is (= {"<New User>" ["You're invited to join Metabase's Metabase"] "PI:EMAIL:<EMAIL>END_PI" ["<New User> accepted their Metabase invite"]} (-> (invite-user-accept-and-check-inboxes! :invitor default-invitor) (select-keys ["<New User>" "PI:EMAIL:<EMAIL>END_PI"])))) (testing "...including the site admin if it is set..." (mt/with-temporary-setting-values [admin-email "PI:EMAIL:<EMAIL>END_PI"] (is (= {"<New User>" ["You're invited to join Metabase's Metabase"] "PI:EMAIL:<EMAIL>END_PI" ["<New User> accepted their Metabase invite"] "PI:EMAIL:<EMAIL>END_PI" ["<New User> accepted their Metabase invite"]} (-> (invite-user-accept-and-check-inboxes! :invitor default-invitor) (select-keys ["<New User>" "PI:EMAIL:<EMAIL>END_PI" "PI:EMAIL:<EMAIL>END_PI"]))))) (testing "... but if that admin is inactive they shouldn't get an email" (mt/with-temp User [inactive-admin {:is_superuser true, :is_active false}] (is (= {"<New User>" ["You're invited to join Metabase's Metabase"] "PI:EMAIL:<EMAIL>END_PI" ["<New User> accepted their Metabase invite"]} (-> (invite-user-accept-and-check-inboxes! :invitor (assoc inactive-admin :is_active false)) (select-keys ["<New User>" "PI:EMAIL:<EMAIL>END_PI" (:email inactive-admin)])))))))) (testing "for google auth, all admins should get an email..." (mt/with-temp User [_ {:is_superuser true, :email "PI:EMAIL:<EMAIL>END_PI"}] (is (= {"PI:EMAIL:<EMAIL>END_PI" ["<New User> created a Metabase account"] "PI:EMAIL:<EMAIL>END_PI" ["<New User> created a Metabase account"]} (-> (invite-user-accept-and-check-inboxes! :google-auth? true) (select-keys ["PI:EMAIL:<EMAIL>END_PI" "PI:EMAIL:<EMAIL>END_PI"]))))) (testing "...including the site admin if it is set..." (mt/with-temporary-setting-values [admin-email "PI:EMAIL:<EMAIL>END_PI"] (mt/with-temp User [_ {:is_superuser true, :email "PI:EMAIL:<EMAIL>END_PI"}] (is (= {"PI:EMAIL:<EMAIL>END_PI" ["<New User> created a Metabase account"] "PI:EMAIL:<EMAIL>END_PI" ["<New User> created a Metabase account"] "PI:EMAIL:<EMAIL>END_PI" ["<New User> created a Metabase account"]} (-> (invite-user-accept-and-check-inboxes! :google-auth? true) (select-keys ["PI:EMAIL:<EMAIL>END_PI" "PI:EMAIL:<EMAIL>END_PI" "PI:EMAIL:<EMAIL>END_PI"])))))) (testing "...unless they are inactive" (mt/with-temp User [user {:is_superuser true, :is_active false}] (is (= {"PI:EMAIL:<EMAIL>END_PI" ["<New User> created a Metabase account"]} (-> (invite-user-accept-and-check-inboxes! :google-auth? true) (select-keys ["PI:EMAIL:<EMAIL>END_PI" (:email user)]))))))))) (deftest ldap-user-passwords-test (testing (str "LDAP users should not persist their passwords. Check that if somehow we get passed an LDAP user " "password, it gets swapped with something random") (try (user/create-new-ldap-auth-user! {:email "PI:EMAIL:<EMAIL>END_PI" :first_name "Test" :last_name "SomeLdapStuff" :password "PI:PASSWORD:<PASSWORD>END_PI"}) (let [{:keys [password password_salt]} (db/select-one [User :password :password_salt] :email "PI:EMAIL:<EMAIL>END_PI")] (is (= false (u.password/verify-password "should PI:PASSWORD:<PASSWORD>END_PI" password_salt password)))) (finally (db/delete! User :email "PI:EMAIL:<EMAIL>END_PI"))))) (deftest new-admin-user-test (testing (str "when you create a new user with `is_superuser` set to `true`, it should create a " "PermissionsGroupMembership object") (mt/with-temp User [user {:is_superuser true}] (is (= true (db/exists? PermissionsGroupMembership :user_id (u/the-id user), :group_id (u/the-id (group/admin)))))))) (deftest ldap-sequential-login-attributes-test (testing "You should be able to create a new LDAP user if some `login_attributes` are vectors (#10291)" (try (user/create-new-ldap-auth-user! {:email "PI:EMAIL:<EMAIL>END_PI" :first_name "PI:NAME:<NAME>END_PI" :last_name "PI:NAME:<NAME>END_PI" :login_attributes {:local_birds ["PI:NAME:<NAME>END_PI" "MountPI:NAME:<NAME>END_PI"]}}) (is (= {"local_birds" ["PI:NAME:<NAME>END_PI JPI:NAME:<NAME>END_PI" "MountPI:NAME:<NAME>END_PI"]} (db/select-one-field :login_attributes User :email "PI:EMAIL:<EMAIL>END_PI"))) (finally (db/delete! User :email "PI:EMAIL:<EMAIL>END_PI"))))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | New Group IDs Functions | ;;; +----------------------------------------------------------------------------------------------------------------+ (defn group-names [groups-or-ids] (when (seq groups-or-ids) (db/select-field :name PermissionsGroup :id [:in (map u/the-id groups-or-ids)]))) (defn- do-with-group [group-properties group-members f] (mt/with-temp PermissionsGroup [group group-properties] (doseq [member group-members] (db/insert! PermissionsGroupMembership {:group_id (u/the-id group) :user_id (if (keyword? member) (mt/user->id member) (u/the-id member))})) (f group))) (defmacro ^:private with-groups [[group-binding group-properties members & more-groups] & body] (if (seq more-groups) `(with-groups [~group-binding ~group-properties ~members] (with-groups ~more-groups ~@body)) `(do-with-group ~group-properties ~members (fn [~group-binding] ~@body)))) (deftest group-ids-test (testing "the `group-ids` hydration function" (testing "should work as expected" (with-groups [_ {:name "Group 1"} #{:lucky :rasta} _ {:name "Group 2"} #{:lucky} _ {:name "Group 3"} #{}] (is (= #{"All Users" "Group 2" "Group 1"} (group-names (user/group-ids (mt/user->id :lucky))))))) (testing "should be a single DB call" (with-groups [_ {:name "Group 1"} #{:lucky} _ {:name "Group 2"} #{:lucky} _ {:name "Group 3"} #{}] (let [lucky-id (mt/user->id :lucky)] (db/with-call-counting [call-count] (user/group-ids lucky-id) (is (= 1 (call-count))))))) (testing "shouldn't barf if passed `nil`" (is (= nil (user/group-ids nil)))))) (deftest add-group-ids-test (testing "the `add-group-ids` hydration function" (testing "should do a batched hydate" (with-groups [_ {:name "Group 1"} #{:lucky :rasta} _ {:name "Group 2"} #{:lucky} _ {:name "Group 3"} #{}] (let [users (user/add-group-ids (map test-users/fetch-user [:lucky :rasta]))] (is (= {"Lucky" #{"All Users" "Group 1" "Group 2"} "Rasta" #{"All Users" "Group 1"}} (zipmap (map :first_name users) (map (comp group-names :group_ids) users))))))) (testing "should be the hydrate function for `:group_ids`" (with-redefs [user/group-ids (constantly '(user/group-ids <user>)) user/add-group-ids (fn [users] (for [user users] (assoc user :group_ids '(user/add-group-ids <users>))))] (testing "for a single User" (is (= '(user/add-group-ids <users>) (-> (hydrate (User (mt/user->id :lucky)) :group_ids) :group_ids)))) (testing "for multiple Users" (is (= '[(user/add-group-ids <users>) (user/add-group-ids <users>)] (as-> (map test-users/fetch-user [:rasta :lucky]) users (hydrate users :group_ids) (mapv :group_ids users))))))) (testing "should be done in a single DB call" (with-groups [_ {:name "Group 1"} #{:lucky :rasta} _ {:name "Group 2"} #{:lucky} _ {:name "Group 3"} #{}] (let [users (mapv test-users/fetch-user [:lucky :rasta])] (db/with-call-counting [call-count] (dorun (user/add-group-ids users)) (is (= 1 (call-count))))))) (testing "shouldn't barf if passed an empty seq" (is (= nil (user/add-group-ids [])))))) (defn user-group-names [user-or-id-or-kw] (group-names (user/group-ids (if (keyword? user-or-id-or-kw) (test-users/fetch-user user-or-id-or-kw) user-or-id-or-kw)))) (deftest set-permissions-groups-test (testing "set-permissions-groups!" (testing "should be able to add a User to new groups" (with-groups [group-1 {:name "Group 1"} #{} group-2 {:name "Group 2"} #{}] (user/set-permissions-groups! (mt/user->id :lucky) #{(group/all-users) group-1 group-2}) (is (= #{"All Users" "Group 1" "Group 2"} (user-group-names :lucky))))) (testing "should be able to remove a User from groups" (with-groups [group-1 {:name "Group 1"} #{:lucky} group-2 {:name "Group 2"} #{:lucky}] (user/set-permissions-groups! (mt/user->id :lucky) #{(group/all-users)}) (is (= #{"All Users"} (user-group-names :lucky))))) (testing "should be able to add & remove groups at the same time! :wow:" (with-groups [group-1 {:name "Group 1"} #{:lucky} group-2 {:name "Group 2"} #{}] (user/set-permissions-groups! (mt/user->id :lucky) #{(group/all-users) group-2}) (is (= #{"All Users" "Group 2"} (user-group-names :lucky))))) (testing "should throw an Exception if you attempt to remove someone from All Users" (with-groups [group-1 {:name "Group 1"} #{}] (is (thrown? Exception (user/set-permissions-groups! (mt/user->id :lucky) #{group-1}))))) (testing "should be able to add someone to the Admin group" (mt/with-temp User [user] (user/set-permissions-groups! user #{(group/all-users) (group/admin)}) (is (= #{"Administrators" "All Users"} (user-group-names user))) (testing "their is_superuser flag should be set to true" (is (= true (db/select-one-field :is_superuser User :id (u/the-id user))))))) (testing "should be able to remove someone from the Admin group" (mt/with-temp User [user {:is_superuser true}] (user/set-permissions-groups! user #{(group/all-users)}) (is (= #{"All Users"} (user-group-names user))) (testing "their is_superuser flag should be set to false" (is (= false (db/select-one-field :is_superuser User :id (u/the-id user))))))) (testing "should run all changes in a transaction -- if one set of changes fails, others should not be persisted" (testing "Invalid ADD operation" ;; User should not be removed from the admin group because the attempt to add them to the Integer/MAX_VALUE group ;; should fail, causing the entire transaction to fail (mt/with-temp User [user {:is_superuser true}] (u/ignore-exceptions (user/set-permissions-groups! user #{(group/all-users) Integer/MAX_VALUE})) (is (= true (db/select-one-field :is_superuser User :id (u/the-id user)))))) (testing "Invalid REMOVE operation" ;; Attempt to remove someone from All Users + add to a valid group at the same time -- neither should persist (mt/with-temp User [user] (with-groups [group {:name "Group"} {}] (u/ignore-exceptions (user/set-permissions-groups! (test-users/fetch-user :lucky) #{group}))) (is (= #{"All Users"} (user-group-names :lucky)) "If an INVALID REMOVE is attempted, valid adds should not be persisted")))))) (deftest set-password-test (testing "set-password!" (testing "should change the password" (mt/with-temp User [{user-id :id} {:password "PI:PASSWORD:<PASSWORD>END_PI"}] (letfn [(password [] (db/select-one-field :password User :id user-id))] (let [original-password (PI:PASSWORD:<PASSWORD>END_PI)] (user/set-password! user-id "PI:PASSWORD:<PASSWORD>END_PI") (is (not= original-password (password))))))) (testing "should clear out password reset token" (mt/with-temp User [{user-id :id} {:reset_token "PI:PASSWORD:<PASSWORD>END_PI"}] (user/set-password! user-id "PI:PASSWORD:<PASSWORD>END_PI") (is (= nil (db/select-one-field :reset_token User :id user-id))))) (testing "should clear out all existing Sessions" (mt/with-temp* [User [{user-id :id}] Session [_ {:id (str (java.util.UUID/randomUUID)), :user_id user-id}] Session [_ {:id (str (java.util.UUID/randomUUID)), :user_id user-id}]] (letfn [(session-count [] (db/count Session :user_id user-id))] (is (= 2 (session-count))) (user/set-password! user-id "PI:PASSWORD:<PASSWORD>END_PI") (is (= 0 (session-count)))))))) (deftest validate-locale-test (testing "`:locale` should be validated" (testing "creating a new User" (testing "valid locale" (mt/with-temp User [{user-id :id} {:locale "en_US"}] (is (= "en_US" (db/select-one-field :locale User :id user-id))))) (testing "invalid locale" (is (thrown? AssertionError (mt/with-temp User [{user-id :id} {:locale "en_XX"}]))))) (testing "updating a User" (mt/with-temp User [{user-id :id} {:locale "en_US"}] (testing "valid locale" (db/update! User user-id :locale "en_GB") (is (= "en_GB" (db/select-one-field :locale User :id user-id)))) (testing "invalid locale" (is (thrown? AssertionError (db/update! User user-id :locale "en_XX")))))))) (deftest normalize-locale-test (testing "`:locale` should be normalized" (mt/with-temp User [{user-id :id} {:locale "EN-us"}] (testing "creating a new User" (is (= "en_US" (db/select-one-field :locale User :id user-id)))) (testing "updating a User" (db/update! User user-id :locale "en-GB") (is (= "en_GB" (db/select-one-field :locale User :id user-id)))))))
[ { "context": "azon.awssdk.core ResponseBytes)))\n\n(def +db-key+ \"crux.ddb-s3.root\")\n\n(definline S [v] `(-> (AttributeValue/builder)", "end": 1332, "score": 0.99910569190979, "start": 1316, "tag": "KEY", "value": "crux.ddb-s3.root" }, { "context": "= :oldTx\")\n (.key {\"key\" (S +db-key+)})\n (.expressionAttributeName", "end": 8217, "score": 0.6106745004653931, "start": 8214, "tag": "KEY", "value": "key" }, { "context": " (let [tx-date (Date.)\n key (format \"%s%016x.%016x\" prefix tx (.getTime tx-date))\n ", "end": 11391, "score": 0.9324158430099487, "start": 11369, "tag": "KEY", "value": "format \"%s%016x.%016x\"" } ]
src/crux/ddb_s3/impl.clj
csm/crux-ddb-s3
2
(ns crux.ddb-s3.impl (:require [clojure.string :as string] [clojure.tools.logging :as log]) (:import (software.amazon.awssdk.services.dynamodb DynamoDbAsyncClient) (software.amazon.awssdk.services.dynamodb.model AttributeValue GetItemResponse GetItemRequest ConditionalCheckFailedException PutItemRequest UpdateItemRequest AttributeDefinition ScalarAttributeType KeySchemaElement KeyType CreateTableRequest ProvisionedThroughput DescribeTableRequest ResourceNotFoundException DescribeTableResponse TableStatus) (java.util.function Function) (java.util.concurrent CompletableFuture TimeUnit Executors ScheduledExecutorService) (crux.ddb_s3 DDBS3Configurator) (java.util Collection Date) (software.amazon.awssdk.services.s3 S3AsyncClient) (software.amazon.awssdk.services.s3.model HeadBucketRequest NoSuchBucketException CreateBucketRequest CreateBucketConfiguration BucketLocationConstraint ListObjectsV2Request ListObjectsV2Response S3Object GetObjectRequest PutObjectRequest) (software.amazon.awssdk.regions.providers DefaultAwsRegionProviderChain) (software.amazon.awssdk.core.async AsyncResponseTransformer AsyncRequestBody) (software.amazon.awssdk.core ResponseBytes))) (def +db-key+ "crux.ddb-s3.root") (definline S [v] `(-> (AttributeValue/builder) (.s ~v) (.build))) (definline N [v] `(-> (AttributeValue/builder) (.n (str ~v)) (.build))) (def ^:private -catch (reify Function (apply [_ e] e))) (def ^:private retry-executor (delay (Executors/newSingleThreadScheduledExecutor))) (defn- ^CompletableFuture delayed-future [delay ^TimeUnit delay-units] (let [future (CompletableFuture.)] (.schedule ^ScheduledExecutorService @retry-executor (reify Callable (call [_] (.complete future true))) (long delay) delay-units) future)) (def ^:private attribute-definitions [(-> (AttributeDefinition/builder) (.attributeName "key") (.attributeType ScalarAttributeType/S) (.build))]) (def ^:private key-schema [(-> (KeySchemaElement/builder) (.attributeName "key") (.keyType KeyType/HASH) (.build))]) (defn create-table [^DDBS3Configurator configurator ^DynamoDbAsyncClient client table-name] (let [request (-> (CreateTableRequest/builder) (.tableName table-name) (.attributeDefinitions ^Collection attribute-definitions) (.keySchema ^Collection key-schema) (.provisionedThroughput ^ProvisionedThroughput (-> (ProvisionedThroughput/builder) (.readCapacityUnits 1) (.writeCapacityUnits 1) (.build))) (->> (.createTable configurator)) (.build))] (.createTable client ^CreateTableRequest request))) (defn ensure-table-exists [^DDBS3Configurator configurator ^DynamoDbAsyncClient client table-name] (-> (.describeTable client ^DescribeTableRequest (-> (DescribeTableRequest/builder) (.tableName table-name) (.build))) (.exceptionally (reify Function (apply [_ e] (if (or (instance? ResourceNotFoundException e) (instance? ResourceNotFoundException (.getCause e))) nil (throw e))))) (.thenCompose (reify Function (apply [_ response] (if response (if (or (not= (set attribute-definitions) (-> ^DescribeTableResponse response (.table) (.attributeDefinitions) (set))) (not= (set key-schema) (-> ^DescribeTableResponse response (.table) (.keySchema) (set)))) (throw (ex-info "table exists but has an invalid schema" {:attribute-definitions (-> ^DescribeTableResponse response (.table) (.attributeDefinitions)) :key-schema (-> ^DescribeTableResponse response (.table) (.keySchema)) :required-attribute-definitions attribute-definitions :required-key-schema key-schema})) (CompletableFuture/completedFuture :ok)) (create-table configurator client table-name))))))) (defn ensure-table-ready [^DynamoDbAsyncClient client table-name] (-> (.describeTable client ^DescribeTableRequest (-> (DescribeTableRequest/builder) (.tableName table-name) (.build))) (.thenCompose (reify Function (apply [_ result] (if (some-> ^DescribeTableResponse result (.table) (.tableStatus) (= TableStatus/ACTIVE)) (CompletableFuture/completedFuture true) (.thenCompose (delayed-future 1 TimeUnit/SECONDS) (reify Function (apply [_ _] (ensure-table-ready client table-name)))))))))) (defn create-bucket [^DDBS3Configurator configurator ^S3AsyncClient client bucket-name] (.createBucket client ^CreateBucketRequest (-> (CreateBucketRequest/builder) (.bucket bucket-name) (.createBucketConfiguration ^CreateBucketConfiguration (-> (CreateBucketConfiguration/builder) (.locationConstraint (BucketLocationConstraint/fromValue (str (.getRegion (DefaultAwsRegionProviderChain.))))) (.build))) (->> (.createBucket configurator)) (.build)))) (defn ensure-bucket-exists [^DDBS3Configurator configurator ^S3AsyncClient client bucket-name] (-> (.headBucket client ^HeadBucketRequest (-> (HeadBucketRequest/builder) (.bucket bucket-name) (.build))) (.exceptionally (reify Function (apply [_ e] (if (or (instance? NoSuchBucketException e) (instance? NoSuchBucketException (.getCause e))) nil (throw e))))) (.thenCompose (reify Function (apply [_ result] (if (instance? Throwable result) (create-bucket configurator client bucket-name) (CompletableFuture/completedFuture true))))))) (defn- init-tx-info [^DynamoDbAsyncClient client table-name] (log/info (pr-str {:task ::init-tx-info :phase :begin})) (let [start (System/currentTimeMillis) tx 0 request (-> (PutItemRequest/builder) (.tableName table-name) (.item {"key" (S +db-key+) "currentTx" (N tx)}) (.conditionExpression "attribute_not_exists(#key)") (.expressionAttributeNames {"#key" "key"}) (.build))] (-> (.putItem client ^PutItemRequest request) (.exceptionally -catch) (.thenApply (reify Function (apply [_ _] (log/info (pr-str {:task ::init-tx-info :phase :end :ms (- (System/currentTimeMillis) start)})) tx)))))) (defn- increment-tx [^DynamoDbAsyncClient client table-name tx] (log/info (pr-str {:task ::increment-tx :phase :begin :tx tx})) (let [start (System/currentTimeMillis) next-tx (unchecked-inc tx) request (-> (UpdateItemRequest/builder) (.tableName table-name) (.updateExpression "SET #tx = :newTx") (.conditionExpression "#tx = :oldTx") (.key {"key" (S +db-key+)}) (.expressionAttributeNames {"#tx" "currentTx"}) (.expressionAttributeValues {":newTx" (N next-tx) ":oldTx" (N tx)}) (.build))] (-> (.updateItem client ^UpdateItemRequest request) (.thenApply (reify Function (apply [_ _] (log/info (pr-str {:task ::increment-tx :phase :end :next-tx next-tx :ms (- (System/currentTimeMillis) start)})) next-tx)))))) (defn select-next-txid [^DynamoDbAsyncClient client table-name & {:keys [delay] :or {delay 10}}] (let [start (System/currentTimeMillis)] (log/info (pr-str {:task ::select-next-txid :phase :begin})) (let [get-request (-> (GetItemRequest/builder) (.tableName table-name) (.consistentRead true) (.attributesToGet ["currentTx"]) (.key {"key" (S +db-key+)}) (.build))] (-> (.getItem client ^GetItemRequest get-request) (.thenCompose (reify Function (apply [_ response] (log/debug (pr-str {:task ::select-next-txid :phase :read-db-info :info response :ms (- (System/currentTimeMillis) start)})) (if (.hasItem ^GetItemResponse response) (increment-tx client table-name (-> ^GetItemResponse response (.item) ^AttributeValue (get "currentTx") (.n) (Long/parseLong))) (init-tx-info client table-name))))) (.exceptionally -catch) (.thenCompose (reify Function (apply [_ result] (if (instance? Throwable result) (if (or (instance? ConditionalCheckFailedException result) (instance? ConditionalCheckFailedException (.getCause ^Throwable result))) (-> (delayed-future delay TimeUnit/MILLISECONDS) (.thenCompose (reify Function (apply [_ _] (select-next-txid client table-name :delay (max 60000 (long (* delay 1.5)))))))) (throw result)) (do (log/info (pr-str {:task ::select-next-txid :phase :end :result result :ms (- (System/currentTimeMillis) start)})) (CompletableFuture/completedFuture result)))))))))) (defn submit-tx [^DDBS3Configurator configurator ^DynamoDbAsyncClient ddb-client ^S3AsyncClient s3-client table-name bucket-name prefix tx-events] (let [start (System/currentTimeMillis)] (log/info (pr-str {:task ::submit-tx :phase :start})) (-> (select-next-txid ddb-client table-name) (.thenCompose (reify Function (apply [_ tx] (log/info (pr-str {:task ::submit-tx :phase :commit-tx :tx tx :ms (- (System/currentTimeMillis) start)})) (let [tx-date (Date.) key (format "%s%016x.%016x" prefix tx (.getTime tx-date)) blob (.freeze configurator tx-events)] (-> (.putObject s3-client (-> (PutObjectRequest/builder) (.bucket bucket-name) (.key key) (->> (.putObject configurator)) ^PutObjectRequest (.build)) (AsyncRequestBody/fromBytes blob)) (.thenApply (reify Function (apply [_ _] (log/info (pr-str {:task ::submit-tx :phase :end :ms (- (System/currentTimeMillis) start)})) #:crux.tx{:tx-id tx :tx-time tx-date}))))))))))) (defn object->tx [^DDBS3Configurator configurator ^S3AsyncClient client ^S3Object object bucket-name prefix] (try (log/debug (pr-str {:task ::object->tx :phase :begin :key (.key object)})) (let [[tx date] (string/split (subs (.key object) (.length prefix)) #"\.") tx (Long/parseLong tx 16) date (Date. (Long/parseLong date 16)) start (System/currentTimeMillis) object @(.getObject client ^GetObjectRequest (-> (GetObjectRequest/builder) (.bucket bucket-name) (.key (.key object)) (.build)) (AsyncResponseTransformer/toBytes)) events (.thaw configurator (.asByteArray ^ResponseBytes object))] (log/debug (pr-str {:task ::object->tx :phase :end :ms (- (System/currentTimeMillis) start)})) {:crux.tx/tx-id tx :crux.tx/tx-time date :crux.tx.event/tx-events events}) (catch Exception x (log/warn x (str "skipping invalid object from S3 with key: " (.key object))) nil))) (defn object-iterator [^S3AsyncClient client bucket-name prefix from-tx continuation-token] (let [page ^ListObjectsV2Response @(.listObjectsV2 client ^ListObjectsV2Request (cond-> (ListObjectsV2Request/builder) :then (.bucket bucket-name) (some? from-tx) (.startAfter (format "%016x" from-tx)) (some? continuation-token) (.continuationToken continuation-token) :then (.prefix prefix) :then (.build))) next-page (when (.isTruncated page) (lazy-seq (object-iterator client bucket-name prefix nil (.continuationToken page))))] (concat (.contents page) next-page))) (defn tx-iterator [^DDBS3Configurator configurator ^S3AsyncClient client bucket-name prefix from-tx] (let [object-iter (object-iterator client bucket-name prefix from-tx nil)] (sequence (comp (map #(object->tx configurator client % bucket-name prefix)) (remove nil?)) object-iter))) (defn last-tx [^DynamoDbAsyncClient client table-name] (-> (.getItem client ^GetItemRequest (-> (GetItemRequest/builder) (.tableName table-name) (.key {"key" (S +db-key+)}) (.build))) (.thenApply (reify Function (apply [_ item] (when item (when-let [item (.item ^GetItemResponse item)] (when-let [tx (some-> item ^AttributeValue (get "currentTx") (.n) (Long/parseLong))] {:crux.tx/tx-id tx}))))))))
78691
(ns crux.ddb-s3.impl (:require [clojure.string :as string] [clojure.tools.logging :as log]) (:import (software.amazon.awssdk.services.dynamodb DynamoDbAsyncClient) (software.amazon.awssdk.services.dynamodb.model AttributeValue GetItemResponse GetItemRequest ConditionalCheckFailedException PutItemRequest UpdateItemRequest AttributeDefinition ScalarAttributeType KeySchemaElement KeyType CreateTableRequest ProvisionedThroughput DescribeTableRequest ResourceNotFoundException DescribeTableResponse TableStatus) (java.util.function Function) (java.util.concurrent CompletableFuture TimeUnit Executors ScheduledExecutorService) (crux.ddb_s3 DDBS3Configurator) (java.util Collection Date) (software.amazon.awssdk.services.s3 S3AsyncClient) (software.amazon.awssdk.services.s3.model HeadBucketRequest NoSuchBucketException CreateBucketRequest CreateBucketConfiguration BucketLocationConstraint ListObjectsV2Request ListObjectsV2Response S3Object GetObjectRequest PutObjectRequest) (software.amazon.awssdk.regions.providers DefaultAwsRegionProviderChain) (software.amazon.awssdk.core.async AsyncResponseTransformer AsyncRequestBody) (software.amazon.awssdk.core ResponseBytes))) (def +db-key+ "<KEY>") (definline S [v] `(-> (AttributeValue/builder) (.s ~v) (.build))) (definline N [v] `(-> (AttributeValue/builder) (.n (str ~v)) (.build))) (def ^:private -catch (reify Function (apply [_ e] e))) (def ^:private retry-executor (delay (Executors/newSingleThreadScheduledExecutor))) (defn- ^CompletableFuture delayed-future [delay ^TimeUnit delay-units] (let [future (CompletableFuture.)] (.schedule ^ScheduledExecutorService @retry-executor (reify Callable (call [_] (.complete future true))) (long delay) delay-units) future)) (def ^:private attribute-definitions [(-> (AttributeDefinition/builder) (.attributeName "key") (.attributeType ScalarAttributeType/S) (.build))]) (def ^:private key-schema [(-> (KeySchemaElement/builder) (.attributeName "key") (.keyType KeyType/HASH) (.build))]) (defn create-table [^DDBS3Configurator configurator ^DynamoDbAsyncClient client table-name] (let [request (-> (CreateTableRequest/builder) (.tableName table-name) (.attributeDefinitions ^Collection attribute-definitions) (.keySchema ^Collection key-schema) (.provisionedThroughput ^ProvisionedThroughput (-> (ProvisionedThroughput/builder) (.readCapacityUnits 1) (.writeCapacityUnits 1) (.build))) (->> (.createTable configurator)) (.build))] (.createTable client ^CreateTableRequest request))) (defn ensure-table-exists [^DDBS3Configurator configurator ^DynamoDbAsyncClient client table-name] (-> (.describeTable client ^DescribeTableRequest (-> (DescribeTableRequest/builder) (.tableName table-name) (.build))) (.exceptionally (reify Function (apply [_ e] (if (or (instance? ResourceNotFoundException e) (instance? ResourceNotFoundException (.getCause e))) nil (throw e))))) (.thenCompose (reify Function (apply [_ response] (if response (if (or (not= (set attribute-definitions) (-> ^DescribeTableResponse response (.table) (.attributeDefinitions) (set))) (not= (set key-schema) (-> ^DescribeTableResponse response (.table) (.keySchema) (set)))) (throw (ex-info "table exists but has an invalid schema" {:attribute-definitions (-> ^DescribeTableResponse response (.table) (.attributeDefinitions)) :key-schema (-> ^DescribeTableResponse response (.table) (.keySchema)) :required-attribute-definitions attribute-definitions :required-key-schema key-schema})) (CompletableFuture/completedFuture :ok)) (create-table configurator client table-name))))))) (defn ensure-table-ready [^DynamoDbAsyncClient client table-name] (-> (.describeTable client ^DescribeTableRequest (-> (DescribeTableRequest/builder) (.tableName table-name) (.build))) (.thenCompose (reify Function (apply [_ result] (if (some-> ^DescribeTableResponse result (.table) (.tableStatus) (= TableStatus/ACTIVE)) (CompletableFuture/completedFuture true) (.thenCompose (delayed-future 1 TimeUnit/SECONDS) (reify Function (apply [_ _] (ensure-table-ready client table-name)))))))))) (defn create-bucket [^DDBS3Configurator configurator ^S3AsyncClient client bucket-name] (.createBucket client ^CreateBucketRequest (-> (CreateBucketRequest/builder) (.bucket bucket-name) (.createBucketConfiguration ^CreateBucketConfiguration (-> (CreateBucketConfiguration/builder) (.locationConstraint (BucketLocationConstraint/fromValue (str (.getRegion (DefaultAwsRegionProviderChain.))))) (.build))) (->> (.createBucket configurator)) (.build)))) (defn ensure-bucket-exists [^DDBS3Configurator configurator ^S3AsyncClient client bucket-name] (-> (.headBucket client ^HeadBucketRequest (-> (HeadBucketRequest/builder) (.bucket bucket-name) (.build))) (.exceptionally (reify Function (apply [_ e] (if (or (instance? NoSuchBucketException e) (instance? NoSuchBucketException (.getCause e))) nil (throw e))))) (.thenCompose (reify Function (apply [_ result] (if (instance? Throwable result) (create-bucket configurator client bucket-name) (CompletableFuture/completedFuture true))))))) (defn- init-tx-info [^DynamoDbAsyncClient client table-name] (log/info (pr-str {:task ::init-tx-info :phase :begin})) (let [start (System/currentTimeMillis) tx 0 request (-> (PutItemRequest/builder) (.tableName table-name) (.item {"key" (S +db-key+) "currentTx" (N tx)}) (.conditionExpression "attribute_not_exists(#key)") (.expressionAttributeNames {"#key" "key"}) (.build))] (-> (.putItem client ^PutItemRequest request) (.exceptionally -catch) (.thenApply (reify Function (apply [_ _] (log/info (pr-str {:task ::init-tx-info :phase :end :ms (- (System/currentTimeMillis) start)})) tx)))))) (defn- increment-tx [^DynamoDbAsyncClient client table-name tx] (log/info (pr-str {:task ::increment-tx :phase :begin :tx tx})) (let [start (System/currentTimeMillis) next-tx (unchecked-inc tx) request (-> (UpdateItemRequest/builder) (.tableName table-name) (.updateExpression "SET #tx = :newTx") (.conditionExpression "#tx = :oldTx") (.key {"key" (S +db-<KEY>+)}) (.expressionAttributeNames {"#tx" "currentTx"}) (.expressionAttributeValues {":newTx" (N next-tx) ":oldTx" (N tx)}) (.build))] (-> (.updateItem client ^UpdateItemRequest request) (.thenApply (reify Function (apply [_ _] (log/info (pr-str {:task ::increment-tx :phase :end :next-tx next-tx :ms (- (System/currentTimeMillis) start)})) next-tx)))))) (defn select-next-txid [^DynamoDbAsyncClient client table-name & {:keys [delay] :or {delay 10}}] (let [start (System/currentTimeMillis)] (log/info (pr-str {:task ::select-next-txid :phase :begin})) (let [get-request (-> (GetItemRequest/builder) (.tableName table-name) (.consistentRead true) (.attributesToGet ["currentTx"]) (.key {"key" (S +db-key+)}) (.build))] (-> (.getItem client ^GetItemRequest get-request) (.thenCompose (reify Function (apply [_ response] (log/debug (pr-str {:task ::select-next-txid :phase :read-db-info :info response :ms (- (System/currentTimeMillis) start)})) (if (.hasItem ^GetItemResponse response) (increment-tx client table-name (-> ^GetItemResponse response (.item) ^AttributeValue (get "currentTx") (.n) (Long/parseLong))) (init-tx-info client table-name))))) (.exceptionally -catch) (.thenCompose (reify Function (apply [_ result] (if (instance? Throwable result) (if (or (instance? ConditionalCheckFailedException result) (instance? ConditionalCheckFailedException (.getCause ^Throwable result))) (-> (delayed-future delay TimeUnit/MILLISECONDS) (.thenCompose (reify Function (apply [_ _] (select-next-txid client table-name :delay (max 60000 (long (* delay 1.5)))))))) (throw result)) (do (log/info (pr-str {:task ::select-next-txid :phase :end :result result :ms (- (System/currentTimeMillis) start)})) (CompletableFuture/completedFuture result)))))))))) (defn submit-tx [^DDBS3Configurator configurator ^DynamoDbAsyncClient ddb-client ^S3AsyncClient s3-client table-name bucket-name prefix tx-events] (let [start (System/currentTimeMillis)] (log/info (pr-str {:task ::submit-tx :phase :start})) (-> (select-next-txid ddb-client table-name) (.thenCompose (reify Function (apply [_ tx] (log/info (pr-str {:task ::submit-tx :phase :commit-tx :tx tx :ms (- (System/currentTimeMillis) start)})) (let [tx-date (Date.) key (<KEY> prefix tx (.getTime tx-date)) blob (.freeze configurator tx-events)] (-> (.putObject s3-client (-> (PutObjectRequest/builder) (.bucket bucket-name) (.key key) (->> (.putObject configurator)) ^PutObjectRequest (.build)) (AsyncRequestBody/fromBytes blob)) (.thenApply (reify Function (apply [_ _] (log/info (pr-str {:task ::submit-tx :phase :end :ms (- (System/currentTimeMillis) start)})) #:crux.tx{:tx-id tx :tx-time tx-date}))))))))))) (defn object->tx [^DDBS3Configurator configurator ^S3AsyncClient client ^S3Object object bucket-name prefix] (try (log/debug (pr-str {:task ::object->tx :phase :begin :key (.key object)})) (let [[tx date] (string/split (subs (.key object) (.length prefix)) #"\.") tx (Long/parseLong tx 16) date (Date. (Long/parseLong date 16)) start (System/currentTimeMillis) object @(.getObject client ^GetObjectRequest (-> (GetObjectRequest/builder) (.bucket bucket-name) (.key (.key object)) (.build)) (AsyncResponseTransformer/toBytes)) events (.thaw configurator (.asByteArray ^ResponseBytes object))] (log/debug (pr-str {:task ::object->tx :phase :end :ms (- (System/currentTimeMillis) start)})) {:crux.tx/tx-id tx :crux.tx/tx-time date :crux.tx.event/tx-events events}) (catch Exception x (log/warn x (str "skipping invalid object from S3 with key: " (.key object))) nil))) (defn object-iterator [^S3AsyncClient client bucket-name prefix from-tx continuation-token] (let [page ^ListObjectsV2Response @(.listObjectsV2 client ^ListObjectsV2Request (cond-> (ListObjectsV2Request/builder) :then (.bucket bucket-name) (some? from-tx) (.startAfter (format "%016x" from-tx)) (some? continuation-token) (.continuationToken continuation-token) :then (.prefix prefix) :then (.build))) next-page (when (.isTruncated page) (lazy-seq (object-iterator client bucket-name prefix nil (.continuationToken page))))] (concat (.contents page) next-page))) (defn tx-iterator [^DDBS3Configurator configurator ^S3AsyncClient client bucket-name prefix from-tx] (let [object-iter (object-iterator client bucket-name prefix from-tx nil)] (sequence (comp (map #(object->tx configurator client % bucket-name prefix)) (remove nil?)) object-iter))) (defn last-tx [^DynamoDbAsyncClient client table-name] (-> (.getItem client ^GetItemRequest (-> (GetItemRequest/builder) (.tableName table-name) (.key {"key" (S +db-key+)}) (.build))) (.thenApply (reify Function (apply [_ item] (when item (when-let [item (.item ^GetItemResponse item)] (when-let [tx (some-> item ^AttributeValue (get "currentTx") (.n) (Long/parseLong))] {:crux.tx/tx-id tx}))))))))
true
(ns crux.ddb-s3.impl (:require [clojure.string :as string] [clojure.tools.logging :as log]) (:import (software.amazon.awssdk.services.dynamodb DynamoDbAsyncClient) (software.amazon.awssdk.services.dynamodb.model AttributeValue GetItemResponse GetItemRequest ConditionalCheckFailedException PutItemRequest UpdateItemRequest AttributeDefinition ScalarAttributeType KeySchemaElement KeyType CreateTableRequest ProvisionedThroughput DescribeTableRequest ResourceNotFoundException DescribeTableResponse TableStatus) (java.util.function Function) (java.util.concurrent CompletableFuture TimeUnit Executors ScheduledExecutorService) (crux.ddb_s3 DDBS3Configurator) (java.util Collection Date) (software.amazon.awssdk.services.s3 S3AsyncClient) (software.amazon.awssdk.services.s3.model HeadBucketRequest NoSuchBucketException CreateBucketRequest CreateBucketConfiguration BucketLocationConstraint ListObjectsV2Request ListObjectsV2Response S3Object GetObjectRequest PutObjectRequest) (software.amazon.awssdk.regions.providers DefaultAwsRegionProviderChain) (software.amazon.awssdk.core.async AsyncResponseTransformer AsyncRequestBody) (software.amazon.awssdk.core ResponseBytes))) (def +db-key+ "PI:KEY:<KEY>END_PI") (definline S [v] `(-> (AttributeValue/builder) (.s ~v) (.build))) (definline N [v] `(-> (AttributeValue/builder) (.n (str ~v)) (.build))) (def ^:private -catch (reify Function (apply [_ e] e))) (def ^:private retry-executor (delay (Executors/newSingleThreadScheduledExecutor))) (defn- ^CompletableFuture delayed-future [delay ^TimeUnit delay-units] (let [future (CompletableFuture.)] (.schedule ^ScheduledExecutorService @retry-executor (reify Callable (call [_] (.complete future true))) (long delay) delay-units) future)) (def ^:private attribute-definitions [(-> (AttributeDefinition/builder) (.attributeName "key") (.attributeType ScalarAttributeType/S) (.build))]) (def ^:private key-schema [(-> (KeySchemaElement/builder) (.attributeName "key") (.keyType KeyType/HASH) (.build))]) (defn create-table [^DDBS3Configurator configurator ^DynamoDbAsyncClient client table-name] (let [request (-> (CreateTableRequest/builder) (.tableName table-name) (.attributeDefinitions ^Collection attribute-definitions) (.keySchema ^Collection key-schema) (.provisionedThroughput ^ProvisionedThroughput (-> (ProvisionedThroughput/builder) (.readCapacityUnits 1) (.writeCapacityUnits 1) (.build))) (->> (.createTable configurator)) (.build))] (.createTable client ^CreateTableRequest request))) (defn ensure-table-exists [^DDBS3Configurator configurator ^DynamoDbAsyncClient client table-name] (-> (.describeTable client ^DescribeTableRequest (-> (DescribeTableRequest/builder) (.tableName table-name) (.build))) (.exceptionally (reify Function (apply [_ e] (if (or (instance? ResourceNotFoundException e) (instance? ResourceNotFoundException (.getCause e))) nil (throw e))))) (.thenCompose (reify Function (apply [_ response] (if response (if (or (not= (set attribute-definitions) (-> ^DescribeTableResponse response (.table) (.attributeDefinitions) (set))) (not= (set key-schema) (-> ^DescribeTableResponse response (.table) (.keySchema) (set)))) (throw (ex-info "table exists but has an invalid schema" {:attribute-definitions (-> ^DescribeTableResponse response (.table) (.attributeDefinitions)) :key-schema (-> ^DescribeTableResponse response (.table) (.keySchema)) :required-attribute-definitions attribute-definitions :required-key-schema key-schema})) (CompletableFuture/completedFuture :ok)) (create-table configurator client table-name))))))) (defn ensure-table-ready [^DynamoDbAsyncClient client table-name] (-> (.describeTable client ^DescribeTableRequest (-> (DescribeTableRequest/builder) (.tableName table-name) (.build))) (.thenCompose (reify Function (apply [_ result] (if (some-> ^DescribeTableResponse result (.table) (.tableStatus) (= TableStatus/ACTIVE)) (CompletableFuture/completedFuture true) (.thenCompose (delayed-future 1 TimeUnit/SECONDS) (reify Function (apply [_ _] (ensure-table-ready client table-name)))))))))) (defn create-bucket [^DDBS3Configurator configurator ^S3AsyncClient client bucket-name] (.createBucket client ^CreateBucketRequest (-> (CreateBucketRequest/builder) (.bucket bucket-name) (.createBucketConfiguration ^CreateBucketConfiguration (-> (CreateBucketConfiguration/builder) (.locationConstraint (BucketLocationConstraint/fromValue (str (.getRegion (DefaultAwsRegionProviderChain.))))) (.build))) (->> (.createBucket configurator)) (.build)))) (defn ensure-bucket-exists [^DDBS3Configurator configurator ^S3AsyncClient client bucket-name] (-> (.headBucket client ^HeadBucketRequest (-> (HeadBucketRequest/builder) (.bucket bucket-name) (.build))) (.exceptionally (reify Function (apply [_ e] (if (or (instance? NoSuchBucketException e) (instance? NoSuchBucketException (.getCause e))) nil (throw e))))) (.thenCompose (reify Function (apply [_ result] (if (instance? Throwable result) (create-bucket configurator client bucket-name) (CompletableFuture/completedFuture true))))))) (defn- init-tx-info [^DynamoDbAsyncClient client table-name] (log/info (pr-str {:task ::init-tx-info :phase :begin})) (let [start (System/currentTimeMillis) tx 0 request (-> (PutItemRequest/builder) (.tableName table-name) (.item {"key" (S +db-key+) "currentTx" (N tx)}) (.conditionExpression "attribute_not_exists(#key)") (.expressionAttributeNames {"#key" "key"}) (.build))] (-> (.putItem client ^PutItemRequest request) (.exceptionally -catch) (.thenApply (reify Function (apply [_ _] (log/info (pr-str {:task ::init-tx-info :phase :end :ms (- (System/currentTimeMillis) start)})) tx)))))) (defn- increment-tx [^DynamoDbAsyncClient client table-name tx] (log/info (pr-str {:task ::increment-tx :phase :begin :tx tx})) (let [start (System/currentTimeMillis) next-tx (unchecked-inc tx) request (-> (UpdateItemRequest/builder) (.tableName table-name) (.updateExpression "SET #tx = :newTx") (.conditionExpression "#tx = :oldTx") (.key {"key" (S +db-PI:KEY:<KEY>END_PI+)}) (.expressionAttributeNames {"#tx" "currentTx"}) (.expressionAttributeValues {":newTx" (N next-tx) ":oldTx" (N tx)}) (.build))] (-> (.updateItem client ^UpdateItemRequest request) (.thenApply (reify Function (apply [_ _] (log/info (pr-str {:task ::increment-tx :phase :end :next-tx next-tx :ms (- (System/currentTimeMillis) start)})) next-tx)))))) (defn select-next-txid [^DynamoDbAsyncClient client table-name & {:keys [delay] :or {delay 10}}] (let [start (System/currentTimeMillis)] (log/info (pr-str {:task ::select-next-txid :phase :begin})) (let [get-request (-> (GetItemRequest/builder) (.tableName table-name) (.consistentRead true) (.attributesToGet ["currentTx"]) (.key {"key" (S +db-key+)}) (.build))] (-> (.getItem client ^GetItemRequest get-request) (.thenCompose (reify Function (apply [_ response] (log/debug (pr-str {:task ::select-next-txid :phase :read-db-info :info response :ms (- (System/currentTimeMillis) start)})) (if (.hasItem ^GetItemResponse response) (increment-tx client table-name (-> ^GetItemResponse response (.item) ^AttributeValue (get "currentTx") (.n) (Long/parseLong))) (init-tx-info client table-name))))) (.exceptionally -catch) (.thenCompose (reify Function (apply [_ result] (if (instance? Throwable result) (if (or (instance? ConditionalCheckFailedException result) (instance? ConditionalCheckFailedException (.getCause ^Throwable result))) (-> (delayed-future delay TimeUnit/MILLISECONDS) (.thenCompose (reify Function (apply [_ _] (select-next-txid client table-name :delay (max 60000 (long (* delay 1.5)))))))) (throw result)) (do (log/info (pr-str {:task ::select-next-txid :phase :end :result result :ms (- (System/currentTimeMillis) start)})) (CompletableFuture/completedFuture result)))))))))) (defn submit-tx [^DDBS3Configurator configurator ^DynamoDbAsyncClient ddb-client ^S3AsyncClient s3-client table-name bucket-name prefix tx-events] (let [start (System/currentTimeMillis)] (log/info (pr-str {:task ::submit-tx :phase :start})) (-> (select-next-txid ddb-client table-name) (.thenCompose (reify Function (apply [_ tx] (log/info (pr-str {:task ::submit-tx :phase :commit-tx :tx tx :ms (- (System/currentTimeMillis) start)})) (let [tx-date (Date.) key (PI:KEY:<KEY>END_PI prefix tx (.getTime tx-date)) blob (.freeze configurator tx-events)] (-> (.putObject s3-client (-> (PutObjectRequest/builder) (.bucket bucket-name) (.key key) (->> (.putObject configurator)) ^PutObjectRequest (.build)) (AsyncRequestBody/fromBytes blob)) (.thenApply (reify Function (apply [_ _] (log/info (pr-str {:task ::submit-tx :phase :end :ms (- (System/currentTimeMillis) start)})) #:crux.tx{:tx-id tx :tx-time tx-date}))))))))))) (defn object->tx [^DDBS3Configurator configurator ^S3AsyncClient client ^S3Object object bucket-name prefix] (try (log/debug (pr-str {:task ::object->tx :phase :begin :key (.key object)})) (let [[tx date] (string/split (subs (.key object) (.length prefix)) #"\.") tx (Long/parseLong tx 16) date (Date. (Long/parseLong date 16)) start (System/currentTimeMillis) object @(.getObject client ^GetObjectRequest (-> (GetObjectRequest/builder) (.bucket bucket-name) (.key (.key object)) (.build)) (AsyncResponseTransformer/toBytes)) events (.thaw configurator (.asByteArray ^ResponseBytes object))] (log/debug (pr-str {:task ::object->tx :phase :end :ms (- (System/currentTimeMillis) start)})) {:crux.tx/tx-id tx :crux.tx/tx-time date :crux.tx.event/tx-events events}) (catch Exception x (log/warn x (str "skipping invalid object from S3 with key: " (.key object))) nil))) (defn object-iterator [^S3AsyncClient client bucket-name prefix from-tx continuation-token] (let [page ^ListObjectsV2Response @(.listObjectsV2 client ^ListObjectsV2Request (cond-> (ListObjectsV2Request/builder) :then (.bucket bucket-name) (some? from-tx) (.startAfter (format "%016x" from-tx)) (some? continuation-token) (.continuationToken continuation-token) :then (.prefix prefix) :then (.build))) next-page (when (.isTruncated page) (lazy-seq (object-iterator client bucket-name prefix nil (.continuationToken page))))] (concat (.contents page) next-page))) (defn tx-iterator [^DDBS3Configurator configurator ^S3AsyncClient client bucket-name prefix from-tx] (let [object-iter (object-iterator client bucket-name prefix from-tx nil)] (sequence (comp (map #(object->tx configurator client % bucket-name prefix)) (remove nil?)) object-iter))) (defn last-tx [^DynamoDbAsyncClient client table-name] (-> (.getItem client ^GetItemRequest (-> (GetItemRequest/builder) (.tableName table-name) (.key {"key" (S +db-key+)}) (.build))) (.thenApply (reify Function (apply [_ item] (when item (when-let [item (.item ^GetItemResponse item)] (when-let [tx (some-> item ^AttributeValue (get "currentTx") (.n) (Long/parseLong))] {:crux.tx/tx-id tx}))))))))
[ { "context": " (java.net URL)))\n\n;; https://github.com/weissjeffm/gdax-bot/blob/master/src/coinbase_api/core.clj\n\n;", "end": 623, "score": 0.9995101690292358, "start": 613, "tag": "USERNAME", "value": "weissjeffm" }, { "context": " [key message]\n (.init hmac (SecretKeySpec. key \"HmacSHA256\"))\n (.doFinal hmac message))\n\n(defn ^:private wr", "end": 1900, "score": 0.7157580852508545, "start": 1890, "tag": "KEY", "value": "HmacSHA256" } ]
crypto/src/crypto/services/gdax.clj
micahasmith/crypto-watch
6
(ns crypto.services.gdax (:require [gniazdo.core :as ws] [clojure.core.async :as a] [clojure.data.json :as json] [crypto.infra.helpers :refer :all] [crypto.infra.websockets :as websockets] [clj-http.client :as http] [taoensso.timbre :as timbre :refer [log trace debug info warn error fatal logf tracef debugf infof warnf errorf fatalf reportf spy get-env]]) (:import (java.util Base64) (javax.crypto.spec SecretKeySpec) (java.net URL))) ;; https://github.com/weissjeffm/gdax-bot/blob/master/src/coinbase_api/core.clj ;(def ws-url "wss://ws-feed-public.sandbox.exchange.coinbase.com") ;(def ws-url "wss://ws-feed.exchange.coinbase.com") (def ^:private ws-url "wss://ws-feed.gdax.com") ;(def api-url "https://api-public.sandbox.exchange.coinbase.com") (def ^:private api-url "https://api.gdax.com") ;; ;; websocket shiiiiiiit ;; (defn listen! [product-ids init-shutdown-chan to-chan] { :pre [(some? product-ids) (not-empty product-ids)] } (websockets/listen! ws-url 10000 init-shutdown-chan to-chan (fn [conn] (ws/send-msg conn (json/write-str {:type "subscribe" :gdax-api/product_ids product-ids})) (ws/send-msg conn (json/write-str {:type "heartbeat" :on true})) (ws/send-msg conn (json/write-str {:type "matches" :on true})) ))) ;; ;; REST af ;; (defonce ^:private hmac (javax.crypto.Mac/getInstance "HmacSHA256")) (defn ^:private encode [bs] (-> (Base64/getEncoder) (.encodeToString bs))) (defn ^:private decode [s] (-> (Base64/getDecoder) (.decode s))) (defn ^:private sign [key message] (.init hmac (SecretKeySpec. key "HmacSHA256")) (.doFinal hmac message)) (defn ^:private wrap-coinbase-auth [client] (fn [req] (let [sk (-> req :CB-ACCESS-SECRET decode) timestamp (format "%f" (/ (System/currentTimeMillis) 1000.0)) sign-message (str timestamp (-> req :method name .toUpperCase) (-> req :url (URL.) .getPath) (:body req)) headers {:CB-ACCESS-KEY (:CB-ACCESS-KEY req) :CB-ACCESS-SIGN (->> sign-message .getBytes (sign sk) encode) :CB-ACCESS-TIMESTAMP timestamp :CB-ACCESS-PASSPHRASE (:CB-ACCESS-PASSPHRASE req)}] (client (update-in req [:headers] merge headers))))) (defmacro ^:private with-coinbase-auth [& body] `(http/with-middleware (conj http/default-middleware #'wrap-coinbase-auth) ~@body)) (def ^:dynamic *credentials*) (defn -get [url] (with-coinbase-auth (http/get url *credentials*))) (defn -post [url body] (with-coinbase-auth (http/post url (assoc *credentials* :body body :content-type :json)))) (defn ^:private url [path] (format "%s%s" api-url path)) (defn get-products [] (->> (http/get (str api-url "/products") {:as :json}) :body)) (def ^:private -usd-xf (comp (filter #(= (-> % :quote_currency) "USD")))) (defn get-usd-products [] (->> (get-products) (eduction -usd-xf))) (defn get-product-book-2 [id] (->> (http/get (str api-url "/products/" id "/book?level=2") {:as :json}) :body)) (defn get-product-book-3 [id] (info "fecthing book" id) (->> (http/get (str api-url "/products/" id "/book?level=3") {:as :json}) :body)) (defrecord watch-books-msg [type obj ts]) (defn watch-books-3! [product-ids init-shudown-chan to-chan] (a/go-loop [msg (a/alt! init-shudown-chan :shutting-down (a/timeout 1100) :ok)] (cond (= msg :ok) (do (info "fetching books") (try (->> product-ids (map (fn [id] ;; pause (a/<!! (a/timeout 2000)) ;; get data (get-product-book-3 id))) (run! #(a/>!! to-chan (->watch-books-msg :book-3 % (now-string))))) (catch Exception e (do (error e "gdax books")))) (recur (a/alt! init-shudown-chan :shutting-down (a/timeout 60000) :ok))) :else (info "shutting down watch-books-3")))) ;(get-product-book "BTC-USD")
15942
(ns crypto.services.gdax (:require [gniazdo.core :as ws] [clojure.core.async :as a] [clojure.data.json :as json] [crypto.infra.helpers :refer :all] [crypto.infra.websockets :as websockets] [clj-http.client :as http] [taoensso.timbre :as timbre :refer [log trace debug info warn error fatal logf tracef debugf infof warnf errorf fatalf reportf spy get-env]]) (:import (java.util Base64) (javax.crypto.spec SecretKeySpec) (java.net URL))) ;; https://github.com/weissjeffm/gdax-bot/blob/master/src/coinbase_api/core.clj ;(def ws-url "wss://ws-feed-public.sandbox.exchange.coinbase.com") ;(def ws-url "wss://ws-feed.exchange.coinbase.com") (def ^:private ws-url "wss://ws-feed.gdax.com") ;(def api-url "https://api-public.sandbox.exchange.coinbase.com") (def ^:private api-url "https://api.gdax.com") ;; ;; websocket shiiiiiiit ;; (defn listen! [product-ids init-shutdown-chan to-chan] { :pre [(some? product-ids) (not-empty product-ids)] } (websockets/listen! ws-url 10000 init-shutdown-chan to-chan (fn [conn] (ws/send-msg conn (json/write-str {:type "subscribe" :gdax-api/product_ids product-ids})) (ws/send-msg conn (json/write-str {:type "heartbeat" :on true})) (ws/send-msg conn (json/write-str {:type "matches" :on true})) ))) ;; ;; REST af ;; (defonce ^:private hmac (javax.crypto.Mac/getInstance "HmacSHA256")) (defn ^:private encode [bs] (-> (Base64/getEncoder) (.encodeToString bs))) (defn ^:private decode [s] (-> (Base64/getDecoder) (.decode s))) (defn ^:private sign [key message] (.init hmac (SecretKeySpec. key "<KEY>")) (.doFinal hmac message)) (defn ^:private wrap-coinbase-auth [client] (fn [req] (let [sk (-> req :CB-ACCESS-SECRET decode) timestamp (format "%f" (/ (System/currentTimeMillis) 1000.0)) sign-message (str timestamp (-> req :method name .toUpperCase) (-> req :url (URL.) .getPath) (:body req)) headers {:CB-ACCESS-KEY (:CB-ACCESS-KEY req) :CB-ACCESS-SIGN (->> sign-message .getBytes (sign sk) encode) :CB-ACCESS-TIMESTAMP timestamp :CB-ACCESS-PASSPHRASE (:CB-ACCESS-PASSPHRASE req)}] (client (update-in req [:headers] merge headers))))) (defmacro ^:private with-coinbase-auth [& body] `(http/with-middleware (conj http/default-middleware #'wrap-coinbase-auth) ~@body)) (def ^:dynamic *credentials*) (defn -get [url] (with-coinbase-auth (http/get url *credentials*))) (defn -post [url body] (with-coinbase-auth (http/post url (assoc *credentials* :body body :content-type :json)))) (defn ^:private url [path] (format "%s%s" api-url path)) (defn get-products [] (->> (http/get (str api-url "/products") {:as :json}) :body)) (def ^:private -usd-xf (comp (filter #(= (-> % :quote_currency) "USD")))) (defn get-usd-products [] (->> (get-products) (eduction -usd-xf))) (defn get-product-book-2 [id] (->> (http/get (str api-url "/products/" id "/book?level=2") {:as :json}) :body)) (defn get-product-book-3 [id] (info "fecthing book" id) (->> (http/get (str api-url "/products/" id "/book?level=3") {:as :json}) :body)) (defrecord watch-books-msg [type obj ts]) (defn watch-books-3! [product-ids init-shudown-chan to-chan] (a/go-loop [msg (a/alt! init-shudown-chan :shutting-down (a/timeout 1100) :ok)] (cond (= msg :ok) (do (info "fetching books") (try (->> product-ids (map (fn [id] ;; pause (a/<!! (a/timeout 2000)) ;; get data (get-product-book-3 id))) (run! #(a/>!! to-chan (->watch-books-msg :book-3 % (now-string))))) (catch Exception e (do (error e "gdax books")))) (recur (a/alt! init-shudown-chan :shutting-down (a/timeout 60000) :ok))) :else (info "shutting down watch-books-3")))) ;(get-product-book "BTC-USD")
true
(ns crypto.services.gdax (:require [gniazdo.core :as ws] [clojure.core.async :as a] [clojure.data.json :as json] [crypto.infra.helpers :refer :all] [crypto.infra.websockets :as websockets] [clj-http.client :as http] [taoensso.timbre :as timbre :refer [log trace debug info warn error fatal logf tracef debugf infof warnf errorf fatalf reportf spy get-env]]) (:import (java.util Base64) (javax.crypto.spec SecretKeySpec) (java.net URL))) ;; https://github.com/weissjeffm/gdax-bot/blob/master/src/coinbase_api/core.clj ;(def ws-url "wss://ws-feed-public.sandbox.exchange.coinbase.com") ;(def ws-url "wss://ws-feed.exchange.coinbase.com") (def ^:private ws-url "wss://ws-feed.gdax.com") ;(def api-url "https://api-public.sandbox.exchange.coinbase.com") (def ^:private api-url "https://api.gdax.com") ;; ;; websocket shiiiiiiit ;; (defn listen! [product-ids init-shutdown-chan to-chan] { :pre [(some? product-ids) (not-empty product-ids)] } (websockets/listen! ws-url 10000 init-shutdown-chan to-chan (fn [conn] (ws/send-msg conn (json/write-str {:type "subscribe" :gdax-api/product_ids product-ids})) (ws/send-msg conn (json/write-str {:type "heartbeat" :on true})) (ws/send-msg conn (json/write-str {:type "matches" :on true})) ))) ;; ;; REST af ;; (defonce ^:private hmac (javax.crypto.Mac/getInstance "HmacSHA256")) (defn ^:private encode [bs] (-> (Base64/getEncoder) (.encodeToString bs))) (defn ^:private decode [s] (-> (Base64/getDecoder) (.decode s))) (defn ^:private sign [key message] (.init hmac (SecretKeySpec. key "PI:KEY:<KEY>END_PI")) (.doFinal hmac message)) (defn ^:private wrap-coinbase-auth [client] (fn [req] (let [sk (-> req :CB-ACCESS-SECRET decode) timestamp (format "%f" (/ (System/currentTimeMillis) 1000.0)) sign-message (str timestamp (-> req :method name .toUpperCase) (-> req :url (URL.) .getPath) (:body req)) headers {:CB-ACCESS-KEY (:CB-ACCESS-KEY req) :CB-ACCESS-SIGN (->> sign-message .getBytes (sign sk) encode) :CB-ACCESS-TIMESTAMP timestamp :CB-ACCESS-PASSPHRASE (:CB-ACCESS-PASSPHRASE req)}] (client (update-in req [:headers] merge headers))))) (defmacro ^:private with-coinbase-auth [& body] `(http/with-middleware (conj http/default-middleware #'wrap-coinbase-auth) ~@body)) (def ^:dynamic *credentials*) (defn -get [url] (with-coinbase-auth (http/get url *credentials*))) (defn -post [url body] (with-coinbase-auth (http/post url (assoc *credentials* :body body :content-type :json)))) (defn ^:private url [path] (format "%s%s" api-url path)) (defn get-products [] (->> (http/get (str api-url "/products") {:as :json}) :body)) (def ^:private -usd-xf (comp (filter #(= (-> % :quote_currency) "USD")))) (defn get-usd-products [] (->> (get-products) (eduction -usd-xf))) (defn get-product-book-2 [id] (->> (http/get (str api-url "/products/" id "/book?level=2") {:as :json}) :body)) (defn get-product-book-3 [id] (info "fecthing book" id) (->> (http/get (str api-url "/products/" id "/book?level=3") {:as :json}) :body)) (defrecord watch-books-msg [type obj ts]) (defn watch-books-3! [product-ids init-shudown-chan to-chan] (a/go-loop [msg (a/alt! init-shudown-chan :shutting-down (a/timeout 1100) :ok)] (cond (= msg :ok) (do (info "fetching books") (try (->> product-ids (map (fn [id] ;; pause (a/<!! (a/timeout 2000)) ;; get data (get-product-book-3 id))) (run! #(a/>!! to-chan (->watch-books-msg :book-3 % (now-string))))) (catch Exception e (do (error e "gdax books")))) (recur (a/alt! init-shudown-chan :shutting-down (a/timeout 60000) :ok))) :else (info "shutting down watch-books-3")))) ;(get-product-book "BTC-USD")
[ { "context": "e API for reading the form items\n (let [api-key \"42\"\n catalogue-item (-> (request :post \"/api/", "end": 382, "score": 0.9984522461891174, "start": 380, "tag": "KEY", "value": "42" }, { "context": "draft))\n\n(deftest forms-api-test\n (let [api-key \"42\"\n user-id \"owner\"]\n (testing \"get\"\n ", "end": 1131, "score": 0.9981906414031982, "start": 1129, "tag": "KEY", "value": "42" }, { "context": "\n\n(deftest option-form-item-test\n (let [api-key \"42\"\n user-id \"owner\"]\n (testing \"create\"\n ", "end": 3808, "score": 0.9033045768737793, "start": 3806, "tag": "KEY", "value": "42" } ]
test/clj/rems/test/api/forms.clj
secureb2share/secureb2share-rems
0
(ns ^:integration rems.test.api.forms (:require [clojure.test :refer :all] [rems.handler :refer [app]] [rems.test.api :refer :all] [ring.mock.request :refer :all]) (:import (java.util UUID))) (use-fixtures :once api-fixture) (defn- get-draft-form [form-id] ;; XXX: there is no simple API for reading the form items (let [api-key "42" catalogue-item (-> (request :post "/api/catalogue-items/create") (authenticate api-key "owner") (json-body {:title "tmp" :form form-id :resid 1 :wfid 1}) app assert-response-is-ok read-body) draft (-> (request :get "/api/applications/draft" {:catalogue-items (:id catalogue-item)}) (authenticate api-key "alice") app assert-response-is-ok read-body)] draft)) (deftest forms-api-test (let [api-key "42" user-id "owner"] (testing "get" (let [data (-> (request :get "/api/forms") (authenticate api-key user-id) app assert-response-is-ok read-body)] (is (coll-is-not-empty? data)) (is (= #{:id :organization :title :start :end :active} (set (keys (first data))))))) (testing "create" (let [command {:organization "abc" :title (str "form title " (UUID/randomUUID)) :items [{:title {:en "en title" :fi "fi title"} :optional true :type "text" :input-prompt {:en "en prompt" :fi "fi prompt"}}]}] (testing "invalid create" (let [command-with-invalid-maxlength (assoc-in command [:items 0 :maxlength] -1) response (-> (request :post "/api/forms/create") (authenticate api-key user-id) (json-body command-with-invalid-maxlength) app)] (is (= 400 (:status response)) "can't send negative maxlength"))) (testing "valid create" (-> (request :post "/api/forms/create") (authenticate api-key user-id) (json-body command) app assert-response-is-ok)) (testing "and fetch" (let [body (-> (request :get "/api/forms") (authenticate api-key user-id) app assert-response-is-ok read-body) form (->> body (filter #(= (:title %) (:title command))) first)] ;; TODO: create an API for reading full forms (will be needed latest for editing forms) (is (= (select-keys command [:title :organization]) (select-keys form [:title :organization]))) (is (= [{:optional true :type "text" :localizations {:en {:title "en title" :inputprompt "en prompt"} :fi {:title "fi title" :inputprompt "fi prompt"}}}] (->> (get-draft-form (:id form)) :items (map #(select-keys % [:optional :type :localizations]))))))))))) (deftest option-form-item-test (let [api-key "42" user-id "owner"] (testing "create" (let [command {:organization "abc" :title (str "form title " (UUID/randomUUID)) :items [{:title {:en "en title" :fi "fi title"} :optional true :type "option" :options [{:key "yes" :label {:en "Yes" :fi "Kyllä"}} {:key "no" :label {:en "No" :fi "Ei"}}]}]}] (-> (request :post "/api/forms/create") (authenticate api-key user-id) (json-body command) app assert-response-is-ok) (testing "and fetch" (let [body (-> (request :get "/api/forms") (authenticate api-key user-id) app assert-response-is-ok read-body) form (->> body (filter #(= (:title %) (:title command))) first)] (is (= [{:optional true :type "option" :localizations {:en {:title "en title" :inputprompt nil} :fi {:title "fi title" :inputprompt nil}} :options [{:key "yes" :label {:en "Yes" :fi "Kyllä"}} {:key "no" :label {:en "No" :fi "Ei"}}]}] (->> (get-draft-form (:id form)) :items (map #(select-keys % [:optional :type :localizations :options]))))))))))) (deftest forms-api-filtering-test (let [unfiltered (-> (request :get "/api/forms") (authenticate "42" "owner") app assert-response-is-ok read-body) filtered (-> (request :get "/api/forms" {:active true}) (authenticate "42" "owner") app assert-response-is-ok read-body)] (is (coll-is-not-empty? unfiltered)) (is (coll-is-not-empty? filtered)) (is (every? #(contains? % :active) unfiltered)) (is (every? :active filtered)) (is (< (count filtered) (count unfiltered))))) (deftest forms-api-security-test (testing "without authentication" (testing "list" (let [response (-> (request :get (str "/api/forms")) app) body (read-body response)] (is (response-is-unauthorized? response)) (is (= "unauthorized" body)))) (testing "create" (let [response (-> (request :post "/api/forms/create") (json-body {:organization "abc" :title "the title" :items []}) app)] (is (response-is-unauthorized? response)) (is (= "Invalid anti-forgery token" (read-body response)))))) (testing "without owner role" (testing "list" (let [response (-> (request :get (str "/api/forms")) (authenticate "42" "alice") app) body (read-body response)] (is (response-is-forbidden? response)) (is (= "forbidden" body)))) (testing "create" (let [response (-> (request :post "/api/forms/create") (authenticate "42" "alice") (json-body {:organization "abc" :title "the title" :items []}) app)] (is (response-is-forbidden? response)) (is (= "forbidden" (read-body response)))))))
23739
(ns ^:integration rems.test.api.forms (:require [clojure.test :refer :all] [rems.handler :refer [app]] [rems.test.api :refer :all] [ring.mock.request :refer :all]) (:import (java.util UUID))) (use-fixtures :once api-fixture) (defn- get-draft-form [form-id] ;; XXX: there is no simple API for reading the form items (let [api-key "<KEY>" catalogue-item (-> (request :post "/api/catalogue-items/create") (authenticate api-key "owner") (json-body {:title "tmp" :form form-id :resid 1 :wfid 1}) app assert-response-is-ok read-body) draft (-> (request :get "/api/applications/draft" {:catalogue-items (:id catalogue-item)}) (authenticate api-key "alice") app assert-response-is-ok read-body)] draft)) (deftest forms-api-test (let [api-key "<KEY>" user-id "owner"] (testing "get" (let [data (-> (request :get "/api/forms") (authenticate api-key user-id) app assert-response-is-ok read-body)] (is (coll-is-not-empty? data)) (is (= #{:id :organization :title :start :end :active} (set (keys (first data))))))) (testing "create" (let [command {:organization "abc" :title (str "form title " (UUID/randomUUID)) :items [{:title {:en "en title" :fi "fi title"} :optional true :type "text" :input-prompt {:en "en prompt" :fi "fi prompt"}}]}] (testing "invalid create" (let [command-with-invalid-maxlength (assoc-in command [:items 0 :maxlength] -1) response (-> (request :post "/api/forms/create") (authenticate api-key user-id) (json-body command-with-invalid-maxlength) app)] (is (= 400 (:status response)) "can't send negative maxlength"))) (testing "valid create" (-> (request :post "/api/forms/create") (authenticate api-key user-id) (json-body command) app assert-response-is-ok)) (testing "and fetch" (let [body (-> (request :get "/api/forms") (authenticate api-key user-id) app assert-response-is-ok read-body) form (->> body (filter #(= (:title %) (:title command))) first)] ;; TODO: create an API for reading full forms (will be needed latest for editing forms) (is (= (select-keys command [:title :organization]) (select-keys form [:title :organization]))) (is (= [{:optional true :type "text" :localizations {:en {:title "en title" :inputprompt "en prompt"} :fi {:title "fi title" :inputprompt "fi prompt"}}}] (->> (get-draft-form (:id form)) :items (map #(select-keys % [:optional :type :localizations]))))))))))) (deftest option-form-item-test (let [api-key "<KEY>" user-id "owner"] (testing "create" (let [command {:organization "abc" :title (str "form title " (UUID/randomUUID)) :items [{:title {:en "en title" :fi "fi title"} :optional true :type "option" :options [{:key "yes" :label {:en "Yes" :fi "Kyllä"}} {:key "no" :label {:en "No" :fi "Ei"}}]}]}] (-> (request :post "/api/forms/create") (authenticate api-key user-id) (json-body command) app assert-response-is-ok) (testing "and fetch" (let [body (-> (request :get "/api/forms") (authenticate api-key user-id) app assert-response-is-ok read-body) form (->> body (filter #(= (:title %) (:title command))) first)] (is (= [{:optional true :type "option" :localizations {:en {:title "en title" :inputprompt nil} :fi {:title "fi title" :inputprompt nil}} :options [{:key "yes" :label {:en "Yes" :fi "Kyllä"}} {:key "no" :label {:en "No" :fi "Ei"}}]}] (->> (get-draft-form (:id form)) :items (map #(select-keys % [:optional :type :localizations :options]))))))))))) (deftest forms-api-filtering-test (let [unfiltered (-> (request :get "/api/forms") (authenticate "42" "owner") app assert-response-is-ok read-body) filtered (-> (request :get "/api/forms" {:active true}) (authenticate "42" "owner") app assert-response-is-ok read-body)] (is (coll-is-not-empty? unfiltered)) (is (coll-is-not-empty? filtered)) (is (every? #(contains? % :active) unfiltered)) (is (every? :active filtered)) (is (< (count filtered) (count unfiltered))))) (deftest forms-api-security-test (testing "without authentication" (testing "list" (let [response (-> (request :get (str "/api/forms")) app) body (read-body response)] (is (response-is-unauthorized? response)) (is (= "unauthorized" body)))) (testing "create" (let [response (-> (request :post "/api/forms/create") (json-body {:organization "abc" :title "the title" :items []}) app)] (is (response-is-unauthorized? response)) (is (= "Invalid anti-forgery token" (read-body response)))))) (testing "without owner role" (testing "list" (let [response (-> (request :get (str "/api/forms")) (authenticate "42" "alice") app) body (read-body response)] (is (response-is-forbidden? response)) (is (= "forbidden" body)))) (testing "create" (let [response (-> (request :post "/api/forms/create") (authenticate "42" "alice") (json-body {:organization "abc" :title "the title" :items []}) app)] (is (response-is-forbidden? response)) (is (= "forbidden" (read-body response)))))))
true
(ns ^:integration rems.test.api.forms (:require [clojure.test :refer :all] [rems.handler :refer [app]] [rems.test.api :refer :all] [ring.mock.request :refer :all]) (:import (java.util UUID))) (use-fixtures :once api-fixture) (defn- get-draft-form [form-id] ;; XXX: there is no simple API for reading the form items (let [api-key "PI:KEY:<KEY>END_PI" catalogue-item (-> (request :post "/api/catalogue-items/create") (authenticate api-key "owner") (json-body {:title "tmp" :form form-id :resid 1 :wfid 1}) app assert-response-is-ok read-body) draft (-> (request :get "/api/applications/draft" {:catalogue-items (:id catalogue-item)}) (authenticate api-key "alice") app assert-response-is-ok read-body)] draft)) (deftest forms-api-test (let [api-key "PI:KEY:<KEY>END_PI" user-id "owner"] (testing "get" (let [data (-> (request :get "/api/forms") (authenticate api-key user-id) app assert-response-is-ok read-body)] (is (coll-is-not-empty? data)) (is (= #{:id :organization :title :start :end :active} (set (keys (first data))))))) (testing "create" (let [command {:organization "abc" :title (str "form title " (UUID/randomUUID)) :items [{:title {:en "en title" :fi "fi title"} :optional true :type "text" :input-prompt {:en "en prompt" :fi "fi prompt"}}]}] (testing "invalid create" (let [command-with-invalid-maxlength (assoc-in command [:items 0 :maxlength] -1) response (-> (request :post "/api/forms/create") (authenticate api-key user-id) (json-body command-with-invalid-maxlength) app)] (is (= 400 (:status response)) "can't send negative maxlength"))) (testing "valid create" (-> (request :post "/api/forms/create") (authenticate api-key user-id) (json-body command) app assert-response-is-ok)) (testing "and fetch" (let [body (-> (request :get "/api/forms") (authenticate api-key user-id) app assert-response-is-ok read-body) form (->> body (filter #(= (:title %) (:title command))) first)] ;; TODO: create an API for reading full forms (will be needed latest for editing forms) (is (= (select-keys command [:title :organization]) (select-keys form [:title :organization]))) (is (= [{:optional true :type "text" :localizations {:en {:title "en title" :inputprompt "en prompt"} :fi {:title "fi title" :inputprompt "fi prompt"}}}] (->> (get-draft-form (:id form)) :items (map #(select-keys % [:optional :type :localizations]))))))))))) (deftest option-form-item-test (let [api-key "PI:KEY:<KEY>END_PI" user-id "owner"] (testing "create" (let [command {:organization "abc" :title (str "form title " (UUID/randomUUID)) :items [{:title {:en "en title" :fi "fi title"} :optional true :type "option" :options [{:key "yes" :label {:en "Yes" :fi "Kyllä"}} {:key "no" :label {:en "No" :fi "Ei"}}]}]}] (-> (request :post "/api/forms/create") (authenticate api-key user-id) (json-body command) app assert-response-is-ok) (testing "and fetch" (let [body (-> (request :get "/api/forms") (authenticate api-key user-id) app assert-response-is-ok read-body) form (->> body (filter #(= (:title %) (:title command))) first)] (is (= [{:optional true :type "option" :localizations {:en {:title "en title" :inputprompt nil} :fi {:title "fi title" :inputprompt nil}} :options [{:key "yes" :label {:en "Yes" :fi "Kyllä"}} {:key "no" :label {:en "No" :fi "Ei"}}]}] (->> (get-draft-form (:id form)) :items (map #(select-keys % [:optional :type :localizations :options]))))))))))) (deftest forms-api-filtering-test (let [unfiltered (-> (request :get "/api/forms") (authenticate "42" "owner") app assert-response-is-ok read-body) filtered (-> (request :get "/api/forms" {:active true}) (authenticate "42" "owner") app assert-response-is-ok read-body)] (is (coll-is-not-empty? unfiltered)) (is (coll-is-not-empty? filtered)) (is (every? #(contains? % :active) unfiltered)) (is (every? :active filtered)) (is (< (count filtered) (count unfiltered))))) (deftest forms-api-security-test (testing "without authentication" (testing "list" (let [response (-> (request :get (str "/api/forms")) app) body (read-body response)] (is (response-is-unauthorized? response)) (is (= "unauthorized" body)))) (testing "create" (let [response (-> (request :post "/api/forms/create") (json-body {:organization "abc" :title "the title" :items []}) app)] (is (response-is-unauthorized? response)) (is (= "Invalid anti-forgery token" (read-body response)))))) (testing "without owner role" (testing "list" (let [response (-> (request :get (str "/api/forms")) (authenticate "42" "alice") app) body (read-body response)] (is (response-is-forbidden? response)) (is (= "forbidden" body)))) (testing "create" (let [response (-> (request :post "/api/forms/create") (authenticate "42" "alice") (json-body {:organization "abc" :title "the title" :items []}) app)] (is (response-is-forbidden? response)) (is (= "forbidden" (read-body response)))))))
[ { "context": "; Copyright (c) 2021 Mikołaj Kuranowski\n; SPDX-License-Identifier: WTFPL\n(ns core\n (:req", "end": 39, "score": 0.9996190071105957, "start": 21, "tag": "NAME", "value": "Mikołaj Kuranowski" } ]
src/core.clj
MKuranowski/AdventOfCode2020
0
; Copyright (c) 2021 Mikołaj Kuranowski ; SPDX-License-Identifier: WTFPL (ns core (:require [clojure.java.io :refer [file]] [clojure.string :refer [split-lines]])) (defn parse-int "Tries to parse a base-10 integer" [s] (Integer/parseInt s 10)) (defn lines-from-file "Returns a vector of all lines in a file" [filename] (split-lines (slurp (file filename)))) (defn split-on "Splits a sequence by sub-sequences for which (pred elem) is true. The provided predicate must return pure booleans." [pred coll] (let [!pred (complement pred)] (->> coll (partition-by pred) (filter #(!pred (first %)))))) (def non-nil? (complement nil?)) (defn count-if [pred coll] (reduce + (for [i coll, :when (pred i)] 1))) (defn transpose [coll] (apply map list coll))
120872
; Copyright (c) 2021 <NAME> ; SPDX-License-Identifier: WTFPL (ns core (:require [clojure.java.io :refer [file]] [clojure.string :refer [split-lines]])) (defn parse-int "Tries to parse a base-10 integer" [s] (Integer/parseInt s 10)) (defn lines-from-file "Returns a vector of all lines in a file" [filename] (split-lines (slurp (file filename)))) (defn split-on "Splits a sequence by sub-sequences for which (pred elem) is true. The provided predicate must return pure booleans." [pred coll] (let [!pred (complement pred)] (->> coll (partition-by pred) (filter #(!pred (first %)))))) (def non-nil? (complement nil?)) (defn count-if [pred coll] (reduce + (for [i coll, :when (pred i)] 1))) (defn transpose [coll] (apply map list coll))
true
; Copyright (c) 2021 PI:NAME:<NAME>END_PI ; SPDX-License-Identifier: WTFPL (ns core (:require [clojure.java.io :refer [file]] [clojure.string :refer [split-lines]])) (defn parse-int "Tries to parse a base-10 integer" [s] (Integer/parseInt s 10)) (defn lines-from-file "Returns a vector of all lines in a file" [filename] (split-lines (slurp (file filename)))) (defn split-on "Splits a sequence by sub-sequences for which (pred elem) is true. The provided predicate must return pure booleans." [pred coll] (let [!pred (complement pred)] (->> coll (partition-by pred) (filter #(!pred (first %)))))) (def non-nil? (complement nil?)) (defn count-if [pred coll] (reduce + (for [i coll, :when (pred i)] 1))) (defn transpose [coll] (apply map list coll))
[ { "context": ";;;;;;;;;;;;;;;;;;;;;;;;;;;\n;; Copyright (c) 2008, J. Bester\n;; All rights reserved.\n;;\n;; Redistribution and ", "end": 432, "score": 0.9998812079429626, "start": 423, "tag": "NAME", "value": "J. Bester" } ]
src/cljext/seq.clj
jbester/cljext
9
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; File : seq.clj ;; Function : sequence library ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Send comments or questions to code at freshlime dot org ;; $Id: d7d6133d042ce9c4a2f520bf3b13e95758e5eb83 $ ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Copyright (c) 2008, J. Bester ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are met: ;; * Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; * Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ``AS IS'' AND ANY ;; EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY ;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; ;; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ;; ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ns cljext.seq (:refer-clojure) ) (defn map* "Map that allows mismatch sized lists e.g. (map* vector '(1 2) '(3 4 5)) => ([1 3] [2 4] [nil 5]) " ([fn & cols] (let [len (map count cols)] (loop [result nil cols cols] (if (every? empty? cols) (reverse result) (recur (conj result (apply fn (map first cols))) (map rest cols))))))) (defn vector-map* "Vector Map that allows mismatch sized inputs e.g. (vector-map* vector '(1 2) '(3 4 5)) => ([1 3] [2 4] [nil 5]) " ([fn & cols] (let [len (map count cols)] (loop [result [] cols cols] (if (every? empty? cols) result (recur (conj result (apply fn (map first cols))) (map rest cols))))))) (defn zip "Zip two or more lists together" ([& cols] (apply map vector cols))) (defn zip* "Zip two or more lists together allows uneven lists" ([& cols] (apply map* vector cols))) (defn lazy-zip "A lazy version of zip" ([& cols] (lazy-seq (when-let [s (seq cols)] (cons (apply vector (map first s)) (apply map vector (map rest s))))))) (defn lazy-zip* "Lazily Zip two or more lists together allows uneven lists" ([& cols] (lazy-seq (when-let [s (seq cols)] (cons (apply vector (map* first s)) (apply map* vector (map rest s))))))) (defn unzip "Unzip one list into a list of lists" ([col] (let [length (count col)] (partition length (apply interleave col))))) (defn enumerate "Enumerate a list e.g. '(a b c d) => '([0 a] [1 b] [2 c] [3 d])" ([col] (zip (iterate inc 0) col))) (defn count-if "Count number of times predicate true in a list" ([pred col] (count (for [item col :when (pred item)] item)))) (defn count-occurances "Count number of occurances in a list of specified item" ([item col] (count-if (partial = item) col))) (defn member? "Test for membership in a list" ([el col pred] (loop [col col] (let [[hd & tl] col] (cond (empty? col) false (pred el hd) hd true (recur tl))))) ([el col] (member? el col =))) (defn positions "Return the list of positions where a given element resides" ([el col] (for [[idx elem] (enumerate col) :when (= elem el)] idx))) (defn list-tabulate "Create a list by calling the provided func with the position as a parameter" ([n func] (for [i (range n)] (func i)))) (defn flatten-1 "Flatten the list but only up to the depth of one" ([col] (with-local-vars [result nil] (doseq [term col] (if (seq? term) (var-set result (concat @result term)) (var-set result (concat @result (list term))))) @result))) (defn vector-map "Vector equivalent of map" ([fn & seq] (loop [result [] seq seq] (if (some empty? seq) result (recur (conj result (apply fn (map first seq))) (map rest seq)))))) (defn vector-filter "Vector equivalent of filter" ([fn seq] (loop [result [] seq seq] (if (empty? seq) result (recur (if (fn (first seq)) (conj result (first seq)) result) (rest seq)))))) (defn vector-tabulate "Create a vector based on call func for each position with the index as a parameter i.e. (vector-map 3 f) => [(f 0) (f 1) (f 2)]" ([n func] (vector-map func (range n)))) (defn list->vector "Convert a list to a vector" ([col] (apply vector (seq col)))) (defn min-max "Calculate min and max of a sequence" ([col] (loop [col col cur-min nil cur-max nil] (if (nil? col) [cur-min cur-max] (let [[f & r] col] (cond (or (nil? cur-min) (< f cur-min)) (recur r f cur-max) (or (nil? cur-max) (> f cur-max)) (recur r cur-min f) true (recur r cur-min cur-max))))))) (defn freq "Calculate frequency of items in collection" ([col] (let [freqs (atom {})] (doseq [item col] (let [f (get @freqs item 0)] (swap! freqs assoc item (inc f)))) @freqs)))
49543
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; File : seq.clj ;; Function : sequence library ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Send comments or questions to code at freshlime dot org ;; $Id: d7d6133d042ce9c4a2f520bf3b13e95758e5eb83 $ ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Copyright (c) 2008, <NAME> ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are met: ;; * Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; * Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ``AS IS'' AND ANY ;; EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY ;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; ;; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ;; ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ns cljext.seq (:refer-clojure) ) (defn map* "Map that allows mismatch sized lists e.g. (map* vector '(1 2) '(3 4 5)) => ([1 3] [2 4] [nil 5]) " ([fn & cols] (let [len (map count cols)] (loop [result nil cols cols] (if (every? empty? cols) (reverse result) (recur (conj result (apply fn (map first cols))) (map rest cols))))))) (defn vector-map* "Vector Map that allows mismatch sized inputs e.g. (vector-map* vector '(1 2) '(3 4 5)) => ([1 3] [2 4] [nil 5]) " ([fn & cols] (let [len (map count cols)] (loop [result [] cols cols] (if (every? empty? cols) result (recur (conj result (apply fn (map first cols))) (map rest cols))))))) (defn zip "Zip two or more lists together" ([& cols] (apply map vector cols))) (defn zip* "Zip two or more lists together allows uneven lists" ([& cols] (apply map* vector cols))) (defn lazy-zip "A lazy version of zip" ([& cols] (lazy-seq (when-let [s (seq cols)] (cons (apply vector (map first s)) (apply map vector (map rest s))))))) (defn lazy-zip* "Lazily Zip two or more lists together allows uneven lists" ([& cols] (lazy-seq (when-let [s (seq cols)] (cons (apply vector (map* first s)) (apply map* vector (map rest s))))))) (defn unzip "Unzip one list into a list of lists" ([col] (let [length (count col)] (partition length (apply interleave col))))) (defn enumerate "Enumerate a list e.g. '(a b c d) => '([0 a] [1 b] [2 c] [3 d])" ([col] (zip (iterate inc 0) col))) (defn count-if "Count number of times predicate true in a list" ([pred col] (count (for [item col :when (pred item)] item)))) (defn count-occurances "Count number of occurances in a list of specified item" ([item col] (count-if (partial = item) col))) (defn member? "Test for membership in a list" ([el col pred] (loop [col col] (let [[hd & tl] col] (cond (empty? col) false (pred el hd) hd true (recur tl))))) ([el col] (member? el col =))) (defn positions "Return the list of positions where a given element resides" ([el col] (for [[idx elem] (enumerate col) :when (= elem el)] idx))) (defn list-tabulate "Create a list by calling the provided func with the position as a parameter" ([n func] (for [i (range n)] (func i)))) (defn flatten-1 "Flatten the list but only up to the depth of one" ([col] (with-local-vars [result nil] (doseq [term col] (if (seq? term) (var-set result (concat @result term)) (var-set result (concat @result (list term))))) @result))) (defn vector-map "Vector equivalent of map" ([fn & seq] (loop [result [] seq seq] (if (some empty? seq) result (recur (conj result (apply fn (map first seq))) (map rest seq)))))) (defn vector-filter "Vector equivalent of filter" ([fn seq] (loop [result [] seq seq] (if (empty? seq) result (recur (if (fn (first seq)) (conj result (first seq)) result) (rest seq)))))) (defn vector-tabulate "Create a vector based on call func for each position with the index as a parameter i.e. (vector-map 3 f) => [(f 0) (f 1) (f 2)]" ([n func] (vector-map func (range n)))) (defn list->vector "Convert a list to a vector" ([col] (apply vector (seq col)))) (defn min-max "Calculate min and max of a sequence" ([col] (loop [col col cur-min nil cur-max nil] (if (nil? col) [cur-min cur-max] (let [[f & r] col] (cond (or (nil? cur-min) (< f cur-min)) (recur r f cur-max) (or (nil? cur-max) (> f cur-max)) (recur r cur-min f) true (recur r cur-min cur-max))))))) (defn freq "Calculate frequency of items in collection" ([col] (let [freqs (atom {})] (doseq [item col] (let [f (get @freqs item 0)] (swap! freqs assoc item (inc f)))) @freqs)))
true
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; File : seq.clj ;; Function : sequence library ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Send comments or questions to code at freshlime dot org ;; $Id: d7d6133d042ce9c4a2f520bf3b13e95758e5eb83 $ ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Copyright (c) 2008, PI:NAME:<NAME>END_PI ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are met: ;; * Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; * Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ``AS IS'' AND ANY ;; EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY ;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; ;; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ;; ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ns cljext.seq (:refer-clojure) ) (defn map* "Map that allows mismatch sized lists e.g. (map* vector '(1 2) '(3 4 5)) => ([1 3] [2 4] [nil 5]) " ([fn & cols] (let [len (map count cols)] (loop [result nil cols cols] (if (every? empty? cols) (reverse result) (recur (conj result (apply fn (map first cols))) (map rest cols))))))) (defn vector-map* "Vector Map that allows mismatch sized inputs e.g. (vector-map* vector '(1 2) '(3 4 5)) => ([1 3] [2 4] [nil 5]) " ([fn & cols] (let [len (map count cols)] (loop [result [] cols cols] (if (every? empty? cols) result (recur (conj result (apply fn (map first cols))) (map rest cols))))))) (defn zip "Zip two or more lists together" ([& cols] (apply map vector cols))) (defn zip* "Zip two or more lists together allows uneven lists" ([& cols] (apply map* vector cols))) (defn lazy-zip "A lazy version of zip" ([& cols] (lazy-seq (when-let [s (seq cols)] (cons (apply vector (map first s)) (apply map vector (map rest s))))))) (defn lazy-zip* "Lazily Zip two or more lists together allows uneven lists" ([& cols] (lazy-seq (when-let [s (seq cols)] (cons (apply vector (map* first s)) (apply map* vector (map rest s))))))) (defn unzip "Unzip one list into a list of lists" ([col] (let [length (count col)] (partition length (apply interleave col))))) (defn enumerate "Enumerate a list e.g. '(a b c d) => '([0 a] [1 b] [2 c] [3 d])" ([col] (zip (iterate inc 0) col))) (defn count-if "Count number of times predicate true in a list" ([pred col] (count (for [item col :when (pred item)] item)))) (defn count-occurances "Count number of occurances in a list of specified item" ([item col] (count-if (partial = item) col))) (defn member? "Test for membership in a list" ([el col pred] (loop [col col] (let [[hd & tl] col] (cond (empty? col) false (pred el hd) hd true (recur tl))))) ([el col] (member? el col =))) (defn positions "Return the list of positions where a given element resides" ([el col] (for [[idx elem] (enumerate col) :when (= elem el)] idx))) (defn list-tabulate "Create a list by calling the provided func with the position as a parameter" ([n func] (for [i (range n)] (func i)))) (defn flatten-1 "Flatten the list but only up to the depth of one" ([col] (with-local-vars [result nil] (doseq [term col] (if (seq? term) (var-set result (concat @result term)) (var-set result (concat @result (list term))))) @result))) (defn vector-map "Vector equivalent of map" ([fn & seq] (loop [result [] seq seq] (if (some empty? seq) result (recur (conj result (apply fn (map first seq))) (map rest seq)))))) (defn vector-filter "Vector equivalent of filter" ([fn seq] (loop [result [] seq seq] (if (empty? seq) result (recur (if (fn (first seq)) (conj result (first seq)) result) (rest seq)))))) (defn vector-tabulate "Create a vector based on call func for each position with the index as a parameter i.e. (vector-map 3 f) => [(f 0) (f 1) (f 2)]" ([n func] (vector-map func (range n)))) (defn list->vector "Convert a list to a vector" ([col] (apply vector (seq col)))) (defn min-max "Calculate min and max of a sequence" ([col] (loop [col col cur-min nil cur-max nil] (if (nil? col) [cur-min cur-max] (let [[f & r] col] (cond (or (nil? cur-min) (< f cur-min)) (recur r f cur-max) (or (nil? cur-max) (> f cur-max)) (recur r cur-min f) true (recur r cur-min cur-max))))))) (defn freq "Calculate frequency of items in collection" ([col] (let [freqs (atom {})] (doseq [item col] (let [f (get @freqs item 0)] (swap! freqs assoc item (inc f)))) @freqs)))
[ { "context": "s car]))\n\n(def redis-conn {:pool {} :spec {:host \"127.0.0.1\"\n :port 6377}})\n(", "end": 664, "score": 0.9997000098228455, "start": 655, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "\"\n :client-id \"billingApp\"\n :client-password \"fe0a7e01-8b66-4706-8f37-e7d333c29e6f\"\n :redirect-uri \"http://localhost:3000/auth-cod", "end": 1138, "score": 0.9992712736129761, "start": 1102, "tag": "PASSWORD", "value": "fe0a7e01-8b66-4706-8f37-e7d333c29e6f" } ]
clj-auth-service/src/core/sso_clojure.clj
sguessou/sso-clojure
2
(ns core.sso-clojure (:require [cheshire.core :refer [generate-string parse-string]] [clj-http.client :as client] [clojure.walk :refer [keywordize-keys]] [muuntaja.middleware :as muuntaja] [reitit.ring :as reitit] [ring.adapter.jetty :as jetty] [ring.util.http-response :as response] [ring.util.response :refer [redirect]] [ring.middleware.reload :refer [wrap-reload]] [ring.util.codec :as codec] [selmer.parser :as selmer] [selmer.middleware :refer [wrap-error-page]] [slingshot.slingshot :refer [try+ throw+]] [taoensso.timbre :as log] [taoensso.carmine :as car])) (def redis-conn {:pool {} :spec {:host "127.0.0.1" :port 6377}}) (defmacro wcar* [& body] `(car/wcar redis-conn ~@body)) (def config {:auth-url "http://localhost:8080/auth/realms/sso-test/protocol/openid-connect/auth" :logout-url "http://localhost:8080/auth/realms/sso-test/protocol/openid-connect/logout" :token-endpoint "http://localhost:8080/auth/realms/sso-test/protocol/openid-connect/token" :client-id "billingApp" :client-password "fe0a7e01-8b66-4706-8f37-e7d333c29e6f" :redirect-uri "http://localhost:3000/auth-code-redirect" :landing-page "http://localhost:3000" :services-endpoint "http://localhost:4000/billing/v1/services"}) (def app-var (atom {})) (defn wrap-nocache [handler] (fn [request] (-> request handler (assoc-in [:headers "Pragma"] "no-cache")))) (defn wrap-formats [handler] (-> handler (muuntaja/wrap-format))) (defn response-handler [request] (response/ok (str "<html><body>your IP is: " (:remote-addr request) "</body></html>"))) (defn home-handler [request] (response/ok (selmer/render-file "login.html" {:title "~=[λ RuL3z!]=~" :session (:session-state @app-var) :code (:code @app-var) :access-token (get-in @app-var [:token :access_token]) :refresh-token (get-in @app-var [:token :refresh_token]) :scope (get-in @app-var [:token :scope]) :services (:services @app-var)}))) (defn login-handler [request] (let [state (.toString (java.util.UUID/randomUUID))] (wcar* (car/set (str "STATE-" state) state "EX" 180)) ;; create a redirect URL for authentication endpoint. (let [client_id (:client-id config) redirect_uri (:redirect-uri config) query-string (client/generate-query-string {:client_id client_id :response_type "code" :redirect_uri redirect_uri :state state}) auth-url (:auth-url config)] (redirect (str auth-url "?" query-string))))) (defn get-token [] (client/post (:token-endpoint config) {:headers {"Content-Type" "application/x-www-form-urlencoded"} :basic-auth [(:client-id config) (:client-password config)] :form-params {:grant_type "authorization_code" :code (:code @app-var) :redirect_uri (:redirect-uri config) :client_id (:client-id config)}})) (defn- format-response [resp] (-> resp :body parse-string keywordize-keys)) (defn- exchange-token [] (let [token (get-token)] (swap! app-var assoc :token (format-response token)) (log/info ::exchange-token {:token (get-in @app-var [:token :token_type])}) (redirect (:landing-page config)))) (defn auth-code-redirect [request] (log/info ::auth-redirect {:query-string (:query-string request)}) (let [query-params (-> request :query-string codec/form-decode keywordize-keys) landing-page (:landing-page config) state (:state query-params)] (log/info ::auth-code-redirect {:state state}) (if (nil? (wcar* (car/get (str "STATE-" state)))) (do (log/info ::auth-code-redirect {:error "State Error"}) (response/bad-request "Error")) (do (swap! app-var assoc :code (:code query-params) :session-state (:session_state query-params)) (wcar* (car/set (str "STATE-" state) nil)) (exchange-token))))) (defn logout-handler [request] (let [query-string (client/generate-query-string {:redirect_uri (:landing-page config)}) logout-url (str (:logout-url config) "?" query-string)] (reset! app-var {}) (redirect logout-url))) (defn services-handler [request] (log/info ::services-handler {:addr (:remote-addr request)}) ;; redis is used here for debugging purposes only #_(wcar* (car/set (str "TEST-TOKEN-" (.toString (java.util.UUID/randomUUID))) "TEST" "EX" 180)) (if-let [services (try+ (client/get (:services-endpoint config) {:headers {"Authorization" (str "Bearer " (get-in @app-var [:token :access_token]))} :socket-timeout 500 :connection-timeout 500}) (catch Object _ (log/error ::services "Upstream error") (response/bad-request "upstream-error")))] (do (swap! app-var assoc :services (-> services :body parse-string (get "services"))) (log/info ::services {:services services}) (redirect (:landing-page config))) (do (swap! app-var assoc :service {:services []}) (redirect (:landing-page config))))) (defn refresh-token [request] (let [response (client/post (:token-endpoint config) {:headers {"Content-Type" "application/x-www-form-urlencoded"} :basic-auth [(:client-id config) (:client-password config)] :form-params {:grant_type "refresh_token" :refresh_token (get-in @app-var [:token :refresh_token])}})] (log/info ::refresh-token {:token (format-response response)}) (redirect (:landing-page config)))) (def routes [["/" {:get home-handler}] ["/login" {:get login-handler}] ["/services" {:get services-handler :options services-handler}] ["/logout" {:get logout-handler}] ["/refresh-token" {:get refresh-token}] ["/auth-code-redirect" {:get auth-code-redirect}]]) (def handler (reitit/routes (reitit/ring-handler (reitit/router routes)) (reitit/create-resource-handler {:path "/"}) (reitit/create-default-handler {:not-found (constantly (response/not-found "404 - Page not found")) :method-not-allowed (constantly (response/method-not-allowed "405 - Not allowed")) :not-acceptable (constantly (response/not-acceptable "406 - Not acceptable"))}))) (defn -main [] (jetty/run-jetty (-> #'handler wrap-nocache wrap-reload) {:port 3000 :join? false}))
113314
(ns core.sso-clojure (:require [cheshire.core :refer [generate-string parse-string]] [clj-http.client :as client] [clojure.walk :refer [keywordize-keys]] [muuntaja.middleware :as muuntaja] [reitit.ring :as reitit] [ring.adapter.jetty :as jetty] [ring.util.http-response :as response] [ring.util.response :refer [redirect]] [ring.middleware.reload :refer [wrap-reload]] [ring.util.codec :as codec] [selmer.parser :as selmer] [selmer.middleware :refer [wrap-error-page]] [slingshot.slingshot :refer [try+ throw+]] [taoensso.timbre :as log] [taoensso.carmine :as car])) (def redis-conn {:pool {} :spec {:host "127.0.0.1" :port 6377}}) (defmacro wcar* [& body] `(car/wcar redis-conn ~@body)) (def config {:auth-url "http://localhost:8080/auth/realms/sso-test/protocol/openid-connect/auth" :logout-url "http://localhost:8080/auth/realms/sso-test/protocol/openid-connect/logout" :token-endpoint "http://localhost:8080/auth/realms/sso-test/protocol/openid-connect/token" :client-id "billingApp" :client-password "<PASSWORD>" :redirect-uri "http://localhost:3000/auth-code-redirect" :landing-page "http://localhost:3000" :services-endpoint "http://localhost:4000/billing/v1/services"}) (def app-var (atom {})) (defn wrap-nocache [handler] (fn [request] (-> request handler (assoc-in [:headers "Pragma"] "no-cache")))) (defn wrap-formats [handler] (-> handler (muuntaja/wrap-format))) (defn response-handler [request] (response/ok (str "<html><body>your IP is: " (:remote-addr request) "</body></html>"))) (defn home-handler [request] (response/ok (selmer/render-file "login.html" {:title "~=[λ RuL3z!]=~" :session (:session-state @app-var) :code (:code @app-var) :access-token (get-in @app-var [:token :access_token]) :refresh-token (get-in @app-var [:token :refresh_token]) :scope (get-in @app-var [:token :scope]) :services (:services @app-var)}))) (defn login-handler [request] (let [state (.toString (java.util.UUID/randomUUID))] (wcar* (car/set (str "STATE-" state) state "EX" 180)) ;; create a redirect URL for authentication endpoint. (let [client_id (:client-id config) redirect_uri (:redirect-uri config) query-string (client/generate-query-string {:client_id client_id :response_type "code" :redirect_uri redirect_uri :state state}) auth-url (:auth-url config)] (redirect (str auth-url "?" query-string))))) (defn get-token [] (client/post (:token-endpoint config) {:headers {"Content-Type" "application/x-www-form-urlencoded"} :basic-auth [(:client-id config) (:client-password config)] :form-params {:grant_type "authorization_code" :code (:code @app-var) :redirect_uri (:redirect-uri config) :client_id (:client-id config)}})) (defn- format-response [resp] (-> resp :body parse-string keywordize-keys)) (defn- exchange-token [] (let [token (get-token)] (swap! app-var assoc :token (format-response token)) (log/info ::exchange-token {:token (get-in @app-var [:token :token_type])}) (redirect (:landing-page config)))) (defn auth-code-redirect [request] (log/info ::auth-redirect {:query-string (:query-string request)}) (let [query-params (-> request :query-string codec/form-decode keywordize-keys) landing-page (:landing-page config) state (:state query-params)] (log/info ::auth-code-redirect {:state state}) (if (nil? (wcar* (car/get (str "STATE-" state)))) (do (log/info ::auth-code-redirect {:error "State Error"}) (response/bad-request "Error")) (do (swap! app-var assoc :code (:code query-params) :session-state (:session_state query-params)) (wcar* (car/set (str "STATE-" state) nil)) (exchange-token))))) (defn logout-handler [request] (let [query-string (client/generate-query-string {:redirect_uri (:landing-page config)}) logout-url (str (:logout-url config) "?" query-string)] (reset! app-var {}) (redirect logout-url))) (defn services-handler [request] (log/info ::services-handler {:addr (:remote-addr request)}) ;; redis is used here for debugging purposes only #_(wcar* (car/set (str "TEST-TOKEN-" (.toString (java.util.UUID/randomUUID))) "TEST" "EX" 180)) (if-let [services (try+ (client/get (:services-endpoint config) {:headers {"Authorization" (str "Bearer " (get-in @app-var [:token :access_token]))} :socket-timeout 500 :connection-timeout 500}) (catch Object _ (log/error ::services "Upstream error") (response/bad-request "upstream-error")))] (do (swap! app-var assoc :services (-> services :body parse-string (get "services"))) (log/info ::services {:services services}) (redirect (:landing-page config))) (do (swap! app-var assoc :service {:services []}) (redirect (:landing-page config))))) (defn refresh-token [request] (let [response (client/post (:token-endpoint config) {:headers {"Content-Type" "application/x-www-form-urlencoded"} :basic-auth [(:client-id config) (:client-password config)] :form-params {:grant_type "refresh_token" :refresh_token (get-in @app-var [:token :refresh_token])}})] (log/info ::refresh-token {:token (format-response response)}) (redirect (:landing-page config)))) (def routes [["/" {:get home-handler}] ["/login" {:get login-handler}] ["/services" {:get services-handler :options services-handler}] ["/logout" {:get logout-handler}] ["/refresh-token" {:get refresh-token}] ["/auth-code-redirect" {:get auth-code-redirect}]]) (def handler (reitit/routes (reitit/ring-handler (reitit/router routes)) (reitit/create-resource-handler {:path "/"}) (reitit/create-default-handler {:not-found (constantly (response/not-found "404 - Page not found")) :method-not-allowed (constantly (response/method-not-allowed "405 - Not allowed")) :not-acceptable (constantly (response/not-acceptable "406 - Not acceptable"))}))) (defn -main [] (jetty/run-jetty (-> #'handler wrap-nocache wrap-reload) {:port 3000 :join? false}))
true
(ns core.sso-clojure (:require [cheshire.core :refer [generate-string parse-string]] [clj-http.client :as client] [clojure.walk :refer [keywordize-keys]] [muuntaja.middleware :as muuntaja] [reitit.ring :as reitit] [ring.adapter.jetty :as jetty] [ring.util.http-response :as response] [ring.util.response :refer [redirect]] [ring.middleware.reload :refer [wrap-reload]] [ring.util.codec :as codec] [selmer.parser :as selmer] [selmer.middleware :refer [wrap-error-page]] [slingshot.slingshot :refer [try+ throw+]] [taoensso.timbre :as log] [taoensso.carmine :as car])) (def redis-conn {:pool {} :spec {:host "127.0.0.1" :port 6377}}) (defmacro wcar* [& body] `(car/wcar redis-conn ~@body)) (def config {:auth-url "http://localhost:8080/auth/realms/sso-test/protocol/openid-connect/auth" :logout-url "http://localhost:8080/auth/realms/sso-test/protocol/openid-connect/logout" :token-endpoint "http://localhost:8080/auth/realms/sso-test/protocol/openid-connect/token" :client-id "billingApp" :client-password "PI:PASSWORD:<PASSWORD>END_PI" :redirect-uri "http://localhost:3000/auth-code-redirect" :landing-page "http://localhost:3000" :services-endpoint "http://localhost:4000/billing/v1/services"}) (def app-var (atom {})) (defn wrap-nocache [handler] (fn [request] (-> request handler (assoc-in [:headers "Pragma"] "no-cache")))) (defn wrap-formats [handler] (-> handler (muuntaja/wrap-format))) (defn response-handler [request] (response/ok (str "<html><body>your IP is: " (:remote-addr request) "</body></html>"))) (defn home-handler [request] (response/ok (selmer/render-file "login.html" {:title "~=[λ RuL3z!]=~" :session (:session-state @app-var) :code (:code @app-var) :access-token (get-in @app-var [:token :access_token]) :refresh-token (get-in @app-var [:token :refresh_token]) :scope (get-in @app-var [:token :scope]) :services (:services @app-var)}))) (defn login-handler [request] (let [state (.toString (java.util.UUID/randomUUID))] (wcar* (car/set (str "STATE-" state) state "EX" 180)) ;; create a redirect URL for authentication endpoint. (let [client_id (:client-id config) redirect_uri (:redirect-uri config) query-string (client/generate-query-string {:client_id client_id :response_type "code" :redirect_uri redirect_uri :state state}) auth-url (:auth-url config)] (redirect (str auth-url "?" query-string))))) (defn get-token [] (client/post (:token-endpoint config) {:headers {"Content-Type" "application/x-www-form-urlencoded"} :basic-auth [(:client-id config) (:client-password config)] :form-params {:grant_type "authorization_code" :code (:code @app-var) :redirect_uri (:redirect-uri config) :client_id (:client-id config)}})) (defn- format-response [resp] (-> resp :body parse-string keywordize-keys)) (defn- exchange-token [] (let [token (get-token)] (swap! app-var assoc :token (format-response token)) (log/info ::exchange-token {:token (get-in @app-var [:token :token_type])}) (redirect (:landing-page config)))) (defn auth-code-redirect [request] (log/info ::auth-redirect {:query-string (:query-string request)}) (let [query-params (-> request :query-string codec/form-decode keywordize-keys) landing-page (:landing-page config) state (:state query-params)] (log/info ::auth-code-redirect {:state state}) (if (nil? (wcar* (car/get (str "STATE-" state)))) (do (log/info ::auth-code-redirect {:error "State Error"}) (response/bad-request "Error")) (do (swap! app-var assoc :code (:code query-params) :session-state (:session_state query-params)) (wcar* (car/set (str "STATE-" state) nil)) (exchange-token))))) (defn logout-handler [request] (let [query-string (client/generate-query-string {:redirect_uri (:landing-page config)}) logout-url (str (:logout-url config) "?" query-string)] (reset! app-var {}) (redirect logout-url))) (defn services-handler [request] (log/info ::services-handler {:addr (:remote-addr request)}) ;; redis is used here for debugging purposes only #_(wcar* (car/set (str "TEST-TOKEN-" (.toString (java.util.UUID/randomUUID))) "TEST" "EX" 180)) (if-let [services (try+ (client/get (:services-endpoint config) {:headers {"Authorization" (str "Bearer " (get-in @app-var [:token :access_token]))} :socket-timeout 500 :connection-timeout 500}) (catch Object _ (log/error ::services "Upstream error") (response/bad-request "upstream-error")))] (do (swap! app-var assoc :services (-> services :body parse-string (get "services"))) (log/info ::services {:services services}) (redirect (:landing-page config))) (do (swap! app-var assoc :service {:services []}) (redirect (:landing-page config))))) (defn refresh-token [request] (let [response (client/post (:token-endpoint config) {:headers {"Content-Type" "application/x-www-form-urlencoded"} :basic-auth [(:client-id config) (:client-password config)] :form-params {:grant_type "refresh_token" :refresh_token (get-in @app-var [:token :refresh_token])}})] (log/info ::refresh-token {:token (format-response response)}) (redirect (:landing-page config)))) (def routes [["/" {:get home-handler}] ["/login" {:get login-handler}] ["/services" {:get services-handler :options services-handler}] ["/logout" {:get logout-handler}] ["/refresh-token" {:get refresh-token}] ["/auth-code-redirect" {:get auth-code-redirect}]]) (def handler (reitit/routes (reitit/ring-handler (reitit/router routes)) (reitit/create-resource-handler {:path "/"}) (reitit/create-default-handler {:not-found (constantly (response/not-found "404 - Page not found")) :method-not-allowed (constantly (response/method-not-allowed "405 - Not allowed")) :not-acceptable (constantly (response/not-acceptable "406 - Not acceptable"))}))) (defn -main [] (jetty/run-jetty (-> #'handler wrap-nocache wrap-reload) {:port 3000 :join? false}))
[ { "context": "ondence for an individual market.\"\n :author \"Anna Shchiptsova\"}\n commodities-auction.compute.demand-corresponde", "end": 570, "score": 0.9998854398727417, "start": 554, "tag": "NAME", "value": "Anna Shchiptsova" } ]
src/commodities_auction/compute/demand_correspondence.clj
shchipts/commodities-auction
0
; Copyright (c) 2020 International Institute for Applied Systems Analysis. ; All rights reserved. The use and distribution terms for this software ; are covered by the MIT License (http://opensource.org/licenses/MIT) ; which can be found in the file LICENSE at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns ^{:doc "Demand correspondence for an individual market." :author "Anna Shchiptsova"} commodities-auction.compute.demand-correspondence (:require [clojure.set :as s])) (defn- entry-with-home "Appends domestic industry supply to imports." [{entry :entry demand :demand total-demand :total-demand}] (assoc entry :home (- total-demand demand))) (defn- demand-fn "Returns supply function." [entry exit] (fn [price] (cond (<= price entry) 0 (> price exit) (- exit entry) :else (- price entry)))) (defn- demand-fns "Returns collection of supply functions." [entry exit] (->> (keys entry) ((juxt identity (fn [ks] (map #(demand-fn (get entry %) (get exit %)) ks)))) (apply zipmap))) (defn- exit "Returns a hash map of supply constraints for market imports." [{supply :supply entry :entry total-demand :total-demand}] (reduce-kv (fn [m k v] (->> (get entry k) (+ v) (#(if (> % total-demand) total-demand %)) (assoc m k))) {} supply)) (defn- exit-with-home "Returns a hash map of supply constraints for market imports and domestic insdustry." [market-parameters] (assoc (exit market-parameters) :home (:total-demand market-parameters))) (defn- construct "Constructs demand correspondence from parameters." ([total-demand] (construct 0 1 total-demand {})) ([k n price kernel] (hash-map :k k :n n :kernel kernel :price price))) (defn build "Builds correspondence between optimal import bundles and market price. Arguments to this function must include parameters of import supply curves, market demand and total demand in the network of commodity markets. If provided, search for demand set starts from the specified price level." ([market-parameters] (build market-parameters 0)) ([{supply :supply demand :demand entry :entry total-demand :total-demand :as market-parameters} price] (let [exit_ (exit-with-home market-parameters) entry_ (entry-with-home market-parameters) fns (demand-fns entry_ exit_) aggregate #(->> (vals fns) (map (fn [f] (f %))) (apply +))] (if (->> (vals entry) (filter #(< % total-demand)) not-empty) (->> (vals entry_) (concat (vals exit_)) (filter #(not (< % price))) (#(conj % price)) distinct sort (map #(vector % (aggregate %))) (take-while #(<= (second %) demand)) last ((fn [[p v]] (let [fquery (let [active (filter #(and (> (get exit_ %) p) (<= (get entry_ %) p)) (keys fns))] (fn [f] (f (- demand v) (count active)))) kp (+ (fquery quot) p) next-price (if (pos? (fquery mod)) (inc kp) kp)] (->> (dissoc fns :home) (filter (fn [[_ f]] (pos? (f next-price)))) (into {}) (reduce-kv #(assoc %1 %2 (%3 kp)) {}) (construct (- demand (aggregate kp)) (->> (keys fns) (filter #(and (>= (get exit_ %) next-price) (< (get entry_ %) next-price))) count) next-price)))))) (construct total-demand))))) (defn price-inc "Measures price increment for next iteration in English auction from single market data. Arguments to this function must include list of importers in the excess demand set, market parameters and current market price." [ids {entry :entry :as market-parameters} {p :price}] (let [exit (exit market-parameters) entry_ (entry-with-home market-parameters) present (->> (filter (fn [[_ v]] (< v p)) entry_) (map first) set)] (if (= present (set ids)) (->> (keys entry_) (#(s/difference (set %) (set ids))) vec (select-keys entry_) vals (apply min) (#(- (inc %) p))) (->> (set ids) (s/intersection present) (reduce #(let [x (if (< (get exit %2) p) (- p (get exit %2)) 1)] (cond (= x 1) (reduced 1) (nil? %1) x (< x %1) x :else %1)) nil))))) (defn rebuild "Rebuilds correspondence between optimal import bundles and market price starting from necessary price for imports obtained in the previous iteration of English auction. Arguments to this function must include market parameters and results of previous iteration." [market-parameters {price :price k :k}] (build market-parameters (if (zero? k) price (dec price))))
80081
; Copyright (c) 2020 International Institute for Applied Systems Analysis. ; All rights reserved. The use and distribution terms for this software ; are covered by the MIT License (http://opensource.org/licenses/MIT) ; which can be found in the file LICENSE at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns ^{:doc "Demand correspondence for an individual market." :author "<NAME>"} commodities-auction.compute.demand-correspondence (:require [clojure.set :as s])) (defn- entry-with-home "Appends domestic industry supply to imports." [{entry :entry demand :demand total-demand :total-demand}] (assoc entry :home (- total-demand demand))) (defn- demand-fn "Returns supply function." [entry exit] (fn [price] (cond (<= price entry) 0 (> price exit) (- exit entry) :else (- price entry)))) (defn- demand-fns "Returns collection of supply functions." [entry exit] (->> (keys entry) ((juxt identity (fn [ks] (map #(demand-fn (get entry %) (get exit %)) ks)))) (apply zipmap))) (defn- exit "Returns a hash map of supply constraints for market imports." [{supply :supply entry :entry total-demand :total-demand}] (reduce-kv (fn [m k v] (->> (get entry k) (+ v) (#(if (> % total-demand) total-demand %)) (assoc m k))) {} supply)) (defn- exit-with-home "Returns a hash map of supply constraints for market imports and domestic insdustry." [market-parameters] (assoc (exit market-parameters) :home (:total-demand market-parameters))) (defn- construct "Constructs demand correspondence from parameters." ([total-demand] (construct 0 1 total-demand {})) ([k n price kernel] (hash-map :k k :n n :kernel kernel :price price))) (defn build "Builds correspondence between optimal import bundles and market price. Arguments to this function must include parameters of import supply curves, market demand and total demand in the network of commodity markets. If provided, search for demand set starts from the specified price level." ([market-parameters] (build market-parameters 0)) ([{supply :supply demand :demand entry :entry total-demand :total-demand :as market-parameters} price] (let [exit_ (exit-with-home market-parameters) entry_ (entry-with-home market-parameters) fns (demand-fns entry_ exit_) aggregate #(->> (vals fns) (map (fn [f] (f %))) (apply +))] (if (->> (vals entry) (filter #(< % total-demand)) not-empty) (->> (vals entry_) (concat (vals exit_)) (filter #(not (< % price))) (#(conj % price)) distinct sort (map #(vector % (aggregate %))) (take-while #(<= (second %) demand)) last ((fn [[p v]] (let [fquery (let [active (filter #(and (> (get exit_ %) p) (<= (get entry_ %) p)) (keys fns))] (fn [f] (f (- demand v) (count active)))) kp (+ (fquery quot) p) next-price (if (pos? (fquery mod)) (inc kp) kp)] (->> (dissoc fns :home) (filter (fn [[_ f]] (pos? (f next-price)))) (into {}) (reduce-kv #(assoc %1 %2 (%3 kp)) {}) (construct (- demand (aggregate kp)) (->> (keys fns) (filter #(and (>= (get exit_ %) next-price) (< (get entry_ %) next-price))) count) next-price)))))) (construct total-demand))))) (defn price-inc "Measures price increment for next iteration in English auction from single market data. Arguments to this function must include list of importers in the excess demand set, market parameters and current market price." [ids {entry :entry :as market-parameters} {p :price}] (let [exit (exit market-parameters) entry_ (entry-with-home market-parameters) present (->> (filter (fn [[_ v]] (< v p)) entry_) (map first) set)] (if (= present (set ids)) (->> (keys entry_) (#(s/difference (set %) (set ids))) vec (select-keys entry_) vals (apply min) (#(- (inc %) p))) (->> (set ids) (s/intersection present) (reduce #(let [x (if (< (get exit %2) p) (- p (get exit %2)) 1)] (cond (= x 1) (reduced 1) (nil? %1) x (< x %1) x :else %1)) nil))))) (defn rebuild "Rebuilds correspondence between optimal import bundles and market price starting from necessary price for imports obtained in the previous iteration of English auction. Arguments to this function must include market parameters and results of previous iteration." [market-parameters {price :price k :k}] (build market-parameters (if (zero? k) price (dec price))))
true
; Copyright (c) 2020 International Institute for Applied Systems Analysis. ; All rights reserved. The use and distribution terms for this software ; are covered by the MIT License (http://opensource.org/licenses/MIT) ; which can be found in the file LICENSE at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns ^{:doc "Demand correspondence for an individual market." :author "PI:NAME:<NAME>END_PI"} commodities-auction.compute.demand-correspondence (:require [clojure.set :as s])) (defn- entry-with-home "Appends domestic industry supply to imports." [{entry :entry demand :demand total-demand :total-demand}] (assoc entry :home (- total-demand demand))) (defn- demand-fn "Returns supply function." [entry exit] (fn [price] (cond (<= price entry) 0 (> price exit) (- exit entry) :else (- price entry)))) (defn- demand-fns "Returns collection of supply functions." [entry exit] (->> (keys entry) ((juxt identity (fn [ks] (map #(demand-fn (get entry %) (get exit %)) ks)))) (apply zipmap))) (defn- exit "Returns a hash map of supply constraints for market imports." [{supply :supply entry :entry total-demand :total-demand}] (reduce-kv (fn [m k v] (->> (get entry k) (+ v) (#(if (> % total-demand) total-demand %)) (assoc m k))) {} supply)) (defn- exit-with-home "Returns a hash map of supply constraints for market imports and domestic insdustry." [market-parameters] (assoc (exit market-parameters) :home (:total-demand market-parameters))) (defn- construct "Constructs demand correspondence from parameters." ([total-demand] (construct 0 1 total-demand {})) ([k n price kernel] (hash-map :k k :n n :kernel kernel :price price))) (defn build "Builds correspondence between optimal import bundles and market price. Arguments to this function must include parameters of import supply curves, market demand and total demand in the network of commodity markets. If provided, search for demand set starts from the specified price level." ([market-parameters] (build market-parameters 0)) ([{supply :supply demand :demand entry :entry total-demand :total-demand :as market-parameters} price] (let [exit_ (exit-with-home market-parameters) entry_ (entry-with-home market-parameters) fns (demand-fns entry_ exit_) aggregate #(->> (vals fns) (map (fn [f] (f %))) (apply +))] (if (->> (vals entry) (filter #(< % total-demand)) not-empty) (->> (vals entry_) (concat (vals exit_)) (filter #(not (< % price))) (#(conj % price)) distinct sort (map #(vector % (aggregate %))) (take-while #(<= (second %) demand)) last ((fn [[p v]] (let [fquery (let [active (filter #(and (> (get exit_ %) p) (<= (get entry_ %) p)) (keys fns))] (fn [f] (f (- demand v) (count active)))) kp (+ (fquery quot) p) next-price (if (pos? (fquery mod)) (inc kp) kp)] (->> (dissoc fns :home) (filter (fn [[_ f]] (pos? (f next-price)))) (into {}) (reduce-kv #(assoc %1 %2 (%3 kp)) {}) (construct (- demand (aggregate kp)) (->> (keys fns) (filter #(and (>= (get exit_ %) next-price) (< (get entry_ %) next-price))) count) next-price)))))) (construct total-demand))))) (defn price-inc "Measures price increment for next iteration in English auction from single market data. Arguments to this function must include list of importers in the excess demand set, market parameters and current market price." [ids {entry :entry :as market-parameters} {p :price}] (let [exit (exit market-parameters) entry_ (entry-with-home market-parameters) present (->> (filter (fn [[_ v]] (< v p)) entry_) (map first) set)] (if (= present (set ids)) (->> (keys entry_) (#(s/difference (set %) (set ids))) vec (select-keys entry_) vals (apply min) (#(- (inc %) p))) (->> (set ids) (s/intersection present) (reduce #(let [x (if (< (get exit %2) p) (- p (get exit %2)) 1)] (cond (= x 1) (reduced 1) (nil? %1) x (< x %1) x :else %1)) nil))))) (defn rebuild "Rebuilds correspondence between optimal import bundles and market price starting from necessary price for imports obtained in the previous iteration of English auction. Arguments to this function must include market parameters and results of previous iteration." [market-parameters {price :price k :k}] (build market-parameters (if (zero? k) price (dec price))))
[ { "context": "ib.conf :refer [conf]]))\n;\n\n;; https://github.com/tomekw/hikari-cp/\n(comment\n (make-datasource\n {", "end": 323, "score": 0.9987152218818665, "start": 317, "tag": "USERNAME", "value": "tomekw" }, { "context": " :adapter \"postgresql\"\n :username \"username\"\n :password \"password\"\n :databa", "end": 583, "score": 0.9978756904602051, "start": 575, "tag": "USERNAME", "value": "username" }, { "context": " :username \"username\"\n :password \"password\"\n :database-name \"database\"\n :s", "end": 614, "score": 0.999323308467865, "start": 606, "tag": "PASSWORD", "value": "password" } ]
src/mlib/psql/conn.clj
maxp/mlib-app
3
(ns mlib.psql.conn (:require [clj-time.coerce :as tc] [jdbc.core :as jdbc] [jdbc.proto :refer [ISQLType ISQLResultSetReadColumn]] [hikari-cp.core :refer [make-datasource]] [mount.core :refer [defstate]] [mlib.log :refer [info warn]] [mlib.conf :refer [conf]])) ; ;; https://github.com/tomekw/hikari-cp/ (comment (make-datasource {:connection-timeout 30000 :idle-timeout 600000 :max-lifetime 1800000 :minimum-idle 10 :maximum-pool-size 10 :adapter "postgresql" :username "username" :password "password" :database-name "database" :server-name "localhost" :port-number 5432}) (with-open [conn (jdbc/connection ds)] (do-stuff conn))) ; (defstate ds :start (if-let [cfg (:psql conf)] (make-datasource cfg) (do (warn "psql ds disabled") false)) :stop (when ds (.close ds))) ; (defn dbc [] (jdbc/connection ds)) ; ;;; ;;; ;;; ;;; (extend-protocol ISQLType ; org.joda.time.DateTime (as-sql-type [this conn] (tc/to-sql-time this)) ; (set-stmt-parameter! [this conn stmt index] (.setTimestamp stmt index (tc/to-sql-time this)))) ; (extend-protocol ISQLResultSetReadColumn ; java.sql.Timestamp (from-sql-type [this conn metadata index] (tc/from-sql-time this)) ; java.sql.Date (from-sql-type [this conn metadata index] (tc/from-sql-date this)) ; java.sql.Time (from-sql-type [this conn metadata index] (org.joda.time.DateTime. this))) ; ; ; http://clojure.github.io/java.jdbc/#clojure.java.jdbc/IResultSetReadColumn ; (extend-protocol jdbc/IResultSetReadColumn ; java.sql.Timestamp ; (result-set-read-column [v _2 _3] ; (tc/from-sql-time v)) ; java.sql.Date ; (result-set-read-column [v _2 _3] ; (tc/from-sql-date v)) ; java.sql.Time ; (result-set-read-column [v _2 _3] ; (org.joda.time.DateTime. v))) ; ; ; http://clojure.github.io/java.jdbc/#clojure.java.jdbc/ISQLValue ; (extend-protocol jdbc/ISQLValue ; org.joda.time.DateTime ; (sql-value [v] ; (tc/to-sql-time v))) ;;.
114430
(ns mlib.psql.conn (:require [clj-time.coerce :as tc] [jdbc.core :as jdbc] [jdbc.proto :refer [ISQLType ISQLResultSetReadColumn]] [hikari-cp.core :refer [make-datasource]] [mount.core :refer [defstate]] [mlib.log :refer [info warn]] [mlib.conf :refer [conf]])) ; ;; https://github.com/tomekw/hikari-cp/ (comment (make-datasource {:connection-timeout 30000 :idle-timeout 600000 :max-lifetime 1800000 :minimum-idle 10 :maximum-pool-size 10 :adapter "postgresql" :username "username" :password "<PASSWORD>" :database-name "database" :server-name "localhost" :port-number 5432}) (with-open [conn (jdbc/connection ds)] (do-stuff conn))) ; (defstate ds :start (if-let [cfg (:psql conf)] (make-datasource cfg) (do (warn "psql ds disabled") false)) :stop (when ds (.close ds))) ; (defn dbc [] (jdbc/connection ds)) ; ;;; ;;; ;;; ;;; (extend-protocol ISQLType ; org.joda.time.DateTime (as-sql-type [this conn] (tc/to-sql-time this)) ; (set-stmt-parameter! [this conn stmt index] (.setTimestamp stmt index (tc/to-sql-time this)))) ; (extend-protocol ISQLResultSetReadColumn ; java.sql.Timestamp (from-sql-type [this conn metadata index] (tc/from-sql-time this)) ; java.sql.Date (from-sql-type [this conn metadata index] (tc/from-sql-date this)) ; java.sql.Time (from-sql-type [this conn metadata index] (org.joda.time.DateTime. this))) ; ; ; http://clojure.github.io/java.jdbc/#clojure.java.jdbc/IResultSetReadColumn ; (extend-protocol jdbc/IResultSetReadColumn ; java.sql.Timestamp ; (result-set-read-column [v _2 _3] ; (tc/from-sql-time v)) ; java.sql.Date ; (result-set-read-column [v _2 _3] ; (tc/from-sql-date v)) ; java.sql.Time ; (result-set-read-column [v _2 _3] ; (org.joda.time.DateTime. v))) ; ; ; http://clojure.github.io/java.jdbc/#clojure.java.jdbc/ISQLValue ; (extend-protocol jdbc/ISQLValue ; org.joda.time.DateTime ; (sql-value [v] ; (tc/to-sql-time v))) ;;.
true
(ns mlib.psql.conn (:require [clj-time.coerce :as tc] [jdbc.core :as jdbc] [jdbc.proto :refer [ISQLType ISQLResultSetReadColumn]] [hikari-cp.core :refer [make-datasource]] [mount.core :refer [defstate]] [mlib.log :refer [info warn]] [mlib.conf :refer [conf]])) ; ;; https://github.com/tomekw/hikari-cp/ (comment (make-datasource {:connection-timeout 30000 :idle-timeout 600000 :max-lifetime 1800000 :minimum-idle 10 :maximum-pool-size 10 :adapter "postgresql" :username "username" :password "PI:PASSWORD:<PASSWORD>END_PI" :database-name "database" :server-name "localhost" :port-number 5432}) (with-open [conn (jdbc/connection ds)] (do-stuff conn))) ; (defstate ds :start (if-let [cfg (:psql conf)] (make-datasource cfg) (do (warn "psql ds disabled") false)) :stop (when ds (.close ds))) ; (defn dbc [] (jdbc/connection ds)) ; ;;; ;;; ;;; ;;; (extend-protocol ISQLType ; org.joda.time.DateTime (as-sql-type [this conn] (tc/to-sql-time this)) ; (set-stmt-parameter! [this conn stmt index] (.setTimestamp stmt index (tc/to-sql-time this)))) ; (extend-protocol ISQLResultSetReadColumn ; java.sql.Timestamp (from-sql-type [this conn metadata index] (tc/from-sql-time this)) ; java.sql.Date (from-sql-type [this conn metadata index] (tc/from-sql-date this)) ; java.sql.Time (from-sql-type [this conn metadata index] (org.joda.time.DateTime. this))) ; ; ; http://clojure.github.io/java.jdbc/#clojure.java.jdbc/IResultSetReadColumn ; (extend-protocol jdbc/IResultSetReadColumn ; java.sql.Timestamp ; (result-set-read-column [v _2 _3] ; (tc/from-sql-time v)) ; java.sql.Date ; (result-set-read-column [v _2 _3] ; (tc/from-sql-date v)) ; java.sql.Time ; (result-set-read-column [v _2 _3] ; (org.joda.time.DateTime. v))) ; ; ; http://clojure.github.io/java.jdbc/#clojure.java.jdbc/ISQLValue ; (extend-protocol jdbc/ISQLValue ; org.joda.time.DateTime ; (sql-value [v] ; (tc/to-sql-time v))) ;;.
[ { "context": "st-check-object-normal\n (is (nil? (check {:data \"testing@test.test\" :function email-address? :dataname \"email\" :requ", "end": 262, "score": 0.9999207258224487, "start": 245, "tag": "EMAIL", "value": "testing@test.test" }, { "context": " test-check-object-nil\n (is (nil? (check {:data \"testing@test.test\" :function email-address?})))\n (is (= \"\\\"email\\\"", "end": 678, "score": 0.9999208450317383, "start": 661, "tag": "EMAIL", "value": "testing@test.test" }, { "context": "bject-multifunc\n ;and\n (is (nil? (check {:data \"testing@test.test\" :function [:and isString? email-address?]})))\n ", "end": 964, "score": 0.9999204874038696, "start": 947, "tag": "EMAIL", "value": "testing@test.test" }, { "context": "between 4 and 32 characters.\" \n (check {:data \"testing@test.test\" :function [:and username? email-address?]})))\n ", "end": 1153, "score": 0.999921977519989, "start": 1136, "tag": "EMAIL", "value": "testing@test.test" }, { "context": "ddress?]})))\n ;or\n (is (nil?\n (check {:data \"testing@test.test\" :function [:or username? email-address?]})))\n (", "end": 1587, "score": 0.9999209642410278, "start": 1570, "tag": "EMAIL", "value": "testing@test.test" }, { "context": "ddress?]})))\n ;nested\n (is (nil? (check {:data \"testing@test.test\" :function [:and [:or isString? username?] email-", "end": 1943, "score": 0.9999176859855652, "start": 1926, "tag": "EMAIL", "value": "testing@test.test" }, { "context": "check-object-multidata\n (is (nil? (check {:data \"testing@test.test\" :function email-address?}\n {:d", "end": 2229, "score": 0.9999175071716309, "start": 2212, "tag": "EMAIL", "value": "testing@test.test" }, { "context": "a nil :function isString?}\n {:data \"testing@test.test\" :function username?}))))\n", "end": 2656, "score": 0.9999209642410278, "start": 2639, "tag": "EMAIL", "value": "testing@test.test" } ]
test/verifications/running_checks.clj
mvrcrypto/customapi
1
(ns verifications.running-checks (:require [clojure.test :refer :all] [verifications.data-verification :refer :all] [verifications.data-utils :refer :all])) (deftest test-check-object-normal (is (nil? (check {:data "testing@test.test" :function email-address? :dataname "email" :required true}))) (is (= "\"email\" is not RFC 2822 compliant." (check {:data "testing" :function email-address? :dataname "email" :required true}))) (is (= "Missing required value : \"email\"." (check {:data nil :function email-address? :dataname "email" :required true})))) (deftest test-check-object-nil (is (nil? (check {:data "testing@test.test" :function email-address?}))) (is (= "\"email\" is not RFC 2822 compliant." (check {:data "testing" :function email-address?}))) (is (nil? (check {:data nil :function email-address?})))) (deftest test-check-object-multifunc ;and (is (nil? (check {:data "testing@test.test" :function [:and isString? email-address?]}))) (is (= "The \"username\" can't contain special characters and has to be between 4 and 32 characters." (check {:data "testing@test.test" :function [:and username? email-address?]}))) (is (= "\"email\" is not RFC 2822 compliant." (check {:data "testing" :function [:and username? email-address?]}))) (is (= "The \"username\" can't contain special characters and has to be between 4 and 32 characters.\n\"email\" is not RFC 2822 compliant." (check {:data 1 :function [:and username? email-address?]}))) ;or (is (nil? (check {:data "testing@test.test" :function [:or username? email-address?]}))) (is (nil? (check {:data "testing" :function [:or username? email-address?]}))) (is (= "The \"username\" can't contain special characters and has to be between 4 and 32 characters." (check {:data 1 :function [:or username? email-address?]}))) ;nested (is (nil? (check {:data "testing@test.test" :function [:and [:or isString? username?] email-address?]}))) (is (= "\"email\" is not RFC 2822 compliant." (check {:data "testing" :function [:and [:or isString? username?] email-address?]})))) (deftest test-check-object-multidata (is (nil? (check {:data "testing@test.test" :function email-address?} {:data nil :function isString?} {:data "testing" :function username?}))) (is (= "\"email\" is not RFC 2822 compliant.\nThe \"username\" can't contain special characters and has to be between 4 and 32 characters." (check {:data "testing" :function email-address?} {:data nil :function isString?} {:data "testing@test.test" :function username?}))))
29633
(ns verifications.running-checks (:require [clojure.test :refer :all] [verifications.data-verification :refer :all] [verifications.data-utils :refer :all])) (deftest test-check-object-normal (is (nil? (check {:data "<EMAIL>" :function email-address? :dataname "email" :required true}))) (is (= "\"email\" is not RFC 2822 compliant." (check {:data "testing" :function email-address? :dataname "email" :required true}))) (is (= "Missing required value : \"email\"." (check {:data nil :function email-address? :dataname "email" :required true})))) (deftest test-check-object-nil (is (nil? (check {:data "<EMAIL>" :function email-address?}))) (is (= "\"email\" is not RFC 2822 compliant." (check {:data "testing" :function email-address?}))) (is (nil? (check {:data nil :function email-address?})))) (deftest test-check-object-multifunc ;and (is (nil? (check {:data "<EMAIL>" :function [:and isString? email-address?]}))) (is (= "The \"username\" can't contain special characters and has to be between 4 and 32 characters." (check {:data "<EMAIL>" :function [:and username? email-address?]}))) (is (= "\"email\" is not RFC 2822 compliant." (check {:data "testing" :function [:and username? email-address?]}))) (is (= "The \"username\" can't contain special characters and has to be between 4 and 32 characters.\n\"email\" is not RFC 2822 compliant." (check {:data 1 :function [:and username? email-address?]}))) ;or (is (nil? (check {:data "<EMAIL>" :function [:or username? email-address?]}))) (is (nil? (check {:data "testing" :function [:or username? email-address?]}))) (is (= "The \"username\" can't contain special characters and has to be between 4 and 32 characters." (check {:data 1 :function [:or username? email-address?]}))) ;nested (is (nil? (check {:data "<EMAIL>" :function [:and [:or isString? username?] email-address?]}))) (is (= "\"email\" is not RFC 2822 compliant." (check {:data "testing" :function [:and [:or isString? username?] email-address?]})))) (deftest test-check-object-multidata (is (nil? (check {:data "<EMAIL>" :function email-address?} {:data nil :function isString?} {:data "testing" :function username?}))) (is (= "\"email\" is not RFC 2822 compliant.\nThe \"username\" can't contain special characters and has to be between 4 and 32 characters." (check {:data "testing" :function email-address?} {:data nil :function isString?} {:data "<EMAIL>" :function username?}))))
true
(ns verifications.running-checks (:require [clojure.test :refer :all] [verifications.data-verification :refer :all] [verifications.data-utils :refer :all])) (deftest test-check-object-normal (is (nil? (check {:data "PI:EMAIL:<EMAIL>END_PI" :function email-address? :dataname "email" :required true}))) (is (= "\"email\" is not RFC 2822 compliant." (check {:data "testing" :function email-address? :dataname "email" :required true}))) (is (= "Missing required value : \"email\"." (check {:data nil :function email-address? :dataname "email" :required true})))) (deftest test-check-object-nil (is (nil? (check {:data "PI:EMAIL:<EMAIL>END_PI" :function email-address?}))) (is (= "\"email\" is not RFC 2822 compliant." (check {:data "testing" :function email-address?}))) (is (nil? (check {:data nil :function email-address?})))) (deftest test-check-object-multifunc ;and (is (nil? (check {:data "PI:EMAIL:<EMAIL>END_PI" :function [:and isString? email-address?]}))) (is (= "The \"username\" can't contain special characters and has to be between 4 and 32 characters." (check {:data "PI:EMAIL:<EMAIL>END_PI" :function [:and username? email-address?]}))) (is (= "\"email\" is not RFC 2822 compliant." (check {:data "testing" :function [:and username? email-address?]}))) (is (= "The \"username\" can't contain special characters and has to be between 4 and 32 characters.\n\"email\" is not RFC 2822 compliant." (check {:data 1 :function [:and username? email-address?]}))) ;or (is (nil? (check {:data "PI:EMAIL:<EMAIL>END_PI" :function [:or username? email-address?]}))) (is (nil? (check {:data "testing" :function [:or username? email-address?]}))) (is (= "The \"username\" can't contain special characters and has to be between 4 and 32 characters." (check {:data 1 :function [:or username? email-address?]}))) ;nested (is (nil? (check {:data "PI:EMAIL:<EMAIL>END_PI" :function [:and [:or isString? username?] email-address?]}))) (is (= "\"email\" is not RFC 2822 compliant." (check {:data "testing" :function [:and [:or isString? username?] email-address?]})))) (deftest test-check-object-multidata (is (nil? (check {:data "PI:EMAIL:<EMAIL>END_PI" :function email-address?} {:data nil :function isString?} {:data "testing" :function username?}))) (is (= "\"email\" is not RFC 2822 compliant.\nThe \"username\" can't contain special characters and has to be between 4 and 32 characters." (check {:data "testing" :function email-address?} {:data nil :function isString?} {:data "PI:EMAIL:<EMAIL>END_PI" :function username?}))))
[ { "context": "; Copyright (c) 2021 Mikołaj Kuranowski\n; SPDX-License-Identifier: WTFPL\n(ns day11a\n (:r", "end": 39, "score": 0.9994767308235168, "start": 21, "tag": "NAME", "value": "Mikołaj Kuranowski" } ]
src/day11a.clj
MKuranowski/AdventOfCode2020
0
; Copyright (c) 2021 Mikołaj Kuranowski ; SPDX-License-Identifier: WTFPL (ns day11a (:require [core] [clojure.math.combinatorics :refer [cartesian-product]] [clojure.string :refer [join]])) (defn adjecent-seats [r c] (->> (cartesian-product [(dec r) r (inc r)] [(dec c) c (inc c)]) (filter #(or (not= (first %) r) (not= (second %) c))))) (defn count-adjecent-occupied [r c table] (->> (adjecent-seats r c) (map #(get (get table (first %)) (second %))) (filter #(= % \#)) (count))) (defn new-value [r c table] (case (get (get table r) c) \L (if (= 0 (count-adjecent-occupied r c table)) \# \L) \# (if (<= 4 (count-adjecent-occupied r c table)) \L \#) \.)) (defn new-row [r table] (->> (range (count (table r))) (map #(new-value r % table)) (apply str))) (defn new-table [table] (->> (range (count table)) (map #(new-row % table)) vec)) (defn new-table-until-stable [table] (loop [t table] (let [nt (new-table t)] (if (= t nt) t (recur nt))))) (defn -main [filename] (->> filename core/lines-from-file (new-table-until-stable) (join "\n") (core/count-if #(= % \#)) (prn)))
56450
; Copyright (c) 2021 <NAME> ; SPDX-License-Identifier: WTFPL (ns day11a (:require [core] [clojure.math.combinatorics :refer [cartesian-product]] [clojure.string :refer [join]])) (defn adjecent-seats [r c] (->> (cartesian-product [(dec r) r (inc r)] [(dec c) c (inc c)]) (filter #(or (not= (first %) r) (not= (second %) c))))) (defn count-adjecent-occupied [r c table] (->> (adjecent-seats r c) (map #(get (get table (first %)) (second %))) (filter #(= % \#)) (count))) (defn new-value [r c table] (case (get (get table r) c) \L (if (= 0 (count-adjecent-occupied r c table)) \# \L) \# (if (<= 4 (count-adjecent-occupied r c table)) \L \#) \.)) (defn new-row [r table] (->> (range (count (table r))) (map #(new-value r % table)) (apply str))) (defn new-table [table] (->> (range (count table)) (map #(new-row % table)) vec)) (defn new-table-until-stable [table] (loop [t table] (let [nt (new-table t)] (if (= t nt) t (recur nt))))) (defn -main [filename] (->> filename core/lines-from-file (new-table-until-stable) (join "\n") (core/count-if #(= % \#)) (prn)))
true
; Copyright (c) 2021 PI:NAME:<NAME>END_PI ; SPDX-License-Identifier: WTFPL (ns day11a (:require [core] [clojure.math.combinatorics :refer [cartesian-product]] [clojure.string :refer [join]])) (defn adjecent-seats [r c] (->> (cartesian-product [(dec r) r (inc r)] [(dec c) c (inc c)]) (filter #(or (not= (first %) r) (not= (second %) c))))) (defn count-adjecent-occupied [r c table] (->> (adjecent-seats r c) (map #(get (get table (first %)) (second %))) (filter #(= % \#)) (count))) (defn new-value [r c table] (case (get (get table r) c) \L (if (= 0 (count-adjecent-occupied r c table)) \# \L) \# (if (<= 4 (count-adjecent-occupied r c table)) \L \#) \.)) (defn new-row [r table] (->> (range (count (table r))) (map #(new-value r % table)) (apply str))) (defn new-table [table] (->> (range (count table)) (map #(new-row % table)) vec)) (defn new-table-until-stable [table] (loop [t table] (let [nt (new-table t)] (if (= t nt) t (recur nt))))) (defn -main [filename] (->> filename core/lines-from-file (new-table-until-stable) (join "\n") (core/count-if #(= % \#)) (prn)))
[ { "context": "dTsp\" 1592794769601,\n;; \"fullName\" \"Ian Sluiter\",\n;; \"statusDesc\" \"Active\",\n;; ", "end": 3362, "score": 0.9998255968093872, "start": 3351, "tag": "NAME", "value": "Ian Sluiter" }, { "context": "\"roleCde\" \"con\",\n;; \"loginNameNme\" \"ISluiter\",\n;; \"surnameNme\" \"Sluiter\",\n;; ", "end": 3523, "score": 0.9813976287841797, "start": 3515, "tag": "NAME", "value": "ISluiter" }, { "context": "meNme\" \"ISluiter\",\n;; \"surnameNme\" \"Sluiter\",\n;; \"givenNme\" \"Ian\",\n;; ", "end": 3564, "score": 0.9998349547386169, "start": 3557, "tag": "NAME", "value": "Sluiter" }, { "context": "rnameNme\" \"Sluiter\",\n;; \"givenNme\" \"Ian\",\n;; \"userUid\" 1},\n ;; ", "end": 3599, "score": 0.999819278717041, "start": 3596, "tag": "NAME", "value": "Ian" } ]
src/glider/event_store/core.clj
JohanCodinha/glider
0
(ns glider.event-store.core (:require [java-time :refer [local-date local-date-time as] :as jt] [clojure.string :as st] [malli.core :as m] [malli.util :as mu] [malli.error :as me] [malli.provider :as mp] [malli.generator :as mg] [malli.transform :as mt] [glider.db :as db] [next.jdbc :as jdbc] [next.jdbc.sql :refer [insert! query delete!]] [cheshire.core :refer [generate-string parse-string]] )) ;add to event ;read event (defn uuid [] (java.util.UUID/randomUUID)) (def event-schema [:map [:type [:or string? keyword?]] [:stream-id uuid?] [:created-at inst?] [:metadata {:optional true} [:or map? nil?]] [:payload map?]]) (defn payload->events "Generate an event" [{:keys [:version :metadata :payload :stream-id :type :stream-id]}] {:post [(m/validate event-schema %)]} (let [id (uuid) created-at (java.time.Instant/now)] {:id id :type type :version 1 :stream-id (or stream-id (uuid)) :created-at created-at :metadata metadata :payload payload})) (comment (def taxon-was-observed-schema (mu/merge event-schema [:map [:payload [:map [:taxon-id int?] [:common-name string?] [:observer string?] [:location [:tuple double? double?]]]]])) (defn generate-event [] (mg/generate taxon-was-observed-schema))) (defn keyword->str [k] (str (.-sym k))) (defn append-to-stream [{:keys [stream-id version events created-at metadata payload]}] (db/insert! :events {:stream_id stream-id :created_at created-at :version version :metadata metadata :payload payload})) (defn dash->underscore [kword] (-> kword str (st/replace "-" "_") rest st/join keyword)) (defn margs [& args] (prn (count args))) (defn append-to-stream-multi! [events] (apply db/insert-multi! :events (update-in (db/events->rows-cols events) [0] #(map dash->underscore %)))) (defn query-event-stream [stream-id path value] (let [json-sql-path (str "'{" (apply str (interpose "," (map name path))) "}'") sql (str "SELECT * FROM events WHERE stream_id = ? AND " "data #> " json-sql-path " = ?")] (println json-sql-path value) (println sql) (db/select! [sql (keyword->str stream-id) value])) ;return list of events ) (defn fetch-event-stream [stream-id] (let [sql "SELECT * FROM events WHERE stream_id = ?"] (db/select! [sql (java.util.UUID/fromString stream-id)]))) (comment (fetch-event-stream "d6382102-9106-4872-a39c-f747d8b76225") ;; => [#:events{:id #uuid "448846bd-7a07-42cf-9ab3-c3130ce8af4f", ;; :stream_id #uuid "d6382102-9106-4872-a39c-f747d8b76225", ;; :type ":glider.domains.legacy/retrieved-user", ;; :version 1, ;; :created_at #inst "2020-09-10T05:29:49.909000000-00:00", ;; :payload ;; {"statusCde" "active", ;; "organisationNmes" "Ogyris Pty Ltd", ;; "modifiedTsp" 1592794769601, ;; "fullName" "Ian Sluiter", ;; "statusDesc" "Active", ;; "roleDesc" "Contributor", ;; "roleCde" "con", ;; "loginNameNme" "ISluiter", ;; "surnameNme" "Sluiter", ;; "givenNme" "Ian", ;; "userUid" 1}, ;; :metadata nil}] ) (comment (append-to-stream ::test 1 {:nope 1 :nes {:ted :ok}}) (query-event-stream "d6382102-9106-4872-a39c-f747d8b76225" #_#_["nope"] "ok") (query-event-stream )) ; http request | cli request ; |-> request handler (check auth - parse params ...) ; reitit - malli ; |-> command handler (read events to build state - return events) ; multi-method - malli ; |-> hapend event (return nil) ; |-> (react to event) (comment (mp/provide [{"test" true "stpo" 123}]))
81661
(ns glider.event-store.core (:require [java-time :refer [local-date local-date-time as] :as jt] [clojure.string :as st] [malli.core :as m] [malli.util :as mu] [malli.error :as me] [malli.provider :as mp] [malli.generator :as mg] [malli.transform :as mt] [glider.db :as db] [next.jdbc :as jdbc] [next.jdbc.sql :refer [insert! query delete!]] [cheshire.core :refer [generate-string parse-string]] )) ;add to event ;read event (defn uuid [] (java.util.UUID/randomUUID)) (def event-schema [:map [:type [:or string? keyword?]] [:stream-id uuid?] [:created-at inst?] [:metadata {:optional true} [:or map? nil?]] [:payload map?]]) (defn payload->events "Generate an event" [{:keys [:version :metadata :payload :stream-id :type :stream-id]}] {:post [(m/validate event-schema %)]} (let [id (uuid) created-at (java.time.Instant/now)] {:id id :type type :version 1 :stream-id (or stream-id (uuid)) :created-at created-at :metadata metadata :payload payload})) (comment (def taxon-was-observed-schema (mu/merge event-schema [:map [:payload [:map [:taxon-id int?] [:common-name string?] [:observer string?] [:location [:tuple double? double?]]]]])) (defn generate-event [] (mg/generate taxon-was-observed-schema))) (defn keyword->str [k] (str (.-sym k))) (defn append-to-stream [{:keys [stream-id version events created-at metadata payload]}] (db/insert! :events {:stream_id stream-id :created_at created-at :version version :metadata metadata :payload payload})) (defn dash->underscore [kword] (-> kword str (st/replace "-" "_") rest st/join keyword)) (defn margs [& args] (prn (count args))) (defn append-to-stream-multi! [events] (apply db/insert-multi! :events (update-in (db/events->rows-cols events) [0] #(map dash->underscore %)))) (defn query-event-stream [stream-id path value] (let [json-sql-path (str "'{" (apply str (interpose "," (map name path))) "}'") sql (str "SELECT * FROM events WHERE stream_id = ? AND " "data #> " json-sql-path " = ?")] (println json-sql-path value) (println sql) (db/select! [sql (keyword->str stream-id) value])) ;return list of events ) (defn fetch-event-stream [stream-id] (let [sql "SELECT * FROM events WHERE stream_id = ?"] (db/select! [sql (java.util.UUID/fromString stream-id)]))) (comment (fetch-event-stream "d6382102-9106-4872-a39c-f747d8b76225") ;; => [#:events{:id #uuid "448846bd-7a07-42cf-9ab3-c3130ce8af4f", ;; :stream_id #uuid "d6382102-9106-4872-a39c-f747d8b76225", ;; :type ":glider.domains.legacy/retrieved-user", ;; :version 1, ;; :created_at #inst "2020-09-10T05:29:49.909000000-00:00", ;; :payload ;; {"statusCde" "active", ;; "organisationNmes" "Ogyris Pty Ltd", ;; "modifiedTsp" 1592794769601, ;; "fullName" "<NAME>", ;; "statusDesc" "Active", ;; "roleDesc" "Contributor", ;; "roleCde" "con", ;; "loginNameNme" "<NAME>", ;; "surnameNme" "<NAME>", ;; "givenNme" "<NAME>", ;; "userUid" 1}, ;; :metadata nil}] ) (comment (append-to-stream ::test 1 {:nope 1 :nes {:ted :ok}}) (query-event-stream "d6382102-9106-4872-a39c-f747d8b76225" #_#_["nope"] "ok") (query-event-stream )) ; http request | cli request ; |-> request handler (check auth - parse params ...) ; reitit - malli ; |-> command handler (read events to build state - return events) ; multi-method - malli ; |-> hapend event (return nil) ; |-> (react to event) (comment (mp/provide [{"test" true "stpo" 123}]))
true
(ns glider.event-store.core (:require [java-time :refer [local-date local-date-time as] :as jt] [clojure.string :as st] [malli.core :as m] [malli.util :as mu] [malli.error :as me] [malli.provider :as mp] [malli.generator :as mg] [malli.transform :as mt] [glider.db :as db] [next.jdbc :as jdbc] [next.jdbc.sql :refer [insert! query delete!]] [cheshire.core :refer [generate-string parse-string]] )) ;add to event ;read event (defn uuid [] (java.util.UUID/randomUUID)) (def event-schema [:map [:type [:or string? keyword?]] [:stream-id uuid?] [:created-at inst?] [:metadata {:optional true} [:or map? nil?]] [:payload map?]]) (defn payload->events "Generate an event" [{:keys [:version :metadata :payload :stream-id :type :stream-id]}] {:post [(m/validate event-schema %)]} (let [id (uuid) created-at (java.time.Instant/now)] {:id id :type type :version 1 :stream-id (or stream-id (uuid)) :created-at created-at :metadata metadata :payload payload})) (comment (def taxon-was-observed-schema (mu/merge event-schema [:map [:payload [:map [:taxon-id int?] [:common-name string?] [:observer string?] [:location [:tuple double? double?]]]]])) (defn generate-event [] (mg/generate taxon-was-observed-schema))) (defn keyword->str [k] (str (.-sym k))) (defn append-to-stream [{:keys [stream-id version events created-at metadata payload]}] (db/insert! :events {:stream_id stream-id :created_at created-at :version version :metadata metadata :payload payload})) (defn dash->underscore [kword] (-> kword str (st/replace "-" "_") rest st/join keyword)) (defn margs [& args] (prn (count args))) (defn append-to-stream-multi! [events] (apply db/insert-multi! :events (update-in (db/events->rows-cols events) [0] #(map dash->underscore %)))) (defn query-event-stream [stream-id path value] (let [json-sql-path (str "'{" (apply str (interpose "," (map name path))) "}'") sql (str "SELECT * FROM events WHERE stream_id = ? AND " "data #> " json-sql-path " = ?")] (println json-sql-path value) (println sql) (db/select! [sql (keyword->str stream-id) value])) ;return list of events ) (defn fetch-event-stream [stream-id] (let [sql "SELECT * FROM events WHERE stream_id = ?"] (db/select! [sql (java.util.UUID/fromString stream-id)]))) (comment (fetch-event-stream "d6382102-9106-4872-a39c-f747d8b76225") ;; => [#:events{:id #uuid "448846bd-7a07-42cf-9ab3-c3130ce8af4f", ;; :stream_id #uuid "d6382102-9106-4872-a39c-f747d8b76225", ;; :type ":glider.domains.legacy/retrieved-user", ;; :version 1, ;; :created_at #inst "2020-09-10T05:29:49.909000000-00:00", ;; :payload ;; {"statusCde" "active", ;; "organisationNmes" "Ogyris Pty Ltd", ;; "modifiedTsp" 1592794769601, ;; "fullName" "PI:NAME:<NAME>END_PI", ;; "statusDesc" "Active", ;; "roleDesc" "Contributor", ;; "roleCde" "con", ;; "loginNameNme" "PI:NAME:<NAME>END_PI", ;; "surnameNme" "PI:NAME:<NAME>END_PI", ;; "givenNme" "PI:NAME:<NAME>END_PI", ;; "userUid" 1}, ;; :metadata nil}] ) (comment (append-to-stream ::test 1 {:nope 1 :nes {:ted :ok}}) (query-event-stream "d6382102-9106-4872-a39c-f747d8b76225" #_#_["nope"] "ok") (query-event-stream )) ; http request | cli request ; |-> request handler (check auth - parse params ...) ; reitit - malli ; |-> command handler (read events to build state - return events) ; multi-method - malli ; |-> hapend event (return nil) ; |-> (react to event) (comment (mp/provide [{"test" true "stpo" 123}]))
[ { "context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li", "end": 111, "score": 0.9998117089271545, "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.999819278717041, "start": 113, "tag": "NAME", "value": "Christian Murray" } ]
editor/test/internal/connection_rules.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 internal.connection-rules (:require [clojure.test :refer :all] [dynamo.graph :as g] [support.test-support :refer :all])) (g/defnode InputNode (input string-scalar g/Str)) (g/defnode OutputNode (property string-scalar g/Str) (property int-scalar g/Int)) (deftest connection-rules (testing "compatible single value connections" (with-clean-system (let [[output input] (tx-nodes (g/make-node world OutputNode) (g/make-node world InputNode))] (g/connect! output :string-scalar input :string-scalar) (is (g/connected? (g/now) output :string-scalar input :string-scalar))))) (testing "incompatible single value connections" (with-clean-system (let [[output input] (tx-nodes (g/make-node world OutputNode) (g/make-node world InputNode))] (is (thrown? AssertionError (g/connect! output :int-scalar input :string-scalar))) (is (not (g/connected? (g/now) output :string-scalar input :string-scalar))))))) (deftest uni-connection-replaced (testing "single transaction" (with-clean-system (let [[out in next-out] (tx-nodes (g/make-nodes world [out [OutputNode :string-scalar "first-val"] in InputNode next-out [OutputNode :string-scalar "second-val"]] (g/connect out :string-scalar in :string-scalar) (g/connect next-out :string-scalar in :string-scalar)))] (is (= "second-val" (g/node-value in :string-scalar)))))) (testing "separate transactions" (with-clean-system (let [[out in next-out] (tx-nodes (g/make-nodes world [out [OutputNode :string-scalar "first-val"] in InputNode next-out [OutputNode :string-scalar "second-val"]] (g/connect out :string-scalar in :string-scalar)))] (g/connect! next-out :string-scalar in :string-scalar) (is (= "second-val" (g/node-value in :string-scalar)))))))
55512
;; 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 internal.connection-rules (:require [clojure.test :refer :all] [dynamo.graph :as g] [support.test-support :refer :all])) (g/defnode InputNode (input string-scalar g/Str)) (g/defnode OutputNode (property string-scalar g/Str) (property int-scalar g/Int)) (deftest connection-rules (testing "compatible single value connections" (with-clean-system (let [[output input] (tx-nodes (g/make-node world OutputNode) (g/make-node world InputNode))] (g/connect! output :string-scalar input :string-scalar) (is (g/connected? (g/now) output :string-scalar input :string-scalar))))) (testing "incompatible single value connections" (with-clean-system (let [[output input] (tx-nodes (g/make-node world OutputNode) (g/make-node world InputNode))] (is (thrown? AssertionError (g/connect! output :int-scalar input :string-scalar))) (is (not (g/connected? (g/now) output :string-scalar input :string-scalar))))))) (deftest uni-connection-replaced (testing "single transaction" (with-clean-system (let [[out in next-out] (tx-nodes (g/make-nodes world [out [OutputNode :string-scalar "first-val"] in InputNode next-out [OutputNode :string-scalar "second-val"]] (g/connect out :string-scalar in :string-scalar) (g/connect next-out :string-scalar in :string-scalar)))] (is (= "second-val" (g/node-value in :string-scalar)))))) (testing "separate transactions" (with-clean-system (let [[out in next-out] (tx-nodes (g/make-nodes world [out [OutputNode :string-scalar "first-val"] in InputNode next-out [OutputNode :string-scalar "second-val"]] (g/connect out :string-scalar in :string-scalar)))] (g/connect! next-out :string-scalar in :string-scalar) (is (= "second-val" (g/node-value in :string-scalar)))))))
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 internal.connection-rules (:require [clojure.test :refer :all] [dynamo.graph :as g] [support.test-support :refer :all])) (g/defnode InputNode (input string-scalar g/Str)) (g/defnode OutputNode (property string-scalar g/Str) (property int-scalar g/Int)) (deftest connection-rules (testing "compatible single value connections" (with-clean-system (let [[output input] (tx-nodes (g/make-node world OutputNode) (g/make-node world InputNode))] (g/connect! output :string-scalar input :string-scalar) (is (g/connected? (g/now) output :string-scalar input :string-scalar))))) (testing "incompatible single value connections" (with-clean-system (let [[output input] (tx-nodes (g/make-node world OutputNode) (g/make-node world InputNode))] (is (thrown? AssertionError (g/connect! output :int-scalar input :string-scalar))) (is (not (g/connected? (g/now) output :string-scalar input :string-scalar))))))) (deftest uni-connection-replaced (testing "single transaction" (with-clean-system (let [[out in next-out] (tx-nodes (g/make-nodes world [out [OutputNode :string-scalar "first-val"] in InputNode next-out [OutputNode :string-scalar "second-val"]] (g/connect out :string-scalar in :string-scalar) (g/connect next-out :string-scalar in :string-scalar)))] (is (= "second-val" (g/node-value in :string-scalar)))))) (testing "separate transactions" (with-clean-system (let [[out in next-out] (tx-nodes (g/make-nodes world [out [OutputNode :string-scalar "first-val"] in InputNode next-out [OutputNode :string-scalar "second-val"]] (g/connect out :string-scalar in :string-scalar)))] (g/connect! next-out :string-scalar in :string-scalar) (is (= "second-val" (g/node-value in :string-scalar)))))))
[ { "context": " :mentortype \"1\",\n :name \"Åk 9\",\n :resourcetype \"0\",\n :review", "end": 283, "score": 0.89128577709198, "start": 279, "tag": "NAME", "value": "Åk 9" }, { "context": " :mentortype \"0\",\n :name \"Åk 9:a\",\n :resourcetype \"0\",\n :rev", "end": 688, "score": 0.6137439012527466, "start": 686, "tag": "NAME", "value": "Åk" }, { "context": " \"64731\",\n :email \"emilia@live.se\",\n :logincount \"5124\",\n ", "end": 1070, "score": 0.9999253153800964, "start": 1056, "tag": "EMAIL", "value": "emilia@live.se" }, { "context": "nt \"5124\",\n :fname \"Emilia\",\n :sex \"f\",\n :s", "end": 1148, "score": 0.9987503290176392, "start": 1142, "tag": "NAME", "value": "Emilia" }, { "context": " \"Mariefred\",\n :username \"emilia.arman\",\n :contactinfo \"\",\n :ab", "end": 1317, "score": 0.9996758699417114, "start": 1305, "tag": "USERNAME", "value": "emilia.arman" }, { "context": " :pocode \"\",\n :email \"fanny.orsa@gripsholmsskolan.se\",\n :logincount \"259\",\n :fname", "end": 1998, "score": 0.9999257922172546, "start": 1968, "tag": "EMAIL", "value": "fanny.orsa@gripsholmsskolan.se" }, { "context": " :logincount \"259\",\n :fname \"Fanny\",\n :socialnumber \"870506-0000\",\n ", "end": 2062, "score": 0.9998378753662109, "start": 2057, "tag": "NAME", "value": "Fanny" }, { "context": " :city \"\",\n :username \"fanny.orsa\",\n :type \"0\",\n :contact", "end": 2167, "score": 0.9989598393440247, "start": 2157, "tag": "USERNAME", "value": "fanny.orsa" }, { "context": " :contactinfo \"\",\n :lname \"Örså\",\n :address1 \"\",\n :homephon", "end": 2256, "score": 0.9998140335083008, "start": 2252, "tag": "NAME", "value": "Örså" } ]
src/inventist/schoolsoft/client/examples.clj
solidfox/inventist-backend
0
(ns inventist.schoolsoft.client.examples) (comment "Groups look like this comming from schoolsoft" {:maxstudent "0", :description "Åk 9", :classtype "1", :leavepickup "0", :mentortype "1", :name "Åk 9", :resourcetype "0", :reviewtype "1", :active "1", :id "271", :classplanning "1", :externalid "{F95BADFC-E432-4268-8264-49BF02965DE2}"} {:maxstudent "0", :description "Åk 9:a", :classtype "0", :leavepickup "0", :mentortype "0", :name "Åk 9:a", :resourcetype "0", :reviewtype "1", :active "1", :id "176", :classplanning "0", :externalid "{5F3E0A72-CF01-4777-9576-EA690B41B6E5}"}) (comment "Students" {:lastlogin "2018-03-29 15:30", :pocode "64731", :email "emilia@live.se", :logincount "5124", :fname "Emilia", :sex "f", :socialnumber "020909-0000", :city "Mariefred", :username "emilia.arman", :contactinfo "", :absencemessagetype "-1", :notpublish "0", :lname "Example", :address1 "Redacted 9", :homephone "", :workphone "", :address2 "", :active "1", :id "243", :picture "student243.jpg", :swimmingability "0", :mobile "0708283947", :classid "271"}) (comment "Teachers" {:lastlogin "2018-03-25 15:12", :pocode "", :email "fanny.orsa@gripsholmsskolan.se", :logincount "259", :fname "Fanny", :socialnumber "870506-0000", :city "", :username "fanny.orsa", :type "0", :contactinfo "", :lname "Örså", :address1 "", :homephone "", :workphone "", :address2 "", :active "1", :id "38", :initial "FÖ", :mobile ""})
110098
(ns inventist.schoolsoft.client.examples) (comment "Groups look like this comming from schoolsoft" {:maxstudent "0", :description "Åk 9", :classtype "1", :leavepickup "0", :mentortype "1", :name "<NAME>", :resourcetype "0", :reviewtype "1", :active "1", :id "271", :classplanning "1", :externalid "{F95BADFC-E432-4268-8264-49BF02965DE2}"} {:maxstudent "0", :description "Åk 9:a", :classtype "0", :leavepickup "0", :mentortype "0", :name "<NAME> 9:a", :resourcetype "0", :reviewtype "1", :active "1", :id "176", :classplanning "0", :externalid "{5F3E0A72-CF01-4777-9576-EA690B41B6E5}"}) (comment "Students" {:lastlogin "2018-03-29 15:30", :pocode "64731", :email "<EMAIL>", :logincount "5124", :fname "<NAME>", :sex "f", :socialnumber "020909-0000", :city "Mariefred", :username "emilia.arman", :contactinfo "", :absencemessagetype "-1", :notpublish "0", :lname "Example", :address1 "Redacted 9", :homephone "", :workphone "", :address2 "", :active "1", :id "243", :picture "student243.jpg", :swimmingability "0", :mobile "0708283947", :classid "271"}) (comment "Teachers" {:lastlogin "2018-03-25 15:12", :pocode "", :email "<EMAIL>", :logincount "259", :fname "<NAME>", :socialnumber "870506-0000", :city "", :username "fanny.orsa", :type "0", :contactinfo "", :lname "<NAME>", :address1 "", :homephone "", :workphone "", :address2 "", :active "1", :id "38", :initial "FÖ", :mobile ""})
true
(ns inventist.schoolsoft.client.examples) (comment "Groups look like this comming from schoolsoft" {:maxstudent "0", :description "Åk 9", :classtype "1", :leavepickup "0", :mentortype "1", :name "PI:NAME:<NAME>END_PI", :resourcetype "0", :reviewtype "1", :active "1", :id "271", :classplanning "1", :externalid "{F95BADFC-E432-4268-8264-49BF02965DE2}"} {:maxstudent "0", :description "Åk 9:a", :classtype "0", :leavepickup "0", :mentortype "0", :name "PI:NAME:<NAME>END_PI 9:a", :resourcetype "0", :reviewtype "1", :active "1", :id "176", :classplanning "0", :externalid "{5F3E0A72-CF01-4777-9576-EA690B41B6E5}"}) (comment "Students" {:lastlogin "2018-03-29 15:30", :pocode "64731", :email "PI:EMAIL:<EMAIL>END_PI", :logincount "5124", :fname "PI:NAME:<NAME>END_PI", :sex "f", :socialnumber "020909-0000", :city "Mariefred", :username "emilia.arman", :contactinfo "", :absencemessagetype "-1", :notpublish "0", :lname "Example", :address1 "Redacted 9", :homephone "", :workphone "", :address2 "", :active "1", :id "243", :picture "student243.jpg", :swimmingability "0", :mobile "0708283947", :classid "271"}) (comment "Teachers" {:lastlogin "2018-03-25 15:12", :pocode "", :email "PI:EMAIL:<EMAIL>END_PI", :logincount "259", :fname "PI:NAME:<NAME>END_PI", :socialnumber "870506-0000", :city "", :username "fanny.orsa", :type "0", :contactinfo "", :lname "PI:NAME:<NAME>END_PI", :address1 "", :homephone "", :workphone "", :address2 "", :active "1", :id "38", :initial "FÖ", :mobile ""})
[ { "context": ";;\n;; Author:: Adam Jacob (<adam@opscode.com>)\n;; Author:: Christopher Brow", "end": 25, "score": 0.9998428225517273, "start": 15, "tag": "NAME", "value": "Adam Jacob" }, { "context": ";;\n;; Author:: Adam Jacob (<adam@opscode.com>)\n;; Author:: Christopher Brown (<cb@opscode.com>", "end": 44, "score": 0.9999341368675232, "start": 28, "tag": "EMAIL", "value": "adam@opscode.com" }, { "context": "thor:: Adam Jacob (<adam@opscode.com>)\n;; Author:: Christopher Brown (<cb@opscode.com>)\n;; Copyright:: Copyright (c) 2", "end": 76, "score": 0.9996588826179504, "start": 59, "tag": "NAME", "value": "Christopher Brown" }, { "context": "dam@opscode.com>)\n;; Author:: Christopher Brown (<cb@opscode.com>)\n;; Copyright:: Copyright (c) 2010 Opscode, Inc.", "end": 93, "score": 0.9999333024024963, "start": 79, "tag": "EMAIL", "value": "cb@opscode.com" } ]
src/omnibus/ohai.clj
racker/omnibus
2
;; ;; Author:: Adam Jacob (<adam@opscode.com>) ;; Author:: Christopher Brown (<cb@opscode.com>) ;; Copyright:: Copyright (c) 2010 Opscode, Inc. ;; License:: Apache License, Version 2.0 ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; (ns omnibus.ohai (:use [omnibus.log] [clojure.contrib.json] [clojure.contrib.logging :only [log]] [clojure.contrib.io :only [make-parents file-str]] [clojure.java.shell :only [sh]]) (:require [clojure.contrib.string :as str]) (:gen-class)) (defn ohai "Use Ohai to get our Operating System and Machine Architecture" [] (let [ohai-data (read-json ((sh "ohai") :out))] {:os (get ohai-data :os), :machine (get-in ohai-data [:kernel :machine]), :platform (let [ohai-platform (get ohai-data :platform)] (if (or (= ohai-platform "scientific") (= ohai-platform "redhat") (= ohai-platform "centos")) "el" ohai-platform)), :platform_version (get ohai-data :platform_version)})) (def ohai (memoize ohai)) (defn os-and-machine [& ohai-keys] (get-in (ohai) ohai-keys)) (defn is-platform? "Returns true if the current platform matches the argument" [to-check] (= (os-and-machine :platform) to-check)) (defn is-os? "Returns true if the current OS matches the argument" [to-check] (= (os-and-machine :os) to-check)) (defn is-machine? "Returns true if the current machine matches the argument" [to-check] (= (os-and-machine :machine) to-check))
10186
;; ;; Author:: <NAME> (<<EMAIL>>) ;; Author:: <NAME> (<<EMAIL>>) ;; Copyright:: Copyright (c) 2010 Opscode, Inc. ;; License:: Apache License, Version 2.0 ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; (ns omnibus.ohai (:use [omnibus.log] [clojure.contrib.json] [clojure.contrib.logging :only [log]] [clojure.contrib.io :only [make-parents file-str]] [clojure.java.shell :only [sh]]) (:require [clojure.contrib.string :as str]) (:gen-class)) (defn ohai "Use Ohai to get our Operating System and Machine Architecture" [] (let [ohai-data (read-json ((sh "ohai") :out))] {:os (get ohai-data :os), :machine (get-in ohai-data [:kernel :machine]), :platform (let [ohai-platform (get ohai-data :platform)] (if (or (= ohai-platform "scientific") (= ohai-platform "redhat") (= ohai-platform "centos")) "el" ohai-platform)), :platform_version (get ohai-data :platform_version)})) (def ohai (memoize ohai)) (defn os-and-machine [& ohai-keys] (get-in (ohai) ohai-keys)) (defn is-platform? "Returns true if the current platform matches the argument" [to-check] (= (os-and-machine :platform) to-check)) (defn is-os? "Returns true if the current OS matches the argument" [to-check] (= (os-and-machine :os) to-check)) (defn is-machine? "Returns true if the current machine matches the argument" [to-check] (= (os-and-machine :machine) to-check))
true
;; ;; Author:: PI:NAME:<NAME>END_PI (<PI:EMAIL:<EMAIL>END_PI>) ;; Author:: PI:NAME:<NAME>END_PI (<PI:EMAIL:<EMAIL>END_PI>) ;; Copyright:: Copyright (c) 2010 Opscode, Inc. ;; License:: Apache License, Version 2.0 ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; (ns omnibus.ohai (:use [omnibus.log] [clojure.contrib.json] [clojure.contrib.logging :only [log]] [clojure.contrib.io :only [make-parents file-str]] [clojure.java.shell :only [sh]]) (:require [clojure.contrib.string :as str]) (:gen-class)) (defn ohai "Use Ohai to get our Operating System and Machine Architecture" [] (let [ohai-data (read-json ((sh "ohai") :out))] {:os (get ohai-data :os), :machine (get-in ohai-data [:kernel :machine]), :platform (let [ohai-platform (get ohai-data :platform)] (if (or (= ohai-platform "scientific") (= ohai-platform "redhat") (= ohai-platform "centos")) "el" ohai-platform)), :platform_version (get ohai-data :platform_version)})) (def ohai (memoize ohai)) (defn os-and-machine [& ohai-keys] (get-in (ohai) ohai-keys)) (defn is-platform? "Returns true if the current platform matches the argument" [to-check] (= (os-and-machine :platform) to-check)) (defn is-os? "Returns true if the current OS matches the argument" [to-check] (= (os-and-machine :os) to-check)) (defn is-machine? "Returns true if the current machine matches the argument" [to-check] (= (os-and-machine :machine) to-check))
[ { "context": " by the SC synth\n engine.\"\n :author \"Jeff Rose, Sam Aaron\"}\n overtone.sc.envelope\n (:use [over", "end": 658, "score": 0.9998887777328491, "start": 649, "tag": "NAME", "value": "Jeff Rose" }, { "context": " synth\n engine.\"\n :author \"Jeff Rose, Sam Aaron\"}\n overtone.sc.envelope\n (:use [overtone.util l", "end": 669, "score": 0.9998852610588074, "start": 660, "tag": "NAME", "value": "Sam Aaron" }, { "context": ";;;;;;;;;;;;\n;; Envelope Curve Shapes\n;; Thanks to ScalaCollider for these shape formulas!\n;;;;;;;;;;;;;;;;;;;;;;;", "end": 6473, "score": 0.9671391844749451, "start": 6460, "tag": "USERNAME", "value": "ScalaCollider" } ]
src/overtone/sc/envelope.clj
rosejn/overtone
4
(ns ^{:doc "An envelope defines a waveform that will be used to control another component of a synthesizer over time. It is typical to use envelopes to control the amplitude of a source waveform. For example, an envelope will dictate that a sound should start quick and loud, but then drop shortly and tail off gently. Another common usage is to see envelopes controlling filter cutoff values over time. These are the typical envelope functions found in SuperCollider, and they output a series of numbers that is understood by the SC synth engine." :author "Jeff Rose, Sam Aaron"} overtone.sc.envelope (:use [overtone.util lib] [overtone.sc ugens])) (def ENV-SHAPES {:step 0 :lin 1 :linear 1 :exp 2 :exponential 2 :sin 3 :sine 3 :wel 4 :welch 4 :sqr 6 :squared 6 :cub 7 :cubed 7 }) (defn- shape->id "Create a repeating shapes list corresponding to a specific shape type. Looks shape s up in ENV-SHAPES if it's a keyword. If not, it assumes the val represents the bespoke curve vals for a generic curve shape (shape type 5). the bespoke curve vals aren't used here, but are picked up in curve-value. Mirrors *shapeNumber in supercollider/SCClassLibrary/Common/Audio/Env.sc" [s] (if (keyword? s) (repeat (s ENV-SHAPES)) (repeat 5))) (defn- curve-value "Create the curves list for this curve type. For all standard shapes this list of vals isn't used. It's only required when the shape is a generic 'curve' shape when the curve vals represent the curvature value for each segment. A single float is repeated for all segments whilst a list of floats can be used to represent the curvature value for each segment individually. Mirrors curveValue in supercollider/SCClassLibrary/Common/Audio/Env.sc" ;; [c] (cond (sequential? c) c (number? c) (repeat c) :else (repeat 0))) ;; Envelope specs describe a series of segments of a line, which can be used to automate ;; control values in synths. ;; ;; [ <initialLevel>, ;; <numberOfSegments>, ;; <releaseNode>, ;; <loopNode>, ;; <segment1TargetLevel>, <segment1Duration>, <segment1Shape>, <segment1Curve>, ;; ... ;; <segment-N...> ] (defn envelope "Create an envelope curve description array suitable for the env-gen ugen. Requires a list of levels (the points that the envelope will pass through and a list of durations (the duration in time of the lines between each point). Optionally a curve may be specified. This may be one of: * :step - flat segments * :linear - linear segments, the default * :exponential - natural exponential growth and decay. In this case, the levels must all be nonzero and the have the same sign. * :sine - sinusoidal S shaped segments. * :welch - sinusoidal segments shaped like the sides of a Welch window. * a Float - a curvature value to be repeated for all segments. * an Array of Floats - individual curvature values for each segment. If a release-node is specified (an integer index) the envelope will sustain at the release node until released which occurs when the gate input of the env-gen is set to zero. If a loop-node is specified (an integer index) the output will loop through those nodes starting at the loop node to the node immediately preceeding the release node, before back to the loop node, and so on. Note that the envelope only transitions to the release node when released. The loop is escaped when a gate signal is sent, which results with the the output transitioning to the release node." ;;See prAsArray in supercollider/SCClassLibrary/Common/Audio/Env.sc [levels durations & [curve release-node loop-node]] (let [curve (or curve :linear) reln (or release-node -99) loopn (or loop-node -99) shapes (shape->id curve) curves (curve-value curve)] (apply vector (concat [(first levels) (count durations) reln loopn] (interleave (rest levels) durations shapes curves))))) (defunk triangle "Create a triangle envelope description array suitable for use with the env-gen ugen" [dur 1 level 1] (with-overloaded-ugens (let [dur (* dur 0.5)] (envelope [0 level 0] [dur dur])))) (defunk sine "Create a sine envelope description suitable for use with the env-gen ugen" [dur 1 level 1] (with-overloaded-ugens (let [dur (* dur 0.5)] (envelope [0 level 0] [dur dur] :sine)))) (defunk perc "Create a percussive envelope description suitable for use with the env-gen ugen" [attack 0.01 release 1 level 1 curve -4] (with-overloaded-ugens (envelope [0 level 0] [attack release] curve))) (defunk lin-env "Create a trapezoidal envelope description suitable for use with the env-gen ugen" [attack 0.01 sustain 1 release 1 level 1 curve :linear] (with-overloaded-ugens (envelope [0 level level 0] [attack sustain release] curve))) (defunk cutoff "Create a cutoff envelope description suitable for use with the env-gen ugen" [release 0.1 level 1 curve :linear] (with-overloaded-ugens (envelope [level 0] [release] curve 0))) (defunk dadsr "Create a delayed attack decay sustain release envelope suitable for use with the env-gen ugen" [delay-t 0.1 attack 0.01 decay 0.3 sustain 0.5 release 1 level 1 curve -4 bias 0] (with-overloaded-ugens (envelope (map #(+ %1 bias) [0 0 level (* level sustain) 0]) [delay-t attack decay release] curve))) (defunk adsr "Create an attack decay sustain release envelope suitable for use with the env-gen ugen" [attack 0.01 decay 0.3 sustain 1 release 1 level 1 curve -4 bias 0] (with-overloaded-ugens (envelope (map #(+ %1 bias) [0 level (* level sustain) 0]) [attack decay release] curve 2))) (defunk asr "Create an attack sustain release envelope sutable for use with the env-gen ugen" [attack 0.01 sustain 1 release 1 curve -4] (with-overloaded-ugens (envelope [0 sustain 0] [attack release] curve 1))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Envelope Curve Shapes ;; Thanks to ScalaCollider for these shape formulas! ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn step-shape [pos y1 y2] (if (< pos 1) y1 y2)) (defn linear-shape [pos y1 y2] (+ y1 (* pos (- y2 y1)))) (defn exponential-shape [pos y1 y2] (let [limit (max 0.0001 y1)] (* limit (Math/pow (/ y2 limit) pos)))) (defn sine-shape [pos y1 y2] (+ y1 (* (- y2 y1) (+ (* -1 (Math/cos (* Math/PI pos)) 0.5) 0.5)))) (defn welch-shape [pos y1 y2] (let [pos (if (< y1 y2) pos (- 1.0 pos))] (+ y1 (* (- y2 y1) (Math/sin (* Math/PI 0.5 pos)))))) (defn curve-shape [pos y1 y2 curvature] (if (< (Math/abs curvature) 0.0001) (+ (* pos (- y2 y1)) y1) (let [denominator (- 1.0 (Math/exp curvature)) numerator (- 1.0 (Math/exp (* pos curvature)))] (+ y1 (* (- y2 y1) (/ numerator denominator)))))) (defn squared-shape [pos y1 y2] (let [y1-s (Math/sqrt y1) y2-s (Math/sqrt y2) yp (+ y1-s (* pos (- y2-s y1-s)))] (* yp yp))) (defn cubed-shape [pos y1 y2] (let [y1-c (Math/pow y1 0.3333333) y2-c (Math/pow y2 0.3333333) yp (+ y1-c (* pos (- y2-c y1-c)))] (* yp yp yp)))
102189
(ns ^{:doc "An envelope defines a waveform that will be used to control another component of a synthesizer over time. It is typical to use envelopes to control the amplitude of a source waveform. For example, an envelope will dictate that a sound should start quick and loud, but then drop shortly and tail off gently. Another common usage is to see envelopes controlling filter cutoff values over time. These are the typical envelope functions found in SuperCollider, and they output a series of numbers that is understood by the SC synth engine." :author "<NAME>, <NAME>"} overtone.sc.envelope (:use [overtone.util lib] [overtone.sc ugens])) (def ENV-SHAPES {:step 0 :lin 1 :linear 1 :exp 2 :exponential 2 :sin 3 :sine 3 :wel 4 :welch 4 :sqr 6 :squared 6 :cub 7 :cubed 7 }) (defn- shape->id "Create a repeating shapes list corresponding to a specific shape type. Looks shape s up in ENV-SHAPES if it's a keyword. If not, it assumes the val represents the bespoke curve vals for a generic curve shape (shape type 5). the bespoke curve vals aren't used here, but are picked up in curve-value. Mirrors *shapeNumber in supercollider/SCClassLibrary/Common/Audio/Env.sc" [s] (if (keyword? s) (repeat (s ENV-SHAPES)) (repeat 5))) (defn- curve-value "Create the curves list for this curve type. For all standard shapes this list of vals isn't used. It's only required when the shape is a generic 'curve' shape when the curve vals represent the curvature value for each segment. A single float is repeated for all segments whilst a list of floats can be used to represent the curvature value for each segment individually. Mirrors curveValue in supercollider/SCClassLibrary/Common/Audio/Env.sc" ;; [c] (cond (sequential? c) c (number? c) (repeat c) :else (repeat 0))) ;; Envelope specs describe a series of segments of a line, which can be used to automate ;; control values in synths. ;; ;; [ <initialLevel>, ;; <numberOfSegments>, ;; <releaseNode>, ;; <loopNode>, ;; <segment1TargetLevel>, <segment1Duration>, <segment1Shape>, <segment1Curve>, ;; ... ;; <segment-N...> ] (defn envelope "Create an envelope curve description array suitable for the env-gen ugen. Requires a list of levels (the points that the envelope will pass through and a list of durations (the duration in time of the lines between each point). Optionally a curve may be specified. This may be one of: * :step - flat segments * :linear - linear segments, the default * :exponential - natural exponential growth and decay. In this case, the levels must all be nonzero and the have the same sign. * :sine - sinusoidal S shaped segments. * :welch - sinusoidal segments shaped like the sides of a Welch window. * a Float - a curvature value to be repeated for all segments. * an Array of Floats - individual curvature values for each segment. If a release-node is specified (an integer index) the envelope will sustain at the release node until released which occurs when the gate input of the env-gen is set to zero. If a loop-node is specified (an integer index) the output will loop through those nodes starting at the loop node to the node immediately preceeding the release node, before back to the loop node, and so on. Note that the envelope only transitions to the release node when released. The loop is escaped when a gate signal is sent, which results with the the output transitioning to the release node." ;;See prAsArray in supercollider/SCClassLibrary/Common/Audio/Env.sc [levels durations & [curve release-node loop-node]] (let [curve (or curve :linear) reln (or release-node -99) loopn (or loop-node -99) shapes (shape->id curve) curves (curve-value curve)] (apply vector (concat [(first levels) (count durations) reln loopn] (interleave (rest levels) durations shapes curves))))) (defunk triangle "Create a triangle envelope description array suitable for use with the env-gen ugen" [dur 1 level 1] (with-overloaded-ugens (let [dur (* dur 0.5)] (envelope [0 level 0] [dur dur])))) (defunk sine "Create a sine envelope description suitable for use with the env-gen ugen" [dur 1 level 1] (with-overloaded-ugens (let [dur (* dur 0.5)] (envelope [0 level 0] [dur dur] :sine)))) (defunk perc "Create a percussive envelope description suitable for use with the env-gen ugen" [attack 0.01 release 1 level 1 curve -4] (with-overloaded-ugens (envelope [0 level 0] [attack release] curve))) (defunk lin-env "Create a trapezoidal envelope description suitable for use with the env-gen ugen" [attack 0.01 sustain 1 release 1 level 1 curve :linear] (with-overloaded-ugens (envelope [0 level level 0] [attack sustain release] curve))) (defunk cutoff "Create a cutoff envelope description suitable for use with the env-gen ugen" [release 0.1 level 1 curve :linear] (with-overloaded-ugens (envelope [level 0] [release] curve 0))) (defunk dadsr "Create a delayed attack decay sustain release envelope suitable for use with the env-gen ugen" [delay-t 0.1 attack 0.01 decay 0.3 sustain 0.5 release 1 level 1 curve -4 bias 0] (with-overloaded-ugens (envelope (map #(+ %1 bias) [0 0 level (* level sustain) 0]) [delay-t attack decay release] curve))) (defunk adsr "Create an attack decay sustain release envelope suitable for use with the env-gen ugen" [attack 0.01 decay 0.3 sustain 1 release 1 level 1 curve -4 bias 0] (with-overloaded-ugens (envelope (map #(+ %1 bias) [0 level (* level sustain) 0]) [attack decay release] curve 2))) (defunk asr "Create an attack sustain release envelope sutable for use with the env-gen ugen" [attack 0.01 sustain 1 release 1 curve -4] (with-overloaded-ugens (envelope [0 sustain 0] [attack release] curve 1))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Envelope Curve Shapes ;; Thanks to ScalaCollider for these shape formulas! ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn step-shape [pos y1 y2] (if (< pos 1) y1 y2)) (defn linear-shape [pos y1 y2] (+ y1 (* pos (- y2 y1)))) (defn exponential-shape [pos y1 y2] (let [limit (max 0.0001 y1)] (* limit (Math/pow (/ y2 limit) pos)))) (defn sine-shape [pos y1 y2] (+ y1 (* (- y2 y1) (+ (* -1 (Math/cos (* Math/PI pos)) 0.5) 0.5)))) (defn welch-shape [pos y1 y2] (let [pos (if (< y1 y2) pos (- 1.0 pos))] (+ y1 (* (- y2 y1) (Math/sin (* Math/PI 0.5 pos)))))) (defn curve-shape [pos y1 y2 curvature] (if (< (Math/abs curvature) 0.0001) (+ (* pos (- y2 y1)) y1) (let [denominator (- 1.0 (Math/exp curvature)) numerator (- 1.0 (Math/exp (* pos curvature)))] (+ y1 (* (- y2 y1) (/ numerator denominator)))))) (defn squared-shape [pos y1 y2] (let [y1-s (Math/sqrt y1) y2-s (Math/sqrt y2) yp (+ y1-s (* pos (- y2-s y1-s)))] (* yp yp))) (defn cubed-shape [pos y1 y2] (let [y1-c (Math/pow y1 0.3333333) y2-c (Math/pow y2 0.3333333) yp (+ y1-c (* pos (- y2-c y1-c)))] (* yp yp yp)))
true
(ns ^{:doc "An envelope defines a waveform that will be used to control another component of a synthesizer over time. It is typical to use envelopes to control the amplitude of a source waveform. For example, an envelope will dictate that a sound should start quick and loud, but then drop shortly and tail off gently. Another common usage is to see envelopes controlling filter cutoff values over time. These are the typical envelope functions found in SuperCollider, and they output a series of numbers that is understood by the SC synth engine." :author "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI"} overtone.sc.envelope (:use [overtone.util lib] [overtone.sc ugens])) (def ENV-SHAPES {:step 0 :lin 1 :linear 1 :exp 2 :exponential 2 :sin 3 :sine 3 :wel 4 :welch 4 :sqr 6 :squared 6 :cub 7 :cubed 7 }) (defn- shape->id "Create a repeating shapes list corresponding to a specific shape type. Looks shape s up in ENV-SHAPES if it's a keyword. If not, it assumes the val represents the bespoke curve vals for a generic curve shape (shape type 5). the bespoke curve vals aren't used here, but are picked up in curve-value. Mirrors *shapeNumber in supercollider/SCClassLibrary/Common/Audio/Env.sc" [s] (if (keyword? s) (repeat (s ENV-SHAPES)) (repeat 5))) (defn- curve-value "Create the curves list for this curve type. For all standard shapes this list of vals isn't used. It's only required when the shape is a generic 'curve' shape when the curve vals represent the curvature value for each segment. A single float is repeated for all segments whilst a list of floats can be used to represent the curvature value for each segment individually. Mirrors curveValue in supercollider/SCClassLibrary/Common/Audio/Env.sc" ;; [c] (cond (sequential? c) c (number? c) (repeat c) :else (repeat 0))) ;; Envelope specs describe a series of segments of a line, which can be used to automate ;; control values in synths. ;; ;; [ <initialLevel>, ;; <numberOfSegments>, ;; <releaseNode>, ;; <loopNode>, ;; <segment1TargetLevel>, <segment1Duration>, <segment1Shape>, <segment1Curve>, ;; ... ;; <segment-N...> ] (defn envelope "Create an envelope curve description array suitable for the env-gen ugen. Requires a list of levels (the points that the envelope will pass through and a list of durations (the duration in time of the lines between each point). Optionally a curve may be specified. This may be one of: * :step - flat segments * :linear - linear segments, the default * :exponential - natural exponential growth and decay. In this case, the levels must all be nonzero and the have the same sign. * :sine - sinusoidal S shaped segments. * :welch - sinusoidal segments shaped like the sides of a Welch window. * a Float - a curvature value to be repeated for all segments. * an Array of Floats - individual curvature values for each segment. If a release-node is specified (an integer index) the envelope will sustain at the release node until released which occurs when the gate input of the env-gen is set to zero. If a loop-node is specified (an integer index) the output will loop through those nodes starting at the loop node to the node immediately preceeding the release node, before back to the loop node, and so on. Note that the envelope only transitions to the release node when released. The loop is escaped when a gate signal is sent, which results with the the output transitioning to the release node." ;;See prAsArray in supercollider/SCClassLibrary/Common/Audio/Env.sc [levels durations & [curve release-node loop-node]] (let [curve (or curve :linear) reln (or release-node -99) loopn (or loop-node -99) shapes (shape->id curve) curves (curve-value curve)] (apply vector (concat [(first levels) (count durations) reln loopn] (interleave (rest levels) durations shapes curves))))) (defunk triangle "Create a triangle envelope description array suitable for use with the env-gen ugen" [dur 1 level 1] (with-overloaded-ugens (let [dur (* dur 0.5)] (envelope [0 level 0] [dur dur])))) (defunk sine "Create a sine envelope description suitable for use with the env-gen ugen" [dur 1 level 1] (with-overloaded-ugens (let [dur (* dur 0.5)] (envelope [0 level 0] [dur dur] :sine)))) (defunk perc "Create a percussive envelope description suitable for use with the env-gen ugen" [attack 0.01 release 1 level 1 curve -4] (with-overloaded-ugens (envelope [0 level 0] [attack release] curve))) (defunk lin-env "Create a trapezoidal envelope description suitable for use with the env-gen ugen" [attack 0.01 sustain 1 release 1 level 1 curve :linear] (with-overloaded-ugens (envelope [0 level level 0] [attack sustain release] curve))) (defunk cutoff "Create a cutoff envelope description suitable for use with the env-gen ugen" [release 0.1 level 1 curve :linear] (with-overloaded-ugens (envelope [level 0] [release] curve 0))) (defunk dadsr "Create a delayed attack decay sustain release envelope suitable for use with the env-gen ugen" [delay-t 0.1 attack 0.01 decay 0.3 sustain 0.5 release 1 level 1 curve -4 bias 0] (with-overloaded-ugens (envelope (map #(+ %1 bias) [0 0 level (* level sustain) 0]) [delay-t attack decay release] curve))) (defunk adsr "Create an attack decay sustain release envelope suitable for use with the env-gen ugen" [attack 0.01 decay 0.3 sustain 1 release 1 level 1 curve -4 bias 0] (with-overloaded-ugens (envelope (map #(+ %1 bias) [0 level (* level sustain) 0]) [attack decay release] curve 2))) (defunk asr "Create an attack sustain release envelope sutable for use with the env-gen ugen" [attack 0.01 sustain 1 release 1 curve -4] (with-overloaded-ugens (envelope [0 sustain 0] [attack release] curve 1))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Envelope Curve Shapes ;; Thanks to ScalaCollider for these shape formulas! ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn step-shape [pos y1 y2] (if (< pos 1) y1 y2)) (defn linear-shape [pos y1 y2] (+ y1 (* pos (- y2 y1)))) (defn exponential-shape [pos y1 y2] (let [limit (max 0.0001 y1)] (* limit (Math/pow (/ y2 limit) pos)))) (defn sine-shape [pos y1 y2] (+ y1 (* (- y2 y1) (+ (* -1 (Math/cos (* Math/PI pos)) 0.5) 0.5)))) (defn welch-shape [pos y1 y2] (let [pos (if (< y1 y2) pos (- 1.0 pos))] (+ y1 (* (- y2 y1) (Math/sin (* Math/PI 0.5 pos)))))) (defn curve-shape [pos y1 y2 curvature] (if (< (Math/abs curvature) 0.0001) (+ (* pos (- y2 y1)) y1) (let [denominator (- 1.0 (Math/exp curvature)) numerator (- 1.0 (Math/exp (* pos curvature)))] (+ y1 (* (- y2 y1) (/ numerator denominator)))))) (defn squared-shape [pos y1 y2] (let [y1-s (Math/sqrt y1) y2-s (Math/sqrt y2) yp (+ y1-s (* pos (- y2-s y1-s)))] (* yp yp))) (defn cubed-shape [pos y1 y2] (let [y1-c (Math/pow y1 0.3333333) y2-c (Math/pow y2 0.3333333) yp (+ y1-c (* pos (- y2-c y1-c)))] (* yp yp yp)))
[ { "context": " a source query.\n See [#9767](https://github.com/metabase/metabase/issues/9767) for more details. After thi", "end": 21765, "score": 0.99881911277771, "start": 21757, "tag": "USERNAME", "value": "metabase" }, { "context": "eral\n `:aggregation-options`](https://github.com/metabase/mbql/pull/7). Because user-generated names are no", "end": 22086, "score": 0.997105598449707, "start": 22078, "tag": "USERNAME", "value": "metabase" }, { "context": "\n\n {:query \\\"SELECT * FROM birds WHERE name = 'Reggae'\\\"}\n\n This is used to power features such as 'Co", "end": 24319, "score": 0.9891493320465088, "start": 24313, "tag": "NAME", "value": "Reggae" } ]
c#-metabase/src/metabase/driver.clj
hanakhry/Crime_Admin
0
(ns metabase.driver "Metabase Drivers handle various things we need to do with connected data warehouse databases, including things like introspecting their schemas and processing and running MBQL queries. Drivers must implement some or all of the multimethods defined below, and register themselves with a call to [[metabase.driver/register!]]. SQL-based drivers can use the `:sql` driver as a parent, and JDBC-based SQL drivers can use `:sql-jdbc`. Both of these drivers define additional multimethods that child drivers should implement; see [[metabase.driver.sql]] and [[metabase.driver.sql-jdbc]] for more details." (:require [clojure.string :as str] [clojure.tools.logging :as log] [metabase.driver.impl :as impl] [metabase.models.setting :as setting :refer [defsetting]] [metabase.plugins.classloader :as classloader] [metabase.util.i18n :refer [deferred-tru trs tru]] [metabase.util.schema :as su] [potemkin :as p] [schema.core :as s] [toucan.db :as db]) (:import org.joda.time.DateTime)) (declare notify-database-updated) (defn- notify-all-databases-updated "Send notification that all Databases should immediately release cached resources (i.e., connection pools). Currently only used below by [[report-timezone]] setter (i.e., only used when report timezone changes). Reusing pooled connections with the old session timezone can have weird effects, especially if report timezone is changed to `nil` (meaning subsequent queries will not attempt to change the session timezone) or something considered invalid by a given Database (meaning subsequent queries will fail to change the session timezone)." [] (doseq [{driver :engine, id :id, :as database} (db/select 'Database)] (try (notify-database-updated driver database) (catch Throwable e (log/error e (trs "Failed to notify {0} Database {1} updated" driver id)))))) (defsetting report-timezone (deferred-tru "Connection timezone to use when executing queries. Defaults to system timezone.") :setter (fn [new-value] (setting/set-string! :report-timezone new-value) (notify-all-databases-updated))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | Current Driver | ;;; +----------------------------------------------------------------------------------------------------------------+ (def ^:dynamic *driver* "Current driver (a keyword such as `:postgres`) in use by the Query Processor/tests/etc. Bind this with `with-driver` below. The QP binds the driver this way in the `bind-driver` middleware." nil) (declare the-driver) (defn do-with-driver "Impl for `with-driver`." [driver f] (binding [*driver* (the-driver driver)] (f))) (defmacro with-driver "Bind current driver to `driver` and execute `body`. (driver/with-driver :postgres ...)" {:style/indent 1} [driver & body] `(do-with-driver ~driver (fn [] ~@body))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | Driver Registration / Hierarchy / Multimethod Dispatch | ;;; +----------------------------------------------------------------------------------------------------------------+ (p/import-vars [impl hierarchy register! initialized?]) (add-watch #'hierarchy nil (fn [_ _ _ _] (when (not= hierarchy impl/hierarchy) ;; this is a dev-facing error so no need to i18n it. (throw (Exception. (str "Don't alter #'metabase.driver/hierarchy directly, since it is imported from " "metabase.driver.impl. Alter #'metabase.driver.impl/hierarchy instead if you need to " "alter the var directly.")))))) (defn available? "Is this driver available for use? (i.e. should we show it as an option when adding a new database?) This is `true` for all registered, non-abstract drivers and false everything else. Note that an available driver is not necessarily initialized yet; for example lazy-loaded drivers are *registered* when Metabase starts up (meaning this will return `true` for them) and only initialized when first needed." [driver] ((every-pred impl/registered? impl/concrete?) driver)) (defn the-driver "Like [[clojure.core/the-ns]]. Converts argument to a keyword, then loads and registers the driver if not already done, throwing an Exception if it fails or is invalid. Returns keyword. Note that this does not neccessarily mean the driver is initialized (e.g., its full implementation and deps might not be loaded into memory) -- see also [[the-initialized-driver]]. This is useful in several cases: ;; Ensuring a driver is loaded & registered (isa? driver/hierarchy (the-driver :postgres) (the-driver :sql-jdbc) ;; Accepting either strings or keywords (e.g., in API endpoints) (the-driver \"h2\") ; -> :h2 ;; Ensuring a driver you are passed is valid (db/insert! Database :engine (name (the-driver driver))) (the-driver :postgres) ; -> :postgres (the-driver :baby) ; -> Exception" [driver] {:pre [((some-fn keyword? string?) driver)]} (classloader/the-classloader) (let [driver (keyword driver)] (impl/load-driver-namespace-if-needed! driver) driver)) (defn add-parent! "Add a new parent to `driver`." [driver new-parent] (when-not *compile-files* (impl/load-driver-namespace-if-needed! driver) (impl/load-driver-namespace-if-needed! new-parent) (alter-var-root #'impl/hierarchy derive driver new-parent))) (defn- dispatch-on-uninitialized-driver "Dispatch function to use for driver multimethods. Dispatches on first arg, a driver keyword; loads that driver's namespace if not already done. DOES NOT INITIALIZE THE DRIVER. Driver multimethods for abstract drivers like `:sql` or `:sql-jdbc` should use [[dispatch-on-initialized-driver]] to ensure the driver is initialized (i.e., its method implementations will be loaded)." [driver & _] (the-driver driver)) (declare initialize!) (defn the-initialized-driver "Like [[the-driver]], but also initializes the driver if not already initialized." [driver] (let [driver (the-driver driver)] (impl/initialize-if-needed! driver initialize!) driver)) (defn dispatch-on-initialized-driver "Like [[dispatch-on-uninitialized-driver]], but guarantees a driver is initialized before dispatch. Prefer [[the-driver]] for trivial methods that should do not require the driver to be initialized (e.g., ones that simply return information about the driver, but do not actually connect to any databases.)" [driver & _] (the-initialized-driver driver)) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | Interface (Multimethod Defintions) | ;;; +----------------------------------------------------------------------------------------------------------------+ ;; Methods a driver can implement. Not all of these are required; some have default implementations immediately below ;; them. ;; ;; SOME TIPS: ;; ;; To call the Clojure equivalent of the superclass implementation of a method, use `get-method` with the parent driver: ;; ;; (driver/register-driver! :my-driver, :parent :sql-jdbc) ;; ;; (defmethod driver/describe-table :my-driver [driver database table] ;; (-> ((get-method driver/describe-table :sql-jdbc) driver databse table) ;; (update :tables add-materialized-views))) ;; ;; Make sure to pass along the `driver` parameter-as when you call other methods, rather than hardcoding the name of ;; the current driver (e.g. `:my-driver` in the example above). This way if other drivers use your driver as a parent ;; in the future their implementations of any methods called by those methods will get used. (defmulti initialize! "DO NOT CALL THIS METHOD DIRECTLY. Called automatically once and only once the first time a non-trivial driver method is called; implementers should do one-time initialization as needed (for example, registering JDBC drivers used internally by the driver.) 'Trivial' methods include a tiny handful of ones like [[connection-properties]] that simply provide information about the driver, but do not connect to databases; these can be be supplied, for example, by a Metabase plugin manifest file (which is supplied for lazy-loaded drivers). Methods that require connecting to a database dispatch off of [[the-initialized-driver]], which will initialize a driver if not already done so. You will rarely need to write an implentation for this method yourself. A lazy-loaded driver (like most of the Metabase drivers in v1.0 and above) are automatiaclly given an implentation of this method that performs the `init-steps` specified in the plugin manifest (such as loading namespaces in question). If you do need to implement this method yourself, you do not need to call parent implementations. We'll take care of that for you." {:arglists '([driver])} dispatch-on-uninitialized-driver) ;; VERY IMPORTANT: Unlike all other driver multimethods, we DO NOT use the driver hierarchy for dispatch here. Why? ;; We do not want a driver to inherit parent drivers' implementations and have those implementations end up getting ;; called multiple times. If a driver does not implement `initialize!`, *always* fall back to the default no-op ;; implementation. ;; ;; `initialize-if-needed!` takes care to make sure a driver's parent(s) are initialized before initializing a driver. (defmethod initialize! :default [_]) ; no-op (defmulti display-name "A nice name for the driver that we'll display to in the admin panel, e.g. \"PostgreSQL\" for `:postgres`. Default implementation capitializes the name of the driver, e.g. `:presto` becomes \"Presto\". When writing a driver that you plan to ship as a separate, lazy-loading plugin (including core drivers packaged this way, like SQLite), you do not need to implement this method; instead, specifiy it in your plugin manifest, and `lazy-loaded-driver` will create an implementation for you. Probably best if we only have one place where we set values for this." {:arglists '([driver])} dispatch-on-uninitialized-driver :hierarchy #'hierarchy) (defmethod display-name :default [driver] (str/capitalize (name driver))) (defmulti can-connect? "Check whether we can connect to a `Database` with `details-map` and perform a simple query. For example, a SQL database might try running a query like `SELECT 1;`. This function should return truthy if a connection to the DB can be made successfully, otherwise it should return falsey or throw an appropriate Exception. Exceptions if a connection cannot be made." {:arglists '([driver details])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmulti describe-database "Return a map containing information that describes all of the tables in a `database`, an instance of the `Database` model. It is expected that this function will be peformant and avoid draining meaningful resources of the database. Results should match the [[metabase.sync.interface/DatabaseMetadata]] schema." {:arglists '([driver database])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmulti describe-table "Return a map containing information that describes the physical schema of `table` (i.e. the fields contained therein). `database` will be an instance of the `Database` model; and `table`, an instance of the `Table` model. It is expected that this function will be peformant and avoid draining meaningful resources of the database. Results should match the [[metabase.sync.interface/TableMetadata]] schema." {:arglists '([driver database table])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmulti escape-entity-name-for-metadata "escaping for when calling `.getColumns` or `.getTables` on table names or schema names. Useful for when a database driver has difference escaping rules for table or schema names when used from metadata. For example, oracle treats slashes differently when querying versus when used with `.getTables` or `.getColumns`" {:arglists '([driver table-name])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod escape-entity-name-for-metadata :default [_driver table-name] table-name) (defmulti describe-table-fks "Return information about the foreign keys in a `table`. Required for drivers that support `:foreign-keys`. Results should match the [[metabase.sync.interface/FKMetadata]] schema." {:arglists '([this database table])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod describe-table-fks ::driver [_ _ _] nil) (def ConnectionDetailsProperty "Schema for a map containing information about a connection property we should ask the user to supply when setting up a new database, as returned by an implementation of `connection-properties`." (s/constrained { ;; The key that should be used to store this property in the `details` map. :name su/NonBlankString ;; Human-readable name that should be displayed to the User in UI for editing this field. :display-name su/NonBlankString ;; Type of this property. Defaults to `:string` if unspecified. ;; `:select` is a `String` in the backend. (s/optional-key :type) (s/enum :string :integer :boolean :password :select :text) ;; A default value for this field if the user hasn't set an explicit value. This is shown in the UI as a ;; placeholder. (s/optional-key :default) s/Any ;; Placeholder value to show in the UI if user hasn't set an explicit value. Similar to `:default`, but this value ;; is *not* saved to `:details` if no explicit value is set. Since `:default` values are also shown as ;; placeholders, you cannot specify both `:default` and `:placeholder`. (s/optional-key :placeholder) s/Any ;; Is this property required? Defaults to `false`. (s/optional-key :required?) s/Bool ;; Any options for `:select` types (s/optional-key :options) {s/Keyword s/Str}} (complement (every-pred #(contains? % :default) #(contains? % :placeholder))) "connection details that does not have both default and placeholder")) (defmulti connection-properties "Return information about the connection properties that should be exposed to the user for databases that will use this driver. This information is used to build the UI for editing a Database `details` map, and for validating it on the backend. It should include things like `host`, `port`, and other driver-specific parameters. Each property must conform to the [[ConnectionDetailsProperty]] schema above. There are several definitions for common properties available in the [[metabase.driver.common]] namespace, such as `default-host-details` and `default-port-details`. Prefer using these if possible. Like `display-name`, lazy-loaded drivers should specify this in their plugin manifest; `lazy-loaded-driver` will automatically create an implementation for you." {:arglists '([driver])} dispatch-on-uninitialized-driver :hierarchy #'hierarchy) (defmulti execute-reducible-query "Execute a native query against that database and return rows that can be reduced using `transduce`/`reduce`. Pass metadata about the columns and the reducible object to `respond`, which has the signature (respond results-metadata rows) You can use [[metabase.query-processor.reducible/reducible-rows]] to create reducible, streaming results. Example impl: (defmethod reducible-query :my-driver [_ query context respond] (with-open [results (run-query! query)] (respond {:cols [{:name \"my_col\"}]} (qp.reducible/reducible-rows (get-row results) (context/canceled-chan context)))))" {:added "0.35.0", :arglists '([driver query context respond])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (def driver-features "Set of all features a driver can support." #{ ;; Does this database support foreign key relationships? :foreign-keys ;; Does this database support nested fields (e.g. Mongo)? :nested-fields ;; Does this driver support setting a timezone for the query? :set-timezone ;; Does the driver support *basic* aggregations like `:count` and `:sum`? (Currently, everything besides standard ;; deviation is considered \"basic\"; only GA doesn't support this). ;; ;; DEFAULTS TO TRUE. :basic-aggregations ;; Does this driver support standard deviation and variance aggregations? :standard-deviation-aggregations ;; Does this driver support expressions (e.g. adding the values of 2 columns together)? :expressions ;; Does this driver support parameter substitution in native queries, where parameter expressions are replaced ;; with a single value? e.g. ;; ;; SELECT * FROM table WHERE field = {{param}} ;; -> ;; SELECT * FROM table WHERE field = 1 :native-parameters ;; Does the driver support using expressions inside aggregations? e.g. something like \"sum(x) + count(y)\" or ;; \"avg(x + y)\" :expression-aggregations ;; Does the driver support using a query as the `:source-query` of another MBQL query? Examples are CTEs or ;; subselects in SQL queries. :nested-queries ;; Does the driver support binning as specified by the `binning-strategy` clause? :binning ;; Does this driver not let you specify whether or not our string search filter clauses (`:contains`, ;; `:starts-with`, and `:ends-with`, collectively the equivalent of SQL `LIKE`) are case-senstive or not? This ;; informs whether we should present you with the 'Case Sensitive' checkbox in the UI. At the time of this writing ;; SQLite, SQLServer, and MySQL do not support this -- `LIKE` clauses are always case-insensitive. ;; ;; DEFAULTS TO TRUE. :case-sensitivity-string-filter-options :left-join :right-join :inner-join :full-join :regex ;; Does the driver support advanced math expressions such as log, power, ... :advanced-math-expressions ;; Does the driver support percentile calculations (including median) :percentile-aggregations}) (defmulti ^:deprecated supports? "Does this driver support a certain `feature`? (A feature is a keyword, and can be any of the ones listed above in [[driver-features]].) (supports? :postgres :set-timezone) ; -> true deprecated — [[database-supports?]] is intended to replace this method. However, it driver authors should continue _implementing_ `supports?` for the time being until we get a chance to migrate all our usages." {:arglists '([driver feature])} (fn [driver feature] (when-not (driver-features feature) (throw (Exception. (tru "Invalid driver feature: {0}" feature)))) [(dispatch-on-initialized-driver driver) feature]) :hierarchy #'hierarchy) (defmethod supports? :default [_ _] false) (defmethod supports? [::driver :basic-aggregations] [_ _] true) (defmethod supports? [::driver :case-sensitivity-string-filter-options] [_ _] true) (defmulti database-supports? "Does this driver and specific instance of a database support a certain `feature`? (A feature is a keyword, and can be any of the ones listed above in `driver-features`. Note that it's the same set of `driver-features` with respect to both database-supports? and [[supports?]]) Database is guaranteed to be a Database instance. Most drivers can always return true or always return false for a given feature (e.g., :left-join is not supported by any version of Mongo DB). In some cases, a feature may only be supported by certain versions of the database engine. In this case, after implementing `:version` in `describe-database` for the driver, you can check in `(get-in db [:details :version])` and determine whether a feature is supported for this particular database. (database-supports? :mongo :set-timezone mongo-db) ; -> true" {:arglists '([driver feature database])} (fn [driver feature database] (when-not (driver-features feature) (throw (Exception. (tru "Invalid driver feature: {0}" feature)))) [(dispatch-on-initialized-driver driver) feature]) :hierarchy #'hierarchy) (defmethod database-supports? :default [driver feature _] (supports? driver feature)) (defmulti ^:deprecated format-custom-field-name "Prior to Metabase 0.33.0, you could specifiy custom names for aggregations in MBQL by wrapping the clause in a `:named` clause: [:named [:count] \"My Count\"] This name was used for both the `:display_name` in the query results, and for the `:name` used as an alias in the query (e.g. the right-hand side of a SQL `AS` expression). Because some custom display names weren't allowed by some drivers, or would be transformed in some way (for example, Redshift always lowercases custom aliases), this method was needed so we could match the name we had given the column with the one in the query results. In 0.33.0, we started using `:named` internally to alias aggregations in middleware in *all* queries to prevent issues with referring to multiple aggregations of the same type when that query was used as a source query. See [#9767](https://github.com/metabase/metabase/issues/9767) for more details. After this change, it became desirable to differentiate between such internally-generated aliases and display names, which need not be used in the query at all; thus in MBQL 1.3.0 [`:named` was replaced by the more general `:aggregation-options`](https://github.com/metabase/mbql/pull/7). Because user-generated names are no longer used as aliases in native queries themselves, this method is no longer needed and will be removed in a future release." {:arglists '([driver custom-field-name])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod format-custom-field-name ::driver [_ custom-field-name] custom-field-name) (defmulti humanize-connection-error-message "Return a humanized (user-facing) version of an connection error message. Generic error messages are provided in `metabase.driver.common/connection-error-messages`; return one of these whenever possible. Error messages can be strings, or localized strings, as returned by `metabase.util.i18n/trs` and `metabase.util.i18n/tru`." {:arglists '([this message])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod humanize-connection-error-message ::driver [_ message] message) (defmulti mbql->native "Transpile an MBQL query into the appropriate native query form. `query` will match the schema for an MBQL query in `metabase.mbql.schema/Query`; this function should return a native query that conforms to that schema. If the underlying query language supports remarks or comments, the driver should use `query->remark` to generate an appropriate message and include that in an appropriate place; alternatively a driver might directly include the query's `:info` dictionary if the underlying language is JSON-based. The result of this function will be passed directly into calls to `execute-reducible-query`. For example, a driver like Postgres would build a valid SQL expression and return a map such as: {:query \"-- Metabase card: 10 user: 5 SELECT * FROM my_table\"}" {:arglists '([driver query]), :style/indent 1} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmulti splice-parameters-into-native-query "For a native query that has separate parameters, such as a JDBC prepared statement, e.g. {:query \"SELECT * FROM birds WHERE name = ?\", :params [\"Reggae\"]} splice the parameters in to the native query as literals so it can be executed by the user, e.g. {:query \"SELECT * FROM birds WHERE name = 'Reggae'\"} This is used to power features such as 'Convert this Question to SQL' in the Query Builder. Normally when executing the query we'd like to leave the statement as a prepared one and pass parameters that way instead of splicing them in as literals so as to avoid SQL injection vulnerabilities. Thus the results of this method are not normally executed by the Query Processor when processing an MBQL query. However when people convert a question to SQL they can see what they will be executing and edit the query as needed. Input to this function follows the same shape as output of `mbql->native` -- that is, it will be a so-called 'inner' native query, with `:query` and `:params` keys, as in the example code above; output should be of the same format. This method might be called even if no splicing needs to take place, e.g. if `:params` is empty; implementations should be sure to handle this situation correctly. For databases that do not feature concepts like 'prepared statements', this method need not be implemented; the default implementation is an identity function." {:arglists '([driver query]), :style/indent 1} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod splice-parameters-into-native-query ::driver [_ query] query) ;; TODO - we should just have some sort of `core.async` channel to handle DB update notifications instead (defmulti notify-database-updated "Notify the driver that the attributes of a `database` have changed, or that `database was deleted. This is specifically relevant in the event that the driver was doing some caching or connection pooling; the driver should release ALL related resources when this is called." {:arglists '([driver database])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod notify-database-updated ::driver [_ _] nil) ; no-op (defmulti sync-in-context "Drivers may provide this function if they need to do special setup before a sync operation such as `sync-database!`. The sync operation itself is encapsulated as the lambda `f`, which must be called with no arguments. (defn sync-in-context [driver database f] (with-connection [_ database] (f)))" {:arglists '([driver database f]), :style/indent 2} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod sync-in-context ::driver [_ _ f] (f)) (defmulti table-rows-seq "Return a sequence of *all* the rows in a given `table`, which is guaranteed to have at least `:name` and `:schema` keys. (It is guaranteed to satisfy the `DatabaseMetadataTable` schema in `metabase.sync.interface`.) Currently, this is only used for iterating over the values in a `_metabase_metadata` table. As such, the results are not expected to be returned lazily. There is no expectation that the results be returned in any given order. This method is currently only used by the H2 driver to load the Sample Dataset, so it is not neccesary for any other drivers to implement it at this time." {:arglists '([driver database table])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmulti db-default-timezone "Return the *system* timezone ID name of this database, i.e. the timezone that local dates/times/datetimes are considered to be in by default. Ideally, this method should return a timezone ID like `America/Los_Angeles`, but an offset formatted like `-08:00` is acceptable in cases where the actual ID cannot be provided." {:added "0.34.0", :arglists '(^java.lang.String [driver database])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod db-default-timezone ::driver [_ _] nil) ;; TIMEZONE FIXME — remove this method entirely (defmulti current-db-time "Return the current time and timezone from the perspective of `database`. You can use `metabase.driver.common/current-db-time` to implement this. This should return a Joda-Time `DateTime`. deprecated — the only thing this method is ultimately used for is to determine the db's system timezone. `db-default-timezone` has been introduced as an intended replacement for this method; implement it instead. this method will be removed in a future release." {:deprecated "0.34.0", :arglists '(^org.joda.time.DateTime [driver database])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod current-db-time ::driver [_ _] nil) (defmulti substitute-native-parameters "For drivers that support `:native-parameters`. Substitute parameters in a normalized 'inner' native query. {:query \"SELECT count(*) FROM table WHERE id = {{param}}\" :template-tags {:param {:name \"param\", :display-name \"Param\", :type :number}} :parameters [{:type :number :target [:variable [:template-tag \"param\"]] :value 2}]} -> {:query \"SELECT count(*) FROM table WHERE id = 2\"} Much of the implementation for this method is shared across drivers and lives in the `metabase.driver.common.parameters.*` namespaces. See the `:sql` and `:mongo` drivers for sample implementations of this method.`Driver-agnostic end-to-end native parameter tests live in `metabase.query-processor-test.parameters-test` and other namespaces." {:arglists '([driver inner-query])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmulti default-field-order "Return how fields should be sorted by default for this database." {:added "0.36.0" :arglists '([driver])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod default-field-order ::driver [_] :database) (defmulti db-start-of-week "Return start of week for given database" {:added "0.37.0" :arglists '([driver])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmulti incorporate-ssh-tunnel-details "A multimethod for driver-specific behavior required to incorporate details for an opened SSH tunnel into the DB details. In most cases, this will simply involve updating the :host and :port (to point to the tunnel entry point, instead of the backing database server), but some drivers may have more specific behavior." {:added "0.39.0" :arglists '([driver db-details])} dispatch-on-uninitialized-driver :hierarchy #'hierarchy) (defmulti normalize-db-details "Normalizes db-details for the given driver. This is to handle migrations that are too difficult to perform via regular Liquibase queries. This multimethod will be called from a `:post-select` handler within the database model. The full `database` model object is passed as the 2nd parameter, and the multimethod implementation is expected to update the value for `:details`. The default implementation is essentially `identity` (i.e returns `database` unchanged). This multimethod will only be called if `:details` is actually present in the `database` map." {:added "0.41.0" :arglists '([driver database])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod normalize-db-details ::driver [_ db-details] ;; no normalization by default db-details) (defmulti superseded-by "Returns the driver that supersedes the given `driver`. A non-nil return value means that the given `driver` is deprecated in Metabase and will eventually be replaced by the returned driver, in some future version (at which point any databases using it will be migrated to the new one). This is currently only used on the frontend for the purpose of showing/hiding deprecated drivers. A driver can make use of this facility by adding a top-level `superseded-by` key to its plugin manifest YAML file, or (less preferred) overriding this multimethod directly." {:added "0.41.0" :arglists '([driver])} dispatch-on-uninitialized-driver :hierarchy #'hierarchy) (defmethod superseded-by :default [_] nil)
97096
(ns metabase.driver "Metabase Drivers handle various things we need to do with connected data warehouse databases, including things like introspecting their schemas and processing and running MBQL queries. Drivers must implement some or all of the multimethods defined below, and register themselves with a call to [[metabase.driver/register!]]. SQL-based drivers can use the `:sql` driver as a parent, and JDBC-based SQL drivers can use `:sql-jdbc`. Both of these drivers define additional multimethods that child drivers should implement; see [[metabase.driver.sql]] and [[metabase.driver.sql-jdbc]] for more details." (:require [clojure.string :as str] [clojure.tools.logging :as log] [metabase.driver.impl :as impl] [metabase.models.setting :as setting :refer [defsetting]] [metabase.plugins.classloader :as classloader] [metabase.util.i18n :refer [deferred-tru trs tru]] [metabase.util.schema :as su] [potemkin :as p] [schema.core :as s] [toucan.db :as db]) (:import org.joda.time.DateTime)) (declare notify-database-updated) (defn- notify-all-databases-updated "Send notification that all Databases should immediately release cached resources (i.e., connection pools). Currently only used below by [[report-timezone]] setter (i.e., only used when report timezone changes). Reusing pooled connections with the old session timezone can have weird effects, especially if report timezone is changed to `nil` (meaning subsequent queries will not attempt to change the session timezone) or something considered invalid by a given Database (meaning subsequent queries will fail to change the session timezone)." [] (doseq [{driver :engine, id :id, :as database} (db/select 'Database)] (try (notify-database-updated driver database) (catch Throwable e (log/error e (trs "Failed to notify {0} Database {1} updated" driver id)))))) (defsetting report-timezone (deferred-tru "Connection timezone to use when executing queries. Defaults to system timezone.") :setter (fn [new-value] (setting/set-string! :report-timezone new-value) (notify-all-databases-updated))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | Current Driver | ;;; +----------------------------------------------------------------------------------------------------------------+ (def ^:dynamic *driver* "Current driver (a keyword such as `:postgres`) in use by the Query Processor/tests/etc. Bind this with `with-driver` below. The QP binds the driver this way in the `bind-driver` middleware." nil) (declare the-driver) (defn do-with-driver "Impl for `with-driver`." [driver f] (binding [*driver* (the-driver driver)] (f))) (defmacro with-driver "Bind current driver to `driver` and execute `body`. (driver/with-driver :postgres ...)" {:style/indent 1} [driver & body] `(do-with-driver ~driver (fn [] ~@body))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | Driver Registration / Hierarchy / Multimethod Dispatch | ;;; +----------------------------------------------------------------------------------------------------------------+ (p/import-vars [impl hierarchy register! initialized?]) (add-watch #'hierarchy nil (fn [_ _ _ _] (when (not= hierarchy impl/hierarchy) ;; this is a dev-facing error so no need to i18n it. (throw (Exception. (str "Don't alter #'metabase.driver/hierarchy directly, since it is imported from " "metabase.driver.impl. Alter #'metabase.driver.impl/hierarchy instead if you need to " "alter the var directly.")))))) (defn available? "Is this driver available for use? (i.e. should we show it as an option when adding a new database?) This is `true` for all registered, non-abstract drivers and false everything else. Note that an available driver is not necessarily initialized yet; for example lazy-loaded drivers are *registered* when Metabase starts up (meaning this will return `true` for them) and only initialized when first needed." [driver] ((every-pred impl/registered? impl/concrete?) driver)) (defn the-driver "Like [[clojure.core/the-ns]]. Converts argument to a keyword, then loads and registers the driver if not already done, throwing an Exception if it fails or is invalid. Returns keyword. Note that this does not neccessarily mean the driver is initialized (e.g., its full implementation and deps might not be loaded into memory) -- see also [[the-initialized-driver]]. This is useful in several cases: ;; Ensuring a driver is loaded & registered (isa? driver/hierarchy (the-driver :postgres) (the-driver :sql-jdbc) ;; Accepting either strings or keywords (e.g., in API endpoints) (the-driver \"h2\") ; -> :h2 ;; Ensuring a driver you are passed is valid (db/insert! Database :engine (name (the-driver driver))) (the-driver :postgres) ; -> :postgres (the-driver :baby) ; -> Exception" [driver] {:pre [((some-fn keyword? string?) driver)]} (classloader/the-classloader) (let [driver (keyword driver)] (impl/load-driver-namespace-if-needed! driver) driver)) (defn add-parent! "Add a new parent to `driver`." [driver new-parent] (when-not *compile-files* (impl/load-driver-namespace-if-needed! driver) (impl/load-driver-namespace-if-needed! new-parent) (alter-var-root #'impl/hierarchy derive driver new-parent))) (defn- dispatch-on-uninitialized-driver "Dispatch function to use for driver multimethods. Dispatches on first arg, a driver keyword; loads that driver's namespace if not already done. DOES NOT INITIALIZE THE DRIVER. Driver multimethods for abstract drivers like `:sql` or `:sql-jdbc` should use [[dispatch-on-initialized-driver]] to ensure the driver is initialized (i.e., its method implementations will be loaded)." [driver & _] (the-driver driver)) (declare initialize!) (defn the-initialized-driver "Like [[the-driver]], but also initializes the driver if not already initialized." [driver] (let [driver (the-driver driver)] (impl/initialize-if-needed! driver initialize!) driver)) (defn dispatch-on-initialized-driver "Like [[dispatch-on-uninitialized-driver]], but guarantees a driver is initialized before dispatch. Prefer [[the-driver]] for trivial methods that should do not require the driver to be initialized (e.g., ones that simply return information about the driver, but do not actually connect to any databases.)" [driver & _] (the-initialized-driver driver)) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | Interface (Multimethod Defintions) | ;;; +----------------------------------------------------------------------------------------------------------------+ ;; Methods a driver can implement. Not all of these are required; some have default implementations immediately below ;; them. ;; ;; SOME TIPS: ;; ;; To call the Clojure equivalent of the superclass implementation of a method, use `get-method` with the parent driver: ;; ;; (driver/register-driver! :my-driver, :parent :sql-jdbc) ;; ;; (defmethod driver/describe-table :my-driver [driver database table] ;; (-> ((get-method driver/describe-table :sql-jdbc) driver databse table) ;; (update :tables add-materialized-views))) ;; ;; Make sure to pass along the `driver` parameter-as when you call other methods, rather than hardcoding the name of ;; the current driver (e.g. `:my-driver` in the example above). This way if other drivers use your driver as a parent ;; in the future their implementations of any methods called by those methods will get used. (defmulti initialize! "DO NOT CALL THIS METHOD DIRECTLY. Called automatically once and only once the first time a non-trivial driver method is called; implementers should do one-time initialization as needed (for example, registering JDBC drivers used internally by the driver.) 'Trivial' methods include a tiny handful of ones like [[connection-properties]] that simply provide information about the driver, but do not connect to databases; these can be be supplied, for example, by a Metabase plugin manifest file (which is supplied for lazy-loaded drivers). Methods that require connecting to a database dispatch off of [[the-initialized-driver]], which will initialize a driver if not already done so. You will rarely need to write an implentation for this method yourself. A lazy-loaded driver (like most of the Metabase drivers in v1.0 and above) are automatiaclly given an implentation of this method that performs the `init-steps` specified in the plugin manifest (such as loading namespaces in question). If you do need to implement this method yourself, you do not need to call parent implementations. We'll take care of that for you." {:arglists '([driver])} dispatch-on-uninitialized-driver) ;; VERY IMPORTANT: Unlike all other driver multimethods, we DO NOT use the driver hierarchy for dispatch here. Why? ;; We do not want a driver to inherit parent drivers' implementations and have those implementations end up getting ;; called multiple times. If a driver does not implement `initialize!`, *always* fall back to the default no-op ;; implementation. ;; ;; `initialize-if-needed!` takes care to make sure a driver's parent(s) are initialized before initializing a driver. (defmethod initialize! :default [_]) ; no-op (defmulti display-name "A nice name for the driver that we'll display to in the admin panel, e.g. \"PostgreSQL\" for `:postgres`. Default implementation capitializes the name of the driver, e.g. `:presto` becomes \"Presto\". When writing a driver that you plan to ship as a separate, lazy-loading plugin (including core drivers packaged this way, like SQLite), you do not need to implement this method; instead, specifiy it in your plugin manifest, and `lazy-loaded-driver` will create an implementation for you. Probably best if we only have one place where we set values for this." {:arglists '([driver])} dispatch-on-uninitialized-driver :hierarchy #'hierarchy) (defmethod display-name :default [driver] (str/capitalize (name driver))) (defmulti can-connect? "Check whether we can connect to a `Database` with `details-map` and perform a simple query. For example, a SQL database might try running a query like `SELECT 1;`. This function should return truthy if a connection to the DB can be made successfully, otherwise it should return falsey or throw an appropriate Exception. Exceptions if a connection cannot be made." {:arglists '([driver details])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmulti describe-database "Return a map containing information that describes all of the tables in a `database`, an instance of the `Database` model. It is expected that this function will be peformant and avoid draining meaningful resources of the database. Results should match the [[metabase.sync.interface/DatabaseMetadata]] schema." {:arglists '([driver database])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmulti describe-table "Return a map containing information that describes the physical schema of `table` (i.e. the fields contained therein). `database` will be an instance of the `Database` model; and `table`, an instance of the `Table` model. It is expected that this function will be peformant and avoid draining meaningful resources of the database. Results should match the [[metabase.sync.interface/TableMetadata]] schema." {:arglists '([driver database table])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmulti escape-entity-name-for-metadata "escaping for when calling `.getColumns` or `.getTables` on table names or schema names. Useful for when a database driver has difference escaping rules for table or schema names when used from metadata. For example, oracle treats slashes differently when querying versus when used with `.getTables` or `.getColumns`" {:arglists '([driver table-name])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod escape-entity-name-for-metadata :default [_driver table-name] table-name) (defmulti describe-table-fks "Return information about the foreign keys in a `table`. Required for drivers that support `:foreign-keys`. Results should match the [[metabase.sync.interface/FKMetadata]] schema." {:arglists '([this database table])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod describe-table-fks ::driver [_ _ _] nil) (def ConnectionDetailsProperty "Schema for a map containing information about a connection property we should ask the user to supply when setting up a new database, as returned by an implementation of `connection-properties`." (s/constrained { ;; The key that should be used to store this property in the `details` map. :name su/NonBlankString ;; Human-readable name that should be displayed to the User in UI for editing this field. :display-name su/NonBlankString ;; Type of this property. Defaults to `:string` if unspecified. ;; `:select` is a `String` in the backend. (s/optional-key :type) (s/enum :string :integer :boolean :password :select :text) ;; A default value for this field if the user hasn't set an explicit value. This is shown in the UI as a ;; placeholder. (s/optional-key :default) s/Any ;; Placeholder value to show in the UI if user hasn't set an explicit value. Similar to `:default`, but this value ;; is *not* saved to `:details` if no explicit value is set. Since `:default` values are also shown as ;; placeholders, you cannot specify both `:default` and `:placeholder`. (s/optional-key :placeholder) s/Any ;; Is this property required? Defaults to `false`. (s/optional-key :required?) s/Bool ;; Any options for `:select` types (s/optional-key :options) {s/Keyword s/Str}} (complement (every-pred #(contains? % :default) #(contains? % :placeholder))) "connection details that does not have both default and placeholder")) (defmulti connection-properties "Return information about the connection properties that should be exposed to the user for databases that will use this driver. This information is used to build the UI for editing a Database `details` map, and for validating it on the backend. It should include things like `host`, `port`, and other driver-specific parameters. Each property must conform to the [[ConnectionDetailsProperty]] schema above. There are several definitions for common properties available in the [[metabase.driver.common]] namespace, such as `default-host-details` and `default-port-details`. Prefer using these if possible. Like `display-name`, lazy-loaded drivers should specify this in their plugin manifest; `lazy-loaded-driver` will automatically create an implementation for you." {:arglists '([driver])} dispatch-on-uninitialized-driver :hierarchy #'hierarchy) (defmulti execute-reducible-query "Execute a native query against that database and return rows that can be reduced using `transduce`/`reduce`. Pass metadata about the columns and the reducible object to `respond`, which has the signature (respond results-metadata rows) You can use [[metabase.query-processor.reducible/reducible-rows]] to create reducible, streaming results. Example impl: (defmethod reducible-query :my-driver [_ query context respond] (with-open [results (run-query! query)] (respond {:cols [{:name \"my_col\"}]} (qp.reducible/reducible-rows (get-row results) (context/canceled-chan context)))))" {:added "0.35.0", :arglists '([driver query context respond])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (def driver-features "Set of all features a driver can support." #{ ;; Does this database support foreign key relationships? :foreign-keys ;; Does this database support nested fields (e.g. Mongo)? :nested-fields ;; Does this driver support setting a timezone for the query? :set-timezone ;; Does the driver support *basic* aggregations like `:count` and `:sum`? (Currently, everything besides standard ;; deviation is considered \"basic\"; only GA doesn't support this). ;; ;; DEFAULTS TO TRUE. :basic-aggregations ;; Does this driver support standard deviation and variance aggregations? :standard-deviation-aggregations ;; Does this driver support expressions (e.g. adding the values of 2 columns together)? :expressions ;; Does this driver support parameter substitution in native queries, where parameter expressions are replaced ;; with a single value? e.g. ;; ;; SELECT * FROM table WHERE field = {{param}} ;; -> ;; SELECT * FROM table WHERE field = 1 :native-parameters ;; Does the driver support using expressions inside aggregations? e.g. something like \"sum(x) + count(y)\" or ;; \"avg(x + y)\" :expression-aggregations ;; Does the driver support using a query as the `:source-query` of another MBQL query? Examples are CTEs or ;; subselects in SQL queries. :nested-queries ;; Does the driver support binning as specified by the `binning-strategy` clause? :binning ;; Does this driver not let you specify whether or not our string search filter clauses (`:contains`, ;; `:starts-with`, and `:ends-with`, collectively the equivalent of SQL `LIKE`) are case-senstive or not? This ;; informs whether we should present you with the 'Case Sensitive' checkbox in the UI. At the time of this writing ;; SQLite, SQLServer, and MySQL do not support this -- `LIKE` clauses are always case-insensitive. ;; ;; DEFAULTS TO TRUE. :case-sensitivity-string-filter-options :left-join :right-join :inner-join :full-join :regex ;; Does the driver support advanced math expressions such as log, power, ... :advanced-math-expressions ;; Does the driver support percentile calculations (including median) :percentile-aggregations}) (defmulti ^:deprecated supports? "Does this driver support a certain `feature`? (A feature is a keyword, and can be any of the ones listed above in [[driver-features]].) (supports? :postgres :set-timezone) ; -> true deprecated — [[database-supports?]] is intended to replace this method. However, it driver authors should continue _implementing_ `supports?` for the time being until we get a chance to migrate all our usages." {:arglists '([driver feature])} (fn [driver feature] (when-not (driver-features feature) (throw (Exception. (tru "Invalid driver feature: {0}" feature)))) [(dispatch-on-initialized-driver driver) feature]) :hierarchy #'hierarchy) (defmethod supports? :default [_ _] false) (defmethod supports? [::driver :basic-aggregations] [_ _] true) (defmethod supports? [::driver :case-sensitivity-string-filter-options] [_ _] true) (defmulti database-supports? "Does this driver and specific instance of a database support a certain `feature`? (A feature is a keyword, and can be any of the ones listed above in `driver-features`. Note that it's the same set of `driver-features` with respect to both database-supports? and [[supports?]]) Database is guaranteed to be a Database instance. Most drivers can always return true or always return false for a given feature (e.g., :left-join is not supported by any version of Mongo DB). In some cases, a feature may only be supported by certain versions of the database engine. In this case, after implementing `:version` in `describe-database` for the driver, you can check in `(get-in db [:details :version])` and determine whether a feature is supported for this particular database. (database-supports? :mongo :set-timezone mongo-db) ; -> true" {:arglists '([driver feature database])} (fn [driver feature database] (when-not (driver-features feature) (throw (Exception. (tru "Invalid driver feature: {0}" feature)))) [(dispatch-on-initialized-driver driver) feature]) :hierarchy #'hierarchy) (defmethod database-supports? :default [driver feature _] (supports? driver feature)) (defmulti ^:deprecated format-custom-field-name "Prior to Metabase 0.33.0, you could specifiy custom names for aggregations in MBQL by wrapping the clause in a `:named` clause: [:named [:count] \"My Count\"] This name was used for both the `:display_name` in the query results, and for the `:name` used as an alias in the query (e.g. the right-hand side of a SQL `AS` expression). Because some custom display names weren't allowed by some drivers, or would be transformed in some way (for example, Redshift always lowercases custom aliases), this method was needed so we could match the name we had given the column with the one in the query results. In 0.33.0, we started using `:named` internally to alias aggregations in middleware in *all* queries to prevent issues with referring to multiple aggregations of the same type when that query was used as a source query. See [#9767](https://github.com/metabase/metabase/issues/9767) for more details. After this change, it became desirable to differentiate between such internally-generated aliases and display names, which need not be used in the query at all; thus in MBQL 1.3.0 [`:named` was replaced by the more general `:aggregation-options`](https://github.com/metabase/mbql/pull/7). Because user-generated names are no longer used as aliases in native queries themselves, this method is no longer needed and will be removed in a future release." {:arglists '([driver custom-field-name])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod format-custom-field-name ::driver [_ custom-field-name] custom-field-name) (defmulti humanize-connection-error-message "Return a humanized (user-facing) version of an connection error message. Generic error messages are provided in `metabase.driver.common/connection-error-messages`; return one of these whenever possible. Error messages can be strings, or localized strings, as returned by `metabase.util.i18n/trs` and `metabase.util.i18n/tru`." {:arglists '([this message])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod humanize-connection-error-message ::driver [_ message] message) (defmulti mbql->native "Transpile an MBQL query into the appropriate native query form. `query` will match the schema for an MBQL query in `metabase.mbql.schema/Query`; this function should return a native query that conforms to that schema. If the underlying query language supports remarks or comments, the driver should use `query->remark` to generate an appropriate message and include that in an appropriate place; alternatively a driver might directly include the query's `:info` dictionary if the underlying language is JSON-based. The result of this function will be passed directly into calls to `execute-reducible-query`. For example, a driver like Postgres would build a valid SQL expression and return a map such as: {:query \"-- Metabase card: 10 user: 5 SELECT * FROM my_table\"}" {:arglists '([driver query]), :style/indent 1} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmulti splice-parameters-into-native-query "For a native query that has separate parameters, such as a JDBC prepared statement, e.g. {:query \"SELECT * FROM birds WHERE name = ?\", :params [\"Reggae\"]} splice the parameters in to the native query as literals so it can be executed by the user, e.g. {:query \"SELECT * FROM birds WHERE name = '<NAME>'\"} This is used to power features such as 'Convert this Question to SQL' in the Query Builder. Normally when executing the query we'd like to leave the statement as a prepared one and pass parameters that way instead of splicing them in as literals so as to avoid SQL injection vulnerabilities. Thus the results of this method are not normally executed by the Query Processor when processing an MBQL query. However when people convert a question to SQL they can see what they will be executing and edit the query as needed. Input to this function follows the same shape as output of `mbql->native` -- that is, it will be a so-called 'inner' native query, with `:query` and `:params` keys, as in the example code above; output should be of the same format. This method might be called even if no splicing needs to take place, e.g. if `:params` is empty; implementations should be sure to handle this situation correctly. For databases that do not feature concepts like 'prepared statements', this method need not be implemented; the default implementation is an identity function." {:arglists '([driver query]), :style/indent 1} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod splice-parameters-into-native-query ::driver [_ query] query) ;; TODO - we should just have some sort of `core.async` channel to handle DB update notifications instead (defmulti notify-database-updated "Notify the driver that the attributes of a `database` have changed, or that `database was deleted. This is specifically relevant in the event that the driver was doing some caching or connection pooling; the driver should release ALL related resources when this is called." {:arglists '([driver database])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod notify-database-updated ::driver [_ _] nil) ; no-op (defmulti sync-in-context "Drivers may provide this function if they need to do special setup before a sync operation such as `sync-database!`. The sync operation itself is encapsulated as the lambda `f`, which must be called with no arguments. (defn sync-in-context [driver database f] (with-connection [_ database] (f)))" {:arglists '([driver database f]), :style/indent 2} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod sync-in-context ::driver [_ _ f] (f)) (defmulti table-rows-seq "Return a sequence of *all* the rows in a given `table`, which is guaranteed to have at least `:name` and `:schema` keys. (It is guaranteed to satisfy the `DatabaseMetadataTable` schema in `metabase.sync.interface`.) Currently, this is only used for iterating over the values in a `_metabase_metadata` table. As such, the results are not expected to be returned lazily. There is no expectation that the results be returned in any given order. This method is currently only used by the H2 driver to load the Sample Dataset, so it is not neccesary for any other drivers to implement it at this time." {:arglists '([driver database table])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmulti db-default-timezone "Return the *system* timezone ID name of this database, i.e. the timezone that local dates/times/datetimes are considered to be in by default. Ideally, this method should return a timezone ID like `America/Los_Angeles`, but an offset formatted like `-08:00` is acceptable in cases where the actual ID cannot be provided." {:added "0.34.0", :arglists '(^java.lang.String [driver database])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod db-default-timezone ::driver [_ _] nil) ;; TIMEZONE FIXME — remove this method entirely (defmulti current-db-time "Return the current time and timezone from the perspective of `database`. You can use `metabase.driver.common/current-db-time` to implement this. This should return a Joda-Time `DateTime`. deprecated — the only thing this method is ultimately used for is to determine the db's system timezone. `db-default-timezone` has been introduced as an intended replacement for this method; implement it instead. this method will be removed in a future release." {:deprecated "0.34.0", :arglists '(^org.joda.time.DateTime [driver database])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod current-db-time ::driver [_ _] nil) (defmulti substitute-native-parameters "For drivers that support `:native-parameters`. Substitute parameters in a normalized 'inner' native query. {:query \"SELECT count(*) FROM table WHERE id = {{param}}\" :template-tags {:param {:name \"param\", :display-name \"Param\", :type :number}} :parameters [{:type :number :target [:variable [:template-tag \"param\"]] :value 2}]} -> {:query \"SELECT count(*) FROM table WHERE id = 2\"} Much of the implementation for this method is shared across drivers and lives in the `metabase.driver.common.parameters.*` namespaces. See the `:sql` and `:mongo` drivers for sample implementations of this method.`Driver-agnostic end-to-end native parameter tests live in `metabase.query-processor-test.parameters-test` and other namespaces." {:arglists '([driver inner-query])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmulti default-field-order "Return how fields should be sorted by default for this database." {:added "0.36.0" :arglists '([driver])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod default-field-order ::driver [_] :database) (defmulti db-start-of-week "Return start of week for given database" {:added "0.37.0" :arglists '([driver])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmulti incorporate-ssh-tunnel-details "A multimethod for driver-specific behavior required to incorporate details for an opened SSH tunnel into the DB details. In most cases, this will simply involve updating the :host and :port (to point to the tunnel entry point, instead of the backing database server), but some drivers may have more specific behavior." {:added "0.39.0" :arglists '([driver db-details])} dispatch-on-uninitialized-driver :hierarchy #'hierarchy) (defmulti normalize-db-details "Normalizes db-details for the given driver. This is to handle migrations that are too difficult to perform via regular Liquibase queries. This multimethod will be called from a `:post-select` handler within the database model. The full `database` model object is passed as the 2nd parameter, and the multimethod implementation is expected to update the value for `:details`. The default implementation is essentially `identity` (i.e returns `database` unchanged). This multimethod will only be called if `:details` is actually present in the `database` map." {:added "0.41.0" :arglists '([driver database])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod normalize-db-details ::driver [_ db-details] ;; no normalization by default db-details) (defmulti superseded-by "Returns the driver that supersedes the given `driver`. A non-nil return value means that the given `driver` is deprecated in Metabase and will eventually be replaced by the returned driver, in some future version (at which point any databases using it will be migrated to the new one). This is currently only used on the frontend for the purpose of showing/hiding deprecated drivers. A driver can make use of this facility by adding a top-level `superseded-by` key to its plugin manifest YAML file, or (less preferred) overriding this multimethod directly." {:added "0.41.0" :arglists '([driver])} dispatch-on-uninitialized-driver :hierarchy #'hierarchy) (defmethod superseded-by :default [_] nil)
true
(ns metabase.driver "Metabase Drivers handle various things we need to do with connected data warehouse databases, including things like introspecting their schemas and processing and running MBQL queries. Drivers must implement some or all of the multimethods defined below, and register themselves with a call to [[metabase.driver/register!]]. SQL-based drivers can use the `:sql` driver as a parent, and JDBC-based SQL drivers can use `:sql-jdbc`. Both of these drivers define additional multimethods that child drivers should implement; see [[metabase.driver.sql]] and [[metabase.driver.sql-jdbc]] for more details." (:require [clojure.string :as str] [clojure.tools.logging :as log] [metabase.driver.impl :as impl] [metabase.models.setting :as setting :refer [defsetting]] [metabase.plugins.classloader :as classloader] [metabase.util.i18n :refer [deferred-tru trs tru]] [metabase.util.schema :as su] [potemkin :as p] [schema.core :as s] [toucan.db :as db]) (:import org.joda.time.DateTime)) (declare notify-database-updated) (defn- notify-all-databases-updated "Send notification that all Databases should immediately release cached resources (i.e., connection pools). Currently only used below by [[report-timezone]] setter (i.e., only used when report timezone changes). Reusing pooled connections with the old session timezone can have weird effects, especially if report timezone is changed to `nil` (meaning subsequent queries will not attempt to change the session timezone) or something considered invalid by a given Database (meaning subsequent queries will fail to change the session timezone)." [] (doseq [{driver :engine, id :id, :as database} (db/select 'Database)] (try (notify-database-updated driver database) (catch Throwable e (log/error e (trs "Failed to notify {0} Database {1} updated" driver id)))))) (defsetting report-timezone (deferred-tru "Connection timezone to use when executing queries. Defaults to system timezone.") :setter (fn [new-value] (setting/set-string! :report-timezone new-value) (notify-all-databases-updated))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | Current Driver | ;;; +----------------------------------------------------------------------------------------------------------------+ (def ^:dynamic *driver* "Current driver (a keyword such as `:postgres`) in use by the Query Processor/tests/etc. Bind this with `with-driver` below. The QP binds the driver this way in the `bind-driver` middleware." nil) (declare the-driver) (defn do-with-driver "Impl for `with-driver`." [driver f] (binding [*driver* (the-driver driver)] (f))) (defmacro with-driver "Bind current driver to `driver` and execute `body`. (driver/with-driver :postgres ...)" {:style/indent 1} [driver & body] `(do-with-driver ~driver (fn [] ~@body))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | Driver Registration / Hierarchy / Multimethod Dispatch | ;;; +----------------------------------------------------------------------------------------------------------------+ (p/import-vars [impl hierarchy register! initialized?]) (add-watch #'hierarchy nil (fn [_ _ _ _] (when (not= hierarchy impl/hierarchy) ;; this is a dev-facing error so no need to i18n it. (throw (Exception. (str "Don't alter #'metabase.driver/hierarchy directly, since it is imported from " "metabase.driver.impl. Alter #'metabase.driver.impl/hierarchy instead if you need to " "alter the var directly.")))))) (defn available? "Is this driver available for use? (i.e. should we show it as an option when adding a new database?) This is `true` for all registered, non-abstract drivers and false everything else. Note that an available driver is not necessarily initialized yet; for example lazy-loaded drivers are *registered* when Metabase starts up (meaning this will return `true` for them) and only initialized when first needed." [driver] ((every-pred impl/registered? impl/concrete?) driver)) (defn the-driver "Like [[clojure.core/the-ns]]. Converts argument to a keyword, then loads and registers the driver if not already done, throwing an Exception if it fails or is invalid. Returns keyword. Note that this does not neccessarily mean the driver is initialized (e.g., its full implementation and deps might not be loaded into memory) -- see also [[the-initialized-driver]]. This is useful in several cases: ;; Ensuring a driver is loaded & registered (isa? driver/hierarchy (the-driver :postgres) (the-driver :sql-jdbc) ;; Accepting either strings or keywords (e.g., in API endpoints) (the-driver \"h2\") ; -> :h2 ;; Ensuring a driver you are passed is valid (db/insert! Database :engine (name (the-driver driver))) (the-driver :postgres) ; -> :postgres (the-driver :baby) ; -> Exception" [driver] {:pre [((some-fn keyword? string?) driver)]} (classloader/the-classloader) (let [driver (keyword driver)] (impl/load-driver-namespace-if-needed! driver) driver)) (defn add-parent! "Add a new parent to `driver`." [driver new-parent] (when-not *compile-files* (impl/load-driver-namespace-if-needed! driver) (impl/load-driver-namespace-if-needed! new-parent) (alter-var-root #'impl/hierarchy derive driver new-parent))) (defn- dispatch-on-uninitialized-driver "Dispatch function to use for driver multimethods. Dispatches on first arg, a driver keyword; loads that driver's namespace if not already done. DOES NOT INITIALIZE THE DRIVER. Driver multimethods for abstract drivers like `:sql` or `:sql-jdbc` should use [[dispatch-on-initialized-driver]] to ensure the driver is initialized (i.e., its method implementations will be loaded)." [driver & _] (the-driver driver)) (declare initialize!) (defn the-initialized-driver "Like [[the-driver]], but also initializes the driver if not already initialized." [driver] (let [driver (the-driver driver)] (impl/initialize-if-needed! driver initialize!) driver)) (defn dispatch-on-initialized-driver "Like [[dispatch-on-uninitialized-driver]], but guarantees a driver is initialized before dispatch. Prefer [[the-driver]] for trivial methods that should do not require the driver to be initialized (e.g., ones that simply return information about the driver, but do not actually connect to any databases.)" [driver & _] (the-initialized-driver driver)) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | Interface (Multimethod Defintions) | ;;; +----------------------------------------------------------------------------------------------------------------+ ;; Methods a driver can implement. Not all of these are required; some have default implementations immediately below ;; them. ;; ;; SOME TIPS: ;; ;; To call the Clojure equivalent of the superclass implementation of a method, use `get-method` with the parent driver: ;; ;; (driver/register-driver! :my-driver, :parent :sql-jdbc) ;; ;; (defmethod driver/describe-table :my-driver [driver database table] ;; (-> ((get-method driver/describe-table :sql-jdbc) driver databse table) ;; (update :tables add-materialized-views))) ;; ;; Make sure to pass along the `driver` parameter-as when you call other methods, rather than hardcoding the name of ;; the current driver (e.g. `:my-driver` in the example above). This way if other drivers use your driver as a parent ;; in the future their implementations of any methods called by those methods will get used. (defmulti initialize! "DO NOT CALL THIS METHOD DIRECTLY. Called automatically once and only once the first time a non-trivial driver method is called; implementers should do one-time initialization as needed (for example, registering JDBC drivers used internally by the driver.) 'Trivial' methods include a tiny handful of ones like [[connection-properties]] that simply provide information about the driver, but do not connect to databases; these can be be supplied, for example, by a Metabase plugin manifest file (which is supplied for lazy-loaded drivers). Methods that require connecting to a database dispatch off of [[the-initialized-driver]], which will initialize a driver if not already done so. You will rarely need to write an implentation for this method yourself. A lazy-loaded driver (like most of the Metabase drivers in v1.0 and above) are automatiaclly given an implentation of this method that performs the `init-steps` specified in the plugin manifest (such as loading namespaces in question). If you do need to implement this method yourself, you do not need to call parent implementations. We'll take care of that for you." {:arglists '([driver])} dispatch-on-uninitialized-driver) ;; VERY IMPORTANT: Unlike all other driver multimethods, we DO NOT use the driver hierarchy for dispatch here. Why? ;; We do not want a driver to inherit parent drivers' implementations and have those implementations end up getting ;; called multiple times. If a driver does not implement `initialize!`, *always* fall back to the default no-op ;; implementation. ;; ;; `initialize-if-needed!` takes care to make sure a driver's parent(s) are initialized before initializing a driver. (defmethod initialize! :default [_]) ; no-op (defmulti display-name "A nice name for the driver that we'll display to in the admin panel, e.g. \"PostgreSQL\" for `:postgres`. Default implementation capitializes the name of the driver, e.g. `:presto` becomes \"Presto\". When writing a driver that you plan to ship as a separate, lazy-loading plugin (including core drivers packaged this way, like SQLite), you do not need to implement this method; instead, specifiy it in your plugin manifest, and `lazy-loaded-driver` will create an implementation for you. Probably best if we only have one place where we set values for this." {:arglists '([driver])} dispatch-on-uninitialized-driver :hierarchy #'hierarchy) (defmethod display-name :default [driver] (str/capitalize (name driver))) (defmulti can-connect? "Check whether we can connect to a `Database` with `details-map` and perform a simple query. For example, a SQL database might try running a query like `SELECT 1;`. This function should return truthy if a connection to the DB can be made successfully, otherwise it should return falsey or throw an appropriate Exception. Exceptions if a connection cannot be made." {:arglists '([driver details])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmulti describe-database "Return a map containing information that describes all of the tables in a `database`, an instance of the `Database` model. It is expected that this function will be peformant and avoid draining meaningful resources of the database. Results should match the [[metabase.sync.interface/DatabaseMetadata]] schema." {:arglists '([driver database])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmulti describe-table "Return a map containing information that describes the physical schema of `table` (i.e. the fields contained therein). `database` will be an instance of the `Database` model; and `table`, an instance of the `Table` model. It is expected that this function will be peformant and avoid draining meaningful resources of the database. Results should match the [[metabase.sync.interface/TableMetadata]] schema." {:arglists '([driver database table])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmulti escape-entity-name-for-metadata "escaping for when calling `.getColumns` or `.getTables` on table names or schema names. Useful for when a database driver has difference escaping rules for table or schema names when used from metadata. For example, oracle treats slashes differently when querying versus when used with `.getTables` or `.getColumns`" {:arglists '([driver table-name])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod escape-entity-name-for-metadata :default [_driver table-name] table-name) (defmulti describe-table-fks "Return information about the foreign keys in a `table`. Required for drivers that support `:foreign-keys`. Results should match the [[metabase.sync.interface/FKMetadata]] schema." {:arglists '([this database table])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod describe-table-fks ::driver [_ _ _] nil) (def ConnectionDetailsProperty "Schema for a map containing information about a connection property we should ask the user to supply when setting up a new database, as returned by an implementation of `connection-properties`." (s/constrained { ;; The key that should be used to store this property in the `details` map. :name su/NonBlankString ;; Human-readable name that should be displayed to the User in UI for editing this field. :display-name su/NonBlankString ;; Type of this property. Defaults to `:string` if unspecified. ;; `:select` is a `String` in the backend. (s/optional-key :type) (s/enum :string :integer :boolean :password :select :text) ;; A default value for this field if the user hasn't set an explicit value. This is shown in the UI as a ;; placeholder. (s/optional-key :default) s/Any ;; Placeholder value to show in the UI if user hasn't set an explicit value. Similar to `:default`, but this value ;; is *not* saved to `:details` if no explicit value is set. Since `:default` values are also shown as ;; placeholders, you cannot specify both `:default` and `:placeholder`. (s/optional-key :placeholder) s/Any ;; Is this property required? Defaults to `false`. (s/optional-key :required?) s/Bool ;; Any options for `:select` types (s/optional-key :options) {s/Keyword s/Str}} (complement (every-pred #(contains? % :default) #(contains? % :placeholder))) "connection details that does not have both default and placeholder")) (defmulti connection-properties "Return information about the connection properties that should be exposed to the user for databases that will use this driver. This information is used to build the UI for editing a Database `details` map, and for validating it on the backend. It should include things like `host`, `port`, and other driver-specific parameters. Each property must conform to the [[ConnectionDetailsProperty]] schema above. There are several definitions for common properties available in the [[metabase.driver.common]] namespace, such as `default-host-details` and `default-port-details`. Prefer using these if possible. Like `display-name`, lazy-loaded drivers should specify this in their plugin manifest; `lazy-loaded-driver` will automatically create an implementation for you." {:arglists '([driver])} dispatch-on-uninitialized-driver :hierarchy #'hierarchy) (defmulti execute-reducible-query "Execute a native query against that database and return rows that can be reduced using `transduce`/`reduce`. Pass metadata about the columns and the reducible object to `respond`, which has the signature (respond results-metadata rows) You can use [[metabase.query-processor.reducible/reducible-rows]] to create reducible, streaming results. Example impl: (defmethod reducible-query :my-driver [_ query context respond] (with-open [results (run-query! query)] (respond {:cols [{:name \"my_col\"}]} (qp.reducible/reducible-rows (get-row results) (context/canceled-chan context)))))" {:added "0.35.0", :arglists '([driver query context respond])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (def driver-features "Set of all features a driver can support." #{ ;; Does this database support foreign key relationships? :foreign-keys ;; Does this database support nested fields (e.g. Mongo)? :nested-fields ;; Does this driver support setting a timezone for the query? :set-timezone ;; Does the driver support *basic* aggregations like `:count` and `:sum`? (Currently, everything besides standard ;; deviation is considered \"basic\"; only GA doesn't support this). ;; ;; DEFAULTS TO TRUE. :basic-aggregations ;; Does this driver support standard deviation and variance aggregations? :standard-deviation-aggregations ;; Does this driver support expressions (e.g. adding the values of 2 columns together)? :expressions ;; Does this driver support parameter substitution in native queries, where parameter expressions are replaced ;; with a single value? e.g. ;; ;; SELECT * FROM table WHERE field = {{param}} ;; -> ;; SELECT * FROM table WHERE field = 1 :native-parameters ;; Does the driver support using expressions inside aggregations? e.g. something like \"sum(x) + count(y)\" or ;; \"avg(x + y)\" :expression-aggregations ;; Does the driver support using a query as the `:source-query` of another MBQL query? Examples are CTEs or ;; subselects in SQL queries. :nested-queries ;; Does the driver support binning as specified by the `binning-strategy` clause? :binning ;; Does this driver not let you specify whether or not our string search filter clauses (`:contains`, ;; `:starts-with`, and `:ends-with`, collectively the equivalent of SQL `LIKE`) are case-senstive or not? This ;; informs whether we should present you with the 'Case Sensitive' checkbox in the UI. At the time of this writing ;; SQLite, SQLServer, and MySQL do not support this -- `LIKE` clauses are always case-insensitive. ;; ;; DEFAULTS TO TRUE. :case-sensitivity-string-filter-options :left-join :right-join :inner-join :full-join :regex ;; Does the driver support advanced math expressions such as log, power, ... :advanced-math-expressions ;; Does the driver support percentile calculations (including median) :percentile-aggregations}) (defmulti ^:deprecated supports? "Does this driver support a certain `feature`? (A feature is a keyword, and can be any of the ones listed above in [[driver-features]].) (supports? :postgres :set-timezone) ; -> true deprecated — [[database-supports?]] is intended to replace this method. However, it driver authors should continue _implementing_ `supports?` for the time being until we get a chance to migrate all our usages." {:arglists '([driver feature])} (fn [driver feature] (when-not (driver-features feature) (throw (Exception. (tru "Invalid driver feature: {0}" feature)))) [(dispatch-on-initialized-driver driver) feature]) :hierarchy #'hierarchy) (defmethod supports? :default [_ _] false) (defmethod supports? [::driver :basic-aggregations] [_ _] true) (defmethod supports? [::driver :case-sensitivity-string-filter-options] [_ _] true) (defmulti database-supports? "Does this driver and specific instance of a database support a certain `feature`? (A feature is a keyword, and can be any of the ones listed above in `driver-features`. Note that it's the same set of `driver-features` with respect to both database-supports? and [[supports?]]) Database is guaranteed to be a Database instance. Most drivers can always return true or always return false for a given feature (e.g., :left-join is not supported by any version of Mongo DB). In some cases, a feature may only be supported by certain versions of the database engine. In this case, after implementing `:version` in `describe-database` for the driver, you can check in `(get-in db [:details :version])` and determine whether a feature is supported for this particular database. (database-supports? :mongo :set-timezone mongo-db) ; -> true" {:arglists '([driver feature database])} (fn [driver feature database] (when-not (driver-features feature) (throw (Exception. (tru "Invalid driver feature: {0}" feature)))) [(dispatch-on-initialized-driver driver) feature]) :hierarchy #'hierarchy) (defmethod database-supports? :default [driver feature _] (supports? driver feature)) (defmulti ^:deprecated format-custom-field-name "Prior to Metabase 0.33.0, you could specifiy custom names for aggregations in MBQL by wrapping the clause in a `:named` clause: [:named [:count] \"My Count\"] This name was used for both the `:display_name` in the query results, and for the `:name` used as an alias in the query (e.g. the right-hand side of a SQL `AS` expression). Because some custom display names weren't allowed by some drivers, or would be transformed in some way (for example, Redshift always lowercases custom aliases), this method was needed so we could match the name we had given the column with the one in the query results. In 0.33.0, we started using `:named` internally to alias aggregations in middleware in *all* queries to prevent issues with referring to multiple aggregations of the same type when that query was used as a source query. See [#9767](https://github.com/metabase/metabase/issues/9767) for more details. After this change, it became desirable to differentiate between such internally-generated aliases and display names, which need not be used in the query at all; thus in MBQL 1.3.0 [`:named` was replaced by the more general `:aggregation-options`](https://github.com/metabase/mbql/pull/7). Because user-generated names are no longer used as aliases in native queries themselves, this method is no longer needed and will be removed in a future release." {:arglists '([driver custom-field-name])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod format-custom-field-name ::driver [_ custom-field-name] custom-field-name) (defmulti humanize-connection-error-message "Return a humanized (user-facing) version of an connection error message. Generic error messages are provided in `metabase.driver.common/connection-error-messages`; return one of these whenever possible. Error messages can be strings, or localized strings, as returned by `metabase.util.i18n/trs` and `metabase.util.i18n/tru`." {:arglists '([this message])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod humanize-connection-error-message ::driver [_ message] message) (defmulti mbql->native "Transpile an MBQL query into the appropriate native query form. `query` will match the schema for an MBQL query in `metabase.mbql.schema/Query`; this function should return a native query that conforms to that schema. If the underlying query language supports remarks or comments, the driver should use `query->remark` to generate an appropriate message and include that in an appropriate place; alternatively a driver might directly include the query's `:info` dictionary if the underlying language is JSON-based. The result of this function will be passed directly into calls to `execute-reducible-query`. For example, a driver like Postgres would build a valid SQL expression and return a map such as: {:query \"-- Metabase card: 10 user: 5 SELECT * FROM my_table\"}" {:arglists '([driver query]), :style/indent 1} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmulti splice-parameters-into-native-query "For a native query that has separate parameters, such as a JDBC prepared statement, e.g. {:query \"SELECT * FROM birds WHERE name = ?\", :params [\"Reggae\"]} splice the parameters in to the native query as literals so it can be executed by the user, e.g. {:query \"SELECT * FROM birds WHERE name = 'PI:NAME:<NAME>END_PI'\"} This is used to power features such as 'Convert this Question to SQL' in the Query Builder. Normally when executing the query we'd like to leave the statement as a prepared one and pass parameters that way instead of splicing them in as literals so as to avoid SQL injection vulnerabilities. Thus the results of this method are not normally executed by the Query Processor when processing an MBQL query. However when people convert a question to SQL they can see what they will be executing and edit the query as needed. Input to this function follows the same shape as output of `mbql->native` -- that is, it will be a so-called 'inner' native query, with `:query` and `:params` keys, as in the example code above; output should be of the same format. This method might be called even if no splicing needs to take place, e.g. if `:params` is empty; implementations should be sure to handle this situation correctly. For databases that do not feature concepts like 'prepared statements', this method need not be implemented; the default implementation is an identity function." {:arglists '([driver query]), :style/indent 1} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod splice-parameters-into-native-query ::driver [_ query] query) ;; TODO - we should just have some sort of `core.async` channel to handle DB update notifications instead (defmulti notify-database-updated "Notify the driver that the attributes of a `database` have changed, or that `database was deleted. This is specifically relevant in the event that the driver was doing some caching or connection pooling; the driver should release ALL related resources when this is called." {:arglists '([driver database])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod notify-database-updated ::driver [_ _] nil) ; no-op (defmulti sync-in-context "Drivers may provide this function if they need to do special setup before a sync operation such as `sync-database!`. The sync operation itself is encapsulated as the lambda `f`, which must be called with no arguments. (defn sync-in-context [driver database f] (with-connection [_ database] (f)))" {:arglists '([driver database f]), :style/indent 2} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod sync-in-context ::driver [_ _ f] (f)) (defmulti table-rows-seq "Return a sequence of *all* the rows in a given `table`, which is guaranteed to have at least `:name` and `:schema` keys. (It is guaranteed to satisfy the `DatabaseMetadataTable` schema in `metabase.sync.interface`.) Currently, this is only used for iterating over the values in a `_metabase_metadata` table. As such, the results are not expected to be returned lazily. There is no expectation that the results be returned in any given order. This method is currently only used by the H2 driver to load the Sample Dataset, so it is not neccesary for any other drivers to implement it at this time." {:arglists '([driver database table])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmulti db-default-timezone "Return the *system* timezone ID name of this database, i.e. the timezone that local dates/times/datetimes are considered to be in by default. Ideally, this method should return a timezone ID like `America/Los_Angeles`, but an offset formatted like `-08:00` is acceptable in cases where the actual ID cannot be provided." {:added "0.34.0", :arglists '(^java.lang.String [driver database])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod db-default-timezone ::driver [_ _] nil) ;; TIMEZONE FIXME — remove this method entirely (defmulti current-db-time "Return the current time and timezone from the perspective of `database`. You can use `metabase.driver.common/current-db-time` to implement this. This should return a Joda-Time `DateTime`. deprecated — the only thing this method is ultimately used for is to determine the db's system timezone. `db-default-timezone` has been introduced as an intended replacement for this method; implement it instead. this method will be removed in a future release." {:deprecated "0.34.0", :arglists '(^org.joda.time.DateTime [driver database])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod current-db-time ::driver [_ _] nil) (defmulti substitute-native-parameters "For drivers that support `:native-parameters`. Substitute parameters in a normalized 'inner' native query. {:query \"SELECT count(*) FROM table WHERE id = {{param}}\" :template-tags {:param {:name \"param\", :display-name \"Param\", :type :number}} :parameters [{:type :number :target [:variable [:template-tag \"param\"]] :value 2}]} -> {:query \"SELECT count(*) FROM table WHERE id = 2\"} Much of the implementation for this method is shared across drivers and lives in the `metabase.driver.common.parameters.*` namespaces. See the `:sql` and `:mongo` drivers for sample implementations of this method.`Driver-agnostic end-to-end native parameter tests live in `metabase.query-processor-test.parameters-test` and other namespaces." {:arglists '([driver inner-query])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmulti default-field-order "Return how fields should be sorted by default for this database." {:added "0.36.0" :arglists '([driver])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod default-field-order ::driver [_] :database) (defmulti db-start-of-week "Return start of week for given database" {:added "0.37.0" :arglists '([driver])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmulti incorporate-ssh-tunnel-details "A multimethod for driver-specific behavior required to incorporate details for an opened SSH tunnel into the DB details. In most cases, this will simply involve updating the :host and :port (to point to the tunnel entry point, instead of the backing database server), but some drivers may have more specific behavior." {:added "0.39.0" :arglists '([driver db-details])} dispatch-on-uninitialized-driver :hierarchy #'hierarchy) (defmulti normalize-db-details "Normalizes db-details for the given driver. This is to handle migrations that are too difficult to perform via regular Liquibase queries. This multimethod will be called from a `:post-select` handler within the database model. The full `database` model object is passed as the 2nd parameter, and the multimethod implementation is expected to update the value for `:details`. The default implementation is essentially `identity` (i.e returns `database` unchanged). This multimethod will only be called if `:details` is actually present in the `database` map." {:added "0.41.0" :arglists '([driver database])} dispatch-on-initialized-driver :hierarchy #'hierarchy) (defmethod normalize-db-details ::driver [_ db-details] ;; no normalization by default db-details) (defmulti superseded-by "Returns the driver that supersedes the given `driver`. A non-nil return value means that the given `driver` is deprecated in Metabase and will eventually be replaced by the returned driver, in some future version (at which point any databases using it will be migrated to the new one). This is currently only used on the frontend for the purpose of showing/hiding deprecated drivers. A driver can make use of this facility by adding a top-level `superseded-by` key to its plugin manifest YAML file, or (less preferred) overriding this multimethod directly." {:added "0.41.0" :arglists '([driver])} dispatch-on-uninitialized-driver :hierarchy #'hierarchy) (defmethod superseded-by :default [_] nil)
[ { "context": " [id (assoc settings :username username :password password)]\n [id settings])))\n\n(defn add-auth-interact", "end": 1147, "score": 0.7903245687484741, "start": 1139, "tag": "PASSWORD", "value": "password" } ]
leiningen/deploy.clj
prapisarda/Scripts
0
(ns leiningen.deploy "Build and deploy jar to remote repository." (:require [cemerick.pomegranate.aether :as aether] [leiningen.core.classpath :as classpath] [leiningen.core.main :as main] [leiningen.core.eval :as eval] [leiningen.core.user :as user] [leiningen.core.utils :as utils] [clojure.java.io :as io] [leiningen.pom :as pom] [leiningen.jar :as jar] [clojure.java.shell :as sh] [clojure.string :as string])) (defn- abort-message [message] (cond (re-find #"Return code is 405" message) (str message "\n" "Ensure you are deploying over SSL.") (re-find #"Return code is 401" message) (str message "\n" "See `lein help deploying` for an explanation of how" " to specify credentials.") :else message)) (defn add-auth-from-url [[id settings]] (let [url (utils/build-url id) user-info (and url (.getUserInfo url)) [username password] (and user-info (.split user-info ":"))] (if username [id (assoc settings :username username :password password)] [id settings]))) (defn add-auth-interactively [[id settings]] (if (or (and (:username settings) (some settings [:password :passphrase :private-key-file])) (:no-auth settings) (re-find #"(file|scp|scpexe)://" (:url settings))) [id settings] (do (when @utils/rebound-io? (main/abort "No credentials found for" id "(did you mean `lein deploy" "clojars`?)\nPassword prompts are not supported when ran" "after other (potentially)\ninteractive tasks.\nSee `lein" "help deploy` for an explanation of how to specify" "credentials.")) (print "No credentials found for" id) (when (not= "clojars" id) (print "(did you mean `lein deploy clojars`?)")) (println "\nSee `lein help deploying` for how to configure credentials" "to avoid prompts.") (print "Username: ") (flush) (let [username (read-line) console (System/console) password (if console (.readPassword console "%s" (into-array ["Password: "])) (do (println "LEIN IS UNABLE TO TURN OFF ECHOING, SO" "THE PASSWORD IS PRINTED TO THE CONSOLE") (print "Password: ") (flush) (read-line)))] [id (assoc settings :username username :password password)])))) ;; repo names must not contain path delimiters because they're used by ;; aether for form filenames (defn- sanitize-repo-name [name] (last (.split name "/"))) (defn repo-for [project name] (let [settings (merge (get (into {} (:repositories project)) name) (get (into {} (:deploy-repositories project)) name))] (-> [(sanitize-repo-name name) (or settings {:url name})] (classpath/add-repo-auth) (add-auth-from-url) (add-auth-interactively)))) (defn signing-args "Produce GPG arguments for signing a file." [file opts] (let [key-spec (if-let [key (:gpg-key opts)] ["--default-key" key])] `["--yes" "-ab" ~@key-spec "--" ~file])) (defn sign "Create a detached signature and return the signature file name." [file opts] (let [{:keys [err exit]} (apply user/gpg (signing-args file opts))] (when-not (zero? exit) (main/abort "Could not sign" (str file "\n" err (if err "\n") "\nSee `lein help gpg` for how to set up gpg.\n" "If you don't expect people to need to verify the " "authorship of your jar, you\ncan add `:sign-releases " "false` to the relevant `:deploy-repositories` entry."))) (str file ".asc"))) (defn signature-for-artifact [[coords artifact-file] opts] {(apply concat (update-in (apply hash-map coords) [:extension] #(str (or % "jar") ".asc"))) (sign artifact-file opts)}) (defn signatures-for-artifacts "Creates and returns the list of signatures for the artifacts needed to be signed." [artifacts sig-opts] (let [total (count artifacts)] (println "Need to sign" total "files with GPG") (doall (map-indexed (fn [idx [coords artifact-file :as artifact]] (printf "[%d/%d] Signing %s with GPG\n" (inc idx) total artifact-file) (flush) (signature-for-artifact artifact sig-opts)) artifacts)))) (defn sign-for-repo? "Generally sign artifacts for this repo?" [repo] (:sign-releases (second repo) true)) (defn signing-opts "Extract signing options map from a project." [project repo] (merge (:signing project) (:signing (second repo)))) (defn files-for [project repo] (let [signed? (sign-for-repo? repo) ;; If pom is put in "target/", :auto-clean true will remove it if the ;; jar is created afterwards. So make jar first, then pom. artifacts (merge (jar/jar project) {[:extension "pom"] (pom/pom project)}) sig-opts (signing-opts project repo)] (if (and signed? (not (.endsWith (:version project) "-SNAPSHOT"))) (reduce merge artifacts (signatures-for-artifacts artifacts sig-opts)) artifacts))) (defn warn-missing-metadata [project] (doseq [key [:description :license :url]] (when (or (nil? (project key)) (re-find #"FIXME" (str (project key)))) (main/warn "WARNING: please set" key "in project.clj.")))) (defn- in-branches [branches] (-> (sh/sh "git" "rev-parse" "--abbrev-ref" "HEAD") :out butlast string/join branches not)) (defn- extension [f] (if-let [[_ signed-extension] (re-find #"\.([a-z]+\.asc)$" f)] signed-extension (if (= "pom.xml" (.getName (io/file f))) "pom" (last (.split f "\\."))))) (defn classifier "The classifier is be located between the version and extension name of the artifact. See http://maven.apache.org/plugins/maven-deploy-plugin/examples/deploying-with-classifiers.html " [version f] (let [pattern (re-pattern (format "%s-(.*)\\.%s" version (extension f))) [_ classifier-of] (re-find pattern f)] (when-not (empty? classifier-of) classifier-of))) (defn- fail-on-empty-project [project] (when-not (:root project) (main/abort "Couldn't find project.clj, which is needed for deploy task"))) (defn ^:no-project-needed deploy "Deploy jar and pom to remote repository. The target repository will be looked up in :repositories in project.clj: :repositories [[\"snapshots\" \"https://internal.repo/snapshots\"] [\"releases\" \"https://internal.repo/releases\"] [\"alternate\" \"https://other.server/repo\"]] If you don't provide a repository name to deploy to, either \"snapshots\" or \"releases\" will be used depending on your project's current version. You may provide a repository URL instead of a name. See `lein help deploying` under \"Authentication\" for instructions on how to configure your credentials so you are not prompted on each deploy. You can also deploy arbitrary artifacts from disk: $ lein deploy myrepo com.blueant/fancypants 1.0.1 fancypants.jar pom.xml While this works with any arbitrary files on disk, downstream projects will not be able to depend on jars that are deployed without a pom." ([project] (deploy project (if (pom/snapshot? project) "snapshots" "releases"))) ([project repository] (fail-on-empty-project project) (let [branches (set (:deploy-branches project))] (when (and (seq branches) (in-branches branches)) (apply main/abort "Can only deploy from branches listed in" ":deploy-branches:" branches))) (warn-missing-metadata project) (let [repo (repo-for project repository) files (files-for project repo)] (try (java.lang.System/setProperty "aether.checksums.forSignature" "true") (main/debug "Deploying" files "to" repo) (aether/deploy :coordinates [(symbol (:group project) (:name project)) (:version project)] :artifact-map files :transfer-listener :stdout :repository [repo]) (catch org.eclipse.aether.deployment.DeploymentException e (when main/*debug* (.printStackTrace e)) (main/abort (abort-message (.getMessage e))))))) ([project repository identifier version & files] (let [identifier (symbol identifier) artifact-id (name identifier) group-id (namespace identifier) repo (repo-for project repository) artifacts (for [f files] [[:extension (extension f) :classifier (classifier version f)] f])] (java.lang.System/setProperty "aether.checksums.forSignature" "true") (main/debug "Deploying" files "to" repo) (aether/deploy :coordinates [(symbol group-id artifact-id) version] :artifact-map (into {} artifacts) :transfer-listener :stdout :repository [repo] :local-repo (:local-repo project)))))
91007
(ns leiningen.deploy "Build and deploy jar to remote repository." (:require [cemerick.pomegranate.aether :as aether] [leiningen.core.classpath :as classpath] [leiningen.core.main :as main] [leiningen.core.eval :as eval] [leiningen.core.user :as user] [leiningen.core.utils :as utils] [clojure.java.io :as io] [leiningen.pom :as pom] [leiningen.jar :as jar] [clojure.java.shell :as sh] [clojure.string :as string])) (defn- abort-message [message] (cond (re-find #"Return code is 405" message) (str message "\n" "Ensure you are deploying over SSL.") (re-find #"Return code is 401" message) (str message "\n" "See `lein help deploying` for an explanation of how" " to specify credentials.") :else message)) (defn add-auth-from-url [[id settings]] (let [url (utils/build-url id) user-info (and url (.getUserInfo url)) [username password] (and user-info (.split user-info ":"))] (if username [id (assoc settings :username username :password <PASSWORD>)] [id settings]))) (defn add-auth-interactively [[id settings]] (if (or (and (:username settings) (some settings [:password :passphrase :private-key-file])) (:no-auth settings) (re-find #"(file|scp|scpexe)://" (:url settings))) [id settings] (do (when @utils/rebound-io? (main/abort "No credentials found for" id "(did you mean `lein deploy" "clojars`?)\nPassword prompts are not supported when ran" "after other (potentially)\ninteractive tasks.\nSee `lein" "help deploy` for an explanation of how to specify" "credentials.")) (print "No credentials found for" id) (when (not= "clojars" id) (print "(did you mean `lein deploy clojars`?)")) (println "\nSee `lein help deploying` for how to configure credentials" "to avoid prompts.") (print "Username: ") (flush) (let [username (read-line) console (System/console) password (if console (.readPassword console "%s" (into-array ["Password: "])) (do (println "LEIN IS UNABLE TO TURN OFF ECHOING, SO" "THE PASSWORD IS PRINTED TO THE CONSOLE") (print "Password: ") (flush) (read-line)))] [id (assoc settings :username username :password password)])))) ;; repo names must not contain path delimiters because they're used by ;; aether for form filenames (defn- sanitize-repo-name [name] (last (.split name "/"))) (defn repo-for [project name] (let [settings (merge (get (into {} (:repositories project)) name) (get (into {} (:deploy-repositories project)) name))] (-> [(sanitize-repo-name name) (or settings {:url name})] (classpath/add-repo-auth) (add-auth-from-url) (add-auth-interactively)))) (defn signing-args "Produce GPG arguments for signing a file." [file opts] (let [key-spec (if-let [key (:gpg-key opts)] ["--default-key" key])] `["--yes" "-ab" ~@key-spec "--" ~file])) (defn sign "Create a detached signature and return the signature file name." [file opts] (let [{:keys [err exit]} (apply user/gpg (signing-args file opts))] (when-not (zero? exit) (main/abort "Could not sign" (str file "\n" err (if err "\n") "\nSee `lein help gpg` for how to set up gpg.\n" "If you don't expect people to need to verify the " "authorship of your jar, you\ncan add `:sign-releases " "false` to the relevant `:deploy-repositories` entry."))) (str file ".asc"))) (defn signature-for-artifact [[coords artifact-file] opts] {(apply concat (update-in (apply hash-map coords) [:extension] #(str (or % "jar") ".asc"))) (sign artifact-file opts)}) (defn signatures-for-artifacts "Creates and returns the list of signatures for the artifacts needed to be signed." [artifacts sig-opts] (let [total (count artifacts)] (println "Need to sign" total "files with GPG") (doall (map-indexed (fn [idx [coords artifact-file :as artifact]] (printf "[%d/%d] Signing %s with GPG\n" (inc idx) total artifact-file) (flush) (signature-for-artifact artifact sig-opts)) artifacts)))) (defn sign-for-repo? "Generally sign artifacts for this repo?" [repo] (:sign-releases (second repo) true)) (defn signing-opts "Extract signing options map from a project." [project repo] (merge (:signing project) (:signing (second repo)))) (defn files-for [project repo] (let [signed? (sign-for-repo? repo) ;; If pom is put in "target/", :auto-clean true will remove it if the ;; jar is created afterwards. So make jar first, then pom. artifacts (merge (jar/jar project) {[:extension "pom"] (pom/pom project)}) sig-opts (signing-opts project repo)] (if (and signed? (not (.endsWith (:version project) "-SNAPSHOT"))) (reduce merge artifacts (signatures-for-artifacts artifacts sig-opts)) artifacts))) (defn warn-missing-metadata [project] (doseq [key [:description :license :url]] (when (or (nil? (project key)) (re-find #"FIXME" (str (project key)))) (main/warn "WARNING: please set" key "in project.clj.")))) (defn- in-branches [branches] (-> (sh/sh "git" "rev-parse" "--abbrev-ref" "HEAD") :out butlast string/join branches not)) (defn- extension [f] (if-let [[_ signed-extension] (re-find #"\.([a-z]+\.asc)$" f)] signed-extension (if (= "pom.xml" (.getName (io/file f))) "pom" (last (.split f "\\."))))) (defn classifier "The classifier is be located between the version and extension name of the artifact. See http://maven.apache.org/plugins/maven-deploy-plugin/examples/deploying-with-classifiers.html " [version f] (let [pattern (re-pattern (format "%s-(.*)\\.%s" version (extension f))) [_ classifier-of] (re-find pattern f)] (when-not (empty? classifier-of) classifier-of))) (defn- fail-on-empty-project [project] (when-not (:root project) (main/abort "Couldn't find project.clj, which is needed for deploy task"))) (defn ^:no-project-needed deploy "Deploy jar and pom to remote repository. The target repository will be looked up in :repositories in project.clj: :repositories [[\"snapshots\" \"https://internal.repo/snapshots\"] [\"releases\" \"https://internal.repo/releases\"] [\"alternate\" \"https://other.server/repo\"]] If you don't provide a repository name to deploy to, either \"snapshots\" or \"releases\" will be used depending on your project's current version. You may provide a repository URL instead of a name. See `lein help deploying` under \"Authentication\" for instructions on how to configure your credentials so you are not prompted on each deploy. You can also deploy arbitrary artifacts from disk: $ lein deploy myrepo com.blueant/fancypants 1.0.1 fancypants.jar pom.xml While this works with any arbitrary files on disk, downstream projects will not be able to depend on jars that are deployed without a pom." ([project] (deploy project (if (pom/snapshot? project) "snapshots" "releases"))) ([project repository] (fail-on-empty-project project) (let [branches (set (:deploy-branches project))] (when (and (seq branches) (in-branches branches)) (apply main/abort "Can only deploy from branches listed in" ":deploy-branches:" branches))) (warn-missing-metadata project) (let [repo (repo-for project repository) files (files-for project repo)] (try (java.lang.System/setProperty "aether.checksums.forSignature" "true") (main/debug "Deploying" files "to" repo) (aether/deploy :coordinates [(symbol (:group project) (:name project)) (:version project)] :artifact-map files :transfer-listener :stdout :repository [repo]) (catch org.eclipse.aether.deployment.DeploymentException e (when main/*debug* (.printStackTrace e)) (main/abort (abort-message (.getMessage e))))))) ([project repository identifier version & files] (let [identifier (symbol identifier) artifact-id (name identifier) group-id (namespace identifier) repo (repo-for project repository) artifacts (for [f files] [[:extension (extension f) :classifier (classifier version f)] f])] (java.lang.System/setProperty "aether.checksums.forSignature" "true") (main/debug "Deploying" files "to" repo) (aether/deploy :coordinates [(symbol group-id artifact-id) version] :artifact-map (into {} artifacts) :transfer-listener :stdout :repository [repo] :local-repo (:local-repo project)))))
true
(ns leiningen.deploy "Build and deploy jar to remote repository." (:require [cemerick.pomegranate.aether :as aether] [leiningen.core.classpath :as classpath] [leiningen.core.main :as main] [leiningen.core.eval :as eval] [leiningen.core.user :as user] [leiningen.core.utils :as utils] [clojure.java.io :as io] [leiningen.pom :as pom] [leiningen.jar :as jar] [clojure.java.shell :as sh] [clojure.string :as string])) (defn- abort-message [message] (cond (re-find #"Return code is 405" message) (str message "\n" "Ensure you are deploying over SSL.") (re-find #"Return code is 401" message) (str message "\n" "See `lein help deploying` for an explanation of how" " to specify credentials.") :else message)) (defn add-auth-from-url [[id settings]] (let [url (utils/build-url id) user-info (and url (.getUserInfo url)) [username password] (and user-info (.split user-info ":"))] (if username [id (assoc settings :username username :password PI:PASSWORD:<PASSWORD>END_PI)] [id settings]))) (defn add-auth-interactively [[id settings]] (if (or (and (:username settings) (some settings [:password :passphrase :private-key-file])) (:no-auth settings) (re-find #"(file|scp|scpexe)://" (:url settings))) [id settings] (do (when @utils/rebound-io? (main/abort "No credentials found for" id "(did you mean `lein deploy" "clojars`?)\nPassword prompts are not supported when ran" "after other (potentially)\ninteractive tasks.\nSee `lein" "help deploy` for an explanation of how to specify" "credentials.")) (print "No credentials found for" id) (when (not= "clojars" id) (print "(did you mean `lein deploy clojars`?)")) (println "\nSee `lein help deploying` for how to configure credentials" "to avoid prompts.") (print "Username: ") (flush) (let [username (read-line) console (System/console) password (if console (.readPassword console "%s" (into-array ["Password: "])) (do (println "LEIN IS UNABLE TO TURN OFF ECHOING, SO" "THE PASSWORD IS PRINTED TO THE CONSOLE") (print "Password: ") (flush) (read-line)))] [id (assoc settings :username username :password password)])))) ;; repo names must not contain path delimiters because they're used by ;; aether for form filenames (defn- sanitize-repo-name [name] (last (.split name "/"))) (defn repo-for [project name] (let [settings (merge (get (into {} (:repositories project)) name) (get (into {} (:deploy-repositories project)) name))] (-> [(sanitize-repo-name name) (or settings {:url name})] (classpath/add-repo-auth) (add-auth-from-url) (add-auth-interactively)))) (defn signing-args "Produce GPG arguments for signing a file." [file opts] (let [key-spec (if-let [key (:gpg-key opts)] ["--default-key" key])] `["--yes" "-ab" ~@key-spec "--" ~file])) (defn sign "Create a detached signature and return the signature file name." [file opts] (let [{:keys [err exit]} (apply user/gpg (signing-args file opts))] (when-not (zero? exit) (main/abort "Could not sign" (str file "\n" err (if err "\n") "\nSee `lein help gpg` for how to set up gpg.\n" "If you don't expect people to need to verify the " "authorship of your jar, you\ncan add `:sign-releases " "false` to the relevant `:deploy-repositories` entry."))) (str file ".asc"))) (defn signature-for-artifact [[coords artifact-file] opts] {(apply concat (update-in (apply hash-map coords) [:extension] #(str (or % "jar") ".asc"))) (sign artifact-file opts)}) (defn signatures-for-artifacts "Creates and returns the list of signatures for the artifacts needed to be signed." [artifacts sig-opts] (let [total (count artifacts)] (println "Need to sign" total "files with GPG") (doall (map-indexed (fn [idx [coords artifact-file :as artifact]] (printf "[%d/%d] Signing %s with GPG\n" (inc idx) total artifact-file) (flush) (signature-for-artifact artifact sig-opts)) artifacts)))) (defn sign-for-repo? "Generally sign artifacts for this repo?" [repo] (:sign-releases (second repo) true)) (defn signing-opts "Extract signing options map from a project." [project repo] (merge (:signing project) (:signing (second repo)))) (defn files-for [project repo] (let [signed? (sign-for-repo? repo) ;; If pom is put in "target/", :auto-clean true will remove it if the ;; jar is created afterwards. So make jar first, then pom. artifacts (merge (jar/jar project) {[:extension "pom"] (pom/pom project)}) sig-opts (signing-opts project repo)] (if (and signed? (not (.endsWith (:version project) "-SNAPSHOT"))) (reduce merge artifacts (signatures-for-artifacts artifacts sig-opts)) artifacts))) (defn warn-missing-metadata [project] (doseq [key [:description :license :url]] (when (or (nil? (project key)) (re-find #"FIXME" (str (project key)))) (main/warn "WARNING: please set" key "in project.clj.")))) (defn- in-branches [branches] (-> (sh/sh "git" "rev-parse" "--abbrev-ref" "HEAD") :out butlast string/join branches not)) (defn- extension [f] (if-let [[_ signed-extension] (re-find #"\.([a-z]+\.asc)$" f)] signed-extension (if (= "pom.xml" (.getName (io/file f))) "pom" (last (.split f "\\."))))) (defn classifier "The classifier is be located between the version and extension name of the artifact. See http://maven.apache.org/plugins/maven-deploy-plugin/examples/deploying-with-classifiers.html " [version f] (let [pattern (re-pattern (format "%s-(.*)\\.%s" version (extension f))) [_ classifier-of] (re-find pattern f)] (when-not (empty? classifier-of) classifier-of))) (defn- fail-on-empty-project [project] (when-not (:root project) (main/abort "Couldn't find project.clj, which is needed for deploy task"))) (defn ^:no-project-needed deploy "Deploy jar and pom to remote repository. The target repository will be looked up in :repositories in project.clj: :repositories [[\"snapshots\" \"https://internal.repo/snapshots\"] [\"releases\" \"https://internal.repo/releases\"] [\"alternate\" \"https://other.server/repo\"]] If you don't provide a repository name to deploy to, either \"snapshots\" or \"releases\" will be used depending on your project's current version. You may provide a repository URL instead of a name. See `lein help deploying` under \"Authentication\" for instructions on how to configure your credentials so you are not prompted on each deploy. You can also deploy arbitrary artifacts from disk: $ lein deploy myrepo com.blueant/fancypants 1.0.1 fancypants.jar pom.xml While this works with any arbitrary files on disk, downstream projects will not be able to depend on jars that are deployed without a pom." ([project] (deploy project (if (pom/snapshot? project) "snapshots" "releases"))) ([project repository] (fail-on-empty-project project) (let [branches (set (:deploy-branches project))] (when (and (seq branches) (in-branches branches)) (apply main/abort "Can only deploy from branches listed in" ":deploy-branches:" branches))) (warn-missing-metadata project) (let [repo (repo-for project repository) files (files-for project repo)] (try (java.lang.System/setProperty "aether.checksums.forSignature" "true") (main/debug "Deploying" files "to" repo) (aether/deploy :coordinates [(symbol (:group project) (:name project)) (:version project)] :artifact-map files :transfer-listener :stdout :repository [repo]) (catch org.eclipse.aether.deployment.DeploymentException e (when main/*debug* (.printStackTrace e)) (main/abort (abort-message (.getMessage e))))))) ([project repository identifier version & files] (let [identifier (symbol identifier) artifact-id (name identifier) group-id (namespace identifier) repo (repo-for project repository) artifacts (for [f files] [[:extension (extension f) :classifier (classifier version f)] f])] (java.lang.System/setProperty "aether.checksums.forSignature" "true") (main/debug "Deploying" files "to" repo) (aether/deploy :coordinates [(symbol group-id artifact-id) version] :artifact-map (into {} artifacts) :transfer-listener :stdout :repository [repo] :local-repo (:local-repo project)))))
[ { "context": "r \\\"cloudservers-us\\\")\n (def provider-identity \\\"username\\\")\n (def provider-credential \\\"password\\\")\n\n ;;", "end": 1515, "score": 0.9888896942138672, "start": 1507, "tag": "USERNAME", "value": "username" }, { "context": "entity \\\"username\\\")\n (def provider-credential \\\"password\\\")\n\n ;; create a compute service\n (def compute\n", "end": 1556, "score": 0.9764328598976135, "start": 1548, "tag": "PASSWORD", "value": "password" } ]
compute/src/main/clojure/org/jclouds/compute2.clj
danbroudy/jclouds
1
; ; Licensed to the Apache Software Foundation (ASF) under one or more ; contributor license agreements. See the NOTICE file distributed with ; this work for additional information regarding copyright ownership. ; The ASF licenses this file to You under the Apache License, Version 2.0 ; (the "License"); you may not use this file except in compliance with ; the License. You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; (ns org.jclouds.compute2 "A clojure binding to the jclouds ComputeService. jclouds supports many compute providers including Amazon EC2 (aws-ec2), Rackspace Cloud Servers (cloudservers-us), GoGrid (gogrid), There are over a dozen to choose from. Current supported providers are available via the following dependency: org.jclouds/jclouds-allcompute You can inquire about which providers are loaded via the following: (seq (org.jclouds.providers.Providers/allCompute)) (seq (org.jclouds.apis.Apis/allCompute)) Here's an example of getting some compute configuration from rackspace: (use 'org.jclouds.compute2) (use 'clojure.pprint) (def provider \"cloudservers-us\") (def provider-identity \"username\") (def provider-credential \"password\") ;; create a compute service (def compute (compute-service provider provider-identity provider-credential)) (pprint (locations compute)) (pprint (images compute)) (pprint (nodes compute)) (pprint (hardware-profiles compute))) Here's an example of creating and running a small linux node in the group webserver: ;; create a compute service using ssh and log4j extensions (def compute (compute-service provider provider-identity provider-credential :sshj :log4j)) (create-node \"webserver\" compute) See http://code.google.com/p/jclouds for details. " (:use org.jclouds.core (org.jclouds predicate) [clojure.core.incubator :only (-?>)]) (:import java.io.File java.util.Properties [org.jclouds ContextBuilder] [org.jclouds.domain Location] [org.jclouds.compute ComputeService ComputeServiceContext] [org.jclouds.compute.domain Template TemplateBuilder ComputeMetadata NodeMetadata Hardware OsFamily Image] [org.jclouds.compute.options TemplateOptions RunScriptOptions RunScriptOptions$Builder] [org.jclouds.compute.predicates NodePredicates] [com.google.common.collect ImmutableSet]) ) (defn compute-service "Create a logged in context." ([#^String provider #^String provider-identity #^String provider-credential & options] (let [module-keys (set (keys module-lookup)) ext-modules (filter #(module-keys %) options) opts (apply hash-map (filter #(not (module-keys %)) options))] (.. (ContextBuilder/newBuilder provider) (credentials provider-identity provider-credential) (modules (apply modules (concat ext-modules (opts :extensions)))) (overrides (reduce #(do (.put %1 (name (first %2)) (second %2)) %1) (Properties.) (dissoc opts :extensions))) (buildView ComputeServiceContext) (getComputeService)))) ([#^ComputeServiceContext compute-context] (.getComputeService compute-context))) (defn compute-context "Returns a compute context from a compute service." [compute] (.getContext compute)) (defn compute-service? [object] (instance? ComputeService object)) (defn compute-context? [object] (instance? ComputeServiceContext object)) (defn locations "Retrieve the available compute locations for the compute context." ([#^ComputeService compute] (seq (.listAssignableLocations compute)))) (defn nodes "Retrieve the existing nodes for the compute context." ([#^ComputeService compute] (seq (.listNodes compute)))) (defn nodes-with-details "Retrieve the existing nodes for the compute context." ([#^ComputeService compute] (seq (.listNodesDetailsMatching compute (NodePredicates/all))))) (defn nodes-with-details-matching "List details for all nodes matching fn pred. pred should be a fn of one argument that takes a ComputeMetadata and returns true or false. " ([#^ComputeService compute pred] (seq (.listNodesDetailsMatching compute (to-predicate pred))))) (defn nodes-in-group "list details of all the nodes in the given group." ([#^ComputeService compute #^String group] (filter #(= (.getGroup %) group) (nodes-with-details compute)))) (defn images "Retrieve the available images for the compute context." ([#^ComputeService compute] (seq (.listImages compute)))) (defn hardware-profiles "Retrieve the available node hardware profiles for the compute context." ([#^ComputeService compute] (seq (.listHardwareProfiles compute)))) (defn default-template ([#^ComputeService compute] (.. compute (templateBuilder) (options (org.jclouds.compute.options.TemplateOptions$Builder/authorizePublicKey (slurp (str (. System getProperty "user.home") "/.ssh/id_rsa.pub")))) build))) (defn create-nodes "Create the specified number of nodes using the default or specified template. ;; Simplest way to add 2 small linux nodes to the group webserver is to run (create-nodes \"webserver\" 2 compute) ;; Note that this will actually add another 2 nodes to the set called ;; \"webserver\"" ([group count compute] (create-nodes group count (default-template compute) compute)) ([#^ComputeService compute group count template] (seq (.createNodesInGroup compute group count template)))) (defn create-node "Create a node using the default or specified template. ;; simplest way to add a small linux node to the group webserver is to run (create-node \"webserver\" compute) ;; Note that this will actually add another node to the set called ;; \"webserver\"" ([compute group] (create-node compute group (default-template compute))) ([compute group template] (first (create-nodes compute group 1 template)))) (defn #^NodeMetadata node-details "Retrieve the node metadata, given its id." ([#^ComputeService compute id] (.getNodeMetadata compute id))) (defn suspend-nodes-matching "Suspend all nodes matching the fn pred. pred should be a fn of one argument that takes a ComputeMetadata and returns true or false." ([#^ComputeService compute pred] (.suspendNodesMatching compute (to-predicate pred)))) (defn suspend-node "Suspend a node, given its id." ([#^ComputeService compute id] (.suspendNode compute id))) (defn resume-nodes-matching "Suspend all the nodes in the fn pred. pred should be a fn of one argument that takes a ComputeMetadata and returns true or false." ([#^ComputeService compute pred] (.resumeNodesMatching compute (to-predicate pred)))) (defn resume-node "Resume a node, given its id." ([#^ComputeService compute id] (.resumeNode compute id))) (defn reboot-nodes-matching "Reboot all the nodes in the fn pred. pred should be a fn of one argument that takes a ComputeMetadata and returns true or false." ([#^ComputeService compute pred] (.rebootNodesMatching compute (to-predicate pred)))) (defn reboot-node "Reboot a node, given its id." ([#^ComputeService compute id] (.rebootNode compute id))) (defn destroy-nodes-matching "Destroy all the nodes in the fn pred. pred should be a fn of one argument that takes a ComputeMetadata and returns true or false. ;; destroy all nodes (destroy-nodes-matching compute (constantly true)) " ([#^ComputeService compute pred] (.destroyNodesMatching compute (to-predicate pred)))) (defn destroy-node "Destroy a node, given its id." ([#^ComputeService compute id] (.destroyNode compute id))) (defn run-script-on-node "Run a script on a node" ([#^ComputeService compute id command #^RunScriptOptions options] (.runScriptOnNode compute id command options))) (defn run-script-on-nodes-matching "Run a script on the nodes matching the given predicate" ([#^ComputeService compute pred command #^RunScriptOptions options] (.runScriptOnNodesMatching compute (to-predicate pred) command options))) (defmacro status-predicate [node status] `(= (.getStatus ~node) (. org.jclouds.compute.domain.NodeMetadata$Status ~status))) (defn pending? "Predicate for the node being in transition" [#^NodeMetadata node] (status-predicate node PENDING)) (defn running? "Predicate for the node being available for requests." [#^NodeMetadata node] (status-predicate node RUNNING)) (defn terminated? "Predicate for the node being halted." [#^NodeMetadata node] (or (= node nil) (status-predicate node TERMINATED))) (defn suspended? "Predicate for the node being suspended." [#^NodeMetadata node] (status-predicate node SUSPENDED)) (defn error-status? "Predicate for the node being in an error status." [#^NodeMetadata node] (status-predicate node ERROR)) (defn unrecognized-status? "Predicate for the node being in an unrecognized status." [#^NodeMetadata node] (status-predicate node UNRECOGNIZED)) (defn in-group? "Returns a predicate fn which returns true if the node is in the given group, false otherwise" [group] #(= (.getGroup %) group)) (defn public-ips "Returns the node's public ips" [#^NodeMetadata node] (.getPublicAddresses node)) (defn private-ips "Returns the node's private ips" [#^NodeMetadata node] (.getPrivateAddresses node)) (defn group "Returns a the node's group" [#^NodeMetadata node] (.getGroup node)) (defn hostname "Returns the compute node's name" [#^ComputeMetadata node] (.getName node)) (defn location "Returns the compute node's location id" [#^ComputeMetadata node] (-?> node .getLocation .getId)) (defn id "Returns the compute node's id" [#^ComputeMetadata node] (.getId node)) (define-accessors Template image hardware location options) (define-accessors Image version os-family os-description architecture) (define-accessors Hardware processors ram volumes) (define-accessors NodeMetadata "node" credentials hardware status group) (def ^{:doc "TemplateBuilder functions" :private true} template-map (merge (make-option-map kw-memfn-0arg [:smallest :fastest :biggest :any]) (make-option-map kw-memfn-1arg [:from-hardware :from-image :from-template :os-family :location-id :image-id :hardware-id :hypervisor-matches :os-name-matches :os-description-matches :os-version-matches :os-arch-matches :os-64-bit :image-name-matches :image-version-matches :image-description-matches :image-matches :min-cores :min-ram :min-disk]))) (def ^{:doc "TemplateOptions functions" :private true} options-map (merge (make-option-map kw-memfn-0arg [;; ec2 :no-key-pair ;; aws-ec2 :enable-monitoring :no-placement-group]) (make-option-map kw-memfn-1arg [;; RunScriptOptions :override-login-credentials :override-login-user :override-login-password :override-login-private-key :override-authenticate-sudo :name-task :run-as-root :wrap-in-init-script :block-on-complete :block-on-port ;; TemplateOptions :run-script :install-private-key :authorize-public-key :tags ;; cloudstack :security-group-id :network-id :network-ids :setup-static-nat :ip-on-default-network :ips-to-networks ;; ec2 :security-groups :user-data :block-device-mappings :unmap-device-named ;; cloudstack ec2 :key-pair ;; aws-ec2 :placement-group :subnet-id :spot-price :spot-options :iam-instance-profile-name :iam-instance-profile-arn ;; cloudstack aws-ec2 :security-group-ids ;; softlayer :domain-name]) (make-option-map kw-memfn-varargs [;; from TemplateOptions :inbound-ports]) (make-option-map kw-memfn-2arg [;; from TemplateOptions :block-on-port ;; ec2 options :map-ephemeral-device-to-device-name]) {:map-ebs-snapshot-to-device-name (kw-memfn-apply :map-ebs-snapshot-to-device-name device-name snapshot-id size-in-gib delete-on-termination) :map-new-volume-to-device-name (kw-memfn-apply :map-new-volume-to-device-name device-name size-in-gib delete-on-termination)})) (def ^{:doc "All receognised options"} known-template-options (set (mapcat keys [options-map template-map]))) (defn os-families [] (. OsFamily values)) (def enum-map {:os-family (os-families)}) (defn translate-enum-value [kword value] (or (-> (filter #(= (name value) (str %)) (kword enum-map)) first) value)) (defn apply-option [builder option-map option value] (when-let [f (option-map option)] (f builder (translate-enum-value option value)))) (defn build-template "Creates a template that can be used to run nodes. The :os-family key expects a keyword version of OsFamily, eg. :os-family :ubuntu. The :smallest, :fastest, :biggest, and :any keys expect a boolean value. Options correspond to TemplateBuilder methods." [#^ComputeService compute {:keys [from-hardware from-image from-template os-family location-id image-id hardware-id os-name-matches os-description-matches os-version-matches os-arch-matches os-64-bit mage-name-matches image-version-matches image-description-matches image-matches min-cores min-ram min-disk smallest fastest biggest any] :as options}] (let [builder (.. compute (templateBuilder))] (doseq [[option value] options] (when-not (known-template-options option) (throw (Exception. (format "Invalid template builder option : %s" option)))) ;; apply template builder options (try (apply-option builder template-map option value) (catch Exception e (throw (Exception. (format "Problem applying template builder %s with value %s: %s" option (pr-str value) (.getMessage e)) e))))) (let [template (.build builder) template-options (.getOptions template)] (doseq [[option value] options] ;; apply template option options (try (apply-option template-options options-map option value) (catch Exception e (throw (Exception. (format "Problem applying template option %s with value %s: %s" option (pr-str value) (.getMessage e)) e))))) template)))
48458
; ; Licensed to the Apache Software Foundation (ASF) under one or more ; contributor license agreements. See the NOTICE file distributed with ; this work for additional information regarding copyright ownership. ; The ASF licenses this file to You under the Apache License, Version 2.0 ; (the "License"); you may not use this file except in compliance with ; the License. You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; (ns org.jclouds.compute2 "A clojure binding to the jclouds ComputeService. jclouds supports many compute providers including Amazon EC2 (aws-ec2), Rackspace Cloud Servers (cloudservers-us), GoGrid (gogrid), There are over a dozen to choose from. Current supported providers are available via the following dependency: org.jclouds/jclouds-allcompute You can inquire about which providers are loaded via the following: (seq (org.jclouds.providers.Providers/allCompute)) (seq (org.jclouds.apis.Apis/allCompute)) Here's an example of getting some compute configuration from rackspace: (use 'org.jclouds.compute2) (use 'clojure.pprint) (def provider \"cloudservers-us\") (def provider-identity \"username\") (def provider-credential \"<PASSWORD>\") ;; create a compute service (def compute (compute-service provider provider-identity provider-credential)) (pprint (locations compute)) (pprint (images compute)) (pprint (nodes compute)) (pprint (hardware-profiles compute))) Here's an example of creating and running a small linux node in the group webserver: ;; create a compute service using ssh and log4j extensions (def compute (compute-service provider provider-identity provider-credential :sshj :log4j)) (create-node \"webserver\" compute) See http://code.google.com/p/jclouds for details. " (:use org.jclouds.core (org.jclouds predicate) [clojure.core.incubator :only (-?>)]) (:import java.io.File java.util.Properties [org.jclouds ContextBuilder] [org.jclouds.domain Location] [org.jclouds.compute ComputeService ComputeServiceContext] [org.jclouds.compute.domain Template TemplateBuilder ComputeMetadata NodeMetadata Hardware OsFamily Image] [org.jclouds.compute.options TemplateOptions RunScriptOptions RunScriptOptions$Builder] [org.jclouds.compute.predicates NodePredicates] [com.google.common.collect ImmutableSet]) ) (defn compute-service "Create a logged in context." ([#^String provider #^String provider-identity #^String provider-credential & options] (let [module-keys (set (keys module-lookup)) ext-modules (filter #(module-keys %) options) opts (apply hash-map (filter #(not (module-keys %)) options))] (.. (ContextBuilder/newBuilder provider) (credentials provider-identity provider-credential) (modules (apply modules (concat ext-modules (opts :extensions)))) (overrides (reduce #(do (.put %1 (name (first %2)) (second %2)) %1) (Properties.) (dissoc opts :extensions))) (buildView ComputeServiceContext) (getComputeService)))) ([#^ComputeServiceContext compute-context] (.getComputeService compute-context))) (defn compute-context "Returns a compute context from a compute service." [compute] (.getContext compute)) (defn compute-service? [object] (instance? ComputeService object)) (defn compute-context? [object] (instance? ComputeServiceContext object)) (defn locations "Retrieve the available compute locations for the compute context." ([#^ComputeService compute] (seq (.listAssignableLocations compute)))) (defn nodes "Retrieve the existing nodes for the compute context." ([#^ComputeService compute] (seq (.listNodes compute)))) (defn nodes-with-details "Retrieve the existing nodes for the compute context." ([#^ComputeService compute] (seq (.listNodesDetailsMatching compute (NodePredicates/all))))) (defn nodes-with-details-matching "List details for all nodes matching fn pred. pred should be a fn of one argument that takes a ComputeMetadata and returns true or false. " ([#^ComputeService compute pred] (seq (.listNodesDetailsMatching compute (to-predicate pred))))) (defn nodes-in-group "list details of all the nodes in the given group." ([#^ComputeService compute #^String group] (filter #(= (.getGroup %) group) (nodes-with-details compute)))) (defn images "Retrieve the available images for the compute context." ([#^ComputeService compute] (seq (.listImages compute)))) (defn hardware-profiles "Retrieve the available node hardware profiles for the compute context." ([#^ComputeService compute] (seq (.listHardwareProfiles compute)))) (defn default-template ([#^ComputeService compute] (.. compute (templateBuilder) (options (org.jclouds.compute.options.TemplateOptions$Builder/authorizePublicKey (slurp (str (. System getProperty "user.home") "/.ssh/id_rsa.pub")))) build))) (defn create-nodes "Create the specified number of nodes using the default or specified template. ;; Simplest way to add 2 small linux nodes to the group webserver is to run (create-nodes \"webserver\" 2 compute) ;; Note that this will actually add another 2 nodes to the set called ;; \"webserver\"" ([group count compute] (create-nodes group count (default-template compute) compute)) ([#^ComputeService compute group count template] (seq (.createNodesInGroup compute group count template)))) (defn create-node "Create a node using the default or specified template. ;; simplest way to add a small linux node to the group webserver is to run (create-node \"webserver\" compute) ;; Note that this will actually add another node to the set called ;; \"webserver\"" ([compute group] (create-node compute group (default-template compute))) ([compute group template] (first (create-nodes compute group 1 template)))) (defn #^NodeMetadata node-details "Retrieve the node metadata, given its id." ([#^ComputeService compute id] (.getNodeMetadata compute id))) (defn suspend-nodes-matching "Suspend all nodes matching the fn pred. pred should be a fn of one argument that takes a ComputeMetadata and returns true or false." ([#^ComputeService compute pred] (.suspendNodesMatching compute (to-predicate pred)))) (defn suspend-node "Suspend a node, given its id." ([#^ComputeService compute id] (.suspendNode compute id))) (defn resume-nodes-matching "Suspend all the nodes in the fn pred. pred should be a fn of one argument that takes a ComputeMetadata and returns true or false." ([#^ComputeService compute pred] (.resumeNodesMatching compute (to-predicate pred)))) (defn resume-node "Resume a node, given its id." ([#^ComputeService compute id] (.resumeNode compute id))) (defn reboot-nodes-matching "Reboot all the nodes in the fn pred. pred should be a fn of one argument that takes a ComputeMetadata and returns true or false." ([#^ComputeService compute pred] (.rebootNodesMatching compute (to-predicate pred)))) (defn reboot-node "Reboot a node, given its id." ([#^ComputeService compute id] (.rebootNode compute id))) (defn destroy-nodes-matching "Destroy all the nodes in the fn pred. pred should be a fn of one argument that takes a ComputeMetadata and returns true or false. ;; destroy all nodes (destroy-nodes-matching compute (constantly true)) " ([#^ComputeService compute pred] (.destroyNodesMatching compute (to-predicate pred)))) (defn destroy-node "Destroy a node, given its id." ([#^ComputeService compute id] (.destroyNode compute id))) (defn run-script-on-node "Run a script on a node" ([#^ComputeService compute id command #^RunScriptOptions options] (.runScriptOnNode compute id command options))) (defn run-script-on-nodes-matching "Run a script on the nodes matching the given predicate" ([#^ComputeService compute pred command #^RunScriptOptions options] (.runScriptOnNodesMatching compute (to-predicate pred) command options))) (defmacro status-predicate [node status] `(= (.getStatus ~node) (. org.jclouds.compute.domain.NodeMetadata$Status ~status))) (defn pending? "Predicate for the node being in transition" [#^NodeMetadata node] (status-predicate node PENDING)) (defn running? "Predicate for the node being available for requests." [#^NodeMetadata node] (status-predicate node RUNNING)) (defn terminated? "Predicate for the node being halted." [#^NodeMetadata node] (or (= node nil) (status-predicate node TERMINATED))) (defn suspended? "Predicate for the node being suspended." [#^NodeMetadata node] (status-predicate node SUSPENDED)) (defn error-status? "Predicate for the node being in an error status." [#^NodeMetadata node] (status-predicate node ERROR)) (defn unrecognized-status? "Predicate for the node being in an unrecognized status." [#^NodeMetadata node] (status-predicate node UNRECOGNIZED)) (defn in-group? "Returns a predicate fn which returns true if the node is in the given group, false otherwise" [group] #(= (.getGroup %) group)) (defn public-ips "Returns the node's public ips" [#^NodeMetadata node] (.getPublicAddresses node)) (defn private-ips "Returns the node's private ips" [#^NodeMetadata node] (.getPrivateAddresses node)) (defn group "Returns a the node's group" [#^NodeMetadata node] (.getGroup node)) (defn hostname "Returns the compute node's name" [#^ComputeMetadata node] (.getName node)) (defn location "Returns the compute node's location id" [#^ComputeMetadata node] (-?> node .getLocation .getId)) (defn id "Returns the compute node's id" [#^ComputeMetadata node] (.getId node)) (define-accessors Template image hardware location options) (define-accessors Image version os-family os-description architecture) (define-accessors Hardware processors ram volumes) (define-accessors NodeMetadata "node" credentials hardware status group) (def ^{:doc "TemplateBuilder functions" :private true} template-map (merge (make-option-map kw-memfn-0arg [:smallest :fastest :biggest :any]) (make-option-map kw-memfn-1arg [:from-hardware :from-image :from-template :os-family :location-id :image-id :hardware-id :hypervisor-matches :os-name-matches :os-description-matches :os-version-matches :os-arch-matches :os-64-bit :image-name-matches :image-version-matches :image-description-matches :image-matches :min-cores :min-ram :min-disk]))) (def ^{:doc "TemplateOptions functions" :private true} options-map (merge (make-option-map kw-memfn-0arg [;; ec2 :no-key-pair ;; aws-ec2 :enable-monitoring :no-placement-group]) (make-option-map kw-memfn-1arg [;; RunScriptOptions :override-login-credentials :override-login-user :override-login-password :override-login-private-key :override-authenticate-sudo :name-task :run-as-root :wrap-in-init-script :block-on-complete :block-on-port ;; TemplateOptions :run-script :install-private-key :authorize-public-key :tags ;; cloudstack :security-group-id :network-id :network-ids :setup-static-nat :ip-on-default-network :ips-to-networks ;; ec2 :security-groups :user-data :block-device-mappings :unmap-device-named ;; cloudstack ec2 :key-pair ;; aws-ec2 :placement-group :subnet-id :spot-price :spot-options :iam-instance-profile-name :iam-instance-profile-arn ;; cloudstack aws-ec2 :security-group-ids ;; softlayer :domain-name]) (make-option-map kw-memfn-varargs [;; from TemplateOptions :inbound-ports]) (make-option-map kw-memfn-2arg [;; from TemplateOptions :block-on-port ;; ec2 options :map-ephemeral-device-to-device-name]) {:map-ebs-snapshot-to-device-name (kw-memfn-apply :map-ebs-snapshot-to-device-name device-name snapshot-id size-in-gib delete-on-termination) :map-new-volume-to-device-name (kw-memfn-apply :map-new-volume-to-device-name device-name size-in-gib delete-on-termination)})) (def ^{:doc "All receognised options"} known-template-options (set (mapcat keys [options-map template-map]))) (defn os-families [] (. OsFamily values)) (def enum-map {:os-family (os-families)}) (defn translate-enum-value [kword value] (or (-> (filter #(= (name value) (str %)) (kword enum-map)) first) value)) (defn apply-option [builder option-map option value] (when-let [f (option-map option)] (f builder (translate-enum-value option value)))) (defn build-template "Creates a template that can be used to run nodes. The :os-family key expects a keyword version of OsFamily, eg. :os-family :ubuntu. The :smallest, :fastest, :biggest, and :any keys expect a boolean value. Options correspond to TemplateBuilder methods." [#^ComputeService compute {:keys [from-hardware from-image from-template os-family location-id image-id hardware-id os-name-matches os-description-matches os-version-matches os-arch-matches os-64-bit mage-name-matches image-version-matches image-description-matches image-matches min-cores min-ram min-disk smallest fastest biggest any] :as options}] (let [builder (.. compute (templateBuilder))] (doseq [[option value] options] (when-not (known-template-options option) (throw (Exception. (format "Invalid template builder option : %s" option)))) ;; apply template builder options (try (apply-option builder template-map option value) (catch Exception e (throw (Exception. (format "Problem applying template builder %s with value %s: %s" option (pr-str value) (.getMessage e)) e))))) (let [template (.build builder) template-options (.getOptions template)] (doseq [[option value] options] ;; apply template option options (try (apply-option template-options options-map option value) (catch Exception e (throw (Exception. (format "Problem applying template option %s with value %s: %s" option (pr-str value) (.getMessage e)) e))))) template)))
true
; ; Licensed to the Apache Software Foundation (ASF) under one or more ; contributor license agreements. See the NOTICE file distributed with ; this work for additional information regarding copyright ownership. ; The ASF licenses this file to You under the Apache License, Version 2.0 ; (the "License"); you may not use this file except in compliance with ; the License. You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; (ns org.jclouds.compute2 "A clojure binding to the jclouds ComputeService. jclouds supports many compute providers including Amazon EC2 (aws-ec2), Rackspace Cloud Servers (cloudservers-us), GoGrid (gogrid), There are over a dozen to choose from. Current supported providers are available via the following dependency: org.jclouds/jclouds-allcompute You can inquire about which providers are loaded via the following: (seq (org.jclouds.providers.Providers/allCompute)) (seq (org.jclouds.apis.Apis/allCompute)) Here's an example of getting some compute configuration from rackspace: (use 'org.jclouds.compute2) (use 'clojure.pprint) (def provider \"cloudservers-us\") (def provider-identity \"username\") (def provider-credential \"PI:PASSWORD:<PASSWORD>END_PI\") ;; create a compute service (def compute (compute-service provider provider-identity provider-credential)) (pprint (locations compute)) (pprint (images compute)) (pprint (nodes compute)) (pprint (hardware-profiles compute))) Here's an example of creating and running a small linux node in the group webserver: ;; create a compute service using ssh and log4j extensions (def compute (compute-service provider provider-identity provider-credential :sshj :log4j)) (create-node \"webserver\" compute) See http://code.google.com/p/jclouds for details. " (:use org.jclouds.core (org.jclouds predicate) [clojure.core.incubator :only (-?>)]) (:import java.io.File java.util.Properties [org.jclouds ContextBuilder] [org.jclouds.domain Location] [org.jclouds.compute ComputeService ComputeServiceContext] [org.jclouds.compute.domain Template TemplateBuilder ComputeMetadata NodeMetadata Hardware OsFamily Image] [org.jclouds.compute.options TemplateOptions RunScriptOptions RunScriptOptions$Builder] [org.jclouds.compute.predicates NodePredicates] [com.google.common.collect ImmutableSet]) ) (defn compute-service "Create a logged in context." ([#^String provider #^String provider-identity #^String provider-credential & options] (let [module-keys (set (keys module-lookup)) ext-modules (filter #(module-keys %) options) opts (apply hash-map (filter #(not (module-keys %)) options))] (.. (ContextBuilder/newBuilder provider) (credentials provider-identity provider-credential) (modules (apply modules (concat ext-modules (opts :extensions)))) (overrides (reduce #(do (.put %1 (name (first %2)) (second %2)) %1) (Properties.) (dissoc opts :extensions))) (buildView ComputeServiceContext) (getComputeService)))) ([#^ComputeServiceContext compute-context] (.getComputeService compute-context))) (defn compute-context "Returns a compute context from a compute service." [compute] (.getContext compute)) (defn compute-service? [object] (instance? ComputeService object)) (defn compute-context? [object] (instance? ComputeServiceContext object)) (defn locations "Retrieve the available compute locations for the compute context." ([#^ComputeService compute] (seq (.listAssignableLocations compute)))) (defn nodes "Retrieve the existing nodes for the compute context." ([#^ComputeService compute] (seq (.listNodes compute)))) (defn nodes-with-details "Retrieve the existing nodes for the compute context." ([#^ComputeService compute] (seq (.listNodesDetailsMatching compute (NodePredicates/all))))) (defn nodes-with-details-matching "List details for all nodes matching fn pred. pred should be a fn of one argument that takes a ComputeMetadata and returns true or false. " ([#^ComputeService compute pred] (seq (.listNodesDetailsMatching compute (to-predicate pred))))) (defn nodes-in-group "list details of all the nodes in the given group." ([#^ComputeService compute #^String group] (filter #(= (.getGroup %) group) (nodes-with-details compute)))) (defn images "Retrieve the available images for the compute context." ([#^ComputeService compute] (seq (.listImages compute)))) (defn hardware-profiles "Retrieve the available node hardware profiles for the compute context." ([#^ComputeService compute] (seq (.listHardwareProfiles compute)))) (defn default-template ([#^ComputeService compute] (.. compute (templateBuilder) (options (org.jclouds.compute.options.TemplateOptions$Builder/authorizePublicKey (slurp (str (. System getProperty "user.home") "/.ssh/id_rsa.pub")))) build))) (defn create-nodes "Create the specified number of nodes using the default or specified template. ;; Simplest way to add 2 small linux nodes to the group webserver is to run (create-nodes \"webserver\" 2 compute) ;; Note that this will actually add another 2 nodes to the set called ;; \"webserver\"" ([group count compute] (create-nodes group count (default-template compute) compute)) ([#^ComputeService compute group count template] (seq (.createNodesInGroup compute group count template)))) (defn create-node "Create a node using the default or specified template. ;; simplest way to add a small linux node to the group webserver is to run (create-node \"webserver\" compute) ;; Note that this will actually add another node to the set called ;; \"webserver\"" ([compute group] (create-node compute group (default-template compute))) ([compute group template] (first (create-nodes compute group 1 template)))) (defn #^NodeMetadata node-details "Retrieve the node metadata, given its id." ([#^ComputeService compute id] (.getNodeMetadata compute id))) (defn suspend-nodes-matching "Suspend all nodes matching the fn pred. pred should be a fn of one argument that takes a ComputeMetadata and returns true or false." ([#^ComputeService compute pred] (.suspendNodesMatching compute (to-predicate pred)))) (defn suspend-node "Suspend a node, given its id." ([#^ComputeService compute id] (.suspendNode compute id))) (defn resume-nodes-matching "Suspend all the nodes in the fn pred. pred should be a fn of one argument that takes a ComputeMetadata and returns true or false." ([#^ComputeService compute pred] (.resumeNodesMatching compute (to-predicate pred)))) (defn resume-node "Resume a node, given its id." ([#^ComputeService compute id] (.resumeNode compute id))) (defn reboot-nodes-matching "Reboot all the nodes in the fn pred. pred should be a fn of one argument that takes a ComputeMetadata and returns true or false." ([#^ComputeService compute pred] (.rebootNodesMatching compute (to-predicate pred)))) (defn reboot-node "Reboot a node, given its id." ([#^ComputeService compute id] (.rebootNode compute id))) (defn destroy-nodes-matching "Destroy all the nodes in the fn pred. pred should be a fn of one argument that takes a ComputeMetadata and returns true or false. ;; destroy all nodes (destroy-nodes-matching compute (constantly true)) " ([#^ComputeService compute pred] (.destroyNodesMatching compute (to-predicate pred)))) (defn destroy-node "Destroy a node, given its id." ([#^ComputeService compute id] (.destroyNode compute id))) (defn run-script-on-node "Run a script on a node" ([#^ComputeService compute id command #^RunScriptOptions options] (.runScriptOnNode compute id command options))) (defn run-script-on-nodes-matching "Run a script on the nodes matching the given predicate" ([#^ComputeService compute pred command #^RunScriptOptions options] (.runScriptOnNodesMatching compute (to-predicate pred) command options))) (defmacro status-predicate [node status] `(= (.getStatus ~node) (. org.jclouds.compute.domain.NodeMetadata$Status ~status))) (defn pending? "Predicate for the node being in transition" [#^NodeMetadata node] (status-predicate node PENDING)) (defn running? "Predicate for the node being available for requests." [#^NodeMetadata node] (status-predicate node RUNNING)) (defn terminated? "Predicate for the node being halted." [#^NodeMetadata node] (or (= node nil) (status-predicate node TERMINATED))) (defn suspended? "Predicate for the node being suspended." [#^NodeMetadata node] (status-predicate node SUSPENDED)) (defn error-status? "Predicate for the node being in an error status." [#^NodeMetadata node] (status-predicate node ERROR)) (defn unrecognized-status? "Predicate for the node being in an unrecognized status." [#^NodeMetadata node] (status-predicate node UNRECOGNIZED)) (defn in-group? "Returns a predicate fn which returns true if the node is in the given group, false otherwise" [group] #(= (.getGroup %) group)) (defn public-ips "Returns the node's public ips" [#^NodeMetadata node] (.getPublicAddresses node)) (defn private-ips "Returns the node's private ips" [#^NodeMetadata node] (.getPrivateAddresses node)) (defn group "Returns a the node's group" [#^NodeMetadata node] (.getGroup node)) (defn hostname "Returns the compute node's name" [#^ComputeMetadata node] (.getName node)) (defn location "Returns the compute node's location id" [#^ComputeMetadata node] (-?> node .getLocation .getId)) (defn id "Returns the compute node's id" [#^ComputeMetadata node] (.getId node)) (define-accessors Template image hardware location options) (define-accessors Image version os-family os-description architecture) (define-accessors Hardware processors ram volumes) (define-accessors NodeMetadata "node" credentials hardware status group) (def ^{:doc "TemplateBuilder functions" :private true} template-map (merge (make-option-map kw-memfn-0arg [:smallest :fastest :biggest :any]) (make-option-map kw-memfn-1arg [:from-hardware :from-image :from-template :os-family :location-id :image-id :hardware-id :hypervisor-matches :os-name-matches :os-description-matches :os-version-matches :os-arch-matches :os-64-bit :image-name-matches :image-version-matches :image-description-matches :image-matches :min-cores :min-ram :min-disk]))) (def ^{:doc "TemplateOptions functions" :private true} options-map (merge (make-option-map kw-memfn-0arg [;; ec2 :no-key-pair ;; aws-ec2 :enable-monitoring :no-placement-group]) (make-option-map kw-memfn-1arg [;; RunScriptOptions :override-login-credentials :override-login-user :override-login-password :override-login-private-key :override-authenticate-sudo :name-task :run-as-root :wrap-in-init-script :block-on-complete :block-on-port ;; TemplateOptions :run-script :install-private-key :authorize-public-key :tags ;; cloudstack :security-group-id :network-id :network-ids :setup-static-nat :ip-on-default-network :ips-to-networks ;; ec2 :security-groups :user-data :block-device-mappings :unmap-device-named ;; cloudstack ec2 :key-pair ;; aws-ec2 :placement-group :subnet-id :spot-price :spot-options :iam-instance-profile-name :iam-instance-profile-arn ;; cloudstack aws-ec2 :security-group-ids ;; softlayer :domain-name]) (make-option-map kw-memfn-varargs [;; from TemplateOptions :inbound-ports]) (make-option-map kw-memfn-2arg [;; from TemplateOptions :block-on-port ;; ec2 options :map-ephemeral-device-to-device-name]) {:map-ebs-snapshot-to-device-name (kw-memfn-apply :map-ebs-snapshot-to-device-name device-name snapshot-id size-in-gib delete-on-termination) :map-new-volume-to-device-name (kw-memfn-apply :map-new-volume-to-device-name device-name size-in-gib delete-on-termination)})) (def ^{:doc "All receognised options"} known-template-options (set (mapcat keys [options-map template-map]))) (defn os-families [] (. OsFamily values)) (def enum-map {:os-family (os-families)}) (defn translate-enum-value [kword value] (or (-> (filter #(= (name value) (str %)) (kword enum-map)) first) value)) (defn apply-option [builder option-map option value] (when-let [f (option-map option)] (f builder (translate-enum-value option value)))) (defn build-template "Creates a template that can be used to run nodes. The :os-family key expects a keyword version of OsFamily, eg. :os-family :ubuntu. The :smallest, :fastest, :biggest, and :any keys expect a boolean value. Options correspond to TemplateBuilder methods." [#^ComputeService compute {:keys [from-hardware from-image from-template os-family location-id image-id hardware-id os-name-matches os-description-matches os-version-matches os-arch-matches os-64-bit mage-name-matches image-version-matches image-description-matches image-matches min-cores min-ram min-disk smallest fastest biggest any] :as options}] (let [builder (.. compute (templateBuilder))] (doseq [[option value] options] (when-not (known-template-options option) (throw (Exception. (format "Invalid template builder option : %s" option)))) ;; apply template builder options (try (apply-option builder template-map option value) (catch Exception e (throw (Exception. (format "Problem applying template builder %s with value %s: %s" option (pr-str value) (.getMessage e)) e))))) (let [template (.build builder) template-options (.getOptions template)] (doseq [[option value] options] ;; apply template option options (try (apply-option template-options options-map option value) (catch Exception e (throw (Exception. (format "Problem applying template option %s with value %s: %s" option (pr-str value) (.getMessage e)) e))))) template)))
[ { "context": "f neo4j-gcp-bolt-db\n (db/connect (URI. \"bolt://34.72.52.231:7687\")\n \"neo4j\"\n \"j", "end": 482, "score": 0.9996650218963623, "start": 470, "tag": "IP_ADDRESS", "value": "34.72.52.231" }, { "context": " (def neo4j-bolt-db\n (db/connect (URI. \"bolt://35.237.229.3:7687\")\n \"jwall\"\n \"2", "end": 604, "score": 0.9996443390846252, "start": 592, "tag": "IP_ADDRESS", "value": "35.237.229.3" }, { "context": " \"jwall\"\n \"2688\"))\n\n (def token \"secret_Eh9LEwrFvdKJsHLygDSX7QRMCwOV8RnlK4WSKUE6NGn\")\n (def notion-customer-db-id \"de297bebecf84283b", "end": 726, "score": 0.9992666244506836, "start": 676, "tag": "KEY", "value": "secret_Eh9LEwrFvdKJsHLygDSX7QRMCwOV8RnlK4WSKUE6NGn" }, { "context": " (assoc users1 user))] users1)\n\n (let [user [:user] (old-query-tester user-nodes)] user)\n\n (query-t", "end": 7032, "score": 0.7935786247253418, "start": 7028, "tag": "USERNAME", "value": "user" }, { "context": " user)\n\n (query-tester match-user-email {:email \"jwall@braincache.io\"})\n\n ((first (query-tester all_nodes)) :Admin)\n ", "end": 7133, "score": 0.999841034412384, "start": 7114, "tag": "EMAIL", "value": "jwall@braincache.io" } ]
src/datomic/com/example/components/notion_query.clj
justin-wallander/fulcro-rad-demo
0
(ns com.example.components.notion-query (:require [neo4j-clj.core :as db] [org.httpkit.client :as http] [clojure.data.json :as json] ;; [org.httpkit.sni-client :as sni-client] [mount.core :refer [defstate]]) (:import (java.net URI)) ) ;; Change default client for your whole application: ;; (alter-var-root #'org.httpkit.client/*default-client* (fn [_] sni-client/default-client)) (def neo4j-gcp-bolt-db (db/connect (URI. "bolt://34.72.52.231:7687") "neo4j" "jwall")) (def neo4j-bolt-db (db/connect (URI. "bolt://35.237.229.3:7687") "jwall" "2688")) (def token "secret_Eh9LEwrFvdKJsHLygDSX7QRMCwOV8RnlK4WSKUE6NGn") (def notion-customer-db-id "de297bebecf84283bafa4a51b174f326") (def notion-customers (let [options {:headers {"Authorization" (str "Bearer " token) "Notion-Version" "2021-08-16" "Content-Type" "application/json"}} {:keys [status headers body error] :as resp} @(http/post (format "https://api.notion.com/v1/databases/%s/query" notion-customer-db-id) options)] (if error (println "Failed, exception: " error) (json/read-str body)))) ;; (defn from-notion-idx-customer-email [& args] (get-in (((((get-in (first args) ["results" (first (rest args))]) "properties") "personEmail") "rollup") "array") [(first (rest args)) "email"])) ;; notion-customers ;; (def from-notion-idx-customer-email (get-in (((((get-in notion-customers ["results" 0]) "properties") "personEmail") "rollup") "array") [0 "email"])) ;; (from-notion-idx-customer-email [notion-customers 0]) ;; from-notion-idx-customer-email ;; (keys ((get-in notion-customers ["results" 0]) "properties")) (db/defquery match-user-email "MATCH (u:User {email: $email}) RETURN u as user") (db/defquery all_nodes "Match (n) return n{.*} as Nodes, labels(n) as Label") (db/defquery count-nodes "Match (n) return count(n)") (db/defquery type-nodes "Match (n) return distinct labels(n)") (db/defquery get-specific-nodes "MATCH (n) WHERE $node IN labels(n) RETURN n as node") (db/defquery missing-nodes "Match (n) where labels(n) is null return n, id(n)") (db/defquery user-nodes "MATCH (u:User) RETURN u as user") (db/defquery get-activity<-user-nodes "MATCH (n:Activity)<-[]-(u) where u.email is not null and (not (u.email contains 'jwall@')) RETURN n as activity, u as user") (db/defquery get-investor-nodes "MATCH (n:Investor) RETURN n as investor") (db/defquery updating-users-v1 "WITH $results as results FOREACH(row in results | MERGE (u:User{email: row['user']['email']}) SET u = row['user']) return count(*)") (db/defquery updating-Page-v1 "WITH $results as results FOREACH(row in results | MERGE (p:Page {ep: row['page']['ep']}) SET p = row['page']) return count(*)") (db/defquery updating-Proposal-v1 "WITH $results as results FOREACH(row in results | MERGE (p:Proposal {tfToken: row['proposal']['tfToken']}) SET p = row['proposal']) return count(*)") ;; updating-Investor-v1 ;; updating-LoginActivity-v1 (db/defquery updating-users-pages "WITH $results as results FOREACH(row in results | MERGE (u:User{email: row['properties']['personEmail']['rollup']['array'][0]['email']}) SET u.ep= row['properties']['ep']['title'][0]['plain_text'], u.pageID= row['properties']['personName']['relation'][0]['id'], u.name= row['properties']['name']['formula']['string'], u.oppsID= row['properties']['opps']['relation'][0]['id'], u.pin= row['properties']['pin']['rich_text'][0]['plain_text'] MERGE (p:Page{ep: row['properties']['ep']['title'][0]['plain_text']}) ON CREATE SET p.uploads = [] SET p.heroMedia= row['properties']['heroMedia']['url'], p.noteMedia= row['properties']['noteMedia']['url'], p.aboutMedia= row['properties']['aboutMedia']['url'], p.hubDescription= row['properties']['hubDescription']['rich_text'][0]['plain_text'], p.projectDevelopment= row['properties']['*projectDevelopment']['rich_text'][0]['plain_text'], p.announcements= row['properties']['*announcements']['rich_text'][0]['plain_text'], p.projectProspect= row['properties']['*projectProspect']['rich_text'][0]['plain_text'], p.projectDelivered= row['properties']['*projectDelivered']['rich_text'][0]['plain_text'], p.customNote= row['properties']['customNote']['rich_text'][0]['plain_text'], p.houseCount= row['properties']['houseCount']['rich_text'][0]['plain_text'], p.scopeSummary= row['properties']['scopeSummary']['rich_text'][0]['plain_text'], p.proposalSubmitDate= row['properties']['_proposalSubmitDate']['formula']['string'], p.elevationCount = row['properties']['elevationCount']['rich_text'][0]['plain_text'], p.proposalSignedDate= row['properties']['proposalSignedDate']['rollup']['array'][0]['date'], p.stage= row['properties']['stage']['rollup']['array'][0]['select']['name'], p.deliverables= row['properties']['deliverables']['rich_text'][0]['plain_text'], p.clientReqs= row['properties']['clientReqs']['rich_text'][0]['plain_text'], p.proposalAmount = row['properties']['proposalAmount']['number'], p.hubMedia = row['properties']['hubMedia']['url'], p.greetingName = row['properties']['greetingName']['rich_text'][0]['plain_text'] MERGE (u)-[:HAS_PAGE]->(p)) return count(*)") (defn gcp-neo4j-query [query & args] (db/with-transaction neo4j-gcp--bolt-db tx (vec (query tx (first args))))) ;; (db/defquery updating-users-v3 ;; "WITH $results as results ;; FOREACH(row in results | MERGE (p:Proposal {tfToken: row['proposal']['tfToken']}) SET p = row['proposal']) return count(*)") ;; (def new-activity (query-tester get-Nodes)) ;; (def old-activity (old-query-tester get-Nodes)) ;; user specific ;; (count old-activity) ;; old-activity ;; (def new-proposal (query-tester get-Nodes)) ;; (def old-proposal (old-query-tester get-Nodes)) ;; (count new-proposal) ;; (query-tester updating-users-v3 {:results old-proposal}) ;; (for [user users] ;; ((user :user) :email)) (comment (def new-pages (query-tester get-Nodes)) (count new-pages) (count old-pages) (query-tester updating-users-v2 {:results old-pages}) (def old-pages (old-query-tester get-Nodes)) (for [page old-pages] ((page :page) :ep)) (old-query-tester count-nodes) (defn old-query-tester [query & args] (db/with-transaction neo4j-bolt-db tx (vec (query tx (first args))))) (old-query-tester get-specific-nodes {:node "LoginActivity"}) (old-query-tester get-investor-nodes) (type users) (def new-users (query-tester user-nodes)) (def old-users (old-query-tester user-nodes)) (count new-users) new-users (query-tester updating-users-v1 {:results old-users}) (for [user users] (user :user)) (let [(for [user users] (assoc users1 user))] users1) (let [user [:user] (old-query-tester user-nodes)] user) (query-tester match-user-email {:email "jwall@braincache.io"}) ((first (query-tester all_nodes)) :Admin) (old-query-tester all_nodes) (def old-nodes (old-query-tester all_nodes)) ((nth old-nodes 0) :Label) old-nodes (select-keys old-nodes [:Nodes]) (query-tester updating-users-pages {:results results}) (query-tester count_nodes)) (comment comps = '''CALL apoc.periodic.iterate('MATCH (u:User) RETURN u, apoc.static.getAll("notion") as notion', 'CALL apoc.load.jsonParams(notion.pageUrl + u.pageID, {Authorization: notion.token,`Notion-Version`: "2021-08-16"}, null) yield value with u, value set u.company = value["properties"]["comp"]["formula"]["string"]',{})''' opps = '''CALL apoc.periodic.iterate('MATCH (u:User) return u, apoc.static.getAll(\\'notion\\') as notion', 'CALL apoc.load.jsonParams(notion.pageUrl + u.oppsID, {Authorization: notion.token,`Notion-Version`: \\'2021-08-16\\'},null) yield value with u, value set u.opps = value[\\'properties\\'][\\'Property Name\\'][\\'title\\'][0][\\'plain_text\\']',{})''' users_pages = '''WITH apoc.static.getAll('notion') as notion CALL apoc.load.jsonParams(notion.dbUrl + 'de297bebecf84283bafa4a51b174f326' + '/query', {Authorization: 'Bearer ' + notion.token,`Notion-Version`: '2021-08-16'},'',null,{method:'POST'}) YIELD value WITH value.results as results FOREACH(row in results | MERGE (u:User{email: row['properties']['personEmail']['rollup']['array'][0]['email']}) SET u.ep= row['properties']['ep']['title'][0]['plain_text'], u.pageID= row['properties']['personName']['relation'][0]['id'], u.name= row['properties']['name']['formula']['string'], u.oppsID= row['properties']['opps']['relation'][0]['id'], u.pin= row['properties']['pin']['rich_text'][0]['plain_text'] MERGE (p:Page{ep: row['properties']['ep']['title'][0]['plain_text']}) ON CREATE SET p.uploads = [] SET p.heroMedia= row['properties']['heroMedia']['url'], p.noteMedia= row['properties']['noteMedia']['url'], p.aboutMedia= row['properties']['aboutMedia']['url'], p.hubDescription= row['properties']['hubDescription']['rich_text'][0]['plain_text'], p.projectDevelopment= row['properties']['*projectDevelopment']['rich_text'][0]['plain_text'], p.announcements= row['properties']['*announcements']['rich_text'][0]['plain_text'], p.projectProspect= row['properties']['*projectProspect']['rich_text'][0]['plain_text'], p.projectDelivered= row['properties']['*projectDelivered']['rich_text'][0]['plain_text'], p.customNote= row['properties']['customNote']['rich_text'][0]['plain_text'], p.houseCount= row['properties']['houseCount']['rich_text'][0]['plain_text'], p.scopeSummary= row['properties']['scopeSummary']['rich_text'][0]['plain_text'], p.proposalSubmitDate= row['properties']['_proposalSubmitDate']['formula']['string'], p.elevationCount = row['properties']['elevationCount']['rich_text'][0]['plain_text'], p.proposalSignedDate= row['properties']['proposalSignedDate']['rollup']['array'][0]['date'], p.stage= row['properties']['stage']['rollup']['array'][0]['select']['name'], p.deliverables= row['properties']['deliverables']['rich_text'][0]['plain_text'], p.clientReqs= row['properties']['clientReqs']['rich_text'][0]['plain_text'], p.proposalAmount = row['properties']['proposalAmount']['number'], p.hubMedia = row['properties']['hubMedia']['url'], p.greetingName = row['properties']['greetingName']['rich_text'][0]['plain_text'] MERGE (u)-[:HAS_PAGE]->(p)) return count(*)''')
13745
(ns com.example.components.notion-query (:require [neo4j-clj.core :as db] [org.httpkit.client :as http] [clojure.data.json :as json] ;; [org.httpkit.sni-client :as sni-client] [mount.core :refer [defstate]]) (:import (java.net URI)) ) ;; Change default client for your whole application: ;; (alter-var-root #'org.httpkit.client/*default-client* (fn [_] sni-client/default-client)) (def neo4j-gcp-bolt-db (db/connect (URI. "bolt://172.16.17.32:7687") "neo4j" "jwall")) (def neo4j-bolt-db (db/connect (URI. "bolt://172.16.58.3:7687") "jwall" "2688")) (def token "<KEY>") (def notion-customer-db-id "de297bebecf84283bafa4a51b174f326") (def notion-customers (let [options {:headers {"Authorization" (str "Bearer " token) "Notion-Version" "2021-08-16" "Content-Type" "application/json"}} {:keys [status headers body error] :as resp} @(http/post (format "https://api.notion.com/v1/databases/%s/query" notion-customer-db-id) options)] (if error (println "Failed, exception: " error) (json/read-str body)))) ;; (defn from-notion-idx-customer-email [& args] (get-in (((((get-in (first args) ["results" (first (rest args))]) "properties") "personEmail") "rollup") "array") [(first (rest args)) "email"])) ;; notion-customers ;; (def from-notion-idx-customer-email (get-in (((((get-in notion-customers ["results" 0]) "properties") "personEmail") "rollup") "array") [0 "email"])) ;; (from-notion-idx-customer-email [notion-customers 0]) ;; from-notion-idx-customer-email ;; (keys ((get-in notion-customers ["results" 0]) "properties")) (db/defquery match-user-email "MATCH (u:User {email: $email}) RETURN u as user") (db/defquery all_nodes "Match (n) return n{.*} as Nodes, labels(n) as Label") (db/defquery count-nodes "Match (n) return count(n)") (db/defquery type-nodes "Match (n) return distinct labels(n)") (db/defquery get-specific-nodes "MATCH (n) WHERE $node IN labels(n) RETURN n as node") (db/defquery missing-nodes "Match (n) where labels(n) is null return n, id(n)") (db/defquery user-nodes "MATCH (u:User) RETURN u as user") (db/defquery get-activity<-user-nodes "MATCH (n:Activity)<-[]-(u) where u.email is not null and (not (u.email contains 'jwall@')) RETURN n as activity, u as user") (db/defquery get-investor-nodes "MATCH (n:Investor) RETURN n as investor") (db/defquery updating-users-v1 "WITH $results as results FOREACH(row in results | MERGE (u:User{email: row['user']['email']}) SET u = row['user']) return count(*)") (db/defquery updating-Page-v1 "WITH $results as results FOREACH(row in results | MERGE (p:Page {ep: row['page']['ep']}) SET p = row['page']) return count(*)") (db/defquery updating-Proposal-v1 "WITH $results as results FOREACH(row in results | MERGE (p:Proposal {tfToken: row['proposal']['tfToken']}) SET p = row['proposal']) return count(*)") ;; updating-Investor-v1 ;; updating-LoginActivity-v1 (db/defquery updating-users-pages "WITH $results as results FOREACH(row in results | MERGE (u:User{email: row['properties']['personEmail']['rollup']['array'][0]['email']}) SET u.ep= row['properties']['ep']['title'][0]['plain_text'], u.pageID= row['properties']['personName']['relation'][0]['id'], u.name= row['properties']['name']['formula']['string'], u.oppsID= row['properties']['opps']['relation'][0]['id'], u.pin= row['properties']['pin']['rich_text'][0]['plain_text'] MERGE (p:Page{ep: row['properties']['ep']['title'][0]['plain_text']}) ON CREATE SET p.uploads = [] SET p.heroMedia= row['properties']['heroMedia']['url'], p.noteMedia= row['properties']['noteMedia']['url'], p.aboutMedia= row['properties']['aboutMedia']['url'], p.hubDescription= row['properties']['hubDescription']['rich_text'][0]['plain_text'], p.projectDevelopment= row['properties']['*projectDevelopment']['rich_text'][0]['plain_text'], p.announcements= row['properties']['*announcements']['rich_text'][0]['plain_text'], p.projectProspect= row['properties']['*projectProspect']['rich_text'][0]['plain_text'], p.projectDelivered= row['properties']['*projectDelivered']['rich_text'][0]['plain_text'], p.customNote= row['properties']['customNote']['rich_text'][0]['plain_text'], p.houseCount= row['properties']['houseCount']['rich_text'][0]['plain_text'], p.scopeSummary= row['properties']['scopeSummary']['rich_text'][0]['plain_text'], p.proposalSubmitDate= row['properties']['_proposalSubmitDate']['formula']['string'], p.elevationCount = row['properties']['elevationCount']['rich_text'][0]['plain_text'], p.proposalSignedDate= row['properties']['proposalSignedDate']['rollup']['array'][0]['date'], p.stage= row['properties']['stage']['rollup']['array'][0]['select']['name'], p.deliverables= row['properties']['deliverables']['rich_text'][0]['plain_text'], p.clientReqs= row['properties']['clientReqs']['rich_text'][0]['plain_text'], p.proposalAmount = row['properties']['proposalAmount']['number'], p.hubMedia = row['properties']['hubMedia']['url'], p.greetingName = row['properties']['greetingName']['rich_text'][0]['plain_text'] MERGE (u)-[:HAS_PAGE]->(p)) return count(*)") (defn gcp-neo4j-query [query & args] (db/with-transaction neo4j-gcp--bolt-db tx (vec (query tx (first args))))) ;; (db/defquery updating-users-v3 ;; "WITH $results as results ;; FOREACH(row in results | MERGE (p:Proposal {tfToken: row['proposal']['tfToken']}) SET p = row['proposal']) return count(*)") ;; (def new-activity (query-tester get-Nodes)) ;; (def old-activity (old-query-tester get-Nodes)) ;; user specific ;; (count old-activity) ;; old-activity ;; (def new-proposal (query-tester get-Nodes)) ;; (def old-proposal (old-query-tester get-Nodes)) ;; (count new-proposal) ;; (query-tester updating-users-v3 {:results old-proposal}) ;; (for [user users] ;; ((user :user) :email)) (comment (def new-pages (query-tester get-Nodes)) (count new-pages) (count old-pages) (query-tester updating-users-v2 {:results old-pages}) (def old-pages (old-query-tester get-Nodes)) (for [page old-pages] ((page :page) :ep)) (old-query-tester count-nodes) (defn old-query-tester [query & args] (db/with-transaction neo4j-bolt-db tx (vec (query tx (first args))))) (old-query-tester get-specific-nodes {:node "LoginActivity"}) (old-query-tester get-investor-nodes) (type users) (def new-users (query-tester user-nodes)) (def old-users (old-query-tester user-nodes)) (count new-users) new-users (query-tester updating-users-v1 {:results old-users}) (for [user users] (user :user)) (let [(for [user users] (assoc users1 user))] users1) (let [user [:user] (old-query-tester user-nodes)] user) (query-tester match-user-email {:email "<EMAIL>"}) ((first (query-tester all_nodes)) :Admin) (old-query-tester all_nodes) (def old-nodes (old-query-tester all_nodes)) ((nth old-nodes 0) :Label) old-nodes (select-keys old-nodes [:Nodes]) (query-tester updating-users-pages {:results results}) (query-tester count_nodes)) (comment comps = '''CALL apoc.periodic.iterate('MATCH (u:User) RETURN u, apoc.static.getAll("notion") as notion', 'CALL apoc.load.jsonParams(notion.pageUrl + u.pageID, {Authorization: notion.token,`Notion-Version`: "2021-08-16"}, null) yield value with u, value set u.company = value["properties"]["comp"]["formula"]["string"]',{})''' opps = '''CALL apoc.periodic.iterate('MATCH (u:User) return u, apoc.static.getAll(\\'notion\\') as notion', 'CALL apoc.load.jsonParams(notion.pageUrl + u.oppsID, {Authorization: notion.token,`Notion-Version`: \\'2021-08-16\\'},null) yield value with u, value set u.opps = value[\\'properties\\'][\\'Property Name\\'][\\'title\\'][0][\\'plain_text\\']',{})''' users_pages = '''WITH apoc.static.getAll('notion') as notion CALL apoc.load.jsonParams(notion.dbUrl + 'de297bebecf84283bafa4a51b174f326' + '/query', {Authorization: 'Bearer ' + notion.token,`Notion-Version`: '2021-08-16'},'',null,{method:'POST'}) YIELD value WITH value.results as results FOREACH(row in results | MERGE (u:User{email: row['properties']['personEmail']['rollup']['array'][0]['email']}) SET u.ep= row['properties']['ep']['title'][0]['plain_text'], u.pageID= row['properties']['personName']['relation'][0]['id'], u.name= row['properties']['name']['formula']['string'], u.oppsID= row['properties']['opps']['relation'][0]['id'], u.pin= row['properties']['pin']['rich_text'][0]['plain_text'] MERGE (p:Page{ep: row['properties']['ep']['title'][0]['plain_text']}) ON CREATE SET p.uploads = [] SET p.heroMedia= row['properties']['heroMedia']['url'], p.noteMedia= row['properties']['noteMedia']['url'], p.aboutMedia= row['properties']['aboutMedia']['url'], p.hubDescription= row['properties']['hubDescription']['rich_text'][0]['plain_text'], p.projectDevelopment= row['properties']['*projectDevelopment']['rich_text'][0]['plain_text'], p.announcements= row['properties']['*announcements']['rich_text'][0]['plain_text'], p.projectProspect= row['properties']['*projectProspect']['rich_text'][0]['plain_text'], p.projectDelivered= row['properties']['*projectDelivered']['rich_text'][0]['plain_text'], p.customNote= row['properties']['customNote']['rich_text'][0]['plain_text'], p.houseCount= row['properties']['houseCount']['rich_text'][0]['plain_text'], p.scopeSummary= row['properties']['scopeSummary']['rich_text'][0]['plain_text'], p.proposalSubmitDate= row['properties']['_proposalSubmitDate']['formula']['string'], p.elevationCount = row['properties']['elevationCount']['rich_text'][0]['plain_text'], p.proposalSignedDate= row['properties']['proposalSignedDate']['rollup']['array'][0]['date'], p.stage= row['properties']['stage']['rollup']['array'][0]['select']['name'], p.deliverables= row['properties']['deliverables']['rich_text'][0]['plain_text'], p.clientReqs= row['properties']['clientReqs']['rich_text'][0]['plain_text'], p.proposalAmount = row['properties']['proposalAmount']['number'], p.hubMedia = row['properties']['hubMedia']['url'], p.greetingName = row['properties']['greetingName']['rich_text'][0]['plain_text'] MERGE (u)-[:HAS_PAGE]->(p)) return count(*)''')
true
(ns com.example.components.notion-query (:require [neo4j-clj.core :as db] [org.httpkit.client :as http] [clojure.data.json :as json] ;; [org.httpkit.sni-client :as sni-client] [mount.core :refer [defstate]]) (:import (java.net URI)) ) ;; Change default client for your whole application: ;; (alter-var-root #'org.httpkit.client/*default-client* (fn [_] sni-client/default-client)) (def neo4j-gcp-bolt-db (db/connect (URI. "bolt://PI:IP_ADDRESS:172.16.17.32END_PI:7687") "neo4j" "jwall")) (def neo4j-bolt-db (db/connect (URI. "bolt://PI:IP_ADDRESS:172.16.58.3END_PI:7687") "jwall" "2688")) (def token "PI:KEY:<KEY>END_PI") (def notion-customer-db-id "de297bebecf84283bafa4a51b174f326") (def notion-customers (let [options {:headers {"Authorization" (str "Bearer " token) "Notion-Version" "2021-08-16" "Content-Type" "application/json"}} {:keys [status headers body error] :as resp} @(http/post (format "https://api.notion.com/v1/databases/%s/query" notion-customer-db-id) options)] (if error (println "Failed, exception: " error) (json/read-str body)))) ;; (defn from-notion-idx-customer-email [& args] (get-in (((((get-in (first args) ["results" (first (rest args))]) "properties") "personEmail") "rollup") "array") [(first (rest args)) "email"])) ;; notion-customers ;; (def from-notion-idx-customer-email (get-in (((((get-in notion-customers ["results" 0]) "properties") "personEmail") "rollup") "array") [0 "email"])) ;; (from-notion-idx-customer-email [notion-customers 0]) ;; from-notion-idx-customer-email ;; (keys ((get-in notion-customers ["results" 0]) "properties")) (db/defquery match-user-email "MATCH (u:User {email: $email}) RETURN u as user") (db/defquery all_nodes "Match (n) return n{.*} as Nodes, labels(n) as Label") (db/defquery count-nodes "Match (n) return count(n)") (db/defquery type-nodes "Match (n) return distinct labels(n)") (db/defquery get-specific-nodes "MATCH (n) WHERE $node IN labels(n) RETURN n as node") (db/defquery missing-nodes "Match (n) where labels(n) is null return n, id(n)") (db/defquery user-nodes "MATCH (u:User) RETURN u as user") (db/defquery get-activity<-user-nodes "MATCH (n:Activity)<-[]-(u) where u.email is not null and (not (u.email contains 'jwall@')) RETURN n as activity, u as user") (db/defquery get-investor-nodes "MATCH (n:Investor) RETURN n as investor") (db/defquery updating-users-v1 "WITH $results as results FOREACH(row in results | MERGE (u:User{email: row['user']['email']}) SET u = row['user']) return count(*)") (db/defquery updating-Page-v1 "WITH $results as results FOREACH(row in results | MERGE (p:Page {ep: row['page']['ep']}) SET p = row['page']) return count(*)") (db/defquery updating-Proposal-v1 "WITH $results as results FOREACH(row in results | MERGE (p:Proposal {tfToken: row['proposal']['tfToken']}) SET p = row['proposal']) return count(*)") ;; updating-Investor-v1 ;; updating-LoginActivity-v1 (db/defquery updating-users-pages "WITH $results as results FOREACH(row in results | MERGE (u:User{email: row['properties']['personEmail']['rollup']['array'][0]['email']}) SET u.ep= row['properties']['ep']['title'][0]['plain_text'], u.pageID= row['properties']['personName']['relation'][0]['id'], u.name= row['properties']['name']['formula']['string'], u.oppsID= row['properties']['opps']['relation'][0]['id'], u.pin= row['properties']['pin']['rich_text'][0]['plain_text'] MERGE (p:Page{ep: row['properties']['ep']['title'][0]['plain_text']}) ON CREATE SET p.uploads = [] SET p.heroMedia= row['properties']['heroMedia']['url'], p.noteMedia= row['properties']['noteMedia']['url'], p.aboutMedia= row['properties']['aboutMedia']['url'], p.hubDescription= row['properties']['hubDescription']['rich_text'][0]['plain_text'], p.projectDevelopment= row['properties']['*projectDevelopment']['rich_text'][0]['plain_text'], p.announcements= row['properties']['*announcements']['rich_text'][0]['plain_text'], p.projectProspect= row['properties']['*projectProspect']['rich_text'][0]['plain_text'], p.projectDelivered= row['properties']['*projectDelivered']['rich_text'][0]['plain_text'], p.customNote= row['properties']['customNote']['rich_text'][0]['plain_text'], p.houseCount= row['properties']['houseCount']['rich_text'][0]['plain_text'], p.scopeSummary= row['properties']['scopeSummary']['rich_text'][0]['plain_text'], p.proposalSubmitDate= row['properties']['_proposalSubmitDate']['formula']['string'], p.elevationCount = row['properties']['elevationCount']['rich_text'][0]['plain_text'], p.proposalSignedDate= row['properties']['proposalSignedDate']['rollup']['array'][0]['date'], p.stage= row['properties']['stage']['rollup']['array'][0]['select']['name'], p.deliverables= row['properties']['deliverables']['rich_text'][0]['plain_text'], p.clientReqs= row['properties']['clientReqs']['rich_text'][0]['plain_text'], p.proposalAmount = row['properties']['proposalAmount']['number'], p.hubMedia = row['properties']['hubMedia']['url'], p.greetingName = row['properties']['greetingName']['rich_text'][0]['plain_text'] MERGE (u)-[:HAS_PAGE]->(p)) return count(*)") (defn gcp-neo4j-query [query & args] (db/with-transaction neo4j-gcp--bolt-db tx (vec (query tx (first args))))) ;; (db/defquery updating-users-v3 ;; "WITH $results as results ;; FOREACH(row in results | MERGE (p:Proposal {tfToken: row['proposal']['tfToken']}) SET p = row['proposal']) return count(*)") ;; (def new-activity (query-tester get-Nodes)) ;; (def old-activity (old-query-tester get-Nodes)) ;; user specific ;; (count old-activity) ;; old-activity ;; (def new-proposal (query-tester get-Nodes)) ;; (def old-proposal (old-query-tester get-Nodes)) ;; (count new-proposal) ;; (query-tester updating-users-v3 {:results old-proposal}) ;; (for [user users] ;; ((user :user) :email)) (comment (def new-pages (query-tester get-Nodes)) (count new-pages) (count old-pages) (query-tester updating-users-v2 {:results old-pages}) (def old-pages (old-query-tester get-Nodes)) (for [page old-pages] ((page :page) :ep)) (old-query-tester count-nodes) (defn old-query-tester [query & args] (db/with-transaction neo4j-bolt-db tx (vec (query tx (first args))))) (old-query-tester get-specific-nodes {:node "LoginActivity"}) (old-query-tester get-investor-nodes) (type users) (def new-users (query-tester user-nodes)) (def old-users (old-query-tester user-nodes)) (count new-users) new-users (query-tester updating-users-v1 {:results old-users}) (for [user users] (user :user)) (let [(for [user users] (assoc users1 user))] users1) (let [user [:user] (old-query-tester user-nodes)] user) (query-tester match-user-email {:email "PI:EMAIL:<EMAIL>END_PI"}) ((first (query-tester all_nodes)) :Admin) (old-query-tester all_nodes) (def old-nodes (old-query-tester all_nodes)) ((nth old-nodes 0) :Label) old-nodes (select-keys old-nodes [:Nodes]) (query-tester updating-users-pages {:results results}) (query-tester count_nodes)) (comment comps = '''CALL apoc.periodic.iterate('MATCH (u:User) RETURN u, apoc.static.getAll("notion") as notion', 'CALL apoc.load.jsonParams(notion.pageUrl + u.pageID, {Authorization: notion.token,`Notion-Version`: "2021-08-16"}, null) yield value with u, value set u.company = value["properties"]["comp"]["formula"]["string"]',{})''' opps = '''CALL apoc.periodic.iterate('MATCH (u:User) return u, apoc.static.getAll(\\'notion\\') as notion', 'CALL apoc.load.jsonParams(notion.pageUrl + u.oppsID, {Authorization: notion.token,`Notion-Version`: \\'2021-08-16\\'},null) yield value with u, value set u.opps = value[\\'properties\\'][\\'Property Name\\'][\\'title\\'][0][\\'plain_text\\']',{})''' users_pages = '''WITH apoc.static.getAll('notion') as notion CALL apoc.load.jsonParams(notion.dbUrl + 'de297bebecf84283bafa4a51b174f326' + '/query', {Authorization: 'Bearer ' + notion.token,`Notion-Version`: '2021-08-16'},'',null,{method:'POST'}) YIELD value WITH value.results as results FOREACH(row in results | MERGE (u:User{email: row['properties']['personEmail']['rollup']['array'][0]['email']}) SET u.ep= row['properties']['ep']['title'][0]['plain_text'], u.pageID= row['properties']['personName']['relation'][0]['id'], u.name= row['properties']['name']['formula']['string'], u.oppsID= row['properties']['opps']['relation'][0]['id'], u.pin= row['properties']['pin']['rich_text'][0]['plain_text'] MERGE (p:Page{ep: row['properties']['ep']['title'][0]['plain_text']}) ON CREATE SET p.uploads = [] SET p.heroMedia= row['properties']['heroMedia']['url'], p.noteMedia= row['properties']['noteMedia']['url'], p.aboutMedia= row['properties']['aboutMedia']['url'], p.hubDescription= row['properties']['hubDescription']['rich_text'][0]['plain_text'], p.projectDevelopment= row['properties']['*projectDevelopment']['rich_text'][0]['plain_text'], p.announcements= row['properties']['*announcements']['rich_text'][0]['plain_text'], p.projectProspect= row['properties']['*projectProspect']['rich_text'][0]['plain_text'], p.projectDelivered= row['properties']['*projectDelivered']['rich_text'][0]['plain_text'], p.customNote= row['properties']['customNote']['rich_text'][0]['plain_text'], p.houseCount= row['properties']['houseCount']['rich_text'][0]['plain_text'], p.scopeSummary= row['properties']['scopeSummary']['rich_text'][0]['plain_text'], p.proposalSubmitDate= row['properties']['_proposalSubmitDate']['formula']['string'], p.elevationCount = row['properties']['elevationCount']['rich_text'][0]['plain_text'], p.proposalSignedDate= row['properties']['proposalSignedDate']['rollup']['array'][0]['date'], p.stage= row['properties']['stage']['rollup']['array'][0]['select']['name'], p.deliverables= row['properties']['deliverables']['rich_text'][0]['plain_text'], p.clientReqs= row['properties']['clientReqs']['rich_text'][0]['plain_text'], p.proposalAmount = row['properties']['proposalAmount']['number'], p.hubMedia = row['properties']['hubMedia']['url'], p.greetingName = row['properties']['greetingName']['rich_text'][0]['plain_text'] MERGE (u)-[:HAS_PAGE]->(p)) return count(*)''')
[ { "context": " :apex.response/body\n [{\"name\" \"Luna\"}\n {\"name\" \"Sven\"}]})))\n\n ", "end": 1005, "score": 0.9584062695503235, "start": 1001, "tag": "NAME", "value": "Luna" }, { "context": " [{\"name\" \"Luna\"}\n {\"name\" \"Sven\"}]})))\n\n :apex/validators\n ", "end": 1041, "score": 0.9738540053367615, "start": 1037, "tag": "NAME", "value": "Sven" } ]
test/juxt/apex/conditional_request_test.clj
SevereOverfl0w/apex
123
;; Copyright © 2020, JUXT LTD. (ns juxt.apex.conditional-request-test (:require [clojure.java.io :as io] [clojure.string :as str] [clojure.tools.logging :as log] [clojure.test :refer [deftest is testing]] [juxt.apex.request :refer [handler]] [juxt.apex.util :refer [to-rfc-1123-date-time from-rfc-1123-date-time]] [juxt.apex.yaml :as yaml] [juxt.apex.test-util :refer [call-handler]] [ring.mock.request :as mock])) ;; See https://developer.mozilla.org/en-US/docs/Web/HTTP/Conditional_requests (deftest cache-update-test (let [api (yaml/parse-string (slurp (io/resource "juxt/apex/openapi-examples/petstore.yaml"))) h (handler api {:apex/operations {"listPets" {:apex/action (fn [req callback raise] (callback (merge req {:apex.response/status 200 :apex.response/body [{"name" "Luna"} {"name" "Sven"}]}))) :apex/validators (fn [req callback raise] (callback ;; Expectation is to return a new request with ;; validators merged. (merge req {:apex/entity-tag ;; The purpose of this map is also to ;; indicate strong or weak validator strength. {:value "123"} :apex/last-modified {:value (java.time.Instant/parse "2012-12-04T04:21:00Z")}})))}}}) {:keys [status headers body]} @(call-handler h (-> (mock/request :get "http://petstore.swagger.io/v1/pets")))] (is (= 200 status)) (testing "cache-update" (let [last-modified-date (get headers "Last-Modified")] (testing "last-modified header returned as expected" (is (= "Tue, 4 Dec 2012 04:21:00 GMT" last-modified-date))) (let [{:keys [status headers body]} @(call-handler h (-> (mock/request :get "http://petstore.swagger.io/v1/pets") (mock/header "if-modified-since" last-modified-date) ))] (testing "304 if we use the same date in request" (is (= 304 status)))) (let [{:keys [status headers body]} @(call-handler h (-> (mock/request :get "http://petstore.swagger.io/v1/pets") (mock/header "if-modified-since" (to-rfc-1123-date-time (java.time.Instant/parse "2019-01-01T00:00:00Z")))))] (testing "304 if we use a future date in the request" (is (= 304 status)))) (let [{:keys [status headers body]} @(call-handler h (-> (mock/request :get "http://petstore.swagger.io/v1/pets") (mock/header "if-modified-since" (to-rfc-1123-date-time (java.time.Instant/parse "2010-01-01T00:00:00Z")))))] (testing "200 if we use a prior date in the request" (is (= 200 status))) (testing "last-modified header returned as normal when if-modified-since request header exists" (is (= "Tue, 4 Dec 2012 04:21:00 GMT" (get headers "Last-Modified")))))))))
107890
;; Copyright © 2020, JUXT LTD. (ns juxt.apex.conditional-request-test (:require [clojure.java.io :as io] [clojure.string :as str] [clojure.tools.logging :as log] [clojure.test :refer [deftest is testing]] [juxt.apex.request :refer [handler]] [juxt.apex.util :refer [to-rfc-1123-date-time from-rfc-1123-date-time]] [juxt.apex.yaml :as yaml] [juxt.apex.test-util :refer [call-handler]] [ring.mock.request :as mock])) ;; See https://developer.mozilla.org/en-US/docs/Web/HTTP/Conditional_requests (deftest cache-update-test (let [api (yaml/parse-string (slurp (io/resource "juxt/apex/openapi-examples/petstore.yaml"))) h (handler api {:apex/operations {"listPets" {:apex/action (fn [req callback raise] (callback (merge req {:apex.response/status 200 :apex.response/body [{"name" "<NAME>"} {"name" "<NAME>"}]}))) :apex/validators (fn [req callback raise] (callback ;; Expectation is to return a new request with ;; validators merged. (merge req {:apex/entity-tag ;; The purpose of this map is also to ;; indicate strong or weak validator strength. {:value "123"} :apex/last-modified {:value (java.time.Instant/parse "2012-12-04T04:21:00Z")}})))}}}) {:keys [status headers body]} @(call-handler h (-> (mock/request :get "http://petstore.swagger.io/v1/pets")))] (is (= 200 status)) (testing "cache-update" (let [last-modified-date (get headers "Last-Modified")] (testing "last-modified header returned as expected" (is (= "Tue, 4 Dec 2012 04:21:00 GMT" last-modified-date))) (let [{:keys [status headers body]} @(call-handler h (-> (mock/request :get "http://petstore.swagger.io/v1/pets") (mock/header "if-modified-since" last-modified-date) ))] (testing "304 if we use the same date in request" (is (= 304 status)))) (let [{:keys [status headers body]} @(call-handler h (-> (mock/request :get "http://petstore.swagger.io/v1/pets") (mock/header "if-modified-since" (to-rfc-1123-date-time (java.time.Instant/parse "2019-01-01T00:00:00Z")))))] (testing "304 if we use a future date in the request" (is (= 304 status)))) (let [{:keys [status headers body]} @(call-handler h (-> (mock/request :get "http://petstore.swagger.io/v1/pets") (mock/header "if-modified-since" (to-rfc-1123-date-time (java.time.Instant/parse "2010-01-01T00:00:00Z")))))] (testing "200 if we use a prior date in the request" (is (= 200 status))) (testing "last-modified header returned as normal when if-modified-since request header exists" (is (= "Tue, 4 Dec 2012 04:21:00 GMT" (get headers "Last-Modified")))))))))
true
;; Copyright © 2020, JUXT LTD. (ns juxt.apex.conditional-request-test (:require [clojure.java.io :as io] [clojure.string :as str] [clojure.tools.logging :as log] [clojure.test :refer [deftest is testing]] [juxt.apex.request :refer [handler]] [juxt.apex.util :refer [to-rfc-1123-date-time from-rfc-1123-date-time]] [juxt.apex.yaml :as yaml] [juxt.apex.test-util :refer [call-handler]] [ring.mock.request :as mock])) ;; See https://developer.mozilla.org/en-US/docs/Web/HTTP/Conditional_requests (deftest cache-update-test (let [api (yaml/parse-string (slurp (io/resource "juxt/apex/openapi-examples/petstore.yaml"))) h (handler api {:apex/operations {"listPets" {:apex/action (fn [req callback raise] (callback (merge req {:apex.response/status 200 :apex.response/body [{"name" "PI:NAME:<NAME>END_PI"} {"name" "PI:NAME:<NAME>END_PI"}]}))) :apex/validators (fn [req callback raise] (callback ;; Expectation is to return a new request with ;; validators merged. (merge req {:apex/entity-tag ;; The purpose of this map is also to ;; indicate strong or weak validator strength. {:value "123"} :apex/last-modified {:value (java.time.Instant/parse "2012-12-04T04:21:00Z")}})))}}}) {:keys [status headers body]} @(call-handler h (-> (mock/request :get "http://petstore.swagger.io/v1/pets")))] (is (= 200 status)) (testing "cache-update" (let [last-modified-date (get headers "Last-Modified")] (testing "last-modified header returned as expected" (is (= "Tue, 4 Dec 2012 04:21:00 GMT" last-modified-date))) (let [{:keys [status headers body]} @(call-handler h (-> (mock/request :get "http://petstore.swagger.io/v1/pets") (mock/header "if-modified-since" last-modified-date) ))] (testing "304 if we use the same date in request" (is (= 304 status)))) (let [{:keys [status headers body]} @(call-handler h (-> (mock/request :get "http://petstore.swagger.io/v1/pets") (mock/header "if-modified-since" (to-rfc-1123-date-time (java.time.Instant/parse "2019-01-01T00:00:00Z")))))] (testing "304 if we use a future date in the request" (is (= 304 status)))) (let [{:keys [status headers body]} @(call-handler h (-> (mock/request :get "http://petstore.swagger.io/v1/pets") (mock/header "if-modified-since" (to-rfc-1123-date-time (java.time.Instant/parse "2010-01-01T00:00:00Z")))))] (testing "200 if we use a prior date in the request" (is (= 200 status))) (testing "last-modified header returned as normal when if-modified-since request header exists" (is (= "Tue, 4 Dec 2012 04:21:00 GMT" (get headers "Last-Modified")))))))))
[ { "context": "a.rest.tips \"The Foursquare Tips API\"\n {:author \"William Lee (birryree\"}\n (:require [mochify.hiroba.rest :as ", "end": 78, "score": 0.9998712539672852, "start": 67, "tag": "NAME", "value": "William Lee" }, { "context": "The Foursquare Tips API\"\n {:author \"William Lee (birryree\"}\n (:require [mochify.hiroba.rest :as rest]))\n\n(", "end": 88, "score": 0.9993396401405334, "start": 80, "tag": "USERNAME", "value": "birryree" } ]
src/mochify/hiroba/rest/tips.clj
mochify/hiroba
0
(ns mochify.hiroba.rest.tips "The Foursquare Tips API" {:author "William Lee (birryree"} (:require [mochify.hiroba.rest :as rest])) (defn details "Get the details of a tip, including which users (especially friends) have marked the tip a to-do item. Required Parameters: * tip-id (string) - ID of the tip to detail. " ([tip-id] (rest/get (rest/userless-uri "tips" tip-id)))) (defn likes "Returns friends and a total count of users who have liked a tip." [tip-id] (rest/get (rest/userless-uri "tips" tip-id "likes"))) (defn listed "The list that this tip appears on. Optional Parameters: * :oauth_token (string) - If supplied, allows you to specify additional fields for the 'edited' parameter. * :edited (string) - Can be 'created', 'edited', 'followed', 'friends', or 'other'. Only 'other' is supported if the oauth_token is not supplied. " ([tip-id &{:as params}] (rest/get (rest/userless-uri "tips" tip-id "listed")))) (defn saves "Returns friends and a total count of users who have saved this tip." ([tip-id] (rest/get (rest/userless-uri "tips" tip-id "saves"))))
16613
(ns mochify.hiroba.rest.tips "The Foursquare Tips API" {:author "<NAME> (birryree"} (:require [mochify.hiroba.rest :as rest])) (defn details "Get the details of a tip, including which users (especially friends) have marked the tip a to-do item. Required Parameters: * tip-id (string) - ID of the tip to detail. " ([tip-id] (rest/get (rest/userless-uri "tips" tip-id)))) (defn likes "Returns friends and a total count of users who have liked a tip." [tip-id] (rest/get (rest/userless-uri "tips" tip-id "likes"))) (defn listed "The list that this tip appears on. Optional Parameters: * :oauth_token (string) - If supplied, allows you to specify additional fields for the 'edited' parameter. * :edited (string) - Can be 'created', 'edited', 'followed', 'friends', or 'other'. Only 'other' is supported if the oauth_token is not supplied. " ([tip-id &{:as params}] (rest/get (rest/userless-uri "tips" tip-id "listed")))) (defn saves "Returns friends and a total count of users who have saved this tip." ([tip-id] (rest/get (rest/userless-uri "tips" tip-id "saves"))))
true
(ns mochify.hiroba.rest.tips "The Foursquare Tips API" {:author "PI:NAME:<NAME>END_PI (birryree"} (:require [mochify.hiroba.rest :as rest])) (defn details "Get the details of a tip, including which users (especially friends) have marked the tip a to-do item. Required Parameters: * tip-id (string) - ID of the tip to detail. " ([tip-id] (rest/get (rest/userless-uri "tips" tip-id)))) (defn likes "Returns friends and a total count of users who have liked a tip." [tip-id] (rest/get (rest/userless-uri "tips" tip-id "likes"))) (defn listed "The list that this tip appears on. Optional Parameters: * :oauth_token (string) - If supplied, allows you to specify additional fields for the 'edited' parameter. * :edited (string) - Can be 'created', 'edited', 'followed', 'friends', or 'other'. Only 'other' is supported if the oauth_token is not supplied. " ([tip-id &{:as params}] (rest/get (rest/userless-uri "tips" tip-id "listed")))) (defn saves "Returns friends and a total count of users who have saved this tip." ([tip-id] (rest/get (rest/userless-uri "tips" tip-id "saves"))))
[ { "context": "hard))\n\n (should= \"player-x-selection\" (:name human))\n (should= \"player-x-selection\" (:name easy", "end": 9117, "score": 0.962439239025116, "start": 9112, "tag": "NAME", "value": "human" } ]
spec/cljs/ttt_reagent/core_spec.cljs
mdwhatcott/ttt-reagent
0
(ns ttt-reagent.core-spec (:require-macros [speclj.core :refer [describe context before it should= should-not= should-have-invoked with-stubs stub]]) (:require [speclj.core] [ttt-reagent.components :as components] [cljs.pprint :as pprint])) (defn parse-arena [arena grid-width] (let [box-count (* grid-width grid-width)] {:root (first arena) :attributes (second arena) :boxes (->> arena (drop 2) (take box-count) vec) :marks (->> arena (drop 2) (drop box-count) vec)})) (defn click-box! [index] (let [before (components/arena) parsed (parse-arena before 3) box (get (:boxes parsed) index) attributes (second box) on-click! (:on-click attributes)] (on-click!))) (defn assert-class [expected-class indices all-boxes] (let [boxes (map #(get all-boxes %) indices)] (doseq [box boxes :let [class (:class (second box))]] (should= class expected-class)))) (describe "Arena Component" (context "rendering - 3x3" (before (components/new-game! 3)) (context "empty grid" (it "renders empty boxes ready to be clicked" (let [rendered (components/arena) parsed (parse-arena rendered 3) root-attributes (:attributes parsed)] (should= :svg (:root parsed)) (should= "0 0 3 3" (:view-box root-attributes)) (doseq [box (:boxes parsed)] (let [tag (first box) box-attributes (second box)] (should= :rect tag) (should= 0.9 (:width box-attributes)) (should= 0.9 (:height box-attributes)) (should= :empty (:class box-attributes)))))) ; TODO: assert non-nil on-click ) (context "after first turn by X" (before (click-box! 0)) (it "renders the selected box without an on-click handler" (let [rendered (components/arena) parsed (parse-arena rendered 3) clicked-box (first (:boxes parsed)) tag (first clicked-box) config (second clicked-box)] (should= :rect tag) (should= 0.9 (:width config)) (should= 0.9 (:height config)) (should= :empty (:class config)) (should= nil (:on-click config)))) (it "switches the player/mark" (should= :O @components/mark)) (it "renders an 'X' in the clicked box" (let [rendered (components/arena) parsed (parse-arena rendered 3) clicked-box (first (:boxes parsed)) box-config (second clicked-box) mark (first (:marks parsed)) tag (first mark) attributes (second mark)] (should= :path tag) (should= (int (:x attributes)) (int (:x box-config))) (should= (int (:y attributes)) (int (:y box-config))))) ) (context "After X and O both take a turn" (before (click-box! 0) (click-box! 1)) (it "the player/mark gets switched back to 'X'" (should= :X @components/mark)) (it "renders an 'O' in the box that was clicked second" (let [rendered (components/arena) parsed (parse-arena rendered 3) clicked-box (second (:boxes parsed)) box-config (second clicked-box) mark (second (:marks parsed)) tag (first mark) attributes (second mark)] (should= :circle tag) (should= (int (:cx attributes)) (int (:x box-config))) (should= (int (:cy attributes)) (int (:y box-config))))) (it "composes the path of the rendered 'X' mark" (should= ["M 0.75 1.75 " ; upper-left "L 1.25 2.25 " ; lower-right "M 1.25 1.75 " ; upper-right "L 0.75 2.25 "] ; lower-left (components/compose-x-path 1 2))) ) (context "When a game ends in a win" (before (click-box! 0) ; X (click-box! 1) ; O (click-box! 2) ; X (click-box! 3) ; O (click-box! 4) ; X (click-box! 5) ; O (click-box! 6)) ; X (WINNING PLAY) (it "indicates winning/losing moves via background colors" (let [rendered (components/arena) parsed (parse-arena rendered 3) boxes (:boxes parsed)] (assert-class :winner [0 2 4 6] boxes) (assert-class :loser [1 3 5] boxes) (assert-class :empty [7 8] boxes))) ) (context "When starting over" (before (click-box! 0) (click-box! 1) (click-box! 2)) (it "resets the game" (let [button (components/start-over) click (:on-click (second button)) _ (click) mark @components/mark grid @components/grid moves (:moves grid)] (should= mark :X) (should= 0 (count moves))))) ) ) (defn parse-grid-size [component] (let [inputs (drop 2 component) div-radio-3x3 (first inputs) radio-3x3 (second div-radio-3x3) radio-config-3x3 (second radio-3x3) label-3x3 (nth div-radio-3x3 2) label-config-3x3 (second label-3x3) div-radio-4x4 (second inputs) radio-4x4 (second div-radio-4x4) radio-config-4x4 (second radio-4x4) label-4x4 (nth div-radio-4x4 2) label-config-4x4 (second label-4x4)] {:radio-3x3 radio-config-3x3 :radio-4x4 radio-config-4x4 :label-3x3 label-config-3x3 :label-4x4 label-config-4x4})) (describe "Grid Size Selection Component" (before (components/new-game! 3)) (it "defines radio buttons for each supported grid size" (let [parsed (parse-grid-size (components/grid-size-selection)) {:keys [radio-3x3 radio-4x4 label-3x3 label-4x4]} parsed] (should= :radio (:type radio-3x3)) (should= :radio (:type radio-4x4)) (should= "grid-size-selection" (:name radio-3x3)) (should= "grid-size-selection" (:name radio-4x4)) (should= (:id radio-3x3) (:for label-3x3)) (should= (:id radio-4x4) (:for label-4x4)) (should-not= (:id radio-3x3) (:id radio-4x4)))) (it "allows changing the grid size by resetting the game" (let [parsed (parse-grid-size (components/grid-size-selection)) on-click-4x4 (-> parsed :radio-4x4 :on-click) on-click-3x3 (-> parsed :radio-3x3 :on-click)] (click-box! 0) (on-click-4x4) (should= 4 (:width @components/grid)) (should= 0 (count (:filled-by-cell @components/grid))) (click-box! 0) (on-click-3x3) (should= 3 (:width @components/grid)) (should= 0 (count (:filled-by-cell @components/grid))))) (it "does nothing if the size clicked matches the current size" (let [parsed (parse-grid-size (components/grid-size-selection)) on-click-3x3 (-> parsed :radio-3x3 :on-click)] (click-box! 0) (on-click-3x3) (should= 1 (count (:filled-by-cell @components/grid))))) ) (defn parse-player-selection [component] (let [divs (drop 2 component) radios (map #(second (second %)) divs)] {:human (nth radios 0) :easy (nth radios 1) :medium (nth radios 2) :hard (nth radios 3)})) (defn select-player! [mark selected-player] (let [component (components/player-selection mark) parsed (parse-player-selection component) selection (:on-click (selected-player parsed))] (selection))) (defn assert-player-selected [mark selected-player] (select-player! mark selected-player) (should= selected-player (mark @components/players))) (defn assert-selected-player-makes-move [ai-level] (let [mark @components/mark grid @components/grid fake-ai (stub :ai {:return 1})] (with-redefs [ttt.ai/players {ai-level fake-ai}] (select-player! :X ai-level) (click-box! 0) (should= {1 :X} (:filled-by-cell @components/grid)) (should-have-invoked :ai {:with [mark grid]})))) (describe "Player Selection Component" (before (components/new-game! 3)) (it "defines grouped radio buttons for selecting the provided player" (let [component (components/player-selection :X) parsed (parse-player-selection component) {:keys [human easy medium hard]} parsed] (should= :radio (:type human)) (should= :radio (:type easy)) (should= :radio (:type medium)) (should= :radio (:type hard)) (should= "player-x-selection" (:name human)) (should= "player-x-selection" (:name easy)) (should= "player-x-selection" (:name medium)) (should= "player-x-selection" (:name hard)) (should= "player-x-selection--human" (:id human)) (should= "player-x-selection--easy-ai" (:id easy)) (should= "player-x-selection--medium-ai" (:id medium)) (should= "player-x-selection--hard-ai" (:id hard)))) (context "changing the 'X' player" (it "from human to easy ai and back" (assert-player-selected :X :easy) (assert-player-selected :X :human)) (it "from human to medium ai" (assert-player-selected :X :medium) (assert-player-selected :X :human)) (it "from human to hard ai and back" (assert-player-selected :X :hard) (assert-player-selected :X :human)) (it "does not interrupt the game currently in progress" (click-box! 0) (select-player! :X :easy) (should= 1 (count (:filled-by-cell @components/grid)))) ) (context "changing the 'O' player" (it "from human to easy ai and back" (assert-player-selected :O :easy) (assert-player-selected :O :human)) (it "from human to medium ai" (assert-player-selected :O :medium) (assert-player-selected :O :human)) (it "from human to hard ai and back" (assert-player-selected :O :hard) (assert-player-selected :O :human)) (it "does not interrupt the game currently in progress" (click-box! 0) (select-player! :O :easy) (should= 1 (count (:filled-by-cell @components/grid)))) ) (context "selected player makes move" (with-stubs) (it "allows the Easy AI to decide the move" (assert-selected-player-makes-move :easy)) (it "allows the Medium AI to decide the move" (assert-selected-player-makes-move :medium)) (it "allows the Hard AI to decide the move" (assert-selected-player-makes-move :hard)) ) )
22891
(ns ttt-reagent.core-spec (:require-macros [speclj.core :refer [describe context before it should= should-not= should-have-invoked with-stubs stub]]) (:require [speclj.core] [ttt-reagent.components :as components] [cljs.pprint :as pprint])) (defn parse-arena [arena grid-width] (let [box-count (* grid-width grid-width)] {:root (first arena) :attributes (second arena) :boxes (->> arena (drop 2) (take box-count) vec) :marks (->> arena (drop 2) (drop box-count) vec)})) (defn click-box! [index] (let [before (components/arena) parsed (parse-arena before 3) box (get (:boxes parsed) index) attributes (second box) on-click! (:on-click attributes)] (on-click!))) (defn assert-class [expected-class indices all-boxes] (let [boxes (map #(get all-boxes %) indices)] (doseq [box boxes :let [class (:class (second box))]] (should= class expected-class)))) (describe "Arena Component" (context "rendering - 3x3" (before (components/new-game! 3)) (context "empty grid" (it "renders empty boxes ready to be clicked" (let [rendered (components/arena) parsed (parse-arena rendered 3) root-attributes (:attributes parsed)] (should= :svg (:root parsed)) (should= "0 0 3 3" (:view-box root-attributes)) (doseq [box (:boxes parsed)] (let [tag (first box) box-attributes (second box)] (should= :rect tag) (should= 0.9 (:width box-attributes)) (should= 0.9 (:height box-attributes)) (should= :empty (:class box-attributes)))))) ; TODO: assert non-nil on-click ) (context "after first turn by X" (before (click-box! 0)) (it "renders the selected box without an on-click handler" (let [rendered (components/arena) parsed (parse-arena rendered 3) clicked-box (first (:boxes parsed)) tag (first clicked-box) config (second clicked-box)] (should= :rect tag) (should= 0.9 (:width config)) (should= 0.9 (:height config)) (should= :empty (:class config)) (should= nil (:on-click config)))) (it "switches the player/mark" (should= :O @components/mark)) (it "renders an 'X' in the clicked box" (let [rendered (components/arena) parsed (parse-arena rendered 3) clicked-box (first (:boxes parsed)) box-config (second clicked-box) mark (first (:marks parsed)) tag (first mark) attributes (second mark)] (should= :path tag) (should= (int (:x attributes)) (int (:x box-config))) (should= (int (:y attributes)) (int (:y box-config))))) ) (context "After X and O both take a turn" (before (click-box! 0) (click-box! 1)) (it "the player/mark gets switched back to 'X'" (should= :X @components/mark)) (it "renders an 'O' in the box that was clicked second" (let [rendered (components/arena) parsed (parse-arena rendered 3) clicked-box (second (:boxes parsed)) box-config (second clicked-box) mark (second (:marks parsed)) tag (first mark) attributes (second mark)] (should= :circle tag) (should= (int (:cx attributes)) (int (:x box-config))) (should= (int (:cy attributes)) (int (:y box-config))))) (it "composes the path of the rendered 'X' mark" (should= ["M 0.75 1.75 " ; upper-left "L 1.25 2.25 " ; lower-right "M 1.25 1.75 " ; upper-right "L 0.75 2.25 "] ; lower-left (components/compose-x-path 1 2))) ) (context "When a game ends in a win" (before (click-box! 0) ; X (click-box! 1) ; O (click-box! 2) ; X (click-box! 3) ; O (click-box! 4) ; X (click-box! 5) ; O (click-box! 6)) ; X (WINNING PLAY) (it "indicates winning/losing moves via background colors" (let [rendered (components/arena) parsed (parse-arena rendered 3) boxes (:boxes parsed)] (assert-class :winner [0 2 4 6] boxes) (assert-class :loser [1 3 5] boxes) (assert-class :empty [7 8] boxes))) ) (context "When starting over" (before (click-box! 0) (click-box! 1) (click-box! 2)) (it "resets the game" (let [button (components/start-over) click (:on-click (second button)) _ (click) mark @components/mark grid @components/grid moves (:moves grid)] (should= mark :X) (should= 0 (count moves))))) ) ) (defn parse-grid-size [component] (let [inputs (drop 2 component) div-radio-3x3 (first inputs) radio-3x3 (second div-radio-3x3) radio-config-3x3 (second radio-3x3) label-3x3 (nth div-radio-3x3 2) label-config-3x3 (second label-3x3) div-radio-4x4 (second inputs) radio-4x4 (second div-radio-4x4) radio-config-4x4 (second radio-4x4) label-4x4 (nth div-radio-4x4 2) label-config-4x4 (second label-4x4)] {:radio-3x3 radio-config-3x3 :radio-4x4 radio-config-4x4 :label-3x3 label-config-3x3 :label-4x4 label-config-4x4})) (describe "Grid Size Selection Component" (before (components/new-game! 3)) (it "defines radio buttons for each supported grid size" (let [parsed (parse-grid-size (components/grid-size-selection)) {:keys [radio-3x3 radio-4x4 label-3x3 label-4x4]} parsed] (should= :radio (:type radio-3x3)) (should= :radio (:type radio-4x4)) (should= "grid-size-selection" (:name radio-3x3)) (should= "grid-size-selection" (:name radio-4x4)) (should= (:id radio-3x3) (:for label-3x3)) (should= (:id radio-4x4) (:for label-4x4)) (should-not= (:id radio-3x3) (:id radio-4x4)))) (it "allows changing the grid size by resetting the game" (let [parsed (parse-grid-size (components/grid-size-selection)) on-click-4x4 (-> parsed :radio-4x4 :on-click) on-click-3x3 (-> parsed :radio-3x3 :on-click)] (click-box! 0) (on-click-4x4) (should= 4 (:width @components/grid)) (should= 0 (count (:filled-by-cell @components/grid))) (click-box! 0) (on-click-3x3) (should= 3 (:width @components/grid)) (should= 0 (count (:filled-by-cell @components/grid))))) (it "does nothing if the size clicked matches the current size" (let [parsed (parse-grid-size (components/grid-size-selection)) on-click-3x3 (-> parsed :radio-3x3 :on-click)] (click-box! 0) (on-click-3x3) (should= 1 (count (:filled-by-cell @components/grid))))) ) (defn parse-player-selection [component] (let [divs (drop 2 component) radios (map #(second (second %)) divs)] {:human (nth radios 0) :easy (nth radios 1) :medium (nth radios 2) :hard (nth radios 3)})) (defn select-player! [mark selected-player] (let [component (components/player-selection mark) parsed (parse-player-selection component) selection (:on-click (selected-player parsed))] (selection))) (defn assert-player-selected [mark selected-player] (select-player! mark selected-player) (should= selected-player (mark @components/players))) (defn assert-selected-player-makes-move [ai-level] (let [mark @components/mark grid @components/grid fake-ai (stub :ai {:return 1})] (with-redefs [ttt.ai/players {ai-level fake-ai}] (select-player! :X ai-level) (click-box! 0) (should= {1 :X} (:filled-by-cell @components/grid)) (should-have-invoked :ai {:with [mark grid]})))) (describe "Player Selection Component" (before (components/new-game! 3)) (it "defines grouped radio buttons for selecting the provided player" (let [component (components/player-selection :X) parsed (parse-player-selection component) {:keys [human easy medium hard]} parsed] (should= :radio (:type human)) (should= :radio (:type easy)) (should= :radio (:type medium)) (should= :radio (:type hard)) (should= "player-x-selection" (:name <NAME>)) (should= "player-x-selection" (:name easy)) (should= "player-x-selection" (:name medium)) (should= "player-x-selection" (:name hard)) (should= "player-x-selection--human" (:id human)) (should= "player-x-selection--easy-ai" (:id easy)) (should= "player-x-selection--medium-ai" (:id medium)) (should= "player-x-selection--hard-ai" (:id hard)))) (context "changing the 'X' player" (it "from human to easy ai and back" (assert-player-selected :X :easy) (assert-player-selected :X :human)) (it "from human to medium ai" (assert-player-selected :X :medium) (assert-player-selected :X :human)) (it "from human to hard ai and back" (assert-player-selected :X :hard) (assert-player-selected :X :human)) (it "does not interrupt the game currently in progress" (click-box! 0) (select-player! :X :easy) (should= 1 (count (:filled-by-cell @components/grid)))) ) (context "changing the 'O' player" (it "from human to easy ai and back" (assert-player-selected :O :easy) (assert-player-selected :O :human)) (it "from human to medium ai" (assert-player-selected :O :medium) (assert-player-selected :O :human)) (it "from human to hard ai and back" (assert-player-selected :O :hard) (assert-player-selected :O :human)) (it "does not interrupt the game currently in progress" (click-box! 0) (select-player! :O :easy) (should= 1 (count (:filled-by-cell @components/grid)))) ) (context "selected player makes move" (with-stubs) (it "allows the Easy AI to decide the move" (assert-selected-player-makes-move :easy)) (it "allows the Medium AI to decide the move" (assert-selected-player-makes-move :medium)) (it "allows the Hard AI to decide the move" (assert-selected-player-makes-move :hard)) ) )
true
(ns ttt-reagent.core-spec (:require-macros [speclj.core :refer [describe context before it should= should-not= should-have-invoked with-stubs stub]]) (:require [speclj.core] [ttt-reagent.components :as components] [cljs.pprint :as pprint])) (defn parse-arena [arena grid-width] (let [box-count (* grid-width grid-width)] {:root (first arena) :attributes (second arena) :boxes (->> arena (drop 2) (take box-count) vec) :marks (->> arena (drop 2) (drop box-count) vec)})) (defn click-box! [index] (let [before (components/arena) parsed (parse-arena before 3) box (get (:boxes parsed) index) attributes (second box) on-click! (:on-click attributes)] (on-click!))) (defn assert-class [expected-class indices all-boxes] (let [boxes (map #(get all-boxes %) indices)] (doseq [box boxes :let [class (:class (second box))]] (should= class expected-class)))) (describe "Arena Component" (context "rendering - 3x3" (before (components/new-game! 3)) (context "empty grid" (it "renders empty boxes ready to be clicked" (let [rendered (components/arena) parsed (parse-arena rendered 3) root-attributes (:attributes parsed)] (should= :svg (:root parsed)) (should= "0 0 3 3" (:view-box root-attributes)) (doseq [box (:boxes parsed)] (let [tag (first box) box-attributes (second box)] (should= :rect tag) (should= 0.9 (:width box-attributes)) (should= 0.9 (:height box-attributes)) (should= :empty (:class box-attributes)))))) ; TODO: assert non-nil on-click ) (context "after first turn by X" (before (click-box! 0)) (it "renders the selected box without an on-click handler" (let [rendered (components/arena) parsed (parse-arena rendered 3) clicked-box (first (:boxes parsed)) tag (first clicked-box) config (second clicked-box)] (should= :rect tag) (should= 0.9 (:width config)) (should= 0.9 (:height config)) (should= :empty (:class config)) (should= nil (:on-click config)))) (it "switches the player/mark" (should= :O @components/mark)) (it "renders an 'X' in the clicked box" (let [rendered (components/arena) parsed (parse-arena rendered 3) clicked-box (first (:boxes parsed)) box-config (second clicked-box) mark (first (:marks parsed)) tag (first mark) attributes (second mark)] (should= :path tag) (should= (int (:x attributes)) (int (:x box-config))) (should= (int (:y attributes)) (int (:y box-config))))) ) (context "After X and O both take a turn" (before (click-box! 0) (click-box! 1)) (it "the player/mark gets switched back to 'X'" (should= :X @components/mark)) (it "renders an 'O' in the box that was clicked second" (let [rendered (components/arena) parsed (parse-arena rendered 3) clicked-box (second (:boxes parsed)) box-config (second clicked-box) mark (second (:marks parsed)) tag (first mark) attributes (second mark)] (should= :circle tag) (should= (int (:cx attributes)) (int (:x box-config))) (should= (int (:cy attributes)) (int (:y box-config))))) (it "composes the path of the rendered 'X' mark" (should= ["M 0.75 1.75 " ; upper-left "L 1.25 2.25 " ; lower-right "M 1.25 1.75 " ; upper-right "L 0.75 2.25 "] ; lower-left (components/compose-x-path 1 2))) ) (context "When a game ends in a win" (before (click-box! 0) ; X (click-box! 1) ; O (click-box! 2) ; X (click-box! 3) ; O (click-box! 4) ; X (click-box! 5) ; O (click-box! 6)) ; X (WINNING PLAY) (it "indicates winning/losing moves via background colors" (let [rendered (components/arena) parsed (parse-arena rendered 3) boxes (:boxes parsed)] (assert-class :winner [0 2 4 6] boxes) (assert-class :loser [1 3 5] boxes) (assert-class :empty [7 8] boxes))) ) (context "When starting over" (before (click-box! 0) (click-box! 1) (click-box! 2)) (it "resets the game" (let [button (components/start-over) click (:on-click (second button)) _ (click) mark @components/mark grid @components/grid moves (:moves grid)] (should= mark :X) (should= 0 (count moves))))) ) ) (defn parse-grid-size [component] (let [inputs (drop 2 component) div-radio-3x3 (first inputs) radio-3x3 (second div-radio-3x3) radio-config-3x3 (second radio-3x3) label-3x3 (nth div-radio-3x3 2) label-config-3x3 (second label-3x3) div-radio-4x4 (second inputs) radio-4x4 (second div-radio-4x4) radio-config-4x4 (second radio-4x4) label-4x4 (nth div-radio-4x4 2) label-config-4x4 (second label-4x4)] {:radio-3x3 radio-config-3x3 :radio-4x4 radio-config-4x4 :label-3x3 label-config-3x3 :label-4x4 label-config-4x4})) (describe "Grid Size Selection Component" (before (components/new-game! 3)) (it "defines radio buttons for each supported grid size" (let [parsed (parse-grid-size (components/grid-size-selection)) {:keys [radio-3x3 radio-4x4 label-3x3 label-4x4]} parsed] (should= :radio (:type radio-3x3)) (should= :radio (:type radio-4x4)) (should= "grid-size-selection" (:name radio-3x3)) (should= "grid-size-selection" (:name radio-4x4)) (should= (:id radio-3x3) (:for label-3x3)) (should= (:id radio-4x4) (:for label-4x4)) (should-not= (:id radio-3x3) (:id radio-4x4)))) (it "allows changing the grid size by resetting the game" (let [parsed (parse-grid-size (components/grid-size-selection)) on-click-4x4 (-> parsed :radio-4x4 :on-click) on-click-3x3 (-> parsed :radio-3x3 :on-click)] (click-box! 0) (on-click-4x4) (should= 4 (:width @components/grid)) (should= 0 (count (:filled-by-cell @components/grid))) (click-box! 0) (on-click-3x3) (should= 3 (:width @components/grid)) (should= 0 (count (:filled-by-cell @components/grid))))) (it "does nothing if the size clicked matches the current size" (let [parsed (parse-grid-size (components/grid-size-selection)) on-click-3x3 (-> parsed :radio-3x3 :on-click)] (click-box! 0) (on-click-3x3) (should= 1 (count (:filled-by-cell @components/grid))))) ) (defn parse-player-selection [component] (let [divs (drop 2 component) radios (map #(second (second %)) divs)] {:human (nth radios 0) :easy (nth radios 1) :medium (nth radios 2) :hard (nth radios 3)})) (defn select-player! [mark selected-player] (let [component (components/player-selection mark) parsed (parse-player-selection component) selection (:on-click (selected-player parsed))] (selection))) (defn assert-player-selected [mark selected-player] (select-player! mark selected-player) (should= selected-player (mark @components/players))) (defn assert-selected-player-makes-move [ai-level] (let [mark @components/mark grid @components/grid fake-ai (stub :ai {:return 1})] (with-redefs [ttt.ai/players {ai-level fake-ai}] (select-player! :X ai-level) (click-box! 0) (should= {1 :X} (:filled-by-cell @components/grid)) (should-have-invoked :ai {:with [mark grid]})))) (describe "Player Selection Component" (before (components/new-game! 3)) (it "defines grouped radio buttons for selecting the provided player" (let [component (components/player-selection :X) parsed (parse-player-selection component) {:keys [human easy medium hard]} parsed] (should= :radio (:type human)) (should= :radio (:type easy)) (should= :radio (:type medium)) (should= :radio (:type hard)) (should= "player-x-selection" (:name PI:NAME:<NAME>END_PI)) (should= "player-x-selection" (:name easy)) (should= "player-x-selection" (:name medium)) (should= "player-x-selection" (:name hard)) (should= "player-x-selection--human" (:id human)) (should= "player-x-selection--easy-ai" (:id easy)) (should= "player-x-selection--medium-ai" (:id medium)) (should= "player-x-selection--hard-ai" (:id hard)))) (context "changing the 'X' player" (it "from human to easy ai and back" (assert-player-selected :X :easy) (assert-player-selected :X :human)) (it "from human to medium ai" (assert-player-selected :X :medium) (assert-player-selected :X :human)) (it "from human to hard ai and back" (assert-player-selected :X :hard) (assert-player-selected :X :human)) (it "does not interrupt the game currently in progress" (click-box! 0) (select-player! :X :easy) (should= 1 (count (:filled-by-cell @components/grid)))) ) (context "changing the 'O' player" (it "from human to easy ai and back" (assert-player-selected :O :easy) (assert-player-selected :O :human)) (it "from human to medium ai" (assert-player-selected :O :medium) (assert-player-selected :O :human)) (it "from human to hard ai and back" (assert-player-selected :O :hard) (assert-player-selected :O :human)) (it "does not interrupt the game currently in progress" (click-box! 0) (select-player! :O :easy) (should= 1 (count (:filled-by-cell @components/grid)))) ) (context "selected player makes move" (with-stubs) (it "allows the Easy AI to decide the move" (assert-selected-player-makes-move :easy)) (it "allows the Medium AI to decide the move" (assert-selected-player-makes-move :medium)) (it "allows the Hard AI to decide the move" (assert-selected-player-makes-move :hard)) ) )
[ { "context": "as included with require or use.\n;;;\n;;; @20161026 Jose Figueroa Martinez\n\n\n(require '[server.utils.watch :refer :all] :rel", "end": 792, "score": 0.9998703002929688, "start": 770, "tag": "NAME", "value": "Jose Figueroa Martinez" } ]
env.clj
jfigueroama/calendarizacion-mixta-demo
0
; ((:chsk-send! comm) :sente/all-users-without-uid [:evento/datos {:a 1 :b 2}]) ;;; ;;; A little explanation of some issues that someone could encounter ;;; working with Stuart Sierra's component: ;;; I needed to include all component namespaces to be able to start the ;;; system. I don't know why and I will find an answer, but for now, you ;;; need to include all component namespaces to start/stop the system ;;; from a nrepl. This issue doesn't happen on clojure started from ;;; java and including extra classpath. It just happen in the nrepl. ;;; ;;; I figured out the problem when I included some components and those ;;; component started, but not all of them. Just started the componets ;;; whose namespaces was included with require or use. ;;; ;;; @20161026 Jose Figueroa Martinez (require '[server.utils.watch :refer :all] :reload) (def ^:macro λ #'fn) (require '[clojure.string :as st] :reload) (require '[clojure.pprint :refer [pprint ]] :reload) (require '[clojure.java.jdbc :as j] :reload) (require '[com.stuartsierra.component :as component] :reload) (require '[clojure.java.jdbc :as j] :reload) (def config {:mode :dev ; :prod :db {:subname (str "//localhost:3306/ca?" "useUnicode=yes" "&characterEncoding=UTF-8" "&serverTimezone=UTC") :user "root" :db (str "ca?" "useUnicode=yes" "&characterEncoding=UTF-8" "&serverTimezone=UTC") :password "" :useUnicode "yes" :characterEncoding "UTF-8"} :webapp {:port 9001 :mode :dev :thread 4 :base-url "http://localhost:9001" :admin-site-url "http://localhost/ca/shp/?" :solver-call ["python" "main.py" "RS" :dir "./solver/lluvia"] }}) (reload (use 'server.core) "./src/server/core.clj") (def system nil) (defn reload-system [] (do (alter-var-root #'system component/stop) (alter-var-root #'system component/start))) (reload (require '[translator.core :as t]) "./src/translator/core.clj") (reload (require '[domain.core :refer :all]) "./src/domain/core.clj") (reload (require '[server.components.database :as database]) "./src/server/components/database.clj" (reload-system)) (reload (require '[server.components.communicator :as comm]) "./src/server/components/communicator.clj" (reload-system)) (reload (require '[server.components.handler :as handler]) "./src/server/components/handler.clj" (reload-system)) (reload (require '[server.components.webserver :as webserver]) "./src/server/components/webserver.clj" (reload-system)) (reload (require '[server.components.app :as app]) "./src/server/components/app.clj" (reload-system)) (reload (require '[server.handlers :as handlers]) "./src/server/handlers.clj" (reload-system)) (reload (require '[domain.horarios :as horarios]) "./src/domain/horarios.clj" (reload-system)) (def system (app config)) (alter-var-root #'system component/start) #_(alter-var-root #'system component/stop) (def dbc (:db system)) (def comm (:comm system))
9952
; ((:chsk-send! comm) :sente/all-users-without-uid [:evento/datos {:a 1 :b 2}]) ;;; ;;; A little explanation of some issues that someone could encounter ;;; working with Stuart Sierra's component: ;;; I needed to include all component namespaces to be able to start the ;;; system. I don't know why and I will find an answer, but for now, you ;;; need to include all component namespaces to start/stop the system ;;; from a nrepl. This issue doesn't happen on clojure started from ;;; java and including extra classpath. It just happen in the nrepl. ;;; ;;; I figured out the problem when I included some components and those ;;; component started, but not all of them. Just started the componets ;;; whose namespaces was included with require or use. ;;; ;;; @20161026 <NAME> (require '[server.utils.watch :refer :all] :reload) (def ^:macro λ #'fn) (require '[clojure.string :as st] :reload) (require '[clojure.pprint :refer [pprint ]] :reload) (require '[clojure.java.jdbc :as j] :reload) (require '[com.stuartsierra.component :as component] :reload) (require '[clojure.java.jdbc :as j] :reload) (def config {:mode :dev ; :prod :db {:subname (str "//localhost:3306/ca?" "useUnicode=yes" "&characterEncoding=UTF-8" "&serverTimezone=UTC") :user "root" :db (str "ca?" "useUnicode=yes" "&characterEncoding=UTF-8" "&serverTimezone=UTC") :password "" :useUnicode "yes" :characterEncoding "UTF-8"} :webapp {:port 9001 :mode :dev :thread 4 :base-url "http://localhost:9001" :admin-site-url "http://localhost/ca/shp/?" :solver-call ["python" "main.py" "RS" :dir "./solver/lluvia"] }}) (reload (use 'server.core) "./src/server/core.clj") (def system nil) (defn reload-system [] (do (alter-var-root #'system component/stop) (alter-var-root #'system component/start))) (reload (require '[translator.core :as t]) "./src/translator/core.clj") (reload (require '[domain.core :refer :all]) "./src/domain/core.clj") (reload (require '[server.components.database :as database]) "./src/server/components/database.clj" (reload-system)) (reload (require '[server.components.communicator :as comm]) "./src/server/components/communicator.clj" (reload-system)) (reload (require '[server.components.handler :as handler]) "./src/server/components/handler.clj" (reload-system)) (reload (require '[server.components.webserver :as webserver]) "./src/server/components/webserver.clj" (reload-system)) (reload (require '[server.components.app :as app]) "./src/server/components/app.clj" (reload-system)) (reload (require '[server.handlers :as handlers]) "./src/server/handlers.clj" (reload-system)) (reload (require '[domain.horarios :as horarios]) "./src/domain/horarios.clj" (reload-system)) (def system (app config)) (alter-var-root #'system component/start) #_(alter-var-root #'system component/stop) (def dbc (:db system)) (def comm (:comm system))
true
; ((:chsk-send! comm) :sente/all-users-without-uid [:evento/datos {:a 1 :b 2}]) ;;; ;;; A little explanation of some issues that someone could encounter ;;; working with Stuart Sierra's component: ;;; I needed to include all component namespaces to be able to start the ;;; system. I don't know why and I will find an answer, but for now, you ;;; need to include all component namespaces to start/stop the system ;;; from a nrepl. This issue doesn't happen on clojure started from ;;; java and including extra classpath. It just happen in the nrepl. ;;; ;;; I figured out the problem when I included some components and those ;;; component started, but not all of them. Just started the componets ;;; whose namespaces was included with require or use. ;;; ;;; @20161026 PI:NAME:<NAME>END_PI (require '[server.utils.watch :refer :all] :reload) (def ^:macro λ #'fn) (require '[clojure.string :as st] :reload) (require '[clojure.pprint :refer [pprint ]] :reload) (require '[clojure.java.jdbc :as j] :reload) (require '[com.stuartsierra.component :as component] :reload) (require '[clojure.java.jdbc :as j] :reload) (def config {:mode :dev ; :prod :db {:subname (str "//localhost:3306/ca?" "useUnicode=yes" "&characterEncoding=UTF-8" "&serverTimezone=UTC") :user "root" :db (str "ca?" "useUnicode=yes" "&characterEncoding=UTF-8" "&serverTimezone=UTC") :password "" :useUnicode "yes" :characterEncoding "UTF-8"} :webapp {:port 9001 :mode :dev :thread 4 :base-url "http://localhost:9001" :admin-site-url "http://localhost/ca/shp/?" :solver-call ["python" "main.py" "RS" :dir "./solver/lluvia"] }}) (reload (use 'server.core) "./src/server/core.clj") (def system nil) (defn reload-system [] (do (alter-var-root #'system component/stop) (alter-var-root #'system component/start))) (reload (require '[translator.core :as t]) "./src/translator/core.clj") (reload (require '[domain.core :refer :all]) "./src/domain/core.clj") (reload (require '[server.components.database :as database]) "./src/server/components/database.clj" (reload-system)) (reload (require '[server.components.communicator :as comm]) "./src/server/components/communicator.clj" (reload-system)) (reload (require '[server.components.handler :as handler]) "./src/server/components/handler.clj" (reload-system)) (reload (require '[server.components.webserver :as webserver]) "./src/server/components/webserver.clj" (reload-system)) (reload (require '[server.components.app :as app]) "./src/server/components/app.clj" (reload-system)) (reload (require '[server.handlers :as handlers]) "./src/server/handlers.clj" (reload-system)) (reload (require '[domain.horarios :as horarios]) "./src/domain/horarios.clj" (reload-system)) (def system (app config)) (alter-var-root #'system component/start) #_(alter-var-root #'system component/stop) (def dbc (:db system)) (def comm (:comm system))
[ { "context": "data-viewer-16\n :ui/react-key \"5537b4a1-589d-40d2-a98f-509c918f222e\"\n :ui/root\n ", "end": 750, "score": 0.9997468590736389, "start": 714, "tag": "KEY", "value": "5537b4a1-589d-40d2-a98f-509c918f222e" } ]
devcards/fulcro/inspect/ui/transactions_cards.cljs
Lokeh/fulcro-inspect
67
(ns fulcro.inspect.ui.transactions-cards (:require [devcards.core :refer-macros [defcard]] [fulcro-css.css :as css] [fulcro.client.cards :refer-macros [defcard-fulcro]] [fulcro.inspect.ui.transactions :as transactions] [fulcro.inspect.card-helpers :as card-helpers] [fulcro.client.primitives :as fp])) (def tx '{:tx [(fulcro.client.mutations/set-props {:fulcro.inspect.ui.data-viewer/expanded {[] true [:foo] true}})] :ret {fulcro.client.mutations/set-props {:result {:fulcro.inspect.core/app-id :fulcro.inspect.ui.data-viewer-cards/data-viewer-16 :ui/react-key "5537b4a1-589d-40d2-a98f-509c918f222e" :ui/root [:fulcro.inspect.ui.data-viewer/id #uuid "f13d5cb1-82c8-48fa-abc6-73b54dbf33f9"] :fulcro.inspect.ui.data-viewer/id {#uuid "f13d5cb1-82c8-48fa-abc6-73b54dbf33f9" {:fulcro.inspect.ui.data-viewer/id #uuid "f13d5cb1-82c8-48fa-abc6-73b54dbf33f9" :fulcro.inspect.ui.data-viewer/content {:a 3 :b 10 :foo {:barr ["baz" "there"]}} :fulcro.inspect.ui.data-viewer/expanded {[] true [:foo] true}}} :fulcro.client.primitives/tables #{:fulcro.inspect.ui.data-viewer/id} :ui/locale :en}}} :old-state {:id {123 {:a 1}}} :new-state {:id {123 {:b 2}}} :sends {} :ref [:fulcro.inspect.ui.data-viewer/id #uuid "f13d5cb1-82c8-48fa-abc6-73b54dbf33f9"] :component nil}) (def TxRoot (card-helpers/make-root transactions/Transaction ::single-tx)) (defcard-fulcro transaction TxRoot (card-helpers/init-state-atom TxRoot tx)) (def TxListRoot (card-helpers/make-root transactions/TransactionList ::tx-list)) (defcard-fulcro transaction-list TxListRoot {} {:fulcro {:started-callback (fn [{:keys [reconciler]}] (let [ref (-> reconciler fp/app-state deref :ui/root)] (doseq [x (repeat 5 tx)] (fp/transact! reconciler ref [`(transactions/add-tx ~x)]))))}}) (defcard-fulcro transaction-list-empty transactions/TransactionList) (css/upsert-css "transaction" transactions/TransactionList)
53221
(ns fulcro.inspect.ui.transactions-cards (:require [devcards.core :refer-macros [defcard]] [fulcro-css.css :as css] [fulcro.client.cards :refer-macros [defcard-fulcro]] [fulcro.inspect.ui.transactions :as transactions] [fulcro.inspect.card-helpers :as card-helpers] [fulcro.client.primitives :as fp])) (def tx '{:tx [(fulcro.client.mutations/set-props {:fulcro.inspect.ui.data-viewer/expanded {[] true [:foo] true}})] :ret {fulcro.client.mutations/set-props {:result {:fulcro.inspect.core/app-id :fulcro.inspect.ui.data-viewer-cards/data-viewer-16 :ui/react-key "<KEY>" :ui/root [:fulcro.inspect.ui.data-viewer/id #uuid "f13d5cb1-82c8-48fa-abc6-73b54dbf33f9"] :fulcro.inspect.ui.data-viewer/id {#uuid "f13d5cb1-82c8-48fa-abc6-73b54dbf33f9" {:fulcro.inspect.ui.data-viewer/id #uuid "f13d5cb1-82c8-48fa-abc6-73b54dbf33f9" :fulcro.inspect.ui.data-viewer/content {:a 3 :b 10 :foo {:barr ["baz" "there"]}} :fulcro.inspect.ui.data-viewer/expanded {[] true [:foo] true}}} :fulcro.client.primitives/tables #{:fulcro.inspect.ui.data-viewer/id} :ui/locale :en}}} :old-state {:id {123 {:a 1}}} :new-state {:id {123 {:b 2}}} :sends {} :ref [:fulcro.inspect.ui.data-viewer/id #uuid "f13d5cb1-82c8-48fa-abc6-73b54dbf33f9"] :component nil}) (def TxRoot (card-helpers/make-root transactions/Transaction ::single-tx)) (defcard-fulcro transaction TxRoot (card-helpers/init-state-atom TxRoot tx)) (def TxListRoot (card-helpers/make-root transactions/TransactionList ::tx-list)) (defcard-fulcro transaction-list TxListRoot {} {:fulcro {:started-callback (fn [{:keys [reconciler]}] (let [ref (-> reconciler fp/app-state deref :ui/root)] (doseq [x (repeat 5 tx)] (fp/transact! reconciler ref [`(transactions/add-tx ~x)]))))}}) (defcard-fulcro transaction-list-empty transactions/TransactionList) (css/upsert-css "transaction" transactions/TransactionList)
true
(ns fulcro.inspect.ui.transactions-cards (:require [devcards.core :refer-macros [defcard]] [fulcro-css.css :as css] [fulcro.client.cards :refer-macros [defcard-fulcro]] [fulcro.inspect.ui.transactions :as transactions] [fulcro.inspect.card-helpers :as card-helpers] [fulcro.client.primitives :as fp])) (def tx '{:tx [(fulcro.client.mutations/set-props {:fulcro.inspect.ui.data-viewer/expanded {[] true [:foo] true}})] :ret {fulcro.client.mutations/set-props {:result {:fulcro.inspect.core/app-id :fulcro.inspect.ui.data-viewer-cards/data-viewer-16 :ui/react-key "PI:KEY:<KEY>END_PI" :ui/root [:fulcro.inspect.ui.data-viewer/id #uuid "f13d5cb1-82c8-48fa-abc6-73b54dbf33f9"] :fulcro.inspect.ui.data-viewer/id {#uuid "f13d5cb1-82c8-48fa-abc6-73b54dbf33f9" {:fulcro.inspect.ui.data-viewer/id #uuid "f13d5cb1-82c8-48fa-abc6-73b54dbf33f9" :fulcro.inspect.ui.data-viewer/content {:a 3 :b 10 :foo {:barr ["baz" "there"]}} :fulcro.inspect.ui.data-viewer/expanded {[] true [:foo] true}}} :fulcro.client.primitives/tables #{:fulcro.inspect.ui.data-viewer/id} :ui/locale :en}}} :old-state {:id {123 {:a 1}}} :new-state {:id {123 {:b 2}}} :sends {} :ref [:fulcro.inspect.ui.data-viewer/id #uuid "f13d5cb1-82c8-48fa-abc6-73b54dbf33f9"] :component nil}) (def TxRoot (card-helpers/make-root transactions/Transaction ::single-tx)) (defcard-fulcro transaction TxRoot (card-helpers/init-state-atom TxRoot tx)) (def TxListRoot (card-helpers/make-root transactions/TransactionList ::tx-list)) (defcard-fulcro transaction-list TxListRoot {} {:fulcro {:started-callback (fn [{:keys [reconciler]}] (let [ref (-> reconciler fp/app-state deref :ui/root)] (doseq [x (repeat 5 tx)] (fp/transact! reconciler ref [`(transactions/add-tx ~x)]))))}}) (defcard-fulcro transaction-list-empty transactions/TransactionList) (css/upsert-css "transaction" transactions/TransactionList)
[ { "context": "point-url\n {:body \"access_key = 123\"})\n\n result-promise (promise)\n resu", "end": 5609, "score": 0.8785199522972107, "start": 5606, "tag": "KEY", "value": "123" }, { "context": " (fn [request]\n (if (= \"access_key = 123\" (slurp (:body request)))\n {:status 200", "end": 5841, "score": 0.8969734311103821, "start": 5838, "tag": "KEY", "value": "123" }, { "context": "dy-fn-when-provided\n (let [context {:access-key \"123\"}\n endpoint-url \"http://service.example.co", "end": 6237, "score": 0.9295694231987, "start": 6234, "tag": "KEY", "value": "123" }, { "context": " (fn [request]\n (if (= \"access_key = 123\" (slurp (:body request)))\n {:status 200", "end": 6729, "score": 0.9034745097160339, "start": 6726, "tag": "KEY", "value": "123" }, { "context": "rs-fn-when-provided\n (let [context {:access-key \"123\"}\n endpoint-url \"http://service.example.co", "end": 8714, "score": 0.9940984845161438, "start": 8711, "tag": "KEY", "value": "123" }, { "context": "ms-fn-when-provided\n (let [context {:access-key \"123\"}\n endpoint-url \"http://service.example.co", "end": 10949, "score": 0.9825569987297058, "start": 10946, "tag": "KEY", "value": "123" } ]
check-fns/http-endpoint/test/unit/salutem/check_fns/http_endpoint/core_test.clj
logicblocks/salutem
13
(ns salutem.check-fns.http-endpoint.core-test (:require [clojure.test :refer :all] [clojure.set :as set] [cartus.test :as ct] [clj-http.fake :as http] [salutem.core :as salutem] [salutem.check-fns.http-endpoint.core :as scfhe]) (:import [org.apache.http.conn ConnectTimeoutException] [java.net SocketTimeoutException ConnectException])) (declare logged?) (def all-status-codes (into #{} (range 100 600))) (def success-status-codes #{200 201 202 203 204 205 206 207 300 301 302 303 304 307 308}) (def failure-status-codes (set/difference all-status-codes success-status-codes)) (deftest failure-reason-returns-timed-out-for-timeout-exceptions (is (= :timed-out (scfhe/failure-reason (ConnectTimeoutException. "Out of time.")))) (is (= :timed-out (scfhe/failure-reason (SocketTimeoutException. "Out of time.")))) (is (= :timed-out (scfhe/failure-reason (ConnectException. "Timeout connecting to something."))))) (deftest failure-reason-returns-threw-exception-for-non-timeout-exceptions (is (= :threw-exception (scfhe/failure-reason (IllegalArgumentException. "Does not compute.")))) (is (= :threw-exception (scfhe/failure-reason (ConnectException. "Connection refused."))))) (deftest successful?-returns-true-for-response-with-success-status-code (doseq [status-code success-status-codes] (is (scfhe/successful? {:status status-code})))) (deftest successful?-returns-false-for-response-with-failure-status-code (doseq [status-code failure-status-codes] (is (not (scfhe/successful? {:status status-code}))))) (deftest http-endpoint-check-fn-returns-healthy-when-request-successful (let [endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url) context {} result-promise (promise) result-cb (partial deliver result-promise)] (doseq [status-code success-status-codes] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] {:status status-code})} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result) (str status-code " should have produced healthy result")))))) (deftest http-endpoint-check-fn-uses-endpoint-url-fn-when-provided (let [context {:access-key "123"} endpoint-url-fn (fn [context] (str "http://service.example.com/ping?access_key=" (:access-key context))) check-fn (scfhe/http-endpoint-check-fn endpoint-url-fn) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping?access_key=123" (fn [_] {:status 200})} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-uses-get-as-method-by-default (let [context {} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" {:get (fn [_] {:status 200})}} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-uses-supplied-method-when-provided (let [context {} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:method :head}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" {:head (fn [_] {:status 200})}} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-uses-supplied-method-fn-when-provided (let [context {:method :head} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:method (fn [context] (:method context))}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" {:head (fn [_] {:status 200})}} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-uses-empty-body-by-default (let [context {} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" (fn [request] (if (nil? (:body request)) {:status 200} (throw (IllegalStateException. "Expected no body but got one."))))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-uses-supplied-body-when-provided (let [context {} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:body "access_key = 123"}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" (fn [request] (if (= "access_key = 123" (slurp (:body request))) {:status 200} (throw (IllegalStateException. "Expected supplied body but got something else."))))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-uses-supplied-body-fn-when-provided (let [context {:access-key "123"} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:body (fn [context] (str "access_key = " (:access-key context)))}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" (fn [request] (if (= "access_key = 123" (slurp (:body request))) {:status 200} (throw (IllegalStateException. "Expected supplied body but got something else."))))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-passes-no-headers-by-default (let [context {} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" (fn [request] ; accept-encoding added by default (if (empty? (dissoc (:headers request) "accept-encoding")) {:status 200} (throw (IllegalStateException. "Expected no headers but got some."))))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-passes-supplied-headers-when-provided (let [context {} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:headers {"x-important-header" 56}}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" (fn [request] ; accept-encoding added by default (if (= 56 (get-in request [:headers "x-important-header"])) {:status 200} (throw (IllegalStateException. "Expected no headers but got some."))))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-passes-supplied-headers-fn-when-provided (let [context {:access-key "123"} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:headers (fn [context] {"x-access-key" (:access-key context)})}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" (fn [request] ; accept-encoding added by default (if (= (:access-key context) (get-in request [:headers "x-access-key"])) {:status 200} (throw (IllegalStateException. "Expected no headers but got some."))))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-passes-no-query-params-by-default (let [context {} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" (fn [request] (if (nil? (get request :query-params)) {:status 200} (throw (IllegalStateException. "Expected supplied query-params."))))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-passes-supplied-query-params-when-provided (let [context {} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:query-params {:a 1}}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping?a=1" (fn [_] {:status 200})} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-passes-supplied-query-params-fn-when-provided (let [context {:access-key "123"} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:query-params (fn [context] {:access-key (:access-key context)})}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping?access-key=123" (fn [_] {:status 200})} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-passes-additional-options-map (let [context {} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:opts {:max-redirects 5 :redirect-strategy :graceful}}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" (fn [request] (if (and (= 5 (get request :max-redirects)) (= :graceful (get request :redirect-strategy))) {:status 200} (throw (IllegalStateException. "Expected opts."))))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-passes-additional-options-from-fn (let [context {:max-redirects 5} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:opts (fn [context] {:max-redirects (:max-redirects context) :redirect-strategy :graceful})}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" (fn [request] (if (and (= 5 (get request :max-redirects)) (= :graceful (get request :redirect-strategy))) {:status 200} (throw (IllegalStateException. "Expected opts."))))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-returns-unhealthy-when-request-unsuccessful (let [endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url) context {} result-promise (promise) result-cb (partial deliver result-promise)] (doseq [status-code failure-status-codes] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] {:status status-code})} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/unhealthy? result) (str status-code " should have produced unhealthy result")))))) (deftest http-endpoint-check-fn-returns-unhealthy-on-timeout-exceptions (let [endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url) context {}] (doseq [timeout-exception [(ConnectTimeoutException. "We're out of time.") (SocketTimeoutException. "We're out of time.") (ConnectException. "Timeout when connecting.")]] (let [result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] (throw timeout-exception))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/unhealthy? result)) (is (= :timed-out (:salutem/reason result))) (is (= timeout-exception (:salutem/exception result)))))))) (deftest http-endpoint-check-fn-returns-unhealthy-on-other-exception (let [endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url) context {} exception (IllegalArgumentException. "That doesn't look right.") result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] (throw exception))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/unhealthy? result)) (is (= :threw-exception (:salutem/reason result))) (is (= exception (:salutem/exception result)))))) (deftest http-endpoint-check-fn-uses-supplied-successful-response-fn-on-success (let [context {:success-statuses #{200}} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:successful-response-fn (fn [context response] (contains? (:success-statuses context) (get response :status)))}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] {:status 200 :body "All is right with the world."})} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-uses-supplied-successful-response-fn-on-failure (let [context {:success-statuses #{200}} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:successful-response-fn (fn [context response] (contains? (:success-statuses context) (get response :status)))}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] {:status 201 :body "All is right with the world."})} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/unhealthy? result))))) (deftest http-endpoint-check-fn-uses-supplied-response-result-fn-on-success (let [endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:response-result-fn (fn [context response] (if (= 200 (get response :status)) (salutem/healthy (merge context {:message (get response :body)})) (salutem/unhealthy)))}) context {:important :runtime-value} result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] {:status 200 :body "All is right with the world."})} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result)) (is (= "All is right with the world." (:message result))) (is (= :runtime-value (:important result)))))) (deftest http-endpoint-check-fn-uses-supplied-response-result-fn-on-failure (let [endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:response-result-fn (fn [context response] (if (= 200 (get response :status)) (salutem/healthy) (salutem/unhealthy (merge context {:message (get response :body)}))))}) context {:important :runtime-value} result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] {:status 500 :body "Things have gone awry."})} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/unhealthy? result)) (is (= "Things have gone awry." (:message result))) (is (= :runtime-value (:important result)))))) (deftest http-endpoint-check-fn-uses-supplied-failure-reason-fn (let [context {:argument-failure-reason :received-invalid-argument} exception (IllegalArgumentException. "That's not what I need...") endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:failure-reason-fn (fn [context ^Exception exception] (if (isa? (class exception) IllegalArgumentException) (:argument-failure-reason context) :threw-exception))})] (let [result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] (throw exception))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/unhealthy? result)) (is (= :received-invalid-argument (:salutem/reason result))) (is (= exception (:salutem/exception result))))))) (deftest http-endpoint-check-fn-uses-exception-result-fn-on-timeout-exceptions (let [endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:exception-result-fn (fn [context ^Exception exception] (salutem/unhealthy (merge context {:message (.getMessage exception)})))}) context {:important :runtime-value}] (doseq [timeout-exception [(ConnectTimeoutException. "We're out of time.") (SocketTimeoutException. "We're out of time.") (ConnectException. "Timeout when connecting.")]] (let [result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] (throw timeout-exception))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/unhealthy? result)) (is (= (.getMessage ^Exception timeout-exception) (:message result))) (is (= :runtime-value (:important result)))))))) (deftest http-endpoint-check-fn-uses-exception-result-fn-on-other-exceptions (let [endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:exception-result-fn (fn [context ^Exception exception] (salutem/unhealthy (merge context {:message (.getMessage exception)})))}) context {:important :runtime-value}] (doseq [standard-exception [(IllegalArgumentException. "Well that's strange.") (ConnectException. "Connection refused.")]] (let [result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] (throw standard-exception))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/unhealthy? result)) (is (= (.getMessage ^Exception standard-exception) (:message result))) (is (= :runtime-value (:important result)))))))) (deftest http-endpoint-check-fn-logs-on-start-when-logger-in-context (let [logger (ct/logger) context {:logger logger} url "http://service.example.com/ping" method :head query-params {:caller "thing-service"} headers {"x-important-header" 56} body "ping" check-fn (scfhe/http-endpoint-check-fn url {:method method :query-params query-params :headers headers :body body}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {url (fn [_] {:status 200})} (check-fn context result-cb)) (deref result-promise 500 nil) (is (logged? logger {:context {:url url :method method :query-params query-params :headers headers :body body} :level :info :type :salutem.check-fns.http-endpoint/check.starting})))) (deftest http-endpoint-check-fn-logs-on-response-when-logger-in-context (let [logger (ct/logger) context {:logger logger} url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn url) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {url (fn [_] {:status 200})} (check-fn context result-cb)) (deref result-promise 500 nil) (is (logged? logger {:level :info :type :salutem.check-fns.http-endpoint/check.successful})))) (deftest http-endpoint-check-fn-logs-on-timeout-exceptions-when-logger-in-context (let [logger (ct/logger) context {:logger logger} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url)] (doseq [timeout-exception [(ConnectTimeoutException. "We're out of time.") (SocketTimeoutException. "We're out of time.") (ConnectException. "Timeout when connecting.")]] (let [result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] (throw timeout-exception))} (check-fn context result-cb)) (deref result-promise 500 nil) (is (logged? logger {:context {:reason :timed-out} :exception timeout-exception :level :warn :type :salutem.check-fns.http-endpoint/check.failed})))))) (deftest http-endpoint-check-fn-logs-on-other-exceptions-when-logger-in-context (let [logger (ct/logger) context {:logger logger} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url)] (doseq [standard-exception [(IllegalArgumentException. "Well that's strange.") (ConnectException. "Connection refused.")]] (let [result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] (throw standard-exception))} (check-fn context result-cb)) (deref result-promise 500 nil) (is (logged? logger {:context {:reason :threw-exception} :exception standard-exception :level :warn :type :salutem.check-fns.http-endpoint/check.failed}))))))
91585
(ns salutem.check-fns.http-endpoint.core-test (:require [clojure.test :refer :all] [clojure.set :as set] [cartus.test :as ct] [clj-http.fake :as http] [salutem.core :as salutem] [salutem.check-fns.http-endpoint.core :as scfhe]) (:import [org.apache.http.conn ConnectTimeoutException] [java.net SocketTimeoutException ConnectException])) (declare logged?) (def all-status-codes (into #{} (range 100 600))) (def success-status-codes #{200 201 202 203 204 205 206 207 300 301 302 303 304 307 308}) (def failure-status-codes (set/difference all-status-codes success-status-codes)) (deftest failure-reason-returns-timed-out-for-timeout-exceptions (is (= :timed-out (scfhe/failure-reason (ConnectTimeoutException. "Out of time.")))) (is (= :timed-out (scfhe/failure-reason (SocketTimeoutException. "Out of time.")))) (is (= :timed-out (scfhe/failure-reason (ConnectException. "Timeout connecting to something."))))) (deftest failure-reason-returns-threw-exception-for-non-timeout-exceptions (is (= :threw-exception (scfhe/failure-reason (IllegalArgumentException. "Does not compute.")))) (is (= :threw-exception (scfhe/failure-reason (ConnectException. "Connection refused."))))) (deftest successful?-returns-true-for-response-with-success-status-code (doseq [status-code success-status-codes] (is (scfhe/successful? {:status status-code})))) (deftest successful?-returns-false-for-response-with-failure-status-code (doseq [status-code failure-status-codes] (is (not (scfhe/successful? {:status status-code}))))) (deftest http-endpoint-check-fn-returns-healthy-when-request-successful (let [endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url) context {} result-promise (promise) result-cb (partial deliver result-promise)] (doseq [status-code success-status-codes] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] {:status status-code})} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result) (str status-code " should have produced healthy result")))))) (deftest http-endpoint-check-fn-uses-endpoint-url-fn-when-provided (let [context {:access-key "123"} endpoint-url-fn (fn [context] (str "http://service.example.com/ping?access_key=" (:access-key context))) check-fn (scfhe/http-endpoint-check-fn endpoint-url-fn) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping?access_key=123" (fn [_] {:status 200})} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-uses-get-as-method-by-default (let [context {} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" {:get (fn [_] {:status 200})}} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-uses-supplied-method-when-provided (let [context {} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:method :head}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" {:head (fn [_] {:status 200})}} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-uses-supplied-method-fn-when-provided (let [context {:method :head} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:method (fn [context] (:method context))}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" {:head (fn [_] {:status 200})}} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-uses-empty-body-by-default (let [context {} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" (fn [request] (if (nil? (:body request)) {:status 200} (throw (IllegalStateException. "Expected no body but got one."))))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-uses-supplied-body-when-provided (let [context {} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:body "access_key = <KEY>"}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" (fn [request] (if (= "access_key = <KEY>" (slurp (:body request))) {:status 200} (throw (IllegalStateException. "Expected supplied body but got something else."))))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-uses-supplied-body-fn-when-provided (let [context {:access-key "<KEY>"} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:body (fn [context] (str "access_key = " (:access-key context)))}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" (fn [request] (if (= "access_key = <KEY>" (slurp (:body request))) {:status 200} (throw (IllegalStateException. "Expected supplied body but got something else."))))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-passes-no-headers-by-default (let [context {} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" (fn [request] ; accept-encoding added by default (if (empty? (dissoc (:headers request) "accept-encoding")) {:status 200} (throw (IllegalStateException. "Expected no headers but got some."))))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-passes-supplied-headers-when-provided (let [context {} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:headers {"x-important-header" 56}}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" (fn [request] ; accept-encoding added by default (if (= 56 (get-in request [:headers "x-important-header"])) {:status 200} (throw (IllegalStateException. "Expected no headers but got some."))))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-passes-supplied-headers-fn-when-provided (let [context {:access-key "<KEY>"} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:headers (fn [context] {"x-access-key" (:access-key context)})}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" (fn [request] ; accept-encoding added by default (if (= (:access-key context) (get-in request [:headers "x-access-key"])) {:status 200} (throw (IllegalStateException. "Expected no headers but got some."))))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-passes-no-query-params-by-default (let [context {} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" (fn [request] (if (nil? (get request :query-params)) {:status 200} (throw (IllegalStateException. "Expected supplied query-params."))))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-passes-supplied-query-params-when-provided (let [context {} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:query-params {:a 1}}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping?a=1" (fn [_] {:status 200})} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-passes-supplied-query-params-fn-when-provided (let [context {:access-key "<KEY>"} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:query-params (fn [context] {:access-key (:access-key context)})}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping?access-key=123" (fn [_] {:status 200})} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-passes-additional-options-map (let [context {} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:opts {:max-redirects 5 :redirect-strategy :graceful}}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" (fn [request] (if (and (= 5 (get request :max-redirects)) (= :graceful (get request :redirect-strategy))) {:status 200} (throw (IllegalStateException. "Expected opts."))))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-passes-additional-options-from-fn (let [context {:max-redirects 5} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:opts (fn [context] {:max-redirects (:max-redirects context) :redirect-strategy :graceful})}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" (fn [request] (if (and (= 5 (get request :max-redirects)) (= :graceful (get request :redirect-strategy))) {:status 200} (throw (IllegalStateException. "Expected opts."))))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-returns-unhealthy-when-request-unsuccessful (let [endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url) context {} result-promise (promise) result-cb (partial deliver result-promise)] (doseq [status-code failure-status-codes] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] {:status status-code})} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/unhealthy? result) (str status-code " should have produced unhealthy result")))))) (deftest http-endpoint-check-fn-returns-unhealthy-on-timeout-exceptions (let [endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url) context {}] (doseq [timeout-exception [(ConnectTimeoutException. "We're out of time.") (SocketTimeoutException. "We're out of time.") (ConnectException. "Timeout when connecting.")]] (let [result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] (throw timeout-exception))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/unhealthy? result)) (is (= :timed-out (:salutem/reason result))) (is (= timeout-exception (:salutem/exception result)))))))) (deftest http-endpoint-check-fn-returns-unhealthy-on-other-exception (let [endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url) context {} exception (IllegalArgumentException. "That doesn't look right.") result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] (throw exception))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/unhealthy? result)) (is (= :threw-exception (:salutem/reason result))) (is (= exception (:salutem/exception result)))))) (deftest http-endpoint-check-fn-uses-supplied-successful-response-fn-on-success (let [context {:success-statuses #{200}} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:successful-response-fn (fn [context response] (contains? (:success-statuses context) (get response :status)))}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] {:status 200 :body "All is right with the world."})} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-uses-supplied-successful-response-fn-on-failure (let [context {:success-statuses #{200}} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:successful-response-fn (fn [context response] (contains? (:success-statuses context) (get response :status)))}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] {:status 201 :body "All is right with the world."})} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/unhealthy? result))))) (deftest http-endpoint-check-fn-uses-supplied-response-result-fn-on-success (let [endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:response-result-fn (fn [context response] (if (= 200 (get response :status)) (salutem/healthy (merge context {:message (get response :body)})) (salutem/unhealthy)))}) context {:important :runtime-value} result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] {:status 200 :body "All is right with the world."})} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result)) (is (= "All is right with the world." (:message result))) (is (= :runtime-value (:important result)))))) (deftest http-endpoint-check-fn-uses-supplied-response-result-fn-on-failure (let [endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:response-result-fn (fn [context response] (if (= 200 (get response :status)) (salutem/healthy) (salutem/unhealthy (merge context {:message (get response :body)}))))}) context {:important :runtime-value} result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] {:status 500 :body "Things have gone awry."})} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/unhealthy? result)) (is (= "Things have gone awry." (:message result))) (is (= :runtime-value (:important result)))))) (deftest http-endpoint-check-fn-uses-supplied-failure-reason-fn (let [context {:argument-failure-reason :received-invalid-argument} exception (IllegalArgumentException. "That's not what I need...") endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:failure-reason-fn (fn [context ^Exception exception] (if (isa? (class exception) IllegalArgumentException) (:argument-failure-reason context) :threw-exception))})] (let [result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] (throw exception))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/unhealthy? result)) (is (= :received-invalid-argument (:salutem/reason result))) (is (= exception (:salutem/exception result))))))) (deftest http-endpoint-check-fn-uses-exception-result-fn-on-timeout-exceptions (let [endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:exception-result-fn (fn [context ^Exception exception] (salutem/unhealthy (merge context {:message (.getMessage exception)})))}) context {:important :runtime-value}] (doseq [timeout-exception [(ConnectTimeoutException. "We're out of time.") (SocketTimeoutException. "We're out of time.") (ConnectException. "Timeout when connecting.")]] (let [result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] (throw timeout-exception))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/unhealthy? result)) (is (= (.getMessage ^Exception timeout-exception) (:message result))) (is (= :runtime-value (:important result)))))))) (deftest http-endpoint-check-fn-uses-exception-result-fn-on-other-exceptions (let [endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:exception-result-fn (fn [context ^Exception exception] (salutem/unhealthy (merge context {:message (.getMessage exception)})))}) context {:important :runtime-value}] (doseq [standard-exception [(IllegalArgumentException. "Well that's strange.") (ConnectException. "Connection refused.")]] (let [result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] (throw standard-exception))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/unhealthy? result)) (is (= (.getMessage ^Exception standard-exception) (:message result))) (is (= :runtime-value (:important result)))))))) (deftest http-endpoint-check-fn-logs-on-start-when-logger-in-context (let [logger (ct/logger) context {:logger logger} url "http://service.example.com/ping" method :head query-params {:caller "thing-service"} headers {"x-important-header" 56} body "ping" check-fn (scfhe/http-endpoint-check-fn url {:method method :query-params query-params :headers headers :body body}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {url (fn [_] {:status 200})} (check-fn context result-cb)) (deref result-promise 500 nil) (is (logged? logger {:context {:url url :method method :query-params query-params :headers headers :body body} :level :info :type :salutem.check-fns.http-endpoint/check.starting})))) (deftest http-endpoint-check-fn-logs-on-response-when-logger-in-context (let [logger (ct/logger) context {:logger logger} url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn url) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {url (fn [_] {:status 200})} (check-fn context result-cb)) (deref result-promise 500 nil) (is (logged? logger {:level :info :type :salutem.check-fns.http-endpoint/check.successful})))) (deftest http-endpoint-check-fn-logs-on-timeout-exceptions-when-logger-in-context (let [logger (ct/logger) context {:logger logger} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url)] (doseq [timeout-exception [(ConnectTimeoutException. "We're out of time.") (SocketTimeoutException. "We're out of time.") (ConnectException. "Timeout when connecting.")]] (let [result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] (throw timeout-exception))} (check-fn context result-cb)) (deref result-promise 500 nil) (is (logged? logger {:context {:reason :timed-out} :exception timeout-exception :level :warn :type :salutem.check-fns.http-endpoint/check.failed})))))) (deftest http-endpoint-check-fn-logs-on-other-exceptions-when-logger-in-context (let [logger (ct/logger) context {:logger logger} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url)] (doseq [standard-exception [(IllegalArgumentException. "Well that's strange.") (ConnectException. "Connection refused.")]] (let [result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] (throw standard-exception))} (check-fn context result-cb)) (deref result-promise 500 nil) (is (logged? logger {:context {:reason :threw-exception} :exception standard-exception :level :warn :type :salutem.check-fns.http-endpoint/check.failed}))))))
true
(ns salutem.check-fns.http-endpoint.core-test (:require [clojure.test :refer :all] [clojure.set :as set] [cartus.test :as ct] [clj-http.fake :as http] [salutem.core :as salutem] [salutem.check-fns.http-endpoint.core :as scfhe]) (:import [org.apache.http.conn ConnectTimeoutException] [java.net SocketTimeoutException ConnectException])) (declare logged?) (def all-status-codes (into #{} (range 100 600))) (def success-status-codes #{200 201 202 203 204 205 206 207 300 301 302 303 304 307 308}) (def failure-status-codes (set/difference all-status-codes success-status-codes)) (deftest failure-reason-returns-timed-out-for-timeout-exceptions (is (= :timed-out (scfhe/failure-reason (ConnectTimeoutException. "Out of time.")))) (is (= :timed-out (scfhe/failure-reason (SocketTimeoutException. "Out of time.")))) (is (= :timed-out (scfhe/failure-reason (ConnectException. "Timeout connecting to something."))))) (deftest failure-reason-returns-threw-exception-for-non-timeout-exceptions (is (= :threw-exception (scfhe/failure-reason (IllegalArgumentException. "Does not compute.")))) (is (= :threw-exception (scfhe/failure-reason (ConnectException. "Connection refused."))))) (deftest successful?-returns-true-for-response-with-success-status-code (doseq [status-code success-status-codes] (is (scfhe/successful? {:status status-code})))) (deftest successful?-returns-false-for-response-with-failure-status-code (doseq [status-code failure-status-codes] (is (not (scfhe/successful? {:status status-code}))))) (deftest http-endpoint-check-fn-returns-healthy-when-request-successful (let [endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url) context {} result-promise (promise) result-cb (partial deliver result-promise)] (doseq [status-code success-status-codes] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] {:status status-code})} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result) (str status-code " should have produced healthy result")))))) (deftest http-endpoint-check-fn-uses-endpoint-url-fn-when-provided (let [context {:access-key "123"} endpoint-url-fn (fn [context] (str "http://service.example.com/ping?access_key=" (:access-key context))) check-fn (scfhe/http-endpoint-check-fn endpoint-url-fn) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping?access_key=123" (fn [_] {:status 200})} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-uses-get-as-method-by-default (let [context {} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" {:get (fn [_] {:status 200})}} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-uses-supplied-method-when-provided (let [context {} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:method :head}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" {:head (fn [_] {:status 200})}} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-uses-supplied-method-fn-when-provided (let [context {:method :head} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:method (fn [context] (:method context))}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" {:head (fn [_] {:status 200})}} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-uses-empty-body-by-default (let [context {} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" (fn [request] (if (nil? (:body request)) {:status 200} (throw (IllegalStateException. "Expected no body but got one."))))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-uses-supplied-body-when-provided (let [context {} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:body "access_key = PI:KEY:<KEY>END_PI"}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" (fn [request] (if (= "access_key = PI:KEY:<KEY>END_PI" (slurp (:body request))) {:status 200} (throw (IllegalStateException. "Expected supplied body but got something else."))))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-uses-supplied-body-fn-when-provided (let [context {:access-key "PI:KEY:<KEY>END_PI"} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:body (fn [context] (str "access_key = " (:access-key context)))}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" (fn [request] (if (= "access_key = PI:KEY:<KEY>END_PI" (slurp (:body request))) {:status 200} (throw (IllegalStateException. "Expected supplied body but got something else."))))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-passes-no-headers-by-default (let [context {} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" (fn [request] ; accept-encoding added by default (if (empty? (dissoc (:headers request) "accept-encoding")) {:status 200} (throw (IllegalStateException. "Expected no headers but got some."))))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-passes-supplied-headers-when-provided (let [context {} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:headers {"x-important-header" 56}}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" (fn [request] ; accept-encoding added by default (if (= 56 (get-in request [:headers "x-important-header"])) {:status 200} (throw (IllegalStateException. "Expected no headers but got some."))))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-passes-supplied-headers-fn-when-provided (let [context {:access-key "PI:KEY:<KEY>END_PI"} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:headers (fn [context] {"x-access-key" (:access-key context)})}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" (fn [request] ; accept-encoding added by default (if (= (:access-key context) (get-in request [:headers "x-access-key"])) {:status 200} (throw (IllegalStateException. "Expected no headers but got some."))))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-passes-no-query-params-by-default (let [context {} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" (fn [request] (if (nil? (get request :query-params)) {:status 200} (throw (IllegalStateException. "Expected supplied query-params."))))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-passes-supplied-query-params-when-provided (let [context {} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:query-params {:a 1}}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping?a=1" (fn [_] {:status 200})} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-passes-supplied-query-params-fn-when-provided (let [context {:access-key "PI:KEY:<KEY>END_PI"} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:query-params (fn [context] {:access-key (:access-key context)})}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping?access-key=123" (fn [_] {:status 200})} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-passes-additional-options-map (let [context {} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:opts {:max-redirects 5 :redirect-strategy :graceful}}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" (fn [request] (if (and (= 5 (get request :max-redirects)) (= :graceful (get request :redirect-strategy))) {:status 200} (throw (IllegalStateException. "Expected opts."))))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-passes-additional-options-from-fn (let [context {:max-redirects 5} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:opts (fn [context] {:max-redirects (:max-redirects context) :redirect-strategy :graceful})}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {"http://service.example.com/ping" (fn [request] (if (and (= 5 (get request :max-redirects)) (= :graceful (get request :redirect-strategy))) {:status 200} (throw (IllegalStateException. "Expected opts."))))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-returns-unhealthy-when-request-unsuccessful (let [endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url) context {} result-promise (promise) result-cb (partial deliver result-promise)] (doseq [status-code failure-status-codes] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] {:status status-code})} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/unhealthy? result) (str status-code " should have produced unhealthy result")))))) (deftest http-endpoint-check-fn-returns-unhealthy-on-timeout-exceptions (let [endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url) context {}] (doseq [timeout-exception [(ConnectTimeoutException. "We're out of time.") (SocketTimeoutException. "We're out of time.") (ConnectException. "Timeout when connecting.")]] (let [result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] (throw timeout-exception))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/unhealthy? result)) (is (= :timed-out (:salutem/reason result))) (is (= timeout-exception (:salutem/exception result)))))))) (deftest http-endpoint-check-fn-returns-unhealthy-on-other-exception (let [endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url) context {} exception (IllegalArgumentException. "That doesn't look right.") result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] (throw exception))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/unhealthy? result)) (is (= :threw-exception (:salutem/reason result))) (is (= exception (:salutem/exception result)))))) (deftest http-endpoint-check-fn-uses-supplied-successful-response-fn-on-success (let [context {:success-statuses #{200}} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:successful-response-fn (fn [context response] (contains? (:success-statuses context) (get response :status)))}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] {:status 200 :body "All is right with the world."})} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result))))) (deftest http-endpoint-check-fn-uses-supplied-successful-response-fn-on-failure (let [context {:success-statuses #{200}} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:successful-response-fn (fn [context response] (contains? (:success-statuses context) (get response :status)))}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] {:status 201 :body "All is right with the world."})} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/unhealthy? result))))) (deftest http-endpoint-check-fn-uses-supplied-response-result-fn-on-success (let [endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:response-result-fn (fn [context response] (if (= 200 (get response :status)) (salutem/healthy (merge context {:message (get response :body)})) (salutem/unhealthy)))}) context {:important :runtime-value} result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] {:status 200 :body "All is right with the world."})} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/healthy? result)) (is (= "All is right with the world." (:message result))) (is (= :runtime-value (:important result)))))) (deftest http-endpoint-check-fn-uses-supplied-response-result-fn-on-failure (let [endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:response-result-fn (fn [context response] (if (= 200 (get response :status)) (salutem/healthy) (salutem/unhealthy (merge context {:message (get response :body)}))))}) context {:important :runtime-value} result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] {:status 500 :body "Things have gone awry."})} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/unhealthy? result)) (is (= "Things have gone awry." (:message result))) (is (= :runtime-value (:important result)))))) (deftest http-endpoint-check-fn-uses-supplied-failure-reason-fn (let [context {:argument-failure-reason :received-invalid-argument} exception (IllegalArgumentException. "That's not what I need...") endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:failure-reason-fn (fn [context ^Exception exception] (if (isa? (class exception) IllegalArgumentException) (:argument-failure-reason context) :threw-exception))})] (let [result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] (throw exception))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/unhealthy? result)) (is (= :received-invalid-argument (:salutem/reason result))) (is (= exception (:salutem/exception result))))))) (deftest http-endpoint-check-fn-uses-exception-result-fn-on-timeout-exceptions (let [endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:exception-result-fn (fn [context ^Exception exception] (salutem/unhealthy (merge context {:message (.getMessage exception)})))}) context {:important :runtime-value}] (doseq [timeout-exception [(ConnectTimeoutException. "We're out of time.") (SocketTimeoutException. "We're out of time.") (ConnectException. "Timeout when connecting.")]] (let [result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] (throw timeout-exception))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/unhealthy? result)) (is (= (.getMessage ^Exception timeout-exception) (:message result))) (is (= :runtime-value (:important result)))))))) (deftest http-endpoint-check-fn-uses-exception-result-fn-on-other-exceptions (let [endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url {:exception-result-fn (fn [context ^Exception exception] (salutem/unhealthy (merge context {:message (.getMessage exception)})))}) context {:important :runtime-value}] (doseq [standard-exception [(IllegalArgumentException. "Well that's strange.") (ConnectException. "Connection refused.")]] (let [result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] (throw standard-exception))} (check-fn context result-cb)) (let [result (deref result-promise 500 nil)] (is (salutem/unhealthy? result)) (is (= (.getMessage ^Exception standard-exception) (:message result))) (is (= :runtime-value (:important result)))))))) (deftest http-endpoint-check-fn-logs-on-start-when-logger-in-context (let [logger (ct/logger) context {:logger logger} url "http://service.example.com/ping" method :head query-params {:caller "thing-service"} headers {"x-important-header" 56} body "ping" check-fn (scfhe/http-endpoint-check-fn url {:method method :query-params query-params :headers headers :body body}) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {url (fn [_] {:status 200})} (check-fn context result-cb)) (deref result-promise 500 nil) (is (logged? logger {:context {:url url :method method :query-params query-params :headers headers :body body} :level :info :type :salutem.check-fns.http-endpoint/check.starting})))) (deftest http-endpoint-check-fn-logs-on-response-when-logger-in-context (let [logger (ct/logger) context {:logger logger} url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn url) result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {url (fn [_] {:status 200})} (check-fn context result-cb)) (deref result-promise 500 nil) (is (logged? logger {:level :info :type :salutem.check-fns.http-endpoint/check.successful})))) (deftest http-endpoint-check-fn-logs-on-timeout-exceptions-when-logger-in-context (let [logger (ct/logger) context {:logger logger} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url)] (doseq [timeout-exception [(ConnectTimeoutException. "We're out of time.") (SocketTimeoutException. "We're out of time.") (ConnectException. "Timeout when connecting.")]] (let [result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] (throw timeout-exception))} (check-fn context result-cb)) (deref result-promise 500 nil) (is (logged? logger {:context {:reason :timed-out} :exception timeout-exception :level :warn :type :salutem.check-fns.http-endpoint/check.failed})))))) (deftest http-endpoint-check-fn-logs-on-other-exceptions-when-logger-in-context (let [logger (ct/logger) context {:logger logger} endpoint-url "http://service.example.com/ping" check-fn (scfhe/http-endpoint-check-fn endpoint-url)] (doseq [standard-exception [(IllegalArgumentException. "Well that's strange.") (ConnectException. "Connection refused.")]] (let [result-promise (promise) result-cb (partial deliver result-promise)] (http/with-global-fake-routes-in-isolation {endpoint-url (fn [_] (throw standard-exception))} (check-fn context result-cb)) (deref result-promise 500 nil) (is (logged? logger {:context {:reason :threw-exception} :exception standard-exception :level :warn :type :salutem.check-fns.http-endpoint/check.failed}))))))
[ { "context": "(ns \n #^{:author \"Matt Revelle\"\n :doc \"OAuth client library for Clojure.\"}", "end": 33, "score": 0.9998891949653625, "start": 21, "tag": "NAME", "value": "Matt Revelle" }, { "context": "ame username\n :x_auth_password password\n :x_auth_mode \"client_auth\"}\n", "end": 4266, "score": 0.9973751306533813, "start": 4258, "tag": "PASSWORD", "value": "password" } ]
src/oauth/client.clj
adamwynne/clj-oauth
1
(ns #^{:author "Matt Revelle" :doc "OAuth client library for Clojure."} oauth.client (:require [oauth.digest :as digest] [oauth.signature :as sig] [com.twinql.clojure.http :as http] [clojure.string :as str])) (declare success-content authorization-header) (defrecord #^{:doc "OAuth consumer"} consumer [key secret request-uri access-uri authorize-uri signature-method]) (defn check-success-response [m] (let [code (:code m)] (if (or (< code 200) (>= code 300)) (throw (new Exception (str "Got non-success response " code "."))) m))) (defn success-content [m] (:content (check-success-response m))) (defn make-consumer "Make a consumer struct map." [key secret request-uri access-uri authorize-uri signature-method] (consumer. key secret request-uri access-uri authorize-uri signature-method)) ;;; Parse form-encoded bodies from OAuth responses. (defmethod http/entity-as :urldecoded [entity as status] (into {} (if-let [body (http/entity-as entity :string status)] (map (fn [kv] (let [[k v] (str/split kv #"=") k (or k "") v (or v "")] [(keyword (sig/url-decode k)) (sig/url-decode v)])) (str/split body #"&")) nil))) (defn request-token "Fetch request token for the consumer." [consumer & {:as args}] (let [extra-parameters (:parameters args) query (:query args) unsigned-params (merge (sig/oauth-params consumer) extra-parameters) signature (sig/sign consumer (sig/base-string "POST" (:request-uri consumer) (merge unsigned-params query))) params (assoc unsigned-params :oauth_signature signature)] (success-content (http/post (:request-uri consumer) :headers {"Authorization" (authorization-header params)} :parameters (http/map->params {:use-expect-continue false}) :query query :as :urldecoded)))) (defn user-approval-uri "Builds the URI to the Service Provider where the User will be prompted to approve the Consumer's access to their account." [consumer token & {:as rest}] (.toString (http/resolve-uri (:authorize-uri consumer) (merge rest {:oauth_token token})))) (defn access-token "Exchange a request token for an access token. When provided with two arguments, this function operates as per OAuth 1.0. With three arguments, a verifier is used." ([consumer request-token] (access-token consumer request-token nil)) ([consumer request-token verifier] (let [unsigned-params (if verifier (sig/oauth-params consumer (:oauth_token request-token) verifier) (sig/oauth-params consumer (:oauth_token request-token))) signature (sig/sign consumer (sig/base-string "POST" (:access-uri consumer) unsigned-params) (:oauth_token_secret request-token)) params (assoc unsigned-params :oauth_signature signature)] (success-content (http/post (:access-uri consumer) :headers {"Authorization" (authorization-header params)} :parameters (http/map->params {:use-expect-continue false}) :as :urldecoded))))) (defn xauth-access-token "Request an access token with a username and password with xAuth." [consumer username password] (let [oauth-params (sig/oauth-params consumer) post-params {:x_auth_username username :x_auth_password password :x_auth_mode "client_auth"} signature (sig/sign consumer (sig/base-string "POST" (:access-uri consumer) (merge oauth-params post-params))) params (assoc oauth-params :oauth_signature signature)] (success-content (http/post (:access-uri consumer) :query post-params :headers {"Authorization" (authorization-header params)} :parameters (http/map->params {:use-expect-continue false}) :as :urldecoded)))) (defn credentials "Return authorization credentials needed for access to protected resources. The key-value pairs returned as a map will need to be added to the Authorization HTTP header or added as query parameters to the request." ([consumer token token-secret request-method request-uri & [request-params]] (let [unsigned-oauth-params (sig/oauth-params consumer token) unsigned-params (merge request-params unsigned-oauth-params) signature (sig/sign consumer (sig/base-string (-> request-method name str/upper-case) request-uri unsigned-params) token-secret)] (assoc unsigned-oauth-params :oauth_signature signature)))) (defn authorization-header "OAuth credentials formatted for the Authorization HTTP header." ([oauth-params] (str "OAuth " (str/join ", " (map (fn [[k v]] (str (-> k name sig/url-encode) "=\"" (-> v str sig/url-encode) "\"")) oauth-params)))) ([oauth-params realm] (authorization-header (assoc oauth-params realm)))) (defn check-success-response [m] (let [code (:code m) reason (:reason m)] (if (or (< code 200) (>= code 300)) (throw (new Exception (str "Got non-success code: " code ". " "Reason: " reason ", " "Content: " (:content m)))) m))) (defn success-content [m] (:content (check-success-response m)))
95839
(ns #^{:author "<NAME>" :doc "OAuth client library for Clojure."} oauth.client (:require [oauth.digest :as digest] [oauth.signature :as sig] [com.twinql.clojure.http :as http] [clojure.string :as str])) (declare success-content authorization-header) (defrecord #^{:doc "OAuth consumer"} consumer [key secret request-uri access-uri authorize-uri signature-method]) (defn check-success-response [m] (let [code (:code m)] (if (or (< code 200) (>= code 300)) (throw (new Exception (str "Got non-success response " code "."))) m))) (defn success-content [m] (:content (check-success-response m))) (defn make-consumer "Make a consumer struct map." [key secret request-uri access-uri authorize-uri signature-method] (consumer. key secret request-uri access-uri authorize-uri signature-method)) ;;; Parse form-encoded bodies from OAuth responses. (defmethod http/entity-as :urldecoded [entity as status] (into {} (if-let [body (http/entity-as entity :string status)] (map (fn [kv] (let [[k v] (str/split kv #"=") k (or k "") v (or v "")] [(keyword (sig/url-decode k)) (sig/url-decode v)])) (str/split body #"&")) nil))) (defn request-token "Fetch request token for the consumer." [consumer & {:as args}] (let [extra-parameters (:parameters args) query (:query args) unsigned-params (merge (sig/oauth-params consumer) extra-parameters) signature (sig/sign consumer (sig/base-string "POST" (:request-uri consumer) (merge unsigned-params query))) params (assoc unsigned-params :oauth_signature signature)] (success-content (http/post (:request-uri consumer) :headers {"Authorization" (authorization-header params)} :parameters (http/map->params {:use-expect-continue false}) :query query :as :urldecoded)))) (defn user-approval-uri "Builds the URI to the Service Provider where the User will be prompted to approve the Consumer's access to their account." [consumer token & {:as rest}] (.toString (http/resolve-uri (:authorize-uri consumer) (merge rest {:oauth_token token})))) (defn access-token "Exchange a request token for an access token. When provided with two arguments, this function operates as per OAuth 1.0. With three arguments, a verifier is used." ([consumer request-token] (access-token consumer request-token nil)) ([consumer request-token verifier] (let [unsigned-params (if verifier (sig/oauth-params consumer (:oauth_token request-token) verifier) (sig/oauth-params consumer (:oauth_token request-token))) signature (sig/sign consumer (sig/base-string "POST" (:access-uri consumer) unsigned-params) (:oauth_token_secret request-token)) params (assoc unsigned-params :oauth_signature signature)] (success-content (http/post (:access-uri consumer) :headers {"Authorization" (authorization-header params)} :parameters (http/map->params {:use-expect-continue false}) :as :urldecoded))))) (defn xauth-access-token "Request an access token with a username and password with xAuth." [consumer username password] (let [oauth-params (sig/oauth-params consumer) post-params {:x_auth_username username :x_auth_password <PASSWORD> :x_auth_mode "client_auth"} signature (sig/sign consumer (sig/base-string "POST" (:access-uri consumer) (merge oauth-params post-params))) params (assoc oauth-params :oauth_signature signature)] (success-content (http/post (:access-uri consumer) :query post-params :headers {"Authorization" (authorization-header params)} :parameters (http/map->params {:use-expect-continue false}) :as :urldecoded)))) (defn credentials "Return authorization credentials needed for access to protected resources. The key-value pairs returned as a map will need to be added to the Authorization HTTP header or added as query parameters to the request." ([consumer token token-secret request-method request-uri & [request-params]] (let [unsigned-oauth-params (sig/oauth-params consumer token) unsigned-params (merge request-params unsigned-oauth-params) signature (sig/sign consumer (sig/base-string (-> request-method name str/upper-case) request-uri unsigned-params) token-secret)] (assoc unsigned-oauth-params :oauth_signature signature)))) (defn authorization-header "OAuth credentials formatted for the Authorization HTTP header." ([oauth-params] (str "OAuth " (str/join ", " (map (fn [[k v]] (str (-> k name sig/url-encode) "=\"" (-> v str sig/url-encode) "\"")) oauth-params)))) ([oauth-params realm] (authorization-header (assoc oauth-params realm)))) (defn check-success-response [m] (let [code (:code m) reason (:reason m)] (if (or (< code 200) (>= code 300)) (throw (new Exception (str "Got non-success code: " code ". " "Reason: " reason ", " "Content: " (:content m)))) m))) (defn success-content [m] (:content (check-success-response m)))
true
(ns #^{:author "PI:NAME:<NAME>END_PI" :doc "OAuth client library for Clojure."} oauth.client (:require [oauth.digest :as digest] [oauth.signature :as sig] [com.twinql.clojure.http :as http] [clojure.string :as str])) (declare success-content authorization-header) (defrecord #^{:doc "OAuth consumer"} consumer [key secret request-uri access-uri authorize-uri signature-method]) (defn check-success-response [m] (let [code (:code m)] (if (or (< code 200) (>= code 300)) (throw (new Exception (str "Got non-success response " code "."))) m))) (defn success-content [m] (:content (check-success-response m))) (defn make-consumer "Make a consumer struct map." [key secret request-uri access-uri authorize-uri signature-method] (consumer. key secret request-uri access-uri authorize-uri signature-method)) ;;; Parse form-encoded bodies from OAuth responses. (defmethod http/entity-as :urldecoded [entity as status] (into {} (if-let [body (http/entity-as entity :string status)] (map (fn [kv] (let [[k v] (str/split kv #"=") k (or k "") v (or v "")] [(keyword (sig/url-decode k)) (sig/url-decode v)])) (str/split body #"&")) nil))) (defn request-token "Fetch request token for the consumer." [consumer & {:as args}] (let [extra-parameters (:parameters args) query (:query args) unsigned-params (merge (sig/oauth-params consumer) extra-parameters) signature (sig/sign consumer (sig/base-string "POST" (:request-uri consumer) (merge unsigned-params query))) params (assoc unsigned-params :oauth_signature signature)] (success-content (http/post (:request-uri consumer) :headers {"Authorization" (authorization-header params)} :parameters (http/map->params {:use-expect-continue false}) :query query :as :urldecoded)))) (defn user-approval-uri "Builds the URI to the Service Provider where the User will be prompted to approve the Consumer's access to their account." [consumer token & {:as rest}] (.toString (http/resolve-uri (:authorize-uri consumer) (merge rest {:oauth_token token})))) (defn access-token "Exchange a request token for an access token. When provided with two arguments, this function operates as per OAuth 1.0. With three arguments, a verifier is used." ([consumer request-token] (access-token consumer request-token nil)) ([consumer request-token verifier] (let [unsigned-params (if verifier (sig/oauth-params consumer (:oauth_token request-token) verifier) (sig/oauth-params consumer (:oauth_token request-token))) signature (sig/sign consumer (sig/base-string "POST" (:access-uri consumer) unsigned-params) (:oauth_token_secret request-token)) params (assoc unsigned-params :oauth_signature signature)] (success-content (http/post (:access-uri consumer) :headers {"Authorization" (authorization-header params)} :parameters (http/map->params {:use-expect-continue false}) :as :urldecoded))))) (defn xauth-access-token "Request an access token with a username and password with xAuth." [consumer username password] (let [oauth-params (sig/oauth-params consumer) post-params {:x_auth_username username :x_auth_password PI:PASSWORD:<PASSWORD>END_PI :x_auth_mode "client_auth"} signature (sig/sign consumer (sig/base-string "POST" (:access-uri consumer) (merge oauth-params post-params))) params (assoc oauth-params :oauth_signature signature)] (success-content (http/post (:access-uri consumer) :query post-params :headers {"Authorization" (authorization-header params)} :parameters (http/map->params {:use-expect-continue false}) :as :urldecoded)))) (defn credentials "Return authorization credentials needed for access to protected resources. The key-value pairs returned as a map will need to be added to the Authorization HTTP header or added as query parameters to the request." ([consumer token token-secret request-method request-uri & [request-params]] (let [unsigned-oauth-params (sig/oauth-params consumer token) unsigned-params (merge request-params unsigned-oauth-params) signature (sig/sign consumer (sig/base-string (-> request-method name str/upper-case) request-uri unsigned-params) token-secret)] (assoc unsigned-oauth-params :oauth_signature signature)))) (defn authorization-header "OAuth credentials formatted for the Authorization HTTP header." ([oauth-params] (str "OAuth " (str/join ", " (map (fn [[k v]] (str (-> k name sig/url-encode) "=\"" (-> v str sig/url-encode) "\"")) oauth-params)))) ([oauth-params realm] (authorization-header (assoc oauth-params realm)))) (defn check-success-response [m] (let [code (:code m) reason (:reason m)] (if (or (< code 200) (>= code 300)) (throw (new Exception (str "Got non-success code: " code ". " "Reason: " reason ", " "Content: " (:content m)))) m))) (defn success-content [m] (:content (check-success-response m)))
[ { "context": "es)\n;;=> (* string?)\n\n(s/conform ::seq-of-names [\"Makoto Hashimoto\" \"Nicolas Modrzyk\"])\n;;=> [\"Makoto Hashimoto\" \"Ni", "end": 281, "score": 0.9998263716697693, "start": 265, "tag": "NAME", "value": "Makoto Hashimoto" }, { "context": ")\n\n(s/conform ::seq-of-names [\"Makoto Hashimoto\" \"Nicolas Modrzyk\"])\n;;=> [\"Makoto Hashimoto\" \"Nicolas Modrzyk\"]\n\n(", "end": 299, "score": 0.9998712539672852, "start": 284, "tag": "NAME", "value": "Nicolas Modrzyk" }, { "context": "es [\"Makoto Hashimoto\" \"Nicolas Modrzyk\"])\n;;=> [\"Makoto Hashimoto\" \"Nicolas Modrzyk\"]\n\n(s/conform ::seq-of-names [:", "end": 326, "score": 0.9998332858085632, "start": 310, "tag": "NAME", "value": "Makoto Hashimoto" }, { "context": "to\" \"Nicolas Modrzyk\"])\n;;=> [\"Makoto Hashimoto\" \"Nicolas Modrzyk\"]\n\n(s/conform ::seq-of-names [:Makoto-Hashimoto \"", "end": 344, "score": 0.9998711347579956, "start": 329, "tag": "NAME", "value": "Nicolas Modrzyk" }, { "context": "\" \"Nicolas Modrzyk\"]\n\n(s/conform ::seq-of-names [:Makoto-Hashimoto \"Nicolas Modrzyk\"])\n;;=> :clojure.spec/invalid\n\n(", "end": 392, "score": 0.9626339077949524, "start": 376, "tag": "NAME", "value": "Makoto-Hashimoto" }, { "context": "\"]\n\n(s/conform ::seq-of-names [:Makoto-Hashimoto \"Nicolas Modrzyk\"])\n;;=> :clojure.spec/invalid\n\n(s/def ::date (s/m", "end": 409, "score": 0.9998501539230347, "start": 394, "tag": "NAME", "value": "Nicolas Modrzyk" } ]
Chapter 07 Code/spec-example/src/spec_example/core.clj
PacktPublishing/Clojure-Programming-Cookbook
14
(ns spec-example.core (:require [clojure.spec :as s] [clojure.spec.test :as stest] ) ) (s/def ::seq-of-names (s/* string?)) ;;=> :spec-example.core/seq-of-names (s/describe ::seq-of-names) ;;=> (* string?) (s/conform ::seq-of-names ["Makoto Hashimoto" "Nicolas Modrzyk"]) ;;=> ["Makoto Hashimoto" "Nicolas Modrzyk"] (s/conform ::seq-of-names [:Makoto-Hashimoto "Nicolas Modrzyk"]) ;;=> :clojure.spec/invalid (s/def ::date (s/map-of keyword? integer?)) ;;=> :spec-example.core/date (s/conform ::date {:year 2016}) ;;=> {:year 2016} (s/conform ::date {:year 2016 :date 10 :month 7}) ;;=> {:year 2016, :date 10, :month 7} (s/valid? #{"01" "02" "03"} "01") ;;=> true (s/valid? #{"01" "02" "03"} "04") ;;=> false (s/valid? (s/nilable string?) "test") ;;=> true (s/valid? (s/nilable string?) nil) ;;=> true (s/valid? (s/nilable string?) 1) ;;=> false (s/def ::small-int #(<= -32768 % 32767)) ;;=> :spec-example.core/small-int (s/conform ::small-int 10) ;;=> 10 (s/conform ::small-int 50000) ;;=> :clojure.spec/invalid (defn positive-int-add [x y] (+ x y)) ;;=> #'spec-example.core/positive-int-add (s/fdef positive-int-add :args (s/and (s/cat :x integer? :y integer?) #(and (< 0 (:x %) )(< 0 (:y %) ))) :ret integer?) ;;=> spec-example.core/positive-int-add (positive-int-add 1 10) ;;=> 11 (positive-int-add 1 -20) ;;=> -19 (stest/instrument 'positive-int-add) ;;=> #'spec-example.core/positive-int-add (positive-int-add 1 -20) ;;=> ExceptionInfo Call to #'spec-example.core/positive-int-add did not conform to spec: ;;=> val: {:x 1, :y -20} fails at: [:args] predicate: (and (< 0 (:x %)) (< 0 (:y %))) ;;=> :clojure.spec/args (1 -20) ;;=> clojure.core/ex-info (core.clj:4703)
2225
(ns spec-example.core (:require [clojure.spec :as s] [clojure.spec.test :as stest] ) ) (s/def ::seq-of-names (s/* string?)) ;;=> :spec-example.core/seq-of-names (s/describe ::seq-of-names) ;;=> (* string?) (s/conform ::seq-of-names ["<NAME>" "<NAME>"]) ;;=> ["<NAME>" "<NAME>"] (s/conform ::seq-of-names [:<NAME> "<NAME>"]) ;;=> :clojure.spec/invalid (s/def ::date (s/map-of keyword? integer?)) ;;=> :spec-example.core/date (s/conform ::date {:year 2016}) ;;=> {:year 2016} (s/conform ::date {:year 2016 :date 10 :month 7}) ;;=> {:year 2016, :date 10, :month 7} (s/valid? #{"01" "02" "03"} "01") ;;=> true (s/valid? #{"01" "02" "03"} "04") ;;=> false (s/valid? (s/nilable string?) "test") ;;=> true (s/valid? (s/nilable string?) nil) ;;=> true (s/valid? (s/nilable string?) 1) ;;=> false (s/def ::small-int #(<= -32768 % 32767)) ;;=> :spec-example.core/small-int (s/conform ::small-int 10) ;;=> 10 (s/conform ::small-int 50000) ;;=> :clojure.spec/invalid (defn positive-int-add [x y] (+ x y)) ;;=> #'spec-example.core/positive-int-add (s/fdef positive-int-add :args (s/and (s/cat :x integer? :y integer?) #(and (< 0 (:x %) )(< 0 (:y %) ))) :ret integer?) ;;=> spec-example.core/positive-int-add (positive-int-add 1 10) ;;=> 11 (positive-int-add 1 -20) ;;=> -19 (stest/instrument 'positive-int-add) ;;=> #'spec-example.core/positive-int-add (positive-int-add 1 -20) ;;=> ExceptionInfo Call to #'spec-example.core/positive-int-add did not conform to spec: ;;=> val: {:x 1, :y -20} fails at: [:args] predicate: (and (< 0 (:x %)) (< 0 (:y %))) ;;=> :clojure.spec/args (1 -20) ;;=> clojure.core/ex-info (core.clj:4703)
true
(ns spec-example.core (:require [clojure.spec :as s] [clojure.spec.test :as stest] ) ) (s/def ::seq-of-names (s/* string?)) ;;=> :spec-example.core/seq-of-names (s/describe ::seq-of-names) ;;=> (* string?) (s/conform ::seq-of-names ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]) ;;=> ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"] (s/conform ::seq-of-names [:PI:NAME:<NAME>END_PI "PI:NAME:<NAME>END_PI"]) ;;=> :clojure.spec/invalid (s/def ::date (s/map-of keyword? integer?)) ;;=> :spec-example.core/date (s/conform ::date {:year 2016}) ;;=> {:year 2016} (s/conform ::date {:year 2016 :date 10 :month 7}) ;;=> {:year 2016, :date 10, :month 7} (s/valid? #{"01" "02" "03"} "01") ;;=> true (s/valid? #{"01" "02" "03"} "04") ;;=> false (s/valid? (s/nilable string?) "test") ;;=> true (s/valid? (s/nilable string?) nil) ;;=> true (s/valid? (s/nilable string?) 1) ;;=> false (s/def ::small-int #(<= -32768 % 32767)) ;;=> :spec-example.core/small-int (s/conform ::small-int 10) ;;=> 10 (s/conform ::small-int 50000) ;;=> :clojure.spec/invalid (defn positive-int-add [x y] (+ x y)) ;;=> #'spec-example.core/positive-int-add (s/fdef positive-int-add :args (s/and (s/cat :x integer? :y integer?) #(and (< 0 (:x %) )(< 0 (:y %) ))) :ret integer?) ;;=> spec-example.core/positive-int-add (positive-int-add 1 10) ;;=> 11 (positive-int-add 1 -20) ;;=> -19 (stest/instrument 'positive-int-add) ;;=> #'spec-example.core/positive-int-add (positive-int-add 1 -20) ;;=> ExceptionInfo Call to #'spec-example.core/positive-int-add did not conform to spec: ;;=> val: {:x 1, :y -20} fails at: [:args] predicate: (and (< 0 (:x %)) (< 0 (:y %))) ;;=> :clojure.spec/args (1 -20) ;;=> clojure.core/ex-info (core.clj:4703)
[ { "context": " siths))\n(def x [{:sith/id 3616, :sith/name \"Darth Sidious\", :sith/master 2350, :sith/apprentice 1489, :sith", "end": 7291, "score": 0.9998606443405151, "start": 7278, "tag": "NAME", "value": "Darth Sidious" }, { "context": "o\", :homeWorld/id 7}} {:sith/id 1489, :sith/name \"Darth Vader\", :sith/master 3616, :sith/apprentice 1330, :sith", "end": 7435, "score": 0.9998262524604797, "start": 7424, "tag": "NAME", "value": "Darth Vader" }, { "context": "\", :homeWorld/id 18}} {:sith/id 1330, :sith/name \"Antinnis Tremayne\", :sith/master 1489, :sith/homeWorld {:homeWorld/", "end": 7589, "score": 0.9998689293861389, "start": 7572, "tag": "NAME", "value": "Antinnis Tremayne" }, { "context": "get-initial-state Sith {:sith/id 3616 :sith/name \"Darth\"})\n df/marker-table can be used to keep track of", "end": 13373, "score": 0.9758812189102173, "start": 13368, "tag": "NAME", "value": "Darth" } ]
submissions/theianjones/src/main/app/view.cljs
theianjones/flux-challenge
0
(ns app.view (:require [com.fulcrologic.fulcro.application :as app] [com.fulcrologic.fulcro.components :as comp :refer [defsc]] [com.fulcrologic.fulcro.mutations :as m :refer [defmutation]] [com.fulcrologic.fulcro.dom :as dom] [com.fulcrologic.fulcro.data-fetch :as df] [app.proxy :refer [sith-output]])) (comment we are adding the apprentice/master ident to the [:siths :list/siths] ui edge. Then we fetch the data for that sith. When the data comes back, we display the sith slot.) ;; (defmutation load-sith [{:keys [query-class] :sith/keys [id] :as params}] ;; (action [{:keys [app state]}] ;; (swap! state assoc-in [:siths :list/siths] (add-to-list @state id)) ;; (df/load! app [:sith/id id] query-class))) (comment we could just put a df/load into the mutations... you could load from the Sith component. When the mutation is in a cljc file, then you cant import your mutations as well as importing your cljs component into the cljc file... clojure doesnt like you going back and forth like that. (df/load! app [:person/id id] PersonDetail)) (comment "this is the mutation we use to disable the buttons to load more siths.") (defmutation set-button [{:keys [button-key button-value]}] (action [{:keys [app state]}] (swap! state assoc button-key button-value))) (defn toggle-button-enabled [component value] " This function disables the down button if the apprentice does not exist. It also disables the up button if the master doesnt exist. " (let [p (comp/props component) master-exists? (some? (:sith/master p)) apprentice-exists? (some? (:sith/apprentice p))] (when (not apprentice-exists?) (comp/transact! component [(set-button {:button-key :down-enabled :button-value value})])) (when (not master-exists?) (comp/transact! component [(set-button {:button-key :up-enabled :button-value value})])))) (comment "We want to load the sith and disable any buttons if the data for this sith doesnt have the attributes we are looking for") (defsc Sith [this {:sith/keys [id name homeWorld] :as props}] {:query [:sith/id :sith/name :sith/master :sith/apprentice {:sith/homeWorld [:homeWorld/name :homeWorld/id]}] :ident :sith/id :componentDidMount #(toggle-button-enabled % false) :componentWillUnmount #(toggle-button-enabled % true)} (dom/div (dom/h3 name) (dom/h6 "Homeworld: " (dom/span (:homeWorld/name homeWorld))))) (def ui-sith "we can define what attribute we want react to use as a key if we are mapping over a list with this component." (comp/factory Sith {:keyfn :sith/id})) (defn load-sith [query-component component where id] " We pass the query-component so that this function doesnt have to live in this file. The second argument is the component we are loading the sith from. It takes which slot to target when the data loads as the third argument. This function will create the sith ident from the id in the fourth argument." (let [load-target [:slot/by-id where :slot/sith] sith-ident [:sith/id id]] (df/load! component sith-ident query-component {:target load-target :abort-id :jedi}))) (comment "This is component does a lot of the heavy lifting. We can target each of these component slots to load a sith into that slot. When the component mounts, We load the apprentice in the slot below this slot (if it exists) and we load the master in the slot above (if it exists). This assumes that the slot is empty.") (defsc SithSlot [this {:db/keys [id] :slot/keys [sith] :as props} {:keys [at-home?]}] {:query [:db/id {:slot/sith (comp/get-query Sith)}] :initial-state (fn [{:keys [id]}] {:db/id id :slot/sith nil}) :ident [:slot/by-id :db/id] :componentDidUpdate (fn [this prev-props _] (let [p (comp/props this) at-home? (:at-home? (comp/get-computed this)) app-id (-> p :slot/sith :sith/apprentice) app-target (:app-target (comp/get-computed this)) mas-id (-> p :slot/sith :sith/master) mas-target (:mas-target (comp/get-computed this))] (when (and app-id app-target) (load-sith Sith this app-target app-id)) (when (and mas-id mas-target) (load-sith Sith this mas-target mas-id))))} (dom/li :.css-slot {:className (if at-home? "red" "")} (when (some? sith) (ui-sith sith)))) (def ui-slot (comp/factory SithSlot {:keyfn :db/id})) (defn slot->app-target [slot-id] "given a slot id (:one :two :three etc) we add one to that slot for an apprentice" (slot-id {:one :two :two :three :three :four :four :five})) (defn slot->mas-target [slot-id] "given a slot id (:one :two :three etc) we subtract one to that slot number for their master" (slot-id {:two :one :three :two :four :three :five :four})) (defn target-occupied? [slots-data slot-id] "determines if the give slot is currently empty" (reduce (fn [target-occupied? [id val]] (if (= (:db/id val) slot-id) (some? (:slot/sith val)) target-occupied?)) false slots-data)) (defn slot-at-home? [slots slot-id current-planet] "determines if the current planet and the sith's homeworld in a give slot match" (reduce (fn [at-home? [_ val]] (if (= (:db/id val) slot-id) (= (-> val :slot/sith :sith/homeWorld :homeWorld/name) current-planet) at-home?)) false slots)) (defn get-slot-props [component slot-id] "generates the props so that the SithSlot component can load their master or apprentice correctly. For example, this function will return an app-target for a given slot if that :slot/sith has a :sith/apprentice and the slot below it is not occupied. This way the SithSlot component knows to load a sith purely based on the presence of the app-target or mas-target." (let [props (comp/props component) current-planet (comp/get-computed component :current-planet) app-target (slot->app-target slot-id) app-target-occupied? (not (target-occupied? props app-target)) mas-target (slot->mas-target slot-id) mas-target-occupied? (not (target-occupied? props mas-target))] {:app-target (and app-target-occupied? app-target) :mas-target (and mas-target-occupied? mas-target) :at-home? (slot-at-home? props slot-id current-planet)})) (defn set-both-buttons [component value] (comp/transact! component [(set-button {:button-key :down-enabled :button-value value}) (set-button {:button-key :up-enabled :button-value value})])) (defn compact [col] (remove nil? col)) (defn slots->siths [slots] (compact (map (fn [[_ slot]] (:slot/sith slot)) slots))) (defn all-sith-have-attr? [siths attr] (reduce (fn [master-or-appr-missing? sith] (or master-or-appr-missing? (not (some? (attr sith))))) false siths)) (def x [{:sith/id 3616, :sith/name "Darth Sidious", :sith/master 2350, :sith/apprentice 1489, :sith/homeWorld {:homeWorld/name "Naboo", :homeWorld/id 7}} {:sith/id 1489, :sith/name "Darth Vader", :sith/master 3616, :sith/apprentice 1330, :sith/homeWorld {:homeWorld/name "Tatooine", :homeWorld/id 18}} {:sith/id 1330, :sith/name "Antinnis Tremayne", :sith/master 1489, :sith/homeWorld {:homeWorld/name "Coruscant", :homeWorld/id 58}}]) (all-sith-have-attr? x :sith/apprentice) (defn update-buttons [component] (let [props (comp/props component) computed (comp/get-computed component) current-planet (:current-planet computed) siths (slots->siths props) sith-at-home-detected? (reduce (fn [detected-at-home? {:sith/keys [homeWorld]}] (or (= (:homeWorld/name homeWorld) current-planet) detected-at-home?)) false siths) master-missing? (all-sith-have-attr? siths :sith/master) appr-missing? (all-sith-have-attr? siths :sith/apprentice)] (if sith-at-home-detected? (do ;; (app/abort! component :jedi) pathom remote doesnt support aborting requests (set-both-buttons component false)) (comp/transact! component [(set-button {:button-key :down-enabled :button-value (not appr-missing?)}) (set-button {:button-key :up-enabled :button-value (not master-missing?)})])))) (defsc SithList [this {:slot/keys [one two three four five] :as props}] {:query [{:slot/one (comp/get-query SithSlot)} {:slot/two (comp/get-query SithSlot)} {:slot/three (comp/get-query SithSlot)} {:slot/four (comp/get-query SithSlot)} {:slot/five (comp/get-query SithSlot)}] :initial-state (fn [_] {:slot/one (comp/get-initial-state SithSlot {:id :one}) :slot/two (comp/get-initial-state SithSlot {:id :two}) :slot/three (comp/get-initial-state SithSlot {:id :three}) :slot/four (comp/get-initial-state SithSlot {:id :four}) :slot/five (comp/get-initial-state SithSlot {:id :five})}) :ident (fn [] [:LIST :only-one]) :componentDidUpdate (fn [this _ _] (update-buttons this))} (dom/ul :.css-slots (ui-slot (comp/computed one (get-slot-props this :one))) (ui-slot (comp/computed two (get-slot-props this :two))) (ui-slot (comp/computed three (get-slot-props this :three))) (ui-slot (comp/computed four (get-slot-props this :four))) (ui-slot (comp/computed five (get-slot-props this :five))))) (def ui-sith-list (comp/factory SithList {:keyfn :db/id})) (defn merge-ident [slot new-ident] (merge slot {:slot/sith new-ident})) (defmutation navigate-up [_] (action [{:keys [app state]}] (let [old-slots (:slot/by-id @state) new-slot-one (merge-ident (:one old-slots) nil) new-slot-two (merge-ident (:two old-slots) nil) new-slot-three (merge-ident (:three old-slots) (-> old-slots :one :slot/sith)) new-slot-four (merge-ident (:four old-slots) (-> old-slots :two :slot/sith)) new-slot-five (merge-ident (:five old-slots) (-> old-slots :three :slot/sith)) new-slots {:one new-slot-one :two new-slot-two :three new-slot-three :four new-slot-four :five new-slot-five}] (swap! state assoc :slot/by-id new-slots)))) (defmutation navigate-down [_] (action [{:keys [app state]}] (let [old-slots (:slot/by-id @state) new-slot-one (merge-ident (:one old-slots) (-> old-slots :three :slot/sith)) new-slot-two (merge-ident (:two old-slots) (-> old-slots :four :slot/sith)) new-slot-three (merge-ident (:three old-slots) (-> old-slots :five :slot/sith)) new-slot-four (merge-ident (:four old-slots) nil) new-slot-five (merge-ident (:five old-slots) nil) new-slots {:one new-slot-one :two new-slot-two :three new-slot-three :four new-slot-four :five new-slot-five}] (swap! state assoc :slot/by-id new-slots)))) (defmutation set-current-planet [{:keys [planet]}] (action [{:keys [app state]}] (swap! state assoc :current-planet planet))) (defsc Root [this {:keys [root/list up-enabled down-enabled current-planet] :as props}] {:query [{:root/list (comp/get-query SithList)} :up-enabled :down-enabled {:current-planet [:id :name]}] :initial-state (fn [params] {:root/list (comp/get-initial-state SithList {}) :up-enabled true :down-enabled true :current-planet {:id 32, :name "Utapau"}})} (dom/div :.css-root (dom/h1 :.css-planet-monitor "Obi-Wan currently on: " (dom/span (:name current-planet))) (dom/section :.css-scrollable-list (ui-sith-list (comp/computed list {:current-planet (:name current-planet)})) (dom/div :.css-scroll-buttons (dom/button :.css-button-up {:className (if up-enabled "" "css-button-disabled") :disabled (not update-in) :onClick #(when up-enabled (comp/transact! this [(navigate-up)]))}) (dom/button :.css-button-down {:className (if down-enabled "" "css-button-disabled") :disabled (not down-enabled) :onClick #(when down-enabled (comp/transact! this [(navigate-down)]))}))))) (comment (comp/get-initial-state Sith {:sith/id 3616 :sith/name "Darth"}) df/marker-table can be used to keep track of loading states merge/remove-ident*)
88758
(ns app.view (:require [com.fulcrologic.fulcro.application :as app] [com.fulcrologic.fulcro.components :as comp :refer [defsc]] [com.fulcrologic.fulcro.mutations :as m :refer [defmutation]] [com.fulcrologic.fulcro.dom :as dom] [com.fulcrologic.fulcro.data-fetch :as df] [app.proxy :refer [sith-output]])) (comment we are adding the apprentice/master ident to the [:siths :list/siths] ui edge. Then we fetch the data for that sith. When the data comes back, we display the sith slot.) ;; (defmutation load-sith [{:keys [query-class] :sith/keys [id] :as params}] ;; (action [{:keys [app state]}] ;; (swap! state assoc-in [:siths :list/siths] (add-to-list @state id)) ;; (df/load! app [:sith/id id] query-class))) (comment we could just put a df/load into the mutations... you could load from the Sith component. When the mutation is in a cljc file, then you cant import your mutations as well as importing your cljs component into the cljc file... clojure doesnt like you going back and forth like that. (df/load! app [:person/id id] PersonDetail)) (comment "this is the mutation we use to disable the buttons to load more siths.") (defmutation set-button [{:keys [button-key button-value]}] (action [{:keys [app state]}] (swap! state assoc button-key button-value))) (defn toggle-button-enabled [component value] " This function disables the down button if the apprentice does not exist. It also disables the up button if the master doesnt exist. " (let [p (comp/props component) master-exists? (some? (:sith/master p)) apprentice-exists? (some? (:sith/apprentice p))] (when (not apprentice-exists?) (comp/transact! component [(set-button {:button-key :down-enabled :button-value value})])) (when (not master-exists?) (comp/transact! component [(set-button {:button-key :up-enabled :button-value value})])))) (comment "We want to load the sith and disable any buttons if the data for this sith doesnt have the attributes we are looking for") (defsc Sith [this {:sith/keys [id name homeWorld] :as props}] {:query [:sith/id :sith/name :sith/master :sith/apprentice {:sith/homeWorld [:homeWorld/name :homeWorld/id]}] :ident :sith/id :componentDidMount #(toggle-button-enabled % false) :componentWillUnmount #(toggle-button-enabled % true)} (dom/div (dom/h3 name) (dom/h6 "Homeworld: " (dom/span (:homeWorld/name homeWorld))))) (def ui-sith "we can define what attribute we want react to use as a key if we are mapping over a list with this component." (comp/factory Sith {:keyfn :sith/id})) (defn load-sith [query-component component where id] " We pass the query-component so that this function doesnt have to live in this file. The second argument is the component we are loading the sith from. It takes which slot to target when the data loads as the third argument. This function will create the sith ident from the id in the fourth argument." (let [load-target [:slot/by-id where :slot/sith] sith-ident [:sith/id id]] (df/load! component sith-ident query-component {:target load-target :abort-id :jedi}))) (comment "This is component does a lot of the heavy lifting. We can target each of these component slots to load a sith into that slot. When the component mounts, We load the apprentice in the slot below this slot (if it exists) and we load the master in the slot above (if it exists). This assumes that the slot is empty.") (defsc SithSlot [this {:db/keys [id] :slot/keys [sith] :as props} {:keys [at-home?]}] {:query [:db/id {:slot/sith (comp/get-query Sith)}] :initial-state (fn [{:keys [id]}] {:db/id id :slot/sith nil}) :ident [:slot/by-id :db/id] :componentDidUpdate (fn [this prev-props _] (let [p (comp/props this) at-home? (:at-home? (comp/get-computed this)) app-id (-> p :slot/sith :sith/apprentice) app-target (:app-target (comp/get-computed this)) mas-id (-> p :slot/sith :sith/master) mas-target (:mas-target (comp/get-computed this))] (when (and app-id app-target) (load-sith Sith this app-target app-id)) (when (and mas-id mas-target) (load-sith Sith this mas-target mas-id))))} (dom/li :.css-slot {:className (if at-home? "red" "")} (when (some? sith) (ui-sith sith)))) (def ui-slot (comp/factory SithSlot {:keyfn :db/id})) (defn slot->app-target [slot-id] "given a slot id (:one :two :three etc) we add one to that slot for an apprentice" (slot-id {:one :two :two :three :three :four :four :five})) (defn slot->mas-target [slot-id] "given a slot id (:one :two :three etc) we subtract one to that slot number for their master" (slot-id {:two :one :three :two :four :three :five :four})) (defn target-occupied? [slots-data slot-id] "determines if the give slot is currently empty" (reduce (fn [target-occupied? [id val]] (if (= (:db/id val) slot-id) (some? (:slot/sith val)) target-occupied?)) false slots-data)) (defn slot-at-home? [slots slot-id current-planet] "determines if the current planet and the sith's homeworld in a give slot match" (reduce (fn [at-home? [_ val]] (if (= (:db/id val) slot-id) (= (-> val :slot/sith :sith/homeWorld :homeWorld/name) current-planet) at-home?)) false slots)) (defn get-slot-props [component slot-id] "generates the props so that the SithSlot component can load their master or apprentice correctly. For example, this function will return an app-target for a given slot if that :slot/sith has a :sith/apprentice and the slot below it is not occupied. This way the SithSlot component knows to load a sith purely based on the presence of the app-target or mas-target." (let [props (comp/props component) current-planet (comp/get-computed component :current-planet) app-target (slot->app-target slot-id) app-target-occupied? (not (target-occupied? props app-target)) mas-target (slot->mas-target slot-id) mas-target-occupied? (not (target-occupied? props mas-target))] {:app-target (and app-target-occupied? app-target) :mas-target (and mas-target-occupied? mas-target) :at-home? (slot-at-home? props slot-id current-planet)})) (defn set-both-buttons [component value] (comp/transact! component [(set-button {:button-key :down-enabled :button-value value}) (set-button {:button-key :up-enabled :button-value value})])) (defn compact [col] (remove nil? col)) (defn slots->siths [slots] (compact (map (fn [[_ slot]] (:slot/sith slot)) slots))) (defn all-sith-have-attr? [siths attr] (reduce (fn [master-or-appr-missing? sith] (or master-or-appr-missing? (not (some? (attr sith))))) false siths)) (def x [{:sith/id 3616, :sith/name "<NAME>", :sith/master 2350, :sith/apprentice 1489, :sith/homeWorld {:homeWorld/name "Naboo", :homeWorld/id 7}} {:sith/id 1489, :sith/name "<NAME>", :sith/master 3616, :sith/apprentice 1330, :sith/homeWorld {:homeWorld/name "Tatooine", :homeWorld/id 18}} {:sith/id 1330, :sith/name "<NAME>", :sith/master 1489, :sith/homeWorld {:homeWorld/name "Coruscant", :homeWorld/id 58}}]) (all-sith-have-attr? x :sith/apprentice) (defn update-buttons [component] (let [props (comp/props component) computed (comp/get-computed component) current-planet (:current-planet computed) siths (slots->siths props) sith-at-home-detected? (reduce (fn [detected-at-home? {:sith/keys [homeWorld]}] (or (= (:homeWorld/name homeWorld) current-planet) detected-at-home?)) false siths) master-missing? (all-sith-have-attr? siths :sith/master) appr-missing? (all-sith-have-attr? siths :sith/apprentice)] (if sith-at-home-detected? (do ;; (app/abort! component :jedi) pathom remote doesnt support aborting requests (set-both-buttons component false)) (comp/transact! component [(set-button {:button-key :down-enabled :button-value (not appr-missing?)}) (set-button {:button-key :up-enabled :button-value (not master-missing?)})])))) (defsc SithList [this {:slot/keys [one two three four five] :as props}] {:query [{:slot/one (comp/get-query SithSlot)} {:slot/two (comp/get-query SithSlot)} {:slot/three (comp/get-query SithSlot)} {:slot/four (comp/get-query SithSlot)} {:slot/five (comp/get-query SithSlot)}] :initial-state (fn [_] {:slot/one (comp/get-initial-state SithSlot {:id :one}) :slot/two (comp/get-initial-state SithSlot {:id :two}) :slot/three (comp/get-initial-state SithSlot {:id :three}) :slot/four (comp/get-initial-state SithSlot {:id :four}) :slot/five (comp/get-initial-state SithSlot {:id :five})}) :ident (fn [] [:LIST :only-one]) :componentDidUpdate (fn [this _ _] (update-buttons this))} (dom/ul :.css-slots (ui-slot (comp/computed one (get-slot-props this :one))) (ui-slot (comp/computed two (get-slot-props this :two))) (ui-slot (comp/computed three (get-slot-props this :three))) (ui-slot (comp/computed four (get-slot-props this :four))) (ui-slot (comp/computed five (get-slot-props this :five))))) (def ui-sith-list (comp/factory SithList {:keyfn :db/id})) (defn merge-ident [slot new-ident] (merge slot {:slot/sith new-ident})) (defmutation navigate-up [_] (action [{:keys [app state]}] (let [old-slots (:slot/by-id @state) new-slot-one (merge-ident (:one old-slots) nil) new-slot-two (merge-ident (:two old-slots) nil) new-slot-three (merge-ident (:three old-slots) (-> old-slots :one :slot/sith)) new-slot-four (merge-ident (:four old-slots) (-> old-slots :two :slot/sith)) new-slot-five (merge-ident (:five old-slots) (-> old-slots :three :slot/sith)) new-slots {:one new-slot-one :two new-slot-two :three new-slot-three :four new-slot-four :five new-slot-five}] (swap! state assoc :slot/by-id new-slots)))) (defmutation navigate-down [_] (action [{:keys [app state]}] (let [old-slots (:slot/by-id @state) new-slot-one (merge-ident (:one old-slots) (-> old-slots :three :slot/sith)) new-slot-two (merge-ident (:two old-slots) (-> old-slots :four :slot/sith)) new-slot-three (merge-ident (:three old-slots) (-> old-slots :five :slot/sith)) new-slot-four (merge-ident (:four old-slots) nil) new-slot-five (merge-ident (:five old-slots) nil) new-slots {:one new-slot-one :two new-slot-two :three new-slot-three :four new-slot-four :five new-slot-five}] (swap! state assoc :slot/by-id new-slots)))) (defmutation set-current-planet [{:keys [planet]}] (action [{:keys [app state]}] (swap! state assoc :current-planet planet))) (defsc Root [this {:keys [root/list up-enabled down-enabled current-planet] :as props}] {:query [{:root/list (comp/get-query SithList)} :up-enabled :down-enabled {:current-planet [:id :name]}] :initial-state (fn [params] {:root/list (comp/get-initial-state SithList {}) :up-enabled true :down-enabled true :current-planet {:id 32, :name "Utapau"}})} (dom/div :.css-root (dom/h1 :.css-planet-monitor "Obi-Wan currently on: " (dom/span (:name current-planet))) (dom/section :.css-scrollable-list (ui-sith-list (comp/computed list {:current-planet (:name current-planet)})) (dom/div :.css-scroll-buttons (dom/button :.css-button-up {:className (if up-enabled "" "css-button-disabled") :disabled (not update-in) :onClick #(when up-enabled (comp/transact! this [(navigate-up)]))}) (dom/button :.css-button-down {:className (if down-enabled "" "css-button-disabled") :disabled (not down-enabled) :onClick #(when down-enabled (comp/transact! this [(navigate-down)]))}))))) (comment (comp/get-initial-state Sith {:sith/id 3616 :sith/name "<NAME>"}) df/marker-table can be used to keep track of loading states merge/remove-ident*)
true
(ns app.view (:require [com.fulcrologic.fulcro.application :as app] [com.fulcrologic.fulcro.components :as comp :refer [defsc]] [com.fulcrologic.fulcro.mutations :as m :refer [defmutation]] [com.fulcrologic.fulcro.dom :as dom] [com.fulcrologic.fulcro.data-fetch :as df] [app.proxy :refer [sith-output]])) (comment we are adding the apprentice/master ident to the [:siths :list/siths] ui edge. Then we fetch the data for that sith. When the data comes back, we display the sith slot.) ;; (defmutation load-sith [{:keys [query-class] :sith/keys [id] :as params}] ;; (action [{:keys [app state]}] ;; (swap! state assoc-in [:siths :list/siths] (add-to-list @state id)) ;; (df/load! app [:sith/id id] query-class))) (comment we could just put a df/load into the mutations... you could load from the Sith component. When the mutation is in a cljc file, then you cant import your mutations as well as importing your cljs component into the cljc file... clojure doesnt like you going back and forth like that. (df/load! app [:person/id id] PersonDetail)) (comment "this is the mutation we use to disable the buttons to load more siths.") (defmutation set-button [{:keys [button-key button-value]}] (action [{:keys [app state]}] (swap! state assoc button-key button-value))) (defn toggle-button-enabled [component value] " This function disables the down button if the apprentice does not exist. It also disables the up button if the master doesnt exist. " (let [p (comp/props component) master-exists? (some? (:sith/master p)) apprentice-exists? (some? (:sith/apprentice p))] (when (not apprentice-exists?) (comp/transact! component [(set-button {:button-key :down-enabled :button-value value})])) (when (not master-exists?) (comp/transact! component [(set-button {:button-key :up-enabled :button-value value})])))) (comment "We want to load the sith and disable any buttons if the data for this sith doesnt have the attributes we are looking for") (defsc Sith [this {:sith/keys [id name homeWorld] :as props}] {:query [:sith/id :sith/name :sith/master :sith/apprentice {:sith/homeWorld [:homeWorld/name :homeWorld/id]}] :ident :sith/id :componentDidMount #(toggle-button-enabled % false) :componentWillUnmount #(toggle-button-enabled % true)} (dom/div (dom/h3 name) (dom/h6 "Homeworld: " (dom/span (:homeWorld/name homeWorld))))) (def ui-sith "we can define what attribute we want react to use as a key if we are mapping over a list with this component." (comp/factory Sith {:keyfn :sith/id})) (defn load-sith [query-component component where id] " We pass the query-component so that this function doesnt have to live in this file. The second argument is the component we are loading the sith from. It takes which slot to target when the data loads as the third argument. This function will create the sith ident from the id in the fourth argument." (let [load-target [:slot/by-id where :slot/sith] sith-ident [:sith/id id]] (df/load! component sith-ident query-component {:target load-target :abort-id :jedi}))) (comment "This is component does a lot of the heavy lifting. We can target each of these component slots to load a sith into that slot. When the component mounts, We load the apprentice in the slot below this slot (if it exists) and we load the master in the slot above (if it exists). This assumes that the slot is empty.") (defsc SithSlot [this {:db/keys [id] :slot/keys [sith] :as props} {:keys [at-home?]}] {:query [:db/id {:slot/sith (comp/get-query Sith)}] :initial-state (fn [{:keys [id]}] {:db/id id :slot/sith nil}) :ident [:slot/by-id :db/id] :componentDidUpdate (fn [this prev-props _] (let [p (comp/props this) at-home? (:at-home? (comp/get-computed this)) app-id (-> p :slot/sith :sith/apprentice) app-target (:app-target (comp/get-computed this)) mas-id (-> p :slot/sith :sith/master) mas-target (:mas-target (comp/get-computed this))] (when (and app-id app-target) (load-sith Sith this app-target app-id)) (when (and mas-id mas-target) (load-sith Sith this mas-target mas-id))))} (dom/li :.css-slot {:className (if at-home? "red" "")} (when (some? sith) (ui-sith sith)))) (def ui-slot (comp/factory SithSlot {:keyfn :db/id})) (defn slot->app-target [slot-id] "given a slot id (:one :two :three etc) we add one to that slot for an apprentice" (slot-id {:one :two :two :three :three :four :four :five})) (defn slot->mas-target [slot-id] "given a slot id (:one :two :three etc) we subtract one to that slot number for their master" (slot-id {:two :one :three :two :four :three :five :four})) (defn target-occupied? [slots-data slot-id] "determines if the give slot is currently empty" (reduce (fn [target-occupied? [id val]] (if (= (:db/id val) slot-id) (some? (:slot/sith val)) target-occupied?)) false slots-data)) (defn slot-at-home? [slots slot-id current-planet] "determines if the current planet and the sith's homeworld in a give slot match" (reduce (fn [at-home? [_ val]] (if (= (:db/id val) slot-id) (= (-> val :slot/sith :sith/homeWorld :homeWorld/name) current-planet) at-home?)) false slots)) (defn get-slot-props [component slot-id] "generates the props so that the SithSlot component can load their master or apprentice correctly. For example, this function will return an app-target for a given slot if that :slot/sith has a :sith/apprentice and the slot below it is not occupied. This way the SithSlot component knows to load a sith purely based on the presence of the app-target or mas-target." (let [props (comp/props component) current-planet (comp/get-computed component :current-planet) app-target (slot->app-target slot-id) app-target-occupied? (not (target-occupied? props app-target)) mas-target (slot->mas-target slot-id) mas-target-occupied? (not (target-occupied? props mas-target))] {:app-target (and app-target-occupied? app-target) :mas-target (and mas-target-occupied? mas-target) :at-home? (slot-at-home? props slot-id current-planet)})) (defn set-both-buttons [component value] (comp/transact! component [(set-button {:button-key :down-enabled :button-value value}) (set-button {:button-key :up-enabled :button-value value})])) (defn compact [col] (remove nil? col)) (defn slots->siths [slots] (compact (map (fn [[_ slot]] (:slot/sith slot)) slots))) (defn all-sith-have-attr? [siths attr] (reduce (fn [master-or-appr-missing? sith] (or master-or-appr-missing? (not (some? (attr sith))))) false siths)) (def x [{:sith/id 3616, :sith/name "PI:NAME:<NAME>END_PI", :sith/master 2350, :sith/apprentice 1489, :sith/homeWorld {:homeWorld/name "Naboo", :homeWorld/id 7}} {:sith/id 1489, :sith/name "PI:NAME:<NAME>END_PI", :sith/master 3616, :sith/apprentice 1330, :sith/homeWorld {:homeWorld/name "Tatooine", :homeWorld/id 18}} {:sith/id 1330, :sith/name "PI:NAME:<NAME>END_PI", :sith/master 1489, :sith/homeWorld {:homeWorld/name "Coruscant", :homeWorld/id 58}}]) (all-sith-have-attr? x :sith/apprentice) (defn update-buttons [component] (let [props (comp/props component) computed (comp/get-computed component) current-planet (:current-planet computed) siths (slots->siths props) sith-at-home-detected? (reduce (fn [detected-at-home? {:sith/keys [homeWorld]}] (or (= (:homeWorld/name homeWorld) current-planet) detected-at-home?)) false siths) master-missing? (all-sith-have-attr? siths :sith/master) appr-missing? (all-sith-have-attr? siths :sith/apprentice)] (if sith-at-home-detected? (do ;; (app/abort! component :jedi) pathom remote doesnt support aborting requests (set-both-buttons component false)) (comp/transact! component [(set-button {:button-key :down-enabled :button-value (not appr-missing?)}) (set-button {:button-key :up-enabled :button-value (not master-missing?)})])))) (defsc SithList [this {:slot/keys [one two three four five] :as props}] {:query [{:slot/one (comp/get-query SithSlot)} {:slot/two (comp/get-query SithSlot)} {:slot/three (comp/get-query SithSlot)} {:slot/four (comp/get-query SithSlot)} {:slot/five (comp/get-query SithSlot)}] :initial-state (fn [_] {:slot/one (comp/get-initial-state SithSlot {:id :one}) :slot/two (comp/get-initial-state SithSlot {:id :two}) :slot/three (comp/get-initial-state SithSlot {:id :three}) :slot/four (comp/get-initial-state SithSlot {:id :four}) :slot/five (comp/get-initial-state SithSlot {:id :five})}) :ident (fn [] [:LIST :only-one]) :componentDidUpdate (fn [this _ _] (update-buttons this))} (dom/ul :.css-slots (ui-slot (comp/computed one (get-slot-props this :one))) (ui-slot (comp/computed two (get-slot-props this :two))) (ui-slot (comp/computed three (get-slot-props this :three))) (ui-slot (comp/computed four (get-slot-props this :four))) (ui-slot (comp/computed five (get-slot-props this :five))))) (def ui-sith-list (comp/factory SithList {:keyfn :db/id})) (defn merge-ident [slot new-ident] (merge slot {:slot/sith new-ident})) (defmutation navigate-up [_] (action [{:keys [app state]}] (let [old-slots (:slot/by-id @state) new-slot-one (merge-ident (:one old-slots) nil) new-slot-two (merge-ident (:two old-slots) nil) new-slot-three (merge-ident (:three old-slots) (-> old-slots :one :slot/sith)) new-slot-four (merge-ident (:four old-slots) (-> old-slots :two :slot/sith)) new-slot-five (merge-ident (:five old-slots) (-> old-slots :three :slot/sith)) new-slots {:one new-slot-one :two new-slot-two :three new-slot-three :four new-slot-four :five new-slot-five}] (swap! state assoc :slot/by-id new-slots)))) (defmutation navigate-down [_] (action [{:keys [app state]}] (let [old-slots (:slot/by-id @state) new-slot-one (merge-ident (:one old-slots) (-> old-slots :three :slot/sith)) new-slot-two (merge-ident (:two old-slots) (-> old-slots :four :slot/sith)) new-slot-three (merge-ident (:three old-slots) (-> old-slots :five :slot/sith)) new-slot-four (merge-ident (:four old-slots) nil) new-slot-five (merge-ident (:five old-slots) nil) new-slots {:one new-slot-one :two new-slot-two :three new-slot-three :four new-slot-four :five new-slot-five}] (swap! state assoc :slot/by-id new-slots)))) (defmutation set-current-planet [{:keys [planet]}] (action [{:keys [app state]}] (swap! state assoc :current-planet planet))) (defsc Root [this {:keys [root/list up-enabled down-enabled current-planet] :as props}] {:query [{:root/list (comp/get-query SithList)} :up-enabled :down-enabled {:current-planet [:id :name]}] :initial-state (fn [params] {:root/list (comp/get-initial-state SithList {}) :up-enabled true :down-enabled true :current-planet {:id 32, :name "Utapau"}})} (dom/div :.css-root (dom/h1 :.css-planet-monitor "Obi-Wan currently on: " (dom/span (:name current-planet))) (dom/section :.css-scrollable-list (ui-sith-list (comp/computed list {:current-planet (:name current-planet)})) (dom/div :.css-scroll-buttons (dom/button :.css-button-up {:className (if up-enabled "" "css-button-disabled") :disabled (not update-in) :onClick #(when up-enabled (comp/transact! this [(navigate-up)]))}) (dom/button :.css-button-down {:className (if down-enabled "" "css-button-disabled") :disabled (not down-enabled) :onClick #(when down-enabled (comp/transact! this [(navigate-down)]))}))))) (comment (comp/get-initial-state Sith {:sith/id 3616 :sith/name "PI:NAME:<NAME>END_PI"}) df/marker-table can be used to keep track of loading states merge/remove-ident*)
[ { "context": ";; Copyright (c) 2015 Andrey Antukh <niwi@niwi.nz>\n;; Copyright (c) 2015 Alejandro Gó", "end": 35, "score": 0.9998895525932312, "start": 22, "tag": "NAME", "value": "Andrey Antukh" }, { "context": ";; Copyright (c) 2015 Andrey Antukh <niwi@niwi.nz>\n;; Copyright (c) 2015 Alejandro Gómez <alejandro", "end": 49, "score": 0.999933123588562, "start": 37, "tag": "EMAIL", "value": "niwi@niwi.nz" }, { "context": "Andrey Antukh <niwi@niwi.nz>\n;; Copyright (c) 2015 Alejandro Gómez <alejandro@dialelo.com>\n;; All rights reserved.\n;", "end": 88, "score": 0.9998886585235596, "start": 73, "tag": "NAME", "value": "Alejandro Gómez" }, { "context": "i@niwi.nz>\n;; Copyright (c) 2015 Alejandro Gómez <alejandro@dialelo.com>\n;; All rights reserved.\n;;\n;; Redistribution and", "end": 111, "score": 0.9999364018440247, "start": 90, "tag": "EMAIL", "value": "alejandro@dialelo.com" } ]
src/cats/labs/test.cljc
klausharbo/cats
896
;; Copyright (c) 2015 Andrey Antukh <niwi@niwi.nz> ;; Copyright (c) 2015 Alejandro Gómez <alejandro@dialelo.com> ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions ;; are met: ;; ;; 1. Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; 2. Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ;; IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, ;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (ns cats.labs.test (:require [cats.context :as ctx :include-macros true] [cats.core :as m] [cats.protocols :as p] [clojure.test.check.generators :as gen] [clojure.test.check.properties :as prop :include-macros true])) ;; Generator context (def gen-context (reify p/Context p/Functor (-fmap [_ f mv] (gen/fmap f mv)) p/Applicative (-pure [_ v] (gen/return v)) (-fapply [_ gf gv] (m/mlet [f gf v gv] (m/return (f v)))) p/Monad (-mreturn [_ v] (gen/return v)) (-mbind [_ mv f] (gen/bind mv f)))) (extend-type clojure.test.check.generators.Generator p/Contextual (-get-context [_] gen-context)) ;; Semigroup (defn semigroup-associativity [{:keys [ctx gen eq] :or {eq =}}] (prop/for-all [x gen y gen z gen] (ctx/with-context ctx (eq (m/mappend (m/mappend x y) z) (m/mappend x (m/mappend y z)))))) ;; Monoid (defn monoid-identity-element [{:keys [ctx gen empty eq] :or {empty (m/mempty ctx) eq =}}] (prop/for-all [x gen] (ctx/with-context-override ctx (eq x (m/mappend x empty) (m/mappend empty x))))) ;; Functor laws (defn first-functor-law [{:keys [gen eq] :or {eq =}}] (prop/for-all [fa gen] (eq fa (m/fmap identity fa)))) (defn second-functor-law [{:keys [gen f g eq] :or {eq =}}] (prop/for-all [fa gen] (eq (m/fmap (comp g f) fa) (m/fmap g (m/fmap f fa))))) ;; Bifunctor laws (defn bifunctor-first-identity [{:keys [gen eq] :or {eq =}}] (prop/for-all [bv gen] (eq bv (m/left-map identity bv)))) (defn bifunctor-second-identity [{:keys [gen eq] :or {eq =}}] (prop/for-all [bv gen] (eq bv (m/right-map identity bv)))) (defn bifunctor-bimap-identity [{:keys [gen eq] :or {eq =}}] (prop/for-all [bv gen] (eq bv (m/bimap identity identity bv)))) (defn bifunctor-composition [{:keys [gen f g eq] :or {eq =}}] (prop/for-all [bv gen] (eq (m/bimap f g bv) (m/left-map f (m/right-map g bv))))) ;; Applicative laws (defn applicative-identity-law [{:keys [ctx gen eq] :or {eq =}}] (prop/for-all [app gen] (eq app (m/fapply (m/pure ctx identity) app)))) (defn applicative-homomorphism [{:keys [ctx gen f eq] :or {eq =}}] (prop/for-all [x gen] (eq (m/pure ctx (f x)) (m/fapply (m/pure ctx f) (m/pure ctx x))))) (defn applicative-interchange [{:keys [ctx gen appf eq] :or {eq =}}] (prop/for-all [x gen] (eq (m/fapply appf (m/pure ctx x)) (m/fapply (m/pure ctx (fn [f] (f x))) appf)))) (defn applicative-composition [{:keys [ctx gen appf appg eq] :or {eq =}}] (prop/for-all [x gen] (eq (m/fapply appg (m/fapply appf (m/pure ctx x))) (m/fapply (m/pure ctx (m/curry 2 comp)) appf appg (m/pure ctx x))))) ;; Monad laws (defn first-monad-law [{:keys [ctx mf gen eq] :or {gen gen/any eq =}}] (prop/for-all [a gen] (eq (mf a) (m/>>= (m/return ctx a) mf)))) (defn second-monad-law [{:keys [ctx eq] :or {eq =}}] (prop/for-all [a gen/any] (let [m (m/return ctx a)] (eq m (m/>>= m m/return))))) (defn third-monad-law [{:keys [ctx f g eq] :or {eq =}}] (prop/for-all [a gen/any] (let [m (m/return ctx a)] (eq (m/>>= (m/>>= m f) g) (m/>>= m (fn [x] (m/>>= (f x) g))))))) ;; MonadPlus (defn monadplus-associativity [{:keys [ctx gen eq] :or {eq =}}] (prop/for-all [x gen y gen z gen] (eq (m/mplus (m/mplus x y) z) (m/mplus x (m/mplus y z))))) ;; MonadZero (defn monadzero-identity-element [{:keys [ctx gen eq] :or {eq =}}] (prop/for-all [x gen] (ctx/with-context ctx (eq x (m/mplus x (m/mzero ctx)) (m/mplus (m/mzero ctx) x))))) (defn monadzero-bind [{:keys [ctx gen zero eq] :or {zero (m/mzero ctx) eq =}}] (prop/for-all [m gen] (ctx/with-context ctx (eq zero (m/>>= zero (fn [v] (m/return v))) (m/>> m zero)))))
55473
;; Copyright (c) 2015 <NAME> <<EMAIL>> ;; Copyright (c) 2015 <NAME> <<EMAIL>> ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions ;; are met: ;; ;; 1. Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; 2. Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ;; IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, ;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (ns cats.labs.test (:require [cats.context :as ctx :include-macros true] [cats.core :as m] [cats.protocols :as p] [clojure.test.check.generators :as gen] [clojure.test.check.properties :as prop :include-macros true])) ;; Generator context (def gen-context (reify p/Context p/Functor (-fmap [_ f mv] (gen/fmap f mv)) p/Applicative (-pure [_ v] (gen/return v)) (-fapply [_ gf gv] (m/mlet [f gf v gv] (m/return (f v)))) p/Monad (-mreturn [_ v] (gen/return v)) (-mbind [_ mv f] (gen/bind mv f)))) (extend-type clojure.test.check.generators.Generator p/Contextual (-get-context [_] gen-context)) ;; Semigroup (defn semigroup-associativity [{:keys [ctx gen eq] :or {eq =}}] (prop/for-all [x gen y gen z gen] (ctx/with-context ctx (eq (m/mappend (m/mappend x y) z) (m/mappend x (m/mappend y z)))))) ;; Monoid (defn monoid-identity-element [{:keys [ctx gen empty eq] :or {empty (m/mempty ctx) eq =}}] (prop/for-all [x gen] (ctx/with-context-override ctx (eq x (m/mappend x empty) (m/mappend empty x))))) ;; Functor laws (defn first-functor-law [{:keys [gen eq] :or {eq =}}] (prop/for-all [fa gen] (eq fa (m/fmap identity fa)))) (defn second-functor-law [{:keys [gen f g eq] :or {eq =}}] (prop/for-all [fa gen] (eq (m/fmap (comp g f) fa) (m/fmap g (m/fmap f fa))))) ;; Bifunctor laws (defn bifunctor-first-identity [{:keys [gen eq] :or {eq =}}] (prop/for-all [bv gen] (eq bv (m/left-map identity bv)))) (defn bifunctor-second-identity [{:keys [gen eq] :or {eq =}}] (prop/for-all [bv gen] (eq bv (m/right-map identity bv)))) (defn bifunctor-bimap-identity [{:keys [gen eq] :or {eq =}}] (prop/for-all [bv gen] (eq bv (m/bimap identity identity bv)))) (defn bifunctor-composition [{:keys [gen f g eq] :or {eq =}}] (prop/for-all [bv gen] (eq (m/bimap f g bv) (m/left-map f (m/right-map g bv))))) ;; Applicative laws (defn applicative-identity-law [{:keys [ctx gen eq] :or {eq =}}] (prop/for-all [app gen] (eq app (m/fapply (m/pure ctx identity) app)))) (defn applicative-homomorphism [{:keys [ctx gen f eq] :or {eq =}}] (prop/for-all [x gen] (eq (m/pure ctx (f x)) (m/fapply (m/pure ctx f) (m/pure ctx x))))) (defn applicative-interchange [{:keys [ctx gen appf eq] :or {eq =}}] (prop/for-all [x gen] (eq (m/fapply appf (m/pure ctx x)) (m/fapply (m/pure ctx (fn [f] (f x))) appf)))) (defn applicative-composition [{:keys [ctx gen appf appg eq] :or {eq =}}] (prop/for-all [x gen] (eq (m/fapply appg (m/fapply appf (m/pure ctx x))) (m/fapply (m/pure ctx (m/curry 2 comp)) appf appg (m/pure ctx x))))) ;; Monad laws (defn first-monad-law [{:keys [ctx mf gen eq] :or {gen gen/any eq =}}] (prop/for-all [a gen] (eq (mf a) (m/>>= (m/return ctx a) mf)))) (defn second-monad-law [{:keys [ctx eq] :or {eq =}}] (prop/for-all [a gen/any] (let [m (m/return ctx a)] (eq m (m/>>= m m/return))))) (defn third-monad-law [{:keys [ctx f g eq] :or {eq =}}] (prop/for-all [a gen/any] (let [m (m/return ctx a)] (eq (m/>>= (m/>>= m f) g) (m/>>= m (fn [x] (m/>>= (f x) g))))))) ;; MonadPlus (defn monadplus-associativity [{:keys [ctx gen eq] :or {eq =}}] (prop/for-all [x gen y gen z gen] (eq (m/mplus (m/mplus x y) z) (m/mplus x (m/mplus y z))))) ;; MonadZero (defn monadzero-identity-element [{:keys [ctx gen eq] :or {eq =}}] (prop/for-all [x gen] (ctx/with-context ctx (eq x (m/mplus x (m/mzero ctx)) (m/mplus (m/mzero ctx) x))))) (defn monadzero-bind [{:keys [ctx gen zero eq] :or {zero (m/mzero ctx) eq =}}] (prop/for-all [m gen] (ctx/with-context ctx (eq zero (m/>>= zero (fn [v] (m/return v))) (m/>> m zero)))))
true
;; Copyright (c) 2015 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ;; Copyright (c) 2015 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions ;; are met: ;; ;; 1. Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; 2. Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ;; IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, ;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (ns cats.labs.test (:require [cats.context :as ctx :include-macros true] [cats.core :as m] [cats.protocols :as p] [clojure.test.check.generators :as gen] [clojure.test.check.properties :as prop :include-macros true])) ;; Generator context (def gen-context (reify p/Context p/Functor (-fmap [_ f mv] (gen/fmap f mv)) p/Applicative (-pure [_ v] (gen/return v)) (-fapply [_ gf gv] (m/mlet [f gf v gv] (m/return (f v)))) p/Monad (-mreturn [_ v] (gen/return v)) (-mbind [_ mv f] (gen/bind mv f)))) (extend-type clojure.test.check.generators.Generator p/Contextual (-get-context [_] gen-context)) ;; Semigroup (defn semigroup-associativity [{:keys [ctx gen eq] :or {eq =}}] (prop/for-all [x gen y gen z gen] (ctx/with-context ctx (eq (m/mappend (m/mappend x y) z) (m/mappend x (m/mappend y z)))))) ;; Monoid (defn monoid-identity-element [{:keys [ctx gen empty eq] :or {empty (m/mempty ctx) eq =}}] (prop/for-all [x gen] (ctx/with-context-override ctx (eq x (m/mappend x empty) (m/mappend empty x))))) ;; Functor laws (defn first-functor-law [{:keys [gen eq] :or {eq =}}] (prop/for-all [fa gen] (eq fa (m/fmap identity fa)))) (defn second-functor-law [{:keys [gen f g eq] :or {eq =}}] (prop/for-all [fa gen] (eq (m/fmap (comp g f) fa) (m/fmap g (m/fmap f fa))))) ;; Bifunctor laws (defn bifunctor-first-identity [{:keys [gen eq] :or {eq =}}] (prop/for-all [bv gen] (eq bv (m/left-map identity bv)))) (defn bifunctor-second-identity [{:keys [gen eq] :or {eq =}}] (prop/for-all [bv gen] (eq bv (m/right-map identity bv)))) (defn bifunctor-bimap-identity [{:keys [gen eq] :or {eq =}}] (prop/for-all [bv gen] (eq bv (m/bimap identity identity bv)))) (defn bifunctor-composition [{:keys [gen f g eq] :or {eq =}}] (prop/for-all [bv gen] (eq (m/bimap f g bv) (m/left-map f (m/right-map g bv))))) ;; Applicative laws (defn applicative-identity-law [{:keys [ctx gen eq] :or {eq =}}] (prop/for-all [app gen] (eq app (m/fapply (m/pure ctx identity) app)))) (defn applicative-homomorphism [{:keys [ctx gen f eq] :or {eq =}}] (prop/for-all [x gen] (eq (m/pure ctx (f x)) (m/fapply (m/pure ctx f) (m/pure ctx x))))) (defn applicative-interchange [{:keys [ctx gen appf eq] :or {eq =}}] (prop/for-all [x gen] (eq (m/fapply appf (m/pure ctx x)) (m/fapply (m/pure ctx (fn [f] (f x))) appf)))) (defn applicative-composition [{:keys [ctx gen appf appg eq] :or {eq =}}] (prop/for-all [x gen] (eq (m/fapply appg (m/fapply appf (m/pure ctx x))) (m/fapply (m/pure ctx (m/curry 2 comp)) appf appg (m/pure ctx x))))) ;; Monad laws (defn first-monad-law [{:keys [ctx mf gen eq] :or {gen gen/any eq =}}] (prop/for-all [a gen] (eq (mf a) (m/>>= (m/return ctx a) mf)))) (defn second-monad-law [{:keys [ctx eq] :or {eq =}}] (prop/for-all [a gen/any] (let [m (m/return ctx a)] (eq m (m/>>= m m/return))))) (defn third-monad-law [{:keys [ctx f g eq] :or {eq =}}] (prop/for-all [a gen/any] (let [m (m/return ctx a)] (eq (m/>>= (m/>>= m f) g) (m/>>= m (fn [x] (m/>>= (f x) g))))))) ;; MonadPlus (defn monadplus-associativity [{:keys [ctx gen eq] :or {eq =}}] (prop/for-all [x gen y gen z gen] (eq (m/mplus (m/mplus x y) z) (m/mplus x (m/mplus y z))))) ;; MonadZero (defn monadzero-identity-element [{:keys [ctx gen eq] :or {eq =}}] (prop/for-all [x gen] (ctx/with-context ctx (eq x (m/mplus x (m/mzero ctx)) (m/mplus (m/mzero ctx) x))))) (defn monadzero-bind [{:keys [ctx gen zero eq] :or {zero (m/mzero ctx) eq =}}] (prop/for-all [m gen] (ctx/with-context ctx (eq zero (m/>>= zero (fn [v] (m/return v))) (m/>> m zero)))))
[ { "context": "ay [content]\n \"General display function, based on Roger Whitney's lecture slides, builds Jframe for program.\"\n (", "end": 234, "score": 0.9979405999183655, "start": 221, "tag": "NAME", "value": "Roger Whitney" } ]
src/kiwi/gui.clj
SalvatoreTosti/kiwi
0
(ns kiwi.gui (:gen-class) (:require [seesaw.core :as seesaw] )) (defn update-gui [*list active-list] (seesaw/config! active-list :model @*list)) (defn display [content] "General display function, based on Roger Whitney's lecture slides, builds Jframe for program." (let [window (seesaw/frame :title "Kiwi" :on-close :exit :content content :width 425 ;850 :height 550)] ;1100) ;(seesaw/native!) (seesaw/show! window))) (defn run [*list active-list] (display (update-gui *list active-list)))
50668
(ns kiwi.gui (:gen-class) (:require [seesaw.core :as seesaw] )) (defn update-gui [*list active-list] (seesaw/config! active-list :model @*list)) (defn display [content] "General display function, based on <NAME>'s lecture slides, builds Jframe for program." (let [window (seesaw/frame :title "Kiwi" :on-close :exit :content content :width 425 ;850 :height 550)] ;1100) ;(seesaw/native!) (seesaw/show! window))) (defn run [*list active-list] (display (update-gui *list active-list)))
true
(ns kiwi.gui (:gen-class) (:require [seesaw.core :as seesaw] )) (defn update-gui [*list active-list] (seesaw/config! active-list :model @*list)) (defn display [content] "General display function, based on PI:NAME:<NAME>END_PI's lecture slides, builds Jframe for program." (let [window (seesaw/frame :title "Kiwi" :on-close :exit :content content :width 425 ;850 :height 550)] ;1100) ;(seesaw/native!) (seesaw/show! window))) (defn run [*list active-list] (display (update-gui *list active-list)))
[ { "context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li", "end": 111, "score": 0.9998006820678711, "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.9998127222061157, "start": 113, "tag": "NAME", "value": "Christian Murray" }, { "context": "ly stolen from textmate:\n ;; https://github.com/textmate/lua.tmbundle/blob/master/Preferences/Indent.tmPre", "end": 1934, "score": 0.9989006519317627, "start": 1926, "tag": "USERNAME", "value": "textmate" } ]
editor/src/clj/editor/code/script.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.code.script (:require [clojure.string :as string] [dynamo.graph :as g] [editor.build-target :as bt] [editor.code-completion :as code-completion] [editor.code.data :as data] [editor.code.resource :as r] [editor.code.script-intelligence :as si] [editor.defold-project :as project] [editor.graph-util :as gu] [editor.image :as image] [editor.lua :as lua] [editor.lua-parser :as lua-parser] [editor.luajit :as luajit] [editor.properties :as properties] [editor.protobuf :as protobuf] [editor.resource :as resource] [editor.types :as t] [editor.validation :as validation] [editor.workspace :as workspace] [internal.util :as util] [schema.core :as s]) (:import [com.dynamo.lua.proto Lua$LuaModule] [com.google.protobuf ByteString])) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (g/deftype Modules [String]) (def lua-grammar {:name "Lua" :scope-name "source.lua" ;; indent patterns shamelessly stolen from textmate: ;; https://github.com/textmate/lua.tmbundle/blob/master/Preferences/Indent.tmPreferences :indent {:begin #"^([^-]|-(?!-))*((\b(else|function|then|do|repeat)\b((?!\b(end|until)\b)[^\"'])*)|(\{\s*))$" :end #"^\s*((\b(elseif|else|end|until)\b)|(\})|(\)))"} :line-comment "--" :patterns [{:captures {1 {:name "keyword.control.lua"} 2 {:name "entity.name.function.scope.lua"} 3 {:name "entity.name.function.lua"} 4 {:name "punctuation.definition.parameters.begin.lua"} 5 {:name "variable.parameter.function.lua"} 6 {:name "punctuation.definition.parameters.end.lua"}} :match #"\b(function)(?:\s+([a-zA-Z_.:]+[.:])?([a-zA-Z_]\w*)\s*)?(\()([^)]*)(\))" :name "meta.function.lua"} {:match #"(?<![\d.])\s0x[a-fA-F\d]+|\b\d+(\.\d+)?([eE]-?\d+)?|\.\d+([eE]-?\d+)?" :name "constant.numeric.lua"} {:begin #"'" :begin-captures {0 {:name "punctuation.definition.string.begin.lua"}} :end #"'" :end-captures {0 {:name "punctuation.definition.string.end.lua"}} :name "string.quoted.single.lua" :patterns [{:match #"\\." :name "constant.character.escape.lua"}]} {:begin #"\"" :begin-captures {0 {:name "punctuation.definition.string.begin.lua"}} :end #"\"" :end-captures {0 {:name "punctuation.definition.string.end.lua"}} :name "string.quoted.double.lua" :patterns [{:match #"\\." :name "constant.character.escape.lua"}]} {:begin #"(?<!--)\[(=*)\[" :begin-captures {0 {:name "punctuation.definition.string.begin.lua"}} :end #"\]\1\]" :end-captures {0 {:name "punctuation.definition.string.end.lua"}} :name "string.quoted.other.multiline.lua"} {:begin #"--\[(=*)\[" :captures {0 {:name "punctuation.definition.comment.lua"}} :end #"\]\1\]" :name "comment.block.lua"} {:captures {1 {:name "punctuation.definition.comment.lua"}} :match #"(--).*" :name "comment.line.double-dash.lua"} {:match #"\b(and|or|not|break|do|else|for|if|elseif|return|then|repeat|while|until|end|function|local|in|goto)\b" :name "keyword.control.lua"} {:match #"(?<![^.]\.|:)\b([A-Z_][0-9A-Z_]*|false|nil|true|math\.(pi|huge))\b|(?<![.])\.{3}(?!\.)" :name "constant.language.lua"} {:match #"(?<![^.]\.|:)\b(self)\b" :name "variable.language.self.lua"} {:match #"(?<![^.]\.|:)\b(assert|collectgarbage|dofile|error|getfenv|getmetatable|ipairs|loadfile|loadstring|module|next|pairs|pcall|print|rawequal|rawget|rawset|require|select|setfenv|setmetatable|tonumber|tostring|type|unpack|xpcall)\b(?=\s*(?:[({\"']|\[\[))" :name "support.function.lua"} {:match #"(?<![^.]\.|:)\b(coroutine\.(create|resume|running|status|wrap|yield)|string\.(byte|char|dump|find|format|gmatch|gsub|len|lower|match|rep|reverse|sub|upper)|table\.(concat|insert|maxn|remove|sort)|math\.(abs|acos|asin|atan2?|ceil|cosh?|deg|exp|floor|fmod|frexp|ldexp|log|log10|max|min|modf|pow|rad|random|randomseed|sinh?|sqrt|tanh?)|io\.(close|flush|input|lines|open|output|popen|read|tmpfile|type|write)|os\.(clock|date|difftime|execute|exit|getenv|remove|rename|setlocale|time|tmpname)|package\.(cpath|loaded|loadlib|path|preload|seeall)|debug\.(debug|[gs]etfenv|[gs]ethook|getinfo|[gs]etlocal|[gs]etmetatable|getregistry|[gs]etupvalue|traceback))\b(?=\s*(?:[({\"']|\[\[))" :name "support.function.library.lua"} {:match #"\b([A-Za-z_]\w*)\b(?=\s*(?:[({\"']|\[\[))" :name "support.function.any-method.lua"} {:match #"(?<=[^.]\.|:)\b([A-Za-z_]\w*)" :name "variable.other.lua"} {:match #"\+|-|%|#|\*|\/|\^|==?|~=|<=?|>=?|(?<!\.)\.{2}(?!\.)" :name "keyword.operator.lua"}]}) (def lua-code-opts {:code {:grammar lua-grammar}}) (defn script-property-type->property-type "Controls how script property values are represented in the graph and edited." [script-property-type] (case script-property-type :script-property-type-number g/Num :script-property-type-hash g/Str :script-property-type-url g/Str :script-property-type-vector3 t/Vec3 :script-property-type-vector4 t/Vec4 :script-property-type-quat t/Vec3 :script-property-type-boolean g/Bool :script-property-type-resource resource/Resource)) (defn script-property-type->go-prop-type "Controls how script property values are represented in the file formats." [script-property-type] (case script-property-type :script-property-type-number :property-type-number :script-property-type-hash :property-type-hash :script-property-type-url :property-type-url :script-property-type-vector3 :property-type-vector3 :script-property-type-vector4 :property-type-vector4 :script-property-type-quat :property-type-quat :script-property-type-boolean :property-type-boolean :script-property-type-resource :property-type-hash)) (g/deftype ScriptPropertyType (s/enum :script-property-type-number :script-property-type-hash :script-property-type-url :script-property-type-vector3 :script-property-type-vector4 :script-property-type-quat :script-property-type-boolean :script-property-type-resource)) (def script-defs [{:ext "script" :label "Script" :icon "icons/32/Icons_12-Script-type.png" :view-types [:code :default] :view-opts lua-code-opts :tags #{:component :debuggable :non-embeddable :overridable-properties} :tag-opts {:component {:transform-properties #{}}}} {:ext "render_script" :label "Render Script" :icon "icons/32/Icons_12-Script-type.png" :view-types [:code :default] :view-opts lua-code-opts :tags #{:debuggable}} {:ext "gui_script" :label "Gui Script" :icon "icons/32/Icons_12-Script-type.png" :view-types [:code :default] :view-opts lua-code-opts :tags #{:debuggable}} {:ext "lua" :label "Lua Module" :icon "icons/32/Icons_11-Script-general.png" :view-types [:code :default] :view-opts lua-code-opts :tags #{:debuggable}}]) (def ^:private status-errors {:ok nil :invalid-args (g/error-fatal "Invalid arguments to go.property call") ; TODO: not used for now :invalid-value (g/error-fatal "Invalid value in go.property call")}) (defn- prop->key [p] (-> p :name properties/user-name->key)) (def resource-kind->ext "Declares which file extensions are valid for different kinds of resource properties. This affects the Property Editor, but is also used for validation." {"atlas" ["atlas" "tilesource"] "font" "font" "material" "material" "buffer" "buffer" "texture" (conj image/exts "cubemap") "tile_source" "tilesource"}) (def ^:private valid-resource-kind? (partial contains? resource-kind->ext)) (defn- script-property-edit-type [prop-type resource-kind] (if (= resource/Resource prop-type) {:type prop-type :ext (resource-kind->ext resource-kind)} {:type prop-type})) (defn- resource-assignment-error [node-id prop-kw prop-name resource expected-ext] (when (some? resource) (let [resource-ext (resource/ext resource) ext-match? (if (coll? expected-ext) (some? (some (partial = resource-ext) expected-ext)) (= expected-ext resource-ext))] (cond (not ext-match?) (g/->error node-id prop-kw :fatal resource (format "%s '%s' is not of type %s" (validation/format-name prop-name) (resource/proj-path resource) (validation/format-ext expected-ext))) (not (resource/exists? resource)) (g/->error node-id prop-kw :fatal resource (format "%s '%s' could not be found" (validation/format-name prop-name) (resource/proj-path resource))))))) (defn- validate-value-against-edit-type [node-id prop-kw prop-name value edit-type] (when (= resource/Resource (:type edit-type)) (resource-assignment-error node-id prop-kw prop-name value (:ext edit-type)))) (g/defnk produce-script-property-entries [_basis _node-id deleted? name resource-kind type value] (when-not deleted? (let [prop-kw (properties/user-name->key name) prop-type (script-property-type->property-type type) edit-type (script-property-edit-type prop-type resource-kind) error (validate-value-against-edit-type _node-id :value name value edit-type) go-prop-type (script-property-type->go-prop-type type) overridden? (g/property-overridden? _basis _node-id :value) read-only? (nil? (g/override-original _basis _node-id)) visible? (not deleted?)] ;; NOTE: :assoc-original-value? here tells the node internals that it ;; needs to assoc in the :original-value from the overridden node when ;; evaluating :_properties or :_declared-properties. This happens ;; automatically when the overridden property is in the properties map of ;; the OverrideNode, but in our case the ScriptNode is presenting a ;; property that resides on the ScriptPropertyNode, so there won't be an ;; entry in the properties map of the ScriptNode OverrideNode. {prop-kw {:assoc-original-value? overridden? :edit-type edit-type :error error :go-prop-type go-prop-type :node-id _node-id :prop-kw :value :read-only? read-only? :type prop-type :value value :visible visible?}}))) (g/deftype NameNodeIDPair [(s/one s/Str "name") (s/one s/Int "node-id")]) (g/deftype NameNodeIDMap {s/Str s/Int}) (g/deftype ResourceKind (apply s/enum (keys resource-kind->ext))) (g/deftype ScriptPropertyEntries {s/Keyword {:node-id s/Int :go-prop-type properties/TGoPropType :type s/Any :value s/Any s/Keyword s/Any}}) ;; Every declared `go.property("name", 0.0)` in the script code gets a ;; corresponding ScriptPropertyNode. This started as a workaround for the fact ;; that dynamic properties couldn't host the property setter required for ;; resource properties, but it turns out to have other benefits. Like the fact ;; you can edit a property name in the script and have the rename propagate to ;; all usages of the script. (g/defnode ScriptPropertyNode ;; The deleted? property is used instead of deleting the ScriptPropertyNode so ;; that overrides in collections and game objects survive cut-paste operations ;; on the go.property declarations in the script code. (property deleted? g/Bool) (property edit-type g/Any) (property name g/Str) (property resource-kind ResourceKind) (property type ScriptPropertyType) (property value g/Any (value (g/fnk [type resource value] ;; For resource properties we use the Resource from the ;; connected ResourceNode in order to track renames, etc. (case type :script-property-type-resource resource value))) (set (fn [evaluation-context self _old-value new-value] ;; When assigning a resource property, we must make sure the ;; assigned resource is built and included in the game. (let [basis (:basis evaluation-context) project (project/get-project self)] (concat (g/disconnect-sources basis self :resource) (g/disconnect-sources basis self :resource-build-targets) (when (resource/resource? new-value) (:tx-data (project/connect-resource-node evaluation-context project new-value self [[:resource :resource] [:build-targets :resource-build-targets]])))))))) (input resource resource/Resource) (input resource-build-targets g/Any) (output build-targets g/Any (g/fnk [deleted? resource-build-targets type] (when (and (not deleted?) (= :script-property-type-resource type)) resource-build-targets))) (output name+node-id NameNodeIDPair (g/fnk [_node-id name] [name _node-id])) (output property-entries ScriptPropertyEntries :cached produce-script-property-entries)) (defmethod g/node-key ::ScriptPropertyNode [node-id evaluation-context] ;; By implementing this multi-method, overridden property values will be ;; restored on OverrideNode ScriptPropertyNodes when a script is reloaded from ;; disk during resource-sync. The node-key must be unique within the script. (g/node-value node-id :name evaluation-context)) (defn- detect-edits [old-info-by-name new-info-by-name] (into {} (filter (fn [[name new-info]] (when-some [old-info (old-info-by-name name)] (not= old-info new-info)))) new-info-by-name)) (defn- detect-renames [old-info-by-removed-name new-info-by-added-name] (let [added-name-by-new-info (into {} (map (juxt val key)) new-info-by-added-name)] (into {} (keep (fn [[old-name old-info]] (when-some [renamed-name (added-name-by-new-info old-info)] [old-name renamed-name]))) old-info-by-removed-name))) (def ^:private xform-to-name-info-pairs (map (juxt :name #(dissoc % :name)))) (defn- edit-script-property [node-id type resource-kind value] (g/set-property node-id :type type :resource-kind resource-kind :value value)) (defn- create-script-property [script-node-id name type resource-kind value] (g/make-nodes (g/node-id->graph-id script-node-id) [node-id [ScriptPropertyNode :name name]] (edit-script-property node-id type resource-kind value) (g/connect node-id :_node-id script-node-id :nodes) (g/connect node-id :build-targets script-node-id :resource-property-build-targets) (g/connect node-id :name+node-id script-node-id :script-property-name+node-ids) (g/connect node-id :property-entries script-node-id :script-property-entries))) (defn- update-script-properties [evaluation-context script-node-id old-value new-value] (assert (or (nil? old-value) (vector? old-value))) (assert (or (nil? new-value) (vector? new-value))) (let [old-info-by-name (into {} xform-to-name-info-pairs old-value) new-info-by-name (into {} xform-to-name-info-pairs new-value) old-info-by-removed-name (into {} (remove (comp (partial contains? new-info-by-name) key)) old-info-by-name) new-info-by-added-name (into {} (remove (comp (partial contains? old-info-by-name) key)) new-info-by-name) renamed-name-by-old-name (detect-renames old-info-by-removed-name new-info-by-added-name) removed-names (into #{} (remove renamed-name-by-old-name) (keys old-info-by-removed-name)) added-info-by-name (apply dissoc new-info-by-added-name (vals renamed-name-by-old-name)) edited-info-by-name (detect-edits old-info-by-name new-info-by-name) node-ids-by-name (g/node-value script-node-id :script-property-node-ids-by-name evaluation-context)] (concat ;; Renamed properties. (for [[old-name new-name] renamed-name-by-old-name :let [node-id (node-ids-by-name old-name)]] (g/set-property node-id :name new-name)) ;; Added properties. (for [[name {:keys [resource-kind type value]}] added-info-by-name] (if-some [node-id (node-ids-by-name name)] (concat (g/set-property node-id :deleted? false) (edit-script-property node-id type resource-kind value)) (create-script-property script-node-id name type resource-kind value))) ;; Edited properties (i.e. the default value or property type changed). (for [[name {:keys [resource-kind type value]}] edited-info-by-name :let [node-id (node-ids-by-name name)]] (edit-script-property node-id type resource-kind value)) ;; Removed properties. (for [name removed-names :let [node-id (node-ids-by-name name)]] (g/set-property node-id :deleted? true))))) (defn- lift-error [node-id [prop-kw {:keys [error] :as prop} :as property-entry]] (if (nil? error) property-entry (let [lifted-error (g/error-aggregate [error] :_node-id node-id :_label prop-kw :message (:message error) :value (:value error))] [prop-kw (assoc prop :error lifted-error)]))) (g/defnk produce-properties [_declared-properties _node-id script-properties script-property-entries] (cond (g/error? _declared-properties) _declared-properties (g/error? script-property-entries) script-property-entries :else (-> _declared-properties (update :properties into (map (partial lift-error _node-id)) script-property-entries) (update :display-order into (map prop->key) script-properties)))) (defn- go-property-declaration-cursor-ranges "Find the CursorRanges that encompass each `go.property('name', ...)` declaration among the specified lines. These will be replaced with whitespace before the script is compiled for the engine." [lines] (loop [cursor-ranges (transient []) tokens (lua-parser/tokens (data/lines-reader lines)) paren-count 0 consumed []] (if-some [[text :as token] (first tokens)] (case (count consumed) 0 (recur cursor-ranges (next tokens) 0 (case text "go" (conj consumed token) [])) 1 (recur cursor-ranges (next tokens) 0 (case text "." (conj consumed token) [])) 2 (recur cursor-ranges (next tokens) 0 (case text "property" (conj consumed token) [])) 3 (case text "(" (recur cursor-ranges (next tokens) (inc paren-count) consumed) ")" (let [paren-count (dec paren-count)] (assert (not (neg? paren-count))) (if (pos? paren-count) (recur cursor-ranges (next tokens) paren-count consumed) (let [next-tokens (next tokens) [next-text :as next-token] (first next-tokens) [_ start-row start-col] (first consumed) [end-text end-row end-col] (if (= ";" next-text) next-token token) end-col (+ ^long end-col (count end-text)) start-cursor (data/->Cursor start-row start-col) end-cursor (data/->Cursor end-row end-col) cursor-range (data/->CursorRange start-cursor end-cursor)] (recur (conj! cursor-ranges cursor-range) next-tokens 0 [])))) (recur cursor-ranges (next tokens) paren-count consumed))) (persistent! cursor-ranges)))) (defn- line->whitespace [line] (string/join (repeat (count line) \space))) (defn- cursor-range->whitespace-lines [lines cursor-range] (let [{:keys [first-line middle-lines last-line]} (data/cursor-range-subsequence lines cursor-range)] (cond-> (into [(line->whitespace first-line)] (map line->whitespace) middle-lines) (some? last-line) (conj (line->whitespace last-line))))) (defn- strip-go-property-declarations [lines] (data/splice-lines lines (map (juxt identity (partial cursor-range->whitespace-lines lines)) (go-property-declaration-cursor-ranges lines)))) (defn- script->bytecode [lines proj-path arch] (try (luajit/bytecode (data/lines-reader lines) proj-path arch) (catch Exception e (let [{:keys [filename line message]} (ex-data e) cursor-range (some-> line data/line-number->CursorRange)] (g/map->error {:_label :modified-lines :message (.getMessage e) :severity :fatal :user-data (cond-> {:filename filename :message message} (some? cursor-range) (assoc :cursor-range cursor-range))}))))) (defn- build-script [resource dep-resources user-data] ;; We always compile the full source code in order to find syntax errors. ;; We then strip go.property() declarations and recompile if needed. (let [lines (:lines user-data) proj-path (:proj-path user-data) bytecode-or-error (script->bytecode lines proj-path :32-bit)] (g/precluding-errors [bytecode-or-error] (let [go-props (properties/build-go-props dep-resources (:go-props user-data)) modules (:modules user-data) cleaned-lines (strip-go-property-declarations lines) bytecode (if (identical? lines cleaned-lines) bytecode-or-error (script->bytecode cleaned-lines proj-path :32-bit)) bytecode-64 (script->bytecode cleaned-lines proj-path :64-bit)] (assert (not (g/error? bytecode))) (assert (not (g/error? bytecode-64))) {:resource resource :content (protobuf/map->bytes Lua$LuaModule {:source {:script (ByteString/copyFromUtf8 (slurp (data/lines-reader cleaned-lines))) :filename (resource/proj-path (:resource resource)) :bytecode (ByteString/copyFrom ^bytes bytecode) :bytecode-64 (ByteString/copyFrom ^bytes bytecode-64)} :modules modules :resources (mapv lua/lua-module->build-path modules) :properties (properties/go-props->decls go-props true) :property-resources (into (sorted-set) (keep properties/try-get-go-prop-proj-path) go-props)})})))) (g/defnk produce-build-targets [_node-id resource lines script-properties modules module-build-targets original-resource-property-build-targets] (if-some [errors (not-empty (keep (fn [{:keys [name resource-kind type value]}] (let [prop-type (script-property-type->property-type type) edit-type (script-property-edit-type prop-type resource-kind)] (validate-value-against-edit-type _node-id :lines name value edit-type))) script-properties))] (g/error-aggregate errors :_node-id _node-id :_label :build-targets) (let [go-props-with-source-resources (map (fn [{:keys [name type value]}] (let [go-prop-type (script-property-type->go-prop-type type) go-prop-value (properties/clj-value->go-prop-value go-prop-type value)] {:id name :type go-prop-type :value go-prop-value :clj-value value})) script-properties) [go-props go-prop-dep-build-targets] (properties/build-target-go-props original-resource-property-build-targets go-props-with-source-resources)] ;; NOTE: The :user-data must not contain any overridden data. If it does, ;; the build targets won't be fused and the script will be recompiled ;; for every instance of the script component. The :go-props here describe ;; the original property values from the script, never overridden values. [(bt/with-content-hash {:node-id _node-id :resource (workspace/make-build-resource resource) :build-fn build-script :user-data {:lines lines :go-props go-props :modules modules :proj-path (resource/proj-path resource)} :deps (into go-prop-dep-build-targets module-build-targets)})]))) (g/defnk produce-completions [completion-info module-completion-infos script-intelligence-completions] (code-completion/combine-completions completion-info module-completion-infos script-intelligence-completions)) (g/defnk produce-breakpoints [resource regions] (into [] (comp (filter data/breakpoint-region?) (map (fn [region] {:resource resource :row (data/breakpoint-row region)}))) regions)) (g/defnode ScriptNode (inherits r/CodeEditorResourceNode) (input module-build-targets g/Any :array) (input module-completion-infos g/Any :array :substitute gu/array-subst-remove-errors) (input script-intelligence-completions si/ScriptCompletions) (input script-property-name+node-ids NameNodeIDPair :array) (input script-property-entries ScriptPropertyEntries :array) (input resource-property-resources resource/Resource :array) (input resource-property-build-targets g/Any :array :substitute gu/array-subst-remove-errors) (input original-resource-property-build-targets g/Any :array :substitute gu/array-subst-remove-errors) (property completion-info g/Any (default {}) (dynamic visible (g/constantly false))) ;; Overrides modified-lines property in CodeEditorResourceNode. (property modified-lines r/Lines (dynamic visible (g/constantly false)) (set (fn [evaluation-context self _old-value new-value] (let [resource (g/node-value self :resource evaluation-context) lua-info (lua-parser/lua-info (resource/workspace resource) valid-resource-kind? (data/lines-reader new-value)) own-module (lua/path->lua-module (resource/proj-path resource)) completion-info (assoc lua-info :module own-module) modules (into [] (comp (map second) (remove lua/preinstalled-modules)) (:requires lua-info)) script-properties (into [] (comp (filter #(= :ok (:status %))) (util/distinct-by :name)) (:script-properties completion-info))] (concat (g/set-property self :completion-info completion-info) (g/set-property self :modules modules) (g/set-property self :script-properties script-properties)))))) (property modules Modules (default []) (dynamic visible (g/constantly false)) (set (fn [evaluation-context self _old-value new-value] (let [basis (:basis evaluation-context) project (project/get-project basis self)] (concat (g/disconnect-sources basis self :module-build-targets) (g/disconnect-sources basis self :module-completion-infos) (for [module new-value] (let [path (lua/lua-module->path module)] (:tx-data (project/connect-resource-node evaluation-context project path self [[:build-targets :module-build-targets] [:completion-info :module-completion-infos]]))))))))) (property script-properties g/Any (default []) (dynamic visible (g/constantly false)) (set (fn [evaluation-context self old-value new-value] (let [basis (:basis evaluation-context) project (project/get-project self)] (concat (update-script-properties evaluation-context self old-value new-value) (g/disconnect-sources basis self :original-resource-property-build-targets) (for [{:keys [type value]} new-value :when (and (= :script-property-type-resource type) (some? value))] (:tx-data (project/connect-resource-node evaluation-context project value self [[:build-targets :original-resource-property-build-targets]])))))))) ;; Breakpoints output only consumed by project (array input of all code files) ;; and already cached there. Changing breakpoints and pulling project breakpoints ;; does imply a pass over all ScriptNodes to produce new breakpoints, but does ;; not seem to be much of a perf issue. (output breakpoints project/Breakpoints produce-breakpoints) (output _properties g/Properties :cached produce-properties) (output build-targets g/Any :cached produce-build-targets) (output completions g/Any :cached produce-completions) (output resource-property-build-targets g/Any (gu/passthrough resource-property-build-targets)) (output script-property-entries ScriptPropertyEntries (g/fnk [script-property-entries] (reduce into {} script-property-entries))) (output script-property-node-ids-by-name NameNodeIDMap (g/fnk [script-property-name+node-ids] (into {} script-property-name+node-ids)))) (defn- additional-load-fn [project self resource] (let [script-intelligence (project/script-intelligence project)] (g/connect script-intelligence :lua-completions self :script-intelligence-completions))) (defn register-resource-types [workspace] (for [def script-defs :let [args (assoc def :node-type ScriptNode :eager-loading? true :additional-load-fn additional-load-fn)]] (apply r/register-code-resource-type workspace (mapcat identity args))))
63424
;; 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.code.script (:require [clojure.string :as string] [dynamo.graph :as g] [editor.build-target :as bt] [editor.code-completion :as code-completion] [editor.code.data :as data] [editor.code.resource :as r] [editor.code.script-intelligence :as si] [editor.defold-project :as project] [editor.graph-util :as gu] [editor.image :as image] [editor.lua :as lua] [editor.lua-parser :as lua-parser] [editor.luajit :as luajit] [editor.properties :as properties] [editor.protobuf :as protobuf] [editor.resource :as resource] [editor.types :as t] [editor.validation :as validation] [editor.workspace :as workspace] [internal.util :as util] [schema.core :as s]) (:import [com.dynamo.lua.proto Lua$LuaModule] [com.google.protobuf ByteString])) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (g/deftype Modules [String]) (def lua-grammar {:name "Lua" :scope-name "source.lua" ;; indent patterns shamelessly stolen from textmate: ;; https://github.com/textmate/lua.tmbundle/blob/master/Preferences/Indent.tmPreferences :indent {:begin #"^([^-]|-(?!-))*((\b(else|function|then|do|repeat)\b((?!\b(end|until)\b)[^\"'])*)|(\{\s*))$" :end #"^\s*((\b(elseif|else|end|until)\b)|(\})|(\)))"} :line-comment "--" :patterns [{:captures {1 {:name "keyword.control.lua"} 2 {:name "entity.name.function.scope.lua"} 3 {:name "entity.name.function.lua"} 4 {:name "punctuation.definition.parameters.begin.lua"} 5 {:name "variable.parameter.function.lua"} 6 {:name "punctuation.definition.parameters.end.lua"}} :match #"\b(function)(?:\s+([a-zA-Z_.:]+[.:])?([a-zA-Z_]\w*)\s*)?(\()([^)]*)(\))" :name "meta.function.lua"} {:match #"(?<![\d.])\s0x[a-fA-F\d]+|\b\d+(\.\d+)?([eE]-?\d+)?|\.\d+([eE]-?\d+)?" :name "constant.numeric.lua"} {:begin #"'" :begin-captures {0 {:name "punctuation.definition.string.begin.lua"}} :end #"'" :end-captures {0 {:name "punctuation.definition.string.end.lua"}} :name "string.quoted.single.lua" :patterns [{:match #"\\." :name "constant.character.escape.lua"}]} {:begin #"\"" :begin-captures {0 {:name "punctuation.definition.string.begin.lua"}} :end #"\"" :end-captures {0 {:name "punctuation.definition.string.end.lua"}} :name "string.quoted.double.lua" :patterns [{:match #"\\." :name "constant.character.escape.lua"}]} {:begin #"(?<!--)\[(=*)\[" :begin-captures {0 {:name "punctuation.definition.string.begin.lua"}} :end #"\]\1\]" :end-captures {0 {:name "punctuation.definition.string.end.lua"}} :name "string.quoted.other.multiline.lua"} {:begin #"--\[(=*)\[" :captures {0 {:name "punctuation.definition.comment.lua"}} :end #"\]\1\]" :name "comment.block.lua"} {:captures {1 {:name "punctuation.definition.comment.lua"}} :match #"(--).*" :name "comment.line.double-dash.lua"} {:match #"\b(and|or|not|break|do|else|for|if|elseif|return|then|repeat|while|until|end|function|local|in|goto)\b" :name "keyword.control.lua"} {:match #"(?<![^.]\.|:)\b([A-Z_][0-9A-Z_]*|false|nil|true|math\.(pi|huge))\b|(?<![.])\.{3}(?!\.)" :name "constant.language.lua"} {:match #"(?<![^.]\.|:)\b(self)\b" :name "variable.language.self.lua"} {:match #"(?<![^.]\.|:)\b(assert|collectgarbage|dofile|error|getfenv|getmetatable|ipairs|loadfile|loadstring|module|next|pairs|pcall|print|rawequal|rawget|rawset|require|select|setfenv|setmetatable|tonumber|tostring|type|unpack|xpcall)\b(?=\s*(?:[({\"']|\[\[))" :name "support.function.lua"} {:match #"(?<![^.]\.|:)\b(coroutine\.(create|resume|running|status|wrap|yield)|string\.(byte|char|dump|find|format|gmatch|gsub|len|lower|match|rep|reverse|sub|upper)|table\.(concat|insert|maxn|remove|sort)|math\.(abs|acos|asin|atan2?|ceil|cosh?|deg|exp|floor|fmod|frexp|ldexp|log|log10|max|min|modf|pow|rad|random|randomseed|sinh?|sqrt|tanh?)|io\.(close|flush|input|lines|open|output|popen|read|tmpfile|type|write)|os\.(clock|date|difftime|execute|exit|getenv|remove|rename|setlocale|time|tmpname)|package\.(cpath|loaded|loadlib|path|preload|seeall)|debug\.(debug|[gs]etfenv|[gs]ethook|getinfo|[gs]etlocal|[gs]etmetatable|getregistry|[gs]etupvalue|traceback))\b(?=\s*(?:[({\"']|\[\[))" :name "support.function.library.lua"} {:match #"\b([A-Za-z_]\w*)\b(?=\s*(?:[({\"']|\[\[))" :name "support.function.any-method.lua"} {:match #"(?<=[^.]\.|:)\b([A-Za-z_]\w*)" :name "variable.other.lua"} {:match #"\+|-|%|#|\*|\/|\^|==?|~=|<=?|>=?|(?<!\.)\.{2}(?!\.)" :name "keyword.operator.lua"}]}) (def lua-code-opts {:code {:grammar lua-grammar}}) (defn script-property-type->property-type "Controls how script property values are represented in the graph and edited." [script-property-type] (case script-property-type :script-property-type-number g/Num :script-property-type-hash g/Str :script-property-type-url g/Str :script-property-type-vector3 t/Vec3 :script-property-type-vector4 t/Vec4 :script-property-type-quat t/Vec3 :script-property-type-boolean g/Bool :script-property-type-resource resource/Resource)) (defn script-property-type->go-prop-type "Controls how script property values are represented in the file formats." [script-property-type] (case script-property-type :script-property-type-number :property-type-number :script-property-type-hash :property-type-hash :script-property-type-url :property-type-url :script-property-type-vector3 :property-type-vector3 :script-property-type-vector4 :property-type-vector4 :script-property-type-quat :property-type-quat :script-property-type-boolean :property-type-boolean :script-property-type-resource :property-type-hash)) (g/deftype ScriptPropertyType (s/enum :script-property-type-number :script-property-type-hash :script-property-type-url :script-property-type-vector3 :script-property-type-vector4 :script-property-type-quat :script-property-type-boolean :script-property-type-resource)) (def script-defs [{:ext "script" :label "Script" :icon "icons/32/Icons_12-Script-type.png" :view-types [:code :default] :view-opts lua-code-opts :tags #{:component :debuggable :non-embeddable :overridable-properties} :tag-opts {:component {:transform-properties #{}}}} {:ext "render_script" :label "Render Script" :icon "icons/32/Icons_12-Script-type.png" :view-types [:code :default] :view-opts lua-code-opts :tags #{:debuggable}} {:ext "gui_script" :label "Gui Script" :icon "icons/32/Icons_12-Script-type.png" :view-types [:code :default] :view-opts lua-code-opts :tags #{:debuggable}} {:ext "lua" :label "Lua Module" :icon "icons/32/Icons_11-Script-general.png" :view-types [:code :default] :view-opts lua-code-opts :tags #{:debuggable}}]) (def ^:private status-errors {:ok nil :invalid-args (g/error-fatal "Invalid arguments to go.property call") ; TODO: not used for now :invalid-value (g/error-fatal "Invalid value in go.property call")}) (defn- prop->key [p] (-> p :name properties/user-name->key)) (def resource-kind->ext "Declares which file extensions are valid for different kinds of resource properties. This affects the Property Editor, but is also used for validation." {"atlas" ["atlas" "tilesource"] "font" "font" "material" "material" "buffer" "buffer" "texture" (conj image/exts "cubemap") "tile_source" "tilesource"}) (def ^:private valid-resource-kind? (partial contains? resource-kind->ext)) (defn- script-property-edit-type [prop-type resource-kind] (if (= resource/Resource prop-type) {:type prop-type :ext (resource-kind->ext resource-kind)} {:type prop-type})) (defn- resource-assignment-error [node-id prop-kw prop-name resource expected-ext] (when (some? resource) (let [resource-ext (resource/ext resource) ext-match? (if (coll? expected-ext) (some? (some (partial = resource-ext) expected-ext)) (= expected-ext resource-ext))] (cond (not ext-match?) (g/->error node-id prop-kw :fatal resource (format "%s '%s' is not of type %s" (validation/format-name prop-name) (resource/proj-path resource) (validation/format-ext expected-ext))) (not (resource/exists? resource)) (g/->error node-id prop-kw :fatal resource (format "%s '%s' could not be found" (validation/format-name prop-name) (resource/proj-path resource))))))) (defn- validate-value-against-edit-type [node-id prop-kw prop-name value edit-type] (when (= resource/Resource (:type edit-type)) (resource-assignment-error node-id prop-kw prop-name value (:ext edit-type)))) (g/defnk produce-script-property-entries [_basis _node-id deleted? name resource-kind type value] (when-not deleted? (let [prop-kw (properties/user-name->key name) prop-type (script-property-type->property-type type) edit-type (script-property-edit-type prop-type resource-kind) error (validate-value-against-edit-type _node-id :value name value edit-type) go-prop-type (script-property-type->go-prop-type type) overridden? (g/property-overridden? _basis _node-id :value) read-only? (nil? (g/override-original _basis _node-id)) visible? (not deleted?)] ;; NOTE: :assoc-original-value? here tells the node internals that it ;; needs to assoc in the :original-value from the overridden node when ;; evaluating :_properties or :_declared-properties. This happens ;; automatically when the overridden property is in the properties map of ;; the OverrideNode, but in our case the ScriptNode is presenting a ;; property that resides on the ScriptPropertyNode, so there won't be an ;; entry in the properties map of the ScriptNode OverrideNode. {prop-kw {:assoc-original-value? overridden? :edit-type edit-type :error error :go-prop-type go-prop-type :node-id _node-id :prop-kw :value :read-only? read-only? :type prop-type :value value :visible visible?}}))) (g/deftype NameNodeIDPair [(s/one s/Str "name") (s/one s/Int "node-id")]) (g/deftype NameNodeIDMap {s/Str s/Int}) (g/deftype ResourceKind (apply s/enum (keys resource-kind->ext))) (g/deftype ScriptPropertyEntries {s/Keyword {:node-id s/Int :go-prop-type properties/TGoPropType :type s/Any :value s/Any s/Keyword s/Any}}) ;; Every declared `go.property("name", 0.0)` in the script code gets a ;; corresponding ScriptPropertyNode. This started as a workaround for the fact ;; that dynamic properties couldn't host the property setter required for ;; resource properties, but it turns out to have other benefits. Like the fact ;; you can edit a property name in the script and have the rename propagate to ;; all usages of the script. (g/defnode ScriptPropertyNode ;; The deleted? property is used instead of deleting the ScriptPropertyNode so ;; that overrides in collections and game objects survive cut-paste operations ;; on the go.property declarations in the script code. (property deleted? g/Bool) (property edit-type g/Any) (property name g/Str) (property resource-kind ResourceKind) (property type ScriptPropertyType) (property value g/Any (value (g/fnk [type resource value] ;; For resource properties we use the Resource from the ;; connected ResourceNode in order to track renames, etc. (case type :script-property-type-resource resource value))) (set (fn [evaluation-context self _old-value new-value] ;; When assigning a resource property, we must make sure the ;; assigned resource is built and included in the game. (let [basis (:basis evaluation-context) project (project/get-project self)] (concat (g/disconnect-sources basis self :resource) (g/disconnect-sources basis self :resource-build-targets) (when (resource/resource? new-value) (:tx-data (project/connect-resource-node evaluation-context project new-value self [[:resource :resource] [:build-targets :resource-build-targets]])))))))) (input resource resource/Resource) (input resource-build-targets g/Any) (output build-targets g/Any (g/fnk [deleted? resource-build-targets type] (when (and (not deleted?) (= :script-property-type-resource type)) resource-build-targets))) (output name+node-id NameNodeIDPair (g/fnk [_node-id name] [name _node-id])) (output property-entries ScriptPropertyEntries :cached produce-script-property-entries)) (defmethod g/node-key ::ScriptPropertyNode [node-id evaluation-context] ;; By implementing this multi-method, overridden property values will be ;; restored on OverrideNode ScriptPropertyNodes when a script is reloaded from ;; disk during resource-sync. The node-key must be unique within the script. (g/node-value node-id :name evaluation-context)) (defn- detect-edits [old-info-by-name new-info-by-name] (into {} (filter (fn [[name new-info]] (when-some [old-info (old-info-by-name name)] (not= old-info new-info)))) new-info-by-name)) (defn- detect-renames [old-info-by-removed-name new-info-by-added-name] (let [added-name-by-new-info (into {} (map (juxt val key)) new-info-by-added-name)] (into {} (keep (fn [[old-name old-info]] (when-some [renamed-name (added-name-by-new-info old-info)] [old-name renamed-name]))) old-info-by-removed-name))) (def ^:private xform-to-name-info-pairs (map (juxt :name #(dissoc % :name)))) (defn- edit-script-property [node-id type resource-kind value] (g/set-property node-id :type type :resource-kind resource-kind :value value)) (defn- create-script-property [script-node-id name type resource-kind value] (g/make-nodes (g/node-id->graph-id script-node-id) [node-id [ScriptPropertyNode :name name]] (edit-script-property node-id type resource-kind value) (g/connect node-id :_node-id script-node-id :nodes) (g/connect node-id :build-targets script-node-id :resource-property-build-targets) (g/connect node-id :name+node-id script-node-id :script-property-name+node-ids) (g/connect node-id :property-entries script-node-id :script-property-entries))) (defn- update-script-properties [evaluation-context script-node-id old-value new-value] (assert (or (nil? old-value) (vector? old-value))) (assert (or (nil? new-value) (vector? new-value))) (let [old-info-by-name (into {} xform-to-name-info-pairs old-value) new-info-by-name (into {} xform-to-name-info-pairs new-value) old-info-by-removed-name (into {} (remove (comp (partial contains? new-info-by-name) key)) old-info-by-name) new-info-by-added-name (into {} (remove (comp (partial contains? old-info-by-name) key)) new-info-by-name) renamed-name-by-old-name (detect-renames old-info-by-removed-name new-info-by-added-name) removed-names (into #{} (remove renamed-name-by-old-name) (keys old-info-by-removed-name)) added-info-by-name (apply dissoc new-info-by-added-name (vals renamed-name-by-old-name)) edited-info-by-name (detect-edits old-info-by-name new-info-by-name) node-ids-by-name (g/node-value script-node-id :script-property-node-ids-by-name evaluation-context)] (concat ;; Renamed properties. (for [[old-name new-name] renamed-name-by-old-name :let [node-id (node-ids-by-name old-name)]] (g/set-property node-id :name new-name)) ;; Added properties. (for [[name {:keys [resource-kind type value]}] added-info-by-name] (if-some [node-id (node-ids-by-name name)] (concat (g/set-property node-id :deleted? false) (edit-script-property node-id type resource-kind value)) (create-script-property script-node-id name type resource-kind value))) ;; Edited properties (i.e. the default value or property type changed). (for [[name {:keys [resource-kind type value]}] edited-info-by-name :let [node-id (node-ids-by-name name)]] (edit-script-property node-id type resource-kind value)) ;; Removed properties. (for [name removed-names :let [node-id (node-ids-by-name name)]] (g/set-property node-id :deleted? true))))) (defn- lift-error [node-id [prop-kw {:keys [error] :as prop} :as property-entry]] (if (nil? error) property-entry (let [lifted-error (g/error-aggregate [error] :_node-id node-id :_label prop-kw :message (:message error) :value (:value error))] [prop-kw (assoc prop :error lifted-error)]))) (g/defnk produce-properties [_declared-properties _node-id script-properties script-property-entries] (cond (g/error? _declared-properties) _declared-properties (g/error? script-property-entries) script-property-entries :else (-> _declared-properties (update :properties into (map (partial lift-error _node-id)) script-property-entries) (update :display-order into (map prop->key) script-properties)))) (defn- go-property-declaration-cursor-ranges "Find the CursorRanges that encompass each `go.property('name', ...)` declaration among the specified lines. These will be replaced with whitespace before the script is compiled for the engine." [lines] (loop [cursor-ranges (transient []) tokens (lua-parser/tokens (data/lines-reader lines)) paren-count 0 consumed []] (if-some [[text :as token] (first tokens)] (case (count consumed) 0 (recur cursor-ranges (next tokens) 0 (case text "go" (conj consumed token) [])) 1 (recur cursor-ranges (next tokens) 0 (case text "." (conj consumed token) [])) 2 (recur cursor-ranges (next tokens) 0 (case text "property" (conj consumed token) [])) 3 (case text "(" (recur cursor-ranges (next tokens) (inc paren-count) consumed) ")" (let [paren-count (dec paren-count)] (assert (not (neg? paren-count))) (if (pos? paren-count) (recur cursor-ranges (next tokens) paren-count consumed) (let [next-tokens (next tokens) [next-text :as next-token] (first next-tokens) [_ start-row start-col] (first consumed) [end-text end-row end-col] (if (= ";" next-text) next-token token) end-col (+ ^long end-col (count end-text)) start-cursor (data/->Cursor start-row start-col) end-cursor (data/->Cursor end-row end-col) cursor-range (data/->CursorRange start-cursor end-cursor)] (recur (conj! cursor-ranges cursor-range) next-tokens 0 [])))) (recur cursor-ranges (next tokens) paren-count consumed))) (persistent! cursor-ranges)))) (defn- line->whitespace [line] (string/join (repeat (count line) \space))) (defn- cursor-range->whitespace-lines [lines cursor-range] (let [{:keys [first-line middle-lines last-line]} (data/cursor-range-subsequence lines cursor-range)] (cond-> (into [(line->whitespace first-line)] (map line->whitespace) middle-lines) (some? last-line) (conj (line->whitespace last-line))))) (defn- strip-go-property-declarations [lines] (data/splice-lines lines (map (juxt identity (partial cursor-range->whitespace-lines lines)) (go-property-declaration-cursor-ranges lines)))) (defn- script->bytecode [lines proj-path arch] (try (luajit/bytecode (data/lines-reader lines) proj-path arch) (catch Exception e (let [{:keys [filename line message]} (ex-data e) cursor-range (some-> line data/line-number->CursorRange)] (g/map->error {:_label :modified-lines :message (.getMessage e) :severity :fatal :user-data (cond-> {:filename filename :message message} (some? cursor-range) (assoc :cursor-range cursor-range))}))))) (defn- build-script [resource dep-resources user-data] ;; We always compile the full source code in order to find syntax errors. ;; We then strip go.property() declarations and recompile if needed. (let [lines (:lines user-data) proj-path (:proj-path user-data) bytecode-or-error (script->bytecode lines proj-path :32-bit)] (g/precluding-errors [bytecode-or-error] (let [go-props (properties/build-go-props dep-resources (:go-props user-data)) modules (:modules user-data) cleaned-lines (strip-go-property-declarations lines) bytecode (if (identical? lines cleaned-lines) bytecode-or-error (script->bytecode cleaned-lines proj-path :32-bit)) bytecode-64 (script->bytecode cleaned-lines proj-path :64-bit)] (assert (not (g/error? bytecode))) (assert (not (g/error? bytecode-64))) {:resource resource :content (protobuf/map->bytes Lua$LuaModule {:source {:script (ByteString/copyFromUtf8 (slurp (data/lines-reader cleaned-lines))) :filename (resource/proj-path (:resource resource)) :bytecode (ByteString/copyFrom ^bytes bytecode) :bytecode-64 (ByteString/copyFrom ^bytes bytecode-64)} :modules modules :resources (mapv lua/lua-module->build-path modules) :properties (properties/go-props->decls go-props true) :property-resources (into (sorted-set) (keep properties/try-get-go-prop-proj-path) go-props)})})))) (g/defnk produce-build-targets [_node-id resource lines script-properties modules module-build-targets original-resource-property-build-targets] (if-some [errors (not-empty (keep (fn [{:keys [name resource-kind type value]}] (let [prop-type (script-property-type->property-type type) edit-type (script-property-edit-type prop-type resource-kind)] (validate-value-against-edit-type _node-id :lines name value edit-type))) script-properties))] (g/error-aggregate errors :_node-id _node-id :_label :build-targets) (let [go-props-with-source-resources (map (fn [{:keys [name type value]}] (let [go-prop-type (script-property-type->go-prop-type type) go-prop-value (properties/clj-value->go-prop-value go-prop-type value)] {:id name :type go-prop-type :value go-prop-value :clj-value value})) script-properties) [go-props go-prop-dep-build-targets] (properties/build-target-go-props original-resource-property-build-targets go-props-with-source-resources)] ;; NOTE: The :user-data must not contain any overridden data. If it does, ;; the build targets won't be fused and the script will be recompiled ;; for every instance of the script component. The :go-props here describe ;; the original property values from the script, never overridden values. [(bt/with-content-hash {:node-id _node-id :resource (workspace/make-build-resource resource) :build-fn build-script :user-data {:lines lines :go-props go-props :modules modules :proj-path (resource/proj-path resource)} :deps (into go-prop-dep-build-targets module-build-targets)})]))) (g/defnk produce-completions [completion-info module-completion-infos script-intelligence-completions] (code-completion/combine-completions completion-info module-completion-infos script-intelligence-completions)) (g/defnk produce-breakpoints [resource regions] (into [] (comp (filter data/breakpoint-region?) (map (fn [region] {:resource resource :row (data/breakpoint-row region)}))) regions)) (g/defnode ScriptNode (inherits r/CodeEditorResourceNode) (input module-build-targets g/Any :array) (input module-completion-infos g/Any :array :substitute gu/array-subst-remove-errors) (input script-intelligence-completions si/ScriptCompletions) (input script-property-name+node-ids NameNodeIDPair :array) (input script-property-entries ScriptPropertyEntries :array) (input resource-property-resources resource/Resource :array) (input resource-property-build-targets g/Any :array :substitute gu/array-subst-remove-errors) (input original-resource-property-build-targets g/Any :array :substitute gu/array-subst-remove-errors) (property completion-info g/Any (default {}) (dynamic visible (g/constantly false))) ;; Overrides modified-lines property in CodeEditorResourceNode. (property modified-lines r/Lines (dynamic visible (g/constantly false)) (set (fn [evaluation-context self _old-value new-value] (let [resource (g/node-value self :resource evaluation-context) lua-info (lua-parser/lua-info (resource/workspace resource) valid-resource-kind? (data/lines-reader new-value)) own-module (lua/path->lua-module (resource/proj-path resource)) completion-info (assoc lua-info :module own-module) modules (into [] (comp (map second) (remove lua/preinstalled-modules)) (:requires lua-info)) script-properties (into [] (comp (filter #(= :ok (:status %))) (util/distinct-by :name)) (:script-properties completion-info))] (concat (g/set-property self :completion-info completion-info) (g/set-property self :modules modules) (g/set-property self :script-properties script-properties)))))) (property modules Modules (default []) (dynamic visible (g/constantly false)) (set (fn [evaluation-context self _old-value new-value] (let [basis (:basis evaluation-context) project (project/get-project basis self)] (concat (g/disconnect-sources basis self :module-build-targets) (g/disconnect-sources basis self :module-completion-infos) (for [module new-value] (let [path (lua/lua-module->path module)] (:tx-data (project/connect-resource-node evaluation-context project path self [[:build-targets :module-build-targets] [:completion-info :module-completion-infos]]))))))))) (property script-properties g/Any (default []) (dynamic visible (g/constantly false)) (set (fn [evaluation-context self old-value new-value] (let [basis (:basis evaluation-context) project (project/get-project self)] (concat (update-script-properties evaluation-context self old-value new-value) (g/disconnect-sources basis self :original-resource-property-build-targets) (for [{:keys [type value]} new-value :when (and (= :script-property-type-resource type) (some? value))] (:tx-data (project/connect-resource-node evaluation-context project value self [[:build-targets :original-resource-property-build-targets]])))))))) ;; Breakpoints output only consumed by project (array input of all code files) ;; and already cached there. Changing breakpoints and pulling project breakpoints ;; does imply a pass over all ScriptNodes to produce new breakpoints, but does ;; not seem to be much of a perf issue. (output breakpoints project/Breakpoints produce-breakpoints) (output _properties g/Properties :cached produce-properties) (output build-targets g/Any :cached produce-build-targets) (output completions g/Any :cached produce-completions) (output resource-property-build-targets g/Any (gu/passthrough resource-property-build-targets)) (output script-property-entries ScriptPropertyEntries (g/fnk [script-property-entries] (reduce into {} script-property-entries))) (output script-property-node-ids-by-name NameNodeIDMap (g/fnk [script-property-name+node-ids] (into {} script-property-name+node-ids)))) (defn- additional-load-fn [project self resource] (let [script-intelligence (project/script-intelligence project)] (g/connect script-intelligence :lua-completions self :script-intelligence-completions))) (defn register-resource-types [workspace] (for [def script-defs :let [args (assoc def :node-type ScriptNode :eager-loading? true :additional-load-fn additional-load-fn)]] (apply r/register-code-resource-type workspace (mapcat identity args))))
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.code.script (:require [clojure.string :as string] [dynamo.graph :as g] [editor.build-target :as bt] [editor.code-completion :as code-completion] [editor.code.data :as data] [editor.code.resource :as r] [editor.code.script-intelligence :as si] [editor.defold-project :as project] [editor.graph-util :as gu] [editor.image :as image] [editor.lua :as lua] [editor.lua-parser :as lua-parser] [editor.luajit :as luajit] [editor.properties :as properties] [editor.protobuf :as protobuf] [editor.resource :as resource] [editor.types :as t] [editor.validation :as validation] [editor.workspace :as workspace] [internal.util :as util] [schema.core :as s]) (:import [com.dynamo.lua.proto Lua$LuaModule] [com.google.protobuf ByteString])) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (g/deftype Modules [String]) (def lua-grammar {:name "Lua" :scope-name "source.lua" ;; indent patterns shamelessly stolen from textmate: ;; https://github.com/textmate/lua.tmbundle/blob/master/Preferences/Indent.tmPreferences :indent {:begin #"^([^-]|-(?!-))*((\b(else|function|then|do|repeat)\b((?!\b(end|until)\b)[^\"'])*)|(\{\s*))$" :end #"^\s*((\b(elseif|else|end|until)\b)|(\})|(\)))"} :line-comment "--" :patterns [{:captures {1 {:name "keyword.control.lua"} 2 {:name "entity.name.function.scope.lua"} 3 {:name "entity.name.function.lua"} 4 {:name "punctuation.definition.parameters.begin.lua"} 5 {:name "variable.parameter.function.lua"} 6 {:name "punctuation.definition.parameters.end.lua"}} :match #"\b(function)(?:\s+([a-zA-Z_.:]+[.:])?([a-zA-Z_]\w*)\s*)?(\()([^)]*)(\))" :name "meta.function.lua"} {:match #"(?<![\d.])\s0x[a-fA-F\d]+|\b\d+(\.\d+)?([eE]-?\d+)?|\.\d+([eE]-?\d+)?" :name "constant.numeric.lua"} {:begin #"'" :begin-captures {0 {:name "punctuation.definition.string.begin.lua"}} :end #"'" :end-captures {0 {:name "punctuation.definition.string.end.lua"}} :name "string.quoted.single.lua" :patterns [{:match #"\\." :name "constant.character.escape.lua"}]} {:begin #"\"" :begin-captures {0 {:name "punctuation.definition.string.begin.lua"}} :end #"\"" :end-captures {0 {:name "punctuation.definition.string.end.lua"}} :name "string.quoted.double.lua" :patterns [{:match #"\\." :name "constant.character.escape.lua"}]} {:begin #"(?<!--)\[(=*)\[" :begin-captures {0 {:name "punctuation.definition.string.begin.lua"}} :end #"\]\1\]" :end-captures {0 {:name "punctuation.definition.string.end.lua"}} :name "string.quoted.other.multiline.lua"} {:begin #"--\[(=*)\[" :captures {0 {:name "punctuation.definition.comment.lua"}} :end #"\]\1\]" :name "comment.block.lua"} {:captures {1 {:name "punctuation.definition.comment.lua"}} :match #"(--).*" :name "comment.line.double-dash.lua"} {:match #"\b(and|or|not|break|do|else|for|if|elseif|return|then|repeat|while|until|end|function|local|in|goto)\b" :name "keyword.control.lua"} {:match #"(?<![^.]\.|:)\b([A-Z_][0-9A-Z_]*|false|nil|true|math\.(pi|huge))\b|(?<![.])\.{3}(?!\.)" :name "constant.language.lua"} {:match #"(?<![^.]\.|:)\b(self)\b" :name "variable.language.self.lua"} {:match #"(?<![^.]\.|:)\b(assert|collectgarbage|dofile|error|getfenv|getmetatable|ipairs|loadfile|loadstring|module|next|pairs|pcall|print|rawequal|rawget|rawset|require|select|setfenv|setmetatable|tonumber|tostring|type|unpack|xpcall)\b(?=\s*(?:[({\"']|\[\[))" :name "support.function.lua"} {:match #"(?<![^.]\.|:)\b(coroutine\.(create|resume|running|status|wrap|yield)|string\.(byte|char|dump|find|format|gmatch|gsub|len|lower|match|rep|reverse|sub|upper)|table\.(concat|insert|maxn|remove|sort)|math\.(abs|acos|asin|atan2?|ceil|cosh?|deg|exp|floor|fmod|frexp|ldexp|log|log10|max|min|modf|pow|rad|random|randomseed|sinh?|sqrt|tanh?)|io\.(close|flush|input|lines|open|output|popen|read|tmpfile|type|write)|os\.(clock|date|difftime|execute|exit|getenv|remove|rename|setlocale|time|tmpname)|package\.(cpath|loaded|loadlib|path|preload|seeall)|debug\.(debug|[gs]etfenv|[gs]ethook|getinfo|[gs]etlocal|[gs]etmetatable|getregistry|[gs]etupvalue|traceback))\b(?=\s*(?:[({\"']|\[\[))" :name "support.function.library.lua"} {:match #"\b([A-Za-z_]\w*)\b(?=\s*(?:[({\"']|\[\[))" :name "support.function.any-method.lua"} {:match #"(?<=[^.]\.|:)\b([A-Za-z_]\w*)" :name "variable.other.lua"} {:match #"\+|-|%|#|\*|\/|\^|==?|~=|<=?|>=?|(?<!\.)\.{2}(?!\.)" :name "keyword.operator.lua"}]}) (def lua-code-opts {:code {:grammar lua-grammar}}) (defn script-property-type->property-type "Controls how script property values are represented in the graph and edited." [script-property-type] (case script-property-type :script-property-type-number g/Num :script-property-type-hash g/Str :script-property-type-url g/Str :script-property-type-vector3 t/Vec3 :script-property-type-vector4 t/Vec4 :script-property-type-quat t/Vec3 :script-property-type-boolean g/Bool :script-property-type-resource resource/Resource)) (defn script-property-type->go-prop-type "Controls how script property values are represented in the file formats." [script-property-type] (case script-property-type :script-property-type-number :property-type-number :script-property-type-hash :property-type-hash :script-property-type-url :property-type-url :script-property-type-vector3 :property-type-vector3 :script-property-type-vector4 :property-type-vector4 :script-property-type-quat :property-type-quat :script-property-type-boolean :property-type-boolean :script-property-type-resource :property-type-hash)) (g/deftype ScriptPropertyType (s/enum :script-property-type-number :script-property-type-hash :script-property-type-url :script-property-type-vector3 :script-property-type-vector4 :script-property-type-quat :script-property-type-boolean :script-property-type-resource)) (def script-defs [{:ext "script" :label "Script" :icon "icons/32/Icons_12-Script-type.png" :view-types [:code :default] :view-opts lua-code-opts :tags #{:component :debuggable :non-embeddable :overridable-properties} :tag-opts {:component {:transform-properties #{}}}} {:ext "render_script" :label "Render Script" :icon "icons/32/Icons_12-Script-type.png" :view-types [:code :default] :view-opts lua-code-opts :tags #{:debuggable}} {:ext "gui_script" :label "Gui Script" :icon "icons/32/Icons_12-Script-type.png" :view-types [:code :default] :view-opts lua-code-opts :tags #{:debuggable}} {:ext "lua" :label "Lua Module" :icon "icons/32/Icons_11-Script-general.png" :view-types [:code :default] :view-opts lua-code-opts :tags #{:debuggable}}]) (def ^:private status-errors {:ok nil :invalid-args (g/error-fatal "Invalid arguments to go.property call") ; TODO: not used for now :invalid-value (g/error-fatal "Invalid value in go.property call")}) (defn- prop->key [p] (-> p :name properties/user-name->key)) (def resource-kind->ext "Declares which file extensions are valid for different kinds of resource properties. This affects the Property Editor, but is also used for validation." {"atlas" ["atlas" "tilesource"] "font" "font" "material" "material" "buffer" "buffer" "texture" (conj image/exts "cubemap") "tile_source" "tilesource"}) (def ^:private valid-resource-kind? (partial contains? resource-kind->ext)) (defn- script-property-edit-type [prop-type resource-kind] (if (= resource/Resource prop-type) {:type prop-type :ext (resource-kind->ext resource-kind)} {:type prop-type})) (defn- resource-assignment-error [node-id prop-kw prop-name resource expected-ext] (when (some? resource) (let [resource-ext (resource/ext resource) ext-match? (if (coll? expected-ext) (some? (some (partial = resource-ext) expected-ext)) (= expected-ext resource-ext))] (cond (not ext-match?) (g/->error node-id prop-kw :fatal resource (format "%s '%s' is not of type %s" (validation/format-name prop-name) (resource/proj-path resource) (validation/format-ext expected-ext))) (not (resource/exists? resource)) (g/->error node-id prop-kw :fatal resource (format "%s '%s' could not be found" (validation/format-name prop-name) (resource/proj-path resource))))))) (defn- validate-value-against-edit-type [node-id prop-kw prop-name value edit-type] (when (= resource/Resource (:type edit-type)) (resource-assignment-error node-id prop-kw prop-name value (:ext edit-type)))) (g/defnk produce-script-property-entries [_basis _node-id deleted? name resource-kind type value] (when-not deleted? (let [prop-kw (properties/user-name->key name) prop-type (script-property-type->property-type type) edit-type (script-property-edit-type prop-type resource-kind) error (validate-value-against-edit-type _node-id :value name value edit-type) go-prop-type (script-property-type->go-prop-type type) overridden? (g/property-overridden? _basis _node-id :value) read-only? (nil? (g/override-original _basis _node-id)) visible? (not deleted?)] ;; NOTE: :assoc-original-value? here tells the node internals that it ;; needs to assoc in the :original-value from the overridden node when ;; evaluating :_properties or :_declared-properties. This happens ;; automatically when the overridden property is in the properties map of ;; the OverrideNode, but in our case the ScriptNode is presenting a ;; property that resides on the ScriptPropertyNode, so there won't be an ;; entry in the properties map of the ScriptNode OverrideNode. {prop-kw {:assoc-original-value? overridden? :edit-type edit-type :error error :go-prop-type go-prop-type :node-id _node-id :prop-kw :value :read-only? read-only? :type prop-type :value value :visible visible?}}))) (g/deftype NameNodeIDPair [(s/one s/Str "name") (s/one s/Int "node-id")]) (g/deftype NameNodeIDMap {s/Str s/Int}) (g/deftype ResourceKind (apply s/enum (keys resource-kind->ext))) (g/deftype ScriptPropertyEntries {s/Keyword {:node-id s/Int :go-prop-type properties/TGoPropType :type s/Any :value s/Any s/Keyword s/Any}}) ;; Every declared `go.property("name", 0.0)` in the script code gets a ;; corresponding ScriptPropertyNode. This started as a workaround for the fact ;; that dynamic properties couldn't host the property setter required for ;; resource properties, but it turns out to have other benefits. Like the fact ;; you can edit a property name in the script and have the rename propagate to ;; all usages of the script. (g/defnode ScriptPropertyNode ;; The deleted? property is used instead of deleting the ScriptPropertyNode so ;; that overrides in collections and game objects survive cut-paste operations ;; on the go.property declarations in the script code. (property deleted? g/Bool) (property edit-type g/Any) (property name g/Str) (property resource-kind ResourceKind) (property type ScriptPropertyType) (property value g/Any (value (g/fnk [type resource value] ;; For resource properties we use the Resource from the ;; connected ResourceNode in order to track renames, etc. (case type :script-property-type-resource resource value))) (set (fn [evaluation-context self _old-value new-value] ;; When assigning a resource property, we must make sure the ;; assigned resource is built and included in the game. (let [basis (:basis evaluation-context) project (project/get-project self)] (concat (g/disconnect-sources basis self :resource) (g/disconnect-sources basis self :resource-build-targets) (when (resource/resource? new-value) (:tx-data (project/connect-resource-node evaluation-context project new-value self [[:resource :resource] [:build-targets :resource-build-targets]])))))))) (input resource resource/Resource) (input resource-build-targets g/Any) (output build-targets g/Any (g/fnk [deleted? resource-build-targets type] (when (and (not deleted?) (= :script-property-type-resource type)) resource-build-targets))) (output name+node-id NameNodeIDPair (g/fnk [_node-id name] [name _node-id])) (output property-entries ScriptPropertyEntries :cached produce-script-property-entries)) (defmethod g/node-key ::ScriptPropertyNode [node-id evaluation-context] ;; By implementing this multi-method, overridden property values will be ;; restored on OverrideNode ScriptPropertyNodes when a script is reloaded from ;; disk during resource-sync. The node-key must be unique within the script. (g/node-value node-id :name evaluation-context)) (defn- detect-edits [old-info-by-name new-info-by-name] (into {} (filter (fn [[name new-info]] (when-some [old-info (old-info-by-name name)] (not= old-info new-info)))) new-info-by-name)) (defn- detect-renames [old-info-by-removed-name new-info-by-added-name] (let [added-name-by-new-info (into {} (map (juxt val key)) new-info-by-added-name)] (into {} (keep (fn [[old-name old-info]] (when-some [renamed-name (added-name-by-new-info old-info)] [old-name renamed-name]))) old-info-by-removed-name))) (def ^:private xform-to-name-info-pairs (map (juxt :name #(dissoc % :name)))) (defn- edit-script-property [node-id type resource-kind value] (g/set-property node-id :type type :resource-kind resource-kind :value value)) (defn- create-script-property [script-node-id name type resource-kind value] (g/make-nodes (g/node-id->graph-id script-node-id) [node-id [ScriptPropertyNode :name name]] (edit-script-property node-id type resource-kind value) (g/connect node-id :_node-id script-node-id :nodes) (g/connect node-id :build-targets script-node-id :resource-property-build-targets) (g/connect node-id :name+node-id script-node-id :script-property-name+node-ids) (g/connect node-id :property-entries script-node-id :script-property-entries))) (defn- update-script-properties [evaluation-context script-node-id old-value new-value] (assert (or (nil? old-value) (vector? old-value))) (assert (or (nil? new-value) (vector? new-value))) (let [old-info-by-name (into {} xform-to-name-info-pairs old-value) new-info-by-name (into {} xform-to-name-info-pairs new-value) old-info-by-removed-name (into {} (remove (comp (partial contains? new-info-by-name) key)) old-info-by-name) new-info-by-added-name (into {} (remove (comp (partial contains? old-info-by-name) key)) new-info-by-name) renamed-name-by-old-name (detect-renames old-info-by-removed-name new-info-by-added-name) removed-names (into #{} (remove renamed-name-by-old-name) (keys old-info-by-removed-name)) added-info-by-name (apply dissoc new-info-by-added-name (vals renamed-name-by-old-name)) edited-info-by-name (detect-edits old-info-by-name new-info-by-name) node-ids-by-name (g/node-value script-node-id :script-property-node-ids-by-name evaluation-context)] (concat ;; Renamed properties. (for [[old-name new-name] renamed-name-by-old-name :let [node-id (node-ids-by-name old-name)]] (g/set-property node-id :name new-name)) ;; Added properties. (for [[name {:keys [resource-kind type value]}] added-info-by-name] (if-some [node-id (node-ids-by-name name)] (concat (g/set-property node-id :deleted? false) (edit-script-property node-id type resource-kind value)) (create-script-property script-node-id name type resource-kind value))) ;; Edited properties (i.e. the default value or property type changed). (for [[name {:keys [resource-kind type value]}] edited-info-by-name :let [node-id (node-ids-by-name name)]] (edit-script-property node-id type resource-kind value)) ;; Removed properties. (for [name removed-names :let [node-id (node-ids-by-name name)]] (g/set-property node-id :deleted? true))))) (defn- lift-error [node-id [prop-kw {:keys [error] :as prop} :as property-entry]] (if (nil? error) property-entry (let [lifted-error (g/error-aggregate [error] :_node-id node-id :_label prop-kw :message (:message error) :value (:value error))] [prop-kw (assoc prop :error lifted-error)]))) (g/defnk produce-properties [_declared-properties _node-id script-properties script-property-entries] (cond (g/error? _declared-properties) _declared-properties (g/error? script-property-entries) script-property-entries :else (-> _declared-properties (update :properties into (map (partial lift-error _node-id)) script-property-entries) (update :display-order into (map prop->key) script-properties)))) (defn- go-property-declaration-cursor-ranges "Find the CursorRanges that encompass each `go.property('name', ...)` declaration among the specified lines. These will be replaced with whitespace before the script is compiled for the engine." [lines] (loop [cursor-ranges (transient []) tokens (lua-parser/tokens (data/lines-reader lines)) paren-count 0 consumed []] (if-some [[text :as token] (first tokens)] (case (count consumed) 0 (recur cursor-ranges (next tokens) 0 (case text "go" (conj consumed token) [])) 1 (recur cursor-ranges (next tokens) 0 (case text "." (conj consumed token) [])) 2 (recur cursor-ranges (next tokens) 0 (case text "property" (conj consumed token) [])) 3 (case text "(" (recur cursor-ranges (next tokens) (inc paren-count) consumed) ")" (let [paren-count (dec paren-count)] (assert (not (neg? paren-count))) (if (pos? paren-count) (recur cursor-ranges (next tokens) paren-count consumed) (let [next-tokens (next tokens) [next-text :as next-token] (first next-tokens) [_ start-row start-col] (first consumed) [end-text end-row end-col] (if (= ";" next-text) next-token token) end-col (+ ^long end-col (count end-text)) start-cursor (data/->Cursor start-row start-col) end-cursor (data/->Cursor end-row end-col) cursor-range (data/->CursorRange start-cursor end-cursor)] (recur (conj! cursor-ranges cursor-range) next-tokens 0 [])))) (recur cursor-ranges (next tokens) paren-count consumed))) (persistent! cursor-ranges)))) (defn- line->whitespace [line] (string/join (repeat (count line) \space))) (defn- cursor-range->whitespace-lines [lines cursor-range] (let [{:keys [first-line middle-lines last-line]} (data/cursor-range-subsequence lines cursor-range)] (cond-> (into [(line->whitespace first-line)] (map line->whitespace) middle-lines) (some? last-line) (conj (line->whitespace last-line))))) (defn- strip-go-property-declarations [lines] (data/splice-lines lines (map (juxt identity (partial cursor-range->whitespace-lines lines)) (go-property-declaration-cursor-ranges lines)))) (defn- script->bytecode [lines proj-path arch] (try (luajit/bytecode (data/lines-reader lines) proj-path arch) (catch Exception e (let [{:keys [filename line message]} (ex-data e) cursor-range (some-> line data/line-number->CursorRange)] (g/map->error {:_label :modified-lines :message (.getMessage e) :severity :fatal :user-data (cond-> {:filename filename :message message} (some? cursor-range) (assoc :cursor-range cursor-range))}))))) (defn- build-script [resource dep-resources user-data] ;; We always compile the full source code in order to find syntax errors. ;; We then strip go.property() declarations and recompile if needed. (let [lines (:lines user-data) proj-path (:proj-path user-data) bytecode-or-error (script->bytecode lines proj-path :32-bit)] (g/precluding-errors [bytecode-or-error] (let [go-props (properties/build-go-props dep-resources (:go-props user-data)) modules (:modules user-data) cleaned-lines (strip-go-property-declarations lines) bytecode (if (identical? lines cleaned-lines) bytecode-or-error (script->bytecode cleaned-lines proj-path :32-bit)) bytecode-64 (script->bytecode cleaned-lines proj-path :64-bit)] (assert (not (g/error? bytecode))) (assert (not (g/error? bytecode-64))) {:resource resource :content (protobuf/map->bytes Lua$LuaModule {:source {:script (ByteString/copyFromUtf8 (slurp (data/lines-reader cleaned-lines))) :filename (resource/proj-path (:resource resource)) :bytecode (ByteString/copyFrom ^bytes bytecode) :bytecode-64 (ByteString/copyFrom ^bytes bytecode-64)} :modules modules :resources (mapv lua/lua-module->build-path modules) :properties (properties/go-props->decls go-props true) :property-resources (into (sorted-set) (keep properties/try-get-go-prop-proj-path) go-props)})})))) (g/defnk produce-build-targets [_node-id resource lines script-properties modules module-build-targets original-resource-property-build-targets] (if-some [errors (not-empty (keep (fn [{:keys [name resource-kind type value]}] (let [prop-type (script-property-type->property-type type) edit-type (script-property-edit-type prop-type resource-kind)] (validate-value-against-edit-type _node-id :lines name value edit-type))) script-properties))] (g/error-aggregate errors :_node-id _node-id :_label :build-targets) (let [go-props-with-source-resources (map (fn [{:keys [name type value]}] (let [go-prop-type (script-property-type->go-prop-type type) go-prop-value (properties/clj-value->go-prop-value go-prop-type value)] {:id name :type go-prop-type :value go-prop-value :clj-value value})) script-properties) [go-props go-prop-dep-build-targets] (properties/build-target-go-props original-resource-property-build-targets go-props-with-source-resources)] ;; NOTE: The :user-data must not contain any overridden data. If it does, ;; the build targets won't be fused and the script will be recompiled ;; for every instance of the script component. The :go-props here describe ;; the original property values from the script, never overridden values. [(bt/with-content-hash {:node-id _node-id :resource (workspace/make-build-resource resource) :build-fn build-script :user-data {:lines lines :go-props go-props :modules modules :proj-path (resource/proj-path resource)} :deps (into go-prop-dep-build-targets module-build-targets)})]))) (g/defnk produce-completions [completion-info module-completion-infos script-intelligence-completions] (code-completion/combine-completions completion-info module-completion-infos script-intelligence-completions)) (g/defnk produce-breakpoints [resource regions] (into [] (comp (filter data/breakpoint-region?) (map (fn [region] {:resource resource :row (data/breakpoint-row region)}))) regions)) (g/defnode ScriptNode (inherits r/CodeEditorResourceNode) (input module-build-targets g/Any :array) (input module-completion-infos g/Any :array :substitute gu/array-subst-remove-errors) (input script-intelligence-completions si/ScriptCompletions) (input script-property-name+node-ids NameNodeIDPair :array) (input script-property-entries ScriptPropertyEntries :array) (input resource-property-resources resource/Resource :array) (input resource-property-build-targets g/Any :array :substitute gu/array-subst-remove-errors) (input original-resource-property-build-targets g/Any :array :substitute gu/array-subst-remove-errors) (property completion-info g/Any (default {}) (dynamic visible (g/constantly false))) ;; Overrides modified-lines property in CodeEditorResourceNode. (property modified-lines r/Lines (dynamic visible (g/constantly false)) (set (fn [evaluation-context self _old-value new-value] (let [resource (g/node-value self :resource evaluation-context) lua-info (lua-parser/lua-info (resource/workspace resource) valid-resource-kind? (data/lines-reader new-value)) own-module (lua/path->lua-module (resource/proj-path resource)) completion-info (assoc lua-info :module own-module) modules (into [] (comp (map second) (remove lua/preinstalled-modules)) (:requires lua-info)) script-properties (into [] (comp (filter #(= :ok (:status %))) (util/distinct-by :name)) (:script-properties completion-info))] (concat (g/set-property self :completion-info completion-info) (g/set-property self :modules modules) (g/set-property self :script-properties script-properties)))))) (property modules Modules (default []) (dynamic visible (g/constantly false)) (set (fn [evaluation-context self _old-value new-value] (let [basis (:basis evaluation-context) project (project/get-project basis self)] (concat (g/disconnect-sources basis self :module-build-targets) (g/disconnect-sources basis self :module-completion-infos) (for [module new-value] (let [path (lua/lua-module->path module)] (:tx-data (project/connect-resource-node evaluation-context project path self [[:build-targets :module-build-targets] [:completion-info :module-completion-infos]]))))))))) (property script-properties g/Any (default []) (dynamic visible (g/constantly false)) (set (fn [evaluation-context self old-value new-value] (let [basis (:basis evaluation-context) project (project/get-project self)] (concat (update-script-properties evaluation-context self old-value new-value) (g/disconnect-sources basis self :original-resource-property-build-targets) (for [{:keys [type value]} new-value :when (and (= :script-property-type-resource type) (some? value))] (:tx-data (project/connect-resource-node evaluation-context project value self [[:build-targets :original-resource-property-build-targets]])))))))) ;; Breakpoints output only consumed by project (array input of all code files) ;; and already cached there. Changing breakpoints and pulling project breakpoints ;; does imply a pass over all ScriptNodes to produce new breakpoints, but does ;; not seem to be much of a perf issue. (output breakpoints project/Breakpoints produce-breakpoints) (output _properties g/Properties :cached produce-properties) (output build-targets g/Any :cached produce-build-targets) (output completions g/Any :cached produce-completions) (output resource-property-build-targets g/Any (gu/passthrough resource-property-build-targets)) (output script-property-entries ScriptPropertyEntries (g/fnk [script-property-entries] (reduce into {} script-property-entries))) (output script-property-node-ids-by-name NameNodeIDMap (g/fnk [script-property-name+node-ids] (into {} script-property-name+node-ids)))) (defn- additional-load-fn [project self resource] (let [script-intelligence (project/script-intelligence project)] (g/connect script-intelligence :lua-completions self :script-intelligence-completions))) (defn register-resource-types [workspace] (for [def script-defs :let [args (assoc def :node-type ScriptNode :eager-loading? true :additional-load-fn additional-load-fn)]] (apply r/register-code-resource-type workspace (mapcat identity args))))
[ { "context": "ary for handling HGVS\"\n :url \"https://github.com/chrovis/clj-hgvs\"\n :license {:name \"Apache License, Vers", "end": 122, "score": 0.9994365572929382, "start": 115, "tag": "USERNAME", "value": "chrovis" }, { "context": " \"docs\"\n :source-uri \"https://github.com/chrovis/clj-hgvs/blob/{version}/{filepath}#L{line}\"}\n :d", "end": 1668, "score": 0.9981870651245117, "start": 1661, "tag": "USERNAME", "value": "chrovis" }, { "context": "e}\"}\n :doo {:build \"test\"}\n :signing {:gpg-key \"developer@xcoo.jp\"})\n", "end": 1776, "score": 0.999916136264801, "start": 1759, "tag": "EMAIL", "value": "developer@xcoo.jp" } ]
project.clj
chrovis/clj-hgvs
5
(defproject clj-hgvs "0.4.5" :description "Clojure(Script) library for handling HGVS" :url "https://github.com/chrovis/clj-hgvs" :license {:name "Apache License, Version 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0"} :dependencies [[org.clojure/clojure "1.9.0" :scope "provided"] [org.clojure/clojurescript "1.10.520" :scope "provided"]] :plugins [[lein-cljsbuild "1.1.7"] [lein-cloverage "1.1.2"] [lein-codox "0.10.7"] [lein-doo "0.1.11"]] :profiles {:dev {:dependencies [[org.clojure/test.check "0.10.0"] [codox-theme-rdash "0.1.2"]]} :1.8 {:dependencies [[org.clojure/clojure "1.8.0"] [clojure-future-spec "1.9.0"]]} :1.9 {:dependencies [[org.clojure/clojure "1.9.0"]]} :1.10 {:dependencies [[org.clojure/clojure "1.10.3"]]}} :deploy-repositories [["snapshots" {:url "https://clojars.org/repo/" :username [:env/clojars_username :gpg] :password [:env/clojars_password :gpg]}]] :cljsbuild {:builds {:test {:source-paths ["src" "test"] :compiler {:output-to "target/testable.js" :output-dir "target" :main clj-hgvs.runner :optimizations :none}}}} :codox {:project {:name "clj-hgvs"} :themes [:rdash] :namespaces [#"^clj-hgvs\.(?!internal)"] :output-path "docs" :source-uri "https://github.com/chrovis/clj-hgvs/blob/{version}/{filepath}#L{line}"} :doo {:build "test"} :signing {:gpg-key "developer@xcoo.jp"})
103649
(defproject clj-hgvs "0.4.5" :description "Clojure(Script) library for handling HGVS" :url "https://github.com/chrovis/clj-hgvs" :license {:name "Apache License, Version 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0"} :dependencies [[org.clojure/clojure "1.9.0" :scope "provided"] [org.clojure/clojurescript "1.10.520" :scope "provided"]] :plugins [[lein-cljsbuild "1.1.7"] [lein-cloverage "1.1.2"] [lein-codox "0.10.7"] [lein-doo "0.1.11"]] :profiles {:dev {:dependencies [[org.clojure/test.check "0.10.0"] [codox-theme-rdash "0.1.2"]]} :1.8 {:dependencies [[org.clojure/clojure "1.8.0"] [clojure-future-spec "1.9.0"]]} :1.9 {:dependencies [[org.clojure/clojure "1.9.0"]]} :1.10 {:dependencies [[org.clojure/clojure "1.10.3"]]}} :deploy-repositories [["snapshots" {:url "https://clojars.org/repo/" :username [:env/clojars_username :gpg] :password [:env/clojars_password :gpg]}]] :cljsbuild {:builds {:test {:source-paths ["src" "test"] :compiler {:output-to "target/testable.js" :output-dir "target" :main clj-hgvs.runner :optimizations :none}}}} :codox {:project {:name "clj-hgvs"} :themes [:rdash] :namespaces [#"^clj-hgvs\.(?!internal)"] :output-path "docs" :source-uri "https://github.com/chrovis/clj-hgvs/blob/{version}/{filepath}#L{line}"} :doo {:build "test"} :signing {:gpg-key "<EMAIL>"})
true
(defproject clj-hgvs "0.4.5" :description "Clojure(Script) library for handling HGVS" :url "https://github.com/chrovis/clj-hgvs" :license {:name "Apache License, Version 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0"} :dependencies [[org.clojure/clojure "1.9.0" :scope "provided"] [org.clojure/clojurescript "1.10.520" :scope "provided"]] :plugins [[lein-cljsbuild "1.1.7"] [lein-cloverage "1.1.2"] [lein-codox "0.10.7"] [lein-doo "0.1.11"]] :profiles {:dev {:dependencies [[org.clojure/test.check "0.10.0"] [codox-theme-rdash "0.1.2"]]} :1.8 {:dependencies [[org.clojure/clojure "1.8.0"] [clojure-future-spec "1.9.0"]]} :1.9 {:dependencies [[org.clojure/clojure "1.9.0"]]} :1.10 {:dependencies [[org.clojure/clojure "1.10.3"]]}} :deploy-repositories [["snapshots" {:url "https://clojars.org/repo/" :username [:env/clojars_username :gpg] :password [:env/clojars_password :gpg]}]] :cljsbuild {:builds {:test {:source-paths ["src" "test"] :compiler {:output-to "target/testable.js" :output-dir "target" :main clj-hgvs.runner :optimizations :none}}}} :codox {:project {:name "clj-hgvs"} :themes [:rdash] :namespaces [#"^clj-hgvs\.(?!internal)"] :output-path "docs" :source-uri "https://github.com/chrovis/clj-hgvs/blob/{version}/{filepath}#L{line}"} :doo {:build "test"} :signing {:gpg-key "PI:EMAIL:<EMAIL>END_PI"})
[ { "context": ";;\n;;\n;; Copyright 2013-2015 Netflix, Inc.\n;;\n;; Licensed under the Apache Lic", "end": 33, "score": 0.9654280543327332, "start": 30, "tag": "NAME", "value": "Net" } ]
pigpen-rx/src/main/clojure/pigpen/rx.clj
ombagus/Netflix
327
;; ;; ;; Copyright 2013-2015 Netflix, Inc. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns pigpen.rx "A high performance dump operator. The default implementation in pigpen.core uses lazy seqs, which can be inefficient on larger data. The rx implementation uses rx-java to deliver a slightly more performance for large local datasets. " (:require [pigpen.rx.core :as rx] [pigpen.rx.extensions :refer [multicast->observable]] [rx.lang.clojure.blocking :as rx-blocking] [pigpen.local :as local] [pigpen.oven :as oven])) (defn dump "Executes a script locally and returns the resulting values as a clojure sequence. This command is very useful for unit tests. Example: (->> (pig/load-clj \"input.clj\") (pig/map inc) (pig/filter even?) (pig-rx/dump) (clojure.core/map #(* % %)) (clojure.core/filter even?)) (deftest test-script (is (= (->> (pig/load-clj \"input.clj\") (pig/map inc) (pig/filter even?) (pig-rx/dump)) [2 4 6]))) Note: pig/store commands return the output data pig/store-many commands merge their results " {:added "0.1.0"} [query] (let [state {:code-cache (atom {})} graph (oven/bake :rx {} {} query) last-command (:id (last graph))] (->> graph (reduce (partial rx/graph->observable+ state) {}) (last-command) (multicast->observable) (rx-blocking/into []) (map (comp local/remove-sentinel-nil val first)))))
11315
;; ;; ;; Copyright 2013-2015 <NAME>flix, Inc. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns pigpen.rx "A high performance dump operator. The default implementation in pigpen.core uses lazy seqs, which can be inefficient on larger data. The rx implementation uses rx-java to deliver a slightly more performance for large local datasets. " (:require [pigpen.rx.core :as rx] [pigpen.rx.extensions :refer [multicast->observable]] [rx.lang.clojure.blocking :as rx-blocking] [pigpen.local :as local] [pigpen.oven :as oven])) (defn dump "Executes a script locally and returns the resulting values as a clojure sequence. This command is very useful for unit tests. Example: (->> (pig/load-clj \"input.clj\") (pig/map inc) (pig/filter even?) (pig-rx/dump) (clojure.core/map #(* % %)) (clojure.core/filter even?)) (deftest test-script (is (= (->> (pig/load-clj \"input.clj\") (pig/map inc) (pig/filter even?) (pig-rx/dump)) [2 4 6]))) Note: pig/store commands return the output data pig/store-many commands merge their results " {:added "0.1.0"} [query] (let [state {:code-cache (atom {})} graph (oven/bake :rx {} {} query) last-command (:id (last graph))] (->> graph (reduce (partial rx/graph->observable+ state) {}) (last-command) (multicast->observable) (rx-blocking/into []) (map (comp local/remove-sentinel-nil val first)))))
true
;; ;; ;; Copyright 2013-2015 PI:NAME:<NAME>END_PIflix, Inc. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns pigpen.rx "A high performance dump operator. The default implementation in pigpen.core uses lazy seqs, which can be inefficient on larger data. The rx implementation uses rx-java to deliver a slightly more performance for large local datasets. " (:require [pigpen.rx.core :as rx] [pigpen.rx.extensions :refer [multicast->observable]] [rx.lang.clojure.blocking :as rx-blocking] [pigpen.local :as local] [pigpen.oven :as oven])) (defn dump "Executes a script locally and returns the resulting values as a clojure sequence. This command is very useful for unit tests. Example: (->> (pig/load-clj \"input.clj\") (pig/map inc) (pig/filter even?) (pig-rx/dump) (clojure.core/map #(* % %)) (clojure.core/filter even?)) (deftest test-script (is (= (->> (pig/load-clj \"input.clj\") (pig/map inc) (pig/filter even?) (pig-rx/dump)) [2 4 6]))) Note: pig/store commands return the output data pig/store-many commands merge their results " {:added "0.1.0"} [query] (let [state {:code-cache (atom {})} graph (oven/bake :rx {} {} query) last-command (:id (last graph))] (->> graph (reduce (partial rx/graph->observable+ state) {}) (last-command) (multicast->observable) (rx-blocking/into []) (map (comp local/remove-sentinel-nil val first)))))
[ { "context": "hub-button []\n [:a\n {:href \"https://github.com/ergenekonyigit/trendcat\"\n :target \"_blank\"}\n [:svg\n {:wi", "end": 4533, "score": 0.9994605183601379, "start": 4519, "tag": "USERNAME", "value": "ergenekonyigit" }, { "context": "5.84\n1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015\n2.896-.015 3.286 0 ", "end": 5350, "score": 0.9744735956192017, "start": 5340, "tag": "IP_ADDRESS", "value": "5.92.42.36" } ]
src/trendcat/components/home.cljs
ergenekonyigit/trendcat
79
(ns trendcat.components.home (:require [reagent.core :as r] [trendcat.db :refer [app-state set-item! get-item moon-toggle]] [trendcat.components.github-list :refer [github-list]] [trendcat.components.hnews-list :refer [hnews-list]] [trendcat.actions :refer [get-github-trends get-hnews-stories]])) (defn language-select [] [:div.select [:select {:style {:width "200px" :color (if (:dark-mode @app-state) "#878a8c" "#363636") :background-color (if (:dark-mode @app-state) "#1a1a1a" "#ffffff") :border-color (if (:dark-mode @app-state) "#363636" "#cccccc")} :default-value (:lang @app-state) :on-change #(do (swap! app-state assoc :lang (-> % .-target .-value)) (set-item! "current-lang" (:lang @app-state)) (get-github-trends {:force? true :since (:since @app-state) :lang (:lang @app-state)}))} [:option {:value ""} "All Languages"] [:option {:value "rand"} "Random"] [:optgroup {:label "Popular"} (for [fav-language (:fav-languages @app-state)] ^{:key (:name fav-language)} [:option {:value (:urlParam fav-language)} (:name fav-language)])] [:optgroup {:label "Everything else"} (for [language (:languages @app-state)] ^{:key (:name language)} [:option {:value (:urlParam language)} (:name language)])]]]) (defn github-since-select [since-name] (let [dropdown-items {"daily" "Today" "weekly" "This Week" "monthly" "This Month"}] [:div.dropdown.is-hoverable {:style {:margin "0 5px"}} [:div.dropdown-trigger [:button.button {:aria-haspopup "true" :aria-controls "dropdown-menu" :style {:width "110px" :color (if (:dark-mode @app-state) "#878a8c" "#363636") :background-color (if (:dark-mode @app-state) "#1a1a1a" "#ffffff") :border-color (if (:dark-mode @app-state) "#363636" "#cccccc")}} [:span since-name]]] [:div#dropdown-menu {:class "dropdown-menu" :role "menu"} [:div.dropdown-content {:style {:background-color (if (:dark-mode @app-state) "#1a1a1a" "#ffffff")}} (doall (for [item dropdown-items] ^{:key (str (random-uuid))} [:a.dropdown-item {:style {:color (if (:dark-mode @app-state) "#d7dadc" "#363636")} :on-click #(do (swap! app-state assoc :since (first item)) (set-item! "current-since" (:since @app-state)) (get-github-trends {:force? true :since (:since @app-state) :lang (:lang @app-state)}))} (second item)]))]]])) (defn hnews-select [story-name] (let [dropdown-items {"topstories" "Top" "newstories" "New" "showstories" "Show"}] [:div.dropdown.is-hoverable {:style {:margin "0 5px"}} [:div.dropdown-trigger [:button.button {:aria-haspopup "true" :aria-controls "dropdown-menu" :style {:width "110px" :color (if (:dark-mode @app-state) "#878a8c" "#363636") :background-color (if (:dark-mode @app-state) "#1a1a1a" "#ffffff") :border-color (if (:dark-mode @app-state) "#363636" "#cccccc")}} [:span story-name]]] [:div#dropdown-menu {:class "dropdown-menu" :role "menu"} [:div.dropdown-content {:style {:background-color (if (:dark-mode @app-state) "#1a1a1a" "#ffffff")}} (doall (for [item dropdown-items] ^{:key (str (random-uuid))} [:a.dropdown-item {:style {:color (if (:dark-mode @app-state) "#d7dadc" "#363636")} :on-click #(do (swap! app-state assoc :stories (first item)) (set-item! "stories" (:stories @app-state)) (swap! app-state assoc :hnews-story-items []) (get-hnews-stories {:force? true :type (:stories @app-state)}))} (second item)]))]]])) (defn github-button [] [:a {:href "https://github.com/ergenekonyigit/trendcat" :target "_blank"} [:svg {:width "24px" :role "img" :view-box "0 0 24 24" :xmlns "http://www.w3.org/2000/svg"} [:path {:fill (if (:dark-mode @app-state) "#d7dadc" "#363636") :d "M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"}]]]) (defn settings-icon [] [:svg {:style {:cursor "pointer"} :width "24px" :height "24px" :role "img" :view-box "0 0 20 20" :xmlns "http://www.w3.org/2000/svg"} [:path {:fill (if (:dark-mode @app-state) "#d7dadc" "#363636") :d "M7.03093403,10 C7.03093403,8.36301971 8.36301971,7.03093403 10,7.03093403 C11.6369803,7.03093403 12.9679409,8.36301971 12.9679409,10 C12.9679409,11.6369803 11.6369803,12.969066 10,12.969066 C8.36301971,12.969066 7.03093403,11.6369803 7.03093403, 10 M16.4016617,8.49127796 C16.2362761,7.79148295 15.9606334,7.13669084 15.5916096,6.5437777 L16.5231696,5.06768276 C16.7526843,4.70315931 16.7684353,4.22387849 16.5231696,3.83572852 C16.1833977,3.29794393 15.4712269,3.13593351 14.9323172,3.47683044 L13.4562223,4.40839036 C12.8633092,4.03936662 12.208517,3.76259882 11.508722,3.59833825 L11.1250724,1.89947899 C11.0294412,1.47982699 10.7020452,1.12992949 10.2542664,1.02867298 C9.63322641,0.888038932 9.01556168,1.27843904 8.87492764,1.89947899 L8.49127796,3.59833825 C7.79148295,3.76259882 7.13669084,4.03936662 6.54265263,4.40726528 L5.06768276,3.47683044 C4.70315931,3.24731568 4.22387849,3.23156466 3.83572852,3.47683044 C3.29794393,3.81660229 3.13593351,4.5287731 3.47683044,5.06768276 L4.40726528,6.54265263 C4.03936662,7.13669084 3.76259882,7.79148295 3.59721318,8.49127796 L1.89947899,8.87492764 C1.47982699,8.97055879 1.12992949,9.29795485 1.02867298,9.74573365 C0.888038932,10.3667736 1.27843904,10.9844383 1.89947899,11.1250724 L3.59721318,11.508722 C3.76259882,12.208517 4.03936662,12.8633092 4.40726528,13.4573474 L3.47683044,14.9323172 C3.24731568,15.2968407 3.23156466,15.7761215 3.47683044,16.1642715 C3.81660229,16.7020561 4.5287731,16.8640665 5.06768276,16.5231696 L6.54265263,15.5927347 C7.13669084,15.9606334 7.79148295,16.2374012 8.49127796,16.4016617 L8.87492764,18.100521 C8.97055879,18.520173 9.29795485,18.8700705 9.74573365,18.971327 C10.3667736,19.1119611 10.9844383,18.721561 11.1250724,18.100521 L11.508722,16.4016617 C12.208517,16.2374012 12.8633092,15.9606334 13.4562223,15.5916096 L14.9323172,16.5231696 C15.2968407,16.7526843 15.7749964,16.7684353 16.1631464,16.5231696 C16.7020561,16.1833977 16.8629414,15.4712269 16.5231696,14.9323172 L15.5916096,13.4562223 C15.9606334,12.8633092 16.2362761,12.208517 16.4016617,11.508722 L18.100521,11.1250724 C18.520173,11.0294412 18.8700705,10.7020452 18.971327,10.2542664 C19.1119611,9.63322641 18.721561,9.01556168 18.100521,8.87492764 L16.4016617,8.49127796 Z"}]]) (defn splash-screen-setting [] [:<> [:div {:style {:color (if (:dark-mode @app-state) "#d7dadc" "#363636")}} "Splash Screen:"] [:label {:style {:display "flex" :align-items "center" :color (if (:dark-mode @app-state) "#878a8c" "#4a4a4a") :padding "10px 0px"}} [:input {:style {:margin-right "10px" :vertical-align "middle" :position "relative" :bottom "1px"} :type "checkbox" :default-checked (:splash-screen @app-state) :on-click #(set-item! "splash-screen" (-> % .-target .-checked))}] "Digital Clock"]]) (defn request-delay-setting [] [:<> [:div {:style {:color (if (:dark-mode @app-state) "#d7dadc" "#363636") :display "flex" :align-items "center" :padding "10px 0px"}} "Request Delay:"] [:div.select [:select {:style {:width "200px" :color (if (:dark-mode @app-state) "#878a8c" "#363636") :background-color (if (:dark-mode @app-state) "#1a1a1a" "#ffffff") :border-color (if (:dark-mode @app-state) "#363636" "#cccccc")} :default-value (:request-delay @app-state) :on-change #(do (swap! app-state assoc :request-delay (-> % .-target .-value)) (set-item! "request-delay" (:request-delay @app-state)))} (for [option (:delay-options @app-state)] ^{:key (:value option)} [:option {:value (:value option)} (:label option)])]]]) (defn settings-card [] (fn [] [:div.modal-content {:style {:padding "20px" :margin "0 0 60px 0" :border-radius "8px" :background-color (if (:dark-mode @app-state) "#1a1a1a" "#ffffff") :overflow "hidden" :border-width "1px" :border-style "solid" :border-color (if (:dark-mode @app-state) "#363636" "#cccccc")}} [:div {:style {:margin-bottom "10px" :padding-bottom "10px" :border-bottom (if (:dark-mode @app-state) "1px solid #4a4a4a" "1px solid #edeff1")}} [:span.title {:style {:color (if (:dark-mode @app-state) "#d7dadc" "#363636")}} "Settings"]] [splash-screen-setting] [request-delay-setting]])) (defn first-header [] (let [modal? (r/atom nil)] (fn [] [:div {:style {:display "flex" :flex-direction "row" :justify-content "space-between" :align-items "center"}} [:div.title.is-2 {:style {:color "#f34"}} "trendcat"] [:div {:style {:display "flex" :flex-direction "row" :margin-bottom "24px"}} [:div {:on-click #(reset! modal? true)} (when @modal? [:div.modal.is-active [:div.modal-background {:on-click #(do (-> % .stopPropagation) (reset! modal? false))}] [settings-card]]) [settings-icon]] [:span {:style {:margin-left "10px"}} [:div {:on-click #(do (swap! app-state assoc :dark-mode (not (:dark-mode @app-state))) (set-item! "dark-mode" (:dark-mode @app-state)))} [:img {:style {:cursor "pointer"} :width "24" :height "24" :role "presentation" :src moon-toggle}]]] [:span {:style {:margin-left "10px"}} [github-button]]]]))) (defn github-header [] (let [since-name (case (:since @app-state) "daily" "Today" "weekly" "This Week" "monthly" "This Month")] [:div {:style {:display "flex" :flex-direction "row" :justify-content "space-between" :flex-wrap "wrap"}} [:div {:style {:margin-bottom "10px"}} [:span.title {:style {:color (if (:dark-mode @app-state) "#d7dadc" "#363636")}} "GitHub"]] [:div {:style {:display "flex" :flex-direction "row" :justify-content "flex-end" :margin-bottom "10px"}} [language-select] [github-since-select since-name]]])) (defn hnews-header [] (let [story-name (case (:stories @app-state) "topstories" "Top" "newstories" "New" "showstories" "Show")] [:div {:style {:display "flex" :flex-direction "row" :justify-content "space-between" :flex-wrap "wrap"}} [:div {:style {:margin-bottom "10px"}} [:span.title {:style {:color (if (:dark-mode @app-state) "#d7dadc" "#363636")}} "Hacker News"]] [:div {:style {:margin-left "auto" :margin-bottom "10px"}} [hnews-select story-name]]])) (defn home [] (r/create-class {:component-did-mount #(do (get-github-trends {:force? (if-not (get-item "request-delay") true false) :lang (:lang @app-state) :since (:since @app-state)}) (get-hnews-stories {:force? (if-not (get-item "request-delay") true false) :type (:stories @app-state)})) :reagent-render (let [on-mouse-move (r/atom false)] (fn [] (let [timer (r/atom (js/Date.)) time-updater (js/setInterval #(reset! timer (js/Date.)) 1000) time-str (-> @timer .toTimeString (clojure.string/split " ") first)] [:div {:onMouseMove #(reset! on-mouse-move (boolean (-> % .-nativeEvent .-offsetX))) :style {:min-height "100vh" :background-color (if (:dark-mode @app-state) "#111" "#edeff1")}} (if (and (:splash-screen @app-state) (not @on-mouse-move)) [:div.hero.is-fullheight [:div.hero-body [:div.container [:div {:style {:height "100%" :display "flex" :align-items "center" :justify-content "center" :font-variant-numeric "tabular-nums" :font-size "10vw" :color (if (:dark-mode @app-state) "#d7dadc" "#363636")}} time-str]]]] [:div.container [:section.hero [:div.hero-body [first-header]]] [:div.columns.is-desktop {:style {:margin-left 0 :margin-right 0}} [:div.column [github-header] [github-list]] [:div.column [hnews-header] [hnews-list]]]])])))}))
13840
(ns trendcat.components.home (:require [reagent.core :as r] [trendcat.db :refer [app-state set-item! get-item moon-toggle]] [trendcat.components.github-list :refer [github-list]] [trendcat.components.hnews-list :refer [hnews-list]] [trendcat.actions :refer [get-github-trends get-hnews-stories]])) (defn language-select [] [:div.select [:select {:style {:width "200px" :color (if (:dark-mode @app-state) "#878a8c" "#363636") :background-color (if (:dark-mode @app-state) "#1a1a1a" "#ffffff") :border-color (if (:dark-mode @app-state) "#363636" "#cccccc")} :default-value (:lang @app-state) :on-change #(do (swap! app-state assoc :lang (-> % .-target .-value)) (set-item! "current-lang" (:lang @app-state)) (get-github-trends {:force? true :since (:since @app-state) :lang (:lang @app-state)}))} [:option {:value ""} "All Languages"] [:option {:value "rand"} "Random"] [:optgroup {:label "Popular"} (for [fav-language (:fav-languages @app-state)] ^{:key (:name fav-language)} [:option {:value (:urlParam fav-language)} (:name fav-language)])] [:optgroup {:label "Everything else"} (for [language (:languages @app-state)] ^{:key (:name language)} [:option {:value (:urlParam language)} (:name language)])]]]) (defn github-since-select [since-name] (let [dropdown-items {"daily" "Today" "weekly" "This Week" "monthly" "This Month"}] [:div.dropdown.is-hoverable {:style {:margin "0 5px"}} [:div.dropdown-trigger [:button.button {:aria-haspopup "true" :aria-controls "dropdown-menu" :style {:width "110px" :color (if (:dark-mode @app-state) "#878a8c" "#363636") :background-color (if (:dark-mode @app-state) "#1a1a1a" "#ffffff") :border-color (if (:dark-mode @app-state) "#363636" "#cccccc")}} [:span since-name]]] [:div#dropdown-menu {:class "dropdown-menu" :role "menu"} [:div.dropdown-content {:style {:background-color (if (:dark-mode @app-state) "#1a1a1a" "#ffffff")}} (doall (for [item dropdown-items] ^{:key (str (random-uuid))} [:a.dropdown-item {:style {:color (if (:dark-mode @app-state) "#d7dadc" "#363636")} :on-click #(do (swap! app-state assoc :since (first item)) (set-item! "current-since" (:since @app-state)) (get-github-trends {:force? true :since (:since @app-state) :lang (:lang @app-state)}))} (second item)]))]]])) (defn hnews-select [story-name] (let [dropdown-items {"topstories" "Top" "newstories" "New" "showstories" "Show"}] [:div.dropdown.is-hoverable {:style {:margin "0 5px"}} [:div.dropdown-trigger [:button.button {:aria-haspopup "true" :aria-controls "dropdown-menu" :style {:width "110px" :color (if (:dark-mode @app-state) "#878a8c" "#363636") :background-color (if (:dark-mode @app-state) "#1a1a1a" "#ffffff") :border-color (if (:dark-mode @app-state) "#363636" "#cccccc")}} [:span story-name]]] [:div#dropdown-menu {:class "dropdown-menu" :role "menu"} [:div.dropdown-content {:style {:background-color (if (:dark-mode @app-state) "#1a1a1a" "#ffffff")}} (doall (for [item dropdown-items] ^{:key (str (random-uuid))} [:a.dropdown-item {:style {:color (if (:dark-mode @app-state) "#d7dadc" "#363636")} :on-click #(do (swap! app-state assoc :stories (first item)) (set-item! "stories" (:stories @app-state)) (swap! app-state assoc :hnews-story-items []) (get-hnews-stories {:force? true :type (:stories @app-state)}))} (second item)]))]]])) (defn github-button [] [:a {:href "https://github.com/ergenekonyigit/trendcat" :target "_blank"} [:svg {:width "24px" :role "img" :view-box "0 0 24 24" :xmlns "http://www.w3.org/2000/svg"} [:path {:fill (if (:dark-mode @app-state) "#d7dadc" "#363636") :d "M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 192.168.3.11.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"}]]]) (defn settings-icon [] [:svg {:style {:cursor "pointer"} :width "24px" :height "24px" :role "img" :view-box "0 0 20 20" :xmlns "http://www.w3.org/2000/svg"} [:path {:fill (if (:dark-mode @app-state) "#d7dadc" "#363636") :d "M7.03093403,10 C7.03093403,8.36301971 8.36301971,7.03093403 10,7.03093403 C11.6369803,7.03093403 12.9679409,8.36301971 12.9679409,10 C12.9679409,11.6369803 11.6369803,12.969066 10,12.969066 C8.36301971,12.969066 7.03093403,11.6369803 7.03093403, 10 M16.4016617,8.49127796 C16.2362761,7.79148295 15.9606334,7.13669084 15.5916096,6.5437777 L16.5231696,5.06768276 C16.7526843,4.70315931 16.7684353,4.22387849 16.5231696,3.83572852 C16.1833977,3.29794393 15.4712269,3.13593351 14.9323172,3.47683044 L13.4562223,4.40839036 C12.8633092,4.03936662 12.208517,3.76259882 11.508722,3.59833825 L11.1250724,1.89947899 C11.0294412,1.47982699 10.7020452,1.12992949 10.2542664,1.02867298 C9.63322641,0.888038932 9.01556168,1.27843904 8.87492764,1.89947899 L8.49127796,3.59833825 C7.79148295,3.76259882 7.13669084,4.03936662 6.54265263,4.40726528 L5.06768276,3.47683044 C4.70315931,3.24731568 4.22387849,3.23156466 3.83572852,3.47683044 C3.29794393,3.81660229 3.13593351,4.5287731 3.47683044,5.06768276 L4.40726528,6.54265263 C4.03936662,7.13669084 3.76259882,7.79148295 3.59721318,8.49127796 L1.89947899,8.87492764 C1.47982699,8.97055879 1.12992949,9.29795485 1.02867298,9.74573365 C0.888038932,10.3667736 1.27843904,10.9844383 1.89947899,11.1250724 L3.59721318,11.508722 C3.76259882,12.208517 4.03936662,12.8633092 4.40726528,13.4573474 L3.47683044,14.9323172 C3.24731568,15.2968407 3.23156466,15.7761215 3.47683044,16.1642715 C3.81660229,16.7020561 4.5287731,16.8640665 5.06768276,16.5231696 L6.54265263,15.5927347 C7.13669084,15.9606334 7.79148295,16.2374012 8.49127796,16.4016617 L8.87492764,18.100521 C8.97055879,18.520173 9.29795485,18.8700705 9.74573365,18.971327 C10.3667736,19.1119611 10.9844383,18.721561 11.1250724,18.100521 L11.508722,16.4016617 C12.208517,16.2374012 12.8633092,15.9606334 13.4562223,15.5916096 L14.9323172,16.5231696 C15.2968407,16.7526843 15.7749964,16.7684353 16.1631464,16.5231696 C16.7020561,16.1833977 16.8629414,15.4712269 16.5231696,14.9323172 L15.5916096,13.4562223 C15.9606334,12.8633092 16.2362761,12.208517 16.4016617,11.508722 L18.100521,11.1250724 C18.520173,11.0294412 18.8700705,10.7020452 18.971327,10.2542664 C19.1119611,9.63322641 18.721561,9.01556168 18.100521,8.87492764 L16.4016617,8.49127796 Z"}]]) (defn splash-screen-setting [] [:<> [:div {:style {:color (if (:dark-mode @app-state) "#d7dadc" "#363636")}} "Splash Screen:"] [:label {:style {:display "flex" :align-items "center" :color (if (:dark-mode @app-state) "#878a8c" "#4a4a4a") :padding "10px 0px"}} [:input {:style {:margin-right "10px" :vertical-align "middle" :position "relative" :bottom "1px"} :type "checkbox" :default-checked (:splash-screen @app-state) :on-click #(set-item! "splash-screen" (-> % .-target .-checked))}] "Digital Clock"]]) (defn request-delay-setting [] [:<> [:div {:style {:color (if (:dark-mode @app-state) "#d7dadc" "#363636") :display "flex" :align-items "center" :padding "10px 0px"}} "Request Delay:"] [:div.select [:select {:style {:width "200px" :color (if (:dark-mode @app-state) "#878a8c" "#363636") :background-color (if (:dark-mode @app-state) "#1a1a1a" "#ffffff") :border-color (if (:dark-mode @app-state) "#363636" "#cccccc")} :default-value (:request-delay @app-state) :on-change #(do (swap! app-state assoc :request-delay (-> % .-target .-value)) (set-item! "request-delay" (:request-delay @app-state)))} (for [option (:delay-options @app-state)] ^{:key (:value option)} [:option {:value (:value option)} (:label option)])]]]) (defn settings-card [] (fn [] [:div.modal-content {:style {:padding "20px" :margin "0 0 60px 0" :border-radius "8px" :background-color (if (:dark-mode @app-state) "#1a1a1a" "#ffffff") :overflow "hidden" :border-width "1px" :border-style "solid" :border-color (if (:dark-mode @app-state) "#363636" "#cccccc")}} [:div {:style {:margin-bottom "10px" :padding-bottom "10px" :border-bottom (if (:dark-mode @app-state) "1px solid #4a4a4a" "1px solid #edeff1")}} [:span.title {:style {:color (if (:dark-mode @app-state) "#d7dadc" "#363636")}} "Settings"]] [splash-screen-setting] [request-delay-setting]])) (defn first-header [] (let [modal? (r/atom nil)] (fn [] [:div {:style {:display "flex" :flex-direction "row" :justify-content "space-between" :align-items "center"}} [:div.title.is-2 {:style {:color "#f34"}} "trendcat"] [:div {:style {:display "flex" :flex-direction "row" :margin-bottom "24px"}} [:div {:on-click #(reset! modal? true)} (when @modal? [:div.modal.is-active [:div.modal-background {:on-click #(do (-> % .stopPropagation) (reset! modal? false))}] [settings-card]]) [settings-icon]] [:span {:style {:margin-left "10px"}} [:div {:on-click #(do (swap! app-state assoc :dark-mode (not (:dark-mode @app-state))) (set-item! "dark-mode" (:dark-mode @app-state)))} [:img {:style {:cursor "pointer"} :width "24" :height "24" :role "presentation" :src moon-toggle}]]] [:span {:style {:margin-left "10px"}} [github-button]]]]))) (defn github-header [] (let [since-name (case (:since @app-state) "daily" "Today" "weekly" "This Week" "monthly" "This Month")] [:div {:style {:display "flex" :flex-direction "row" :justify-content "space-between" :flex-wrap "wrap"}} [:div {:style {:margin-bottom "10px"}} [:span.title {:style {:color (if (:dark-mode @app-state) "#d7dadc" "#363636")}} "GitHub"]] [:div {:style {:display "flex" :flex-direction "row" :justify-content "flex-end" :margin-bottom "10px"}} [language-select] [github-since-select since-name]]])) (defn hnews-header [] (let [story-name (case (:stories @app-state) "topstories" "Top" "newstories" "New" "showstories" "Show")] [:div {:style {:display "flex" :flex-direction "row" :justify-content "space-between" :flex-wrap "wrap"}} [:div {:style {:margin-bottom "10px"}} [:span.title {:style {:color (if (:dark-mode @app-state) "#d7dadc" "#363636")}} "Hacker News"]] [:div {:style {:margin-left "auto" :margin-bottom "10px"}} [hnews-select story-name]]])) (defn home [] (r/create-class {:component-did-mount #(do (get-github-trends {:force? (if-not (get-item "request-delay") true false) :lang (:lang @app-state) :since (:since @app-state)}) (get-hnews-stories {:force? (if-not (get-item "request-delay") true false) :type (:stories @app-state)})) :reagent-render (let [on-mouse-move (r/atom false)] (fn [] (let [timer (r/atom (js/Date.)) time-updater (js/setInterval #(reset! timer (js/Date.)) 1000) time-str (-> @timer .toTimeString (clojure.string/split " ") first)] [:div {:onMouseMove #(reset! on-mouse-move (boolean (-> % .-nativeEvent .-offsetX))) :style {:min-height "100vh" :background-color (if (:dark-mode @app-state) "#111" "#edeff1")}} (if (and (:splash-screen @app-state) (not @on-mouse-move)) [:div.hero.is-fullheight [:div.hero-body [:div.container [:div {:style {:height "100%" :display "flex" :align-items "center" :justify-content "center" :font-variant-numeric "tabular-nums" :font-size "10vw" :color (if (:dark-mode @app-state) "#d7dadc" "#363636")}} time-str]]]] [:div.container [:section.hero [:div.hero-body [first-header]]] [:div.columns.is-desktop {:style {:margin-left 0 :margin-right 0}} [:div.column [github-header] [github-list]] [:div.column [hnews-header] [hnews-list]]]])])))}))
true
(ns trendcat.components.home (:require [reagent.core :as r] [trendcat.db :refer [app-state set-item! get-item moon-toggle]] [trendcat.components.github-list :refer [github-list]] [trendcat.components.hnews-list :refer [hnews-list]] [trendcat.actions :refer [get-github-trends get-hnews-stories]])) (defn language-select [] [:div.select [:select {:style {:width "200px" :color (if (:dark-mode @app-state) "#878a8c" "#363636") :background-color (if (:dark-mode @app-state) "#1a1a1a" "#ffffff") :border-color (if (:dark-mode @app-state) "#363636" "#cccccc")} :default-value (:lang @app-state) :on-change #(do (swap! app-state assoc :lang (-> % .-target .-value)) (set-item! "current-lang" (:lang @app-state)) (get-github-trends {:force? true :since (:since @app-state) :lang (:lang @app-state)}))} [:option {:value ""} "All Languages"] [:option {:value "rand"} "Random"] [:optgroup {:label "Popular"} (for [fav-language (:fav-languages @app-state)] ^{:key (:name fav-language)} [:option {:value (:urlParam fav-language)} (:name fav-language)])] [:optgroup {:label "Everything else"} (for [language (:languages @app-state)] ^{:key (:name language)} [:option {:value (:urlParam language)} (:name language)])]]]) (defn github-since-select [since-name] (let [dropdown-items {"daily" "Today" "weekly" "This Week" "monthly" "This Month"}] [:div.dropdown.is-hoverable {:style {:margin "0 5px"}} [:div.dropdown-trigger [:button.button {:aria-haspopup "true" :aria-controls "dropdown-menu" :style {:width "110px" :color (if (:dark-mode @app-state) "#878a8c" "#363636") :background-color (if (:dark-mode @app-state) "#1a1a1a" "#ffffff") :border-color (if (:dark-mode @app-state) "#363636" "#cccccc")}} [:span since-name]]] [:div#dropdown-menu {:class "dropdown-menu" :role "menu"} [:div.dropdown-content {:style {:background-color (if (:dark-mode @app-state) "#1a1a1a" "#ffffff")}} (doall (for [item dropdown-items] ^{:key (str (random-uuid))} [:a.dropdown-item {:style {:color (if (:dark-mode @app-state) "#d7dadc" "#363636")} :on-click #(do (swap! app-state assoc :since (first item)) (set-item! "current-since" (:since @app-state)) (get-github-trends {:force? true :since (:since @app-state) :lang (:lang @app-state)}))} (second item)]))]]])) (defn hnews-select [story-name] (let [dropdown-items {"topstories" "Top" "newstories" "New" "showstories" "Show"}] [:div.dropdown.is-hoverable {:style {:margin "0 5px"}} [:div.dropdown-trigger [:button.button {:aria-haspopup "true" :aria-controls "dropdown-menu" :style {:width "110px" :color (if (:dark-mode @app-state) "#878a8c" "#363636") :background-color (if (:dark-mode @app-state) "#1a1a1a" "#ffffff") :border-color (if (:dark-mode @app-state) "#363636" "#cccccc")}} [:span story-name]]] [:div#dropdown-menu {:class "dropdown-menu" :role "menu"} [:div.dropdown-content {:style {:background-color (if (:dark-mode @app-state) "#1a1a1a" "#ffffff")}} (doall (for [item dropdown-items] ^{:key (str (random-uuid))} [:a.dropdown-item {:style {:color (if (:dark-mode @app-state) "#d7dadc" "#363636")} :on-click #(do (swap! app-state assoc :stories (first item)) (set-item! "stories" (:stories @app-state)) (swap! app-state assoc :hnews-story-items []) (get-hnews-stories {:force? true :type (:stories @app-state)}))} (second item)]))]]])) (defn github-button [] [:a {:href "https://github.com/ergenekonyigit/trendcat" :target "_blank"} [:svg {:width "24px" :role "img" :view-box "0 0 24 24" :xmlns "http://www.w3.org/2000/svg"} [:path {:fill (if (:dark-mode @app-state) "#d7dadc" "#363636") :d "M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 PI:IP_ADDRESS:192.168.3.11END_PI.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"}]]]) (defn settings-icon [] [:svg {:style {:cursor "pointer"} :width "24px" :height "24px" :role "img" :view-box "0 0 20 20" :xmlns "http://www.w3.org/2000/svg"} [:path {:fill (if (:dark-mode @app-state) "#d7dadc" "#363636") :d "M7.03093403,10 C7.03093403,8.36301971 8.36301971,7.03093403 10,7.03093403 C11.6369803,7.03093403 12.9679409,8.36301971 12.9679409,10 C12.9679409,11.6369803 11.6369803,12.969066 10,12.969066 C8.36301971,12.969066 7.03093403,11.6369803 7.03093403, 10 M16.4016617,8.49127796 C16.2362761,7.79148295 15.9606334,7.13669084 15.5916096,6.5437777 L16.5231696,5.06768276 C16.7526843,4.70315931 16.7684353,4.22387849 16.5231696,3.83572852 C16.1833977,3.29794393 15.4712269,3.13593351 14.9323172,3.47683044 L13.4562223,4.40839036 C12.8633092,4.03936662 12.208517,3.76259882 11.508722,3.59833825 L11.1250724,1.89947899 C11.0294412,1.47982699 10.7020452,1.12992949 10.2542664,1.02867298 C9.63322641,0.888038932 9.01556168,1.27843904 8.87492764,1.89947899 L8.49127796,3.59833825 C7.79148295,3.76259882 7.13669084,4.03936662 6.54265263,4.40726528 L5.06768276,3.47683044 C4.70315931,3.24731568 4.22387849,3.23156466 3.83572852,3.47683044 C3.29794393,3.81660229 3.13593351,4.5287731 3.47683044,5.06768276 L4.40726528,6.54265263 C4.03936662,7.13669084 3.76259882,7.79148295 3.59721318,8.49127796 L1.89947899,8.87492764 C1.47982699,8.97055879 1.12992949,9.29795485 1.02867298,9.74573365 C0.888038932,10.3667736 1.27843904,10.9844383 1.89947899,11.1250724 L3.59721318,11.508722 C3.76259882,12.208517 4.03936662,12.8633092 4.40726528,13.4573474 L3.47683044,14.9323172 C3.24731568,15.2968407 3.23156466,15.7761215 3.47683044,16.1642715 C3.81660229,16.7020561 4.5287731,16.8640665 5.06768276,16.5231696 L6.54265263,15.5927347 C7.13669084,15.9606334 7.79148295,16.2374012 8.49127796,16.4016617 L8.87492764,18.100521 C8.97055879,18.520173 9.29795485,18.8700705 9.74573365,18.971327 C10.3667736,19.1119611 10.9844383,18.721561 11.1250724,18.100521 L11.508722,16.4016617 C12.208517,16.2374012 12.8633092,15.9606334 13.4562223,15.5916096 L14.9323172,16.5231696 C15.2968407,16.7526843 15.7749964,16.7684353 16.1631464,16.5231696 C16.7020561,16.1833977 16.8629414,15.4712269 16.5231696,14.9323172 L15.5916096,13.4562223 C15.9606334,12.8633092 16.2362761,12.208517 16.4016617,11.508722 L18.100521,11.1250724 C18.520173,11.0294412 18.8700705,10.7020452 18.971327,10.2542664 C19.1119611,9.63322641 18.721561,9.01556168 18.100521,8.87492764 L16.4016617,8.49127796 Z"}]]) (defn splash-screen-setting [] [:<> [:div {:style {:color (if (:dark-mode @app-state) "#d7dadc" "#363636")}} "Splash Screen:"] [:label {:style {:display "flex" :align-items "center" :color (if (:dark-mode @app-state) "#878a8c" "#4a4a4a") :padding "10px 0px"}} [:input {:style {:margin-right "10px" :vertical-align "middle" :position "relative" :bottom "1px"} :type "checkbox" :default-checked (:splash-screen @app-state) :on-click #(set-item! "splash-screen" (-> % .-target .-checked))}] "Digital Clock"]]) (defn request-delay-setting [] [:<> [:div {:style {:color (if (:dark-mode @app-state) "#d7dadc" "#363636") :display "flex" :align-items "center" :padding "10px 0px"}} "Request Delay:"] [:div.select [:select {:style {:width "200px" :color (if (:dark-mode @app-state) "#878a8c" "#363636") :background-color (if (:dark-mode @app-state) "#1a1a1a" "#ffffff") :border-color (if (:dark-mode @app-state) "#363636" "#cccccc")} :default-value (:request-delay @app-state) :on-change #(do (swap! app-state assoc :request-delay (-> % .-target .-value)) (set-item! "request-delay" (:request-delay @app-state)))} (for [option (:delay-options @app-state)] ^{:key (:value option)} [:option {:value (:value option)} (:label option)])]]]) (defn settings-card [] (fn [] [:div.modal-content {:style {:padding "20px" :margin "0 0 60px 0" :border-radius "8px" :background-color (if (:dark-mode @app-state) "#1a1a1a" "#ffffff") :overflow "hidden" :border-width "1px" :border-style "solid" :border-color (if (:dark-mode @app-state) "#363636" "#cccccc")}} [:div {:style {:margin-bottom "10px" :padding-bottom "10px" :border-bottom (if (:dark-mode @app-state) "1px solid #4a4a4a" "1px solid #edeff1")}} [:span.title {:style {:color (if (:dark-mode @app-state) "#d7dadc" "#363636")}} "Settings"]] [splash-screen-setting] [request-delay-setting]])) (defn first-header [] (let [modal? (r/atom nil)] (fn [] [:div {:style {:display "flex" :flex-direction "row" :justify-content "space-between" :align-items "center"}} [:div.title.is-2 {:style {:color "#f34"}} "trendcat"] [:div {:style {:display "flex" :flex-direction "row" :margin-bottom "24px"}} [:div {:on-click #(reset! modal? true)} (when @modal? [:div.modal.is-active [:div.modal-background {:on-click #(do (-> % .stopPropagation) (reset! modal? false))}] [settings-card]]) [settings-icon]] [:span {:style {:margin-left "10px"}} [:div {:on-click #(do (swap! app-state assoc :dark-mode (not (:dark-mode @app-state))) (set-item! "dark-mode" (:dark-mode @app-state)))} [:img {:style {:cursor "pointer"} :width "24" :height "24" :role "presentation" :src moon-toggle}]]] [:span {:style {:margin-left "10px"}} [github-button]]]]))) (defn github-header [] (let [since-name (case (:since @app-state) "daily" "Today" "weekly" "This Week" "monthly" "This Month")] [:div {:style {:display "flex" :flex-direction "row" :justify-content "space-between" :flex-wrap "wrap"}} [:div {:style {:margin-bottom "10px"}} [:span.title {:style {:color (if (:dark-mode @app-state) "#d7dadc" "#363636")}} "GitHub"]] [:div {:style {:display "flex" :flex-direction "row" :justify-content "flex-end" :margin-bottom "10px"}} [language-select] [github-since-select since-name]]])) (defn hnews-header [] (let [story-name (case (:stories @app-state) "topstories" "Top" "newstories" "New" "showstories" "Show")] [:div {:style {:display "flex" :flex-direction "row" :justify-content "space-between" :flex-wrap "wrap"}} [:div {:style {:margin-bottom "10px"}} [:span.title {:style {:color (if (:dark-mode @app-state) "#d7dadc" "#363636")}} "Hacker News"]] [:div {:style {:margin-left "auto" :margin-bottom "10px"}} [hnews-select story-name]]])) (defn home [] (r/create-class {:component-did-mount #(do (get-github-trends {:force? (if-not (get-item "request-delay") true false) :lang (:lang @app-state) :since (:since @app-state)}) (get-hnews-stories {:force? (if-not (get-item "request-delay") true false) :type (:stories @app-state)})) :reagent-render (let [on-mouse-move (r/atom false)] (fn [] (let [timer (r/atom (js/Date.)) time-updater (js/setInterval #(reset! timer (js/Date.)) 1000) time-str (-> @timer .toTimeString (clojure.string/split " ") first)] [:div {:onMouseMove #(reset! on-mouse-move (boolean (-> % .-nativeEvent .-offsetX))) :style {:min-height "100vh" :background-color (if (:dark-mode @app-state) "#111" "#edeff1")}} (if (and (:splash-screen @app-state) (not @on-mouse-move)) [:div.hero.is-fullheight [:div.hero-body [:div.container [:div {:style {:height "100%" :display "flex" :align-items "center" :justify-content "center" :font-variant-numeric "tabular-nums" :font-size "10vw" :color (if (:dark-mode @app-state) "#d7dadc" "#363636")}} time-str]]]] [:div.container [:section.hero [:div.hero-body [first-header]]] [:div.columns.is-desktop {:style {:margin-left 0 :margin-right 0}} [:div.column [github-header] [github-list]] [:div.column [hnews-header] [hnews-list]]]])])))}))
[ { "context": "-url \"https://www.potterapi.com/v1/\")\n(def api-key \"$2a$10$/wSQHx3YG0.R8KaR1waNAe0teh1gawP6SOMunIFMcDDsF0y//MoxK\")\n\n(defn create-request-map\n []\n {\n :params ", "end": 176, "score": 0.9989833235740662, "start": 115, "tag": "KEY", "value": "\"$2a$10$/wSQHx3YG0.R8KaR1waNAe0teh1gawP6SOMunIFMcDDsF0y//MoxK" } ]
src/muggle/util.cljs
burkaydurdu/muggle
7
(ns muggle.util (:require [ajax.core :as ajax])) (def api-url "https://www.potterapi.com/v1/") (def api-key "$2a$10$/wSQHx3YG0.R8KaR1waNAe0teh1gawP6SOMunIFMcDDsF0y//MoxK") (defn create-request-map [] { :params {:key api-key} :format (ajax/json-request-format) :response-format :json :keywords? true}) (defn get-image [name] (cond (= name "Gryffindor") "/images/grif.png" (= name "Ravenclaw") "/images/rav.png" (= name "Slytherin") "/images/sly.png" (= name "Hufflepuff") "/images/huf.png"))
112073
(ns muggle.util (:require [ajax.core :as ajax])) (def api-url "https://www.potterapi.com/v1/") (def api-key <KEY>") (defn create-request-map [] { :params {:key api-key} :format (ajax/json-request-format) :response-format :json :keywords? true}) (defn get-image [name] (cond (= name "Gryffindor") "/images/grif.png" (= name "Ravenclaw") "/images/rav.png" (= name "Slytherin") "/images/sly.png" (= name "Hufflepuff") "/images/huf.png"))
true
(ns muggle.util (:require [ajax.core :as ajax])) (def api-url "https://www.potterapi.com/v1/") (def api-key PI:KEY:<KEY>END_PI") (defn create-request-map [] { :params {:key api-key} :format (ajax/json-request-format) :response-format :json :keywords? true}) (defn get-image [name] (cond (= name "Gryffindor") "/images/grif.png" (= name "Ravenclaw") "/images/rav.png" (= name "Slytherin") "/images/sly.png" (= name "Hufflepuff") "/images/huf.png"))
[ { "context": ";; Copyright 2018 Chris Rink\n;;\n;; Licensed under the Apache License, Version ", "end": 28, "score": 0.9998548626899719, "start": 18, "tag": "NAME", "value": "Chris Rink" } ]
src/clojure/repopreview/logging.clj
chrisrink10/repopreview
0
;; Copyright 2018 Chris Rink ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns repopreview.logging (:require [clojure.spec.alpha :as s] [mount.core :refer [defstate]] [taoensso.timbre :as timbre] [repopreview.config :as config])) (s/def ::level #{:debug :info :warn :error :fatal}) (defn level "Read the logging level configuration from the environment." [] (config/config [:logging :level])) (defstate timbre-config :start (timbre/set-level! (level)))
74922
;; Copyright 2018 <NAME> ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns repopreview.logging (:require [clojure.spec.alpha :as s] [mount.core :refer [defstate]] [taoensso.timbre :as timbre] [repopreview.config :as config])) (s/def ::level #{:debug :info :warn :error :fatal}) (defn level "Read the logging level configuration from the environment." [] (config/config [:logging :level])) (defstate timbre-config :start (timbre/set-level! (level)))
true
;; Copyright 2018 PI:NAME:<NAME>END_PI ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns repopreview.logging (:require [clojure.spec.alpha :as s] [mount.core :refer [defstate]] [taoensso.timbre :as timbre] [repopreview.config :as config])) (s/def ::level #{:debug :info :warn :error :fatal}) (defn level "Read the logging level configuration from the environment." [] (config/config [:logging :level])) (defstate timbre-config :start (timbre/set-level! (level)))
[ { "context": "my-coll\")\n inserted-a (inserter db {:name \"Sten\" :email \"email@sten.no\"})\n inserted-a (ins", "end": 1338, "score": 0.9861866235733032, "start": 1334, "tag": "NAME", "value": "Sten" }, { "context": " inserted-a (inserter db {:name \"Sten\" :email \"email@sten.no\"})\n inserted-a (inserter db {:name \"Arne\" ", "end": 1361, "score": 0.9998824000358582, "start": 1348, "tag": "EMAIL", "value": "email@sten.no" }, { "context": "ten.no\"})\n inserted-a (inserter db {:name \"Arne\" :email \"email@arne.no\"})\n finder (db/make", "end": 1409, "score": 0.9975255727767944, "start": 1405, "tag": "NAME", "value": "Arne" }, { "context": " inserted-a (inserter db {:name \"Arne\" :email \"email@arne.no\"})\n finder (db/make-find-all-with-output-f", "end": 1432, "score": 0.9998927116394043, "start": 1419, "tag": "EMAIL", "value": "email@arne.no" }, { "context": "ilter \"my-coll\")\n found (finder db {:name \"Sten\"} [\"email\"])]\n (is (= (count found) 1))\n (i", "end": 1536, "score": 0.783380389213562, "start": 1532, "tag": "NAME", "value": "Sten" }, { "context": "remove #(= (key %) :_id) (first found))) [:email \"email@sten.no\"]))))\n\n(deftest count-whole-collection-and-by-cri", "end": 1662, "score": 0.9999128580093384, "start": 1649, "tag": "EMAIL", "value": "email@sten.no" }, { "context": "my-coll\")\n inserted-a (inserter db {:name \"Sten\" :email \"email@sten.no\"})\n inserted-a (ins", "end": 1806, "score": 0.998847484588623, "start": 1802, "tag": "NAME", "value": "Sten" }, { "context": " inserted-a (inserter db {:name \"Sten\" :email \"email@sten.no\"})\n inserted-a (inserter db {:name \"Arne\" ", "end": 1829, "score": 0.999911904335022, "start": 1816, "tag": "EMAIL", "value": "email@sten.no" }, { "context": "ten.no\"})\n inserted-a (inserter db {:name \"Arne\" :email \"email@arne.no\"})\n counter (db/mak", "end": 1877, "score": 0.9994617104530334, "start": 1873, "tag": "NAME", "value": "Arne" }, { "context": " inserted-a (inserter db {:name \"Arne\" :email \"email@arne.no\"})\n counter (db/make-count \"my-coll\")\n ", "end": 1900, "score": 0.9998831748962402, "start": 1887, "tag": "EMAIL", "value": "email@arne.no" }, { "context": "b)\n the-criteria-count (counter db {:name \"Sten\"})]\n (is (= the-whole-count 2))\n (is (= the", "end": 2034, "score": 0.9974896907806396, "start": 2030, "tag": "NAME", "value": "Sten" } ]
test/oiiku_mongodb/test/db.clj
oiiku/oiiku-mongodb-clojure
1
(ns oiiku-mongodb.test.db (:require [oiiku-mongodb.db :as db] [monger.core :as mc] oiiku-mongodb.test-helper) (:use clojure.test monger.operators) (:import [org.bson.types ObjectId])) (def db (db/create-db "oiiku-mongodb-tests")) (use-fixtures :each (fn [f] (oiiku-mongodb.test-helper/reset-db db) (f))) (deftest inserting (let [inserter (db/make-insert "my-coll") inserted (inserter db {:foo "bar"})] (is (= (inserted :foo) "bar")) (is (contains? inserted :_id)))) (deftest find-one (let [inserter (db/make-insert "my-coll") inserted (inserter db {:foo "bar"}) finder (db/make-find-one "my-coll") found (finder db {:foo "bar"})] (is (= inserted found)))) (deftest find-all (let [inserter (db/make-insert "my-coll") inserted-a (inserter db {:foo "bar"}) inserted-b (inserter db {:foo "baz"}) inserted-c (inserter db {:foo "bar"}) finder (db/make-find-all "my-coll") found (finder db {:foo "bar"})] (is (= (count found) 2)) ;; TODO: Don't make the test depend on (unspecified) order (is (= (nth found 0) inserted-a)) (is (= (nth found 1) inserted-c)))) (deftest find-all-with-output-filtering (let [inserter (db/make-insert "my-coll") inserted-a (inserter db {:name "Sten" :email "email@sten.no"}) inserted-a (inserter db {:name "Arne" :email "email@arne.no"}) finder (db/make-find-all-with-output-filter "my-coll") found (finder db {:name "Sten"} ["email"])] (is (= (count found) 1)) (is (= (first (remove #(= (key %) :_id) (first found))) [:email "email@sten.no"])))) (deftest count-whole-collection-and-by-criteria (let [inserter (db/make-insert "my-coll") inserted-a (inserter db {:name "Sten" :email "email@sten.no"}) inserted-a (inserter db {:name "Arne" :email "email@arne.no"}) counter (db/make-count "my-coll") the-whole-count (counter db) the-criteria-count (counter db {:name "Sten"})] (is (= the-whole-count 2)) (is (= the-criteria-count 1)))) (deftest find-one-non-existing (let [finder (db/make-find-one "my-coll") found (finder db {:foo "bar"})] (is (nil? found)))) (deftest deleting (let [inserter (db/make-insert "my-coll") inserted (inserter db {:foo "bar"}) deleter (db/make-delete "my-coll")] (deleter db (inserted :_id)) (let [finder (db/make-find-one "my-coll") found (finder db {:foo "bar"})] (is (nil? found))))) (deftest querying-by-id (let [inserter (db/make-insert "my-coll") inserted (inserter db {:foo "bar"}) finder (db/make-find-one "my-coll") found (finder db {:_id (inserted :_id)})] (is (= inserted found)))) (deftest querying-in-by-id (let [inserter (db/make-insert "my-coll") inserted-a (inserter db {}) inserted-b (inserter db {}) inserted-c (inserter db {}) finder (db/make-find-all "my-coll") found (finder db {:_id {:$in [(inserted-a :_id) (inserted-c :_id)]}})] (is (= (count found) 2)) ;; TODO: Don't make the test depend on (unspecified) order (is (= (nth found 0) inserted-a)) (is (= (nth found 1) inserted-c)))) (deftest querying-ne-by-id (let [inserter (db/make-insert "my-coll") inserted-a (inserter db {}) inserted-b (inserter db {}) finder (db/make-find-all "my-coll") found (finder db {:_id {:$ne (inserted-a :_id)}}) ] (is (= (count found) 1)) (is (= (nth found 0) inserted-b)))) (deftest serializing (let [oid-a (ObjectId.) oid-b (ObjectId.) oid-c (ObjectId.) record {:_id oid-a :users [oid-b oid-c] :foo "bar"} res (db/serialize record)] (is (= res {:id (.toString oid-a) :users [(.toString oid-b) (.toString oid-c)] :foo "bar"})))) (deftest nested-map-with-string-keys (let [inserter (db/make-insert "my-coll") inserted (inserter db {:foo {"test" 123}})] (is (= (inserted :foo) {"test" 123})))) (deftest perform-ensure-index (db/perform-ensure-index db {"my-coll" [{:foo 1} {:unique true}]}) (let [inserter (db/make-insert "my-coll") inserted-a (inserter db {:foo "test"}) inserted-b (db/duplicate-key-guard (inserter db {:foo "test"}))] (is (= (inserted-b :db/duplicate-key))))) (deftest getting-name (is (= (db/get-db-name db) "oiiku-mongodb-tests"))) (deftest updating-by-id (let [inserter (db/make-insert "my-coll") updater (db/make-update-by-id "my-coll") finder (db/make-find-one "my-coll") inserted (inserter db {:foo "bar"})] (updater db (inserted :_id) {:foo "baz"}) (is (= ((finder db {:_id (inserted :_id)}) :foo) "baz")) (updater db (inserted :_id) {:test 123}) (is (= ((finder db {:_id (inserted :_id)}) :test) 123)))) (deftest updating-by-criteria (let [inserter (db/make-insert "my-coll") updater (db/make-update "my-coll") finder (db/make-find-one "my-coll") inserted (inserter db {:foo "bar"}) result (updater db {:foo "bar"} {$push {:banan "kake"}})] (is (monger.result/updated-existing? result)))) (deftest upsert-inserts-when-document-does-not-exist (let [upserter (db/make-upsert "my-coll") finder (db/make-find-one "my-coll") result (upserter db {:banan "sjokolade"} {:banan "sjokolade"})] (is (not (monger.result/updated-existing? result))))) (deftest upsert-inserts-when-document-does-exists (let [upserter (db/make-upsert "my-coll") finder (db/make-find-one "my-coll") result (upserter db {:banan "sjokolade"} {:banan "sjokolade"})] (is (not (monger.result/updated-existing? result))) (is (monger.result/updated-existing? (upserter db {:banan "sjokolade"} {:banan "smak"}))))) (deftest save-by-id (let [inserter (db/make-insert "my-coll") saver (db/make-save-by-id "my-coll") inserted (inserter db {:foo "bar"}) updated (saver db (inserted :_id) {:bar "baz"})] (is (= updated {:bar "baz" :_id (inserted :_id)})))) (deftest if-valid-oid-oid-is-valid (let [oid (ObjectId.) result (db/if-valid-oid oid (fn [object-id] object-id) (fn [] "nope" ))] (is (identical? result oid)))) (deftest if-valid-oid-oid-is-invalid (let [result (db/if-valid-oid "123" (fn [object-id] object-id) (fn [] "nope" ))] (is (= result "nope")))) (deftest if-valid-oid-oid-is-valid-but-then-is-nil (let [oid (ObjectId.) result (db/if-valid-oid oid (fn [object-id]) (fn [] "nope" ))] (is (= result "nope")))) (deftest dropping (let [droppable-db (db/create-db "oiiku-mongodb-tests-dropping-test") inserter (db/make-insert "foos") counter (db/make-count "foos")] (try (inserter droppable-db {:hello "world"}) (is (= 1 (counter droppable-db))) (db/drop-database droppable-db) (is (= 0 (counter droppable-db))) (finally (db/drop-database droppable-db)))))
92756
(ns oiiku-mongodb.test.db (:require [oiiku-mongodb.db :as db] [monger.core :as mc] oiiku-mongodb.test-helper) (:use clojure.test monger.operators) (:import [org.bson.types ObjectId])) (def db (db/create-db "oiiku-mongodb-tests")) (use-fixtures :each (fn [f] (oiiku-mongodb.test-helper/reset-db db) (f))) (deftest inserting (let [inserter (db/make-insert "my-coll") inserted (inserter db {:foo "bar"})] (is (= (inserted :foo) "bar")) (is (contains? inserted :_id)))) (deftest find-one (let [inserter (db/make-insert "my-coll") inserted (inserter db {:foo "bar"}) finder (db/make-find-one "my-coll") found (finder db {:foo "bar"})] (is (= inserted found)))) (deftest find-all (let [inserter (db/make-insert "my-coll") inserted-a (inserter db {:foo "bar"}) inserted-b (inserter db {:foo "baz"}) inserted-c (inserter db {:foo "bar"}) finder (db/make-find-all "my-coll") found (finder db {:foo "bar"})] (is (= (count found) 2)) ;; TODO: Don't make the test depend on (unspecified) order (is (= (nth found 0) inserted-a)) (is (= (nth found 1) inserted-c)))) (deftest find-all-with-output-filtering (let [inserter (db/make-insert "my-coll") inserted-a (inserter db {:name "<NAME>" :email "<EMAIL>"}) inserted-a (inserter db {:name "<NAME>" :email "<EMAIL>"}) finder (db/make-find-all-with-output-filter "my-coll") found (finder db {:name "<NAME>"} ["email"])] (is (= (count found) 1)) (is (= (first (remove #(= (key %) :_id) (first found))) [:email "<EMAIL>"])))) (deftest count-whole-collection-and-by-criteria (let [inserter (db/make-insert "my-coll") inserted-a (inserter db {:name "<NAME>" :email "<EMAIL>"}) inserted-a (inserter db {:name "<NAME>" :email "<EMAIL>"}) counter (db/make-count "my-coll") the-whole-count (counter db) the-criteria-count (counter db {:name "<NAME>"})] (is (= the-whole-count 2)) (is (= the-criteria-count 1)))) (deftest find-one-non-existing (let [finder (db/make-find-one "my-coll") found (finder db {:foo "bar"})] (is (nil? found)))) (deftest deleting (let [inserter (db/make-insert "my-coll") inserted (inserter db {:foo "bar"}) deleter (db/make-delete "my-coll")] (deleter db (inserted :_id)) (let [finder (db/make-find-one "my-coll") found (finder db {:foo "bar"})] (is (nil? found))))) (deftest querying-by-id (let [inserter (db/make-insert "my-coll") inserted (inserter db {:foo "bar"}) finder (db/make-find-one "my-coll") found (finder db {:_id (inserted :_id)})] (is (= inserted found)))) (deftest querying-in-by-id (let [inserter (db/make-insert "my-coll") inserted-a (inserter db {}) inserted-b (inserter db {}) inserted-c (inserter db {}) finder (db/make-find-all "my-coll") found (finder db {:_id {:$in [(inserted-a :_id) (inserted-c :_id)]}})] (is (= (count found) 2)) ;; TODO: Don't make the test depend on (unspecified) order (is (= (nth found 0) inserted-a)) (is (= (nth found 1) inserted-c)))) (deftest querying-ne-by-id (let [inserter (db/make-insert "my-coll") inserted-a (inserter db {}) inserted-b (inserter db {}) finder (db/make-find-all "my-coll") found (finder db {:_id {:$ne (inserted-a :_id)}}) ] (is (= (count found) 1)) (is (= (nth found 0) inserted-b)))) (deftest serializing (let [oid-a (ObjectId.) oid-b (ObjectId.) oid-c (ObjectId.) record {:_id oid-a :users [oid-b oid-c] :foo "bar"} res (db/serialize record)] (is (= res {:id (.toString oid-a) :users [(.toString oid-b) (.toString oid-c)] :foo "bar"})))) (deftest nested-map-with-string-keys (let [inserter (db/make-insert "my-coll") inserted (inserter db {:foo {"test" 123}})] (is (= (inserted :foo) {"test" 123})))) (deftest perform-ensure-index (db/perform-ensure-index db {"my-coll" [{:foo 1} {:unique true}]}) (let [inserter (db/make-insert "my-coll") inserted-a (inserter db {:foo "test"}) inserted-b (db/duplicate-key-guard (inserter db {:foo "test"}))] (is (= (inserted-b :db/duplicate-key))))) (deftest getting-name (is (= (db/get-db-name db) "oiiku-mongodb-tests"))) (deftest updating-by-id (let [inserter (db/make-insert "my-coll") updater (db/make-update-by-id "my-coll") finder (db/make-find-one "my-coll") inserted (inserter db {:foo "bar"})] (updater db (inserted :_id) {:foo "baz"}) (is (= ((finder db {:_id (inserted :_id)}) :foo) "baz")) (updater db (inserted :_id) {:test 123}) (is (= ((finder db {:_id (inserted :_id)}) :test) 123)))) (deftest updating-by-criteria (let [inserter (db/make-insert "my-coll") updater (db/make-update "my-coll") finder (db/make-find-one "my-coll") inserted (inserter db {:foo "bar"}) result (updater db {:foo "bar"} {$push {:banan "kake"}})] (is (monger.result/updated-existing? result)))) (deftest upsert-inserts-when-document-does-not-exist (let [upserter (db/make-upsert "my-coll") finder (db/make-find-one "my-coll") result (upserter db {:banan "sjokolade"} {:banan "sjokolade"})] (is (not (monger.result/updated-existing? result))))) (deftest upsert-inserts-when-document-does-exists (let [upserter (db/make-upsert "my-coll") finder (db/make-find-one "my-coll") result (upserter db {:banan "sjokolade"} {:banan "sjokolade"})] (is (not (monger.result/updated-existing? result))) (is (monger.result/updated-existing? (upserter db {:banan "sjokolade"} {:banan "smak"}))))) (deftest save-by-id (let [inserter (db/make-insert "my-coll") saver (db/make-save-by-id "my-coll") inserted (inserter db {:foo "bar"}) updated (saver db (inserted :_id) {:bar "baz"})] (is (= updated {:bar "baz" :_id (inserted :_id)})))) (deftest if-valid-oid-oid-is-valid (let [oid (ObjectId.) result (db/if-valid-oid oid (fn [object-id] object-id) (fn [] "nope" ))] (is (identical? result oid)))) (deftest if-valid-oid-oid-is-invalid (let [result (db/if-valid-oid "123" (fn [object-id] object-id) (fn [] "nope" ))] (is (= result "nope")))) (deftest if-valid-oid-oid-is-valid-but-then-is-nil (let [oid (ObjectId.) result (db/if-valid-oid oid (fn [object-id]) (fn [] "nope" ))] (is (= result "nope")))) (deftest dropping (let [droppable-db (db/create-db "oiiku-mongodb-tests-dropping-test") inserter (db/make-insert "foos") counter (db/make-count "foos")] (try (inserter droppable-db {:hello "world"}) (is (= 1 (counter droppable-db))) (db/drop-database droppable-db) (is (= 0 (counter droppable-db))) (finally (db/drop-database droppable-db)))))
true
(ns oiiku-mongodb.test.db (:require [oiiku-mongodb.db :as db] [monger.core :as mc] oiiku-mongodb.test-helper) (:use clojure.test monger.operators) (:import [org.bson.types ObjectId])) (def db (db/create-db "oiiku-mongodb-tests")) (use-fixtures :each (fn [f] (oiiku-mongodb.test-helper/reset-db db) (f))) (deftest inserting (let [inserter (db/make-insert "my-coll") inserted (inserter db {:foo "bar"})] (is (= (inserted :foo) "bar")) (is (contains? inserted :_id)))) (deftest find-one (let [inserter (db/make-insert "my-coll") inserted (inserter db {:foo "bar"}) finder (db/make-find-one "my-coll") found (finder db {:foo "bar"})] (is (= inserted found)))) (deftest find-all (let [inserter (db/make-insert "my-coll") inserted-a (inserter db {:foo "bar"}) inserted-b (inserter db {:foo "baz"}) inserted-c (inserter db {:foo "bar"}) finder (db/make-find-all "my-coll") found (finder db {:foo "bar"})] (is (= (count found) 2)) ;; TODO: Don't make the test depend on (unspecified) order (is (= (nth found 0) inserted-a)) (is (= (nth found 1) inserted-c)))) (deftest find-all-with-output-filtering (let [inserter (db/make-insert "my-coll") inserted-a (inserter db {:name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"}) inserted-a (inserter db {:name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"}) finder (db/make-find-all-with-output-filter "my-coll") found (finder db {:name "PI:NAME:<NAME>END_PI"} ["email"])] (is (= (count found) 1)) (is (= (first (remove #(= (key %) :_id) (first found))) [:email "PI:EMAIL:<EMAIL>END_PI"])))) (deftest count-whole-collection-and-by-criteria (let [inserter (db/make-insert "my-coll") inserted-a (inserter db {:name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"}) inserted-a (inserter db {:name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"}) counter (db/make-count "my-coll") the-whole-count (counter db) the-criteria-count (counter db {:name "PI:NAME:<NAME>END_PI"})] (is (= the-whole-count 2)) (is (= the-criteria-count 1)))) (deftest find-one-non-existing (let [finder (db/make-find-one "my-coll") found (finder db {:foo "bar"})] (is (nil? found)))) (deftest deleting (let [inserter (db/make-insert "my-coll") inserted (inserter db {:foo "bar"}) deleter (db/make-delete "my-coll")] (deleter db (inserted :_id)) (let [finder (db/make-find-one "my-coll") found (finder db {:foo "bar"})] (is (nil? found))))) (deftest querying-by-id (let [inserter (db/make-insert "my-coll") inserted (inserter db {:foo "bar"}) finder (db/make-find-one "my-coll") found (finder db {:_id (inserted :_id)})] (is (= inserted found)))) (deftest querying-in-by-id (let [inserter (db/make-insert "my-coll") inserted-a (inserter db {}) inserted-b (inserter db {}) inserted-c (inserter db {}) finder (db/make-find-all "my-coll") found (finder db {:_id {:$in [(inserted-a :_id) (inserted-c :_id)]}})] (is (= (count found) 2)) ;; TODO: Don't make the test depend on (unspecified) order (is (= (nth found 0) inserted-a)) (is (= (nth found 1) inserted-c)))) (deftest querying-ne-by-id (let [inserter (db/make-insert "my-coll") inserted-a (inserter db {}) inserted-b (inserter db {}) finder (db/make-find-all "my-coll") found (finder db {:_id {:$ne (inserted-a :_id)}}) ] (is (= (count found) 1)) (is (= (nth found 0) inserted-b)))) (deftest serializing (let [oid-a (ObjectId.) oid-b (ObjectId.) oid-c (ObjectId.) record {:_id oid-a :users [oid-b oid-c] :foo "bar"} res (db/serialize record)] (is (= res {:id (.toString oid-a) :users [(.toString oid-b) (.toString oid-c)] :foo "bar"})))) (deftest nested-map-with-string-keys (let [inserter (db/make-insert "my-coll") inserted (inserter db {:foo {"test" 123}})] (is (= (inserted :foo) {"test" 123})))) (deftest perform-ensure-index (db/perform-ensure-index db {"my-coll" [{:foo 1} {:unique true}]}) (let [inserter (db/make-insert "my-coll") inserted-a (inserter db {:foo "test"}) inserted-b (db/duplicate-key-guard (inserter db {:foo "test"}))] (is (= (inserted-b :db/duplicate-key))))) (deftest getting-name (is (= (db/get-db-name db) "oiiku-mongodb-tests"))) (deftest updating-by-id (let [inserter (db/make-insert "my-coll") updater (db/make-update-by-id "my-coll") finder (db/make-find-one "my-coll") inserted (inserter db {:foo "bar"})] (updater db (inserted :_id) {:foo "baz"}) (is (= ((finder db {:_id (inserted :_id)}) :foo) "baz")) (updater db (inserted :_id) {:test 123}) (is (= ((finder db {:_id (inserted :_id)}) :test) 123)))) (deftest updating-by-criteria (let [inserter (db/make-insert "my-coll") updater (db/make-update "my-coll") finder (db/make-find-one "my-coll") inserted (inserter db {:foo "bar"}) result (updater db {:foo "bar"} {$push {:banan "kake"}})] (is (monger.result/updated-existing? result)))) (deftest upsert-inserts-when-document-does-not-exist (let [upserter (db/make-upsert "my-coll") finder (db/make-find-one "my-coll") result (upserter db {:banan "sjokolade"} {:banan "sjokolade"})] (is (not (monger.result/updated-existing? result))))) (deftest upsert-inserts-when-document-does-exists (let [upserter (db/make-upsert "my-coll") finder (db/make-find-one "my-coll") result (upserter db {:banan "sjokolade"} {:banan "sjokolade"})] (is (not (monger.result/updated-existing? result))) (is (monger.result/updated-existing? (upserter db {:banan "sjokolade"} {:banan "smak"}))))) (deftest save-by-id (let [inserter (db/make-insert "my-coll") saver (db/make-save-by-id "my-coll") inserted (inserter db {:foo "bar"}) updated (saver db (inserted :_id) {:bar "baz"})] (is (= updated {:bar "baz" :_id (inserted :_id)})))) (deftest if-valid-oid-oid-is-valid (let [oid (ObjectId.) result (db/if-valid-oid oid (fn [object-id] object-id) (fn [] "nope" ))] (is (identical? result oid)))) (deftest if-valid-oid-oid-is-invalid (let [result (db/if-valid-oid "123" (fn [object-id] object-id) (fn [] "nope" ))] (is (= result "nope")))) (deftest if-valid-oid-oid-is-valid-but-then-is-nil (let [oid (ObjectId.) result (db/if-valid-oid oid (fn [object-id]) (fn [] "nope" ))] (is (= result "nope")))) (deftest dropping (let [droppable-db (db/create-db "oiiku-mongodb-tests-dropping-test") inserter (db/make-insert "foos") counter (db/make-count "foos")] (try (inserter droppable-db {:hello "world"}) (is (= 1 (counter droppable-db))) (db/drop-database droppable-db) (is (= 0 (counter droppable-db))) (finally (db/drop-database droppable-db)))))
[ { "context": " :where [[e :foaf/givenName \"Pablo\"]]}))))\n\n (t/is (= #{[(keyword \"http://dbpedia.o", "end": 1076, "score": 0.9980605840682983, "start": 1071, "tag": "NAME", "value": "Pablo" }, { "context": " :where [[p :foaf/givenName \"Pablo\"]\n [g :dbo/author p", "end": 1431, "score": 0.9993718266487122, "start": 1426, "tag": "NAME", "value": "Pablo" } ]
crux-test/test/crux/dbpedia_test.clj
neuromantik33/crux
0
(ns crux.dbpedia-test (:require [clojure.test :as t] [crux.fixtures.kafka :as fk] [crux.fixtures.api :as fapi :refer [*api*]] [crux.api :as crux] [crux.fixtures.kv :as fkv] [crux.fixtures.api :as apif] [crux.rdf :as rdf] [clojure.java.io :as io] [crux.sparql :as sparql])) (t/use-fixtures :once fk/with-embedded-kafka-cluster) (t/use-fixtures :each fk/with-cluster-node-opts fkv/with-kv-dir apif/with-node) (t/deftest test-can-transact-and-query-dbpedia-entities (fapi/submit+await-tx (->> (concat (rdf/->tx-ops (rdf/ntriples "crux/Pablo_Picasso.ntriples")) (rdf/->tx-ops (rdf/ntriples "crux/Guernica_(Picasso).ntriples"))) (rdf/->default-language))) (t/is (= #{[:http://dbpedia.org/resource/Pablo_Picasso]} (crux/q (crux/db *api*) (rdf/with-prefix {:foaf "http://xmlns.com/foaf/0.1/"} '{:find [e] :where [[e :foaf/givenName "Pablo"]]})))) (t/is (= #{[(keyword "http://dbpedia.org/resource/Guernica_(Picasso)")]} (crux/q (crux/db *api*) (rdf/with-prefix {:foaf "http://xmlns.com/foaf/0.1/" :dbo "http://dbpedia.org/ontology/"} '{:find [g] :where [[p :foaf/givenName "Pablo"] [g :dbo/author p]]}))))) ;; Download from http://wiki.dbpedia.org/services-resources/ontology ;; mappingbased_properties_en.nt is the main data. ;; instance_types_en.nt contains type definitions only. ;; specific_mappingbased_properties_en.nt contains extra literals. ;; dbpedia_2014.owl is the OWL schema, not dealt with. ;; Test assumes these files are living somewhere on the classpath ;; (probably crux-test/resources related to the crux project). ;; There are 5053979 entities across 33449633 triplets in ;; mappingbased_properties_en.nt. ;; RocksDB: ;; 1.6G /tmp/kafka-log1572248494326726941 ;; 2.0G /tmp/kv-store8136342842355297151 ;; 583800ms ~9.7mins transact ;; 861799ms ~14.40mins index ;; LMDB: ;; 1.6G /tmp/kafka-log17904986480319416547 ;; 9.3G /tmp/kv-store4104462813030460112 ;; 640528ms ~10.7mins transact ;; 2940230ms 49mins index ;; Could use test selectors. (def run-dbpedia-tests? false) (t/deftest test-can-transact-all-dbpedia-entities (let [mappingbased-properties-file (io/resource "dbpedia/mappingbased_properties_en.nt")] (if (and run-dbpedia-tests? mappingbased-properties-file) (let [max-limit Long/MAX_VALUE] (t/testing "ingesting data" (time (rdf/with-ntriples mappingbased-properties-file (fn [ntriples] (let [last-tx (->> ntriples (map rdf/->tx-op) (take max-limit) (partition-all 1000) (reduce (fn [_ ops] (crux/submit-tx *api* ops))))] (crux/await-tx *api* last-tx)))))) (t/testing "querying transacted data" (t/is (= (rdf/with-prefix {:dbr "http://dbpedia.org/resource/"} #{[:dbr/Aristotle] [(keyword "dbr/Aristotle_(painting)")] [(keyword "dbr/Aristotle_(book)")]}) (crux/q (crux/db *api*) (rdf/with-prefix {:foaf "http://xmlns.com/foaf/0.1"} '{:find [e] :where [[e :foaf/name "Aristotle"]]})))))) (t/is true "skipping"))))
23249
(ns crux.dbpedia-test (:require [clojure.test :as t] [crux.fixtures.kafka :as fk] [crux.fixtures.api :as fapi :refer [*api*]] [crux.api :as crux] [crux.fixtures.kv :as fkv] [crux.fixtures.api :as apif] [crux.rdf :as rdf] [clojure.java.io :as io] [crux.sparql :as sparql])) (t/use-fixtures :once fk/with-embedded-kafka-cluster) (t/use-fixtures :each fk/with-cluster-node-opts fkv/with-kv-dir apif/with-node) (t/deftest test-can-transact-and-query-dbpedia-entities (fapi/submit+await-tx (->> (concat (rdf/->tx-ops (rdf/ntriples "crux/Pablo_Picasso.ntriples")) (rdf/->tx-ops (rdf/ntriples "crux/Guernica_(Picasso).ntriples"))) (rdf/->default-language))) (t/is (= #{[:http://dbpedia.org/resource/Pablo_Picasso]} (crux/q (crux/db *api*) (rdf/with-prefix {:foaf "http://xmlns.com/foaf/0.1/"} '{:find [e] :where [[e :foaf/givenName "<NAME>"]]})))) (t/is (= #{[(keyword "http://dbpedia.org/resource/Guernica_(Picasso)")]} (crux/q (crux/db *api*) (rdf/with-prefix {:foaf "http://xmlns.com/foaf/0.1/" :dbo "http://dbpedia.org/ontology/"} '{:find [g] :where [[p :foaf/givenName "<NAME>"] [g :dbo/author p]]}))))) ;; Download from http://wiki.dbpedia.org/services-resources/ontology ;; mappingbased_properties_en.nt is the main data. ;; instance_types_en.nt contains type definitions only. ;; specific_mappingbased_properties_en.nt contains extra literals. ;; dbpedia_2014.owl is the OWL schema, not dealt with. ;; Test assumes these files are living somewhere on the classpath ;; (probably crux-test/resources related to the crux project). ;; There are 5053979 entities across 33449633 triplets in ;; mappingbased_properties_en.nt. ;; RocksDB: ;; 1.6G /tmp/kafka-log1572248494326726941 ;; 2.0G /tmp/kv-store8136342842355297151 ;; 583800ms ~9.7mins transact ;; 861799ms ~14.40mins index ;; LMDB: ;; 1.6G /tmp/kafka-log17904986480319416547 ;; 9.3G /tmp/kv-store4104462813030460112 ;; 640528ms ~10.7mins transact ;; 2940230ms 49mins index ;; Could use test selectors. (def run-dbpedia-tests? false) (t/deftest test-can-transact-all-dbpedia-entities (let [mappingbased-properties-file (io/resource "dbpedia/mappingbased_properties_en.nt")] (if (and run-dbpedia-tests? mappingbased-properties-file) (let [max-limit Long/MAX_VALUE] (t/testing "ingesting data" (time (rdf/with-ntriples mappingbased-properties-file (fn [ntriples] (let [last-tx (->> ntriples (map rdf/->tx-op) (take max-limit) (partition-all 1000) (reduce (fn [_ ops] (crux/submit-tx *api* ops))))] (crux/await-tx *api* last-tx)))))) (t/testing "querying transacted data" (t/is (= (rdf/with-prefix {:dbr "http://dbpedia.org/resource/"} #{[:dbr/Aristotle] [(keyword "dbr/Aristotle_(painting)")] [(keyword "dbr/Aristotle_(book)")]}) (crux/q (crux/db *api*) (rdf/with-prefix {:foaf "http://xmlns.com/foaf/0.1"} '{:find [e] :where [[e :foaf/name "Aristotle"]]})))))) (t/is true "skipping"))))
true
(ns crux.dbpedia-test (:require [clojure.test :as t] [crux.fixtures.kafka :as fk] [crux.fixtures.api :as fapi :refer [*api*]] [crux.api :as crux] [crux.fixtures.kv :as fkv] [crux.fixtures.api :as apif] [crux.rdf :as rdf] [clojure.java.io :as io] [crux.sparql :as sparql])) (t/use-fixtures :once fk/with-embedded-kafka-cluster) (t/use-fixtures :each fk/with-cluster-node-opts fkv/with-kv-dir apif/with-node) (t/deftest test-can-transact-and-query-dbpedia-entities (fapi/submit+await-tx (->> (concat (rdf/->tx-ops (rdf/ntriples "crux/Pablo_Picasso.ntriples")) (rdf/->tx-ops (rdf/ntriples "crux/Guernica_(Picasso).ntriples"))) (rdf/->default-language))) (t/is (= #{[:http://dbpedia.org/resource/Pablo_Picasso]} (crux/q (crux/db *api*) (rdf/with-prefix {:foaf "http://xmlns.com/foaf/0.1/"} '{:find [e] :where [[e :foaf/givenName "PI:NAME:<NAME>END_PI"]]})))) (t/is (= #{[(keyword "http://dbpedia.org/resource/Guernica_(Picasso)")]} (crux/q (crux/db *api*) (rdf/with-prefix {:foaf "http://xmlns.com/foaf/0.1/" :dbo "http://dbpedia.org/ontology/"} '{:find [g] :where [[p :foaf/givenName "PI:NAME:<NAME>END_PI"] [g :dbo/author p]]}))))) ;; Download from http://wiki.dbpedia.org/services-resources/ontology ;; mappingbased_properties_en.nt is the main data. ;; instance_types_en.nt contains type definitions only. ;; specific_mappingbased_properties_en.nt contains extra literals. ;; dbpedia_2014.owl is the OWL schema, not dealt with. ;; Test assumes these files are living somewhere on the classpath ;; (probably crux-test/resources related to the crux project). ;; There are 5053979 entities across 33449633 triplets in ;; mappingbased_properties_en.nt. ;; RocksDB: ;; 1.6G /tmp/kafka-log1572248494326726941 ;; 2.0G /tmp/kv-store8136342842355297151 ;; 583800ms ~9.7mins transact ;; 861799ms ~14.40mins index ;; LMDB: ;; 1.6G /tmp/kafka-log17904986480319416547 ;; 9.3G /tmp/kv-store4104462813030460112 ;; 640528ms ~10.7mins transact ;; 2940230ms 49mins index ;; Could use test selectors. (def run-dbpedia-tests? false) (t/deftest test-can-transact-all-dbpedia-entities (let [mappingbased-properties-file (io/resource "dbpedia/mappingbased_properties_en.nt")] (if (and run-dbpedia-tests? mappingbased-properties-file) (let [max-limit Long/MAX_VALUE] (t/testing "ingesting data" (time (rdf/with-ntriples mappingbased-properties-file (fn [ntriples] (let [last-tx (->> ntriples (map rdf/->tx-op) (take max-limit) (partition-all 1000) (reduce (fn [_ ops] (crux/submit-tx *api* ops))))] (crux/await-tx *api* last-tx)))))) (t/testing "querying transacted data" (t/is (= (rdf/with-prefix {:dbr "http://dbpedia.org/resource/"} #{[:dbr/Aristotle] [(keyword "dbr/Aristotle_(painting)")] [(keyword "dbr/Aristotle_(book)")]}) (crux/q (crux/db *api*) (rdf/with-prefix {:foaf "http://xmlns.com/foaf/0.1"} '{:find [e] :where [[e :foaf/name "Aristotle"]]})))))) (t/is true "skipping"))))
[ { "context": "\"\n \"Do not tolerate intolerance.\"\n \"My name is Adam and I've made this game for you (and me).\"\n \"Pl", "end": 16891, "score": 0.9984877109527588, "start": 16887, "tag": "NAME", "value": "Adam" } ]
src/word_grid/app.cljs
adam-james-v/word-grid
3
(ns word-grid.app (:require [clojure.string :as str] [reagent.core :as r] [svg-clj.utils :as utils] [svg-clj.elements :as el] [svg-clj.path :as path] [svg-clj.transforms :as tf] [svg-clj.parametric :as p] [svg-clj.layout :as lo] [svg-clj.composites :as comp :refer [svg]] [goog.events :as events]) (:import [goog.events EventType])) ;; Constants and references (def tile-w 40) (def tile-pad 4) ;; grid-unit (def gu (+ tile-w tile-pad)) (def window (r/atom [js/window.innerWidth js/window.innerHeight])) (defn ww [] (first @window)) (defn wh [] (second @window)) ;; one tile -> {:pos [0 0] :letter "A"} (defn rect-grid [nx ny x-spacing y-spacing] (for [b (range ny) a (range nx)] [(* a x-spacing) (* b y-spacing)])) (def tiles (let [letters (shuffle (concat (repeat 13 "A") (repeat 3 "B") (repeat 3 "C") (repeat 6 "D") (repeat 18 "E") (repeat 3 "F") (repeat 4 "G") (repeat 3 "H") (repeat 12 "I") (repeat 2 "J") (repeat 2 "K") (repeat 5 "L") (repeat 3 "M") (repeat 8 "N") (repeat 11 "O") (repeat 3 "P") (repeat 2 "Q") (repeat 9 "R") (repeat 6 "S") (repeat 9 "T") (repeat 6 "U") (repeat 3 "V") (repeat 3 "W") (repeat 2 "X") (repeat 3 "Y") (repeat 2 "Z"))) f (fn [pos letter] {:pos pos :letter letter :visible? false}) wwh (Math/floor (/ (ww) 2)) whh (Math/floor (/ (wh) 2)) grid (->> (rect-grid 7 (Math/ceil (/ (count letters) 7)) gu gu) #_(partition 2) #_(map first) (map #(utils/v+ % [(/ gu 2) (/ gu 2)])) (map #(utils/v+ % [(* gu -3) (* gu -1)])) (map #(utils/v+ % [(- wwh (mod wwh gu)) (- whh (mod whh gu))]))) tiles (map f grid letters)] (r/atom (zipmap (range) tiles)))) (def board-pos (r/atom [(/ gu 2) (/ gu 2)])) ;; https://stackoverflow.com/a/25123243 (defn split-when [f s] (reduce (fn [acc [a b]] (if (f b a) (conj acc [b]) (update-in acc [(dec (count acc))] conj b))) [[(first s)]] (partition 2 1 s))) (defn- overlaps? [tiles] (->> tiles vals (filter :visible?) (map :pos) frequencies vals (some #(= 2 %)))) (defn- get-ids-by-pos [pos tiles] (let [ts (map (fn [[id tile]] (assoc tile :id id)) tiles)] (->> ts (filter #(= pos (:pos %))) (map :id)))) (defn- move-tile-down [id tiles] (update-in tiles [id :pos] #(utils/v+ % [0 gu]))) (defn fix-overlaps [tiles] (if (not (overlaps? tiles)) tiles (let [positions (map (fn [[_ {:keys [pos]}]] pos) tiles) overlap-ids (filter #(> (count %) 1) (map #(get-ids-by-pos % tiles) positions))] (recur (move-tile-down (first (first overlap-ids)) tiles))))) (defn fix-overlaps! [] (let [fixed (fix-overlaps @tiles)] (reset! tiles fixed))) (defn visible? [id] (get-in @tiles [id :visible?])) (defn snap-tiles! [] (let [snap-tile (fn [[x y]] [(Math/floor (- (+ x (/ gu 2.0)) (mod x gu))) (Math/floor (- (+ y (/ gu 2.0)) (mod y gu)))])] (doseq [id (filter visible? (range 145))] (swap! tiles update-in [id :pos] snap-tile)))) (defn update-state! [] (snap-tiles!) (fix-overlaps!)) (defn get-words [] (let [f (fn [[_ {:keys [pos letter visible?]}]] (when visible? {:x (int (/ (first pos) gu)) :y (int (/ (second pos) gu)) :letter letter})) rows (->> (map f @tiles) (remove nil?) (sort-by :y) (partition-by #(get % :y)) (map (fn [s] (sort-by :x s))) (mapcat #(split-when (fn [a b] (not= (:x a) (inc (:x b)))) %)) (map (fn [s] (apply str (map :letter s)))) (remove #(= 1 (count %)))) cols (->> (map f @tiles) (remove nil?) (sort-by :x) (partition-by #(get % :x)) (map (fn [s] (sort-by :y s))) (mapcat #(split-when (fn [a b] (not= (:y a) (inc (:y b)))) %)) (map (fn [s] (apply str (map :letter s)))) (remove #(= 1 (count %))))] {:horizontal rows :vertical cols})) ;; Utility functions (defn get-client-mid [evt] (let [r (.getBoundingClientRect (.-target evt)) left (.-left r) top (.-top r) bottom (.-bottom r) right (.-right r) w (- right left) h (- bottom top)] {:x (- right (/ w 2.0)) :y (- bottom (/ h 2.0))})) (defn prevent-motion [e] (js/window.scrollTo 0 0) (e.preventDefault) (e.stopPropagation)) (events/listen js/window EventType.SCROLL prevent-motion) (events/listen js/window EventType.TOUCHMOVE prevent-motion) ;; Event handlers (defn mouse-move-handler [id offset] (fn [evt] (let [cx (.-clientX evt) cy (.-clientY evt) ox (:x offset) oy (:y offset)] (if (= id :board) (reset! board-pos [(Math/floor (- cx ox)) (Math/floor (- cy oy))]) (swap! tiles assoc-in [id :pos] [(Math/floor (- cx ox)) (Math/floor (- cy oy))]))))) (defn mouse-up-handler [on-move] (fn me [evt] (events/unlisten js/window EventType.MOUSEMOVE on-move))) (defn mouse-down-handler [id] (fn [e] (let [{:keys [x y] :as mid} (get-client-mid e) [bx by] (utils/v* [-1 -1] @board-pos) cx (.-clientX e) cy (.-clientY e) offset (if (= id :board) {:x (+ cx bx) :y (+ cy by)} {:x (- cx (when-not (= id :board) x) bx) :y (- cy (when-not (= id :board) y) by)}) on-move (mouse-move-handler id offset)] (events/listen js/window EventType.MOUSEMOVE on-move) (events/listen js/window EventType.MOUSEUP (mouse-up-handler on-move))))) (defn touch-move-handler [id offset] (fn [evt] (let [cx (.-clientX evt) cy (.-clientY evt) ox (:x offset) oy (:y offset)] (if (= id :board) (reset! board-pos [(Math/floor (- cx ox)) (Math/floor (- cy oy))]) (swap! tiles assoc-in [id :pos] [(Math/floor (- cx ox)) (Math/floor (- cy oy))]))))) (defn touch-end-handler [on-move] (fn te [evt] (events/unlisten js/window EventType.TOUCHMOVE on-move))) (defn touch-start-handler [id] (fn [e] (let [{:keys [x y] :as mid} (get-client-mid e) [bx by] (utils/v* [-1 -1] @board-pos) cx (.-pageX (first (.-changedTouches e))) cy (.-pageY (first (.-changedTouches e))) offset (if (= id :board) {:x (+ cx bx) :y (+ cy by)} {:x (- cx (when-not (= id :board) x) bx) :y (- cy (when-not (= id :board) y) by)}) on-move (touch-move-handler id offset)] (e.preventDefault) (events/listen js/window EventType.TOUCHMOVE on-move) (events/listen js/window EventType.TOUCHEND (touch-end-handler on-move))))) ;; components (defn tile [[id {:keys [pos letter visible?]}]] (when visible? (-> (el/g #_(el/g (for [i (reverse (range 0 4))] (-> (el/rect tile-w tile-w) (tf/translate [(* i 0.8) i]) (tf/style {:rx 5 :fill "#EBE89A" :stroke "#9E9C59" :stroke-width 1.5})))) (-> (el/rect tile-w tile-w) (tf/style {:rx 5 :fill "#EBE89A" :stroke "#9E9C59" :stroke-width 1 #_#_:filter "drop-shadow(1px 1px 4px rgb(0 0 0 / 0.2))"})) #_(el/text (str pos)) (-> (el/text letter) (tf/translate [0 4]) (tf/style {:fill "#9E6067" :font-size (str (* 0.625 gu) "px") :font-family "Palatino" :style {:user-select "none" :-moz-user-select "none" :-webkit-user-select "none"}}))) (tf/translate (utils/v+ pos @board-pos)) (tf/style {:on-mouse-down (mouse-down-handler id) :on-touch-start (touch-start-handler id)})))) (defn wordlist [] (let [scrabble-finder-url "https://scrabble.merriam.com/finder/" {:keys [horizontal vertical]} (get-words) lh 20 vlist-offset (* (+ 3 (count horizontal)) lh) f (fn [pos] (fn [idx t] [:a {:key idx :xlinkHref (str scrabble-finder-url t) :target "_blank"} (-> (el/text t) (tf/translate pos) (tf/translate [0 (* idx lh)]) (tf/style {:fill "#9E6067" :text-decoration "underline"}))]))] (el/g (-> (el/text "HORIZONTAL:") (tf/translate [50 lh])) (map-indexed (f [50 (* 2 lh)]) horizontal) (-> (el/text "VERTICAL:") (tf/translate [50 vlist-offset])) (map-indexed (f [50 (+ lh vlist-offset)]) vertical)))) (defn center-button-pos [] [(* 1 gu) (- (wh) (* 0.625 gu))]) (defn center! [e] (reset! board-pos [0 0])) (defn center-button [] (-> (el/g (-> (el/rect (* 2 tile-w) tile-w) (tf/style {:rx 5 :stroke "#596B4C" :stroke-width 1 :fill "#C3EBA7" :filter "drop-shadow(1px 1px 4px rgb(0 0 0 / 0.2))"})) (-> (el/text "CENTER") (tf/translate [0 3]) (tf/style {:fill "#596B4C" :opacity 1 :font-size (str (* 0.375 gu) "px") :font-family "Palatino" :style {:user-select "none" :-moz-user-select "none" :-webkit-user-select "none"}}))) (tf/translate (center-button-pos)) (tf/style {:on-click center! #_#_:on-touch-start center!}))) (def dump-target-line (r/atom nil)) (defn dump-button-pos [] [(- (ww) (* 1 gu)) (- (wh) (* 0.625 gu))]) (defn show-dump-target [e] (let [positions (->> @tiles (filter (fn [[_ {:keys [visible?]}]] visible?)) (map (fn [[_ {:keys [pos]}]] pos))) pta (->> (sort-by #(utils/distance (utils/v+ % @board-pos) (dump-button-pos)) positions) first (utils/v+ @board-pos)) ptc (dump-button-pos) ptb (utils/v+ ((p/line pta ptc) 0.5) ((p/circle (* 4 gu)) (rand)))] (reset! dump-target-line (-> (path/bezier pta ptb ptc) (tf/style {:stroke-linecap "round" :fill "none" :stroke-width 7 :stroke "#EB838E" :opacity 0.3}))) (js/setTimeout #(reset! dump-target-line nil) 700))) (defn dump! [e] (let [ts @tiles positions (->> ts (filter (fn [[_ {:keys [visible?]}]] visible?)) (map (fn [[id {:keys [pos]}]] [id pos]))) to-dump (->> positions (sort-by #(utils/distance (utils/v+ (second %) @board-pos) (dump-button-pos))) first) to-show (->> ts (remove (fn [[_ {:keys [visible?]}]] visible?)) (map (fn [[id {:keys [pos]}]] id)) (take 3))] (doseq [to-show (map-indexed vector (sort to-show))] (let [position [(- (/ (ww) 2) (mod (/ (ww) 2) gu) (- gu) (* (first to-show) gu)) (- (wh) (mod (wh) gu) (* 2 gu))]] (swap! tiles assoc-in [(second to-show) :pos] (utils/v- position @board-pos)) (swap! tiles assoc-in [(second to-show) :visible?] true))) (swap! tiles assoc-in [(first to-dump) :visible?] false))) (defn dump-button [] (-> (el/g (-> (el/rect (* 2 tile-w) tile-w) (tf/style {:rx 5 :stroke "#9E6067" :stroke-width 1 :fill "#EB838E" :filter "drop-shadow(1px 1px 4px rgb(0 0 0 / 0.2))"})) (-> (el/text "DUMP") (tf/translate [0 3]) (tf/style {:fill "#9E6067" :opacity 1 :font-size (str (* 0.375 gu) "px") :font-family "Palatino" :style {:user-select "none" :-moz-user-select "none" :-webkit-user-select "none"}}))) (tf/translate (dump-button-pos)) (tf/style {:on-click dump! :on-touch-end dump! :on-mouse-over show-dump-target :on-touch-start show-dump-target}))) (defn add-button-pos [] [(/ (ww) 2) (- (wh) (* 0.625 gu))]) (defn add! [] (let [ts @tiles positions (->> ts (filter (fn [[_ {:keys [visible?]}]] visible?)) (map (fn [[id {:keys [pos]}]] [id pos]))) to-show (->> ts (remove (fn [[_ {:keys [visible?]}]] visible?)) (map (fn [[id {:keys [pos]}]] id)) (take 1))] (doseq [to-show (map-indexed vector (sort to-show))] (let [position [(- (/ (ww) 2) (mod (/ (ww) 2) gu) (- gu) (* (first to-show) gu)) (- (wh) (mod (wh) gu) (* 2 gu))]] (swap! tiles assoc-in [(second to-show) :pos] (utils/v- position @board-pos)) (swap! tiles assoc-in [(second to-show) :visible?] true))))) (defn add-button [] (-> (el/g (-> (el/rect (* 2 tile-w) tile-w) (tf/style {:rx 5 :stroke "#596B4C" :stroke-width 1 :fill "#C3EBA7" :filter "drop-shadow(1px 1px 4px rgb(0 0 0 / 0.2))"})) (-> (el/text "ADD") (tf/translate [0 3]) (tf/style {:fill "#596B4C" :opacity 1 :font-size (str (* 0.375 gu) "px") :font-family "Palatino" :style {:user-select "none" :-moz-user-select "none" :-webkit-user-select "none"}}))) (tf/translate (add-button-pos)) (tf/style {:on-click add! #_#_:on-touch-end add!}))) (defn share-button-pos [] [(- (ww) (* 1 gu)) (* 0.625 gu)]) (defn share! [] (let [text "ON CLIPBOARD"] (js/navigator.clipboard.writeText text))) (defn share-button [] (-> (el/g (-> (el/rect (* 2 tile-w) tile-w) (tf/style {:rx 5 :stroke "#596B4C" :stroke-width 1 :fill "#C3EBA7" :filter "drop-shadow(1px 1px 4px rgb(0 0 0 / 0.2))"})) (-> (el/text "SHARE") (tf/translate [0 3]) (tf/style {:fill "#596B4C" :opacity 1 :font-size (str (* 0.375 gu) "px") :font-family "Palatino" :style {:user-select "none" :-moz-user-select "none" :-webkit-user-select "none"}}))) (tf/translate (share-button-pos)) (tf/style {:on-click share! #_#_:on-touch-end add!}))) (def titles ["Wow, it's words!" "Oops, all letters!" "You've seen a crossword before, right?" "WWWWWWOOOOORRRDDDDS!" "I like word games, ok?" "Naming things is hard. This is a game with letters." "grid + letters = words + fun" "Clean up these tiles, please." "Grams. Grams. Grams." "Letters make words. Words are fun." "Do not tolerate intolerance." "My name is Adam and I've made this game for you (and me)." "Please be kind to other people."]) (def rand-title (first (shuffle titles))) (defn title [] (-> (el/text rand-title) (tf/translate [(/ (ww) 2) (* (wh) 0.4)]) (tf/style {:fill "#9E6067" :opacity 0.1 :font-size "40px" :font-family "Palatino" :style {:user-select "none" :-moz-user-select "none" :-webkit-user-select "none"}}))) (defn board [] (let [table (-> (el/rect (* 4 (ww)) (* 4 (wh))) (tf/translate [(* 2 (ww)) (* 2 (wh))]) (tf/style {:fill "#B2D8EB" :on-mouse-down (mouse-down-handler :board) :on-touch-start (touch-start-handler :board)}))] (-> (el/g table [title] ;; debug #_(-> (el/text (str @window)) (tf/translate [(/ (ww) 2) (/ (wh) 2)])) [wordlist] (el/g (map tile @tiles)) @dump-target-line [center-button] [add-button] [dump-button] #_[share-button]) (svg (ww) (wh)) (tf/style {:style {:position "absolute" :left 0 :top 0}})))) (defn app [] [:<> [board] [:span (str @board-pos)]]) (defn mount [app] (doseq [id (range 21)] (swap! tiles assoc-in [id :visible?] true)) (events/listen js/window EventType.MOUSEUP update-state!) (events/listen js/window EventType.TOUCHEND update-state!) (events/listen js/window EventType.RESIZE #(reset! window [js/window.innerWidth js/window.innerHeight])) (r/render-component [app] (js/document.getElementById "root"))) (defn init [] (mount app)) (defn ^:dev/after-load re-render [] (mount app))
99729
(ns word-grid.app (:require [clojure.string :as str] [reagent.core :as r] [svg-clj.utils :as utils] [svg-clj.elements :as el] [svg-clj.path :as path] [svg-clj.transforms :as tf] [svg-clj.parametric :as p] [svg-clj.layout :as lo] [svg-clj.composites :as comp :refer [svg]] [goog.events :as events]) (:import [goog.events EventType])) ;; Constants and references (def tile-w 40) (def tile-pad 4) ;; grid-unit (def gu (+ tile-w tile-pad)) (def window (r/atom [js/window.innerWidth js/window.innerHeight])) (defn ww [] (first @window)) (defn wh [] (second @window)) ;; one tile -> {:pos [0 0] :letter "A"} (defn rect-grid [nx ny x-spacing y-spacing] (for [b (range ny) a (range nx)] [(* a x-spacing) (* b y-spacing)])) (def tiles (let [letters (shuffle (concat (repeat 13 "A") (repeat 3 "B") (repeat 3 "C") (repeat 6 "D") (repeat 18 "E") (repeat 3 "F") (repeat 4 "G") (repeat 3 "H") (repeat 12 "I") (repeat 2 "J") (repeat 2 "K") (repeat 5 "L") (repeat 3 "M") (repeat 8 "N") (repeat 11 "O") (repeat 3 "P") (repeat 2 "Q") (repeat 9 "R") (repeat 6 "S") (repeat 9 "T") (repeat 6 "U") (repeat 3 "V") (repeat 3 "W") (repeat 2 "X") (repeat 3 "Y") (repeat 2 "Z"))) f (fn [pos letter] {:pos pos :letter letter :visible? false}) wwh (Math/floor (/ (ww) 2)) whh (Math/floor (/ (wh) 2)) grid (->> (rect-grid 7 (Math/ceil (/ (count letters) 7)) gu gu) #_(partition 2) #_(map first) (map #(utils/v+ % [(/ gu 2) (/ gu 2)])) (map #(utils/v+ % [(* gu -3) (* gu -1)])) (map #(utils/v+ % [(- wwh (mod wwh gu)) (- whh (mod whh gu))]))) tiles (map f grid letters)] (r/atom (zipmap (range) tiles)))) (def board-pos (r/atom [(/ gu 2) (/ gu 2)])) ;; https://stackoverflow.com/a/25123243 (defn split-when [f s] (reduce (fn [acc [a b]] (if (f b a) (conj acc [b]) (update-in acc [(dec (count acc))] conj b))) [[(first s)]] (partition 2 1 s))) (defn- overlaps? [tiles] (->> tiles vals (filter :visible?) (map :pos) frequencies vals (some #(= 2 %)))) (defn- get-ids-by-pos [pos tiles] (let [ts (map (fn [[id tile]] (assoc tile :id id)) tiles)] (->> ts (filter #(= pos (:pos %))) (map :id)))) (defn- move-tile-down [id tiles] (update-in tiles [id :pos] #(utils/v+ % [0 gu]))) (defn fix-overlaps [tiles] (if (not (overlaps? tiles)) tiles (let [positions (map (fn [[_ {:keys [pos]}]] pos) tiles) overlap-ids (filter #(> (count %) 1) (map #(get-ids-by-pos % tiles) positions))] (recur (move-tile-down (first (first overlap-ids)) tiles))))) (defn fix-overlaps! [] (let [fixed (fix-overlaps @tiles)] (reset! tiles fixed))) (defn visible? [id] (get-in @tiles [id :visible?])) (defn snap-tiles! [] (let [snap-tile (fn [[x y]] [(Math/floor (- (+ x (/ gu 2.0)) (mod x gu))) (Math/floor (- (+ y (/ gu 2.0)) (mod y gu)))])] (doseq [id (filter visible? (range 145))] (swap! tiles update-in [id :pos] snap-tile)))) (defn update-state! [] (snap-tiles!) (fix-overlaps!)) (defn get-words [] (let [f (fn [[_ {:keys [pos letter visible?]}]] (when visible? {:x (int (/ (first pos) gu)) :y (int (/ (second pos) gu)) :letter letter})) rows (->> (map f @tiles) (remove nil?) (sort-by :y) (partition-by #(get % :y)) (map (fn [s] (sort-by :x s))) (mapcat #(split-when (fn [a b] (not= (:x a) (inc (:x b)))) %)) (map (fn [s] (apply str (map :letter s)))) (remove #(= 1 (count %)))) cols (->> (map f @tiles) (remove nil?) (sort-by :x) (partition-by #(get % :x)) (map (fn [s] (sort-by :y s))) (mapcat #(split-when (fn [a b] (not= (:y a) (inc (:y b)))) %)) (map (fn [s] (apply str (map :letter s)))) (remove #(= 1 (count %))))] {:horizontal rows :vertical cols})) ;; Utility functions (defn get-client-mid [evt] (let [r (.getBoundingClientRect (.-target evt)) left (.-left r) top (.-top r) bottom (.-bottom r) right (.-right r) w (- right left) h (- bottom top)] {:x (- right (/ w 2.0)) :y (- bottom (/ h 2.0))})) (defn prevent-motion [e] (js/window.scrollTo 0 0) (e.preventDefault) (e.stopPropagation)) (events/listen js/window EventType.SCROLL prevent-motion) (events/listen js/window EventType.TOUCHMOVE prevent-motion) ;; Event handlers (defn mouse-move-handler [id offset] (fn [evt] (let [cx (.-clientX evt) cy (.-clientY evt) ox (:x offset) oy (:y offset)] (if (= id :board) (reset! board-pos [(Math/floor (- cx ox)) (Math/floor (- cy oy))]) (swap! tiles assoc-in [id :pos] [(Math/floor (- cx ox)) (Math/floor (- cy oy))]))))) (defn mouse-up-handler [on-move] (fn me [evt] (events/unlisten js/window EventType.MOUSEMOVE on-move))) (defn mouse-down-handler [id] (fn [e] (let [{:keys [x y] :as mid} (get-client-mid e) [bx by] (utils/v* [-1 -1] @board-pos) cx (.-clientX e) cy (.-clientY e) offset (if (= id :board) {:x (+ cx bx) :y (+ cy by)} {:x (- cx (when-not (= id :board) x) bx) :y (- cy (when-not (= id :board) y) by)}) on-move (mouse-move-handler id offset)] (events/listen js/window EventType.MOUSEMOVE on-move) (events/listen js/window EventType.MOUSEUP (mouse-up-handler on-move))))) (defn touch-move-handler [id offset] (fn [evt] (let [cx (.-clientX evt) cy (.-clientY evt) ox (:x offset) oy (:y offset)] (if (= id :board) (reset! board-pos [(Math/floor (- cx ox)) (Math/floor (- cy oy))]) (swap! tiles assoc-in [id :pos] [(Math/floor (- cx ox)) (Math/floor (- cy oy))]))))) (defn touch-end-handler [on-move] (fn te [evt] (events/unlisten js/window EventType.TOUCHMOVE on-move))) (defn touch-start-handler [id] (fn [e] (let [{:keys [x y] :as mid} (get-client-mid e) [bx by] (utils/v* [-1 -1] @board-pos) cx (.-pageX (first (.-changedTouches e))) cy (.-pageY (first (.-changedTouches e))) offset (if (= id :board) {:x (+ cx bx) :y (+ cy by)} {:x (- cx (when-not (= id :board) x) bx) :y (- cy (when-not (= id :board) y) by)}) on-move (touch-move-handler id offset)] (e.preventDefault) (events/listen js/window EventType.TOUCHMOVE on-move) (events/listen js/window EventType.TOUCHEND (touch-end-handler on-move))))) ;; components (defn tile [[id {:keys [pos letter visible?]}]] (when visible? (-> (el/g #_(el/g (for [i (reverse (range 0 4))] (-> (el/rect tile-w tile-w) (tf/translate [(* i 0.8) i]) (tf/style {:rx 5 :fill "#EBE89A" :stroke "#9E9C59" :stroke-width 1.5})))) (-> (el/rect tile-w tile-w) (tf/style {:rx 5 :fill "#EBE89A" :stroke "#9E9C59" :stroke-width 1 #_#_:filter "drop-shadow(1px 1px 4px rgb(0 0 0 / 0.2))"})) #_(el/text (str pos)) (-> (el/text letter) (tf/translate [0 4]) (tf/style {:fill "#9E6067" :font-size (str (* 0.625 gu) "px") :font-family "Palatino" :style {:user-select "none" :-moz-user-select "none" :-webkit-user-select "none"}}))) (tf/translate (utils/v+ pos @board-pos)) (tf/style {:on-mouse-down (mouse-down-handler id) :on-touch-start (touch-start-handler id)})))) (defn wordlist [] (let [scrabble-finder-url "https://scrabble.merriam.com/finder/" {:keys [horizontal vertical]} (get-words) lh 20 vlist-offset (* (+ 3 (count horizontal)) lh) f (fn [pos] (fn [idx t] [:a {:key idx :xlinkHref (str scrabble-finder-url t) :target "_blank"} (-> (el/text t) (tf/translate pos) (tf/translate [0 (* idx lh)]) (tf/style {:fill "#9E6067" :text-decoration "underline"}))]))] (el/g (-> (el/text "HORIZONTAL:") (tf/translate [50 lh])) (map-indexed (f [50 (* 2 lh)]) horizontal) (-> (el/text "VERTICAL:") (tf/translate [50 vlist-offset])) (map-indexed (f [50 (+ lh vlist-offset)]) vertical)))) (defn center-button-pos [] [(* 1 gu) (- (wh) (* 0.625 gu))]) (defn center! [e] (reset! board-pos [0 0])) (defn center-button [] (-> (el/g (-> (el/rect (* 2 tile-w) tile-w) (tf/style {:rx 5 :stroke "#596B4C" :stroke-width 1 :fill "#C3EBA7" :filter "drop-shadow(1px 1px 4px rgb(0 0 0 / 0.2))"})) (-> (el/text "CENTER") (tf/translate [0 3]) (tf/style {:fill "#596B4C" :opacity 1 :font-size (str (* 0.375 gu) "px") :font-family "Palatino" :style {:user-select "none" :-moz-user-select "none" :-webkit-user-select "none"}}))) (tf/translate (center-button-pos)) (tf/style {:on-click center! #_#_:on-touch-start center!}))) (def dump-target-line (r/atom nil)) (defn dump-button-pos [] [(- (ww) (* 1 gu)) (- (wh) (* 0.625 gu))]) (defn show-dump-target [e] (let [positions (->> @tiles (filter (fn [[_ {:keys [visible?]}]] visible?)) (map (fn [[_ {:keys [pos]}]] pos))) pta (->> (sort-by #(utils/distance (utils/v+ % @board-pos) (dump-button-pos)) positions) first (utils/v+ @board-pos)) ptc (dump-button-pos) ptb (utils/v+ ((p/line pta ptc) 0.5) ((p/circle (* 4 gu)) (rand)))] (reset! dump-target-line (-> (path/bezier pta ptb ptc) (tf/style {:stroke-linecap "round" :fill "none" :stroke-width 7 :stroke "#EB838E" :opacity 0.3}))) (js/setTimeout #(reset! dump-target-line nil) 700))) (defn dump! [e] (let [ts @tiles positions (->> ts (filter (fn [[_ {:keys [visible?]}]] visible?)) (map (fn [[id {:keys [pos]}]] [id pos]))) to-dump (->> positions (sort-by #(utils/distance (utils/v+ (second %) @board-pos) (dump-button-pos))) first) to-show (->> ts (remove (fn [[_ {:keys [visible?]}]] visible?)) (map (fn [[id {:keys [pos]}]] id)) (take 3))] (doseq [to-show (map-indexed vector (sort to-show))] (let [position [(- (/ (ww) 2) (mod (/ (ww) 2) gu) (- gu) (* (first to-show) gu)) (- (wh) (mod (wh) gu) (* 2 gu))]] (swap! tiles assoc-in [(second to-show) :pos] (utils/v- position @board-pos)) (swap! tiles assoc-in [(second to-show) :visible?] true))) (swap! tiles assoc-in [(first to-dump) :visible?] false))) (defn dump-button [] (-> (el/g (-> (el/rect (* 2 tile-w) tile-w) (tf/style {:rx 5 :stroke "#9E6067" :stroke-width 1 :fill "#EB838E" :filter "drop-shadow(1px 1px 4px rgb(0 0 0 / 0.2))"})) (-> (el/text "DUMP") (tf/translate [0 3]) (tf/style {:fill "#9E6067" :opacity 1 :font-size (str (* 0.375 gu) "px") :font-family "Palatino" :style {:user-select "none" :-moz-user-select "none" :-webkit-user-select "none"}}))) (tf/translate (dump-button-pos)) (tf/style {:on-click dump! :on-touch-end dump! :on-mouse-over show-dump-target :on-touch-start show-dump-target}))) (defn add-button-pos [] [(/ (ww) 2) (- (wh) (* 0.625 gu))]) (defn add! [] (let [ts @tiles positions (->> ts (filter (fn [[_ {:keys [visible?]}]] visible?)) (map (fn [[id {:keys [pos]}]] [id pos]))) to-show (->> ts (remove (fn [[_ {:keys [visible?]}]] visible?)) (map (fn [[id {:keys [pos]}]] id)) (take 1))] (doseq [to-show (map-indexed vector (sort to-show))] (let [position [(- (/ (ww) 2) (mod (/ (ww) 2) gu) (- gu) (* (first to-show) gu)) (- (wh) (mod (wh) gu) (* 2 gu))]] (swap! tiles assoc-in [(second to-show) :pos] (utils/v- position @board-pos)) (swap! tiles assoc-in [(second to-show) :visible?] true))))) (defn add-button [] (-> (el/g (-> (el/rect (* 2 tile-w) tile-w) (tf/style {:rx 5 :stroke "#596B4C" :stroke-width 1 :fill "#C3EBA7" :filter "drop-shadow(1px 1px 4px rgb(0 0 0 / 0.2))"})) (-> (el/text "ADD") (tf/translate [0 3]) (tf/style {:fill "#596B4C" :opacity 1 :font-size (str (* 0.375 gu) "px") :font-family "Palatino" :style {:user-select "none" :-moz-user-select "none" :-webkit-user-select "none"}}))) (tf/translate (add-button-pos)) (tf/style {:on-click add! #_#_:on-touch-end add!}))) (defn share-button-pos [] [(- (ww) (* 1 gu)) (* 0.625 gu)]) (defn share! [] (let [text "ON CLIPBOARD"] (js/navigator.clipboard.writeText text))) (defn share-button [] (-> (el/g (-> (el/rect (* 2 tile-w) tile-w) (tf/style {:rx 5 :stroke "#596B4C" :stroke-width 1 :fill "#C3EBA7" :filter "drop-shadow(1px 1px 4px rgb(0 0 0 / 0.2))"})) (-> (el/text "SHARE") (tf/translate [0 3]) (tf/style {:fill "#596B4C" :opacity 1 :font-size (str (* 0.375 gu) "px") :font-family "Palatino" :style {:user-select "none" :-moz-user-select "none" :-webkit-user-select "none"}}))) (tf/translate (share-button-pos)) (tf/style {:on-click share! #_#_:on-touch-end add!}))) (def titles ["Wow, it's words!" "Oops, all letters!" "You've seen a crossword before, right?" "WWWWWWOOOOORRRDDDDS!" "I like word games, ok?" "Naming things is hard. This is a game with letters." "grid + letters = words + fun" "Clean up these tiles, please." "Grams. Grams. Grams." "Letters make words. Words are fun." "Do not tolerate intolerance." "My name is <NAME> and I've made this game for you (and me)." "Please be kind to other people."]) (def rand-title (first (shuffle titles))) (defn title [] (-> (el/text rand-title) (tf/translate [(/ (ww) 2) (* (wh) 0.4)]) (tf/style {:fill "#9E6067" :opacity 0.1 :font-size "40px" :font-family "Palatino" :style {:user-select "none" :-moz-user-select "none" :-webkit-user-select "none"}}))) (defn board [] (let [table (-> (el/rect (* 4 (ww)) (* 4 (wh))) (tf/translate [(* 2 (ww)) (* 2 (wh))]) (tf/style {:fill "#B2D8EB" :on-mouse-down (mouse-down-handler :board) :on-touch-start (touch-start-handler :board)}))] (-> (el/g table [title] ;; debug #_(-> (el/text (str @window)) (tf/translate [(/ (ww) 2) (/ (wh) 2)])) [wordlist] (el/g (map tile @tiles)) @dump-target-line [center-button] [add-button] [dump-button] #_[share-button]) (svg (ww) (wh)) (tf/style {:style {:position "absolute" :left 0 :top 0}})))) (defn app [] [:<> [board] [:span (str @board-pos)]]) (defn mount [app] (doseq [id (range 21)] (swap! tiles assoc-in [id :visible?] true)) (events/listen js/window EventType.MOUSEUP update-state!) (events/listen js/window EventType.TOUCHEND update-state!) (events/listen js/window EventType.RESIZE #(reset! window [js/window.innerWidth js/window.innerHeight])) (r/render-component [app] (js/document.getElementById "root"))) (defn init [] (mount app)) (defn ^:dev/after-load re-render [] (mount app))
true
(ns word-grid.app (:require [clojure.string :as str] [reagent.core :as r] [svg-clj.utils :as utils] [svg-clj.elements :as el] [svg-clj.path :as path] [svg-clj.transforms :as tf] [svg-clj.parametric :as p] [svg-clj.layout :as lo] [svg-clj.composites :as comp :refer [svg]] [goog.events :as events]) (:import [goog.events EventType])) ;; Constants and references (def tile-w 40) (def tile-pad 4) ;; grid-unit (def gu (+ tile-w tile-pad)) (def window (r/atom [js/window.innerWidth js/window.innerHeight])) (defn ww [] (first @window)) (defn wh [] (second @window)) ;; one tile -> {:pos [0 0] :letter "A"} (defn rect-grid [nx ny x-spacing y-spacing] (for [b (range ny) a (range nx)] [(* a x-spacing) (* b y-spacing)])) (def tiles (let [letters (shuffle (concat (repeat 13 "A") (repeat 3 "B") (repeat 3 "C") (repeat 6 "D") (repeat 18 "E") (repeat 3 "F") (repeat 4 "G") (repeat 3 "H") (repeat 12 "I") (repeat 2 "J") (repeat 2 "K") (repeat 5 "L") (repeat 3 "M") (repeat 8 "N") (repeat 11 "O") (repeat 3 "P") (repeat 2 "Q") (repeat 9 "R") (repeat 6 "S") (repeat 9 "T") (repeat 6 "U") (repeat 3 "V") (repeat 3 "W") (repeat 2 "X") (repeat 3 "Y") (repeat 2 "Z"))) f (fn [pos letter] {:pos pos :letter letter :visible? false}) wwh (Math/floor (/ (ww) 2)) whh (Math/floor (/ (wh) 2)) grid (->> (rect-grid 7 (Math/ceil (/ (count letters) 7)) gu gu) #_(partition 2) #_(map first) (map #(utils/v+ % [(/ gu 2) (/ gu 2)])) (map #(utils/v+ % [(* gu -3) (* gu -1)])) (map #(utils/v+ % [(- wwh (mod wwh gu)) (- whh (mod whh gu))]))) tiles (map f grid letters)] (r/atom (zipmap (range) tiles)))) (def board-pos (r/atom [(/ gu 2) (/ gu 2)])) ;; https://stackoverflow.com/a/25123243 (defn split-when [f s] (reduce (fn [acc [a b]] (if (f b a) (conj acc [b]) (update-in acc [(dec (count acc))] conj b))) [[(first s)]] (partition 2 1 s))) (defn- overlaps? [tiles] (->> tiles vals (filter :visible?) (map :pos) frequencies vals (some #(= 2 %)))) (defn- get-ids-by-pos [pos tiles] (let [ts (map (fn [[id tile]] (assoc tile :id id)) tiles)] (->> ts (filter #(= pos (:pos %))) (map :id)))) (defn- move-tile-down [id tiles] (update-in tiles [id :pos] #(utils/v+ % [0 gu]))) (defn fix-overlaps [tiles] (if (not (overlaps? tiles)) tiles (let [positions (map (fn [[_ {:keys [pos]}]] pos) tiles) overlap-ids (filter #(> (count %) 1) (map #(get-ids-by-pos % tiles) positions))] (recur (move-tile-down (first (first overlap-ids)) tiles))))) (defn fix-overlaps! [] (let [fixed (fix-overlaps @tiles)] (reset! tiles fixed))) (defn visible? [id] (get-in @tiles [id :visible?])) (defn snap-tiles! [] (let [snap-tile (fn [[x y]] [(Math/floor (- (+ x (/ gu 2.0)) (mod x gu))) (Math/floor (- (+ y (/ gu 2.0)) (mod y gu)))])] (doseq [id (filter visible? (range 145))] (swap! tiles update-in [id :pos] snap-tile)))) (defn update-state! [] (snap-tiles!) (fix-overlaps!)) (defn get-words [] (let [f (fn [[_ {:keys [pos letter visible?]}]] (when visible? {:x (int (/ (first pos) gu)) :y (int (/ (second pos) gu)) :letter letter})) rows (->> (map f @tiles) (remove nil?) (sort-by :y) (partition-by #(get % :y)) (map (fn [s] (sort-by :x s))) (mapcat #(split-when (fn [a b] (not= (:x a) (inc (:x b)))) %)) (map (fn [s] (apply str (map :letter s)))) (remove #(= 1 (count %)))) cols (->> (map f @tiles) (remove nil?) (sort-by :x) (partition-by #(get % :x)) (map (fn [s] (sort-by :y s))) (mapcat #(split-when (fn [a b] (not= (:y a) (inc (:y b)))) %)) (map (fn [s] (apply str (map :letter s)))) (remove #(= 1 (count %))))] {:horizontal rows :vertical cols})) ;; Utility functions (defn get-client-mid [evt] (let [r (.getBoundingClientRect (.-target evt)) left (.-left r) top (.-top r) bottom (.-bottom r) right (.-right r) w (- right left) h (- bottom top)] {:x (- right (/ w 2.0)) :y (- bottom (/ h 2.0))})) (defn prevent-motion [e] (js/window.scrollTo 0 0) (e.preventDefault) (e.stopPropagation)) (events/listen js/window EventType.SCROLL prevent-motion) (events/listen js/window EventType.TOUCHMOVE prevent-motion) ;; Event handlers (defn mouse-move-handler [id offset] (fn [evt] (let [cx (.-clientX evt) cy (.-clientY evt) ox (:x offset) oy (:y offset)] (if (= id :board) (reset! board-pos [(Math/floor (- cx ox)) (Math/floor (- cy oy))]) (swap! tiles assoc-in [id :pos] [(Math/floor (- cx ox)) (Math/floor (- cy oy))]))))) (defn mouse-up-handler [on-move] (fn me [evt] (events/unlisten js/window EventType.MOUSEMOVE on-move))) (defn mouse-down-handler [id] (fn [e] (let [{:keys [x y] :as mid} (get-client-mid e) [bx by] (utils/v* [-1 -1] @board-pos) cx (.-clientX e) cy (.-clientY e) offset (if (= id :board) {:x (+ cx bx) :y (+ cy by)} {:x (- cx (when-not (= id :board) x) bx) :y (- cy (when-not (= id :board) y) by)}) on-move (mouse-move-handler id offset)] (events/listen js/window EventType.MOUSEMOVE on-move) (events/listen js/window EventType.MOUSEUP (mouse-up-handler on-move))))) (defn touch-move-handler [id offset] (fn [evt] (let [cx (.-clientX evt) cy (.-clientY evt) ox (:x offset) oy (:y offset)] (if (= id :board) (reset! board-pos [(Math/floor (- cx ox)) (Math/floor (- cy oy))]) (swap! tiles assoc-in [id :pos] [(Math/floor (- cx ox)) (Math/floor (- cy oy))]))))) (defn touch-end-handler [on-move] (fn te [evt] (events/unlisten js/window EventType.TOUCHMOVE on-move))) (defn touch-start-handler [id] (fn [e] (let [{:keys [x y] :as mid} (get-client-mid e) [bx by] (utils/v* [-1 -1] @board-pos) cx (.-pageX (first (.-changedTouches e))) cy (.-pageY (first (.-changedTouches e))) offset (if (= id :board) {:x (+ cx bx) :y (+ cy by)} {:x (- cx (when-not (= id :board) x) bx) :y (- cy (when-not (= id :board) y) by)}) on-move (touch-move-handler id offset)] (e.preventDefault) (events/listen js/window EventType.TOUCHMOVE on-move) (events/listen js/window EventType.TOUCHEND (touch-end-handler on-move))))) ;; components (defn tile [[id {:keys [pos letter visible?]}]] (when visible? (-> (el/g #_(el/g (for [i (reverse (range 0 4))] (-> (el/rect tile-w tile-w) (tf/translate [(* i 0.8) i]) (tf/style {:rx 5 :fill "#EBE89A" :stroke "#9E9C59" :stroke-width 1.5})))) (-> (el/rect tile-w tile-w) (tf/style {:rx 5 :fill "#EBE89A" :stroke "#9E9C59" :stroke-width 1 #_#_:filter "drop-shadow(1px 1px 4px rgb(0 0 0 / 0.2))"})) #_(el/text (str pos)) (-> (el/text letter) (tf/translate [0 4]) (tf/style {:fill "#9E6067" :font-size (str (* 0.625 gu) "px") :font-family "Palatino" :style {:user-select "none" :-moz-user-select "none" :-webkit-user-select "none"}}))) (tf/translate (utils/v+ pos @board-pos)) (tf/style {:on-mouse-down (mouse-down-handler id) :on-touch-start (touch-start-handler id)})))) (defn wordlist [] (let [scrabble-finder-url "https://scrabble.merriam.com/finder/" {:keys [horizontal vertical]} (get-words) lh 20 vlist-offset (* (+ 3 (count horizontal)) lh) f (fn [pos] (fn [idx t] [:a {:key idx :xlinkHref (str scrabble-finder-url t) :target "_blank"} (-> (el/text t) (tf/translate pos) (tf/translate [0 (* idx lh)]) (tf/style {:fill "#9E6067" :text-decoration "underline"}))]))] (el/g (-> (el/text "HORIZONTAL:") (tf/translate [50 lh])) (map-indexed (f [50 (* 2 lh)]) horizontal) (-> (el/text "VERTICAL:") (tf/translate [50 vlist-offset])) (map-indexed (f [50 (+ lh vlist-offset)]) vertical)))) (defn center-button-pos [] [(* 1 gu) (- (wh) (* 0.625 gu))]) (defn center! [e] (reset! board-pos [0 0])) (defn center-button [] (-> (el/g (-> (el/rect (* 2 tile-w) tile-w) (tf/style {:rx 5 :stroke "#596B4C" :stroke-width 1 :fill "#C3EBA7" :filter "drop-shadow(1px 1px 4px rgb(0 0 0 / 0.2))"})) (-> (el/text "CENTER") (tf/translate [0 3]) (tf/style {:fill "#596B4C" :opacity 1 :font-size (str (* 0.375 gu) "px") :font-family "Palatino" :style {:user-select "none" :-moz-user-select "none" :-webkit-user-select "none"}}))) (tf/translate (center-button-pos)) (tf/style {:on-click center! #_#_:on-touch-start center!}))) (def dump-target-line (r/atom nil)) (defn dump-button-pos [] [(- (ww) (* 1 gu)) (- (wh) (* 0.625 gu))]) (defn show-dump-target [e] (let [positions (->> @tiles (filter (fn [[_ {:keys [visible?]}]] visible?)) (map (fn [[_ {:keys [pos]}]] pos))) pta (->> (sort-by #(utils/distance (utils/v+ % @board-pos) (dump-button-pos)) positions) first (utils/v+ @board-pos)) ptc (dump-button-pos) ptb (utils/v+ ((p/line pta ptc) 0.5) ((p/circle (* 4 gu)) (rand)))] (reset! dump-target-line (-> (path/bezier pta ptb ptc) (tf/style {:stroke-linecap "round" :fill "none" :stroke-width 7 :stroke "#EB838E" :opacity 0.3}))) (js/setTimeout #(reset! dump-target-line nil) 700))) (defn dump! [e] (let [ts @tiles positions (->> ts (filter (fn [[_ {:keys [visible?]}]] visible?)) (map (fn [[id {:keys [pos]}]] [id pos]))) to-dump (->> positions (sort-by #(utils/distance (utils/v+ (second %) @board-pos) (dump-button-pos))) first) to-show (->> ts (remove (fn [[_ {:keys [visible?]}]] visible?)) (map (fn [[id {:keys [pos]}]] id)) (take 3))] (doseq [to-show (map-indexed vector (sort to-show))] (let [position [(- (/ (ww) 2) (mod (/ (ww) 2) gu) (- gu) (* (first to-show) gu)) (- (wh) (mod (wh) gu) (* 2 gu))]] (swap! tiles assoc-in [(second to-show) :pos] (utils/v- position @board-pos)) (swap! tiles assoc-in [(second to-show) :visible?] true))) (swap! tiles assoc-in [(first to-dump) :visible?] false))) (defn dump-button [] (-> (el/g (-> (el/rect (* 2 tile-w) tile-w) (tf/style {:rx 5 :stroke "#9E6067" :stroke-width 1 :fill "#EB838E" :filter "drop-shadow(1px 1px 4px rgb(0 0 0 / 0.2))"})) (-> (el/text "DUMP") (tf/translate [0 3]) (tf/style {:fill "#9E6067" :opacity 1 :font-size (str (* 0.375 gu) "px") :font-family "Palatino" :style {:user-select "none" :-moz-user-select "none" :-webkit-user-select "none"}}))) (tf/translate (dump-button-pos)) (tf/style {:on-click dump! :on-touch-end dump! :on-mouse-over show-dump-target :on-touch-start show-dump-target}))) (defn add-button-pos [] [(/ (ww) 2) (- (wh) (* 0.625 gu))]) (defn add! [] (let [ts @tiles positions (->> ts (filter (fn [[_ {:keys [visible?]}]] visible?)) (map (fn [[id {:keys [pos]}]] [id pos]))) to-show (->> ts (remove (fn [[_ {:keys [visible?]}]] visible?)) (map (fn [[id {:keys [pos]}]] id)) (take 1))] (doseq [to-show (map-indexed vector (sort to-show))] (let [position [(- (/ (ww) 2) (mod (/ (ww) 2) gu) (- gu) (* (first to-show) gu)) (- (wh) (mod (wh) gu) (* 2 gu))]] (swap! tiles assoc-in [(second to-show) :pos] (utils/v- position @board-pos)) (swap! tiles assoc-in [(second to-show) :visible?] true))))) (defn add-button [] (-> (el/g (-> (el/rect (* 2 tile-w) tile-w) (tf/style {:rx 5 :stroke "#596B4C" :stroke-width 1 :fill "#C3EBA7" :filter "drop-shadow(1px 1px 4px rgb(0 0 0 / 0.2))"})) (-> (el/text "ADD") (tf/translate [0 3]) (tf/style {:fill "#596B4C" :opacity 1 :font-size (str (* 0.375 gu) "px") :font-family "Palatino" :style {:user-select "none" :-moz-user-select "none" :-webkit-user-select "none"}}))) (tf/translate (add-button-pos)) (tf/style {:on-click add! #_#_:on-touch-end add!}))) (defn share-button-pos [] [(- (ww) (* 1 gu)) (* 0.625 gu)]) (defn share! [] (let [text "ON CLIPBOARD"] (js/navigator.clipboard.writeText text))) (defn share-button [] (-> (el/g (-> (el/rect (* 2 tile-w) tile-w) (tf/style {:rx 5 :stroke "#596B4C" :stroke-width 1 :fill "#C3EBA7" :filter "drop-shadow(1px 1px 4px rgb(0 0 0 / 0.2))"})) (-> (el/text "SHARE") (tf/translate [0 3]) (tf/style {:fill "#596B4C" :opacity 1 :font-size (str (* 0.375 gu) "px") :font-family "Palatino" :style {:user-select "none" :-moz-user-select "none" :-webkit-user-select "none"}}))) (tf/translate (share-button-pos)) (tf/style {:on-click share! #_#_:on-touch-end add!}))) (def titles ["Wow, it's words!" "Oops, all letters!" "You've seen a crossword before, right?" "WWWWWWOOOOORRRDDDDS!" "I like word games, ok?" "Naming things is hard. This is a game with letters." "grid + letters = words + fun" "Clean up these tiles, please." "Grams. Grams. Grams." "Letters make words. Words are fun." "Do not tolerate intolerance." "My name is PI:NAME:<NAME>END_PI and I've made this game for you (and me)." "Please be kind to other people."]) (def rand-title (first (shuffle titles))) (defn title [] (-> (el/text rand-title) (tf/translate [(/ (ww) 2) (* (wh) 0.4)]) (tf/style {:fill "#9E6067" :opacity 0.1 :font-size "40px" :font-family "Palatino" :style {:user-select "none" :-moz-user-select "none" :-webkit-user-select "none"}}))) (defn board [] (let [table (-> (el/rect (* 4 (ww)) (* 4 (wh))) (tf/translate [(* 2 (ww)) (* 2 (wh))]) (tf/style {:fill "#B2D8EB" :on-mouse-down (mouse-down-handler :board) :on-touch-start (touch-start-handler :board)}))] (-> (el/g table [title] ;; debug #_(-> (el/text (str @window)) (tf/translate [(/ (ww) 2) (/ (wh) 2)])) [wordlist] (el/g (map tile @tiles)) @dump-target-line [center-button] [add-button] [dump-button] #_[share-button]) (svg (ww) (wh)) (tf/style {:style {:position "absolute" :left 0 :top 0}})))) (defn app [] [:<> [board] [:span (str @board-pos)]]) (defn mount [app] (doseq [id (range 21)] (swap! tiles assoc-in [id :visible?] true)) (events/listen js/window EventType.MOUSEUP update-state!) (events/listen js/window EventType.TOUCHEND update-state!) (events/listen js/window EventType.RESIZE #(reset! window [js/window.innerWidth js/window.innerHeight])) (r/render-component [app] (js/document.getElementById "root"))) (defn init [] (mount app)) (defn ^:dev/after-load re-render [] (mount app))
[ { "context": "t-db]]))\n\n(t/deftest test-q\n (let [db [[0 :name \"Peter\"]\n [0 :age 40]\n [0 :likes \"", "end": 232, "score": 0.9998257160186768, "start": 227, "tag": "NAME", "value": "Peter" }, { "context": " [0 :likes \"Pizza\"]\n [1 :name \"Erik\"]\n [1 :likes \"Pizza\"]\n [1 :", "end": 316, "score": 0.9998341798782349, "start": 312, "tag": "NAME", "value": "Erik" }, { "context": "q {:find [?e]\n :where [[?e :name (or \"Peter\" \"Erik\")]]} db)\n [[0] [1]])\n\n (is= (q ", "end": 719, "score": 0.9998217821121216, "start": 714, "tag": "NAME", "value": "Peter" }, { "context": " [?e]\n :where [[?e :name (or \"Peter\" \"Erik\")]]} db)\n [[0] [1]])\n\n (is= (q {:find ", "end": 726, "score": 0.9998341798782349, "start": 722, "tag": "NAME", "value": "Erik" }, { "context": "(let [db (create-got-db)\n noble-def-cmd [[\"Renly Baratheon\" \"nobel\"]\n [\"Randyll Tarly\"", "end": 938, "score": 0.9998941421508789, "start": 923, "tag": "NAME", "value": "Renly Baratheon" }, { "context": "enly Baratheon\" \"nobel\"]\n [\"Randyll Tarly\" \"nobel\"]\n [\"Mathis Rowan\" ", "end": 987, "score": 0.9998753070831299, "start": 974, "tag": "NAME", "value": "Randyll Tarly" }, { "context": "\"Randyll Tarly\" \"nobel\"]\n [\"Mathis Rowan\" \"nobel\"]\n [\"Cortnay Penros", "end": 1035, "score": 0.9998853206634521, "start": 1023, "tag": "NAME", "value": "Mathis Rowan" }, { "context": "[\"Mathis Rowan\" \"nobel\"]\n [\"Cortnay Penrose\" \"nobel\"]\n [\"Loras Tyrell\" ", "end": 1086, "score": 0.9998807907104492, "start": 1071, "tag": "NAME", "value": "Cortnay Penrose" }, { "context": "ortnay Penrose\" \"nobel\"]\n [\"Loras Tyrell\" \"nobel\"]]]\n (is=\n \"simply test multiple j", "end": 1134, "score": 0.9998734593391418, "start": 1122, "tag": "NAME", "value": "Loras Tyrell" } ]
test/clj/lhrb/query_test.clj
lhrb/datahog
3
(ns lhrb.query-test (:require [lhrb.query :as sut :refer [q]] [clojure.test :as t] [lhrb.test :refer [is=]] [lhrb.readcsv :refer [create-got-db]])) (t/deftest test-q (let [db [[0 :name "Peter"] [0 :age 40] [0 :likes "Pizza"] [1 :name "Erik"] [1 :likes "Pizza"] [1 :age 30] [2 :age 40] [2 :likes "Pizza"]]] (is= (q {:find [?e] :where [[?e :likes "Pizza"]]} db) [[2] [1] [0]]) (is= (q {:find [?e] :where [[?e :likes "Pizza"] [?e :age 40]]} db) [[2] [0]]) (is= (q {:find [?e] :where [[?e :name (or "Peter" "Erik")]]} db) [[0] [1]]) (is= (q {:find [?e] :where [[?e :age (> ?a 30)]]} db) [[0] [2]]))) (t/deftest got-test (let [db (create-got-db) noble-def-cmd [["Renly Baratheon" "nobel"] ["Randyll Tarly" "nobel"] ["Mathis Rowan" "nobel"] ["Cortnay Penrose" "nobel"] ["Loras Tyrell" "nobel"]]] (is= "simply test multiple joins" (q {:find [?name ?noble] :where [[?b :battle/location "Storm's End"] [?b :battle/defender_commander ?name] [?p :char/Name ?name] [?p :char/Nobility ?noble]]} db) noble-def-cmd) (is= "test 'or' clause. Expect to find two names." (count (q {:find [?e] :where [[?e :char/Name (or "Randa" "Drogo")]]} db)) 2)))
69001
(ns lhrb.query-test (:require [lhrb.query :as sut :refer [q]] [clojure.test :as t] [lhrb.test :refer [is=]] [lhrb.readcsv :refer [create-got-db]])) (t/deftest test-q (let [db [[0 :name "<NAME>"] [0 :age 40] [0 :likes "Pizza"] [1 :name "<NAME>"] [1 :likes "Pizza"] [1 :age 30] [2 :age 40] [2 :likes "Pizza"]]] (is= (q {:find [?e] :where [[?e :likes "Pizza"]]} db) [[2] [1] [0]]) (is= (q {:find [?e] :where [[?e :likes "Pizza"] [?e :age 40]]} db) [[2] [0]]) (is= (q {:find [?e] :where [[?e :name (or "<NAME>" "<NAME>")]]} db) [[0] [1]]) (is= (q {:find [?e] :where [[?e :age (> ?a 30)]]} db) [[0] [2]]))) (t/deftest got-test (let [db (create-got-db) noble-def-cmd [["<NAME>" "nobel"] ["<NAME>" "nobel"] ["<NAME>" "nobel"] ["<NAME>" "nobel"] ["<NAME>" "nobel"]]] (is= "simply test multiple joins" (q {:find [?name ?noble] :where [[?b :battle/location "Storm's End"] [?b :battle/defender_commander ?name] [?p :char/Name ?name] [?p :char/Nobility ?noble]]} db) noble-def-cmd) (is= "test 'or' clause. Expect to find two names." (count (q {:find [?e] :where [[?e :char/Name (or "Randa" "Drogo")]]} db)) 2)))
true
(ns lhrb.query-test (:require [lhrb.query :as sut :refer [q]] [clojure.test :as t] [lhrb.test :refer [is=]] [lhrb.readcsv :refer [create-got-db]])) (t/deftest test-q (let [db [[0 :name "PI:NAME:<NAME>END_PI"] [0 :age 40] [0 :likes "Pizza"] [1 :name "PI:NAME:<NAME>END_PI"] [1 :likes "Pizza"] [1 :age 30] [2 :age 40] [2 :likes "Pizza"]]] (is= (q {:find [?e] :where [[?e :likes "Pizza"]]} db) [[2] [1] [0]]) (is= (q {:find [?e] :where [[?e :likes "Pizza"] [?e :age 40]]} db) [[2] [0]]) (is= (q {:find [?e] :where [[?e :name (or "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI")]]} db) [[0] [1]]) (is= (q {:find [?e] :where [[?e :age (> ?a 30)]]} db) [[0] [2]]))) (t/deftest got-test (let [db (create-got-db) noble-def-cmd [["PI:NAME:<NAME>END_PI" "nobel"] ["PI:NAME:<NAME>END_PI" "nobel"] ["PI:NAME:<NAME>END_PI" "nobel"] ["PI:NAME:<NAME>END_PI" "nobel"] ["PI:NAME:<NAME>END_PI" "nobel"]]] (is= "simply test multiple joins" (q {:find [?name ?noble] :where [[?b :battle/location "Storm's End"] [?b :battle/defender_commander ?name] [?p :char/Name ?name] [?p :char/Nobility ?noble]]} db) noble-def-cmd) (is= "test 'or' clause. Expect to find two names." (count (q {:find [?e] :where [[?e :char/Name (or "Randa" "Drogo")]]} db)) 2)))
[ { "context": "[s :s_nationkey n]\n [n :n_name \"SAUDI ARABIA\"]]\n :order-by [[(count l1) :desc] [s_n", "end": 22862, "score": 0.9997763633728027, "start": 22850, "tag": "NAME", "value": "SAUDI ARABIA" } ]
crux-bench/src/crux/bench/tpch_test.clj
deobald/crux
0
(ns crux.bench.tpch-test (:require [crux.bench :as bench] [crux.api :as crux] [clojure.tools.logging :as log] [crux.fixtures.tpch :as tpch] [clojure.edn :as edn] [clojure.instant :as i] [clojure.java.io :as io] [clojure.string :as str] [clojure.test :as t])) (declare tpch-queries parse-tpch-result validate-tpch-query) (defn run-tpch-query [node n] (crux/q (crux/db node) (assoc (get tpch-queries (dec n)) :timeout 120000))) (defn run-tpch-test [node {:keys [scale-factor] :as opts}] (let [scale-factor (or scale-factor 0.01)] (bench/with-bench-ns :tpch-test (bench/with-crux-dimensions (bench/run-bench :ingest (bench/with-additional-index-metrics node (tpch/load-docs! node scale-factor tpch/tpch-entity->pkey-doc))) ;; TODO we may want to split this up, à la WatDiv, so that we can see if ;; specific queries are slower than our comparison databases (bench/run-bench :queries {:success? (every? true? (for [n (range 1 23)] (let [actual (run-tpch-query node n)] (if (= 0.01 scale-factor) (every? true? (validate-tpch-query actual (parse-tpch-result n))) (boolean actual)))))}))))) ;; "Elapsed time: 21994.835831 msecs" (def q1 '{:find [l_returnflag l_linestatus (sum l_quantity) (sum l_extendedprice) (sum ret_2) (sum ret_4) (avg l_quantity) (avg l_extendedprice) (avg l_discount) (count l)] :where [[l :l_shipdate l_shipdate] [l :l_quantity l_quantity] [l :l_extendedprice l_extendedprice] [l :l_discount l_discount] [l :l_tax l_tax] [l :l_returnflag l_returnflag] [l :l_linestatus l_linestatus] [(<= l_shipdate #inst "1998-09-02")] [(- 1 l_discount) ret_1] [(* l_extendedprice ret_1) ret_2] [(+ 1 l_tax) ret_3] [(* ret_2 ret_3) ret_4]] :order-by [[l_returnflag :asc] [l_linestatus :asc]]}) ;; "Elapsed time: 1304.42464 msecs" (def q2 '{:find [s_acctbal s_name n_name p p_mfgr s_address s_phone s_comment] :where [[p :p_mfgr p_mfgr] [p :p_size 15] [p :p_type p_type] [(re-find #"^.*BRASS$" p_type)] [ps :ps_partkey p] [ps :ps_supplycost ps_supplycost] [(q {:find [(min ps_supplycost)] :in [$ p] :where [[ps :ps_partkey p] [ps :ps_supplycost ps_supplycost] [ps :ps_suppkey s] [s :s_nationkey n] [n :n_regionkey r] [r :r_name "EUROPE"]]} p) [[ps_supplycost]]] [ps :ps_suppkey s] [s :s_acctbal s_acctbal] [s :s_address s_address] [s :s_name s_name] [s :s_phone s_phone] [s :s_comment s_comment] [n :n_name n_name] [s :s_nationkey n] [n :n_regionkey r] [r :r_name "EUROPE"]] :order-by [[s_acctbal :desc] [n_name :asc] [s_name :asc] [p :asc]] :limit 100}) ;; "Elapsed time: 5786.047011 msecs" (def q3 '{:find [o (sum ret_2) o_orderdate o_shippriority] :where [[c :c_mktsegment "BUILDING"] [o :o_custkey c] [o :o_shippriority o_shippriority] [o :o_orderdate o_orderdate] [(< o_orderdate #inst "1995-03-15")] [l :l_orderkey o] [l :l_discount l_discount] [l :l_extendedprice l_extendedprice] [l :l_shipdate l_shipdate] [(> l_shipdate #inst "1995-03-15")] [(- 1 l_discount) ret_1] [(* l_extendedprice ret_1) ret_2]] :order-by [[(sum ret_2) :desc] [o_orderdate :asc]] :limit 10}) ;; "Elapsed time: 1292.874285 msecs" (def q4 '{:find [o_orderpriority (count o)] :where [[o :o_orderdate o_orderdate] [o :o_orderpriority o_orderpriority] [(>= o_orderdate #inst "1993-07-01")] [(< o_orderdate #inst "1993-10-01")] (or-join [o] (and [l :l_orderkey o] [l :l_commitdate l_commitdate] [l :l_receiptdate l_receiptdate] [(< l_commitdate l_receiptdate)]))] :order-by [[o_orderpriority :asc]]}) ;; "Elapsed time: 5319.179341 msecs" (def q5 '{:find [n_name (sum ret_2)] :where [[o :o_custkey c] [l :l_orderkey o] [l :l_suppkey s] [s :s_nationkey n] [c :c_nationkey n] [n :n_name n_name] [n :n_regionkey r] [r :r_name "ASIA"] [l :l_extendedprice l_extendedprice] [l :l_discount l_discount] [o :o_orderdate o_orderdate] [(>= o_orderdate #inst "1994-01-01")] [(< o_orderdate #inst "1995-01-01")] [(- 1 l_discount) ret_1] [(* l_extendedprice ret_1) ret_2]] :order-by [[(sum ret_2) :desc]]}) ;; "Elapsed time: 1773.63273 msecs" (def q6 '{:find [(sum ret_1)] :where [[l :l_shipdate l_shipdate] [l :l_quantity l_quantity] [l :l_extendedprice l_extendedprice] [l :l_discount l_discount] [(>= l_shipdate #inst "1994-01-01")] [(< l_shipdate #inst "1995-01-01")] [(>= l_discount 0.05)] [(<= l_discount 0.07)] [(< l_quantity 24.0)] [(* l_extendedprice l_discount) ret_1]]}) ;; "Elapsed time: 58567.852989 msecs" (def q7 '{:find [supp_nation cust_nation l_year (sum ret_2)] :where [[o :o_custkey c] [l :l_orderkey o] [l :l_suppkey s] [s :s_nationkey n1] [n1 :n_name supp_nation] [c :c_nationkey n2] [n2 :n_name cust_nation] (or (and [n1 :n_name "FRANCE"] [n2 :n_name "GERMANY"]) (and [n1 :n_name "GERMANY"] [n2 :n_name "FRANCE"])) [l :l_shipdate l_shipdate] [l :l_discount l_discount] [l :l_extendedprice l_extendedprice] [(>= l_shipdate #inst "1995-01-01")] [(<= l_shipdate #inst "1996-12-31")] [(- 1 l_discount) ret_1] [(* l_extendedprice ret_1) ret_2] [(pr-str l_shipdate) ret_3] [(subs ret_3 7 11) l_year]] :order-by [[supp_nation :asc] [cust_nation :asc] [l_year :asc]]}) ;; "Elapsed time: 22993.637183 msecs" (def q8 '{:find [o_year mkt_share] :where [[(q {:find [o_year (sum brazil_volume) (sum volume)] :where [[(q {:find [o_year (sum ret_2) nation] :where [[o :o_custkey c] [l :l_orderkey o] [l :l_suppkey s] [l :l_partkey p] [c :c_nationkey n1] [n1 :n_regionkey r1] [r1 :r_name "AMERICA"] [s :s_nationkey n2] [n2 :n_name nation] [l :l_discount l_discount] [l :l_extendedprice l_extendedprice] [o :o_orderdate o_orderdate] [(>= o_orderdate #inst "1995-01-01")] [(<= o_orderdate #inst "1996-12-31")] [p :p_type "ECONOMY ANODIZED STEEL"] [(- 1 l_discount) ret_1] [(* l_extendedprice ret_1) ret_2] [(pr-str o_orderdate) ret_3] [(subs ret_3 7 11) o_year]]}) [[o_year volume nation]]] [(hash-map "BRAZIL" volume) brazil_lookup] [(get brazil_lookup nation 0) brazil_volume]]}) [[o_year brazil_volume volume]]] [(/ brazil_volume volume) mkt_share]] :order-by [[o_year :asc]]}) ;; "Elapsed time: 10066.352268 msecs" (def q9 '{:find [nation o_year (sum ret_4)] :where [[l :l_orderkey o] [l :l_suppkey s] [l :l_partkey p] [ps :ps_partkey p] [ps :ps_suppkey s] [ps :ps_supplycost ps_supplycost] [s :s_nationkey n] [n :n_name nation] [p :p_name p_name] [(re-find #".*green.*" p_name)] [l :l_quantity l_quantity] [l :l_discount l_discount] [l :l_extendedprice l_extendedprice] [o :o_orderdate o_orderdate] [(- 1 l_discount) ret_1] [(* l_extendedprice ret_1) ret_2] [(* ps_supplycost l_quantity) ret_3] [(- ret_2 ret_3) ret_4] [(pr-str o_orderdate) ret_5] [(subs ret_5 7 11) o_year]] :order-by [[nation :asc] [o_year :desc]]}) ;; "Elapsed time: 8893.984112 msecs" (def q10 '{:find [c c_name (sum ret_2) c_acctbal n_name c_address c_phone c_comment] :where [[o :o_custkey c] [l :l_orderkey o] [c :c_nationkey n] [n :n_name n_name] [c :c_name c_name] [c :c_acctbal c_acctbal] [c :c_address c_address] [c :c_phone c_phone] [c :c_comment c_comment] [l :l_extendedprice l_extendedprice] [l :l_discount l_discount] [o :o_orderdate o_orderdate] [(>= o_orderdate #inst "1993-10-01")] [(< o_orderdate #inst "1994-01-01")] [l :l_returnflag "R"] [(- 1 l_discount) ret_1] [(* l_extendedprice ret_1) ret_2]] :order-by [[(sum ret_2) :desc]] :limit 20}) ;; "Elapsed time: 190.177707 msecs" (def q11 '{:find [ps_partkey value] :where [[(q {:find [(sum ret_1)] :where [[ps :ps_availqty ps_availqty] [ps :ps_supplycost ps_supplycost] [ps :ps_suppkey s] [s :s_nationkey n] [n :n_name "GERMANY"] [(* ps_supplycost ps_availqty) ret_1]]}) [[ret_1]]] [(q {:find [ps_partkey (sum ret_1)] :where [[ps :ps_availqty ps_availqty] [ps :ps_supplycost ps_supplycost] [ps :ps_partkey ps_partkey] [ps :ps_suppkey s] [s :s_nationkey n] [n :n_name "GERMANY"] [(* ps_supplycost ps_availqty) ret_1]]}) [[ps_partkey value]]] [(* 0.0001 ret_1) ret_2] [(> value ret_2)]] :order-by [[value :desc]]}) ;; "Elapsed time: 4115.160435 msecs" (def q12 '{:find [l_shipmode (sum high_line_count) (sum low_line_count)] :where [[l :l_orderkey o] [l :l_receiptdate l_receiptdate] [l :l_commitdate l_commitdate] [l :l_shipdate l_shipdate] [(>= l_receiptdate #inst "1994-01-01")] [(< l_receiptdate #inst "1995-01-01")] [(< l_commitdate l_receiptdate)] [(< l_shipdate l_commitdate)] [l :l_shipmode l_shipmode] [l :l_shipmode #{"MAIL" "SHIP"}] [o :o_orderpriority o_orderpriority] [(get {"1-URGENT" [1 0] "2-HIGH" [1 0]} o_orderpriority [0 1]) [high_line_count low_line_count]]] :order-by [[l_shipmode :asc]]}) ;; "Elapsed time: 2187.862433 msecs" (def q13 '{:find [c_count (count c_count)] :where [(or [(q {:find [c (count o)] :where [[o :o_custkey c] [o :o_comment o_comment] (not [(re-find #".*special.*requests.*" o_comment)])]}) [[c c_count]]] (and [c :c_custkey] (not [_ :o_custkey c]) [(identity 0) c_count]))] :order-by [[(count c_count) :desc] [c_count :desc]]}) ;; "Elapsed time: 12734.7558 msecs" (def q14 '{:find [promo_revenue] :where [[(q {:find [(sum ret_3) (sum ret_2)] :where [[l :l_partkey p] [p :p_type p_type] [l :l_shipdate l_shipdate] [l :l_extendedprice l_extendedprice] [l :l_discount l_discount] [(>= l_shipdate #inst "1995-09-01")] [(< l_shipdate #inst "1995-10-01")] [(- 1 l_discount) ret_1] [(* l_extendedprice ret_1) ret_2] [(clojure.string/starts-with? p_type "PROMO") promo?] [(hash-map true ret_2) promo_lookup] [(get promo_lookup promo? 0) ret_3]]}) [[promo not_promo]]] [(/ promo not_promo) ret_1] [(* 100 ret_1) promo_revenue]]}) ;; "Elapsed time: 5651.664312 msecs" (def q15 '{:find [s s_name s_address s_phone total_revenue] :where [[(q {:find [s (sum ret_2)] :where [[l :l_suppkey s] [l :l_shipdate l_shipdate] [l :l_extendedprice l_extendedprice] [l :l_discount l_discount] [(>= l_shipdate #inst "1996-01-01")] [(< l_shipdate #inst "1996-04-01")] [(- 1 l_discount) ret_1] [(* l_extendedprice ret_1) ret_2]]}) revenue] [(q {:find [(max total_revenue)] :in [$ [[_ total_revenue]]]} revenue) [[total_revenue]]] [(identity revenue) [[s total_revenue]]] [s :s_name s_name] [s :s_address s_address] [s :s_phone s_phone]]}) ;; "Elapsed time: 357.971209 msecs" (def q16 '{:find [p_brand p_type p_size (count-distinct s)] :where [[p :p_brand p_brand] [(not= p_brand "Brand#45")] [p :p_type p_type] (not [(re-find #"^MEDIUM POLISHED.*" p_type)]) [p :p_size p_size] [p :p_size #{49 14 23 45 19 3 36 9}] [ps :ps_partkey p] [ps :ps_suppkey s] (not-join [s] [s :s_comment s_comment] [(re-find #".*Customer.*Complaints.*" s_comment)])] :order-by [[(count-distinct s) :desc] [p_brand :asc] [p_type :asc] [p_size :asc]]}) ;; "Elapsed time: 7.41559 msecs" -- unclear if this works, as it returns nothing. (def q17 '{:find [avg_yearly] :where [[(q {:find [(sum l_extendedprice)] :where [[p :p_brand "Brand#23"] [p :p_container "MED BOX"] [l :l_partkey p] [(q {:find [(avg l_quantity)] :in [$ p] :where [[l :l_partkey p] [l :l_quantity l_quantity]]} p) [[avg_quantity]]] [(* 0.2 avg_quantity) ret_1] [l :l_quantity l_quantity] [(< l_quantity ret_1)] [l :l_extendedprice l_extendedprice]]}) [[sum_extendedprice]]] [(/ sum_extendedprice 7.0) avg_yearly]]}) ;; "Elapsed time: 13222.491411 msecs" (def q18 '{:find [c_name c o o_orderdate o_totalprice (sum l_quantity)] :where [[(q {:find [o (sum l_quantity)] :where [[l :l_orderkey o] [l :l_quantity l_quantity]]}) [[o sum_quantity]]] [(> sum_quantity 300.0)] [o :o_custkey c] [c :c_name c_name] [o :o_orderdate o_orderdate] [o :o_totalprice o_totalprice] [l :l_orderkey o] [l :l_quantity l_quantity]] :order-by [[o_totalprice :desc] [o_orderdate :asc]] :limit 100}) ;; "Elapsed time: 4693.23977 msecs" (def q19 '{:find [(sum ret_2)] :where [[l :l_shipmode #{"AIR" "AIR REG"}] [l :l_shipinstruct "DELIVER IN PERSON"] [l :l_discount l_discount] [l :l_extendedprice l_extendedprice] [l :l_partkey p] [l :l_quantity l_quantity] [p :p_size p_size] (or (and [p :p_brand "Brand#12"] [p :p_container #{"SM CASE" "SM BOX" "SM PACK" "SM PKG"}] [(>= l_quantity 1.0)] [(<= l_quantity 11.0)] [(>= p_size 1)] [(<= p_size 5)]) (and [p :p_brand "Brand#23"] [p :p_container #{"MED BAG" "MED BOX" "MED PKG" "MED PACK"}] [(>= l_quantity 10.0)] [(<= l_quantity 20.0)] [(>= p_size 1)] [(<= p_size 10)]) (and [p :p_brand "Brand#34"] [p :p_container #{"LG CASE" "LG BOX" "LG PACK" "LG PKG"}] [(>= l_quantity 20.0)] [(<= l_quantity 30.0)] [(>= p_size 1)] [(<= p_size 15)])) [(- 1 l_discount) ret_1] [(* l_extendedprice ret_1) ret_2]]}) ;; "Elapsed time: 1607.843909 msecs" (def q20 '{:find [s_name s_address] :where [[ps :ps_suppkey s] [ps :ps_partkey p] [p :p_name p_name] [(re-find #"^forest.*" p_name)] [(q {:find [(sum l_quantity)] :in [$ p s] :where [[l :l_partkey p] [l :l_suppkey s] [l :l_shipdate l_shipdate] [(>= l_shipdate #inst "1994-01-01")] [(< l_shipdate #inst "1995-01-01")] [l :l_quantity l_quantity]]} p s) [[sum_quantity]]] [(* sum_quantity 0.5) ret_1] [(long ret_1) ret_2] [ps :ps_availqty ps_availqty] [(> ps_availqty ret_2)] [s :s_name s_name] [s :s_address s_address] [s :s_nationkey n] [n :n_name "CANADA"]] :order-by [[s_name :asc]]}) ;; "Elapsed time: 6805.455401 msecs" (def q21 '{:find [s_name (count l1)] :where [[l1 :l_suppkey s] [s :s_name s_name] [l1 :l_orderkey o] [o :o_orderstatus "F"] [l1 :l_receiptdate l_receiptdate] [l1 :l_commitdate l_commitdate] [(> l_receiptdate l_commitdate)] (or-join [o s] (and [l2 :l_orderkey o] (not [l2 :l_suppkey s]))) (not-join [o s] [l3 :l_orderkey o] (not [l3 :l_suppkey s]) [l3 :l_receiptdate l_receiptdate] [l3 :l_commitdate l_commitdate] [(> l_receiptdate l_commitdate)]) [s :s_nationkey n] [n :n_name "SAUDI ARABIA"]] :order-by [[(count l1) :desc] [s_name :asc]] :limit 100}) ;; "Elapsed time: 270.855812 msecs" (def q22 '{:find [cntrycode (count c) (sum c_acctbal)] :where [[c :c_phone c_phone] [(subs c_phone 0 2) cntrycode] [(contains? #{"13" "31" "23" "29" "30" "18" "17"} cntrycode)] [(q {:find [(avg c_acctbal)] :where [[c :c_acctbal c_acctbal] [(> c_acctbal 0.0)] [c :c_phone c_phone] [(subs c_phone 0 2) cntrycode] [(contains? #{"13" "31" "23" "29" "30" "18" "17"} cntrycode)]]}) [[avg_acctbal]]] [c :c_acctbal c_acctbal] [(> c_acctbal avg_acctbal)] (not-join [c] [o :o_custkey c])] :order-by [[cntrycode :asc]]}) (def tpch-queries [q1 q2 q3 q4 q5 q6 q7 q8 q9 q10 q11 q12 q13 q14 q15 q16 q17 q18 q19 q20 q21 q22]) (defn parse-tpch-result [n] (let [result-csv (slurp (io/resource (format "io/airlift/tpch/queries/q%d.result" n))) [head & lines] (str/split-lines result-csv)] (vec (for [l lines] (vec (for [x (str/split l #"\|") :let [x (try (cond (re-find #"[ ,]" x) x (re-find #"\d\d\d\d-\d\d-\d\d" x) (i/read-instant-date x) :else (edn/read-string x)) (catch Exception e x))]] (cond-> x (symbol? x) (str)))))))) (defn validate-tpch-query [actual expected] (vec (for [[expected-row actual-row] (map vector expected actual) :let [msg (pr-str [expected-row actual-row])]] (every? true? (mapv (fn [x y] (cond (and (number? x) (string? y)) (t/is (str/ends-with? y (str x)) msg) (and (number? x) (number? y)) (let [epsilon 0.01 diff (Math/abs (- (double x) (double y)))] (t/is (<= diff epsilon))) :else (t/is (= x y) msg))) expected-row actual-row))))) (comment ;; SF 0.01 (tpch/load-docs! node 0.01 tpch/tpch-entity->pkey-doc) ;; SQL: (slurp (clojure.java.io/resource "io/airlift/tpch/queries/q1.sql")) ;; Results: (slurp (clojure.java.io/resource "io/airlift/tpch/queries/q1.result")))
13862
(ns crux.bench.tpch-test (:require [crux.bench :as bench] [crux.api :as crux] [clojure.tools.logging :as log] [crux.fixtures.tpch :as tpch] [clojure.edn :as edn] [clojure.instant :as i] [clojure.java.io :as io] [clojure.string :as str] [clojure.test :as t])) (declare tpch-queries parse-tpch-result validate-tpch-query) (defn run-tpch-query [node n] (crux/q (crux/db node) (assoc (get tpch-queries (dec n)) :timeout 120000))) (defn run-tpch-test [node {:keys [scale-factor] :as opts}] (let [scale-factor (or scale-factor 0.01)] (bench/with-bench-ns :tpch-test (bench/with-crux-dimensions (bench/run-bench :ingest (bench/with-additional-index-metrics node (tpch/load-docs! node scale-factor tpch/tpch-entity->pkey-doc))) ;; TODO we may want to split this up, à la WatDiv, so that we can see if ;; specific queries are slower than our comparison databases (bench/run-bench :queries {:success? (every? true? (for [n (range 1 23)] (let [actual (run-tpch-query node n)] (if (= 0.01 scale-factor) (every? true? (validate-tpch-query actual (parse-tpch-result n))) (boolean actual)))))}))))) ;; "Elapsed time: 21994.835831 msecs" (def q1 '{:find [l_returnflag l_linestatus (sum l_quantity) (sum l_extendedprice) (sum ret_2) (sum ret_4) (avg l_quantity) (avg l_extendedprice) (avg l_discount) (count l)] :where [[l :l_shipdate l_shipdate] [l :l_quantity l_quantity] [l :l_extendedprice l_extendedprice] [l :l_discount l_discount] [l :l_tax l_tax] [l :l_returnflag l_returnflag] [l :l_linestatus l_linestatus] [(<= l_shipdate #inst "1998-09-02")] [(- 1 l_discount) ret_1] [(* l_extendedprice ret_1) ret_2] [(+ 1 l_tax) ret_3] [(* ret_2 ret_3) ret_4]] :order-by [[l_returnflag :asc] [l_linestatus :asc]]}) ;; "Elapsed time: 1304.42464 msecs" (def q2 '{:find [s_acctbal s_name n_name p p_mfgr s_address s_phone s_comment] :where [[p :p_mfgr p_mfgr] [p :p_size 15] [p :p_type p_type] [(re-find #"^.*BRASS$" p_type)] [ps :ps_partkey p] [ps :ps_supplycost ps_supplycost] [(q {:find [(min ps_supplycost)] :in [$ p] :where [[ps :ps_partkey p] [ps :ps_supplycost ps_supplycost] [ps :ps_suppkey s] [s :s_nationkey n] [n :n_regionkey r] [r :r_name "EUROPE"]]} p) [[ps_supplycost]]] [ps :ps_suppkey s] [s :s_acctbal s_acctbal] [s :s_address s_address] [s :s_name s_name] [s :s_phone s_phone] [s :s_comment s_comment] [n :n_name n_name] [s :s_nationkey n] [n :n_regionkey r] [r :r_name "EUROPE"]] :order-by [[s_acctbal :desc] [n_name :asc] [s_name :asc] [p :asc]] :limit 100}) ;; "Elapsed time: 5786.047011 msecs" (def q3 '{:find [o (sum ret_2) o_orderdate o_shippriority] :where [[c :c_mktsegment "BUILDING"] [o :o_custkey c] [o :o_shippriority o_shippriority] [o :o_orderdate o_orderdate] [(< o_orderdate #inst "1995-03-15")] [l :l_orderkey o] [l :l_discount l_discount] [l :l_extendedprice l_extendedprice] [l :l_shipdate l_shipdate] [(> l_shipdate #inst "1995-03-15")] [(- 1 l_discount) ret_1] [(* l_extendedprice ret_1) ret_2]] :order-by [[(sum ret_2) :desc] [o_orderdate :asc]] :limit 10}) ;; "Elapsed time: 1292.874285 msecs" (def q4 '{:find [o_orderpriority (count o)] :where [[o :o_orderdate o_orderdate] [o :o_orderpriority o_orderpriority] [(>= o_orderdate #inst "1993-07-01")] [(< o_orderdate #inst "1993-10-01")] (or-join [o] (and [l :l_orderkey o] [l :l_commitdate l_commitdate] [l :l_receiptdate l_receiptdate] [(< l_commitdate l_receiptdate)]))] :order-by [[o_orderpriority :asc]]}) ;; "Elapsed time: 5319.179341 msecs" (def q5 '{:find [n_name (sum ret_2)] :where [[o :o_custkey c] [l :l_orderkey o] [l :l_suppkey s] [s :s_nationkey n] [c :c_nationkey n] [n :n_name n_name] [n :n_regionkey r] [r :r_name "ASIA"] [l :l_extendedprice l_extendedprice] [l :l_discount l_discount] [o :o_orderdate o_orderdate] [(>= o_orderdate #inst "1994-01-01")] [(< o_orderdate #inst "1995-01-01")] [(- 1 l_discount) ret_1] [(* l_extendedprice ret_1) ret_2]] :order-by [[(sum ret_2) :desc]]}) ;; "Elapsed time: 1773.63273 msecs" (def q6 '{:find [(sum ret_1)] :where [[l :l_shipdate l_shipdate] [l :l_quantity l_quantity] [l :l_extendedprice l_extendedprice] [l :l_discount l_discount] [(>= l_shipdate #inst "1994-01-01")] [(< l_shipdate #inst "1995-01-01")] [(>= l_discount 0.05)] [(<= l_discount 0.07)] [(< l_quantity 24.0)] [(* l_extendedprice l_discount) ret_1]]}) ;; "Elapsed time: 58567.852989 msecs" (def q7 '{:find [supp_nation cust_nation l_year (sum ret_2)] :where [[o :o_custkey c] [l :l_orderkey o] [l :l_suppkey s] [s :s_nationkey n1] [n1 :n_name supp_nation] [c :c_nationkey n2] [n2 :n_name cust_nation] (or (and [n1 :n_name "FRANCE"] [n2 :n_name "GERMANY"]) (and [n1 :n_name "GERMANY"] [n2 :n_name "FRANCE"])) [l :l_shipdate l_shipdate] [l :l_discount l_discount] [l :l_extendedprice l_extendedprice] [(>= l_shipdate #inst "1995-01-01")] [(<= l_shipdate #inst "1996-12-31")] [(- 1 l_discount) ret_1] [(* l_extendedprice ret_1) ret_2] [(pr-str l_shipdate) ret_3] [(subs ret_3 7 11) l_year]] :order-by [[supp_nation :asc] [cust_nation :asc] [l_year :asc]]}) ;; "Elapsed time: 22993.637183 msecs" (def q8 '{:find [o_year mkt_share] :where [[(q {:find [o_year (sum brazil_volume) (sum volume)] :where [[(q {:find [o_year (sum ret_2) nation] :where [[o :o_custkey c] [l :l_orderkey o] [l :l_suppkey s] [l :l_partkey p] [c :c_nationkey n1] [n1 :n_regionkey r1] [r1 :r_name "AMERICA"] [s :s_nationkey n2] [n2 :n_name nation] [l :l_discount l_discount] [l :l_extendedprice l_extendedprice] [o :o_orderdate o_orderdate] [(>= o_orderdate #inst "1995-01-01")] [(<= o_orderdate #inst "1996-12-31")] [p :p_type "ECONOMY ANODIZED STEEL"] [(- 1 l_discount) ret_1] [(* l_extendedprice ret_1) ret_2] [(pr-str o_orderdate) ret_3] [(subs ret_3 7 11) o_year]]}) [[o_year volume nation]]] [(hash-map "BRAZIL" volume) brazil_lookup] [(get brazil_lookup nation 0) brazil_volume]]}) [[o_year brazil_volume volume]]] [(/ brazil_volume volume) mkt_share]] :order-by [[o_year :asc]]}) ;; "Elapsed time: 10066.352268 msecs" (def q9 '{:find [nation o_year (sum ret_4)] :where [[l :l_orderkey o] [l :l_suppkey s] [l :l_partkey p] [ps :ps_partkey p] [ps :ps_suppkey s] [ps :ps_supplycost ps_supplycost] [s :s_nationkey n] [n :n_name nation] [p :p_name p_name] [(re-find #".*green.*" p_name)] [l :l_quantity l_quantity] [l :l_discount l_discount] [l :l_extendedprice l_extendedprice] [o :o_orderdate o_orderdate] [(- 1 l_discount) ret_1] [(* l_extendedprice ret_1) ret_2] [(* ps_supplycost l_quantity) ret_3] [(- ret_2 ret_3) ret_4] [(pr-str o_orderdate) ret_5] [(subs ret_5 7 11) o_year]] :order-by [[nation :asc] [o_year :desc]]}) ;; "Elapsed time: 8893.984112 msecs" (def q10 '{:find [c c_name (sum ret_2) c_acctbal n_name c_address c_phone c_comment] :where [[o :o_custkey c] [l :l_orderkey o] [c :c_nationkey n] [n :n_name n_name] [c :c_name c_name] [c :c_acctbal c_acctbal] [c :c_address c_address] [c :c_phone c_phone] [c :c_comment c_comment] [l :l_extendedprice l_extendedprice] [l :l_discount l_discount] [o :o_orderdate o_orderdate] [(>= o_orderdate #inst "1993-10-01")] [(< o_orderdate #inst "1994-01-01")] [l :l_returnflag "R"] [(- 1 l_discount) ret_1] [(* l_extendedprice ret_1) ret_2]] :order-by [[(sum ret_2) :desc]] :limit 20}) ;; "Elapsed time: 190.177707 msecs" (def q11 '{:find [ps_partkey value] :where [[(q {:find [(sum ret_1)] :where [[ps :ps_availqty ps_availqty] [ps :ps_supplycost ps_supplycost] [ps :ps_suppkey s] [s :s_nationkey n] [n :n_name "GERMANY"] [(* ps_supplycost ps_availqty) ret_1]]}) [[ret_1]]] [(q {:find [ps_partkey (sum ret_1)] :where [[ps :ps_availqty ps_availqty] [ps :ps_supplycost ps_supplycost] [ps :ps_partkey ps_partkey] [ps :ps_suppkey s] [s :s_nationkey n] [n :n_name "GERMANY"] [(* ps_supplycost ps_availqty) ret_1]]}) [[ps_partkey value]]] [(* 0.0001 ret_1) ret_2] [(> value ret_2)]] :order-by [[value :desc]]}) ;; "Elapsed time: 4115.160435 msecs" (def q12 '{:find [l_shipmode (sum high_line_count) (sum low_line_count)] :where [[l :l_orderkey o] [l :l_receiptdate l_receiptdate] [l :l_commitdate l_commitdate] [l :l_shipdate l_shipdate] [(>= l_receiptdate #inst "1994-01-01")] [(< l_receiptdate #inst "1995-01-01")] [(< l_commitdate l_receiptdate)] [(< l_shipdate l_commitdate)] [l :l_shipmode l_shipmode] [l :l_shipmode #{"MAIL" "SHIP"}] [o :o_orderpriority o_orderpriority] [(get {"1-URGENT" [1 0] "2-HIGH" [1 0]} o_orderpriority [0 1]) [high_line_count low_line_count]]] :order-by [[l_shipmode :asc]]}) ;; "Elapsed time: 2187.862433 msecs" (def q13 '{:find [c_count (count c_count)] :where [(or [(q {:find [c (count o)] :where [[o :o_custkey c] [o :o_comment o_comment] (not [(re-find #".*special.*requests.*" o_comment)])]}) [[c c_count]]] (and [c :c_custkey] (not [_ :o_custkey c]) [(identity 0) c_count]))] :order-by [[(count c_count) :desc] [c_count :desc]]}) ;; "Elapsed time: 12734.7558 msecs" (def q14 '{:find [promo_revenue] :where [[(q {:find [(sum ret_3) (sum ret_2)] :where [[l :l_partkey p] [p :p_type p_type] [l :l_shipdate l_shipdate] [l :l_extendedprice l_extendedprice] [l :l_discount l_discount] [(>= l_shipdate #inst "1995-09-01")] [(< l_shipdate #inst "1995-10-01")] [(- 1 l_discount) ret_1] [(* l_extendedprice ret_1) ret_2] [(clojure.string/starts-with? p_type "PROMO") promo?] [(hash-map true ret_2) promo_lookup] [(get promo_lookup promo? 0) ret_3]]}) [[promo not_promo]]] [(/ promo not_promo) ret_1] [(* 100 ret_1) promo_revenue]]}) ;; "Elapsed time: 5651.664312 msecs" (def q15 '{:find [s s_name s_address s_phone total_revenue] :where [[(q {:find [s (sum ret_2)] :where [[l :l_suppkey s] [l :l_shipdate l_shipdate] [l :l_extendedprice l_extendedprice] [l :l_discount l_discount] [(>= l_shipdate #inst "1996-01-01")] [(< l_shipdate #inst "1996-04-01")] [(- 1 l_discount) ret_1] [(* l_extendedprice ret_1) ret_2]]}) revenue] [(q {:find [(max total_revenue)] :in [$ [[_ total_revenue]]]} revenue) [[total_revenue]]] [(identity revenue) [[s total_revenue]]] [s :s_name s_name] [s :s_address s_address] [s :s_phone s_phone]]}) ;; "Elapsed time: 357.971209 msecs" (def q16 '{:find [p_brand p_type p_size (count-distinct s)] :where [[p :p_brand p_brand] [(not= p_brand "Brand#45")] [p :p_type p_type] (not [(re-find #"^MEDIUM POLISHED.*" p_type)]) [p :p_size p_size] [p :p_size #{49 14 23 45 19 3 36 9}] [ps :ps_partkey p] [ps :ps_suppkey s] (not-join [s] [s :s_comment s_comment] [(re-find #".*Customer.*Complaints.*" s_comment)])] :order-by [[(count-distinct s) :desc] [p_brand :asc] [p_type :asc] [p_size :asc]]}) ;; "Elapsed time: 7.41559 msecs" -- unclear if this works, as it returns nothing. (def q17 '{:find [avg_yearly] :where [[(q {:find [(sum l_extendedprice)] :where [[p :p_brand "Brand#23"] [p :p_container "MED BOX"] [l :l_partkey p] [(q {:find [(avg l_quantity)] :in [$ p] :where [[l :l_partkey p] [l :l_quantity l_quantity]]} p) [[avg_quantity]]] [(* 0.2 avg_quantity) ret_1] [l :l_quantity l_quantity] [(< l_quantity ret_1)] [l :l_extendedprice l_extendedprice]]}) [[sum_extendedprice]]] [(/ sum_extendedprice 7.0) avg_yearly]]}) ;; "Elapsed time: 13222.491411 msecs" (def q18 '{:find [c_name c o o_orderdate o_totalprice (sum l_quantity)] :where [[(q {:find [o (sum l_quantity)] :where [[l :l_orderkey o] [l :l_quantity l_quantity]]}) [[o sum_quantity]]] [(> sum_quantity 300.0)] [o :o_custkey c] [c :c_name c_name] [o :o_orderdate o_orderdate] [o :o_totalprice o_totalprice] [l :l_orderkey o] [l :l_quantity l_quantity]] :order-by [[o_totalprice :desc] [o_orderdate :asc]] :limit 100}) ;; "Elapsed time: 4693.23977 msecs" (def q19 '{:find [(sum ret_2)] :where [[l :l_shipmode #{"AIR" "AIR REG"}] [l :l_shipinstruct "DELIVER IN PERSON"] [l :l_discount l_discount] [l :l_extendedprice l_extendedprice] [l :l_partkey p] [l :l_quantity l_quantity] [p :p_size p_size] (or (and [p :p_brand "Brand#12"] [p :p_container #{"SM CASE" "SM BOX" "SM PACK" "SM PKG"}] [(>= l_quantity 1.0)] [(<= l_quantity 11.0)] [(>= p_size 1)] [(<= p_size 5)]) (and [p :p_brand "Brand#23"] [p :p_container #{"MED BAG" "MED BOX" "MED PKG" "MED PACK"}] [(>= l_quantity 10.0)] [(<= l_quantity 20.0)] [(>= p_size 1)] [(<= p_size 10)]) (and [p :p_brand "Brand#34"] [p :p_container #{"LG CASE" "LG BOX" "LG PACK" "LG PKG"}] [(>= l_quantity 20.0)] [(<= l_quantity 30.0)] [(>= p_size 1)] [(<= p_size 15)])) [(- 1 l_discount) ret_1] [(* l_extendedprice ret_1) ret_2]]}) ;; "Elapsed time: 1607.843909 msecs" (def q20 '{:find [s_name s_address] :where [[ps :ps_suppkey s] [ps :ps_partkey p] [p :p_name p_name] [(re-find #"^forest.*" p_name)] [(q {:find [(sum l_quantity)] :in [$ p s] :where [[l :l_partkey p] [l :l_suppkey s] [l :l_shipdate l_shipdate] [(>= l_shipdate #inst "1994-01-01")] [(< l_shipdate #inst "1995-01-01")] [l :l_quantity l_quantity]]} p s) [[sum_quantity]]] [(* sum_quantity 0.5) ret_1] [(long ret_1) ret_2] [ps :ps_availqty ps_availqty] [(> ps_availqty ret_2)] [s :s_name s_name] [s :s_address s_address] [s :s_nationkey n] [n :n_name "CANADA"]] :order-by [[s_name :asc]]}) ;; "Elapsed time: 6805.455401 msecs" (def q21 '{:find [s_name (count l1)] :where [[l1 :l_suppkey s] [s :s_name s_name] [l1 :l_orderkey o] [o :o_orderstatus "F"] [l1 :l_receiptdate l_receiptdate] [l1 :l_commitdate l_commitdate] [(> l_receiptdate l_commitdate)] (or-join [o s] (and [l2 :l_orderkey o] (not [l2 :l_suppkey s]))) (not-join [o s] [l3 :l_orderkey o] (not [l3 :l_suppkey s]) [l3 :l_receiptdate l_receiptdate] [l3 :l_commitdate l_commitdate] [(> l_receiptdate l_commitdate)]) [s :s_nationkey n] [n :n_name "<NAME>"]] :order-by [[(count l1) :desc] [s_name :asc]] :limit 100}) ;; "Elapsed time: 270.855812 msecs" (def q22 '{:find [cntrycode (count c) (sum c_acctbal)] :where [[c :c_phone c_phone] [(subs c_phone 0 2) cntrycode] [(contains? #{"13" "31" "23" "29" "30" "18" "17"} cntrycode)] [(q {:find [(avg c_acctbal)] :where [[c :c_acctbal c_acctbal] [(> c_acctbal 0.0)] [c :c_phone c_phone] [(subs c_phone 0 2) cntrycode] [(contains? #{"13" "31" "23" "29" "30" "18" "17"} cntrycode)]]}) [[avg_acctbal]]] [c :c_acctbal c_acctbal] [(> c_acctbal avg_acctbal)] (not-join [c] [o :o_custkey c])] :order-by [[cntrycode :asc]]}) (def tpch-queries [q1 q2 q3 q4 q5 q6 q7 q8 q9 q10 q11 q12 q13 q14 q15 q16 q17 q18 q19 q20 q21 q22]) (defn parse-tpch-result [n] (let [result-csv (slurp (io/resource (format "io/airlift/tpch/queries/q%d.result" n))) [head & lines] (str/split-lines result-csv)] (vec (for [l lines] (vec (for [x (str/split l #"\|") :let [x (try (cond (re-find #"[ ,]" x) x (re-find #"\d\d\d\d-\d\d-\d\d" x) (i/read-instant-date x) :else (edn/read-string x)) (catch Exception e x))]] (cond-> x (symbol? x) (str)))))))) (defn validate-tpch-query [actual expected] (vec (for [[expected-row actual-row] (map vector expected actual) :let [msg (pr-str [expected-row actual-row])]] (every? true? (mapv (fn [x y] (cond (and (number? x) (string? y)) (t/is (str/ends-with? y (str x)) msg) (and (number? x) (number? y)) (let [epsilon 0.01 diff (Math/abs (- (double x) (double y)))] (t/is (<= diff epsilon))) :else (t/is (= x y) msg))) expected-row actual-row))))) (comment ;; SF 0.01 (tpch/load-docs! node 0.01 tpch/tpch-entity->pkey-doc) ;; SQL: (slurp (clojure.java.io/resource "io/airlift/tpch/queries/q1.sql")) ;; Results: (slurp (clojure.java.io/resource "io/airlift/tpch/queries/q1.result")))
true
(ns crux.bench.tpch-test (:require [crux.bench :as bench] [crux.api :as crux] [clojure.tools.logging :as log] [crux.fixtures.tpch :as tpch] [clojure.edn :as edn] [clojure.instant :as i] [clojure.java.io :as io] [clojure.string :as str] [clojure.test :as t])) (declare tpch-queries parse-tpch-result validate-tpch-query) (defn run-tpch-query [node n] (crux/q (crux/db node) (assoc (get tpch-queries (dec n)) :timeout 120000))) (defn run-tpch-test [node {:keys [scale-factor] :as opts}] (let [scale-factor (or scale-factor 0.01)] (bench/with-bench-ns :tpch-test (bench/with-crux-dimensions (bench/run-bench :ingest (bench/with-additional-index-metrics node (tpch/load-docs! node scale-factor tpch/tpch-entity->pkey-doc))) ;; TODO we may want to split this up, à la WatDiv, so that we can see if ;; specific queries are slower than our comparison databases (bench/run-bench :queries {:success? (every? true? (for [n (range 1 23)] (let [actual (run-tpch-query node n)] (if (= 0.01 scale-factor) (every? true? (validate-tpch-query actual (parse-tpch-result n))) (boolean actual)))))}))))) ;; "Elapsed time: 21994.835831 msecs" (def q1 '{:find [l_returnflag l_linestatus (sum l_quantity) (sum l_extendedprice) (sum ret_2) (sum ret_4) (avg l_quantity) (avg l_extendedprice) (avg l_discount) (count l)] :where [[l :l_shipdate l_shipdate] [l :l_quantity l_quantity] [l :l_extendedprice l_extendedprice] [l :l_discount l_discount] [l :l_tax l_tax] [l :l_returnflag l_returnflag] [l :l_linestatus l_linestatus] [(<= l_shipdate #inst "1998-09-02")] [(- 1 l_discount) ret_1] [(* l_extendedprice ret_1) ret_2] [(+ 1 l_tax) ret_3] [(* ret_2 ret_3) ret_4]] :order-by [[l_returnflag :asc] [l_linestatus :asc]]}) ;; "Elapsed time: 1304.42464 msecs" (def q2 '{:find [s_acctbal s_name n_name p p_mfgr s_address s_phone s_comment] :where [[p :p_mfgr p_mfgr] [p :p_size 15] [p :p_type p_type] [(re-find #"^.*BRASS$" p_type)] [ps :ps_partkey p] [ps :ps_supplycost ps_supplycost] [(q {:find [(min ps_supplycost)] :in [$ p] :where [[ps :ps_partkey p] [ps :ps_supplycost ps_supplycost] [ps :ps_suppkey s] [s :s_nationkey n] [n :n_regionkey r] [r :r_name "EUROPE"]]} p) [[ps_supplycost]]] [ps :ps_suppkey s] [s :s_acctbal s_acctbal] [s :s_address s_address] [s :s_name s_name] [s :s_phone s_phone] [s :s_comment s_comment] [n :n_name n_name] [s :s_nationkey n] [n :n_regionkey r] [r :r_name "EUROPE"]] :order-by [[s_acctbal :desc] [n_name :asc] [s_name :asc] [p :asc]] :limit 100}) ;; "Elapsed time: 5786.047011 msecs" (def q3 '{:find [o (sum ret_2) o_orderdate o_shippriority] :where [[c :c_mktsegment "BUILDING"] [o :o_custkey c] [o :o_shippriority o_shippriority] [o :o_orderdate o_orderdate] [(< o_orderdate #inst "1995-03-15")] [l :l_orderkey o] [l :l_discount l_discount] [l :l_extendedprice l_extendedprice] [l :l_shipdate l_shipdate] [(> l_shipdate #inst "1995-03-15")] [(- 1 l_discount) ret_1] [(* l_extendedprice ret_1) ret_2]] :order-by [[(sum ret_2) :desc] [o_orderdate :asc]] :limit 10}) ;; "Elapsed time: 1292.874285 msecs" (def q4 '{:find [o_orderpriority (count o)] :where [[o :o_orderdate o_orderdate] [o :o_orderpriority o_orderpriority] [(>= o_orderdate #inst "1993-07-01")] [(< o_orderdate #inst "1993-10-01")] (or-join [o] (and [l :l_orderkey o] [l :l_commitdate l_commitdate] [l :l_receiptdate l_receiptdate] [(< l_commitdate l_receiptdate)]))] :order-by [[o_orderpriority :asc]]}) ;; "Elapsed time: 5319.179341 msecs" (def q5 '{:find [n_name (sum ret_2)] :where [[o :o_custkey c] [l :l_orderkey o] [l :l_suppkey s] [s :s_nationkey n] [c :c_nationkey n] [n :n_name n_name] [n :n_regionkey r] [r :r_name "ASIA"] [l :l_extendedprice l_extendedprice] [l :l_discount l_discount] [o :o_orderdate o_orderdate] [(>= o_orderdate #inst "1994-01-01")] [(< o_orderdate #inst "1995-01-01")] [(- 1 l_discount) ret_1] [(* l_extendedprice ret_1) ret_2]] :order-by [[(sum ret_2) :desc]]}) ;; "Elapsed time: 1773.63273 msecs" (def q6 '{:find [(sum ret_1)] :where [[l :l_shipdate l_shipdate] [l :l_quantity l_quantity] [l :l_extendedprice l_extendedprice] [l :l_discount l_discount] [(>= l_shipdate #inst "1994-01-01")] [(< l_shipdate #inst "1995-01-01")] [(>= l_discount 0.05)] [(<= l_discount 0.07)] [(< l_quantity 24.0)] [(* l_extendedprice l_discount) ret_1]]}) ;; "Elapsed time: 58567.852989 msecs" (def q7 '{:find [supp_nation cust_nation l_year (sum ret_2)] :where [[o :o_custkey c] [l :l_orderkey o] [l :l_suppkey s] [s :s_nationkey n1] [n1 :n_name supp_nation] [c :c_nationkey n2] [n2 :n_name cust_nation] (or (and [n1 :n_name "FRANCE"] [n2 :n_name "GERMANY"]) (and [n1 :n_name "GERMANY"] [n2 :n_name "FRANCE"])) [l :l_shipdate l_shipdate] [l :l_discount l_discount] [l :l_extendedprice l_extendedprice] [(>= l_shipdate #inst "1995-01-01")] [(<= l_shipdate #inst "1996-12-31")] [(- 1 l_discount) ret_1] [(* l_extendedprice ret_1) ret_2] [(pr-str l_shipdate) ret_3] [(subs ret_3 7 11) l_year]] :order-by [[supp_nation :asc] [cust_nation :asc] [l_year :asc]]}) ;; "Elapsed time: 22993.637183 msecs" (def q8 '{:find [o_year mkt_share] :where [[(q {:find [o_year (sum brazil_volume) (sum volume)] :where [[(q {:find [o_year (sum ret_2) nation] :where [[o :o_custkey c] [l :l_orderkey o] [l :l_suppkey s] [l :l_partkey p] [c :c_nationkey n1] [n1 :n_regionkey r1] [r1 :r_name "AMERICA"] [s :s_nationkey n2] [n2 :n_name nation] [l :l_discount l_discount] [l :l_extendedprice l_extendedprice] [o :o_orderdate o_orderdate] [(>= o_orderdate #inst "1995-01-01")] [(<= o_orderdate #inst "1996-12-31")] [p :p_type "ECONOMY ANODIZED STEEL"] [(- 1 l_discount) ret_1] [(* l_extendedprice ret_1) ret_2] [(pr-str o_orderdate) ret_3] [(subs ret_3 7 11) o_year]]}) [[o_year volume nation]]] [(hash-map "BRAZIL" volume) brazil_lookup] [(get brazil_lookup nation 0) brazil_volume]]}) [[o_year brazil_volume volume]]] [(/ brazil_volume volume) mkt_share]] :order-by [[o_year :asc]]}) ;; "Elapsed time: 10066.352268 msecs" (def q9 '{:find [nation o_year (sum ret_4)] :where [[l :l_orderkey o] [l :l_suppkey s] [l :l_partkey p] [ps :ps_partkey p] [ps :ps_suppkey s] [ps :ps_supplycost ps_supplycost] [s :s_nationkey n] [n :n_name nation] [p :p_name p_name] [(re-find #".*green.*" p_name)] [l :l_quantity l_quantity] [l :l_discount l_discount] [l :l_extendedprice l_extendedprice] [o :o_orderdate o_orderdate] [(- 1 l_discount) ret_1] [(* l_extendedprice ret_1) ret_2] [(* ps_supplycost l_quantity) ret_3] [(- ret_2 ret_3) ret_4] [(pr-str o_orderdate) ret_5] [(subs ret_5 7 11) o_year]] :order-by [[nation :asc] [o_year :desc]]}) ;; "Elapsed time: 8893.984112 msecs" (def q10 '{:find [c c_name (sum ret_2) c_acctbal n_name c_address c_phone c_comment] :where [[o :o_custkey c] [l :l_orderkey o] [c :c_nationkey n] [n :n_name n_name] [c :c_name c_name] [c :c_acctbal c_acctbal] [c :c_address c_address] [c :c_phone c_phone] [c :c_comment c_comment] [l :l_extendedprice l_extendedprice] [l :l_discount l_discount] [o :o_orderdate o_orderdate] [(>= o_orderdate #inst "1993-10-01")] [(< o_orderdate #inst "1994-01-01")] [l :l_returnflag "R"] [(- 1 l_discount) ret_1] [(* l_extendedprice ret_1) ret_2]] :order-by [[(sum ret_2) :desc]] :limit 20}) ;; "Elapsed time: 190.177707 msecs" (def q11 '{:find [ps_partkey value] :where [[(q {:find [(sum ret_1)] :where [[ps :ps_availqty ps_availqty] [ps :ps_supplycost ps_supplycost] [ps :ps_suppkey s] [s :s_nationkey n] [n :n_name "GERMANY"] [(* ps_supplycost ps_availqty) ret_1]]}) [[ret_1]]] [(q {:find [ps_partkey (sum ret_1)] :where [[ps :ps_availqty ps_availqty] [ps :ps_supplycost ps_supplycost] [ps :ps_partkey ps_partkey] [ps :ps_suppkey s] [s :s_nationkey n] [n :n_name "GERMANY"] [(* ps_supplycost ps_availqty) ret_1]]}) [[ps_partkey value]]] [(* 0.0001 ret_1) ret_2] [(> value ret_2)]] :order-by [[value :desc]]}) ;; "Elapsed time: 4115.160435 msecs" (def q12 '{:find [l_shipmode (sum high_line_count) (sum low_line_count)] :where [[l :l_orderkey o] [l :l_receiptdate l_receiptdate] [l :l_commitdate l_commitdate] [l :l_shipdate l_shipdate] [(>= l_receiptdate #inst "1994-01-01")] [(< l_receiptdate #inst "1995-01-01")] [(< l_commitdate l_receiptdate)] [(< l_shipdate l_commitdate)] [l :l_shipmode l_shipmode] [l :l_shipmode #{"MAIL" "SHIP"}] [o :o_orderpriority o_orderpriority] [(get {"1-URGENT" [1 0] "2-HIGH" [1 0]} o_orderpriority [0 1]) [high_line_count low_line_count]]] :order-by [[l_shipmode :asc]]}) ;; "Elapsed time: 2187.862433 msecs" (def q13 '{:find [c_count (count c_count)] :where [(or [(q {:find [c (count o)] :where [[o :o_custkey c] [o :o_comment o_comment] (not [(re-find #".*special.*requests.*" o_comment)])]}) [[c c_count]]] (and [c :c_custkey] (not [_ :o_custkey c]) [(identity 0) c_count]))] :order-by [[(count c_count) :desc] [c_count :desc]]}) ;; "Elapsed time: 12734.7558 msecs" (def q14 '{:find [promo_revenue] :where [[(q {:find [(sum ret_3) (sum ret_2)] :where [[l :l_partkey p] [p :p_type p_type] [l :l_shipdate l_shipdate] [l :l_extendedprice l_extendedprice] [l :l_discount l_discount] [(>= l_shipdate #inst "1995-09-01")] [(< l_shipdate #inst "1995-10-01")] [(- 1 l_discount) ret_1] [(* l_extendedprice ret_1) ret_2] [(clojure.string/starts-with? p_type "PROMO") promo?] [(hash-map true ret_2) promo_lookup] [(get promo_lookup promo? 0) ret_3]]}) [[promo not_promo]]] [(/ promo not_promo) ret_1] [(* 100 ret_1) promo_revenue]]}) ;; "Elapsed time: 5651.664312 msecs" (def q15 '{:find [s s_name s_address s_phone total_revenue] :where [[(q {:find [s (sum ret_2)] :where [[l :l_suppkey s] [l :l_shipdate l_shipdate] [l :l_extendedprice l_extendedprice] [l :l_discount l_discount] [(>= l_shipdate #inst "1996-01-01")] [(< l_shipdate #inst "1996-04-01")] [(- 1 l_discount) ret_1] [(* l_extendedprice ret_1) ret_2]]}) revenue] [(q {:find [(max total_revenue)] :in [$ [[_ total_revenue]]]} revenue) [[total_revenue]]] [(identity revenue) [[s total_revenue]]] [s :s_name s_name] [s :s_address s_address] [s :s_phone s_phone]]}) ;; "Elapsed time: 357.971209 msecs" (def q16 '{:find [p_brand p_type p_size (count-distinct s)] :where [[p :p_brand p_brand] [(not= p_brand "Brand#45")] [p :p_type p_type] (not [(re-find #"^MEDIUM POLISHED.*" p_type)]) [p :p_size p_size] [p :p_size #{49 14 23 45 19 3 36 9}] [ps :ps_partkey p] [ps :ps_suppkey s] (not-join [s] [s :s_comment s_comment] [(re-find #".*Customer.*Complaints.*" s_comment)])] :order-by [[(count-distinct s) :desc] [p_brand :asc] [p_type :asc] [p_size :asc]]}) ;; "Elapsed time: 7.41559 msecs" -- unclear if this works, as it returns nothing. (def q17 '{:find [avg_yearly] :where [[(q {:find [(sum l_extendedprice)] :where [[p :p_brand "Brand#23"] [p :p_container "MED BOX"] [l :l_partkey p] [(q {:find [(avg l_quantity)] :in [$ p] :where [[l :l_partkey p] [l :l_quantity l_quantity]]} p) [[avg_quantity]]] [(* 0.2 avg_quantity) ret_1] [l :l_quantity l_quantity] [(< l_quantity ret_1)] [l :l_extendedprice l_extendedprice]]}) [[sum_extendedprice]]] [(/ sum_extendedprice 7.0) avg_yearly]]}) ;; "Elapsed time: 13222.491411 msecs" (def q18 '{:find [c_name c o o_orderdate o_totalprice (sum l_quantity)] :where [[(q {:find [o (sum l_quantity)] :where [[l :l_orderkey o] [l :l_quantity l_quantity]]}) [[o sum_quantity]]] [(> sum_quantity 300.0)] [o :o_custkey c] [c :c_name c_name] [o :o_orderdate o_orderdate] [o :o_totalprice o_totalprice] [l :l_orderkey o] [l :l_quantity l_quantity]] :order-by [[o_totalprice :desc] [o_orderdate :asc]] :limit 100}) ;; "Elapsed time: 4693.23977 msecs" (def q19 '{:find [(sum ret_2)] :where [[l :l_shipmode #{"AIR" "AIR REG"}] [l :l_shipinstruct "DELIVER IN PERSON"] [l :l_discount l_discount] [l :l_extendedprice l_extendedprice] [l :l_partkey p] [l :l_quantity l_quantity] [p :p_size p_size] (or (and [p :p_brand "Brand#12"] [p :p_container #{"SM CASE" "SM BOX" "SM PACK" "SM PKG"}] [(>= l_quantity 1.0)] [(<= l_quantity 11.0)] [(>= p_size 1)] [(<= p_size 5)]) (and [p :p_brand "Brand#23"] [p :p_container #{"MED BAG" "MED BOX" "MED PKG" "MED PACK"}] [(>= l_quantity 10.0)] [(<= l_quantity 20.0)] [(>= p_size 1)] [(<= p_size 10)]) (and [p :p_brand "Brand#34"] [p :p_container #{"LG CASE" "LG BOX" "LG PACK" "LG PKG"}] [(>= l_quantity 20.0)] [(<= l_quantity 30.0)] [(>= p_size 1)] [(<= p_size 15)])) [(- 1 l_discount) ret_1] [(* l_extendedprice ret_1) ret_2]]}) ;; "Elapsed time: 1607.843909 msecs" (def q20 '{:find [s_name s_address] :where [[ps :ps_suppkey s] [ps :ps_partkey p] [p :p_name p_name] [(re-find #"^forest.*" p_name)] [(q {:find [(sum l_quantity)] :in [$ p s] :where [[l :l_partkey p] [l :l_suppkey s] [l :l_shipdate l_shipdate] [(>= l_shipdate #inst "1994-01-01")] [(< l_shipdate #inst "1995-01-01")] [l :l_quantity l_quantity]]} p s) [[sum_quantity]]] [(* sum_quantity 0.5) ret_1] [(long ret_1) ret_2] [ps :ps_availqty ps_availqty] [(> ps_availqty ret_2)] [s :s_name s_name] [s :s_address s_address] [s :s_nationkey n] [n :n_name "CANADA"]] :order-by [[s_name :asc]]}) ;; "Elapsed time: 6805.455401 msecs" (def q21 '{:find [s_name (count l1)] :where [[l1 :l_suppkey s] [s :s_name s_name] [l1 :l_orderkey o] [o :o_orderstatus "F"] [l1 :l_receiptdate l_receiptdate] [l1 :l_commitdate l_commitdate] [(> l_receiptdate l_commitdate)] (or-join [o s] (and [l2 :l_orderkey o] (not [l2 :l_suppkey s]))) (not-join [o s] [l3 :l_orderkey o] (not [l3 :l_suppkey s]) [l3 :l_receiptdate l_receiptdate] [l3 :l_commitdate l_commitdate] [(> l_receiptdate l_commitdate)]) [s :s_nationkey n] [n :n_name "PI:NAME:<NAME>END_PI"]] :order-by [[(count l1) :desc] [s_name :asc]] :limit 100}) ;; "Elapsed time: 270.855812 msecs" (def q22 '{:find [cntrycode (count c) (sum c_acctbal)] :where [[c :c_phone c_phone] [(subs c_phone 0 2) cntrycode] [(contains? #{"13" "31" "23" "29" "30" "18" "17"} cntrycode)] [(q {:find [(avg c_acctbal)] :where [[c :c_acctbal c_acctbal] [(> c_acctbal 0.0)] [c :c_phone c_phone] [(subs c_phone 0 2) cntrycode] [(contains? #{"13" "31" "23" "29" "30" "18" "17"} cntrycode)]]}) [[avg_acctbal]]] [c :c_acctbal c_acctbal] [(> c_acctbal avg_acctbal)] (not-join [c] [o :o_custkey c])] :order-by [[cntrycode :asc]]}) (def tpch-queries [q1 q2 q3 q4 q5 q6 q7 q8 q9 q10 q11 q12 q13 q14 q15 q16 q17 q18 q19 q20 q21 q22]) (defn parse-tpch-result [n] (let [result-csv (slurp (io/resource (format "io/airlift/tpch/queries/q%d.result" n))) [head & lines] (str/split-lines result-csv)] (vec (for [l lines] (vec (for [x (str/split l #"\|") :let [x (try (cond (re-find #"[ ,]" x) x (re-find #"\d\d\d\d-\d\d-\d\d" x) (i/read-instant-date x) :else (edn/read-string x)) (catch Exception e x))]] (cond-> x (symbol? x) (str)))))))) (defn validate-tpch-query [actual expected] (vec (for [[expected-row actual-row] (map vector expected actual) :let [msg (pr-str [expected-row actual-row])]] (every? true? (mapv (fn [x y] (cond (and (number? x) (string? y)) (t/is (str/ends-with? y (str x)) msg) (and (number? x) (number? y)) (let [epsilon 0.01 diff (Math/abs (- (double x) (double y)))] (t/is (<= diff epsilon))) :else (t/is (= x y) msg))) expected-row actual-row))))) (comment ;; SF 0.01 (tpch/load-docs! node 0.01 tpch/tpch-entity->pkey-doc) ;; SQL: (slurp (clojure.java.io/resource "io/airlift/tpch/queries/q1.sql")) ;; Results: (slurp (clojure.java.io/resource "io/airlift/tpch/queries/q1.result")))
[ { "context": "on-action} \"OK\")\n (b/button {:key \"cancel-button\" :className \"btn-fill\" :kind :danger\n ", "end": 8958, "score": 0.9648194313049316, "start": 8952, "tag": "KEY", "value": "button" } ]
src/main/org/edgexfoundry/ui/manager/ui/notifications.cljs
tmpowers/edgex-ui-clojure
0
;;; Copyright (c) 2019 ;;; IoTech Ltd ;;; SPDX-License-Identifier: Apache-2.0 (ns org.edgexfoundry.ui.manager.ui.notifications (:require [cljs-time.core :as tc] [clojure.string :as str] [clojure.spec.alpha :as s] [fulcro.client.data-fetch :as df] [fulcro.client.localized-dom :as dom] [fulcro.client.mutations :as m :refer [defmutation]] [fulcro.client.primitives :as prim :refer [defui defsc]] [fulcro.client.routing :as r] [fulcro.ui.bootstrap3 :as b] [fulcro.ui.form-state :as fs] [org.edgexfoundry.ui.manager.api.mutations :as mu] [org.edgexfoundry.ui.manager.ui.common :as co] [org.edgexfoundry.ui.manager.ui.date-time-picker :as dtp] [org.edgexfoundry.ui.manager.ui.dialogs :as d] [org.edgexfoundry.ui.manager.ui.load :as ld] [org.edgexfoundry.ui.manager.ui.routing :as ro] [org.edgexfoundry.ui.manager.ui.table :as t :refer [deftable]] [org.edgexfoundry.ui.manager.ui.transmissions :as trn] ["react-tag-box" :refer [TagBox]] ["react-widgets" :refer [SelectList]])) (defn reset-notification* [state] (update-in state co/new-notification-ident #(merge % {:id nil}))) (defsc NotificationSearch [this {:keys [from-dtp to-dtp]}] {:initial-state (fn [p] {:from-dtp (prim/get-initial-state dtp/DateTimePicker {:id :notification-dtp-from :time (tc/yesterday) :float-left true}) :to-dtp (prim/get-initial-state dtp/DateTimePicker {:id :notification-dtp-to :time (-> (tc/today-at-midnight) (tc/plus (tc/days 1))) :float-left true})}) :ident (fn [] [:notification-search :singleton]) :query [{:from-dtp (prim/get-query dtp/DateTimePicker)} {:to-dtp (prim/get-query dtp/DateTimePicker)}]} (dom/div #js {} (dtp/date-time-picker from-dtp) (dom/div #js {:style #js {:float "right" :margin "0 2px" :position "relative"}} (dtp/date-time-picker to-dtp)))) (declare NotificationModal) (defn prepare-notification* [state] (let [ref co/new-notification-ident] (-> state (fs/add-form-config* NotificationModal ref) (reset-notification*)))) (defmutation prepare-notification [noargs] (action [{:keys [state]}] (swap! state (fn [s] (prepare-notification* s))))) (defn show-notification-modal [comp] (prim/transact! comp `[(prepare-notification) (r/set-route {:router :root/modal-router :target ~co/new-notification-ident}) (b/show-modal {:id :notification-modal}) :modal-router])) (defn add-notification [comp {:keys [notify/slug description sender category severity content labels] :as form}] (let [tmp-id (prim/tempid) notifyObj {:tempid tmp-id :slug slug :description description :sender sender :category category :severity severity :content content :labels labels}] (prim/transact! comp `[(b/hide-modal {:id :notification-modal}) (mu/add-notification ~notifyObj) (df/fallback {:action ld/reset-error})]))) (defn do-delete-notification [this id slug] (prim/transact! this `[(mu/delete-notification {:id ~id :slug ~slug}) (t/reset-table-page {:id :show-notifications}) (df/fallback {:action ld/reset-error})])) (def ui-tag-box (co/factory-apply TagBox)) (def ui-select-list (co/factory-apply SelectList)) (s/def :notify/slug #(re-matches #"\S+" %)) (defsc NotificationModal [this {:keys [id modal labels selectedItems] :as props}] {:initial-state (fn [p] {:modal (prim/get-initial-state b/Modal {:id :notification-modal :backdrop true}) :modal/page :new-notification :notify/slug "" :description "" :sender "" :category :SECURITY :severity :CRITICAL :content "" :labels [] :selectedItems []}) :ident (fn [] co/new-notification-ident) :query [:notify/slug :description :sender :category :severity :content :labels fs/form-config-join :id :modal/page {:modal (prim/get-query b/Modal)} :selectedItems] :form-fields #{:notify/slug :description :sender :category :severity :content :labels :selectedItems}} (let [tags [] ctg_opts [{ :id :SECURITY, :name "Security" }, { :id :HW_HEALTH, :name "Hardware Health" }, { :id :SW_HEALTH, :name "Software Health" }] sev_opts [{ :id :CRITICAL, :name "Critical" }, { :id :NORMAL, :name "Normal" }] set-opt! (fn [field] #(m/set-value! this field (keyword (. % -id)))) disable-button (fs/invalid-spec? props :notify/slug) button-action (fn [_] (prim/transact! this `[(fs/mark-complete! {:entity-ident ~co/new-notification-ident})]) (when-not (or (not (fs/checked? props)) (fs/invalid-spec? props :notify/slug)) (add-notification this props)))] (b/ui-modal modal (b/ui-modal-title nil (dom/div #js {:key "title" :style #js {:fontSize "22px"}} "Add Notification")) (b/ui-modal-body {:className "exportModal"} (dom/div :$card (dom/div :$content (dom/div :$form-group (co/input-with-label this :notify/slug "Slug:" "Slug is required" "Unique key of the notification" nil {:required true}) (co/input-with-label this :description "Description:" "" "Description of the notification" nil nil) (co/input-with-label this :sender "Sender:" "" "Sender of the notification" nil nil) (co/input-with-label this :category "Category:" "" "" nil nil (fn [attrs] (ui-select-list {:data ctg_opts :textField :name :onChange (set-opt! :category)}))) (co/input-with-label this :severity "Severity:" "" "" nil nil (fn [attrs] (ui-select-list {:data sev_opts :textField :name :onChange (set-opt! :severity)}))) (co/input-with-label this :content "Content:" "" "" nil nil (fn [attrs] (let [attrs (merge attrs {:onChange (fn [event] (m/set-value! this :content (.. event -target -value)))})] (dom/textarea (clj->js attrs))))) (co/input-with-label this :labels "Labels:" "" "" nil nil (fn [attrs] (ui-tag-box #js {:tags (clj->js tags) :selected (clj->js selectedItems) :selectedText "Label exists" :onSelect (fn [tag] (m/set-value! this :selectedItems (conj selectedItems {:label (. tag -label) :value (. tag -label)} )) (m/set-value! this :labels (conj labels (. tag -label)))) :removeTag (fn [tag] (m/set-value! this :selectedItems (vec (filter #(not= (:value %) (. tag -value)) selectedItems))) (m/set-value! this :labels (vec (filter #(not= % (. tag -value)) labels))))}))))))) (b/ui-modal-footer nil (b/button {:key "ok-next-button" :className "btn-fill" :kind :info :disabled disable-button :onClick button-action} "OK") (b/button {:key "cancel-button" :className "btn-fill" :kind :danger :onClick #(prim/transact! this `[(b/hide-modal {:id :notification-modal}) (fs/reset-form!) (fs/clear-complete!)])} "Cancel"))))) (defn show-transmissions [this type id slug] (prim/transact! this `[(trn/load-transmissions {:slug ~slug})]) (ro/nav-to! this :transmission)) (defn conv-category [_ category] (case category :SECURITY "Security" :HW_HEALTH "Hardware Health" :SW_HEALTH "Software Health" "Unknown")) (defn conv-sev [_ sev] (case sev :CRITICAL "Critical" :NORMAL "Normal" "Unknown")) (defn show-notifications [this] (prim/transact! this `[(load-notifications {})])) (deftable NotificationList :show-notifications :notification [[:slug "Slug"] [:created "Created" #(co/conv-time %2)] [:sender "Sender"] [:category "Category" conv-category] [:severity "Severity" conv-sev] [:content "Content"] [:labels "Labels" #(co/conv-seq %2)]] [{:onClick #(show-notification-modal this) :icon "plus"} {:onClick #(show-notifications this) :icon "refresh"}] :modals [{:modal d/DeleteModal :params {:modal-id :dnt-modal} :callbacks {:onDelete do-delete-notification}}] :actions [{:title "View Transmission" :action-class :info :symbol "file" :onClick show-transmissions} {:title "Delete Transmission" :action-class :danger :symbol "times" :onClick (d/mk-show-modal :dnt-modal props)}] :search-keyword :content :search {:comp NotificationSearch}) (defmutation load-notifications [none] (action [{:keys [reconciler state] :as env}] (let [start (get-in @state [:date-time-picker :notification-dtp-from :time]) end (get-in @state [:date-time-picker :notification-dtp-to :time])] (ld/load reconciler co/notifications-list-ident NotificationList {:params {:start start :end end}}))) (remote [env] (df/remote-load env)))
69384
;;; Copyright (c) 2019 ;;; IoTech Ltd ;;; SPDX-License-Identifier: Apache-2.0 (ns org.edgexfoundry.ui.manager.ui.notifications (:require [cljs-time.core :as tc] [clojure.string :as str] [clojure.spec.alpha :as s] [fulcro.client.data-fetch :as df] [fulcro.client.localized-dom :as dom] [fulcro.client.mutations :as m :refer [defmutation]] [fulcro.client.primitives :as prim :refer [defui defsc]] [fulcro.client.routing :as r] [fulcro.ui.bootstrap3 :as b] [fulcro.ui.form-state :as fs] [org.edgexfoundry.ui.manager.api.mutations :as mu] [org.edgexfoundry.ui.manager.ui.common :as co] [org.edgexfoundry.ui.manager.ui.date-time-picker :as dtp] [org.edgexfoundry.ui.manager.ui.dialogs :as d] [org.edgexfoundry.ui.manager.ui.load :as ld] [org.edgexfoundry.ui.manager.ui.routing :as ro] [org.edgexfoundry.ui.manager.ui.table :as t :refer [deftable]] [org.edgexfoundry.ui.manager.ui.transmissions :as trn] ["react-tag-box" :refer [TagBox]] ["react-widgets" :refer [SelectList]])) (defn reset-notification* [state] (update-in state co/new-notification-ident #(merge % {:id nil}))) (defsc NotificationSearch [this {:keys [from-dtp to-dtp]}] {:initial-state (fn [p] {:from-dtp (prim/get-initial-state dtp/DateTimePicker {:id :notification-dtp-from :time (tc/yesterday) :float-left true}) :to-dtp (prim/get-initial-state dtp/DateTimePicker {:id :notification-dtp-to :time (-> (tc/today-at-midnight) (tc/plus (tc/days 1))) :float-left true})}) :ident (fn [] [:notification-search :singleton]) :query [{:from-dtp (prim/get-query dtp/DateTimePicker)} {:to-dtp (prim/get-query dtp/DateTimePicker)}]} (dom/div #js {} (dtp/date-time-picker from-dtp) (dom/div #js {:style #js {:float "right" :margin "0 2px" :position "relative"}} (dtp/date-time-picker to-dtp)))) (declare NotificationModal) (defn prepare-notification* [state] (let [ref co/new-notification-ident] (-> state (fs/add-form-config* NotificationModal ref) (reset-notification*)))) (defmutation prepare-notification [noargs] (action [{:keys [state]}] (swap! state (fn [s] (prepare-notification* s))))) (defn show-notification-modal [comp] (prim/transact! comp `[(prepare-notification) (r/set-route {:router :root/modal-router :target ~co/new-notification-ident}) (b/show-modal {:id :notification-modal}) :modal-router])) (defn add-notification [comp {:keys [notify/slug description sender category severity content labels] :as form}] (let [tmp-id (prim/tempid) notifyObj {:tempid tmp-id :slug slug :description description :sender sender :category category :severity severity :content content :labels labels}] (prim/transact! comp `[(b/hide-modal {:id :notification-modal}) (mu/add-notification ~notifyObj) (df/fallback {:action ld/reset-error})]))) (defn do-delete-notification [this id slug] (prim/transact! this `[(mu/delete-notification {:id ~id :slug ~slug}) (t/reset-table-page {:id :show-notifications}) (df/fallback {:action ld/reset-error})])) (def ui-tag-box (co/factory-apply TagBox)) (def ui-select-list (co/factory-apply SelectList)) (s/def :notify/slug #(re-matches #"\S+" %)) (defsc NotificationModal [this {:keys [id modal labels selectedItems] :as props}] {:initial-state (fn [p] {:modal (prim/get-initial-state b/Modal {:id :notification-modal :backdrop true}) :modal/page :new-notification :notify/slug "" :description "" :sender "" :category :SECURITY :severity :CRITICAL :content "" :labels [] :selectedItems []}) :ident (fn [] co/new-notification-ident) :query [:notify/slug :description :sender :category :severity :content :labels fs/form-config-join :id :modal/page {:modal (prim/get-query b/Modal)} :selectedItems] :form-fields #{:notify/slug :description :sender :category :severity :content :labels :selectedItems}} (let [tags [] ctg_opts [{ :id :SECURITY, :name "Security" }, { :id :HW_HEALTH, :name "Hardware Health" }, { :id :SW_HEALTH, :name "Software Health" }] sev_opts [{ :id :CRITICAL, :name "Critical" }, { :id :NORMAL, :name "Normal" }] set-opt! (fn [field] #(m/set-value! this field (keyword (. % -id)))) disable-button (fs/invalid-spec? props :notify/slug) button-action (fn [_] (prim/transact! this `[(fs/mark-complete! {:entity-ident ~co/new-notification-ident})]) (when-not (or (not (fs/checked? props)) (fs/invalid-spec? props :notify/slug)) (add-notification this props)))] (b/ui-modal modal (b/ui-modal-title nil (dom/div #js {:key "title" :style #js {:fontSize "22px"}} "Add Notification")) (b/ui-modal-body {:className "exportModal"} (dom/div :$card (dom/div :$content (dom/div :$form-group (co/input-with-label this :notify/slug "Slug:" "Slug is required" "Unique key of the notification" nil {:required true}) (co/input-with-label this :description "Description:" "" "Description of the notification" nil nil) (co/input-with-label this :sender "Sender:" "" "Sender of the notification" nil nil) (co/input-with-label this :category "Category:" "" "" nil nil (fn [attrs] (ui-select-list {:data ctg_opts :textField :name :onChange (set-opt! :category)}))) (co/input-with-label this :severity "Severity:" "" "" nil nil (fn [attrs] (ui-select-list {:data sev_opts :textField :name :onChange (set-opt! :severity)}))) (co/input-with-label this :content "Content:" "" "" nil nil (fn [attrs] (let [attrs (merge attrs {:onChange (fn [event] (m/set-value! this :content (.. event -target -value)))})] (dom/textarea (clj->js attrs))))) (co/input-with-label this :labels "Labels:" "" "" nil nil (fn [attrs] (ui-tag-box #js {:tags (clj->js tags) :selected (clj->js selectedItems) :selectedText "Label exists" :onSelect (fn [tag] (m/set-value! this :selectedItems (conj selectedItems {:label (. tag -label) :value (. tag -label)} )) (m/set-value! this :labels (conj labels (. tag -label)))) :removeTag (fn [tag] (m/set-value! this :selectedItems (vec (filter #(not= (:value %) (. tag -value)) selectedItems))) (m/set-value! this :labels (vec (filter #(not= % (. tag -value)) labels))))}))))))) (b/ui-modal-footer nil (b/button {:key "ok-next-button" :className "btn-fill" :kind :info :disabled disable-button :onClick button-action} "OK") (b/button {:key "cancel-<KEY>" :className "btn-fill" :kind :danger :onClick #(prim/transact! this `[(b/hide-modal {:id :notification-modal}) (fs/reset-form!) (fs/clear-complete!)])} "Cancel"))))) (defn show-transmissions [this type id slug] (prim/transact! this `[(trn/load-transmissions {:slug ~slug})]) (ro/nav-to! this :transmission)) (defn conv-category [_ category] (case category :SECURITY "Security" :HW_HEALTH "Hardware Health" :SW_HEALTH "Software Health" "Unknown")) (defn conv-sev [_ sev] (case sev :CRITICAL "Critical" :NORMAL "Normal" "Unknown")) (defn show-notifications [this] (prim/transact! this `[(load-notifications {})])) (deftable NotificationList :show-notifications :notification [[:slug "Slug"] [:created "Created" #(co/conv-time %2)] [:sender "Sender"] [:category "Category" conv-category] [:severity "Severity" conv-sev] [:content "Content"] [:labels "Labels" #(co/conv-seq %2)]] [{:onClick #(show-notification-modal this) :icon "plus"} {:onClick #(show-notifications this) :icon "refresh"}] :modals [{:modal d/DeleteModal :params {:modal-id :dnt-modal} :callbacks {:onDelete do-delete-notification}}] :actions [{:title "View Transmission" :action-class :info :symbol "file" :onClick show-transmissions} {:title "Delete Transmission" :action-class :danger :symbol "times" :onClick (d/mk-show-modal :dnt-modal props)}] :search-keyword :content :search {:comp NotificationSearch}) (defmutation load-notifications [none] (action [{:keys [reconciler state] :as env}] (let [start (get-in @state [:date-time-picker :notification-dtp-from :time]) end (get-in @state [:date-time-picker :notification-dtp-to :time])] (ld/load reconciler co/notifications-list-ident NotificationList {:params {:start start :end end}}))) (remote [env] (df/remote-load env)))
true
;;; Copyright (c) 2019 ;;; IoTech Ltd ;;; SPDX-License-Identifier: Apache-2.0 (ns org.edgexfoundry.ui.manager.ui.notifications (:require [cljs-time.core :as tc] [clojure.string :as str] [clojure.spec.alpha :as s] [fulcro.client.data-fetch :as df] [fulcro.client.localized-dom :as dom] [fulcro.client.mutations :as m :refer [defmutation]] [fulcro.client.primitives :as prim :refer [defui defsc]] [fulcro.client.routing :as r] [fulcro.ui.bootstrap3 :as b] [fulcro.ui.form-state :as fs] [org.edgexfoundry.ui.manager.api.mutations :as mu] [org.edgexfoundry.ui.manager.ui.common :as co] [org.edgexfoundry.ui.manager.ui.date-time-picker :as dtp] [org.edgexfoundry.ui.manager.ui.dialogs :as d] [org.edgexfoundry.ui.manager.ui.load :as ld] [org.edgexfoundry.ui.manager.ui.routing :as ro] [org.edgexfoundry.ui.manager.ui.table :as t :refer [deftable]] [org.edgexfoundry.ui.manager.ui.transmissions :as trn] ["react-tag-box" :refer [TagBox]] ["react-widgets" :refer [SelectList]])) (defn reset-notification* [state] (update-in state co/new-notification-ident #(merge % {:id nil}))) (defsc NotificationSearch [this {:keys [from-dtp to-dtp]}] {:initial-state (fn [p] {:from-dtp (prim/get-initial-state dtp/DateTimePicker {:id :notification-dtp-from :time (tc/yesterday) :float-left true}) :to-dtp (prim/get-initial-state dtp/DateTimePicker {:id :notification-dtp-to :time (-> (tc/today-at-midnight) (tc/plus (tc/days 1))) :float-left true})}) :ident (fn [] [:notification-search :singleton]) :query [{:from-dtp (prim/get-query dtp/DateTimePicker)} {:to-dtp (prim/get-query dtp/DateTimePicker)}]} (dom/div #js {} (dtp/date-time-picker from-dtp) (dom/div #js {:style #js {:float "right" :margin "0 2px" :position "relative"}} (dtp/date-time-picker to-dtp)))) (declare NotificationModal) (defn prepare-notification* [state] (let [ref co/new-notification-ident] (-> state (fs/add-form-config* NotificationModal ref) (reset-notification*)))) (defmutation prepare-notification [noargs] (action [{:keys [state]}] (swap! state (fn [s] (prepare-notification* s))))) (defn show-notification-modal [comp] (prim/transact! comp `[(prepare-notification) (r/set-route {:router :root/modal-router :target ~co/new-notification-ident}) (b/show-modal {:id :notification-modal}) :modal-router])) (defn add-notification [comp {:keys [notify/slug description sender category severity content labels] :as form}] (let [tmp-id (prim/tempid) notifyObj {:tempid tmp-id :slug slug :description description :sender sender :category category :severity severity :content content :labels labels}] (prim/transact! comp `[(b/hide-modal {:id :notification-modal}) (mu/add-notification ~notifyObj) (df/fallback {:action ld/reset-error})]))) (defn do-delete-notification [this id slug] (prim/transact! this `[(mu/delete-notification {:id ~id :slug ~slug}) (t/reset-table-page {:id :show-notifications}) (df/fallback {:action ld/reset-error})])) (def ui-tag-box (co/factory-apply TagBox)) (def ui-select-list (co/factory-apply SelectList)) (s/def :notify/slug #(re-matches #"\S+" %)) (defsc NotificationModal [this {:keys [id modal labels selectedItems] :as props}] {:initial-state (fn [p] {:modal (prim/get-initial-state b/Modal {:id :notification-modal :backdrop true}) :modal/page :new-notification :notify/slug "" :description "" :sender "" :category :SECURITY :severity :CRITICAL :content "" :labels [] :selectedItems []}) :ident (fn [] co/new-notification-ident) :query [:notify/slug :description :sender :category :severity :content :labels fs/form-config-join :id :modal/page {:modal (prim/get-query b/Modal)} :selectedItems] :form-fields #{:notify/slug :description :sender :category :severity :content :labels :selectedItems}} (let [tags [] ctg_opts [{ :id :SECURITY, :name "Security" }, { :id :HW_HEALTH, :name "Hardware Health" }, { :id :SW_HEALTH, :name "Software Health" }] sev_opts [{ :id :CRITICAL, :name "Critical" }, { :id :NORMAL, :name "Normal" }] set-opt! (fn [field] #(m/set-value! this field (keyword (. % -id)))) disable-button (fs/invalid-spec? props :notify/slug) button-action (fn [_] (prim/transact! this `[(fs/mark-complete! {:entity-ident ~co/new-notification-ident})]) (when-not (or (not (fs/checked? props)) (fs/invalid-spec? props :notify/slug)) (add-notification this props)))] (b/ui-modal modal (b/ui-modal-title nil (dom/div #js {:key "title" :style #js {:fontSize "22px"}} "Add Notification")) (b/ui-modal-body {:className "exportModal"} (dom/div :$card (dom/div :$content (dom/div :$form-group (co/input-with-label this :notify/slug "Slug:" "Slug is required" "Unique key of the notification" nil {:required true}) (co/input-with-label this :description "Description:" "" "Description of the notification" nil nil) (co/input-with-label this :sender "Sender:" "" "Sender of the notification" nil nil) (co/input-with-label this :category "Category:" "" "" nil nil (fn [attrs] (ui-select-list {:data ctg_opts :textField :name :onChange (set-opt! :category)}))) (co/input-with-label this :severity "Severity:" "" "" nil nil (fn [attrs] (ui-select-list {:data sev_opts :textField :name :onChange (set-opt! :severity)}))) (co/input-with-label this :content "Content:" "" "" nil nil (fn [attrs] (let [attrs (merge attrs {:onChange (fn [event] (m/set-value! this :content (.. event -target -value)))})] (dom/textarea (clj->js attrs))))) (co/input-with-label this :labels "Labels:" "" "" nil nil (fn [attrs] (ui-tag-box #js {:tags (clj->js tags) :selected (clj->js selectedItems) :selectedText "Label exists" :onSelect (fn [tag] (m/set-value! this :selectedItems (conj selectedItems {:label (. tag -label) :value (. tag -label)} )) (m/set-value! this :labels (conj labels (. tag -label)))) :removeTag (fn [tag] (m/set-value! this :selectedItems (vec (filter #(not= (:value %) (. tag -value)) selectedItems))) (m/set-value! this :labels (vec (filter #(not= % (. tag -value)) labels))))}))))))) (b/ui-modal-footer nil (b/button {:key "ok-next-button" :className "btn-fill" :kind :info :disabled disable-button :onClick button-action} "OK") (b/button {:key "cancel-PI:KEY:<KEY>END_PI" :className "btn-fill" :kind :danger :onClick #(prim/transact! this `[(b/hide-modal {:id :notification-modal}) (fs/reset-form!) (fs/clear-complete!)])} "Cancel"))))) (defn show-transmissions [this type id slug] (prim/transact! this `[(trn/load-transmissions {:slug ~slug})]) (ro/nav-to! this :transmission)) (defn conv-category [_ category] (case category :SECURITY "Security" :HW_HEALTH "Hardware Health" :SW_HEALTH "Software Health" "Unknown")) (defn conv-sev [_ sev] (case sev :CRITICAL "Critical" :NORMAL "Normal" "Unknown")) (defn show-notifications [this] (prim/transact! this `[(load-notifications {})])) (deftable NotificationList :show-notifications :notification [[:slug "Slug"] [:created "Created" #(co/conv-time %2)] [:sender "Sender"] [:category "Category" conv-category] [:severity "Severity" conv-sev] [:content "Content"] [:labels "Labels" #(co/conv-seq %2)]] [{:onClick #(show-notification-modal this) :icon "plus"} {:onClick #(show-notifications this) :icon "refresh"}] :modals [{:modal d/DeleteModal :params {:modal-id :dnt-modal} :callbacks {:onDelete do-delete-notification}}] :actions [{:title "View Transmission" :action-class :info :symbol "file" :onClick show-transmissions} {:title "Delete Transmission" :action-class :danger :symbol "times" :onClick (d/mk-show-modal :dnt-modal props)}] :search-keyword :content :search {:comp NotificationSearch}) (defmutation load-notifications [none] (action [{:keys [reconciler state] :as env}] (let [start (get-in @state [:date-time-picker :notification-dtp-from :time]) end (get-in @state [:date-time-picker :notification-dtp-to :time])] (ld/load reconciler co/notifications-list-ident NotificationList {:params {:start start :end end}}))) (remote [env] (df/remote-load env)))
[ { "context": "tes the `Pascal Triangle` in lazy way.\"\n {:author [:LeaveNhA \"Seçkin KÜKRER\"]\n :last-update-date \"24-09-2019", "end": 92, "score": 0.900497555732727, "start": 82, "tag": "USERNAME", "value": "[:LeaveNhA" }, { "context": "al Triangle` in lazy way.\"\n {:author [:LeaveNhA \"Seçkin KÜKRER\"]\n :last-update-date \"24-09-2019\"})\n\n(defn row ", "end": 107, "score": 0.9998836517333984, "start": 94, "tag": "NAME", "value": "Seçkin KÜKRER" } ]
exercises/practice/pascals-triangle/src/example-lazy.cljs
joetjen/clojurescript
5
(ns pascals-triangle "Calculates the `Pascal Triangle` in lazy way." {:author [:LeaveNhA "Seçkin KÜKRER"] :last-update-date "24-09-2019"}) (defn row [r] (if (vector? r) (lazy-seq (cons r (row (vec (concat [1N] (map (partial apply +) (partition 2N 1N r)) [1N]))))) (last (take r (row [1]))))) (def triangle (row [1]))
41612
(ns pascals-triangle "Calculates the `Pascal Triangle` in lazy way." {:author [:LeaveNhA "<NAME>"] :last-update-date "24-09-2019"}) (defn row [r] (if (vector? r) (lazy-seq (cons r (row (vec (concat [1N] (map (partial apply +) (partition 2N 1N r)) [1N]))))) (last (take r (row [1]))))) (def triangle (row [1]))
true
(ns pascals-triangle "Calculates the `Pascal Triangle` in lazy way." {:author [:LeaveNhA "PI:NAME:<NAME>END_PI"] :last-update-date "24-09-2019"}) (defn row [r] (if (vector? r) (lazy-seq (cons r (row (vec (concat [1N] (map (partial apply +) (partition 2N 1N r)) [1N]))))) (last (take r (row [1]))))) (def triangle (row [1]))
[ { "context": ";;;\n;;; Copyright 2020 David Edwards\n;;;\n;;; Licensed under the Apache License, Versio", "end": 36, "score": 0.9997915625572205, "start": 23, "tag": "NAME", "value": "David Edwards" } ]
src/rpn/lexer.clj
davidledwards/rpn-clojure
1
;;; ;;; Copyright 2020 David Edwards ;;; ;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;; you may not use this file except in compliance with the License. ;;; You may obtain a copy of the License at ;;; ;;; http://www.apache.org/licenses/LICENSE-2.0 ;;; ;;; Unless required by applicable law or agreed to in writing, software ;;; distributed under the License is distributed on an "AS IS" BASIS, ;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;; See the License for the specific language governing permissions and ;;; limitations under the License. ;;; (ns rpn.lexer "Lexical analyzer." (:require [clojure.string :as string]) (:require [rpn.token :as token])) (def ^:private digits (set (map char (range (int \0) (inc (int \9)))))) (def ^:private letters (set (map char (concat (range (int \A) (inc (int \Z))) (range (int \a) (inc (int \z))))))) (def ^:private whitespace #{\space \newline \tab \return \formfeed}) (defn- read-number [in lexeme] (let [c (first in)] (cond (= c \.) (if (string/includes? lexeme (str c)) (throw (Exception. (str lexeme ": malformed number"))) (recur (rest in) (str lexeme \.))) (digits c) (recur (rest in) (str lexeme c)) :else (if (= (last lexeme) \.) (throw (Exception. (str lexeme ": malformed number"))) [(token/number-token lexeme) in])))) (defn- read-symbol [in lexeme] (let [c (first in)] (cond (letters c) (recur (rest in) (str lexeme c)) :else [(token/reserved-words lexeme (token/symbol-token lexeme)) in]))) (defn- tokenize [in] (let [c (first in)] (cond (whitespace c) (recur (rest in)) (token/simple-words c) [(token/reserved-words (str c)) (rest in)] (digits c) (read-number (rest in) (str c)) (letters c) (read-symbol (rest in) (str c)) (nil? c) [token/EOS-token in] :else (throw (Exception. (str c ": unrecognized character")))))) (defn lexer "A lexical analyzer that transforms a sequence of characters from `in` into a lazy sequence of tokens. Tokens must either be delimited by one or more whitespace characters, or be clearly distinguishable from each other if not separated by whitespace." [in] (lazy-seq (let [[t in-rest] (tokenize in)] (if (token/EOS-token? t) nil (cons t (lexer in-rest))))))
86833
;;; ;;; Copyright 2020 <NAME> ;;; ;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;; you may not use this file except in compliance with the License. ;;; You may obtain a copy of the License at ;;; ;;; http://www.apache.org/licenses/LICENSE-2.0 ;;; ;;; Unless required by applicable law or agreed to in writing, software ;;; distributed under the License is distributed on an "AS IS" BASIS, ;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;; See the License for the specific language governing permissions and ;;; limitations under the License. ;;; (ns rpn.lexer "Lexical analyzer." (:require [clojure.string :as string]) (:require [rpn.token :as token])) (def ^:private digits (set (map char (range (int \0) (inc (int \9)))))) (def ^:private letters (set (map char (concat (range (int \A) (inc (int \Z))) (range (int \a) (inc (int \z))))))) (def ^:private whitespace #{\space \newline \tab \return \formfeed}) (defn- read-number [in lexeme] (let [c (first in)] (cond (= c \.) (if (string/includes? lexeme (str c)) (throw (Exception. (str lexeme ": malformed number"))) (recur (rest in) (str lexeme \.))) (digits c) (recur (rest in) (str lexeme c)) :else (if (= (last lexeme) \.) (throw (Exception. (str lexeme ": malformed number"))) [(token/number-token lexeme) in])))) (defn- read-symbol [in lexeme] (let [c (first in)] (cond (letters c) (recur (rest in) (str lexeme c)) :else [(token/reserved-words lexeme (token/symbol-token lexeme)) in]))) (defn- tokenize [in] (let [c (first in)] (cond (whitespace c) (recur (rest in)) (token/simple-words c) [(token/reserved-words (str c)) (rest in)] (digits c) (read-number (rest in) (str c)) (letters c) (read-symbol (rest in) (str c)) (nil? c) [token/EOS-token in] :else (throw (Exception. (str c ": unrecognized character")))))) (defn lexer "A lexical analyzer that transforms a sequence of characters from `in` into a lazy sequence of tokens. Tokens must either be delimited by one or more whitespace characters, or be clearly distinguishable from each other if not separated by whitespace." [in] (lazy-seq (let [[t in-rest] (tokenize in)] (if (token/EOS-token? t) nil (cons t (lexer in-rest))))))
true
;;; ;;; Copyright 2020 PI:NAME:<NAME>END_PI ;;; ;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;; you may not use this file except in compliance with the License. ;;; You may obtain a copy of the License at ;;; ;;; http://www.apache.org/licenses/LICENSE-2.0 ;;; ;;; Unless required by applicable law or agreed to in writing, software ;;; distributed under the License is distributed on an "AS IS" BASIS, ;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;; See the License for the specific language governing permissions and ;;; limitations under the License. ;;; (ns rpn.lexer "Lexical analyzer." (:require [clojure.string :as string]) (:require [rpn.token :as token])) (def ^:private digits (set (map char (range (int \0) (inc (int \9)))))) (def ^:private letters (set (map char (concat (range (int \A) (inc (int \Z))) (range (int \a) (inc (int \z))))))) (def ^:private whitespace #{\space \newline \tab \return \formfeed}) (defn- read-number [in lexeme] (let [c (first in)] (cond (= c \.) (if (string/includes? lexeme (str c)) (throw (Exception. (str lexeme ": malformed number"))) (recur (rest in) (str lexeme \.))) (digits c) (recur (rest in) (str lexeme c)) :else (if (= (last lexeme) \.) (throw (Exception. (str lexeme ": malformed number"))) [(token/number-token lexeme) in])))) (defn- read-symbol [in lexeme] (let [c (first in)] (cond (letters c) (recur (rest in) (str lexeme c)) :else [(token/reserved-words lexeme (token/symbol-token lexeme)) in]))) (defn- tokenize [in] (let [c (first in)] (cond (whitespace c) (recur (rest in)) (token/simple-words c) [(token/reserved-words (str c)) (rest in)] (digits c) (read-number (rest in) (str c)) (letters c) (read-symbol (rest in) (str c)) (nil? c) [token/EOS-token in] :else (throw (Exception. (str c ": unrecognized character")))))) (defn lexer "A lexical analyzer that transforms a sequence of characters from `in` into a lazy sequence of tokens. Tokens must either be delimited by one or more whitespace characters, or be clearly distinguishable from each other if not separated by whitespace." [in] (lazy-seq (let [[t in-rest] (tokenize in)] (if (token/EOS-token? t) nil (cons t (lexer in-rest))))))
[ { "context": "add-cookies sample-request {:session \"12\" \"name\" \"Nick\"})\n json-body-request (sut/add-body s", "end": 1697, "score": 0.9930961728096008, "start": 1693, "tag": "NAME", "value": "Nick" }, { "context": "st\" (:server-name sample-request)))\n (is (= \"127.0.0.1\" (:remote-addr sample-request)))\n (is (= \"/\"", "end": 2379, "score": 0.999761164188385, "start": 2370, "tag": "IP_ADDRESS", "value": "127.0.0.1" } ]
test/faker/core_test.clj
nnichols/faker
0
(ns faker.core-test (:require [clojure.data.xml :as xml] [clojure.test :refer [deftest is testing]] [faker.core :as sut] [ring.mock.request :as mock])) (def ^:private sample-xml (xml/element :foo {} (xml/element :bar {:bar-attr "baz"}))) (defn ByteStream->string! "Drain a java.io.ByteArrayInputStream of all bytes, and cast it to a string. IMPORTANT: This mutates the state of `stream`, calling this function against the same stream more will always result in \"\"" [stream] (java.lang.String. (.readAllBytes stream))) (deftest ByteStream->string!-demo (testing "Demonstrating that ByteStream->string! is not idempotent" (let [sample-request (sut/add-body (mock/request :get "https://localhost:443/") {:some "key" :another "value"} :json)] (is (= "{\"some\":\"key\",\"another\":\"value\"}" (ByteStream->string! (:body sample-request)))) (is (= "" (ByteStream->string! (:body sample-request)))) (is (= "" (ByteStream->string! (:body sample-request))))))) (deftest update-request-tests (let [sample-request (mock/request :get "https://localhost:443/") json-request (sut/add-content-type sample-request "application/json") content-length-request (sut/add-content-length sample-request "12345") query-string-request (sut/add-query-parameters sample-request "?query=scooby") form-encode-request (sut/add-query-parameters sample-request {:results true :size 50}) headers-request (sut/add-headers sample-request {:auth "some groovy token" :session "random uuid"}) cookies-request (sut/add-cookies sample-request {:session "12" "name" "Nick"}) json-body-request (sut/add-body sample-request {:some "key" :another "value"} :json) raw-body-request (sut/add-body sample-request 123 :raw) form-body-request (sut/add-body sample-request {:pog "champ" :id 3} :inferred) xml-body-request (sut/add-body sample-request sample-xml :xml)] (testing "This block doesn't actually test our functionality, but surfaces the data from ring-mock for comparison (and to see if their API ever changes)" (is (= "HTTP/1.1" (:protocol sample-request))) (is (= 443 (:server-port sample-request))) (is (= "localhost" (:server-name sample-request))) (is (= "127.0.0.1" (:remote-addr sample-request))) (is (= "/" (:uri sample-request))) (is (= :https (:scheme sample-request))) (is (= :get (:request-method sample-request))) (is (= {"host" "localhost:443"} (:headers sample-request))) (is (empty? (dissoc sample-request :protocol :server-port :server-name :remote-addr :uri :scheme :request-method :headers)))) (testing "This block tests all of the add-* functions to make sure the update only the relevant keys" (is (= "application/json" (:content-type json-request))) (is (= "application/json" (get-in json-request [:headers "content-type"]))) (is (= sample-request (-> json-request (dissoc :content-type) (update :headers dissoc "content-type")))) (is (= "12345" (:content-length content-length-request))) (is (= "12345" (get-in content-length-request [:headers "content-length"]))) (is (= sample-request (-> content-length-request (dissoc :content-length) (update :headers dissoc "content-length")))) (is (= sample-request (sut/add-query-parameters sample-request nil))) (is (= "?query=scooby" (:query-string query-string-request))) (is (= sample-request (dissoc query-string-request :query-string))) (is (= "results=true&size=50" (:query-string form-encode-request))) (is (= sample-request (dissoc form-encode-request :query-string))) (is (= sample-request (sut/add-headers sample-request nil))) (is (= sample-request (sut/add-headers sample-request {}))) (is (= {"host" "localhost:443" "auth" "some groovy token" "session" "random uuid"} (:headers headers-request))) (is (= sample-request (update headers-request :headers dissoc "auth" "session"))) (is (= sample-request (sut/add-cookies sample-request nil))) (is (= sample-request (sut/add-cookies sample-request {}))) (is (= {"host" "localhost:443" "cookie" "session=12; name=Nick"} (:headers cookies-request))) (is (= sample-request (update cookies-request :headers dissoc "cookie"))) (is (= sample-request (sut/add-body sample-request nil nil))) (is (= sample-request (sut/add-body sample-request nil :raw))) (is (= 123 (:body raw-body-request))) (is (= sample-request (dissoc raw-body-request :body))) (is (= 2 (:content-length (sut/add-body sample-request {} :json)))) (is (= "application/json" (:content-type (sut/add-body sample-request {} :json)))) (is (= {"host" "localhost:443", "content-type" "application/json", "content-length" "2"} (:headers (sut/add-body sample-request {} :json)))) (is (= java.io.ByteArrayInputStream (type (:body (sut/add-body sample-request {} :json))))) (is (= "{}" (ByteStream->string! (:body (sut/add-body sample-request {} :json))))) (is (= sample-request (-> (sut/add-body sample-request {} :json) (dissoc :content-length :content-type :body) (update :headers dissoc "content-type" "content-length")))) (is (= 32 (:content-length json-body-request))) (is (= "application/json" (:content-type json-body-request))) (is (= {"host" "localhost:443", "content-type" "application/json", "content-length" "32"} (:headers json-body-request))) (is (= java.io.ByteArrayInputStream (type (:body json-body-request)))) (is (= "{\"some\":\"key\",\"another\":\"value\"}" (ByteStream->string! (:body json-body-request)))) (is (= sample-request (-> json-body-request (dissoc :content-length :content-type :body) (update :headers dissoc "content-type" "content-length")))) (is (= "pog=champ&id=3" (ByteStream->string! (:body (sut/add-body sample-request {:pog "champ" :id 3} :form))))) (is (= 14 (:content-length form-body-request))) (is (= "application/x-www-form-urlencoded" (:content-type form-body-request))) (is (= {"host" "localhost:443", "content-type" "application/x-www-form-urlencoded", "content-length" "14"} (:headers form-body-request))) (is (= java.io.ByteArrayInputStream (type (:body form-body-request)))) (is (= "pog=champ&id=3" (ByteStream->string! (:body form-body-request)))) (is (= sample-request (-> form-body-request (dissoc :content-length :content-type :body) (update :headers dissoc "content-type" "content-length")))) (is (= 70 (:content-length xml-body-request))) (is (= "application/xml" (:content-type xml-body-request))) (is (= {"host" "localhost:443", "content-type" "application/xml", "content-length" "70"} (:headers xml-body-request))) (is (= java.io.ByteArrayInputStream (type (:body xml-body-request)))) (is (= "<?xml version=\"1.0\" encoding=\"UTF-8\"?><foo><bar bar-attr=\"baz\"/></foo>" (ByteStream->string! (:body xml-body-request)))) (is (= sample-request (-> xml-body-request (dissoc :content-length :content-type :body) (update :headers dissoc "content-type" "content-length"))))))) (deftest ->uri-test (testing "Demonstrating the route formatting in `->uri`" (is (= "https://localhost:443/v1/test" (sut/->uri :https "localhost" 443 "/v1/test"))) (is (= "ftp://localhost:21/" (sut/->uri :ftp "localhost" 21 "/"))))) (deftest illegal-body-type (testing "Library throws when an unsupported body type is specified" (is (thrown? java.lang.IllegalArgumentException (sut/add-body {} {} :fake))))) (deftest partial-requests (testing "Ensuring each of the wrappers around `mock-request` have the same defaults" (is (= (dissoc (sut/get "/") :request-method) (dissoc (sut/head "/") :request-method) (dissoc (sut/post "/") :request-method) (dissoc (sut/put "/") :request-method) (dissoc (sut/delete "/") :request-method) (dissoc (sut/connect "/") :request-method) (dissoc (sut/options "/") :request-method) (dissoc (sut/trace "/") :request-method) (dissoc (sut/patch "/") :request-method)))))
69952
(ns faker.core-test (:require [clojure.data.xml :as xml] [clojure.test :refer [deftest is testing]] [faker.core :as sut] [ring.mock.request :as mock])) (def ^:private sample-xml (xml/element :foo {} (xml/element :bar {:bar-attr "baz"}))) (defn ByteStream->string! "Drain a java.io.ByteArrayInputStream of all bytes, and cast it to a string. IMPORTANT: This mutates the state of `stream`, calling this function against the same stream more will always result in \"\"" [stream] (java.lang.String. (.readAllBytes stream))) (deftest ByteStream->string!-demo (testing "Demonstrating that ByteStream->string! is not idempotent" (let [sample-request (sut/add-body (mock/request :get "https://localhost:443/") {:some "key" :another "value"} :json)] (is (= "{\"some\":\"key\",\"another\":\"value\"}" (ByteStream->string! (:body sample-request)))) (is (= "" (ByteStream->string! (:body sample-request)))) (is (= "" (ByteStream->string! (:body sample-request))))))) (deftest update-request-tests (let [sample-request (mock/request :get "https://localhost:443/") json-request (sut/add-content-type sample-request "application/json") content-length-request (sut/add-content-length sample-request "12345") query-string-request (sut/add-query-parameters sample-request "?query=scooby") form-encode-request (sut/add-query-parameters sample-request {:results true :size 50}) headers-request (sut/add-headers sample-request {:auth "some groovy token" :session "random uuid"}) cookies-request (sut/add-cookies sample-request {:session "12" "name" "<NAME>"}) json-body-request (sut/add-body sample-request {:some "key" :another "value"} :json) raw-body-request (sut/add-body sample-request 123 :raw) form-body-request (sut/add-body sample-request {:pog "champ" :id 3} :inferred) xml-body-request (sut/add-body sample-request sample-xml :xml)] (testing "This block doesn't actually test our functionality, but surfaces the data from ring-mock for comparison (and to see if their API ever changes)" (is (= "HTTP/1.1" (:protocol sample-request))) (is (= 443 (:server-port sample-request))) (is (= "localhost" (:server-name sample-request))) (is (= "127.0.0.1" (:remote-addr sample-request))) (is (= "/" (:uri sample-request))) (is (= :https (:scheme sample-request))) (is (= :get (:request-method sample-request))) (is (= {"host" "localhost:443"} (:headers sample-request))) (is (empty? (dissoc sample-request :protocol :server-port :server-name :remote-addr :uri :scheme :request-method :headers)))) (testing "This block tests all of the add-* functions to make sure the update only the relevant keys" (is (= "application/json" (:content-type json-request))) (is (= "application/json" (get-in json-request [:headers "content-type"]))) (is (= sample-request (-> json-request (dissoc :content-type) (update :headers dissoc "content-type")))) (is (= "12345" (:content-length content-length-request))) (is (= "12345" (get-in content-length-request [:headers "content-length"]))) (is (= sample-request (-> content-length-request (dissoc :content-length) (update :headers dissoc "content-length")))) (is (= sample-request (sut/add-query-parameters sample-request nil))) (is (= "?query=scooby" (:query-string query-string-request))) (is (= sample-request (dissoc query-string-request :query-string))) (is (= "results=true&size=50" (:query-string form-encode-request))) (is (= sample-request (dissoc form-encode-request :query-string))) (is (= sample-request (sut/add-headers sample-request nil))) (is (= sample-request (sut/add-headers sample-request {}))) (is (= {"host" "localhost:443" "auth" "some groovy token" "session" "random uuid"} (:headers headers-request))) (is (= sample-request (update headers-request :headers dissoc "auth" "session"))) (is (= sample-request (sut/add-cookies sample-request nil))) (is (= sample-request (sut/add-cookies sample-request {}))) (is (= {"host" "localhost:443" "cookie" "session=12; name=Nick"} (:headers cookies-request))) (is (= sample-request (update cookies-request :headers dissoc "cookie"))) (is (= sample-request (sut/add-body sample-request nil nil))) (is (= sample-request (sut/add-body sample-request nil :raw))) (is (= 123 (:body raw-body-request))) (is (= sample-request (dissoc raw-body-request :body))) (is (= 2 (:content-length (sut/add-body sample-request {} :json)))) (is (= "application/json" (:content-type (sut/add-body sample-request {} :json)))) (is (= {"host" "localhost:443", "content-type" "application/json", "content-length" "2"} (:headers (sut/add-body sample-request {} :json)))) (is (= java.io.ByteArrayInputStream (type (:body (sut/add-body sample-request {} :json))))) (is (= "{}" (ByteStream->string! (:body (sut/add-body sample-request {} :json))))) (is (= sample-request (-> (sut/add-body sample-request {} :json) (dissoc :content-length :content-type :body) (update :headers dissoc "content-type" "content-length")))) (is (= 32 (:content-length json-body-request))) (is (= "application/json" (:content-type json-body-request))) (is (= {"host" "localhost:443", "content-type" "application/json", "content-length" "32"} (:headers json-body-request))) (is (= java.io.ByteArrayInputStream (type (:body json-body-request)))) (is (= "{\"some\":\"key\",\"another\":\"value\"}" (ByteStream->string! (:body json-body-request)))) (is (= sample-request (-> json-body-request (dissoc :content-length :content-type :body) (update :headers dissoc "content-type" "content-length")))) (is (= "pog=champ&id=3" (ByteStream->string! (:body (sut/add-body sample-request {:pog "champ" :id 3} :form))))) (is (= 14 (:content-length form-body-request))) (is (= "application/x-www-form-urlencoded" (:content-type form-body-request))) (is (= {"host" "localhost:443", "content-type" "application/x-www-form-urlencoded", "content-length" "14"} (:headers form-body-request))) (is (= java.io.ByteArrayInputStream (type (:body form-body-request)))) (is (= "pog=champ&id=3" (ByteStream->string! (:body form-body-request)))) (is (= sample-request (-> form-body-request (dissoc :content-length :content-type :body) (update :headers dissoc "content-type" "content-length")))) (is (= 70 (:content-length xml-body-request))) (is (= "application/xml" (:content-type xml-body-request))) (is (= {"host" "localhost:443", "content-type" "application/xml", "content-length" "70"} (:headers xml-body-request))) (is (= java.io.ByteArrayInputStream (type (:body xml-body-request)))) (is (= "<?xml version=\"1.0\" encoding=\"UTF-8\"?><foo><bar bar-attr=\"baz\"/></foo>" (ByteStream->string! (:body xml-body-request)))) (is (= sample-request (-> xml-body-request (dissoc :content-length :content-type :body) (update :headers dissoc "content-type" "content-length"))))))) (deftest ->uri-test (testing "Demonstrating the route formatting in `->uri`" (is (= "https://localhost:443/v1/test" (sut/->uri :https "localhost" 443 "/v1/test"))) (is (= "ftp://localhost:21/" (sut/->uri :ftp "localhost" 21 "/"))))) (deftest illegal-body-type (testing "Library throws when an unsupported body type is specified" (is (thrown? java.lang.IllegalArgumentException (sut/add-body {} {} :fake))))) (deftest partial-requests (testing "Ensuring each of the wrappers around `mock-request` have the same defaults" (is (= (dissoc (sut/get "/") :request-method) (dissoc (sut/head "/") :request-method) (dissoc (sut/post "/") :request-method) (dissoc (sut/put "/") :request-method) (dissoc (sut/delete "/") :request-method) (dissoc (sut/connect "/") :request-method) (dissoc (sut/options "/") :request-method) (dissoc (sut/trace "/") :request-method) (dissoc (sut/patch "/") :request-method)))))
true
(ns faker.core-test (:require [clojure.data.xml :as xml] [clojure.test :refer [deftest is testing]] [faker.core :as sut] [ring.mock.request :as mock])) (def ^:private sample-xml (xml/element :foo {} (xml/element :bar {:bar-attr "baz"}))) (defn ByteStream->string! "Drain a java.io.ByteArrayInputStream of all bytes, and cast it to a string. IMPORTANT: This mutates the state of `stream`, calling this function against the same stream more will always result in \"\"" [stream] (java.lang.String. (.readAllBytes stream))) (deftest ByteStream->string!-demo (testing "Demonstrating that ByteStream->string! is not idempotent" (let [sample-request (sut/add-body (mock/request :get "https://localhost:443/") {:some "key" :another "value"} :json)] (is (= "{\"some\":\"key\",\"another\":\"value\"}" (ByteStream->string! (:body sample-request)))) (is (= "" (ByteStream->string! (:body sample-request)))) (is (= "" (ByteStream->string! (:body sample-request))))))) (deftest update-request-tests (let [sample-request (mock/request :get "https://localhost:443/") json-request (sut/add-content-type sample-request "application/json") content-length-request (sut/add-content-length sample-request "12345") query-string-request (sut/add-query-parameters sample-request "?query=scooby") form-encode-request (sut/add-query-parameters sample-request {:results true :size 50}) headers-request (sut/add-headers sample-request {:auth "some groovy token" :session "random uuid"}) cookies-request (sut/add-cookies sample-request {:session "12" "name" "PI:NAME:<NAME>END_PI"}) json-body-request (sut/add-body sample-request {:some "key" :another "value"} :json) raw-body-request (sut/add-body sample-request 123 :raw) form-body-request (sut/add-body sample-request {:pog "champ" :id 3} :inferred) xml-body-request (sut/add-body sample-request sample-xml :xml)] (testing "This block doesn't actually test our functionality, but surfaces the data from ring-mock for comparison (and to see if their API ever changes)" (is (= "HTTP/1.1" (:protocol sample-request))) (is (= 443 (:server-port sample-request))) (is (= "localhost" (:server-name sample-request))) (is (= "127.0.0.1" (:remote-addr sample-request))) (is (= "/" (:uri sample-request))) (is (= :https (:scheme sample-request))) (is (= :get (:request-method sample-request))) (is (= {"host" "localhost:443"} (:headers sample-request))) (is (empty? (dissoc sample-request :protocol :server-port :server-name :remote-addr :uri :scheme :request-method :headers)))) (testing "This block tests all of the add-* functions to make sure the update only the relevant keys" (is (= "application/json" (:content-type json-request))) (is (= "application/json" (get-in json-request [:headers "content-type"]))) (is (= sample-request (-> json-request (dissoc :content-type) (update :headers dissoc "content-type")))) (is (= "12345" (:content-length content-length-request))) (is (= "12345" (get-in content-length-request [:headers "content-length"]))) (is (= sample-request (-> content-length-request (dissoc :content-length) (update :headers dissoc "content-length")))) (is (= sample-request (sut/add-query-parameters sample-request nil))) (is (= "?query=scooby" (:query-string query-string-request))) (is (= sample-request (dissoc query-string-request :query-string))) (is (= "results=true&size=50" (:query-string form-encode-request))) (is (= sample-request (dissoc form-encode-request :query-string))) (is (= sample-request (sut/add-headers sample-request nil))) (is (= sample-request (sut/add-headers sample-request {}))) (is (= {"host" "localhost:443" "auth" "some groovy token" "session" "random uuid"} (:headers headers-request))) (is (= sample-request (update headers-request :headers dissoc "auth" "session"))) (is (= sample-request (sut/add-cookies sample-request nil))) (is (= sample-request (sut/add-cookies sample-request {}))) (is (= {"host" "localhost:443" "cookie" "session=12; name=Nick"} (:headers cookies-request))) (is (= sample-request (update cookies-request :headers dissoc "cookie"))) (is (= sample-request (sut/add-body sample-request nil nil))) (is (= sample-request (sut/add-body sample-request nil :raw))) (is (= 123 (:body raw-body-request))) (is (= sample-request (dissoc raw-body-request :body))) (is (= 2 (:content-length (sut/add-body sample-request {} :json)))) (is (= "application/json" (:content-type (sut/add-body sample-request {} :json)))) (is (= {"host" "localhost:443", "content-type" "application/json", "content-length" "2"} (:headers (sut/add-body sample-request {} :json)))) (is (= java.io.ByteArrayInputStream (type (:body (sut/add-body sample-request {} :json))))) (is (= "{}" (ByteStream->string! (:body (sut/add-body sample-request {} :json))))) (is (= sample-request (-> (sut/add-body sample-request {} :json) (dissoc :content-length :content-type :body) (update :headers dissoc "content-type" "content-length")))) (is (= 32 (:content-length json-body-request))) (is (= "application/json" (:content-type json-body-request))) (is (= {"host" "localhost:443", "content-type" "application/json", "content-length" "32"} (:headers json-body-request))) (is (= java.io.ByteArrayInputStream (type (:body json-body-request)))) (is (= "{\"some\":\"key\",\"another\":\"value\"}" (ByteStream->string! (:body json-body-request)))) (is (= sample-request (-> json-body-request (dissoc :content-length :content-type :body) (update :headers dissoc "content-type" "content-length")))) (is (= "pog=champ&id=3" (ByteStream->string! (:body (sut/add-body sample-request {:pog "champ" :id 3} :form))))) (is (= 14 (:content-length form-body-request))) (is (= "application/x-www-form-urlencoded" (:content-type form-body-request))) (is (= {"host" "localhost:443", "content-type" "application/x-www-form-urlencoded", "content-length" "14"} (:headers form-body-request))) (is (= java.io.ByteArrayInputStream (type (:body form-body-request)))) (is (= "pog=champ&id=3" (ByteStream->string! (:body form-body-request)))) (is (= sample-request (-> form-body-request (dissoc :content-length :content-type :body) (update :headers dissoc "content-type" "content-length")))) (is (= 70 (:content-length xml-body-request))) (is (= "application/xml" (:content-type xml-body-request))) (is (= {"host" "localhost:443", "content-type" "application/xml", "content-length" "70"} (:headers xml-body-request))) (is (= java.io.ByteArrayInputStream (type (:body xml-body-request)))) (is (= "<?xml version=\"1.0\" encoding=\"UTF-8\"?><foo><bar bar-attr=\"baz\"/></foo>" (ByteStream->string! (:body xml-body-request)))) (is (= sample-request (-> xml-body-request (dissoc :content-length :content-type :body) (update :headers dissoc "content-type" "content-length"))))))) (deftest ->uri-test (testing "Demonstrating the route formatting in `->uri`" (is (= "https://localhost:443/v1/test" (sut/->uri :https "localhost" 443 "/v1/test"))) (is (= "ftp://localhost:21/" (sut/->uri :ftp "localhost" 21 "/"))))) (deftest illegal-body-type (testing "Library throws when an unsupported body type is specified" (is (thrown? java.lang.IllegalArgumentException (sut/add-body {} {} :fake))))) (deftest partial-requests (testing "Ensuring each of the wrappers around `mock-request` have the same defaults" (is (= (dissoc (sut/get "/") :request-method) (dissoc (sut/head "/") :request-method) (dissoc (sut/post "/") :request-method) (dissoc (sut/put "/") :request-method) (dissoc (sut/delete "/") :request-method) (dissoc (sut/connect "/") :request-method) (dissoc (sut/options "/") :request-method) (dissoc (sut/trace "/") :request-method) (dissoc (sut/patch "/") :request-method)))))
[ { "context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"wahpenayo at gmail dot com\" \n :date \"2018-01-18\"\n ", "end": 97, "score": 0.5761445760726929, "start": 88, "tag": "EMAIL", "value": "wahpenayo" }, { "context": "ath* :warn-on-boxed)\n(ns ^{:author \"wahpenayo at gmail dot com\" \n :date \"2018-01-18\"\n :doc \"sw", "end": 106, "score": 0.6217911839485168, "start": 102, "tag": "EMAIL", "value": "mail" }, { "context": "rn-on-boxed)\n(ns ^{:author \"wahpenayo at gmail dot com\" \n :date \"2018-01-18\"\n :doc \"sweep minc", "end": 114, "score": 0.6506377458572388, "start": 111, "tag": "EMAIL", "value": "com" } ]
src/scripts/clojure/taigabench/scripts/l2/ontime/mincount.clj
wahpenayo/taigabench
0
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "wahpenayo at gmail dot com" :date "2018-01-18" :doc "sweep mincount values. Public airline ontime data benchmark: https://www.r-bloggers.com/benchmarking-random-forest-implementations/ http://stat-computing.org/dataexpo/2009/" } taigabench.scripts.l2.ontime.mincount (:require [clojure.string :as s] [clojure.java.io :as io] [zana.api :as z] [taiga.api :as taiga] [taigabench.ontime.data :as data] [taigabench.l2.ontime.traintest :as l2])) ;; clj12g src\scripts\clojure\taigabench\scripts\l2\ontime\mincount.clj > ontime.mincount.txt ;; clj48g src\scripts\clojure\taigabench\scripts\l2\ontime\mincount.clj > ontime.mincount.txt ;;---------------------------------------------------------------- (defn- write-csv [^java.util.List records ^java.io.File f] (io/make-parents f) (let [ks (sort (into #{} (mapcat keys records)))] (with-open [w (z/print-writer f)] (binding [*out* w] (println (s/join "," (map name ks))) (doseq [record records] (println (s/join "," (map #(or (str (get record %)) "") ks)))) (flush))))) ;;---------------------------------------------------------------- (def mincounts [7 15 31 63 127 255 511 1023 2047 4095]) (def suffix "2097152") ;;---------------------------------------------------------------- (defn reducer [records ^long mincount] (System/gc) (let [record (z/seconds (print-str "taiga" suffix) (l2/traintest suffix taiga/mean-regression (assoc l2/prototype :mincount mincount))) records (conj records (assoc record :model "taiga"))] (write-csv records (data/output-file "l2-mincount" "taiga.results" "csv")) records)) ;;---------------------------------------------------------------- (reduce reducer [] mincounts) ;;----------------------------------------------------------------
72353
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "<EMAIL> at g<EMAIL> dot <EMAIL>" :date "2018-01-18" :doc "sweep mincount values. Public airline ontime data benchmark: https://www.r-bloggers.com/benchmarking-random-forest-implementations/ http://stat-computing.org/dataexpo/2009/" } taigabench.scripts.l2.ontime.mincount (:require [clojure.string :as s] [clojure.java.io :as io] [zana.api :as z] [taiga.api :as taiga] [taigabench.ontime.data :as data] [taigabench.l2.ontime.traintest :as l2])) ;; clj12g src\scripts\clojure\taigabench\scripts\l2\ontime\mincount.clj > ontime.mincount.txt ;; clj48g src\scripts\clojure\taigabench\scripts\l2\ontime\mincount.clj > ontime.mincount.txt ;;---------------------------------------------------------------- (defn- write-csv [^java.util.List records ^java.io.File f] (io/make-parents f) (let [ks (sort (into #{} (mapcat keys records)))] (with-open [w (z/print-writer f)] (binding [*out* w] (println (s/join "," (map name ks))) (doseq [record records] (println (s/join "," (map #(or (str (get record %)) "") ks)))) (flush))))) ;;---------------------------------------------------------------- (def mincounts [7 15 31 63 127 255 511 1023 2047 4095]) (def suffix "2097152") ;;---------------------------------------------------------------- (defn reducer [records ^long mincount] (System/gc) (let [record (z/seconds (print-str "taiga" suffix) (l2/traintest suffix taiga/mean-regression (assoc l2/prototype :mincount mincount))) records (conj records (assoc record :model "taiga"))] (write-csv records (data/output-file "l2-mincount" "taiga.results" "csv")) records)) ;;---------------------------------------------------------------- (reduce reducer [] mincounts) ;;----------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "PI:EMAIL:<EMAIL>END_PI at gPI:EMAIL:<EMAIL>END_PI dot PI:EMAIL:<EMAIL>END_PI" :date "2018-01-18" :doc "sweep mincount values. Public airline ontime data benchmark: https://www.r-bloggers.com/benchmarking-random-forest-implementations/ http://stat-computing.org/dataexpo/2009/" } taigabench.scripts.l2.ontime.mincount (:require [clojure.string :as s] [clojure.java.io :as io] [zana.api :as z] [taiga.api :as taiga] [taigabench.ontime.data :as data] [taigabench.l2.ontime.traintest :as l2])) ;; clj12g src\scripts\clojure\taigabench\scripts\l2\ontime\mincount.clj > ontime.mincount.txt ;; clj48g src\scripts\clojure\taigabench\scripts\l2\ontime\mincount.clj > ontime.mincount.txt ;;---------------------------------------------------------------- (defn- write-csv [^java.util.List records ^java.io.File f] (io/make-parents f) (let [ks (sort (into #{} (mapcat keys records)))] (with-open [w (z/print-writer f)] (binding [*out* w] (println (s/join "," (map name ks))) (doseq [record records] (println (s/join "," (map #(or (str (get record %)) "") ks)))) (flush))))) ;;---------------------------------------------------------------- (def mincounts [7 15 31 63 127 255 511 1023 2047 4095]) (def suffix "2097152") ;;---------------------------------------------------------------- (defn reducer [records ^long mincount] (System/gc) (let [record (z/seconds (print-str "taiga" suffix) (l2/traintest suffix taiga/mean-regression (assoc l2/prototype :mincount mincount))) records (conj records (assoc record :model "taiga"))] (write-csv records (data/output-file "l2-mincount" "taiga.results" "csv")) records)) ;;---------------------------------------------------------------- (reduce reducer [] mincounts) ;;----------------------------------------------------------------
[ { "context": "er (fn [x] true))\n\n(def card\n {\n :name \"Salesforce New Lead Assist\",\n :header {:title ", "end": 1364, "score": 0.6774859428405762, "start": 1359, "tag": "NAME", "value": "Sales" }, { "context": "ub-salesforce.png\",\n :body [[:lead-name \"Lead Name\"]\n [:lead-mail \"Email\"]\n ", "end": 1819, "score": 0.9902766942977905, "start": 1810, "tag": "NAME", "value": "Lead Name" }, { "context": " :action-key \"USER_INPUT\",\n :request-params {\n", "end": 4485, "score": 0.7168039083480835, "start": 4480, "tag": "KEY", "value": "INPUT" }, { "context": " },\n :action-key \"USER_INPUT\",\n :request-params {\n", "end": 5426, "score": 0.9151191711425781, "start": 5416, "tag": "KEY", "value": "USER_INPUT" } ]
hub-salesforce-leads-connector/src/main/resources/config.clj
vmware/connectors-workspace-one
17
;;Copyright © 2020 VMware, Inc. All Rights Reserved. ;;SPDX-License-Identifier: BSD-2-Clause (require (quote [com.xenovus.xplib :as fl])) (def input identity) (defn get_owner_name [rec] (get (get rec "Owner") "Name")) (defn get_lead_link [rec] (get rec "link")) (def output { :lead-id (fn* [p1__1042#] (get p1__1042# "Id")), :lead-name (fn* [p1__1041#] (get p1__1041# "Name")), :lead-description (fn* [p1__1047#] (get p1__1047# "Description")), :owner-name get_owner_name, :dismiss-url (fn* [p1__1050#] (format "/leads/%s/dismiss" (get p1__1050# "Id"))), :log-call-url (fn* [p1__1049#] (format "/leads/%s/logACall" (get p1__1049# "Id"))), :add-task-url (fn* [p1__1048#] (format "/leads/%s/addTask" (get p1__1048# "Id"))), :id (fn* [p1__1040#] (get p1__1040# "Id")), :lead-phone (fn* [p1__1045#] (get p1__1045# "Phone")), :lead-mail (fn* [p1__1046#] (get p1__1046# "Email")), :lead-status (fn* [p1__1044#] (get p1__1044# "Status")), :lead-company (fn* [p1__1043#] (get p1__1043# "Company")), :lead-link get_lead_link }) (def tenant-admin-filter (fn [x] true)) (def card { :name "Salesforce New Lead Assist", :header {:title "Salesforce - New lead assigned", :subtitle ["New lead" "from" :lead-company], :links {:title "", :subtitle [:lead-link "" ""] } }, :backend_id :lead-id, :image_url "https://vmw-mf-assets.s3.amazonaws.com/connector-images/hub-salesforce.png", :body [[:lead-name "Lead Name"] [:lead-mail "Email"] [:lead-phone "Phone"] [:lead-company "Company"] [:lead-status "Status"] [:owner-name "Owner"] [:lead-description "Comments"] [:lead-link "Lead URL"]], :actions [ { :allow-repeated true, :remove-card-on-completion true, :completed-label "Call Logged", :http-type :post, :primary true, :mutually-exclusive-id "LOG_A_CALL", :label "Log call", :url :log-call-url, :user-input-field { :water-mark "Please Enter Call Details", :min-length 1 }, :action-key "USER_INPUT" } { :allow-repeated true, :remove-card-on-completion true, :completed-label "Task added", :http-type :post, :primary true, :mutually-exclusive-id "ADD_TASK", :label "Add task", :url :add-task-url, :user-input-field { :water-mark "Please Enter Task Subject", :min-length 1 }, :action-key "USER_INPUT" } ], :all-actions [ { :allow-repeated true, :remove-card-on-completion true, :completed-label "Task added", :http-type :post, :primary false, :mutually-exclusive-id "ADD_TASK", :label "Add Task", :url :add-task-url, :user-input-field { :water-mark "Please Enter Task Subject", :min-length 1 }, :action-key "USER_INPUT", :request-params { "lead" :entire } } { :allow-repeated true, :remove-card-on-completion true, :completed-label "Call Logged", :http-type :post, :primary false, :mutually-exclusive-id "LOG_A_CALL", :label "Log A Call", :url :log-call-url, :user-input-field { :water-mark "Please Enter Call Details", :min-length 1 }, :action-key "USER_INPUT", :request-params { "lead" :entire } } { :allow-repeated true, :remove-card-on-completion true, :completed-label "Dismissed", :http-type :post, :primary false, :mutually-exclusive-id "DISMISS_LEAD", :label "Dismiss", :url :dismiss-url, :action-key "DIRECT", :request-params { "lead" :entire } } ] })
71873
;;Copyright © 2020 VMware, Inc. All Rights Reserved. ;;SPDX-License-Identifier: BSD-2-Clause (require (quote [com.xenovus.xplib :as fl])) (def input identity) (defn get_owner_name [rec] (get (get rec "Owner") "Name")) (defn get_lead_link [rec] (get rec "link")) (def output { :lead-id (fn* [p1__1042#] (get p1__1042# "Id")), :lead-name (fn* [p1__1041#] (get p1__1041# "Name")), :lead-description (fn* [p1__1047#] (get p1__1047# "Description")), :owner-name get_owner_name, :dismiss-url (fn* [p1__1050#] (format "/leads/%s/dismiss" (get p1__1050# "Id"))), :log-call-url (fn* [p1__1049#] (format "/leads/%s/logACall" (get p1__1049# "Id"))), :add-task-url (fn* [p1__1048#] (format "/leads/%s/addTask" (get p1__1048# "Id"))), :id (fn* [p1__1040#] (get p1__1040# "Id")), :lead-phone (fn* [p1__1045#] (get p1__1045# "Phone")), :lead-mail (fn* [p1__1046#] (get p1__1046# "Email")), :lead-status (fn* [p1__1044#] (get p1__1044# "Status")), :lead-company (fn* [p1__1043#] (get p1__1043# "Company")), :lead-link get_lead_link }) (def tenant-admin-filter (fn [x] true)) (def card { :name "<NAME>force New Lead Assist", :header {:title "Salesforce - New lead assigned", :subtitle ["New lead" "from" :lead-company], :links {:title "", :subtitle [:lead-link "" ""] } }, :backend_id :lead-id, :image_url "https://vmw-mf-assets.s3.amazonaws.com/connector-images/hub-salesforce.png", :body [[:lead-name "<NAME>"] [:lead-mail "Email"] [:lead-phone "Phone"] [:lead-company "Company"] [:lead-status "Status"] [:owner-name "Owner"] [:lead-description "Comments"] [:lead-link "Lead URL"]], :actions [ { :allow-repeated true, :remove-card-on-completion true, :completed-label "Call Logged", :http-type :post, :primary true, :mutually-exclusive-id "LOG_A_CALL", :label "Log call", :url :log-call-url, :user-input-field { :water-mark "Please Enter Call Details", :min-length 1 }, :action-key "USER_INPUT" } { :allow-repeated true, :remove-card-on-completion true, :completed-label "Task added", :http-type :post, :primary true, :mutually-exclusive-id "ADD_TASK", :label "Add task", :url :add-task-url, :user-input-field { :water-mark "Please Enter Task Subject", :min-length 1 }, :action-key "USER_INPUT" } ], :all-actions [ { :allow-repeated true, :remove-card-on-completion true, :completed-label "Task added", :http-type :post, :primary false, :mutually-exclusive-id "ADD_TASK", :label "Add Task", :url :add-task-url, :user-input-field { :water-mark "Please Enter Task Subject", :min-length 1 }, :action-key "USER_<KEY>", :request-params { "lead" :entire } } { :allow-repeated true, :remove-card-on-completion true, :completed-label "Call Logged", :http-type :post, :primary false, :mutually-exclusive-id "LOG_A_CALL", :label "Log A Call", :url :log-call-url, :user-input-field { :water-mark "Please Enter Call Details", :min-length 1 }, :action-key "<KEY>", :request-params { "lead" :entire } } { :allow-repeated true, :remove-card-on-completion true, :completed-label "Dismissed", :http-type :post, :primary false, :mutually-exclusive-id "DISMISS_LEAD", :label "Dismiss", :url :dismiss-url, :action-key "DIRECT", :request-params { "lead" :entire } } ] })
true
;;Copyright © 2020 VMware, Inc. All Rights Reserved. ;;SPDX-License-Identifier: BSD-2-Clause (require (quote [com.xenovus.xplib :as fl])) (def input identity) (defn get_owner_name [rec] (get (get rec "Owner") "Name")) (defn get_lead_link [rec] (get rec "link")) (def output { :lead-id (fn* [p1__1042#] (get p1__1042# "Id")), :lead-name (fn* [p1__1041#] (get p1__1041# "Name")), :lead-description (fn* [p1__1047#] (get p1__1047# "Description")), :owner-name get_owner_name, :dismiss-url (fn* [p1__1050#] (format "/leads/%s/dismiss" (get p1__1050# "Id"))), :log-call-url (fn* [p1__1049#] (format "/leads/%s/logACall" (get p1__1049# "Id"))), :add-task-url (fn* [p1__1048#] (format "/leads/%s/addTask" (get p1__1048# "Id"))), :id (fn* [p1__1040#] (get p1__1040# "Id")), :lead-phone (fn* [p1__1045#] (get p1__1045# "Phone")), :lead-mail (fn* [p1__1046#] (get p1__1046# "Email")), :lead-status (fn* [p1__1044#] (get p1__1044# "Status")), :lead-company (fn* [p1__1043#] (get p1__1043# "Company")), :lead-link get_lead_link }) (def tenant-admin-filter (fn [x] true)) (def card { :name "PI:NAME:<NAME>END_PIforce New Lead Assist", :header {:title "Salesforce - New lead assigned", :subtitle ["New lead" "from" :lead-company], :links {:title "", :subtitle [:lead-link "" ""] } }, :backend_id :lead-id, :image_url "https://vmw-mf-assets.s3.amazonaws.com/connector-images/hub-salesforce.png", :body [[:lead-name "PI:NAME:<NAME>END_PI"] [:lead-mail "Email"] [:lead-phone "Phone"] [:lead-company "Company"] [:lead-status "Status"] [:owner-name "Owner"] [:lead-description "Comments"] [:lead-link "Lead URL"]], :actions [ { :allow-repeated true, :remove-card-on-completion true, :completed-label "Call Logged", :http-type :post, :primary true, :mutually-exclusive-id "LOG_A_CALL", :label "Log call", :url :log-call-url, :user-input-field { :water-mark "Please Enter Call Details", :min-length 1 }, :action-key "USER_INPUT" } { :allow-repeated true, :remove-card-on-completion true, :completed-label "Task added", :http-type :post, :primary true, :mutually-exclusive-id "ADD_TASK", :label "Add task", :url :add-task-url, :user-input-field { :water-mark "Please Enter Task Subject", :min-length 1 }, :action-key "USER_INPUT" } ], :all-actions [ { :allow-repeated true, :remove-card-on-completion true, :completed-label "Task added", :http-type :post, :primary false, :mutually-exclusive-id "ADD_TASK", :label "Add Task", :url :add-task-url, :user-input-field { :water-mark "Please Enter Task Subject", :min-length 1 }, :action-key "USER_PI:KEY:<KEY>END_PI", :request-params { "lead" :entire } } { :allow-repeated true, :remove-card-on-completion true, :completed-label "Call Logged", :http-type :post, :primary false, :mutually-exclusive-id "LOG_A_CALL", :label "Log A Call", :url :log-call-url, :user-input-field { :water-mark "Please Enter Call Details", :min-length 1 }, :action-key "PI:KEY:<KEY>END_PI", :request-params { "lead" :entire } } { :allow-repeated true, :remove-card-on-completion true, :completed-label "Dismissed", :http-type :post, :primary false, :mutually-exclusive-id "DISMISS_LEAD", :label "Dismiss", :url :dismiss-url, :action-key "DIRECT", :request-params { "lead" :entire } } ] })
[ { "context": "[[org.rksm/test-helpers \"0.1.0\"]]}}\n :scm {:url \"git@github.com:cloxp/cloxp-projects.git\"}\n :pom-addition [:deve", "end": 753, "score": 0.9920382499694824, "start": 739, "tag": "EMAIL", "value": "git@github.com" }, { "context": "[:developer\n [:name \"Robert Krahn\"]\n [:url \"http://rob", "end": 872, "score": 0.9998847842216492, "start": 860, "tag": "NAME", "value": "Robert Krahn" }, { "context": "t.kra.hn\"]\n [:email \"robert.krahn@gmail.com\"]\n [:timezone \"-9\"]]", "end": 996, "score": 0.9999268651008606, "start": 974, "tag": "EMAIL", "value": "robert.krahn@gmail.com" } ]
project.clj
cloxp/cloxp-projects
1
(defproject org.rksm/cloxp-projects "0.1.10-SNAPSHOT" :description "Dealing with clojure projects and project configurations." :license {:name "MIT License" :url "http://opensource.org/licenses/MIT"} :url "http://github.com/cloxp/cloxp-projects" :dependencies [[org.clojure/clojure "1.7.0"] [org.clojure/data.xml "0.0.8"] [org.clojure/data.json "0.2.6"] [com.cemerick/pomegranate "0.3.0"] [org.rksm/system-files "0.1.7-SNAPSHOT"] [classlojure/classlojure "0.6.6"] [leiningen/leiningen "2.5.1" :exclusions [org.clojure/tools.reader]]] :profiles {:dev {:dependencies [[org.rksm/test-helpers "0.1.0"]]}} :scm {:url "git@github.com:cloxp/cloxp-projects.git"} :pom-addition [:developers [:developer [:name "Robert Krahn"] [:url "http://robert.kra.hn"] [:email "robert.krahn@gmail.com"] [:timezone "-9"]]])
111184
(defproject org.rksm/cloxp-projects "0.1.10-SNAPSHOT" :description "Dealing with clojure projects and project configurations." :license {:name "MIT License" :url "http://opensource.org/licenses/MIT"} :url "http://github.com/cloxp/cloxp-projects" :dependencies [[org.clojure/clojure "1.7.0"] [org.clojure/data.xml "0.0.8"] [org.clojure/data.json "0.2.6"] [com.cemerick/pomegranate "0.3.0"] [org.rksm/system-files "0.1.7-SNAPSHOT"] [classlojure/classlojure "0.6.6"] [leiningen/leiningen "2.5.1" :exclusions [org.clojure/tools.reader]]] :profiles {:dev {:dependencies [[org.rksm/test-helpers "0.1.0"]]}} :scm {:url "<EMAIL>:cloxp/cloxp-projects.git"} :pom-addition [:developers [:developer [:name "<NAME>"] [:url "http://robert.kra.hn"] [:email "<EMAIL>"] [:timezone "-9"]]])
true
(defproject org.rksm/cloxp-projects "0.1.10-SNAPSHOT" :description "Dealing with clojure projects and project configurations." :license {:name "MIT License" :url "http://opensource.org/licenses/MIT"} :url "http://github.com/cloxp/cloxp-projects" :dependencies [[org.clojure/clojure "1.7.0"] [org.clojure/data.xml "0.0.8"] [org.clojure/data.json "0.2.6"] [com.cemerick/pomegranate "0.3.0"] [org.rksm/system-files "0.1.7-SNAPSHOT"] [classlojure/classlojure "0.6.6"] [leiningen/leiningen "2.5.1" :exclusions [org.clojure/tools.reader]]] :profiles {:dev {:dependencies [[org.rksm/test-helpers "0.1.0"]]}} :scm {:url "PI:EMAIL:<EMAIL>END_PI:cloxp/cloxp-projects.git"} :pom-addition [:developers [:developer [:name "PI:NAME:<NAME>END_PI"] [:url "http://robert.kra.hn"] [:email "PI:EMAIL:<EMAIL>END_PI"] [:timezone "-9"]]])
[ { "context": "mbre :as timbre]))\n\n\n(def environment {:local-ip \"127.0.0.1\"})\n(defn authenticated\n [state source request]\n ", "end": 1131, "score": 0.9997107982635498, "start": 1122, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "different users\"\n (let [id1 (gen-identity \"user1\")\n id2 (gen-identity \"user2\")\n ", "end": 4978, "score": 0.6346007585525513, "start": 4977, "tag": "USERNAME", "value": "1" }, { "context": "source-2 peer-id-2 peer-id-1 (assoc id1 :machine \"127.0.0.1\") {:local true})\n (msg/success sourc", "end": 13012, "score": 0.9996417164802551, "start": 13003, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": " (let [\n id1 (assoc (gen-identity) :user \"user\")\n id2 (assoc (gen-identity) :user \"user\")", "end": 14257, "score": 0.9925616383552551, "start": 14253, "tag": "USERNAME", "value": "user" }, { "context": " \"user\")\n id2 (assoc (gen-identity) :user \"user\")\n id3 (assoc (gen-identity) :user \"other-", "end": 14305, "score": 0.9765127301216125, "start": 14301, "tag": "USERNAME", "value": "user" }, { "context": " \"user\")\n id3 (assoc (gen-identity) :user \"other-user\")\n [peer-id-1 peer-id-2 peer-id-3] (repeat", "end": 14359, "score": 0.954728364944458, "start": 14349, "tag": "USERNAME", "value": "other-user" }, { "context": " (let [\n id1 (assoc (gen-identity) :user \"user\")\n id2 (assoc (gen-identity) :user \"other-", "end": 22455, "score": 0.998485267162323, "start": 22451, "tag": "USERNAME", "value": "user" }, { "context": " \"user\")\n id2 (assoc (gen-identity) :user \"other-user\")\n [peer-id-1 peer-id-2] (repeatedly 2 pee", "end": 22509, "score": 0.99245685338974, "start": 22499, "tag": "USERNAME", "value": "other-user" }, { "context": " (let [\n id1 (assoc (gen-identity) :user \"user\")\n id2 (assoc (gen-identity) :user \"user\")", "end": 24289, "score": 0.9964984655380249, "start": 24285, "tag": "USERNAME", "value": "user" }, { "context": " \"user\")\n id2 (assoc (gen-identity) :user \"user\")\n [peer-id-1 peer-id-2] (repeatedly 2 pee", "end": 24337, "score": 0.9962478280067444, "start": 24333, "tag": "USERNAME", "value": "user" }, { "context": " :peer_id peer-id-1 :identity (assoc id1 :secret \"buhal\")})\n (first)\n ", "end": 29217, "score": 0.6153890490531921, "start": 29212, "tag": "KEY", "value": "buhal" }, { "context": " :peer_id peer-id-2 :identity (assoc id2 :secret \"buhal\")})\n (first)\n ", "end": 29384, "score": 0.658734917640686, "start": 29379, "tag": "KEY", "value": "buhal" }, { "context": " :peer_id peer-id-1 :identity (assoc id1 :secret \"buhal\")})\n (first)\n ", "end": 36796, "score": 0.6339477300643921, "start": 36791, "tag": "KEY", "value": "buhal" } ]
context-domain/test/gateway/domains/context/t_core.cljc
tsachev/gateway-modules
15
(ns gateway.domains.context.t-core (:require [clojure.test :refer :all] #?(:cljs [gateway.t-macros :refer-macros [just? error-msg?]]) #?(:clj [gateway.t-macros :refer [just? error-msg?]]) [gateway.reason :refer [reason]] [gateway.domains.global.constants :as c] [gateway.domains.context.core :as ctx] [gateway.domains.context.helpers :refer [context-id]] [gateway.domains.global.core :as gc] [gateway.domains.context.messages :as msg] [gateway.t-helpers :refer [gen-identity ch->src request-id! new-state ->node-id node-id peer-id! local-peer remote-peer msgs->ctx-version]] [gateway.common.context.state :as state] [gateway.domains.context.constants :as constants] [gateway.common.context.constants :as cc] [gateway.common.commands :as commands] [gateway.state.peers :as peers] [gateway.common.messages :as m] [gateway.local-node.core :as local-node] [taoensso.timbre :as timbre])) (def environment {:local-ip "127.0.0.1"}) (defn authenticated [state source request] (gc/authenticated state source request nil environment)) (defn create-join [state source request] (let [{:keys [peer_id identity]} request] (-> state (peers/ensure-peer-with-id source peer_id identity nil (:options request)) (first) (ctx/join source (assoc request :domain c/global-domain-uri :destination constants/context-domain-uri))))) (deftest context-creation (testing "contexts can be created if missing" (let [ id1 (gen-identity) source (ch->src "source") request-id (request-id!) context-name "my context" peer-id-1 (peer-id!) create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions nil} msgs (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (ctx/create source create-rq) (second)) context-id (context-id :context-created msgs)] (just? msgs [(msg/context-created source request-id peer-id-1 context-id) (msg/context-added source peer-id-1 peer-id-1 context-id context-name) (m/broadcast {:type :peer :peer-id peer-id-1 :node node-id} (assoc create-rq :type :create-context :version (msgs->ctx-version msgs)))]))) (testing "trying to create a context with an existing name subscribes for it" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {:t 41} :lifetime "retained" :read_permissions nil :write_permissions nil} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) create-rq-2 {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :name context-name :data {:t 42} :lifetime "retained" :read_permissions nil :write_permissions nil} msgs (-> state (ctx/create source create-rq-2) (second))] (is (= msgs [(msg/subscribed-context source request-id peer-id-2 context-id {:t 41})])))) (testing "there can be multiple contexts with the same name for peers with different users" (let [id1 (gen-identity "user1") id2 (gen-identity "user2") [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {:t 41} :lifetime "retained" :read_permissions nil :write_permissions nil} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) create-rq-2 {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :name context-name :data {:t 42} :lifetime "retained" :read_permissions nil :write_permissions nil} [state msgs] (-> state (ctx/create source-2 create-rq-2)) ctx-1 (state/context-by-name state context-name (peers/by-id* state peer-id-1)) ctx-2 (state/context-by-name state context-name (peers/by-id* state peer-id-2))] (is (not= ctx-1 ctx-2)) (just? msgs [(msg/context-created source-2 request-id peer-id-2 (:id ctx-2)) (msg/context-added source-2 peer-id-2 peer-id-2 (:id ctx-2) context-name) (m/broadcast {:type :peer :peer-id peer-id-2 :node node-id} (assoc create-rq-2 :type :create-context :version (msgs->ctx-version msgs)))]))) (testing "creating a context without a peer returns an error" ;; ghostwheel will throw an exception (is (thrown? #?(:clj Exception :cljs :default) (let [request-id (request-id!) source (ch->src "source") msgs (-> (new-state) (ctx/create source {:request_id request-id :name "context-name" :data {:t 41} :lifetime "retained" :read_permissions nil :write_permissions nil}) (second))] (is (error-msg? constants/failure (first msgs)))))))) (deftest context-announcement (testing "when a context is created, its announced to all peers that can see it" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions nil} msgs (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq) (second)) context-id (context-id :context-created msgs)] (just? [(msg/context-added source peer-id-1 peer-id-1 context-id context-name) (msg/context-added source-2 peer-id-2 peer-id-1 context-id context-name) (msg/context-created source request-id peer-id-1 context-id) (m/broadcast {:type :peer :peer-id peer-id-1 :node node-id} (assoc create-rq :type :create-context :version (msgs->ctx-version msgs)))] msgs))) (testing "when a peer join, it receives an announcement for all contexts that it can see" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" request {:request_id request-id :peer_id peer-id-2 :identity id2 :domain c/global-domain-uri :destination constants/context-domain-uri} create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions nil} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (ctx/create source create-rq) (first) (create-join source-2 request)) context (state/context-by-name state context-name (peers/by-id* state peer-id-1)) context-id (:id context)] (just? msgs [(m/peer-added constants/context-domain-uri source-2 peer-id-2 peer-id-1 id1 {:local true}) (m/peer-added constants/context-domain-uri source peer-id-1 peer-id-2 id2 {:local true}) (msg/context-added source-2 peer-id-2 peer-id-1 context-id context-name) (msg/success source-2 request-id peer-id-2) (m/broadcast {:type :peer :peer-id peer-id-2 :node node-id} (assoc request :type :join))]))) (testing "peer joined thru the compatibility mode global domain doesnt receive announcements, but is announced" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) [state msgs] (-> (new-state) (assoc :registered-domains (local-node/build-domains [(ctx/context-domain)])) (authenticated source {:request_id request-id :remote-identity id1})) peer-id-1 (get-in (first msgs) [:body :peer_id]) request {:request_id request-id :peer_id peer-id-2 :identity id2 :domain c/global-domain-uri :destination constants/context-domain-uri} [state msgs] (-> state (create-join source-2 request))] (just? msgs [(m/peer-added constants/context-domain-uri source-2 peer-id-2 peer-id-1 (assoc id1 :machine "127.0.0.1") {:local true}) (msg/success source-2 request-id peer-id-2) (m/broadcast {:type :peer :peer-id peer-id-2 :node node-id} (assoc request :type :join))]) (testing "then if it joins the context domain, it gets announcements of the rest of the peers" (let [ request {:request_id request-id :peer_id peer-id-1 :identity id1 :domain c/global-domain-uri :destination constants/context-domain-uri} [state msgs] (-> state (ctx/join source request))] (just? msgs [(m/peer-added constants/context-domain-uri source peer-id-1 peer-id-2 id2 {:local true}) (msg/success source request-id peer-id-1) (m/broadcast {:type :peer :peer-id peer-id-1 :node node-id} (assoc request :type :join))])))))) (deftest context-restricted-announcement (let [ id1 (assoc (gen-identity) :user "user") id2 (assoc (gen-identity) :user "user") id3 (assoc (gen-identity) :user "other-user") [peer-id-1 peer-id-2 peer-id-3] (repeatedly 3 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") source-3 (ch->src "source-3") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions "$user==#user" :write_permissions nil} msgs (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (create-join source-3 {:request_id request-id :peer_id peer-id-3 :identity id3}) (first) (ctx/create source create-rq) (second)) context-id (context-id :context-created msgs)] (just? [(msg/context-added source peer-id-1 peer-id-1 context-id context-name) (msg/context-added source-2 peer-id-2 peer-id-1 context-id context-name) (msg/context-created source request-id peer-id-1 context-id) (m/broadcast {:type :peer :peer-id peer-id-1 :node node-id} (assoc create-rq :type :create-context :version (msgs->ctx-version msgs)))] msgs))) (deftest context-destroyed-when-owner-leaves (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions nil} state-with-context (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq) (first)) context (state/context-by-name state-with-context context-name (peers/by-id* state-with-context peer-id-1)) remove-rq {:type ::commands/source-removed} [state msgs] (ctx/source-removed state-with-context source remove-rq)] (is (nil? (state/context-by-name state context-name (peers/by-id* state-with-context peer-id-1)))) (is (= msgs [(msg/context-destroyed source-2 peer-id-2 (:id context) (cc/context-destroyed-peer-left constants/context-domain-uri)) (m/peer-removed constants/context-domain-uri source-2 peer-id-2 peer-id-1 constants/reason-peer-removed) (m/broadcast {:type :peer :peer-id peer-id-1 :node node-id} {:request_id nil :domain c/global-domain-uri :peer_id peer-id-1 :type :leave :destination constants/context-domain-uri :reason_uri (:uri constants/reason-peer-removed) :reason (:message constants/reason-peer-removed)})])))) (deftest owner-destroys-context (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions nil} state-with-context (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq) (first)) context (state/context-by-name state-with-context context-name (peers/by-id* state-with-context peer-id-1)) ctx-id (:id context) destroy-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :context_id ctx-id} [state msgs] (ctx/destroy state-with-context source destroy-rq)] (is (nil? (state/context-by-name state context-name (peers/by-id* state-with-context peer-id-1)))) (just? msgs [(msg/context-destroyed source peer-id-1 ctx-id (cc/context-destroyed-explicitly constants/context-domain-uri)) (msg/context-destroyed source-2 peer-id-2 ctx-id (cc/context-destroyed-explicitly constants/context-domain-uri)) (msg/success source request-id peer-id-1) (m/broadcast {:type :peer :peer-id peer-id-1 :node node-id} (assoc destroy-rq :type :destroy-context :name context-name))]))) (deftest non-owner-cant-destroy (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions nil} state-with-context (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq) (first)) context (state/context-by-name state-with-context context-name (peers/by-id* state-with-context peer-id-1)) ctx-id (:id context) [state msgs] (ctx/destroy state-with-context source-2 {:request_id request-id :peer_id peer-id-2 :context_id ctx-id})] (is (some? (state/context-by-name state context-name (peers/by-id* state-with-context peer-id-1)))) (is (= msgs [(msg/error source-2 request-id peer-id-2 (reason (cc/context-not-authorized constants/context-domain-uri) "Not authorized to destroy context"))])))) (deftest destroy-restricted-fail (let [ id1 (assoc (gen-identity) :user "user") id2 (assoc (gen-identity) :user "other-user") [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src nil) source-2 (ch->src nil) request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ref-counted" :read_permissions nil :write_permissions "$user==#user"} state-with-context (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq) (first)) context (state/context-by-name state-with-context context-name (peers/by-id* state-with-context peer-id-1)) ctx-id (:id context) [state msgs] (ctx/destroy state-with-context source-2 {:request_id request-id :peer_id peer-id-2 :context_id ctx-id})] (is (some? (state/context-by-name state context-name (peers/by-id* state-with-context peer-id-1)))) (is (= msgs [(msg/error source-2 request-id peer-id-2 (reason (cc/context-not-authorized constants/context-domain-uri) "Not authorized to destroy context"))])))) (deftest destroy-restricted-success (let [ id1 (assoc (gen-identity) :user "user") id2 (assoc (gen-identity) :user "user") [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ref-counted" :read_permissions nil :write_permissions "$user==#user"} state-with-context (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq) (first)) context (state/context-by-name state-with-context context-name (peers/by-id* state-with-context peer-id-1)) ctx-id (:id context) destroy-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id ctx-id} [state msgs] (ctx/destroy state-with-context source-2 destroy-rq)] (is (nil? (state/context-by-name state context-name (peers/by-id* state-with-context peer-id-1)))) (just? msgs [(msg/context-destroyed source peer-id-1 ctx-id (cc/context-destroyed-explicitly constants/context-domain-uri)) (msg/context-destroyed source-2 peer-id-2 ctx-id (cc/context-destroyed-explicitly constants/context-domain-uri)) (msg/success source-2 request-id peer-id-2) (m/broadcast {:type :peer :peer-id peer-id-2 :node node-id} (assoc destroy-rq :type :destroy-context :name context-name))]))) (deftest context-subscription (testing "contexts can be subscribed to" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions nil} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) subscribe-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id} msgs (-> state (ctx/subscribe source-2 subscribe-rq) (second))] (just? msgs [(msg/subscribed-context source-2 request-id peer-id-2 context-id {}) (m/broadcast {:type :peer :peer-id peer-id-2 :node node-id} (assoc subscribe-rq :type :subscribe-context :name context-name))]))) (testing "having read permissions allows you to subscribe" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions "#secret == $secret" :write_permissions nil} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity (assoc id1 :secret "buhal")}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity (assoc id2 :secret "buhal")}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) subscribe-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id} msgs (-> state (ctx/subscribe source-2 subscribe-rq) (second))] (just? msgs [(msg/subscribed-context source-2 request-id peer-id-2 context-id {}) (m/broadcast {:type :peer :peer-id peer-id-2 :node node-id} (assoc subscribe-rq :type :subscribe-context :name context-name))]))) (testing "unsubscribing from a context stops all evens from it" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions nil} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) ;; unsubscribe from the context unsub-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id} [state unsub-msgs] (-> state (ctx/subscribe source-2 {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id}) (first) (ctx/unsubscribe source-2 unsub-rq)) ;; send an update delta {:added {"k" 5}} update-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :context_id context-id :delta delta} msgs (-> state (ctx/update-ctx source update-rq) (second))] (is (= unsub-msgs [(msg/success source-2 request-id peer-id-2) (m/broadcast {:type :peer :peer-id peer-id-2 :node node-id} (assoc unsub-rq :type :unsubscribe-context :name context-name))])) (just? msgs [(msg/success source request-id peer-id-1) (m/broadcast {:type :peer :peer-id peer-id-1 :node node-id} (assoc update-rq :type :update-context :name context-name :version (msgs->ctx-version msgs)))])))) (deftest context-updates (testing "when a context is updated, the update is broadcasted to all members" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions nil} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) delta {:added {"k" 5}} update-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :context_id context-id :delta delta} msgs (-> state (ctx/subscribe source-2 {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id}) (first) (ctx/update-ctx source update-rq) (second))] (just? msgs [(msg/context-updated source-2 peer-id-2 peer-id-1 context-id delta) (msg/success source request-id peer-id-1) (m/broadcast {:type :peer :peer-id peer-id-1 :node node-id} (assoc update-rq :type :update-context :name context-name :version (msgs->ctx-version msgs)))]))) (testing "updating a context is governed by write permissions" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions "$secret == #secret"} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity (assoc id1 :secret "buhal")}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) delta {:added {"k" 5}} update-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id :delta delta} msgs (-> state (ctx/subscribe source-2 {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id}) (first) (ctx/update-ctx source-2 update-rq) (second))] (just? msgs [(m/error constants/context-domain-uri source-2 request-id peer-id-2 (reason (cc/context-not-authorized constants/context-domain-uri) "Not authorized to update context"))]))) (testing "not having permissions stops you from subscribing to a context" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions "$secret == '1'" :write_permissions "$secret == '2'"} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity (assoc id1 :secret "2")}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity (assoc id2 :secret "3")}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) msgs (-> state (ctx/subscribe source-2 {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id}) (second))] (just? msgs [(m/error constants/context-domain-uri source-2 request-id peer-id-2 (reason (cc/context-not-authorized constants/context-domain-uri) "Not authorized to read context"))]))) (testing "not having a permissions stops you from subscribing via create" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions "$secret == '1'" :write_permissions "$secret == '2'"} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity (assoc id1 :secret "2")}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity (assoc id2 :secret "3")}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) msgs (-> state (ctx/create source-2 (assoc create-rq :peer_id peer-id-2)) (second))] (just? msgs [(m/error constants/context-domain-uri source-2 request-id peer-id-2 (reason (cc/context-not-authorized constants/context-domain-uri) "Not authorized to read context"))]))) (testing "having matching write permissions allows reading even if the read permissions dont match" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions "$secret == '1'" :write_permissions "$secret == '2'"} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity (assoc id1 :secret "2")}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity (assoc id2 :secret "2")}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) subscribe-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id} msgs (-> state (ctx/subscribe source-2 subscribe-rq) (second))] (just? msgs [(msg/subscribed-context source-2 request-id peer-id-2 context-id {}) (m/broadcast {:type :peer :peer-id peer-id-2 :node node-id} (assoc subscribe-rq :type :subscribe-context :name context-name))]))) (testing "data can be deleted" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions nil} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) delta {:removed ["remove-me"]} update-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :context_id context-id :delta delta} msgs (-> state (ctx/subscribe source-2 {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id}) (first) (ctx/update-ctx source update-rq) (second))] (just? msgs [(msg/context-updated source-2 peer-id-2 peer-id-1 context-id delta) (msg/success source request-id peer-id-1) (m/broadcast {:type :peer :peer-id peer-id-1 :node node-id} (assoc update-rq :type :update-context :name context-name :version (msgs->ctx-version msgs)))])))) (deftest context-resets (testing "when a context is reset, the update is broadcasted to all members" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" old-ctx {"a" 1 "b" 2} new-ctx {"a" 2 "c" 3 "d" 4} delta {:reset new-ctx} create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data old-ctx :lifetime "ownership" :read_permissions nil :write_permissions nil} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) update-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :context_id context-id :delta delta} msgs (-> state (ctx/subscribe source-2 {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id}) (first) (ctx/update-ctx source update-rq) (second))] (just? msgs [(msg/context-updated source-2 peer-id-2 peer-id-1 context-id delta) (msg/success source request-id peer-id-1) (m/broadcast {:type :peer :peer-id peer-id-1 :node node-id} (assoc update-rq :type :update-context :name context-name :version (msgs->ctx-version msgs)))])))) (deftest context-update-handling (testing "updated merges the data key by key" (let [state {:contexts {1 {:id 1 :data {:meta {:channel "red"} :data {:color "red" :fruit "apple"}}}}} ctx (state/context-by-id state 1)] (is (= {:data {:color "green" :fruit "apple"} :meta {:channel "red"}} (-> state (state/apply-delta ctx {:updated {:data {:color "green"}}} 1) (state/context-by-id 1) :data))))) (testing "updated replaces existing values with non-associative updates" (let [state {:contexts {1 {:id 1 :data {:meta {:channel "red"} :data {:color "red" :fruit "apple"}}}}} ctx (state/context-by-id state 1)] (is (= {:data "string" :meta {:channel "red"}} (-> state (state/apply-delta ctx {:updated {:data "string"}} 1) (state/context-by-id 1) :data))))) (testing "updated replaces existing non-associative values with new ones" (let [state {:contexts {1 {:id 1 :data {:meta {:channel "red"} :data "string"}}}} ctx (state/context-by-id state 1)] (is (= {:data {:color "green"} :meta {:channel "red"}} (-> state (state/apply-delta ctx {:updated {:data {:color "green"}}} 1) (state/context-by-id 1) :data))))) (testing "updated works with arrays" (let [state {:contexts {1 {:id 1 :data {:array [{"a" 1} {"b" 2}]}}}} ctx (state/context-by-id state 1)] (is (= {:array [{"a" 1} {"b" 2} {"c" 3} {"d" 4}]} (-> state (state/apply-delta ctx {:updated {:array [{"a" 1} {"b" 2} {"c" 3} {"d" 4}]}} 1) (state/context-by-id 1) :data))))) (testing "added replaces the corresponding keys" (let [state {:contexts {1 {:id 1 :data {:meta {:channel "red"} :data {:color "red" :fruit "apple"}}}}} ctx (state/context-by-id state 1)] (is (= {:data {:color "green"} :meta {:channel "red"}} (-> state (state/apply-delta ctx {:added {:data {:color "green"}}} 1) (state/context-by-id 1) :data))))) (testing "removed, well, removes a list of keys" (let [state {:contexts {1 {:id 1 :data {:meta {:channel "red"} :data {:color "red" :fruit "apple"} :bleh {:a 1}}}}} ctx (state/context-by-id state 1)] (is (= {:meta {:channel "red"}} (-> state (state/apply-delta ctx {:removed [:data :bleh]} 1) (state/context-by-id 1) :data))))) (testing "reset with nil data does nothing" (let [state {:contexts {1 {:id 1 :data {:bleh {:a 1} :data {:color "red" :fruit "apple"} :meta {:channel "red"}}}}} ctx (state/context-by-id state 1)] (is (= {:bleh {:a 1} :data {:color "red" :fruit "apple"} :meta {:channel "red"}} (-> state (state/apply-delta ctx {:reset nil} 1) (state/context-by-id 1) :data))))) (testing "set can override top level properties" (let [data {"prop" {"a" 1 "b" 2} "c" 3} state {:contexts {1 {:id 1 :data data}}} ctx (state/context-by-id state 1)] (is (= {"prop" {"d" 4} "c" 3} (-> state (state/apply-delta ctx {:commands [{:type "set" :path "prop" :value {"d" 4}}]} 1) (state/context-by-id 1) :data))))) (testing "set can add a new top level property" (let [data {"prop" {"a" 1 "b" 2} "c" 3} state {:contexts {1 {:id 1 :data data}}} ctx (state/context-by-id state 1)] (is (= {"prop" {"a" 1 "b" 2} "c" 3 "e" 5} (-> state (state/apply-delta ctx {:commands [{:type "set" :path "e" :value 5}]} 1) (state/context-by-id 1) :data))))) (testing "set with empty path replaces the whole object" (let [data {"prop" {"a" 1 "b" 2} "c" 3} state {:contexts {1 {:id 1 :data data}}} ctx (state/context-by-id state 1)] (is (= {"wow" 4} (-> state (state/apply-delta ctx {:commands [{:type "set" :path "" :value {"wow" 4}}]} 1) (state/context-by-id 1) :data))))) (testing "set can create deeply nested properties" (let [data {"prop" {"a" 1 "b" 2} "c" 3} state {:contexts {1 {:id 1 :data data}}} ctx (state/context-by-id state 1)] (is (= {"prop" {"a" {"x" {"y" 42}} "b" 2} "c" 3} (-> state (state/apply-delta ctx {:commands [{:type "set" :path "prop.a.x.y" :value 42}]} 1) (state/context-by-id 1) :data))))) (testing "remove doesnt recursively remove empty parents" (let [data {"prop" {"a" 1} "c" 3} state {:contexts {1 {:id 1 :data data}}} ctx (state/context-by-id state 1)] (is (= {"prop" {} "c" 3} (-> state (state/apply-delta ctx {:commands [{:type "remove" :path "prop.a"}]} 1) (state/context-by-id 1) :data))))) (testing "remove with empty path removes everything" (let [data {"prop" {"a" 1} "c" 3} state {:contexts {1 {:id 1 :data data}}} ctx (state/context-by-id state 1)] (is (= {} (-> state (state/apply-delta ctx {:commands [{:type "remove" :path ""}]} 1) (state/context-by-id 1) :data))))) ) (defn remote-join [state message] (let [body (:body message)] (-> state (peers/ensure-peer-with-id (:source message) (:peer_id body) (:identity body) nil nil) (first) (ctx/join (:source message) body) (first)))) (defn filter-join [messages] (->> messages (filter #(= :join (get-in % [:body :type]))) (first))) (deftest context-create-propagated (testing "context created on one node creates it on a remote node as well" (let [{peer-id-1 :id identity-1 :identity peer-1 :source} (local-peer) {peer-id-2 :id identity-2 :identity peer-2 :source} (local-peer) rid (request-id!) ;; create the first peer (local to node1) and join it to both nodes [node1-state messages] (-> (new-state) (create-join peer-1 {:request_id rid :peer_id peer-id-1 :identity identity-1})) node2-state (remote-join (new-state (->node-id)) (filter-join messages)) ;; create the second peer (local to node2) and join it to both nodes [node2-state messages] (-> node2-state (create-join peer-2 {:request_id rid :peer_id peer-id-2 :identity identity-2})) node1-state (remote-join node1-state (filter-join messages)) ;; create a context on node 1 ctx-data {:value 42} context-name "context" creation-request {:domain constants/context-domain-uri :type :create-context :request_id rid :peer_id peer-id-1 :name context-name :data ctx-data :lifetime "retained"} [node1-state messages] (-> node1-state (ctx/create peer-1 creation-request)) ctx-id (context-id :context-created messages) b (last messages) [node2-state messages] (-> node2-state (ctx/create (:source b) (:body b))) replicated-ctx (state/context-by-name node2-state context-name (peers/by-id* node2-state peer-id-2))] (is (= messages [(msg/context-added peer-2 peer-id-2 peer-id-1 (:id replicated-ctx) context-name)])) (is (= (:data replicated-ctx) ctx-data))))) (def timestamp (atom 0)) (defn next-version [context] (let [version (:version context {:updates 0})] (-> version (update :updates inc) (assoc :timestamp (swap! timestamp inc))))) (defn new-version [] {:updates 0 :timestamp (swap! timestamp inc)}) (deftest context-create-replaces-older-remote-context (with-redefs [state/next-version next-version state/new-version new-version] (testing "context creation overrides an existing older context" (let [{peer-id-1 :id identity-1 :identity peer-1 :source} (local-peer) {peer-id-2 :id identity-2 :identity peer-2 :source} (local-peer) rid (request-id!) ;; create the first peer (local to node1) and join it to both nodes [node1-state messages] (-> (new-state) (create-join peer-1 {:request_id rid :peer_id peer-id-1 :identity identity-1})) node2-state (remote-join (new-state (->node-id)) (filter-join messages)) ;; create the second peer (local to node2) and join it to both nodes [node2-state messages] (-> node2-state (create-join peer-2 {:request_id rid :peer_id peer-id-2 :identity identity-2})) node1-state (remote-join node1-state (filter-join messages)) ;; create a context on node 2 context-name "context" [node2-state messages] (-> node2-state (ctx/create peer-1 {:domain constants/context-domain-uri :type :create-context :request_id rid :peer_id peer-id-2 :name context-name :data {:value 41} :lifetime "retained"})) ;; create a context on node 1 ctx-data {:value 42} [node1-state messages] (-> node1-state (ctx/create peer-1 {:domain constants/context-domain-uri :type :create-context :request_id rid :peer_id peer-id-1 :name context-name :data ctx-data :lifetime "retained"})) ctx-id (context-id :context-created messages) b (last messages) [node2-state messages'] (-> node2-state (ctx/create (:source b) (:body b))) replicated-ctx (state/context-by-name node2-state context-name (peers/by-id* node2-state peer-id-2))] (is (= messages' [(msg/context-updated peer-2 peer-id-2 peer-id-1 (:id replicated-ctx) {:reset ctx-data})])) (is (= (:data replicated-ctx) ctx-data)))))) (deftest context-create-fizzles-new-remote-context (testing "context creation cant override a newer context" (let [{peer-id-1 :id identity-1 :identity peer-1 :source} (local-peer) {peer-id-2 :id identity-2 :identity peer-2 :source} (local-peer) rid (request-id!) ;; create the first peer (local to node1) and join it to both nodes [node1-state messages] (-> (new-state) (create-join peer-1 {:request_id rid :peer_id peer-id-1 :identity identity-1})) node2-state (remote-join (new-state (->node-id)) (filter-join messages)) ;; create the second peer (local to node2) and join it to both nodes [node2-state messages] (-> node2-state (create-join peer-2 {:request_id rid :peer_id peer-id-2 :identity identity-2})) node1-state (remote-join node1-state (filter-join messages)) ;; create a context on node 2 context-name "context" [node2-state messages] (with-redefs [state/new-version (fn [] {:updates 2 :timestamp 0}) state/next-version next-version] (-> node2-state (ctx/create peer-1 {:domain constants/context-domain-uri :type :create-context :request_id rid :peer_id peer-id-2 :name context-name :data {:value 41} :lifetime "retained"}))) ctx-id (context-id :context-created messages) ;; create a context on node 1 [node1-state messages] (with-redefs [state/new-version (fn [] {:updates 1 :timestamp 0}) state/next-version next-version] (-> node1-state (ctx/create peer-1 {:domain constants/context-domain-uri :type :create-context :request_id rid :peer_id peer-id-1 :name context-name :data {:value 42} :lifetime "retained"}))) b (last messages) [node2-state messages'] (-> node2-state (ctx/create (:source b) (:body b))) replicated-ctx (state/context-by-id node2-state ctx-id)] (is (nil? messages')) (is (= (:data replicated-ctx) {:value 41}))))) (deftest context-update-propagated (with-redefs [state/next-version next-version state/new-version new-version] (testing "context updated on one node, gets updated on the other nodes" (let [{peer-id-1 :id identity-1 :identity peer-1 :source} (local-peer) {peer-id-2 :id identity-2 :identity peer-2 :source} (local-peer) rid (request-id!) ;; create the first peer (local to node1) and join it to both nodes [node1-state messages] (-> (new-state) (create-join peer-1 {:request_id rid :peer_id peer-id-1 :identity identity-1})) node2-state (remote-join (new-state (->node-id)) (filter-join messages)) ;; create the second peer (local to node2) and join it to both nodes [node2-state messages] (-> node2-state (create-join peer-2 {:request_id rid :peer_id peer-id-2 :identity identity-2})) node1-state (remote-join node1-state (filter-join messages)) ;; create a context on node 1 ctx-data {:value 42} context-name "context" creation-request {:domain constants/context-domain-uri :type :create-context :request_id rid :peer_id peer-id-1 :name context-name :data ctx-data :lifetime "retained"} [node1-state messages] (-> node1-state (ctx/create peer-1 creation-request)) ctx-id (context-id :context-created messages) b (last messages) [node2-state messages] (-> node2-state (ctx/create (:source b) (:body b))) ;; first node gets updated delta {:added {"k" 5}} update-rq {:domain constants/context-domain-uri :request_id rid :peer_id peer-id-1 :context_id ctx-id :delta delta} [node1-state messages] (-> node1-state (ctx/update-ctx peer-1 update-rq)) ;; apply to second node b (last messages) [node2-state messages'] (-> node2-state (ctx/update-ctx (:source b) (:body b))) replicated-ctx (state/context-by-name node2-state context-name (peers/by-id* node2-state peer-id-2))] (is (= (:data replicated-ctx) (:data (state/context-by-name node1-state context-name (peers/by-id* node1-state peer-id-1))))))))) (deftest subscribe-unsubscribe-ref-counting (with-redefs [state/next-version next-version state/new-version new-version] (testing "subscriptions are tracked on local and remote nodes" (let [{peer-id-1 :id identity-1 :identity peer-1 :source} (local-peer) {peer-id-2 :id identity-2 :identity peer-2 :source} (local-peer) rid (request-id!) ;; create the first peer (local to node1) and join it to both nodes [node1-state messages] (-> (new-state) (create-join peer-1 {:request_id rid :peer_id peer-id-1 :identity identity-1})) node2-state (remote-join (new-state (->node-id)) (filter-join messages)) ;; create the second peer (local to node2) and join it to both nodes [node2-state messages] (-> node2-state (create-join peer-2 {:request_id rid :peer_id peer-id-2 :identity identity-2})) node1-state (remote-join node1-state (filter-join messages)) ;; create a context on node 1 ctx-data {:value 42} creation-request {:domain constants/context-domain-uri :type :create-context :request_id rid :peer_id peer-id-1 :name "context" :data ctx-data :lifetime "ref-counted"} [node1-state messages] (-> node1-state (ctx/create peer-1 creation-request)) ctx-id (context-id :context-created messages) b (last messages) [node2-state messages] (-> node2-state (ctx/create (:source b) (:body b))) ctx-id-2 (some-> node2-state (state/context-by-name "context" (peers/by-id* node2-state peer-id-2)) :id) ;; subscribe on node 1 [node1-state messages] (-> node1-state (ctx/subscribe peer-1 {:domain constants/context-domain-uri :request_id rid :peer_id peer-id-1 :context_id ctx-id})) ;; propagate on node 2 b (last messages) [node2-state messages] (-> node2-state (ctx/subscribe (:source b) (:body b))) ;; subscribe on node 2 [node2-state messages] (-> node2-state (ctx/subscribe peer-2 {:domain constants/context-domain-uri :request_id rid :peer_id peer-id-2 :context_id ctx-id-2})) ;; propagate on node 1 b (last messages) [node1-state messages] (-> node1-state (ctx/subscribe (:source b) (:body b)))] (is (= 2 (-> (state/context-by-id node1-state ctx-id) :members count) (-> (state/context-by-id node2-state ctx-id-2) :members count))) (testing "ref-counting tracks local and remote peers" (let [ ;; unsubscribe on node 1 [node1-state messages] (-> node1-state (ctx/unsubscribe peer-1 {:domain constants/context-domain-uri :request_id rid :peer_id peer-id-1 :context_id ctx-id})) ;; propagate on node 2 b (last messages) [node2-state messages] (-> node2-state (ctx/unsubscribe (:source b) (:body b))) ;; unsubscribe on node 2 [node2-state' messages2] (-> node2-state (ctx/unsubscribe peer-2 {:domain constants/context-domain-uri :request_id rid :peer_id peer-id-2 :context_id ctx-id-2})) ;; propagate on node 1 b (last messages2) [node1-state' messages1] (-> node1-state (ctx/unsubscribe (:source b) (:body b)))] ;; after removing the corresponding local peers, the contexts are still alive (is (= 1 (-> (state/context-by-id node1-state ctx-id) :members count) (-> (state/context-by-id node2-state ctx-id-2) :members count))) ;; and then after the remote peers disappear, the contexts are destroyed (is (= :context-destroyed (-> messages1 last :body :type))) (is (= :context-destroyed (-> messages1 first :body :type))) (is (nil? (state/context-by-id node1-state' ctx-id))) (is (nil? (state/context-by-id node2-state' ctx-id))))))))) (deftest state-propagation (with-redefs [state/next-version next-version state/new-version new-version] (testing "testing that the state is propagated via messages" (let [{peer-id-1 :id identity-1 :identity peer-1 :source} (local-peer) rid (request-id!) ;; create a peer on node 1 [node1-state messages] (-> (new-state) (create-join peer-1 {:request_id rid :peer_id peer-id-1 :identity identity-1})) ;; create a context on node 1 ctx-data {:value 42} [node1-state messages] (-> node1-state (ctx/create peer-1 {:domain constants/context-domain-uri :type :create-context :request_id rid :peer_id peer-id-1 :name "context" :data ctx-data :lifetime "retained"})) ctx-id (context-id :context-created messages) b (last messages) state-messages (ctx/state->messages node1-state) node2-state (-> (new-state) (assoc :registered-domains (local-node/build-domains [(ctx/context-domain)]))) node2-state (reduce (fn [state m] (-> (-> (if (= :join (get-in m [:body :type])) (gc/-handle-message {} {} {} state m) (ctx/-handle-message state m)) (first)))) node2-state state-messages) ; replicated-ctx (state/context-by-id node2-state ctx-id)] (is (= (:data replicated-ctx) ctx-data))))))
120537
(ns gateway.domains.context.t-core (:require [clojure.test :refer :all] #?(:cljs [gateway.t-macros :refer-macros [just? error-msg?]]) #?(:clj [gateway.t-macros :refer [just? error-msg?]]) [gateway.reason :refer [reason]] [gateway.domains.global.constants :as c] [gateway.domains.context.core :as ctx] [gateway.domains.context.helpers :refer [context-id]] [gateway.domains.global.core :as gc] [gateway.domains.context.messages :as msg] [gateway.t-helpers :refer [gen-identity ch->src request-id! new-state ->node-id node-id peer-id! local-peer remote-peer msgs->ctx-version]] [gateway.common.context.state :as state] [gateway.domains.context.constants :as constants] [gateway.common.context.constants :as cc] [gateway.common.commands :as commands] [gateway.state.peers :as peers] [gateway.common.messages :as m] [gateway.local-node.core :as local-node] [taoensso.timbre :as timbre])) (def environment {:local-ip "127.0.0.1"}) (defn authenticated [state source request] (gc/authenticated state source request nil environment)) (defn create-join [state source request] (let [{:keys [peer_id identity]} request] (-> state (peers/ensure-peer-with-id source peer_id identity nil (:options request)) (first) (ctx/join source (assoc request :domain c/global-domain-uri :destination constants/context-domain-uri))))) (deftest context-creation (testing "contexts can be created if missing" (let [ id1 (gen-identity) source (ch->src "source") request-id (request-id!) context-name "my context" peer-id-1 (peer-id!) create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions nil} msgs (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (ctx/create source create-rq) (second)) context-id (context-id :context-created msgs)] (just? msgs [(msg/context-created source request-id peer-id-1 context-id) (msg/context-added source peer-id-1 peer-id-1 context-id context-name) (m/broadcast {:type :peer :peer-id peer-id-1 :node node-id} (assoc create-rq :type :create-context :version (msgs->ctx-version msgs)))]))) (testing "trying to create a context with an existing name subscribes for it" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {:t 41} :lifetime "retained" :read_permissions nil :write_permissions nil} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) create-rq-2 {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :name context-name :data {:t 42} :lifetime "retained" :read_permissions nil :write_permissions nil} msgs (-> state (ctx/create source create-rq-2) (second))] (is (= msgs [(msg/subscribed-context source request-id peer-id-2 context-id {:t 41})])))) (testing "there can be multiple contexts with the same name for peers with different users" (let [id1 (gen-identity "user1") id2 (gen-identity "user2") [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {:t 41} :lifetime "retained" :read_permissions nil :write_permissions nil} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) create-rq-2 {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :name context-name :data {:t 42} :lifetime "retained" :read_permissions nil :write_permissions nil} [state msgs] (-> state (ctx/create source-2 create-rq-2)) ctx-1 (state/context-by-name state context-name (peers/by-id* state peer-id-1)) ctx-2 (state/context-by-name state context-name (peers/by-id* state peer-id-2))] (is (not= ctx-1 ctx-2)) (just? msgs [(msg/context-created source-2 request-id peer-id-2 (:id ctx-2)) (msg/context-added source-2 peer-id-2 peer-id-2 (:id ctx-2) context-name) (m/broadcast {:type :peer :peer-id peer-id-2 :node node-id} (assoc create-rq-2 :type :create-context :version (msgs->ctx-version msgs)))]))) (testing "creating a context without a peer returns an error" ;; ghostwheel will throw an exception (is (thrown? #?(:clj Exception :cljs :default) (let [request-id (request-id!) source (ch->src "source") msgs (-> (new-state) (ctx/create source {:request_id request-id :name "context-name" :data {:t 41} :lifetime "retained" :read_permissions nil :write_permissions nil}) (second))] (is (error-msg? constants/failure (first msgs)))))))) (deftest context-announcement (testing "when a context is created, its announced to all peers that can see it" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions nil} msgs (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq) (second)) context-id (context-id :context-created msgs)] (just? [(msg/context-added source peer-id-1 peer-id-1 context-id context-name) (msg/context-added source-2 peer-id-2 peer-id-1 context-id context-name) (msg/context-created source request-id peer-id-1 context-id) (m/broadcast {:type :peer :peer-id peer-id-1 :node node-id} (assoc create-rq :type :create-context :version (msgs->ctx-version msgs)))] msgs))) (testing "when a peer join, it receives an announcement for all contexts that it can see" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" request {:request_id request-id :peer_id peer-id-2 :identity id2 :domain c/global-domain-uri :destination constants/context-domain-uri} create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions nil} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (ctx/create source create-rq) (first) (create-join source-2 request)) context (state/context-by-name state context-name (peers/by-id* state peer-id-1)) context-id (:id context)] (just? msgs [(m/peer-added constants/context-domain-uri source-2 peer-id-2 peer-id-1 id1 {:local true}) (m/peer-added constants/context-domain-uri source peer-id-1 peer-id-2 id2 {:local true}) (msg/context-added source-2 peer-id-2 peer-id-1 context-id context-name) (msg/success source-2 request-id peer-id-2) (m/broadcast {:type :peer :peer-id peer-id-2 :node node-id} (assoc request :type :join))]))) (testing "peer joined thru the compatibility mode global domain doesnt receive announcements, but is announced" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) [state msgs] (-> (new-state) (assoc :registered-domains (local-node/build-domains [(ctx/context-domain)])) (authenticated source {:request_id request-id :remote-identity id1})) peer-id-1 (get-in (first msgs) [:body :peer_id]) request {:request_id request-id :peer_id peer-id-2 :identity id2 :domain c/global-domain-uri :destination constants/context-domain-uri} [state msgs] (-> state (create-join source-2 request))] (just? msgs [(m/peer-added constants/context-domain-uri source-2 peer-id-2 peer-id-1 (assoc id1 :machine "127.0.0.1") {:local true}) (msg/success source-2 request-id peer-id-2) (m/broadcast {:type :peer :peer-id peer-id-2 :node node-id} (assoc request :type :join))]) (testing "then if it joins the context domain, it gets announcements of the rest of the peers" (let [ request {:request_id request-id :peer_id peer-id-1 :identity id1 :domain c/global-domain-uri :destination constants/context-domain-uri} [state msgs] (-> state (ctx/join source request))] (just? msgs [(m/peer-added constants/context-domain-uri source peer-id-1 peer-id-2 id2 {:local true}) (msg/success source request-id peer-id-1) (m/broadcast {:type :peer :peer-id peer-id-1 :node node-id} (assoc request :type :join))])))))) (deftest context-restricted-announcement (let [ id1 (assoc (gen-identity) :user "user") id2 (assoc (gen-identity) :user "user") id3 (assoc (gen-identity) :user "other-user") [peer-id-1 peer-id-2 peer-id-3] (repeatedly 3 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") source-3 (ch->src "source-3") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions "$user==#user" :write_permissions nil} msgs (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (create-join source-3 {:request_id request-id :peer_id peer-id-3 :identity id3}) (first) (ctx/create source create-rq) (second)) context-id (context-id :context-created msgs)] (just? [(msg/context-added source peer-id-1 peer-id-1 context-id context-name) (msg/context-added source-2 peer-id-2 peer-id-1 context-id context-name) (msg/context-created source request-id peer-id-1 context-id) (m/broadcast {:type :peer :peer-id peer-id-1 :node node-id} (assoc create-rq :type :create-context :version (msgs->ctx-version msgs)))] msgs))) (deftest context-destroyed-when-owner-leaves (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions nil} state-with-context (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq) (first)) context (state/context-by-name state-with-context context-name (peers/by-id* state-with-context peer-id-1)) remove-rq {:type ::commands/source-removed} [state msgs] (ctx/source-removed state-with-context source remove-rq)] (is (nil? (state/context-by-name state context-name (peers/by-id* state-with-context peer-id-1)))) (is (= msgs [(msg/context-destroyed source-2 peer-id-2 (:id context) (cc/context-destroyed-peer-left constants/context-domain-uri)) (m/peer-removed constants/context-domain-uri source-2 peer-id-2 peer-id-1 constants/reason-peer-removed) (m/broadcast {:type :peer :peer-id peer-id-1 :node node-id} {:request_id nil :domain c/global-domain-uri :peer_id peer-id-1 :type :leave :destination constants/context-domain-uri :reason_uri (:uri constants/reason-peer-removed) :reason (:message constants/reason-peer-removed)})])))) (deftest owner-destroys-context (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions nil} state-with-context (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq) (first)) context (state/context-by-name state-with-context context-name (peers/by-id* state-with-context peer-id-1)) ctx-id (:id context) destroy-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :context_id ctx-id} [state msgs] (ctx/destroy state-with-context source destroy-rq)] (is (nil? (state/context-by-name state context-name (peers/by-id* state-with-context peer-id-1)))) (just? msgs [(msg/context-destroyed source peer-id-1 ctx-id (cc/context-destroyed-explicitly constants/context-domain-uri)) (msg/context-destroyed source-2 peer-id-2 ctx-id (cc/context-destroyed-explicitly constants/context-domain-uri)) (msg/success source request-id peer-id-1) (m/broadcast {:type :peer :peer-id peer-id-1 :node node-id} (assoc destroy-rq :type :destroy-context :name context-name))]))) (deftest non-owner-cant-destroy (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions nil} state-with-context (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq) (first)) context (state/context-by-name state-with-context context-name (peers/by-id* state-with-context peer-id-1)) ctx-id (:id context) [state msgs] (ctx/destroy state-with-context source-2 {:request_id request-id :peer_id peer-id-2 :context_id ctx-id})] (is (some? (state/context-by-name state context-name (peers/by-id* state-with-context peer-id-1)))) (is (= msgs [(msg/error source-2 request-id peer-id-2 (reason (cc/context-not-authorized constants/context-domain-uri) "Not authorized to destroy context"))])))) (deftest destroy-restricted-fail (let [ id1 (assoc (gen-identity) :user "user") id2 (assoc (gen-identity) :user "other-user") [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src nil) source-2 (ch->src nil) request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ref-counted" :read_permissions nil :write_permissions "$user==#user"} state-with-context (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq) (first)) context (state/context-by-name state-with-context context-name (peers/by-id* state-with-context peer-id-1)) ctx-id (:id context) [state msgs] (ctx/destroy state-with-context source-2 {:request_id request-id :peer_id peer-id-2 :context_id ctx-id})] (is (some? (state/context-by-name state context-name (peers/by-id* state-with-context peer-id-1)))) (is (= msgs [(msg/error source-2 request-id peer-id-2 (reason (cc/context-not-authorized constants/context-domain-uri) "Not authorized to destroy context"))])))) (deftest destroy-restricted-success (let [ id1 (assoc (gen-identity) :user "user") id2 (assoc (gen-identity) :user "user") [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ref-counted" :read_permissions nil :write_permissions "$user==#user"} state-with-context (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq) (first)) context (state/context-by-name state-with-context context-name (peers/by-id* state-with-context peer-id-1)) ctx-id (:id context) destroy-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id ctx-id} [state msgs] (ctx/destroy state-with-context source-2 destroy-rq)] (is (nil? (state/context-by-name state context-name (peers/by-id* state-with-context peer-id-1)))) (just? msgs [(msg/context-destroyed source peer-id-1 ctx-id (cc/context-destroyed-explicitly constants/context-domain-uri)) (msg/context-destroyed source-2 peer-id-2 ctx-id (cc/context-destroyed-explicitly constants/context-domain-uri)) (msg/success source-2 request-id peer-id-2) (m/broadcast {:type :peer :peer-id peer-id-2 :node node-id} (assoc destroy-rq :type :destroy-context :name context-name))]))) (deftest context-subscription (testing "contexts can be subscribed to" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions nil} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) subscribe-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id} msgs (-> state (ctx/subscribe source-2 subscribe-rq) (second))] (just? msgs [(msg/subscribed-context source-2 request-id peer-id-2 context-id {}) (m/broadcast {:type :peer :peer-id peer-id-2 :node node-id} (assoc subscribe-rq :type :subscribe-context :name context-name))]))) (testing "having read permissions allows you to subscribe" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions "#secret == $secret" :write_permissions nil} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity (assoc id1 :secret "<KEY>")}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity (assoc id2 :secret "<KEY>")}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) subscribe-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id} msgs (-> state (ctx/subscribe source-2 subscribe-rq) (second))] (just? msgs [(msg/subscribed-context source-2 request-id peer-id-2 context-id {}) (m/broadcast {:type :peer :peer-id peer-id-2 :node node-id} (assoc subscribe-rq :type :subscribe-context :name context-name))]))) (testing "unsubscribing from a context stops all evens from it" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions nil} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) ;; unsubscribe from the context unsub-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id} [state unsub-msgs] (-> state (ctx/subscribe source-2 {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id}) (first) (ctx/unsubscribe source-2 unsub-rq)) ;; send an update delta {:added {"k" 5}} update-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :context_id context-id :delta delta} msgs (-> state (ctx/update-ctx source update-rq) (second))] (is (= unsub-msgs [(msg/success source-2 request-id peer-id-2) (m/broadcast {:type :peer :peer-id peer-id-2 :node node-id} (assoc unsub-rq :type :unsubscribe-context :name context-name))])) (just? msgs [(msg/success source request-id peer-id-1) (m/broadcast {:type :peer :peer-id peer-id-1 :node node-id} (assoc update-rq :type :update-context :name context-name :version (msgs->ctx-version msgs)))])))) (deftest context-updates (testing "when a context is updated, the update is broadcasted to all members" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions nil} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) delta {:added {"k" 5}} update-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :context_id context-id :delta delta} msgs (-> state (ctx/subscribe source-2 {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id}) (first) (ctx/update-ctx source update-rq) (second))] (just? msgs [(msg/context-updated source-2 peer-id-2 peer-id-1 context-id delta) (msg/success source request-id peer-id-1) (m/broadcast {:type :peer :peer-id peer-id-1 :node node-id} (assoc update-rq :type :update-context :name context-name :version (msgs->ctx-version msgs)))]))) (testing "updating a context is governed by write permissions" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions "$secret == #secret"} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity (assoc id1 :secret "<KEY>")}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) delta {:added {"k" 5}} update-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id :delta delta} msgs (-> state (ctx/subscribe source-2 {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id}) (first) (ctx/update-ctx source-2 update-rq) (second))] (just? msgs [(m/error constants/context-domain-uri source-2 request-id peer-id-2 (reason (cc/context-not-authorized constants/context-domain-uri) "Not authorized to update context"))]))) (testing "not having permissions stops you from subscribing to a context" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions "$secret == '1'" :write_permissions "$secret == '2'"} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity (assoc id1 :secret "2")}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity (assoc id2 :secret "3")}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) msgs (-> state (ctx/subscribe source-2 {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id}) (second))] (just? msgs [(m/error constants/context-domain-uri source-2 request-id peer-id-2 (reason (cc/context-not-authorized constants/context-domain-uri) "Not authorized to read context"))]))) (testing "not having a permissions stops you from subscribing via create" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions "$secret == '1'" :write_permissions "$secret == '2'"} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity (assoc id1 :secret "2")}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity (assoc id2 :secret "3")}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) msgs (-> state (ctx/create source-2 (assoc create-rq :peer_id peer-id-2)) (second))] (just? msgs [(m/error constants/context-domain-uri source-2 request-id peer-id-2 (reason (cc/context-not-authorized constants/context-domain-uri) "Not authorized to read context"))]))) (testing "having matching write permissions allows reading even if the read permissions dont match" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions "$secret == '1'" :write_permissions "$secret == '2'"} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity (assoc id1 :secret "2")}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity (assoc id2 :secret "2")}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) subscribe-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id} msgs (-> state (ctx/subscribe source-2 subscribe-rq) (second))] (just? msgs [(msg/subscribed-context source-2 request-id peer-id-2 context-id {}) (m/broadcast {:type :peer :peer-id peer-id-2 :node node-id} (assoc subscribe-rq :type :subscribe-context :name context-name))]))) (testing "data can be deleted" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions nil} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) delta {:removed ["remove-me"]} update-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :context_id context-id :delta delta} msgs (-> state (ctx/subscribe source-2 {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id}) (first) (ctx/update-ctx source update-rq) (second))] (just? msgs [(msg/context-updated source-2 peer-id-2 peer-id-1 context-id delta) (msg/success source request-id peer-id-1) (m/broadcast {:type :peer :peer-id peer-id-1 :node node-id} (assoc update-rq :type :update-context :name context-name :version (msgs->ctx-version msgs)))])))) (deftest context-resets (testing "when a context is reset, the update is broadcasted to all members" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" old-ctx {"a" 1 "b" 2} new-ctx {"a" 2 "c" 3 "d" 4} delta {:reset new-ctx} create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data old-ctx :lifetime "ownership" :read_permissions nil :write_permissions nil} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) update-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :context_id context-id :delta delta} msgs (-> state (ctx/subscribe source-2 {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id}) (first) (ctx/update-ctx source update-rq) (second))] (just? msgs [(msg/context-updated source-2 peer-id-2 peer-id-1 context-id delta) (msg/success source request-id peer-id-1) (m/broadcast {:type :peer :peer-id peer-id-1 :node node-id} (assoc update-rq :type :update-context :name context-name :version (msgs->ctx-version msgs)))])))) (deftest context-update-handling (testing "updated merges the data key by key" (let [state {:contexts {1 {:id 1 :data {:meta {:channel "red"} :data {:color "red" :fruit "apple"}}}}} ctx (state/context-by-id state 1)] (is (= {:data {:color "green" :fruit "apple"} :meta {:channel "red"}} (-> state (state/apply-delta ctx {:updated {:data {:color "green"}}} 1) (state/context-by-id 1) :data))))) (testing "updated replaces existing values with non-associative updates" (let [state {:contexts {1 {:id 1 :data {:meta {:channel "red"} :data {:color "red" :fruit "apple"}}}}} ctx (state/context-by-id state 1)] (is (= {:data "string" :meta {:channel "red"}} (-> state (state/apply-delta ctx {:updated {:data "string"}} 1) (state/context-by-id 1) :data))))) (testing "updated replaces existing non-associative values with new ones" (let [state {:contexts {1 {:id 1 :data {:meta {:channel "red"} :data "string"}}}} ctx (state/context-by-id state 1)] (is (= {:data {:color "green"} :meta {:channel "red"}} (-> state (state/apply-delta ctx {:updated {:data {:color "green"}}} 1) (state/context-by-id 1) :data))))) (testing "updated works with arrays" (let [state {:contexts {1 {:id 1 :data {:array [{"a" 1} {"b" 2}]}}}} ctx (state/context-by-id state 1)] (is (= {:array [{"a" 1} {"b" 2} {"c" 3} {"d" 4}]} (-> state (state/apply-delta ctx {:updated {:array [{"a" 1} {"b" 2} {"c" 3} {"d" 4}]}} 1) (state/context-by-id 1) :data))))) (testing "added replaces the corresponding keys" (let [state {:contexts {1 {:id 1 :data {:meta {:channel "red"} :data {:color "red" :fruit "apple"}}}}} ctx (state/context-by-id state 1)] (is (= {:data {:color "green"} :meta {:channel "red"}} (-> state (state/apply-delta ctx {:added {:data {:color "green"}}} 1) (state/context-by-id 1) :data))))) (testing "removed, well, removes a list of keys" (let [state {:contexts {1 {:id 1 :data {:meta {:channel "red"} :data {:color "red" :fruit "apple"} :bleh {:a 1}}}}} ctx (state/context-by-id state 1)] (is (= {:meta {:channel "red"}} (-> state (state/apply-delta ctx {:removed [:data :bleh]} 1) (state/context-by-id 1) :data))))) (testing "reset with nil data does nothing" (let [state {:contexts {1 {:id 1 :data {:bleh {:a 1} :data {:color "red" :fruit "apple"} :meta {:channel "red"}}}}} ctx (state/context-by-id state 1)] (is (= {:bleh {:a 1} :data {:color "red" :fruit "apple"} :meta {:channel "red"}} (-> state (state/apply-delta ctx {:reset nil} 1) (state/context-by-id 1) :data))))) (testing "set can override top level properties" (let [data {"prop" {"a" 1 "b" 2} "c" 3} state {:contexts {1 {:id 1 :data data}}} ctx (state/context-by-id state 1)] (is (= {"prop" {"d" 4} "c" 3} (-> state (state/apply-delta ctx {:commands [{:type "set" :path "prop" :value {"d" 4}}]} 1) (state/context-by-id 1) :data))))) (testing "set can add a new top level property" (let [data {"prop" {"a" 1 "b" 2} "c" 3} state {:contexts {1 {:id 1 :data data}}} ctx (state/context-by-id state 1)] (is (= {"prop" {"a" 1 "b" 2} "c" 3 "e" 5} (-> state (state/apply-delta ctx {:commands [{:type "set" :path "e" :value 5}]} 1) (state/context-by-id 1) :data))))) (testing "set with empty path replaces the whole object" (let [data {"prop" {"a" 1 "b" 2} "c" 3} state {:contexts {1 {:id 1 :data data}}} ctx (state/context-by-id state 1)] (is (= {"wow" 4} (-> state (state/apply-delta ctx {:commands [{:type "set" :path "" :value {"wow" 4}}]} 1) (state/context-by-id 1) :data))))) (testing "set can create deeply nested properties" (let [data {"prop" {"a" 1 "b" 2} "c" 3} state {:contexts {1 {:id 1 :data data}}} ctx (state/context-by-id state 1)] (is (= {"prop" {"a" {"x" {"y" 42}} "b" 2} "c" 3} (-> state (state/apply-delta ctx {:commands [{:type "set" :path "prop.a.x.y" :value 42}]} 1) (state/context-by-id 1) :data))))) (testing "remove doesnt recursively remove empty parents" (let [data {"prop" {"a" 1} "c" 3} state {:contexts {1 {:id 1 :data data}}} ctx (state/context-by-id state 1)] (is (= {"prop" {} "c" 3} (-> state (state/apply-delta ctx {:commands [{:type "remove" :path "prop.a"}]} 1) (state/context-by-id 1) :data))))) (testing "remove with empty path removes everything" (let [data {"prop" {"a" 1} "c" 3} state {:contexts {1 {:id 1 :data data}}} ctx (state/context-by-id state 1)] (is (= {} (-> state (state/apply-delta ctx {:commands [{:type "remove" :path ""}]} 1) (state/context-by-id 1) :data))))) ) (defn remote-join [state message] (let [body (:body message)] (-> state (peers/ensure-peer-with-id (:source message) (:peer_id body) (:identity body) nil nil) (first) (ctx/join (:source message) body) (first)))) (defn filter-join [messages] (->> messages (filter #(= :join (get-in % [:body :type]))) (first))) (deftest context-create-propagated (testing "context created on one node creates it on a remote node as well" (let [{peer-id-1 :id identity-1 :identity peer-1 :source} (local-peer) {peer-id-2 :id identity-2 :identity peer-2 :source} (local-peer) rid (request-id!) ;; create the first peer (local to node1) and join it to both nodes [node1-state messages] (-> (new-state) (create-join peer-1 {:request_id rid :peer_id peer-id-1 :identity identity-1})) node2-state (remote-join (new-state (->node-id)) (filter-join messages)) ;; create the second peer (local to node2) and join it to both nodes [node2-state messages] (-> node2-state (create-join peer-2 {:request_id rid :peer_id peer-id-2 :identity identity-2})) node1-state (remote-join node1-state (filter-join messages)) ;; create a context on node 1 ctx-data {:value 42} context-name "context" creation-request {:domain constants/context-domain-uri :type :create-context :request_id rid :peer_id peer-id-1 :name context-name :data ctx-data :lifetime "retained"} [node1-state messages] (-> node1-state (ctx/create peer-1 creation-request)) ctx-id (context-id :context-created messages) b (last messages) [node2-state messages] (-> node2-state (ctx/create (:source b) (:body b))) replicated-ctx (state/context-by-name node2-state context-name (peers/by-id* node2-state peer-id-2))] (is (= messages [(msg/context-added peer-2 peer-id-2 peer-id-1 (:id replicated-ctx) context-name)])) (is (= (:data replicated-ctx) ctx-data))))) (def timestamp (atom 0)) (defn next-version [context] (let [version (:version context {:updates 0})] (-> version (update :updates inc) (assoc :timestamp (swap! timestamp inc))))) (defn new-version [] {:updates 0 :timestamp (swap! timestamp inc)}) (deftest context-create-replaces-older-remote-context (with-redefs [state/next-version next-version state/new-version new-version] (testing "context creation overrides an existing older context" (let [{peer-id-1 :id identity-1 :identity peer-1 :source} (local-peer) {peer-id-2 :id identity-2 :identity peer-2 :source} (local-peer) rid (request-id!) ;; create the first peer (local to node1) and join it to both nodes [node1-state messages] (-> (new-state) (create-join peer-1 {:request_id rid :peer_id peer-id-1 :identity identity-1})) node2-state (remote-join (new-state (->node-id)) (filter-join messages)) ;; create the second peer (local to node2) and join it to both nodes [node2-state messages] (-> node2-state (create-join peer-2 {:request_id rid :peer_id peer-id-2 :identity identity-2})) node1-state (remote-join node1-state (filter-join messages)) ;; create a context on node 2 context-name "context" [node2-state messages] (-> node2-state (ctx/create peer-1 {:domain constants/context-domain-uri :type :create-context :request_id rid :peer_id peer-id-2 :name context-name :data {:value 41} :lifetime "retained"})) ;; create a context on node 1 ctx-data {:value 42} [node1-state messages] (-> node1-state (ctx/create peer-1 {:domain constants/context-domain-uri :type :create-context :request_id rid :peer_id peer-id-1 :name context-name :data ctx-data :lifetime "retained"})) ctx-id (context-id :context-created messages) b (last messages) [node2-state messages'] (-> node2-state (ctx/create (:source b) (:body b))) replicated-ctx (state/context-by-name node2-state context-name (peers/by-id* node2-state peer-id-2))] (is (= messages' [(msg/context-updated peer-2 peer-id-2 peer-id-1 (:id replicated-ctx) {:reset ctx-data})])) (is (= (:data replicated-ctx) ctx-data)))))) (deftest context-create-fizzles-new-remote-context (testing "context creation cant override a newer context" (let [{peer-id-1 :id identity-1 :identity peer-1 :source} (local-peer) {peer-id-2 :id identity-2 :identity peer-2 :source} (local-peer) rid (request-id!) ;; create the first peer (local to node1) and join it to both nodes [node1-state messages] (-> (new-state) (create-join peer-1 {:request_id rid :peer_id peer-id-1 :identity identity-1})) node2-state (remote-join (new-state (->node-id)) (filter-join messages)) ;; create the second peer (local to node2) and join it to both nodes [node2-state messages] (-> node2-state (create-join peer-2 {:request_id rid :peer_id peer-id-2 :identity identity-2})) node1-state (remote-join node1-state (filter-join messages)) ;; create a context on node 2 context-name "context" [node2-state messages] (with-redefs [state/new-version (fn [] {:updates 2 :timestamp 0}) state/next-version next-version] (-> node2-state (ctx/create peer-1 {:domain constants/context-domain-uri :type :create-context :request_id rid :peer_id peer-id-2 :name context-name :data {:value 41} :lifetime "retained"}))) ctx-id (context-id :context-created messages) ;; create a context on node 1 [node1-state messages] (with-redefs [state/new-version (fn [] {:updates 1 :timestamp 0}) state/next-version next-version] (-> node1-state (ctx/create peer-1 {:domain constants/context-domain-uri :type :create-context :request_id rid :peer_id peer-id-1 :name context-name :data {:value 42} :lifetime "retained"}))) b (last messages) [node2-state messages'] (-> node2-state (ctx/create (:source b) (:body b))) replicated-ctx (state/context-by-id node2-state ctx-id)] (is (nil? messages')) (is (= (:data replicated-ctx) {:value 41}))))) (deftest context-update-propagated (with-redefs [state/next-version next-version state/new-version new-version] (testing "context updated on one node, gets updated on the other nodes" (let [{peer-id-1 :id identity-1 :identity peer-1 :source} (local-peer) {peer-id-2 :id identity-2 :identity peer-2 :source} (local-peer) rid (request-id!) ;; create the first peer (local to node1) and join it to both nodes [node1-state messages] (-> (new-state) (create-join peer-1 {:request_id rid :peer_id peer-id-1 :identity identity-1})) node2-state (remote-join (new-state (->node-id)) (filter-join messages)) ;; create the second peer (local to node2) and join it to both nodes [node2-state messages] (-> node2-state (create-join peer-2 {:request_id rid :peer_id peer-id-2 :identity identity-2})) node1-state (remote-join node1-state (filter-join messages)) ;; create a context on node 1 ctx-data {:value 42} context-name "context" creation-request {:domain constants/context-domain-uri :type :create-context :request_id rid :peer_id peer-id-1 :name context-name :data ctx-data :lifetime "retained"} [node1-state messages] (-> node1-state (ctx/create peer-1 creation-request)) ctx-id (context-id :context-created messages) b (last messages) [node2-state messages] (-> node2-state (ctx/create (:source b) (:body b))) ;; first node gets updated delta {:added {"k" 5}} update-rq {:domain constants/context-domain-uri :request_id rid :peer_id peer-id-1 :context_id ctx-id :delta delta} [node1-state messages] (-> node1-state (ctx/update-ctx peer-1 update-rq)) ;; apply to second node b (last messages) [node2-state messages'] (-> node2-state (ctx/update-ctx (:source b) (:body b))) replicated-ctx (state/context-by-name node2-state context-name (peers/by-id* node2-state peer-id-2))] (is (= (:data replicated-ctx) (:data (state/context-by-name node1-state context-name (peers/by-id* node1-state peer-id-1))))))))) (deftest subscribe-unsubscribe-ref-counting (with-redefs [state/next-version next-version state/new-version new-version] (testing "subscriptions are tracked on local and remote nodes" (let [{peer-id-1 :id identity-1 :identity peer-1 :source} (local-peer) {peer-id-2 :id identity-2 :identity peer-2 :source} (local-peer) rid (request-id!) ;; create the first peer (local to node1) and join it to both nodes [node1-state messages] (-> (new-state) (create-join peer-1 {:request_id rid :peer_id peer-id-1 :identity identity-1})) node2-state (remote-join (new-state (->node-id)) (filter-join messages)) ;; create the second peer (local to node2) and join it to both nodes [node2-state messages] (-> node2-state (create-join peer-2 {:request_id rid :peer_id peer-id-2 :identity identity-2})) node1-state (remote-join node1-state (filter-join messages)) ;; create a context on node 1 ctx-data {:value 42} creation-request {:domain constants/context-domain-uri :type :create-context :request_id rid :peer_id peer-id-1 :name "context" :data ctx-data :lifetime "ref-counted"} [node1-state messages] (-> node1-state (ctx/create peer-1 creation-request)) ctx-id (context-id :context-created messages) b (last messages) [node2-state messages] (-> node2-state (ctx/create (:source b) (:body b))) ctx-id-2 (some-> node2-state (state/context-by-name "context" (peers/by-id* node2-state peer-id-2)) :id) ;; subscribe on node 1 [node1-state messages] (-> node1-state (ctx/subscribe peer-1 {:domain constants/context-domain-uri :request_id rid :peer_id peer-id-1 :context_id ctx-id})) ;; propagate on node 2 b (last messages) [node2-state messages] (-> node2-state (ctx/subscribe (:source b) (:body b))) ;; subscribe on node 2 [node2-state messages] (-> node2-state (ctx/subscribe peer-2 {:domain constants/context-domain-uri :request_id rid :peer_id peer-id-2 :context_id ctx-id-2})) ;; propagate on node 1 b (last messages) [node1-state messages] (-> node1-state (ctx/subscribe (:source b) (:body b)))] (is (= 2 (-> (state/context-by-id node1-state ctx-id) :members count) (-> (state/context-by-id node2-state ctx-id-2) :members count))) (testing "ref-counting tracks local and remote peers" (let [ ;; unsubscribe on node 1 [node1-state messages] (-> node1-state (ctx/unsubscribe peer-1 {:domain constants/context-domain-uri :request_id rid :peer_id peer-id-1 :context_id ctx-id})) ;; propagate on node 2 b (last messages) [node2-state messages] (-> node2-state (ctx/unsubscribe (:source b) (:body b))) ;; unsubscribe on node 2 [node2-state' messages2] (-> node2-state (ctx/unsubscribe peer-2 {:domain constants/context-domain-uri :request_id rid :peer_id peer-id-2 :context_id ctx-id-2})) ;; propagate on node 1 b (last messages2) [node1-state' messages1] (-> node1-state (ctx/unsubscribe (:source b) (:body b)))] ;; after removing the corresponding local peers, the contexts are still alive (is (= 1 (-> (state/context-by-id node1-state ctx-id) :members count) (-> (state/context-by-id node2-state ctx-id-2) :members count))) ;; and then after the remote peers disappear, the contexts are destroyed (is (= :context-destroyed (-> messages1 last :body :type))) (is (= :context-destroyed (-> messages1 first :body :type))) (is (nil? (state/context-by-id node1-state' ctx-id))) (is (nil? (state/context-by-id node2-state' ctx-id))))))))) (deftest state-propagation (with-redefs [state/next-version next-version state/new-version new-version] (testing "testing that the state is propagated via messages" (let [{peer-id-1 :id identity-1 :identity peer-1 :source} (local-peer) rid (request-id!) ;; create a peer on node 1 [node1-state messages] (-> (new-state) (create-join peer-1 {:request_id rid :peer_id peer-id-1 :identity identity-1})) ;; create a context on node 1 ctx-data {:value 42} [node1-state messages] (-> node1-state (ctx/create peer-1 {:domain constants/context-domain-uri :type :create-context :request_id rid :peer_id peer-id-1 :name "context" :data ctx-data :lifetime "retained"})) ctx-id (context-id :context-created messages) b (last messages) state-messages (ctx/state->messages node1-state) node2-state (-> (new-state) (assoc :registered-domains (local-node/build-domains [(ctx/context-domain)]))) node2-state (reduce (fn [state m] (-> (-> (if (= :join (get-in m [:body :type])) (gc/-handle-message {} {} {} state m) (ctx/-handle-message state m)) (first)))) node2-state state-messages) ; replicated-ctx (state/context-by-id node2-state ctx-id)] (is (= (:data replicated-ctx) ctx-data))))))
true
(ns gateway.domains.context.t-core (:require [clojure.test :refer :all] #?(:cljs [gateway.t-macros :refer-macros [just? error-msg?]]) #?(:clj [gateway.t-macros :refer [just? error-msg?]]) [gateway.reason :refer [reason]] [gateway.domains.global.constants :as c] [gateway.domains.context.core :as ctx] [gateway.domains.context.helpers :refer [context-id]] [gateway.domains.global.core :as gc] [gateway.domains.context.messages :as msg] [gateway.t-helpers :refer [gen-identity ch->src request-id! new-state ->node-id node-id peer-id! local-peer remote-peer msgs->ctx-version]] [gateway.common.context.state :as state] [gateway.domains.context.constants :as constants] [gateway.common.context.constants :as cc] [gateway.common.commands :as commands] [gateway.state.peers :as peers] [gateway.common.messages :as m] [gateway.local-node.core :as local-node] [taoensso.timbre :as timbre])) (def environment {:local-ip "127.0.0.1"}) (defn authenticated [state source request] (gc/authenticated state source request nil environment)) (defn create-join [state source request] (let [{:keys [peer_id identity]} request] (-> state (peers/ensure-peer-with-id source peer_id identity nil (:options request)) (first) (ctx/join source (assoc request :domain c/global-domain-uri :destination constants/context-domain-uri))))) (deftest context-creation (testing "contexts can be created if missing" (let [ id1 (gen-identity) source (ch->src "source") request-id (request-id!) context-name "my context" peer-id-1 (peer-id!) create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions nil} msgs (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (ctx/create source create-rq) (second)) context-id (context-id :context-created msgs)] (just? msgs [(msg/context-created source request-id peer-id-1 context-id) (msg/context-added source peer-id-1 peer-id-1 context-id context-name) (m/broadcast {:type :peer :peer-id peer-id-1 :node node-id} (assoc create-rq :type :create-context :version (msgs->ctx-version msgs)))]))) (testing "trying to create a context with an existing name subscribes for it" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {:t 41} :lifetime "retained" :read_permissions nil :write_permissions nil} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) create-rq-2 {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :name context-name :data {:t 42} :lifetime "retained" :read_permissions nil :write_permissions nil} msgs (-> state (ctx/create source create-rq-2) (second))] (is (= msgs [(msg/subscribed-context source request-id peer-id-2 context-id {:t 41})])))) (testing "there can be multiple contexts with the same name for peers with different users" (let [id1 (gen-identity "user1") id2 (gen-identity "user2") [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {:t 41} :lifetime "retained" :read_permissions nil :write_permissions nil} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) create-rq-2 {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :name context-name :data {:t 42} :lifetime "retained" :read_permissions nil :write_permissions nil} [state msgs] (-> state (ctx/create source-2 create-rq-2)) ctx-1 (state/context-by-name state context-name (peers/by-id* state peer-id-1)) ctx-2 (state/context-by-name state context-name (peers/by-id* state peer-id-2))] (is (not= ctx-1 ctx-2)) (just? msgs [(msg/context-created source-2 request-id peer-id-2 (:id ctx-2)) (msg/context-added source-2 peer-id-2 peer-id-2 (:id ctx-2) context-name) (m/broadcast {:type :peer :peer-id peer-id-2 :node node-id} (assoc create-rq-2 :type :create-context :version (msgs->ctx-version msgs)))]))) (testing "creating a context without a peer returns an error" ;; ghostwheel will throw an exception (is (thrown? #?(:clj Exception :cljs :default) (let [request-id (request-id!) source (ch->src "source") msgs (-> (new-state) (ctx/create source {:request_id request-id :name "context-name" :data {:t 41} :lifetime "retained" :read_permissions nil :write_permissions nil}) (second))] (is (error-msg? constants/failure (first msgs)))))))) (deftest context-announcement (testing "when a context is created, its announced to all peers that can see it" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions nil} msgs (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq) (second)) context-id (context-id :context-created msgs)] (just? [(msg/context-added source peer-id-1 peer-id-1 context-id context-name) (msg/context-added source-2 peer-id-2 peer-id-1 context-id context-name) (msg/context-created source request-id peer-id-1 context-id) (m/broadcast {:type :peer :peer-id peer-id-1 :node node-id} (assoc create-rq :type :create-context :version (msgs->ctx-version msgs)))] msgs))) (testing "when a peer join, it receives an announcement for all contexts that it can see" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" request {:request_id request-id :peer_id peer-id-2 :identity id2 :domain c/global-domain-uri :destination constants/context-domain-uri} create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions nil} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (ctx/create source create-rq) (first) (create-join source-2 request)) context (state/context-by-name state context-name (peers/by-id* state peer-id-1)) context-id (:id context)] (just? msgs [(m/peer-added constants/context-domain-uri source-2 peer-id-2 peer-id-1 id1 {:local true}) (m/peer-added constants/context-domain-uri source peer-id-1 peer-id-2 id2 {:local true}) (msg/context-added source-2 peer-id-2 peer-id-1 context-id context-name) (msg/success source-2 request-id peer-id-2) (m/broadcast {:type :peer :peer-id peer-id-2 :node node-id} (assoc request :type :join))]))) (testing "peer joined thru the compatibility mode global domain doesnt receive announcements, but is announced" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) [state msgs] (-> (new-state) (assoc :registered-domains (local-node/build-domains [(ctx/context-domain)])) (authenticated source {:request_id request-id :remote-identity id1})) peer-id-1 (get-in (first msgs) [:body :peer_id]) request {:request_id request-id :peer_id peer-id-2 :identity id2 :domain c/global-domain-uri :destination constants/context-domain-uri} [state msgs] (-> state (create-join source-2 request))] (just? msgs [(m/peer-added constants/context-domain-uri source-2 peer-id-2 peer-id-1 (assoc id1 :machine "127.0.0.1") {:local true}) (msg/success source-2 request-id peer-id-2) (m/broadcast {:type :peer :peer-id peer-id-2 :node node-id} (assoc request :type :join))]) (testing "then if it joins the context domain, it gets announcements of the rest of the peers" (let [ request {:request_id request-id :peer_id peer-id-1 :identity id1 :domain c/global-domain-uri :destination constants/context-domain-uri} [state msgs] (-> state (ctx/join source request))] (just? msgs [(m/peer-added constants/context-domain-uri source peer-id-1 peer-id-2 id2 {:local true}) (msg/success source request-id peer-id-1) (m/broadcast {:type :peer :peer-id peer-id-1 :node node-id} (assoc request :type :join))])))))) (deftest context-restricted-announcement (let [ id1 (assoc (gen-identity) :user "user") id2 (assoc (gen-identity) :user "user") id3 (assoc (gen-identity) :user "other-user") [peer-id-1 peer-id-2 peer-id-3] (repeatedly 3 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") source-3 (ch->src "source-3") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions "$user==#user" :write_permissions nil} msgs (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (create-join source-3 {:request_id request-id :peer_id peer-id-3 :identity id3}) (first) (ctx/create source create-rq) (second)) context-id (context-id :context-created msgs)] (just? [(msg/context-added source peer-id-1 peer-id-1 context-id context-name) (msg/context-added source-2 peer-id-2 peer-id-1 context-id context-name) (msg/context-created source request-id peer-id-1 context-id) (m/broadcast {:type :peer :peer-id peer-id-1 :node node-id} (assoc create-rq :type :create-context :version (msgs->ctx-version msgs)))] msgs))) (deftest context-destroyed-when-owner-leaves (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions nil} state-with-context (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq) (first)) context (state/context-by-name state-with-context context-name (peers/by-id* state-with-context peer-id-1)) remove-rq {:type ::commands/source-removed} [state msgs] (ctx/source-removed state-with-context source remove-rq)] (is (nil? (state/context-by-name state context-name (peers/by-id* state-with-context peer-id-1)))) (is (= msgs [(msg/context-destroyed source-2 peer-id-2 (:id context) (cc/context-destroyed-peer-left constants/context-domain-uri)) (m/peer-removed constants/context-domain-uri source-2 peer-id-2 peer-id-1 constants/reason-peer-removed) (m/broadcast {:type :peer :peer-id peer-id-1 :node node-id} {:request_id nil :domain c/global-domain-uri :peer_id peer-id-1 :type :leave :destination constants/context-domain-uri :reason_uri (:uri constants/reason-peer-removed) :reason (:message constants/reason-peer-removed)})])))) (deftest owner-destroys-context (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions nil} state-with-context (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq) (first)) context (state/context-by-name state-with-context context-name (peers/by-id* state-with-context peer-id-1)) ctx-id (:id context) destroy-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :context_id ctx-id} [state msgs] (ctx/destroy state-with-context source destroy-rq)] (is (nil? (state/context-by-name state context-name (peers/by-id* state-with-context peer-id-1)))) (just? msgs [(msg/context-destroyed source peer-id-1 ctx-id (cc/context-destroyed-explicitly constants/context-domain-uri)) (msg/context-destroyed source-2 peer-id-2 ctx-id (cc/context-destroyed-explicitly constants/context-domain-uri)) (msg/success source request-id peer-id-1) (m/broadcast {:type :peer :peer-id peer-id-1 :node node-id} (assoc destroy-rq :type :destroy-context :name context-name))]))) (deftest non-owner-cant-destroy (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions nil} state-with-context (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq) (first)) context (state/context-by-name state-with-context context-name (peers/by-id* state-with-context peer-id-1)) ctx-id (:id context) [state msgs] (ctx/destroy state-with-context source-2 {:request_id request-id :peer_id peer-id-2 :context_id ctx-id})] (is (some? (state/context-by-name state context-name (peers/by-id* state-with-context peer-id-1)))) (is (= msgs [(msg/error source-2 request-id peer-id-2 (reason (cc/context-not-authorized constants/context-domain-uri) "Not authorized to destroy context"))])))) (deftest destroy-restricted-fail (let [ id1 (assoc (gen-identity) :user "user") id2 (assoc (gen-identity) :user "other-user") [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src nil) source-2 (ch->src nil) request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ref-counted" :read_permissions nil :write_permissions "$user==#user"} state-with-context (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq) (first)) context (state/context-by-name state-with-context context-name (peers/by-id* state-with-context peer-id-1)) ctx-id (:id context) [state msgs] (ctx/destroy state-with-context source-2 {:request_id request-id :peer_id peer-id-2 :context_id ctx-id})] (is (some? (state/context-by-name state context-name (peers/by-id* state-with-context peer-id-1)))) (is (= msgs [(msg/error source-2 request-id peer-id-2 (reason (cc/context-not-authorized constants/context-domain-uri) "Not authorized to destroy context"))])))) (deftest destroy-restricted-success (let [ id1 (assoc (gen-identity) :user "user") id2 (assoc (gen-identity) :user "user") [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ref-counted" :read_permissions nil :write_permissions "$user==#user"} state-with-context (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq) (first)) context (state/context-by-name state-with-context context-name (peers/by-id* state-with-context peer-id-1)) ctx-id (:id context) destroy-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id ctx-id} [state msgs] (ctx/destroy state-with-context source-2 destroy-rq)] (is (nil? (state/context-by-name state context-name (peers/by-id* state-with-context peer-id-1)))) (just? msgs [(msg/context-destroyed source peer-id-1 ctx-id (cc/context-destroyed-explicitly constants/context-domain-uri)) (msg/context-destroyed source-2 peer-id-2 ctx-id (cc/context-destroyed-explicitly constants/context-domain-uri)) (msg/success source-2 request-id peer-id-2) (m/broadcast {:type :peer :peer-id peer-id-2 :node node-id} (assoc destroy-rq :type :destroy-context :name context-name))]))) (deftest context-subscription (testing "contexts can be subscribed to" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions nil} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) subscribe-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id} msgs (-> state (ctx/subscribe source-2 subscribe-rq) (second))] (just? msgs [(msg/subscribed-context source-2 request-id peer-id-2 context-id {}) (m/broadcast {:type :peer :peer-id peer-id-2 :node node-id} (assoc subscribe-rq :type :subscribe-context :name context-name))]))) (testing "having read permissions allows you to subscribe" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions "#secret == $secret" :write_permissions nil} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity (assoc id1 :secret "PI:KEY:<KEY>END_PI")}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity (assoc id2 :secret "PI:KEY:<KEY>END_PI")}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) subscribe-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id} msgs (-> state (ctx/subscribe source-2 subscribe-rq) (second))] (just? msgs [(msg/subscribed-context source-2 request-id peer-id-2 context-id {}) (m/broadcast {:type :peer :peer-id peer-id-2 :node node-id} (assoc subscribe-rq :type :subscribe-context :name context-name))]))) (testing "unsubscribing from a context stops all evens from it" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions nil} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) ;; unsubscribe from the context unsub-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id} [state unsub-msgs] (-> state (ctx/subscribe source-2 {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id}) (first) (ctx/unsubscribe source-2 unsub-rq)) ;; send an update delta {:added {"k" 5}} update-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :context_id context-id :delta delta} msgs (-> state (ctx/update-ctx source update-rq) (second))] (is (= unsub-msgs [(msg/success source-2 request-id peer-id-2) (m/broadcast {:type :peer :peer-id peer-id-2 :node node-id} (assoc unsub-rq :type :unsubscribe-context :name context-name))])) (just? msgs [(msg/success source request-id peer-id-1) (m/broadcast {:type :peer :peer-id peer-id-1 :node node-id} (assoc update-rq :type :update-context :name context-name :version (msgs->ctx-version msgs)))])))) (deftest context-updates (testing "when a context is updated, the update is broadcasted to all members" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions nil} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) delta {:added {"k" 5}} update-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :context_id context-id :delta delta} msgs (-> state (ctx/subscribe source-2 {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id}) (first) (ctx/update-ctx source update-rq) (second))] (just? msgs [(msg/context-updated source-2 peer-id-2 peer-id-1 context-id delta) (msg/success source request-id peer-id-1) (m/broadcast {:type :peer :peer-id peer-id-1 :node node-id} (assoc update-rq :type :update-context :name context-name :version (msgs->ctx-version msgs)))]))) (testing "updating a context is governed by write permissions" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions "$secret == #secret"} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity (assoc id1 :secret "PI:KEY:<KEY>END_PI")}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) delta {:added {"k" 5}} update-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id :delta delta} msgs (-> state (ctx/subscribe source-2 {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id}) (first) (ctx/update-ctx source-2 update-rq) (second))] (just? msgs [(m/error constants/context-domain-uri source-2 request-id peer-id-2 (reason (cc/context-not-authorized constants/context-domain-uri) "Not authorized to update context"))]))) (testing "not having permissions stops you from subscribing to a context" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions "$secret == '1'" :write_permissions "$secret == '2'"} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity (assoc id1 :secret "2")}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity (assoc id2 :secret "3")}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) msgs (-> state (ctx/subscribe source-2 {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id}) (second))] (just? msgs [(m/error constants/context-domain-uri source-2 request-id peer-id-2 (reason (cc/context-not-authorized constants/context-domain-uri) "Not authorized to read context"))]))) (testing "not having a permissions stops you from subscribing via create" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions "$secret == '1'" :write_permissions "$secret == '2'"} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity (assoc id1 :secret "2")}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity (assoc id2 :secret "3")}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) msgs (-> state (ctx/create source-2 (assoc create-rq :peer_id peer-id-2)) (second))] (just? msgs [(m/error constants/context-domain-uri source-2 request-id peer-id-2 (reason (cc/context-not-authorized constants/context-domain-uri) "Not authorized to read context"))]))) (testing "having matching write permissions allows reading even if the read permissions dont match" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions "$secret == '1'" :write_permissions "$secret == '2'"} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity (assoc id1 :secret "2")}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity (assoc id2 :secret "2")}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) subscribe-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id} msgs (-> state (ctx/subscribe source-2 subscribe-rq) (second))] (just? msgs [(msg/subscribed-context source-2 request-id peer-id-2 context-id {}) (m/broadcast {:type :peer :peer-id peer-id-2 :node node-id} (assoc subscribe-rq :type :subscribe-context :name context-name))]))) (testing "data can be deleted" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data {} :lifetime "ownership" :read_permissions nil :write_permissions nil} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) delta {:removed ["remove-me"]} update-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :context_id context-id :delta delta} msgs (-> state (ctx/subscribe source-2 {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id}) (first) (ctx/update-ctx source update-rq) (second))] (just? msgs [(msg/context-updated source-2 peer-id-2 peer-id-1 context-id delta) (msg/success source request-id peer-id-1) (m/broadcast {:type :peer :peer-id peer-id-1 :node node-id} (assoc update-rq :type :update-context :name context-name :version (msgs->ctx-version msgs)))])))) (deftest context-resets (testing "when a context is reset, the update is broadcasted to all members" (let [ [id1 id2] (repeatedly 2 gen-identity) [peer-id-1 peer-id-2] (repeatedly 2 peer-id!) source (ch->src "source") source-2 (ch->src "source-2") request-id (request-id!) context-name "my context" old-ctx {"a" 1 "b" 2} new-ctx {"a" 2 "c" 3 "d" 4} delta {:reset new-ctx} create-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :name context-name :data old-ctx :lifetime "ownership" :read_permissions nil :write_permissions nil} [state msgs] (-> (new-state) (create-join source {:request_id request-id :peer_id peer-id-1 :identity id1}) (first) (create-join source-2 {:request_id request-id :peer_id peer-id-2 :identity id2}) (first) (ctx/create source create-rq)) context-id (context-id :context-created msgs) update-rq {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-1 :context_id context-id :delta delta} msgs (-> state (ctx/subscribe source-2 {:domain constants/context-domain-uri :request_id request-id :peer_id peer-id-2 :context_id context-id}) (first) (ctx/update-ctx source update-rq) (second))] (just? msgs [(msg/context-updated source-2 peer-id-2 peer-id-1 context-id delta) (msg/success source request-id peer-id-1) (m/broadcast {:type :peer :peer-id peer-id-1 :node node-id} (assoc update-rq :type :update-context :name context-name :version (msgs->ctx-version msgs)))])))) (deftest context-update-handling (testing "updated merges the data key by key" (let [state {:contexts {1 {:id 1 :data {:meta {:channel "red"} :data {:color "red" :fruit "apple"}}}}} ctx (state/context-by-id state 1)] (is (= {:data {:color "green" :fruit "apple"} :meta {:channel "red"}} (-> state (state/apply-delta ctx {:updated {:data {:color "green"}}} 1) (state/context-by-id 1) :data))))) (testing "updated replaces existing values with non-associative updates" (let [state {:contexts {1 {:id 1 :data {:meta {:channel "red"} :data {:color "red" :fruit "apple"}}}}} ctx (state/context-by-id state 1)] (is (= {:data "string" :meta {:channel "red"}} (-> state (state/apply-delta ctx {:updated {:data "string"}} 1) (state/context-by-id 1) :data))))) (testing "updated replaces existing non-associative values with new ones" (let [state {:contexts {1 {:id 1 :data {:meta {:channel "red"} :data "string"}}}} ctx (state/context-by-id state 1)] (is (= {:data {:color "green"} :meta {:channel "red"}} (-> state (state/apply-delta ctx {:updated {:data {:color "green"}}} 1) (state/context-by-id 1) :data))))) (testing "updated works with arrays" (let [state {:contexts {1 {:id 1 :data {:array [{"a" 1} {"b" 2}]}}}} ctx (state/context-by-id state 1)] (is (= {:array [{"a" 1} {"b" 2} {"c" 3} {"d" 4}]} (-> state (state/apply-delta ctx {:updated {:array [{"a" 1} {"b" 2} {"c" 3} {"d" 4}]}} 1) (state/context-by-id 1) :data))))) (testing "added replaces the corresponding keys" (let [state {:contexts {1 {:id 1 :data {:meta {:channel "red"} :data {:color "red" :fruit "apple"}}}}} ctx (state/context-by-id state 1)] (is (= {:data {:color "green"} :meta {:channel "red"}} (-> state (state/apply-delta ctx {:added {:data {:color "green"}}} 1) (state/context-by-id 1) :data))))) (testing "removed, well, removes a list of keys" (let [state {:contexts {1 {:id 1 :data {:meta {:channel "red"} :data {:color "red" :fruit "apple"} :bleh {:a 1}}}}} ctx (state/context-by-id state 1)] (is (= {:meta {:channel "red"}} (-> state (state/apply-delta ctx {:removed [:data :bleh]} 1) (state/context-by-id 1) :data))))) (testing "reset with nil data does nothing" (let [state {:contexts {1 {:id 1 :data {:bleh {:a 1} :data {:color "red" :fruit "apple"} :meta {:channel "red"}}}}} ctx (state/context-by-id state 1)] (is (= {:bleh {:a 1} :data {:color "red" :fruit "apple"} :meta {:channel "red"}} (-> state (state/apply-delta ctx {:reset nil} 1) (state/context-by-id 1) :data))))) (testing "set can override top level properties" (let [data {"prop" {"a" 1 "b" 2} "c" 3} state {:contexts {1 {:id 1 :data data}}} ctx (state/context-by-id state 1)] (is (= {"prop" {"d" 4} "c" 3} (-> state (state/apply-delta ctx {:commands [{:type "set" :path "prop" :value {"d" 4}}]} 1) (state/context-by-id 1) :data))))) (testing "set can add a new top level property" (let [data {"prop" {"a" 1 "b" 2} "c" 3} state {:contexts {1 {:id 1 :data data}}} ctx (state/context-by-id state 1)] (is (= {"prop" {"a" 1 "b" 2} "c" 3 "e" 5} (-> state (state/apply-delta ctx {:commands [{:type "set" :path "e" :value 5}]} 1) (state/context-by-id 1) :data))))) (testing "set with empty path replaces the whole object" (let [data {"prop" {"a" 1 "b" 2} "c" 3} state {:contexts {1 {:id 1 :data data}}} ctx (state/context-by-id state 1)] (is (= {"wow" 4} (-> state (state/apply-delta ctx {:commands [{:type "set" :path "" :value {"wow" 4}}]} 1) (state/context-by-id 1) :data))))) (testing "set can create deeply nested properties" (let [data {"prop" {"a" 1 "b" 2} "c" 3} state {:contexts {1 {:id 1 :data data}}} ctx (state/context-by-id state 1)] (is (= {"prop" {"a" {"x" {"y" 42}} "b" 2} "c" 3} (-> state (state/apply-delta ctx {:commands [{:type "set" :path "prop.a.x.y" :value 42}]} 1) (state/context-by-id 1) :data))))) (testing "remove doesnt recursively remove empty parents" (let [data {"prop" {"a" 1} "c" 3} state {:contexts {1 {:id 1 :data data}}} ctx (state/context-by-id state 1)] (is (= {"prop" {} "c" 3} (-> state (state/apply-delta ctx {:commands [{:type "remove" :path "prop.a"}]} 1) (state/context-by-id 1) :data))))) (testing "remove with empty path removes everything" (let [data {"prop" {"a" 1} "c" 3} state {:contexts {1 {:id 1 :data data}}} ctx (state/context-by-id state 1)] (is (= {} (-> state (state/apply-delta ctx {:commands [{:type "remove" :path ""}]} 1) (state/context-by-id 1) :data))))) ) (defn remote-join [state message] (let [body (:body message)] (-> state (peers/ensure-peer-with-id (:source message) (:peer_id body) (:identity body) nil nil) (first) (ctx/join (:source message) body) (first)))) (defn filter-join [messages] (->> messages (filter #(= :join (get-in % [:body :type]))) (first))) (deftest context-create-propagated (testing "context created on one node creates it on a remote node as well" (let [{peer-id-1 :id identity-1 :identity peer-1 :source} (local-peer) {peer-id-2 :id identity-2 :identity peer-2 :source} (local-peer) rid (request-id!) ;; create the first peer (local to node1) and join it to both nodes [node1-state messages] (-> (new-state) (create-join peer-1 {:request_id rid :peer_id peer-id-1 :identity identity-1})) node2-state (remote-join (new-state (->node-id)) (filter-join messages)) ;; create the second peer (local to node2) and join it to both nodes [node2-state messages] (-> node2-state (create-join peer-2 {:request_id rid :peer_id peer-id-2 :identity identity-2})) node1-state (remote-join node1-state (filter-join messages)) ;; create a context on node 1 ctx-data {:value 42} context-name "context" creation-request {:domain constants/context-domain-uri :type :create-context :request_id rid :peer_id peer-id-1 :name context-name :data ctx-data :lifetime "retained"} [node1-state messages] (-> node1-state (ctx/create peer-1 creation-request)) ctx-id (context-id :context-created messages) b (last messages) [node2-state messages] (-> node2-state (ctx/create (:source b) (:body b))) replicated-ctx (state/context-by-name node2-state context-name (peers/by-id* node2-state peer-id-2))] (is (= messages [(msg/context-added peer-2 peer-id-2 peer-id-1 (:id replicated-ctx) context-name)])) (is (= (:data replicated-ctx) ctx-data))))) (def timestamp (atom 0)) (defn next-version [context] (let [version (:version context {:updates 0})] (-> version (update :updates inc) (assoc :timestamp (swap! timestamp inc))))) (defn new-version [] {:updates 0 :timestamp (swap! timestamp inc)}) (deftest context-create-replaces-older-remote-context (with-redefs [state/next-version next-version state/new-version new-version] (testing "context creation overrides an existing older context" (let [{peer-id-1 :id identity-1 :identity peer-1 :source} (local-peer) {peer-id-2 :id identity-2 :identity peer-2 :source} (local-peer) rid (request-id!) ;; create the first peer (local to node1) and join it to both nodes [node1-state messages] (-> (new-state) (create-join peer-1 {:request_id rid :peer_id peer-id-1 :identity identity-1})) node2-state (remote-join (new-state (->node-id)) (filter-join messages)) ;; create the second peer (local to node2) and join it to both nodes [node2-state messages] (-> node2-state (create-join peer-2 {:request_id rid :peer_id peer-id-2 :identity identity-2})) node1-state (remote-join node1-state (filter-join messages)) ;; create a context on node 2 context-name "context" [node2-state messages] (-> node2-state (ctx/create peer-1 {:domain constants/context-domain-uri :type :create-context :request_id rid :peer_id peer-id-2 :name context-name :data {:value 41} :lifetime "retained"})) ;; create a context on node 1 ctx-data {:value 42} [node1-state messages] (-> node1-state (ctx/create peer-1 {:domain constants/context-domain-uri :type :create-context :request_id rid :peer_id peer-id-1 :name context-name :data ctx-data :lifetime "retained"})) ctx-id (context-id :context-created messages) b (last messages) [node2-state messages'] (-> node2-state (ctx/create (:source b) (:body b))) replicated-ctx (state/context-by-name node2-state context-name (peers/by-id* node2-state peer-id-2))] (is (= messages' [(msg/context-updated peer-2 peer-id-2 peer-id-1 (:id replicated-ctx) {:reset ctx-data})])) (is (= (:data replicated-ctx) ctx-data)))))) (deftest context-create-fizzles-new-remote-context (testing "context creation cant override a newer context" (let [{peer-id-1 :id identity-1 :identity peer-1 :source} (local-peer) {peer-id-2 :id identity-2 :identity peer-2 :source} (local-peer) rid (request-id!) ;; create the first peer (local to node1) and join it to both nodes [node1-state messages] (-> (new-state) (create-join peer-1 {:request_id rid :peer_id peer-id-1 :identity identity-1})) node2-state (remote-join (new-state (->node-id)) (filter-join messages)) ;; create the second peer (local to node2) and join it to both nodes [node2-state messages] (-> node2-state (create-join peer-2 {:request_id rid :peer_id peer-id-2 :identity identity-2})) node1-state (remote-join node1-state (filter-join messages)) ;; create a context on node 2 context-name "context" [node2-state messages] (with-redefs [state/new-version (fn [] {:updates 2 :timestamp 0}) state/next-version next-version] (-> node2-state (ctx/create peer-1 {:domain constants/context-domain-uri :type :create-context :request_id rid :peer_id peer-id-2 :name context-name :data {:value 41} :lifetime "retained"}))) ctx-id (context-id :context-created messages) ;; create a context on node 1 [node1-state messages] (with-redefs [state/new-version (fn [] {:updates 1 :timestamp 0}) state/next-version next-version] (-> node1-state (ctx/create peer-1 {:domain constants/context-domain-uri :type :create-context :request_id rid :peer_id peer-id-1 :name context-name :data {:value 42} :lifetime "retained"}))) b (last messages) [node2-state messages'] (-> node2-state (ctx/create (:source b) (:body b))) replicated-ctx (state/context-by-id node2-state ctx-id)] (is (nil? messages')) (is (= (:data replicated-ctx) {:value 41}))))) (deftest context-update-propagated (with-redefs [state/next-version next-version state/new-version new-version] (testing "context updated on one node, gets updated on the other nodes" (let [{peer-id-1 :id identity-1 :identity peer-1 :source} (local-peer) {peer-id-2 :id identity-2 :identity peer-2 :source} (local-peer) rid (request-id!) ;; create the first peer (local to node1) and join it to both nodes [node1-state messages] (-> (new-state) (create-join peer-1 {:request_id rid :peer_id peer-id-1 :identity identity-1})) node2-state (remote-join (new-state (->node-id)) (filter-join messages)) ;; create the second peer (local to node2) and join it to both nodes [node2-state messages] (-> node2-state (create-join peer-2 {:request_id rid :peer_id peer-id-2 :identity identity-2})) node1-state (remote-join node1-state (filter-join messages)) ;; create a context on node 1 ctx-data {:value 42} context-name "context" creation-request {:domain constants/context-domain-uri :type :create-context :request_id rid :peer_id peer-id-1 :name context-name :data ctx-data :lifetime "retained"} [node1-state messages] (-> node1-state (ctx/create peer-1 creation-request)) ctx-id (context-id :context-created messages) b (last messages) [node2-state messages] (-> node2-state (ctx/create (:source b) (:body b))) ;; first node gets updated delta {:added {"k" 5}} update-rq {:domain constants/context-domain-uri :request_id rid :peer_id peer-id-1 :context_id ctx-id :delta delta} [node1-state messages] (-> node1-state (ctx/update-ctx peer-1 update-rq)) ;; apply to second node b (last messages) [node2-state messages'] (-> node2-state (ctx/update-ctx (:source b) (:body b))) replicated-ctx (state/context-by-name node2-state context-name (peers/by-id* node2-state peer-id-2))] (is (= (:data replicated-ctx) (:data (state/context-by-name node1-state context-name (peers/by-id* node1-state peer-id-1))))))))) (deftest subscribe-unsubscribe-ref-counting (with-redefs [state/next-version next-version state/new-version new-version] (testing "subscriptions are tracked on local and remote nodes" (let [{peer-id-1 :id identity-1 :identity peer-1 :source} (local-peer) {peer-id-2 :id identity-2 :identity peer-2 :source} (local-peer) rid (request-id!) ;; create the first peer (local to node1) and join it to both nodes [node1-state messages] (-> (new-state) (create-join peer-1 {:request_id rid :peer_id peer-id-1 :identity identity-1})) node2-state (remote-join (new-state (->node-id)) (filter-join messages)) ;; create the second peer (local to node2) and join it to both nodes [node2-state messages] (-> node2-state (create-join peer-2 {:request_id rid :peer_id peer-id-2 :identity identity-2})) node1-state (remote-join node1-state (filter-join messages)) ;; create a context on node 1 ctx-data {:value 42} creation-request {:domain constants/context-domain-uri :type :create-context :request_id rid :peer_id peer-id-1 :name "context" :data ctx-data :lifetime "ref-counted"} [node1-state messages] (-> node1-state (ctx/create peer-1 creation-request)) ctx-id (context-id :context-created messages) b (last messages) [node2-state messages] (-> node2-state (ctx/create (:source b) (:body b))) ctx-id-2 (some-> node2-state (state/context-by-name "context" (peers/by-id* node2-state peer-id-2)) :id) ;; subscribe on node 1 [node1-state messages] (-> node1-state (ctx/subscribe peer-1 {:domain constants/context-domain-uri :request_id rid :peer_id peer-id-1 :context_id ctx-id})) ;; propagate on node 2 b (last messages) [node2-state messages] (-> node2-state (ctx/subscribe (:source b) (:body b))) ;; subscribe on node 2 [node2-state messages] (-> node2-state (ctx/subscribe peer-2 {:domain constants/context-domain-uri :request_id rid :peer_id peer-id-2 :context_id ctx-id-2})) ;; propagate on node 1 b (last messages) [node1-state messages] (-> node1-state (ctx/subscribe (:source b) (:body b)))] (is (= 2 (-> (state/context-by-id node1-state ctx-id) :members count) (-> (state/context-by-id node2-state ctx-id-2) :members count))) (testing "ref-counting tracks local and remote peers" (let [ ;; unsubscribe on node 1 [node1-state messages] (-> node1-state (ctx/unsubscribe peer-1 {:domain constants/context-domain-uri :request_id rid :peer_id peer-id-1 :context_id ctx-id})) ;; propagate on node 2 b (last messages) [node2-state messages] (-> node2-state (ctx/unsubscribe (:source b) (:body b))) ;; unsubscribe on node 2 [node2-state' messages2] (-> node2-state (ctx/unsubscribe peer-2 {:domain constants/context-domain-uri :request_id rid :peer_id peer-id-2 :context_id ctx-id-2})) ;; propagate on node 1 b (last messages2) [node1-state' messages1] (-> node1-state (ctx/unsubscribe (:source b) (:body b)))] ;; after removing the corresponding local peers, the contexts are still alive (is (= 1 (-> (state/context-by-id node1-state ctx-id) :members count) (-> (state/context-by-id node2-state ctx-id-2) :members count))) ;; and then after the remote peers disappear, the contexts are destroyed (is (= :context-destroyed (-> messages1 last :body :type))) (is (= :context-destroyed (-> messages1 first :body :type))) (is (nil? (state/context-by-id node1-state' ctx-id))) (is (nil? (state/context-by-id node2-state' ctx-id))))))))) (deftest state-propagation (with-redefs [state/next-version next-version state/new-version new-version] (testing "testing that the state is propagated via messages" (let [{peer-id-1 :id identity-1 :identity peer-1 :source} (local-peer) rid (request-id!) ;; create a peer on node 1 [node1-state messages] (-> (new-state) (create-join peer-1 {:request_id rid :peer_id peer-id-1 :identity identity-1})) ;; create a context on node 1 ctx-data {:value 42} [node1-state messages] (-> node1-state (ctx/create peer-1 {:domain constants/context-domain-uri :type :create-context :request_id rid :peer_id peer-id-1 :name "context" :data ctx-data :lifetime "retained"})) ctx-id (context-id :context-created messages) b (last messages) state-messages (ctx/state->messages node1-state) node2-state (-> (new-state) (assoc :registered-domains (local-node/build-domains [(ctx/context-domain)]))) node2-state (reduce (fn [state m] (-> (-> (if (= :join (get-in m [:body :type])) (gc/-handle-message {} {} {} state m) (ctx/-handle-message state m)) (first)))) node2-state state-messages) ; replicated-ctx (state/context-by-id node2-state ctx-id)] (is (= (:data replicated-ctx) ctx-data))))))
[ { "context": " updated false\n\n(def makoto-account (ref {:name \"Makoto Hashimoto\" :amount 1000}))\n;;=> #'chapter06.concurrency/mak", "end": 1278, "score": 0.999852180480957, "start": 1262, "tag": "NAME", "value": "Makoto Hashimoto" }, { "context": "ncy/makoto-account\n(def nico-account (ref {:name \"Nicolas Modrzyk\" :amount 2000}))\n;;=> #'chapter06.concurrency/nic", "end": 1386, "score": 0.9998846054077148, "start": 1371, "tag": "NAME", "value": "Nicolas Modrzyk" }, { "context": "ount is 2010\n;;=> nil\n@nico-account\n;;=> {:name \"Nicolas Modrzyk\", :amount 2010}\n(deref makoto-account)\n;;=> {:nam", "end": 2114, "score": 0.9998745322227478, "start": 2099, "tag": "NAME", "value": "Nicolas Modrzyk" }, { "context": ":amount 2010}\n(deref makoto-account)\n;;=> {:name \"Makoto Hashimoto\", :amount 990}\n\n(do\n (future\n (transfer!", "end": 2183, "score": 0.9998171329498291, "start": 2167, "tag": "NAME", "value": "Makoto Hashimoto" }, { "context": "ount nico-account 300)))\n;;=> transfer money from Makoto Hashimoto to Nicolas Modrzyk amount = 200 begins\n;;=> ", "end": 2377, "score": 0.9968993663787842, "start": 2361, "tag": "NAME", "value": "Makoto Hashimoto" }, { "context": "))\n;;=> transfer money from Makoto Hashimoto to Nicolas Modrzyk amount = 200 begins\n;;=> #<Future@473dad05: :p", "end": 2398, "score": 0.9995685815811157, "start": 2383, "tag": "NAME", "value": "Nicolas Modrzyk" }, { "context": "ture@473dad05: :pending>\n;;=> transfer money from Makoto Hashimoto to Nicolas Modrzyk amount = 300 begins\n;;=> ", "end": 2498, "score": 0.9958974719047546, "start": 2482, "tag": "NAME", "value": "Makoto Hashimoto" }, { "context": "g>\n;;=> transfer money from Makoto Hashimoto to Nicolas Modrzyk amount = 300 begins\n;;=> transfer money from ", "end": 2519, "score": 0.9994610548019409, "start": 2504, "tag": "NAME", "value": "Nicolas Modrzyk" }, { "context": "k amount = 300 begins\n;;=> transfer money from Makoto Hashimoto to Nicolas Modrzyk amount = 300 begins\n;;=> ", "end": 2585, "score": 0.9770992398262024, "start": 2569, "tag": "NAME", "value": "Makoto Hashimoto" }, { "context": "ns\n;;=> transfer money from Makoto Hashimoto to Nicolas Modrzyk amount = 300 begins\n;;=> transfer money from ", "end": 2606, "score": 0.9984688758850098, "start": 2591, "tag": "NAME", "value": "Nicolas Modrzyk" }, { "context": "k amount = 300 begins\n;;=> transfer money from Makoto Hashimoto to Nicolas Modrzyk amount = 300 begins\n;;=> ", "end": 2672, "score": 0.9489575028419495, "start": 2656, "tag": "NAME", "value": "Makoto Hashimoto" }, { "context": "ns\n;;=> transfer money from Makoto Hashimoto to Nicolas Modrzyk amount = 300 begins\n;;=> transfer money from ", "end": 2693, "score": 0.9967520833015442, "start": 2678, "tag": "NAME", "value": "Nicolas Modrzyk" }, { "context": "k amount = 300 begins\n;;=> transfer money from Makoto Hashimoto to Nicolas Modrzyk amount = 300 begins\n;;=> ", "end": 2759, "score": 0.9969637393951416, "start": 2743, "tag": "NAME", "value": "Makoto Hashimoto" }, { "context": "ns\n;;=> transfer money from Makoto Hashimoto to Nicolas Modrzyk amount = 300 begins\n;;=> transfer money from ", "end": 2780, "score": 0.9996452927589417, "start": 2765, "tag": "NAME", "value": "Nicolas Modrzyk" }, { "context": "k amount = 300 begins\n;;=> transfer money from Makoto Hashimoto to Nicolas Modrzyk amount = 300 begins\n;;=> ", "end": 2846, "score": 0.9973764419555664, "start": 2830, "tag": "NAME", "value": "Makoto Hashimoto" }, { "context": "ns\n;;=> transfer money from Makoto Hashimoto to Nicolas Modrzyk amount = 300 begins\n;;=> Now, Makoto Hashimot", "end": 2867, "score": 0.9996379017829895, "start": 2852, "tag": "NAME", "value": "Nicolas Modrzyk" }, { "context": "icolas Modrzyk amount = 300 begins\n;;=> Now, Makoto Hashimoto amount is 790 and Nicolas Modrzyk ", "end": 2908, "score": 0.6698176860809326, "start": 2903, "tag": "NAME", "value": "akoto" }, { "context": ";;=> Now, Makoto Hashimoto amount is 790 and Nicolas Modrzyk amount is 2210\n;;=> transfer money from Makoto", "end": 2957, "score": 0.9656853079795837, "start": 2942, "tag": "NAME", "value": "Nicolas Modrzyk" }, { "context": "Modrzyk amount is 2210\n;;=> transfer money from Makoto Hashimoto to Nicolas Modrzyk amount = 300 begins\n;;=> ", "end": 3017, "score": 0.9941871166229248, "start": 3001, "tag": "NAME", "value": "Makoto Hashimoto" }, { "context": "10\n;;=> transfer money from Makoto Hashimoto to Nicolas Modrzyk amount = 300 begins\n;;=> Now, Makoto Hashimot", "end": 3038, "score": 0.9995205998420715, "start": 3023, "tag": "NAME", "value": "Nicolas Modrzyk" }, { "context": " Nicolas Modrzyk amount = 300 begins\n;;=> Now, Makoto Hashimoto amount is 490 and Nicolas Modrzyk amount", "end": 3086, "score": 0.7952176928520203, "start": 3073, "tag": "NAME", "value": "Makoto Hashim" }, { "context": ";;=> Now, Makoto Hashimoto amount is 490 and Nicolas Modrzyk amount is 2510\n\n(defn ensure-transfer! [from to", "end": 3128, "score": 0.9607400298118591, "start": 3113, "tag": "NAME", "value": "Nicolas Modrzyk" }, { "context": "nt makoto-account 200)))\n;;=> transfer money from Nicolas Modrzyk to Makoto Hashimoto amount = 100 begins\n;;=>", "end": 3819, "score": 0.9998214840888977, "start": 3804, "tag": "NAME", "value": "Nicolas Modrzyk" }, { "context": ")))\n;;=> transfer money from Nicolas Modrzyk to Makoto Hashimoto amount = 100 begins\n;;=> #<Future@53673cd", "end": 3836, "score": 0.881852924823761, "start": 3825, "tag": "NAME", "value": "Makoto Hash" }, { "context": "fer money from Nicolas Modrzyk to Makoto Hashimoto amount = 100 begins\n;;=> #<Future@53673cd8: :p", "end": 3841, "score": 0.5766531229019165, "start": 3838, "tag": "NAME", "value": "oto" }, { "context": "egins\n;;=> #<Future@53673cd8: :pending>\n;;=> Now, Nicolas Modrzyk amount is 2410 and Makoto Hashimoto amount ", "end": 3925, "score": 0.9995627999305725, "start": 3910, "tag": "NAME", "value": "Nicolas Modrzyk" }, { "context": "ashimoto amount is 590\n;;=> transfer money from Nicolas Modrzyk to Makoto Hashimoto amount = 200 begins\n;;=>", "end": 4024, "score": 0.9997879266738892, "start": 4009, "tag": "NAME", "value": "Nicolas Modrzyk" }, { "context": "590\n;;=> transfer money from Nicolas Modrzyk to Makoto Hashimoto amount = 200 begins\n;;=> Now, Nicol", "end": 4036, "score": 0.6319985389709473, "start": 4030, "tag": "NAME", "value": "Makoto" }, { "context": "Makoto Hashimoto amount = 200 begins\n;;=> Now, Nicolas Modrzyk amount is 2210 and Makoto Hashimoto amount ", "end": 4096, "score": 0.9994503855705261, "start": 4081, "tag": "NAME", "value": "Nicolas Modrzyk" }, { "context": ";;=> Now, Nicolas Modrzyk amount is 2210 and Makoto Hashimoto amount is 790\n\n(defn add-watcher [ref]\n (add-w", "end": 4137, "score": 0.9998202323913574, "start": 4121, "tag": "NAME", "value": "Makoto Hashimoto" }, { "context": "-account)\n;;=> #ref[{:status :ready, :val {:name \"Makoto Hashimoto\", :amount 1000}} 0x52f5973a]\n(add-watcher nico-ac", "end": 4465, "score": 0.9998709559440613, "start": 4449, "tag": "NAME", "value": "Makoto Hashimoto" }, { "context": "-account)\n;;=> #ref[{:status :ready, :val {:name \"Nicolas Modrzyk\", :amount 2000}} 0x7ecca962]\n\n(defn refined-trans", "end": 4577, "score": 0.9998917579650879, "start": 4562, "tag": "NAME", "value": "Nicolas Modrzyk" }, { "context": "-transfer!\n\n(do\n (ref-set makoto-account {:name \"Makoto Hashimoto\" :amount 1000})\n (ref-set nico-account {:name \"N", "end": 5002, "score": 0.9998679161071777, "start": 4986, "tag": "NAME", "value": "Makoto Hashimoto" }, { "context": "o\" :amount 1000})\n (ref-set nico-account {:name \"Nicolas Modrzyk\" :amount 2000}))\n;;=> IllegalStateException No tr", "end": 5066, "score": 0.9998919367790222, "start": 5051, "tag": "NAME", "value": "Nicolas Modrzyk" }, { "context": ":208)\n\n\n(dosync\n (ref-set makoto-account {:name \"Makoto Hashimoto\" :amount 1000})\n (ref-set nico-account {:name \"N", "end": 5382, "score": 0.9998714923858643, "start": 5366, "tag": "NAME", "value": "Makoto Hashimoto" }, { "context": "o\" :amount 1000})\n (ref-set nico-account {:name \"Nicolas Modrzyk\" :amount 2000}) \n )\n;;=> \"---- ref changed ---", "end": 5446, "score": 0.9998946189880371, "start": 5431, "tag": "NAME", "value": "Nicolas Modrzyk" }, { "context": "000}) \n )\n;;=> \"---- ref changed --- \" {:name \"Nicolas Modrzyk\", :amount 2000} \" => \" {:name \"Nicolas Modrzyk\", ", "end": 5522, "score": 0.9998928904533386, "start": 5507, "tag": "NAME", "value": "Nicolas Modrzyk" }, { "context": "e \"Nicolas Modrzyk\", :amount 2000} \" => \" {:name \"Nicolas Modrzyk\", :amount 2000}\n;;=> \"---- ref changed --- \" {:na", "end": 5569, "score": 0.9998810887336731, "start": 5554, "tag": "NAME", "value": "Nicolas Modrzyk" }, { "context": "amount 2000}\n;;=> \"---- ref changed --- \" {:name \"Makoto Hashimoto\", :amount 1000} \" => \" {:name \"Makoto Hashimoto\",", "end": 5639, "score": 0.9998695254325867, "start": 5623, "tag": "NAME", "value": "Makoto Hashimoto" }, { "context": " \"Makoto Hashimoto\", :amount 1000} \" => \" {:name \"Makoto Hashimoto\", :amount 1000}\n;;=> {:name \"Nicolas Modrzyk\", :a", "end": 5687, "score": 0.9998610019683838, "start": 5671, "tag": "NAME", "value": "Makoto Hashimoto" }, { "context": "me \"Makoto Hashimoto\", :amount 1000}\n;;=> {:name \"Nicolas Modrzyk\", :amount 2000}\n\n(dosync\n (ref-set makoto-accoun", "end": 5732, "score": 0.9998888373374939, "start": 5717, "tag": "NAME", "value": "Nicolas Modrzyk" }, { "context": " 2000}\n\n(dosync\n (ref-set makoto-account {:name \"Makoto Hashimoto\" :amount 1000})\n (ref-set nico-account {:name \"N", "end": 5808, "score": 0.9998769760131836, "start": 5792, "tag": "NAME", "value": "Makoto Hashimoto" }, { "context": "o\" :amount 1000})\n (ref-set nico-account {:name \"Nicolas Modrzyk\" :amount 2000}) \n )\n\n(do\n (future\n (r", "end": 5872, "score": 0.9998873472213745, "start": 5857, "tag": "NAME", "value": "Nicolas Modrzyk" }, { "context": "9: :pending>\n;;=> \"---- ref changed --- \" {:name \"Nicolas Modrzyk\", :amount 2000} \" => \" {:name \"Nicolas Modrzyk\", ", "end": 6137, "score": 0.9998803734779358, "start": 6122, "tag": "NAME", "value": "Nicolas Modrzyk" }, { "context": "e \"Nicolas Modrzyk\", :amount 2000} \" => \" {:name \"Nicolas Modrzyk\", :amount 2100}\n;;=> \"---- ref changed --- \" {:na", "end": 6184, "score": 0.9998893141746521, "start": 6169, "tag": "NAME", "value": "Nicolas Modrzyk" }, { "context": "amount 2100}\n;;=> \"---- ref changed --- \" {:name \"Makoto Hashimoto\", :amount 1000} \" => \" {:name \"Makoto Hashimoto\",", "end": 6254, "score": 0.9998779296875, "start": 6238, "tag": "NAME", "value": "Makoto Hashimoto" }, { "context": " \"Makoto Hashimoto\", :amount 1000} \" => \" {:name \"Makoto Hashimoto\", :amount 900}\n;;=> \"---- ref changed --- \" {:nam", "end": 6302, "score": 0.9998696446418762, "start": 6286, "tag": "NAME", "value": "Makoto Hashimoto" }, { "context": ":amount 900}\n;;=> \"---- ref changed --- \" {:name \"Nicolas Modrzyk\", :amount 2100} \" => \" {:name \"Nicolas Modrzyk\", ", "end": 6370, "score": 0.9998811483383179, "start": 6355, "tag": "NAME", "value": "Nicolas Modrzyk" }, { "context": "e \"Nicolas Modrzyk\", :amount 2100} \" => \" {:name \"Nicolas Modrzyk\", :amount 1800}\n;;=> \"---- ref changed --- \" {:na", "end": 6417, "score": 0.9998835325241089, "start": 6402, "tag": "NAME", "value": "Nicolas Modrzyk" }, { "context": "amount 1800}\n;;=> \"---- ref changed --- \" {:name \"Makoto Hashimoto\", :amount 900} \" => \" {:name \"Makoto Hashimoto\", ", "end": 6487, "score": 0.9998738169670105, "start": 6471, "tag": "NAME", "value": "Makoto Hashimoto" }, { "context": "e \"Makoto Hashimoto\", :amount 900} \" => \" {:name \"Makoto Hashimoto\", :amount 1200}\n\n(refined-transfer! makoto-accou", "end": 6534, "score": 0.9998690485954285, "start": 6518, "tag": "NAME", "value": "Makoto Hashimoto" }, { "context": "le-agent\n;;=> 1\n\n(def makoto-agent (agent {:name \"Makoto\" :location [100 200]}))\n;;=> #'chapter06.concurre", "end": 7942, "score": 0.9392240643501282, "start": 7936, "tag": "NAME", "value": "Makoto" }, { "context": "000 msecs\n;;=> #agent[{:status :ready, :val {:name Makoto, :location [100 200]}} 0x34a8e8f]\n;;=> #agent[{:s", "end": 8412, "score": 0.6554303169250488, "start": 8406, "tag": "NAME", "value": "Makoto" }, { "context": "x34a8e8f]\n;;=> #agent[{:status :ready, :val {:name Makoto, :location [110 220]}} 0x34a8e8f]\n\n(def x (p", "end": 8489, "score": 0.9321960806846619, "start": 8488, "tag": "NAME", "value": "M" } ]
Chapter 06 Code/src/chapter06/concurrency.clj
PacktPublishing/Clojure-Programming-Cookbook
14
(ns chapter06.concurrency [:require [clojure.core.reducers :as r] ] ) ;; atom & ref (def x (atom 1)) ;;=? #'chapter06.concurrency/x x ;;=> #<Atom@541e8f8d: 1> (deref x) ;;=> 1 @x ;;=> 1 (swap! x inc) ;;=> 2 @x ;;=> 2 (swap! x (partial + 1)) ;;=> 3 (reset! x 1) ;;=> 1 x ;;=> #<Atom@541e8f8d: 1> ;; Using validator (def y (atom 1 :validator (partial > 5))) ;;=> #'chapter06.concurrency/y (swap! y (partial + 2)) ;;=> 3 (swap! y (partial + 2)) ;;=> IllegalStateException Invalid reference state clojure.lang.ARef.validate (ARef.java:33) ;; Using CAS operation (defn cas-test! [my-atom interval] (let [v @my-atom u (inc @my-atom)] (println "current value = " v ", updated value = " u) (Thread/sleep interval) (println "updated " (compare-and-set! my-atom v u)))) ;;=> #'chapter06.concurrency/cas-test! (do (cas-test! x 20) (cas-test! x 30)) ;;=> current value = 1 , updated value = 2 ;;=> updated true ;;=> current value = 2 , updated value = 3 ;;=> updated true ;;=> nil (do (def x (atom 1)) (future (cas-test! x 20)) (future (cas-test! x 30))) ;;=> current value = 1 , updated value = 2 ;;=> current value = 1 , updated value = 2 ;;=> updated true ;;=> updated false (def makoto-account (ref {:name "Makoto Hashimoto" :amount 1000})) ;;=> #'chapter06.concurrency/makoto-account (def nico-account (ref {:name "Nicolas Modrzyk" :amount 2000})) ;;=> #'chapter06.concurrency/nico-account (defn transfer! [from to amount] (dosync (println "transfer money from " (:name @from) " to " (:name @to) " amount = " amount " begins") (alter from assoc :amount (- (:amount @from) amount)) (Thread/sleep 500) (alter to assoc :amount (+ (:amount @to) amount)) (println "Now, " (:name @from) " amount is " (:amount @from) " and " (:name @to) " amount is " (:amount @to)) )) ;;=> #'chapter06.concurrency/transfer! (transfer! makoto-account nico-account 10) ;;=> transfer money from Makoto to Nicolas amount = 10 begins ::=> Now, Makoto amount is 990 and Nicolas amount is 2010 ;;=> nil @nico-account ;;=> {:name "Nicolas Modrzyk", :amount 2010} (deref makoto-account) ;;=> {:name "Makoto Hashimoto", :amount 990} (do (future (transfer! makoto-account nico-account 200)) (future (transfer! makoto-account nico-account 300))) ;;=> transfer money from Makoto Hashimoto to Nicolas Modrzyk amount = 200 begins ;;=> #<Future@473dad05: :pending> ;;=> transfer money from Makoto Hashimoto to Nicolas Modrzyk amount = 300 begins ;;=> transfer money from Makoto Hashimoto to Nicolas Modrzyk amount = 300 begins ;;=> transfer money from Makoto Hashimoto to Nicolas Modrzyk amount = 300 begins ;;=> transfer money from Makoto Hashimoto to Nicolas Modrzyk amount = 300 begins ;;=> transfer money from Makoto Hashimoto to Nicolas Modrzyk amount = 300 begins ;;=> Now, Makoto Hashimoto amount is 790 and Nicolas Modrzyk amount is 2210 ;;=> transfer money from Makoto Hashimoto to Nicolas Modrzyk amount = 300 begins ;;=> Now, Makoto Hashimoto amount is 490 and Nicolas Modrzyk amount is 2510 (defn ensure-transfer! [from to amount] (dosync (ensure from) (println "transfer money from " (:name @from) " to " (:name @to) " amount = " amount " begins") (alter from assoc :amount (- (:amount @from) amount)) (Thread/sleep 500) (alter to assoc :amount (+ (:amount @to) amount)) (println "Now, " (:name @from) " amount is " (:amount @from) " and " (:name @to) " amount is " (:amount @to)))) ;;=> #'chapter06.concurrency/ensure-transfer! (do (future (ensure-transfer! nico-account makoto-account 100)) (future (ensure-transfer! nico-account makoto-account 200))) ;;=> transfer money from Nicolas Modrzyk to Makoto Hashimoto amount = 100 begins ;;=> #<Future@53673cd8: :pending> ;;=> Now, Nicolas Modrzyk amount is 2410 and Makoto Hashimoto amount is 590 ;;=> transfer money from Nicolas Modrzyk to Makoto Hashimoto amount = 200 begins ;;=> Now, Nicolas Modrzyk amount is 2210 and Makoto Hashimoto amount is 790 (defn add-watcher [ref] (add-watch ref :watcher (fn [_ _ old-state new-state] (prn "---- ref changed --- " old-state " => " new-state) ))) ;;=> #'chapter06.concurrency/add-watcher (add-watcher makoto-account) ;;=> #ref[{:status :ready, :val {:name "Makoto Hashimoto", :amount 1000}} 0x52f5973a] (add-watcher nico-account) ;;=> #ref[{:status :ready, :val {:name "Nicolas Modrzyk", :amount 2000}} 0x7ecca962] (defn refined-transfer! [from to amount] (dosync (ensure from) (if (<= (- (:amount @from) amount) 0) (throw (Exception. "insuficiant amount"))) (alter from assoc :amount (- (:amount @from) amount)) (Thread/sleep 500) (alter to assoc :amount (+ (:amount @to) amount)))) ;;=> #'chapter06.concurrency/refined-transfer! (do (ref-set makoto-account {:name "Makoto Hashimoto" :amount 1000}) (ref-set nico-account {:name "Nicolas Modrzyk" :amount 2000})) ;;=> IllegalStateException No transaction running clojure.lang.LockingTransaction.getEx (LockingTransaction.java:208) ;;=> IllegalStateException No transaction running clojure.lang.LockingTransaction.getEx (LockingTransaction.java:208) (dosync (ref-set makoto-account {:name "Makoto Hashimoto" :amount 1000}) (ref-set nico-account {:name "Nicolas Modrzyk" :amount 2000}) ) ;;=> "---- ref changed --- " {:name "Nicolas Modrzyk", :amount 2000} " => " {:name "Nicolas Modrzyk", :amount 2000} ;;=> "---- ref changed --- " {:name "Makoto Hashimoto", :amount 1000} " => " {:name "Makoto Hashimoto", :amount 1000} ;;=> {:name "Nicolas Modrzyk", :amount 2000} (dosync (ref-set makoto-account {:name "Makoto Hashimoto" :amount 1000}) (ref-set nico-account {:name "Nicolas Modrzyk" :amount 2000}) ) (do (future (refined-transfer! makoto-account nico-account 100)) (future (refined-transfer! nico-account makoto-account 300)) ) ;;=> #<Future@4c041c9: :pending> ;;=> "---- ref changed --- " {:name "Nicolas Modrzyk", :amount 2000} " => " {:name "Nicolas Modrzyk", :amount 2100} ;;=> "---- ref changed --- " {:name "Makoto Hashimoto", :amount 1000} " => " {:name "Makoto Hashimoto", :amount 900} ;;=> "---- ref changed --- " {:name "Nicolas Modrzyk", :amount 2100} " => " {:name "Nicolas Modrzyk", :amount 1800} ;;=> "---- ref changed --- " {:name "Makoto Hashimoto", :amount 900} " => " {:name "Makoto Hashimoto", :amount 1200} (refined-transfer! makoto-account nico-account 1500) ;;=> Exception insuficiant bound chapter06.concurrency/transfer!/fn--20708 (form-init8938610057865502322.clj:87) (defn alter-add! [var val] (dosync (Thread/sleep 500) (alter var (partial + val)))) ;;=> #'chapter06.concurrency/alter-add! (do (def v1 (ref 10)) (time (doseq [x [ (future (alter-add! v1 10)) (future (alter-add! v1 10)) (future (alter-add! v1 10)) (future (alter-add! v1 10)) (future (alter-add! v1 10)) ]] @x)) (println @v1) ) ;;=> "Elapsed time: 2504.52562 msecs" ;;=> 60 ;;=> nil (defn commute-add! [var val] (dosync (Thread/sleep 500) (commute var (partial + val)))) ;;=> #'chapter06.concurrency/commute-add! (do (def v1 (ref 10)) (time (doseq [x [(future (commute-add! v1 10)) (future (commute-add! v1 10)) (future (commute-add! v1 10)) (future (commute-add! v1 10)) (future (commute-add! v1 10))]] @x)) (println @v1) ) ;;=> "Elapsed time: 503.967362 msecs" ;;=> 60 (def simple-agent (agent 0)) ;;=> #'chapter06.concurrency/simple-agent simple-agent ;;=> #agent[{:status :ready, :val 0} 0x3aa1d3cc] (send simple-agent inc) ;;=> #agent[{:status :ready, :val 0} 0x3aa1d3cc] @simple-agent ;;=> 1 (def makoto-agent (agent {:name "Makoto" :location [100 200]})) ;;=> #'chapter06.concurrency/makoto-agent (defn move [a dx dy t] (println "moving takes " t "msecs") (Thread/sleep t) (assoc a :location [(+ ((:location a) 0) dx) (+ ((:location a) 1) dy)])) ;;=> #'chapter06.concurrency/move (do (send makoto-agent move 10 20 1000) (println makoto-agent) (await makoto-agent) (println makoto-agent)) ;;=> moving takes 1000 msecs ;;=> #agent[{:status :ready, :val {:name Makoto, :location [100 200]}} 0x34a8e8f] ;;=> #agent[{:status :ready, :val {:name Makoto, :location [110 220]}} 0x34a8e8f] (def x (promise)) ;;=> #'chapter06.concurrency/x (def y (promise)) ;;=> #'chapter06.concurrency/y (def z (promise)) (future (do (deliver z (+ @x @y)) (println "z value : " @z))) ;;=> #future[{:status :pending, :val nil} 0x5524e673] (realized? z) ;;=> false (deliver x 1) ;;=> #promise[{:status :ready, :val 1} 0x2f5df579] (deliver y 1) ;;=> #promise[{:status :ready, :val 1} 0x1614985] ;;=> z value : 2 ;;=> #<Promise@1b7f5e3c: 1> @z ;;=> 2 (defrecord Order [name price qty]) ;; => chapter06.concurrency.Order (defn merge-products [m1 m2] {:total-price (+ (* (.price x) (.qty x)) (* (.price y) (.qty y)))} [m1 m2]) ;; => #'chapter06.concurrency/merge-products (defn ship-products [x y z] (deliver z (merge-products @x @y)) (println "We can ship products " @z)) ;; => #'chapter06.concurrency/ship-products (defn deliver-product [p name price] (deliver p [name price])) ;; => #'chapter06.concurrency/deliver-product (def product-a (promise)) ;; => #'chapter06.concurrency/product-a (def product-b (promise)) ;; => #'chapter06.concurrency/product-b (def shipping-ab (promise)) ;; => #'chapter06.concurrency/shipping-ab (future (ship-products product-a product-b shipping-ab)) ;; => #future[{:status :pending, :val nil} 0x347af059] (deliver product-a (->Order "book" 10.1 5)) ;; => #promise[{:status :ready, :val #chapter06.concurrency.Order{:name "book", :price 10.1, :qty 5}} 0x1a198bfe] (deliver product-b (->Order "pencil" 2.1 10)) ;; => #promise[{:status :ready, :val #chapter06.concurrency.Order{:name "pencil", :price 2.1, :qty 10}} 0x458b44f6] ;;=> We can ship products [#chapter06.concurrency.Order{:name book, :price 10.1, :qty 5} #chapter06.concurrency.Order{:name pencil, :price 2.1, :qty 10}] (time (println (apply pcalls [(fn [] (reduce + (range 10000000))) (fn [] (reduce + (range 10000000 20000000))) ]))) ;;=> (49999995000000 149999995000000) ;;=> "Elapsed time: 454.398538 msecs" ;;=> nil (time (println (let [fn1 (fn [num-list] (reduce + num-list))] (pvalues (fn1 (range 0 10000000)) (fn1 (range 10000000 20000000)))))) ;;=> (49999995000000 149999995000000) ;;=> "Elapsed time: 578.047634 msecs" ;;=> nil
43934
(ns chapter06.concurrency [:require [clojure.core.reducers :as r] ] ) ;; atom & ref (def x (atom 1)) ;;=? #'chapter06.concurrency/x x ;;=> #<Atom@541e8f8d: 1> (deref x) ;;=> 1 @x ;;=> 1 (swap! x inc) ;;=> 2 @x ;;=> 2 (swap! x (partial + 1)) ;;=> 3 (reset! x 1) ;;=> 1 x ;;=> #<Atom@541e8f8d: 1> ;; Using validator (def y (atom 1 :validator (partial > 5))) ;;=> #'chapter06.concurrency/y (swap! y (partial + 2)) ;;=> 3 (swap! y (partial + 2)) ;;=> IllegalStateException Invalid reference state clojure.lang.ARef.validate (ARef.java:33) ;; Using CAS operation (defn cas-test! [my-atom interval] (let [v @my-atom u (inc @my-atom)] (println "current value = " v ", updated value = " u) (Thread/sleep interval) (println "updated " (compare-and-set! my-atom v u)))) ;;=> #'chapter06.concurrency/cas-test! (do (cas-test! x 20) (cas-test! x 30)) ;;=> current value = 1 , updated value = 2 ;;=> updated true ;;=> current value = 2 , updated value = 3 ;;=> updated true ;;=> nil (do (def x (atom 1)) (future (cas-test! x 20)) (future (cas-test! x 30))) ;;=> current value = 1 , updated value = 2 ;;=> current value = 1 , updated value = 2 ;;=> updated true ;;=> updated false (def makoto-account (ref {:name "<NAME>" :amount 1000})) ;;=> #'chapter06.concurrency/makoto-account (def nico-account (ref {:name "<NAME>" :amount 2000})) ;;=> #'chapter06.concurrency/nico-account (defn transfer! [from to amount] (dosync (println "transfer money from " (:name @from) " to " (:name @to) " amount = " amount " begins") (alter from assoc :amount (- (:amount @from) amount)) (Thread/sleep 500) (alter to assoc :amount (+ (:amount @to) amount)) (println "Now, " (:name @from) " amount is " (:amount @from) " and " (:name @to) " amount is " (:amount @to)) )) ;;=> #'chapter06.concurrency/transfer! (transfer! makoto-account nico-account 10) ;;=> transfer money from Makoto to Nicolas amount = 10 begins ::=> Now, Makoto amount is 990 and Nicolas amount is 2010 ;;=> nil @nico-account ;;=> {:name "<NAME>", :amount 2010} (deref makoto-account) ;;=> {:name "<NAME>", :amount 990} (do (future (transfer! makoto-account nico-account 200)) (future (transfer! makoto-account nico-account 300))) ;;=> transfer money from <NAME> to <NAME> amount = 200 begins ;;=> #<Future@473dad05: :pending> ;;=> transfer money from <NAME> to <NAME> amount = 300 begins ;;=> transfer money from <NAME> to <NAME> amount = 300 begins ;;=> transfer money from <NAME> to <NAME> amount = 300 begins ;;=> transfer money from <NAME> to <NAME> amount = 300 begins ;;=> transfer money from <NAME> to <NAME> amount = 300 begins ;;=> Now, M<NAME> Hashimoto amount is 790 and <NAME> amount is 2210 ;;=> transfer money from <NAME> to <NAME> amount = 300 begins ;;=> Now, <NAME>oto amount is 490 and <NAME> amount is 2510 (defn ensure-transfer! [from to amount] (dosync (ensure from) (println "transfer money from " (:name @from) " to " (:name @to) " amount = " amount " begins") (alter from assoc :amount (- (:amount @from) amount)) (Thread/sleep 500) (alter to assoc :amount (+ (:amount @to) amount)) (println "Now, " (:name @from) " amount is " (:amount @from) " and " (:name @to) " amount is " (:amount @to)))) ;;=> #'chapter06.concurrency/ensure-transfer! (do (future (ensure-transfer! nico-account makoto-account 100)) (future (ensure-transfer! nico-account makoto-account 200))) ;;=> transfer money from <NAME> to <NAME>im<NAME> amount = 100 begins ;;=> #<Future@53673cd8: :pending> ;;=> Now, <NAME> amount is 2410 and Makoto Hashimoto amount is 590 ;;=> transfer money from <NAME> to <NAME> Hashimoto amount = 200 begins ;;=> Now, <NAME> amount is 2210 and <NAME> amount is 790 (defn add-watcher [ref] (add-watch ref :watcher (fn [_ _ old-state new-state] (prn "---- ref changed --- " old-state " => " new-state) ))) ;;=> #'chapter06.concurrency/add-watcher (add-watcher makoto-account) ;;=> #ref[{:status :ready, :val {:name "<NAME>", :amount 1000}} 0x52f5973a] (add-watcher nico-account) ;;=> #ref[{:status :ready, :val {:name "<NAME>", :amount 2000}} 0x7ecca962] (defn refined-transfer! [from to amount] (dosync (ensure from) (if (<= (- (:amount @from) amount) 0) (throw (Exception. "insuficiant amount"))) (alter from assoc :amount (- (:amount @from) amount)) (Thread/sleep 500) (alter to assoc :amount (+ (:amount @to) amount)))) ;;=> #'chapter06.concurrency/refined-transfer! (do (ref-set makoto-account {:name "<NAME>" :amount 1000}) (ref-set nico-account {:name "<NAME>" :amount 2000})) ;;=> IllegalStateException No transaction running clojure.lang.LockingTransaction.getEx (LockingTransaction.java:208) ;;=> IllegalStateException No transaction running clojure.lang.LockingTransaction.getEx (LockingTransaction.java:208) (dosync (ref-set makoto-account {:name "<NAME>" :amount 1000}) (ref-set nico-account {:name "<NAME>" :amount 2000}) ) ;;=> "---- ref changed --- " {:name "<NAME>", :amount 2000} " => " {:name "<NAME>", :amount 2000} ;;=> "---- ref changed --- " {:name "<NAME>", :amount 1000} " => " {:name "<NAME>", :amount 1000} ;;=> {:name "<NAME>", :amount 2000} (dosync (ref-set makoto-account {:name "<NAME>" :amount 1000}) (ref-set nico-account {:name "<NAME>" :amount 2000}) ) (do (future (refined-transfer! makoto-account nico-account 100)) (future (refined-transfer! nico-account makoto-account 300)) ) ;;=> #<Future@4c041c9: :pending> ;;=> "---- ref changed --- " {:name "<NAME>", :amount 2000} " => " {:name "<NAME>", :amount 2100} ;;=> "---- ref changed --- " {:name "<NAME>", :amount 1000} " => " {:name "<NAME>", :amount 900} ;;=> "---- ref changed --- " {:name "<NAME>", :amount 2100} " => " {:name "<NAME>", :amount 1800} ;;=> "---- ref changed --- " {:name "<NAME>", :amount 900} " => " {:name "<NAME>", :amount 1200} (refined-transfer! makoto-account nico-account 1500) ;;=> Exception insuficiant bound chapter06.concurrency/transfer!/fn--20708 (form-init8938610057865502322.clj:87) (defn alter-add! [var val] (dosync (Thread/sleep 500) (alter var (partial + val)))) ;;=> #'chapter06.concurrency/alter-add! (do (def v1 (ref 10)) (time (doseq [x [ (future (alter-add! v1 10)) (future (alter-add! v1 10)) (future (alter-add! v1 10)) (future (alter-add! v1 10)) (future (alter-add! v1 10)) ]] @x)) (println @v1) ) ;;=> "Elapsed time: 2504.52562 msecs" ;;=> 60 ;;=> nil (defn commute-add! [var val] (dosync (Thread/sleep 500) (commute var (partial + val)))) ;;=> #'chapter06.concurrency/commute-add! (do (def v1 (ref 10)) (time (doseq [x [(future (commute-add! v1 10)) (future (commute-add! v1 10)) (future (commute-add! v1 10)) (future (commute-add! v1 10)) (future (commute-add! v1 10))]] @x)) (println @v1) ) ;;=> "Elapsed time: 503.967362 msecs" ;;=> 60 (def simple-agent (agent 0)) ;;=> #'chapter06.concurrency/simple-agent simple-agent ;;=> #agent[{:status :ready, :val 0} 0x3aa1d3cc] (send simple-agent inc) ;;=> #agent[{:status :ready, :val 0} 0x3aa1d3cc] @simple-agent ;;=> 1 (def makoto-agent (agent {:name "<NAME>" :location [100 200]})) ;;=> #'chapter06.concurrency/makoto-agent (defn move [a dx dy t] (println "moving takes " t "msecs") (Thread/sleep t) (assoc a :location [(+ ((:location a) 0) dx) (+ ((:location a) 1) dy)])) ;;=> #'chapter06.concurrency/move (do (send makoto-agent move 10 20 1000) (println makoto-agent) (await makoto-agent) (println makoto-agent)) ;;=> moving takes 1000 msecs ;;=> #agent[{:status :ready, :val {:name <NAME>, :location [100 200]}} 0x34a8e8f] ;;=> #agent[{:status :ready, :val {:name <NAME>akoto, :location [110 220]}} 0x34a8e8f] (def x (promise)) ;;=> #'chapter06.concurrency/x (def y (promise)) ;;=> #'chapter06.concurrency/y (def z (promise)) (future (do (deliver z (+ @x @y)) (println "z value : " @z))) ;;=> #future[{:status :pending, :val nil} 0x5524e673] (realized? z) ;;=> false (deliver x 1) ;;=> #promise[{:status :ready, :val 1} 0x2f5df579] (deliver y 1) ;;=> #promise[{:status :ready, :val 1} 0x1614985] ;;=> z value : 2 ;;=> #<Promise@1b7f5e3c: 1> @z ;;=> 2 (defrecord Order [name price qty]) ;; => chapter06.concurrency.Order (defn merge-products [m1 m2] {:total-price (+ (* (.price x) (.qty x)) (* (.price y) (.qty y)))} [m1 m2]) ;; => #'chapter06.concurrency/merge-products (defn ship-products [x y z] (deliver z (merge-products @x @y)) (println "We can ship products " @z)) ;; => #'chapter06.concurrency/ship-products (defn deliver-product [p name price] (deliver p [name price])) ;; => #'chapter06.concurrency/deliver-product (def product-a (promise)) ;; => #'chapter06.concurrency/product-a (def product-b (promise)) ;; => #'chapter06.concurrency/product-b (def shipping-ab (promise)) ;; => #'chapter06.concurrency/shipping-ab (future (ship-products product-a product-b shipping-ab)) ;; => #future[{:status :pending, :val nil} 0x347af059] (deliver product-a (->Order "book" 10.1 5)) ;; => #promise[{:status :ready, :val #chapter06.concurrency.Order{:name "book", :price 10.1, :qty 5}} 0x1a198bfe] (deliver product-b (->Order "pencil" 2.1 10)) ;; => #promise[{:status :ready, :val #chapter06.concurrency.Order{:name "pencil", :price 2.1, :qty 10}} 0x458b44f6] ;;=> We can ship products [#chapter06.concurrency.Order{:name book, :price 10.1, :qty 5} #chapter06.concurrency.Order{:name pencil, :price 2.1, :qty 10}] (time (println (apply pcalls [(fn [] (reduce + (range 10000000))) (fn [] (reduce + (range 10000000 20000000))) ]))) ;;=> (49999995000000 149999995000000) ;;=> "Elapsed time: 454.398538 msecs" ;;=> nil (time (println (let [fn1 (fn [num-list] (reduce + num-list))] (pvalues (fn1 (range 0 10000000)) (fn1 (range 10000000 20000000)))))) ;;=> (49999995000000 149999995000000) ;;=> "Elapsed time: 578.047634 msecs" ;;=> nil
true
(ns chapter06.concurrency [:require [clojure.core.reducers :as r] ] ) ;; atom & ref (def x (atom 1)) ;;=? #'chapter06.concurrency/x x ;;=> #<Atom@541e8f8d: 1> (deref x) ;;=> 1 @x ;;=> 1 (swap! x inc) ;;=> 2 @x ;;=> 2 (swap! x (partial + 1)) ;;=> 3 (reset! x 1) ;;=> 1 x ;;=> #<Atom@541e8f8d: 1> ;; Using validator (def y (atom 1 :validator (partial > 5))) ;;=> #'chapter06.concurrency/y (swap! y (partial + 2)) ;;=> 3 (swap! y (partial + 2)) ;;=> IllegalStateException Invalid reference state clojure.lang.ARef.validate (ARef.java:33) ;; Using CAS operation (defn cas-test! [my-atom interval] (let [v @my-atom u (inc @my-atom)] (println "current value = " v ", updated value = " u) (Thread/sleep interval) (println "updated " (compare-and-set! my-atom v u)))) ;;=> #'chapter06.concurrency/cas-test! (do (cas-test! x 20) (cas-test! x 30)) ;;=> current value = 1 , updated value = 2 ;;=> updated true ;;=> current value = 2 , updated value = 3 ;;=> updated true ;;=> nil (do (def x (atom 1)) (future (cas-test! x 20)) (future (cas-test! x 30))) ;;=> current value = 1 , updated value = 2 ;;=> current value = 1 , updated value = 2 ;;=> updated true ;;=> updated false (def makoto-account (ref {:name "PI:NAME:<NAME>END_PI" :amount 1000})) ;;=> #'chapter06.concurrency/makoto-account (def nico-account (ref {:name "PI:NAME:<NAME>END_PI" :amount 2000})) ;;=> #'chapter06.concurrency/nico-account (defn transfer! [from to amount] (dosync (println "transfer money from " (:name @from) " to " (:name @to) " amount = " amount " begins") (alter from assoc :amount (- (:amount @from) amount)) (Thread/sleep 500) (alter to assoc :amount (+ (:amount @to) amount)) (println "Now, " (:name @from) " amount is " (:amount @from) " and " (:name @to) " amount is " (:amount @to)) )) ;;=> #'chapter06.concurrency/transfer! (transfer! makoto-account nico-account 10) ;;=> transfer money from Makoto to Nicolas amount = 10 begins ::=> Now, Makoto amount is 990 and Nicolas amount is 2010 ;;=> nil @nico-account ;;=> {:name "PI:NAME:<NAME>END_PI", :amount 2010} (deref makoto-account) ;;=> {:name "PI:NAME:<NAME>END_PI", :amount 990} (do (future (transfer! makoto-account nico-account 200)) (future (transfer! makoto-account nico-account 300))) ;;=> transfer money from PI:NAME:<NAME>END_PI to PI:NAME:<NAME>END_PI amount = 200 begins ;;=> #<Future@473dad05: :pending> ;;=> transfer money from PI:NAME:<NAME>END_PI to PI:NAME:<NAME>END_PI amount = 300 begins ;;=> transfer money from PI:NAME:<NAME>END_PI to PI:NAME:<NAME>END_PI amount = 300 begins ;;=> transfer money from PI:NAME:<NAME>END_PI to PI:NAME:<NAME>END_PI amount = 300 begins ;;=> transfer money from PI:NAME:<NAME>END_PI to PI:NAME:<NAME>END_PI amount = 300 begins ;;=> transfer money from PI:NAME:<NAME>END_PI to PI:NAME:<NAME>END_PI amount = 300 begins ;;=> Now, MPI:NAME:<NAME>END_PI Hashimoto amount is 790 and PI:NAME:<NAME>END_PI amount is 2210 ;;=> transfer money from PI:NAME:<NAME>END_PI to PI:NAME:<NAME>END_PI amount = 300 begins ;;=> Now, PI:NAME:<NAME>END_PIoto amount is 490 and PI:NAME:<NAME>END_PI amount is 2510 (defn ensure-transfer! [from to amount] (dosync (ensure from) (println "transfer money from " (:name @from) " to " (:name @to) " amount = " amount " begins") (alter from assoc :amount (- (:amount @from) amount)) (Thread/sleep 500) (alter to assoc :amount (+ (:amount @to) amount)) (println "Now, " (:name @from) " amount is " (:amount @from) " and " (:name @to) " amount is " (:amount @to)))) ;;=> #'chapter06.concurrency/ensure-transfer! (do (future (ensure-transfer! nico-account makoto-account 100)) (future (ensure-transfer! nico-account makoto-account 200))) ;;=> transfer money from PI:NAME:<NAME>END_PI to PI:NAME:<NAME>END_PIimPI:NAME:<NAME>END_PI amount = 100 begins ;;=> #<Future@53673cd8: :pending> ;;=> Now, PI:NAME:<NAME>END_PI amount is 2410 and Makoto Hashimoto amount is 590 ;;=> transfer money from PI:NAME:<NAME>END_PI to PI:NAME:<NAME>END_PI Hashimoto amount = 200 begins ;;=> Now, PI:NAME:<NAME>END_PI amount is 2210 and PI:NAME:<NAME>END_PI amount is 790 (defn add-watcher [ref] (add-watch ref :watcher (fn [_ _ old-state new-state] (prn "---- ref changed --- " old-state " => " new-state) ))) ;;=> #'chapter06.concurrency/add-watcher (add-watcher makoto-account) ;;=> #ref[{:status :ready, :val {:name "PI:NAME:<NAME>END_PI", :amount 1000}} 0x52f5973a] (add-watcher nico-account) ;;=> #ref[{:status :ready, :val {:name "PI:NAME:<NAME>END_PI", :amount 2000}} 0x7ecca962] (defn refined-transfer! [from to amount] (dosync (ensure from) (if (<= (- (:amount @from) amount) 0) (throw (Exception. "insuficiant amount"))) (alter from assoc :amount (- (:amount @from) amount)) (Thread/sleep 500) (alter to assoc :amount (+ (:amount @to) amount)))) ;;=> #'chapter06.concurrency/refined-transfer! (do (ref-set makoto-account {:name "PI:NAME:<NAME>END_PI" :amount 1000}) (ref-set nico-account {:name "PI:NAME:<NAME>END_PI" :amount 2000})) ;;=> IllegalStateException No transaction running clojure.lang.LockingTransaction.getEx (LockingTransaction.java:208) ;;=> IllegalStateException No transaction running clojure.lang.LockingTransaction.getEx (LockingTransaction.java:208) (dosync (ref-set makoto-account {:name "PI:NAME:<NAME>END_PI" :amount 1000}) (ref-set nico-account {:name "PI:NAME:<NAME>END_PI" :amount 2000}) ) ;;=> "---- ref changed --- " {:name "PI:NAME:<NAME>END_PI", :amount 2000} " => " {:name "PI:NAME:<NAME>END_PI", :amount 2000} ;;=> "---- ref changed --- " {:name "PI:NAME:<NAME>END_PI", :amount 1000} " => " {:name "PI:NAME:<NAME>END_PI", :amount 1000} ;;=> {:name "PI:NAME:<NAME>END_PI", :amount 2000} (dosync (ref-set makoto-account {:name "PI:NAME:<NAME>END_PI" :amount 1000}) (ref-set nico-account {:name "PI:NAME:<NAME>END_PI" :amount 2000}) ) (do (future (refined-transfer! makoto-account nico-account 100)) (future (refined-transfer! nico-account makoto-account 300)) ) ;;=> #<Future@4c041c9: :pending> ;;=> "---- ref changed --- " {:name "PI:NAME:<NAME>END_PI", :amount 2000} " => " {:name "PI:NAME:<NAME>END_PI", :amount 2100} ;;=> "---- ref changed --- " {:name "PI:NAME:<NAME>END_PI", :amount 1000} " => " {:name "PI:NAME:<NAME>END_PI", :amount 900} ;;=> "---- ref changed --- " {:name "PI:NAME:<NAME>END_PI", :amount 2100} " => " {:name "PI:NAME:<NAME>END_PI", :amount 1800} ;;=> "---- ref changed --- " {:name "PI:NAME:<NAME>END_PI", :amount 900} " => " {:name "PI:NAME:<NAME>END_PI", :amount 1200} (refined-transfer! makoto-account nico-account 1500) ;;=> Exception insuficiant bound chapter06.concurrency/transfer!/fn--20708 (form-init8938610057865502322.clj:87) (defn alter-add! [var val] (dosync (Thread/sleep 500) (alter var (partial + val)))) ;;=> #'chapter06.concurrency/alter-add! (do (def v1 (ref 10)) (time (doseq [x [ (future (alter-add! v1 10)) (future (alter-add! v1 10)) (future (alter-add! v1 10)) (future (alter-add! v1 10)) (future (alter-add! v1 10)) ]] @x)) (println @v1) ) ;;=> "Elapsed time: 2504.52562 msecs" ;;=> 60 ;;=> nil (defn commute-add! [var val] (dosync (Thread/sleep 500) (commute var (partial + val)))) ;;=> #'chapter06.concurrency/commute-add! (do (def v1 (ref 10)) (time (doseq [x [(future (commute-add! v1 10)) (future (commute-add! v1 10)) (future (commute-add! v1 10)) (future (commute-add! v1 10)) (future (commute-add! v1 10))]] @x)) (println @v1) ) ;;=> "Elapsed time: 503.967362 msecs" ;;=> 60 (def simple-agent (agent 0)) ;;=> #'chapter06.concurrency/simple-agent simple-agent ;;=> #agent[{:status :ready, :val 0} 0x3aa1d3cc] (send simple-agent inc) ;;=> #agent[{:status :ready, :val 0} 0x3aa1d3cc] @simple-agent ;;=> 1 (def makoto-agent (agent {:name "PI:NAME:<NAME>END_PI" :location [100 200]})) ;;=> #'chapter06.concurrency/makoto-agent (defn move [a dx dy t] (println "moving takes " t "msecs") (Thread/sleep t) (assoc a :location [(+ ((:location a) 0) dx) (+ ((:location a) 1) dy)])) ;;=> #'chapter06.concurrency/move (do (send makoto-agent move 10 20 1000) (println makoto-agent) (await makoto-agent) (println makoto-agent)) ;;=> moving takes 1000 msecs ;;=> #agent[{:status :ready, :val {:name PI:NAME:<NAME>END_PI, :location [100 200]}} 0x34a8e8f] ;;=> #agent[{:status :ready, :val {:name PI:NAME:<NAME>END_PIakoto, :location [110 220]}} 0x34a8e8f] (def x (promise)) ;;=> #'chapter06.concurrency/x (def y (promise)) ;;=> #'chapter06.concurrency/y (def z (promise)) (future (do (deliver z (+ @x @y)) (println "z value : " @z))) ;;=> #future[{:status :pending, :val nil} 0x5524e673] (realized? z) ;;=> false (deliver x 1) ;;=> #promise[{:status :ready, :val 1} 0x2f5df579] (deliver y 1) ;;=> #promise[{:status :ready, :val 1} 0x1614985] ;;=> z value : 2 ;;=> #<Promise@1b7f5e3c: 1> @z ;;=> 2 (defrecord Order [name price qty]) ;; => chapter06.concurrency.Order (defn merge-products [m1 m2] {:total-price (+ (* (.price x) (.qty x)) (* (.price y) (.qty y)))} [m1 m2]) ;; => #'chapter06.concurrency/merge-products (defn ship-products [x y z] (deliver z (merge-products @x @y)) (println "We can ship products " @z)) ;; => #'chapter06.concurrency/ship-products (defn deliver-product [p name price] (deliver p [name price])) ;; => #'chapter06.concurrency/deliver-product (def product-a (promise)) ;; => #'chapter06.concurrency/product-a (def product-b (promise)) ;; => #'chapter06.concurrency/product-b (def shipping-ab (promise)) ;; => #'chapter06.concurrency/shipping-ab (future (ship-products product-a product-b shipping-ab)) ;; => #future[{:status :pending, :val nil} 0x347af059] (deliver product-a (->Order "book" 10.1 5)) ;; => #promise[{:status :ready, :val #chapter06.concurrency.Order{:name "book", :price 10.1, :qty 5}} 0x1a198bfe] (deliver product-b (->Order "pencil" 2.1 10)) ;; => #promise[{:status :ready, :val #chapter06.concurrency.Order{:name "pencil", :price 2.1, :qty 10}} 0x458b44f6] ;;=> We can ship products [#chapter06.concurrency.Order{:name book, :price 10.1, :qty 5} #chapter06.concurrency.Order{:name pencil, :price 2.1, :qty 10}] (time (println (apply pcalls [(fn [] (reduce + (range 10000000))) (fn [] (reduce + (range 10000000 20000000))) ]))) ;;=> (49999995000000 149999995000000) ;;=> "Elapsed time: 454.398538 msecs" ;;=> nil (time (println (let [fn1 (fn [num-list] (reduce + num-list))] (pvalues (fn1 (range 0 10000000)) (fn1 (range 10000000 20000000)))))) ;;=> (49999995000000 149999995000000) ;;=> "Elapsed time: 578.047634 msecs" ;;=> nil
[ { "context": ";; Copyright (c) 2014, Andrey Antukh\n;; Copyright (c) 2014, Alejandro Gómez\n;; All rig", "end": 36, "score": 0.999875545501709, "start": 23, "tag": "NAME", "value": "Andrey Antukh" }, { "context": "ght (c) 2014, Andrey Antukh\n;; Copyright (c) 2014, Alejandro Gómez\n;; All rights reserved.\n;;\n;; Redistribution and ", "end": 75, "score": 0.9998605251312256, "start": 60, "tag": "NAME", "value": "Alejandro Gómez" } ]
src/cljx/cats/monad/maybe.cljx
pbaille/cats
0
;; Copyright (c) 2014, Andrey Antukh ;; Copyright (c) 2014, Alejandro Gómez ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions ;; are met: ;; ;; 1. Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; 2. Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ;; IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, ;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (ns cats.monad.maybe "The Maybe Monad." (:require [cats.protocols :as proto])) (declare maybe-monad) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Type constructors and functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (deftype Just [v] proto/Context (get-context [_] maybe-monad) (get-value [_] v) #+clj Object #+clj (equals [self other] (if (instance? Just other) (= v (.-v other)) false)) #+clj (toString [self] (with-out-str (print [v]))) #+cljs cljs.core/IEquiv #+cljs (-equiv [_ other] (if (instance? Just other) (= v (.-v other)) false))) (deftype Nothing [] proto/Context (get-context [_] maybe-monad) (get-value [_] nil) #+clj Object #+clj (equals [_ other] (instance? Nothing other)) #+clj (toString [_] (with-out-str (print ""))) #+cljs cljs.core/IEquiv #+cljs (-equiv [_ other] (instance? Nothing other))) (defn maybe? [v] (or (instance? Just v) (instance? Nothing v) (nil? v))) (defn just ([v] (Just. v)) ([] (Just. nil))) (defn nothing [] (Nothing.)) (defn just? [v] (instance? Just v)) (defn nothing? [v] (or (nil? v) (instance? Nothing v))) (defn from-maybe "Return inner value from maybe monad. Accepts an optional default value. Examples: (from-maybe (just 1)) ;=> 1 (from-maybe (just 1) 42) ;=> 1 (from-maybe (nothing)) ;=> nil (from-maybe (nothing) 42) ;=> 42 " ([mv] {:pre [(maybe? mv)]} (when (just? mv) (.-v mv))) ([mv default] {:pre [(maybe? mv)]} (if (just? mv) (.-v mv) default))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Monad definition ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def maybe-monad (reify proto/Functor (fmap [_ f mv] (if (nothing? mv) mv (just (f (from-maybe mv))))) proto/Applicative (pure [_ v] (just v)) (fapply [m af av] (if (nothing? af) af (proto/fmap m (from-maybe af) av))) proto/Monad (mreturn [_ v] (just v)) (mbind [_ mv f] (if (nothing? mv) mv (f (from-maybe mv)))) proto/MonadZero (mzero [_] (nothing)) proto/MonadPlus (mplus [_ mv mv'] (if (just? mv) mv mv')))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Monad transformer definition ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn maybe-transformer [inner-monad] (reify proto/Functor (fmap [_ f fv] (proto/fmap inner-monad #(proto/fmap maybe-monad f %) fv)) proto/Monad (mreturn [m v] (proto/mreturn inner-monad (just v))) (mbind [_ mv f] (proto/mbind inner-monad mv (fn [maybe-v] (if (just? maybe-v) (f (from-maybe maybe-v)) (proto/mreturn inner-monad (nothing)))))) proto/MonadZero (mzero [_] (proto/mreturn inner-monad (nothing))) proto/MonadPlus (mplus [_ mv mv'] (proto/mbind inner-monad mv (fn [maybe-v] (if (just? maybe-v) (proto/mreturn inner-monad maybe-v) mv')))) proto/MonadTrans (base [_] maybe-monad) (inner [_] inner-monad) (lift [_ mv] (proto/mbind inner-monad mv (fn [v] (proto/mreturn inner-monad (just v)))))))
93967
;; Copyright (c) 2014, <NAME> ;; Copyright (c) 2014, <NAME> ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions ;; are met: ;; ;; 1. Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; 2. Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ;; IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, ;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (ns cats.monad.maybe "The Maybe Monad." (:require [cats.protocols :as proto])) (declare maybe-monad) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Type constructors and functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (deftype Just [v] proto/Context (get-context [_] maybe-monad) (get-value [_] v) #+clj Object #+clj (equals [self other] (if (instance? Just other) (= v (.-v other)) false)) #+clj (toString [self] (with-out-str (print [v]))) #+cljs cljs.core/IEquiv #+cljs (-equiv [_ other] (if (instance? Just other) (= v (.-v other)) false))) (deftype Nothing [] proto/Context (get-context [_] maybe-monad) (get-value [_] nil) #+clj Object #+clj (equals [_ other] (instance? Nothing other)) #+clj (toString [_] (with-out-str (print ""))) #+cljs cljs.core/IEquiv #+cljs (-equiv [_ other] (instance? Nothing other))) (defn maybe? [v] (or (instance? Just v) (instance? Nothing v) (nil? v))) (defn just ([v] (Just. v)) ([] (Just. nil))) (defn nothing [] (Nothing.)) (defn just? [v] (instance? Just v)) (defn nothing? [v] (or (nil? v) (instance? Nothing v))) (defn from-maybe "Return inner value from maybe monad. Accepts an optional default value. Examples: (from-maybe (just 1)) ;=> 1 (from-maybe (just 1) 42) ;=> 1 (from-maybe (nothing)) ;=> nil (from-maybe (nothing) 42) ;=> 42 " ([mv] {:pre [(maybe? mv)]} (when (just? mv) (.-v mv))) ([mv default] {:pre [(maybe? mv)]} (if (just? mv) (.-v mv) default))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Monad definition ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def maybe-monad (reify proto/Functor (fmap [_ f mv] (if (nothing? mv) mv (just (f (from-maybe mv))))) proto/Applicative (pure [_ v] (just v)) (fapply [m af av] (if (nothing? af) af (proto/fmap m (from-maybe af) av))) proto/Monad (mreturn [_ v] (just v)) (mbind [_ mv f] (if (nothing? mv) mv (f (from-maybe mv)))) proto/MonadZero (mzero [_] (nothing)) proto/MonadPlus (mplus [_ mv mv'] (if (just? mv) mv mv')))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Monad transformer definition ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn maybe-transformer [inner-monad] (reify proto/Functor (fmap [_ f fv] (proto/fmap inner-monad #(proto/fmap maybe-monad f %) fv)) proto/Monad (mreturn [m v] (proto/mreturn inner-monad (just v))) (mbind [_ mv f] (proto/mbind inner-monad mv (fn [maybe-v] (if (just? maybe-v) (f (from-maybe maybe-v)) (proto/mreturn inner-monad (nothing)))))) proto/MonadZero (mzero [_] (proto/mreturn inner-monad (nothing))) proto/MonadPlus (mplus [_ mv mv'] (proto/mbind inner-monad mv (fn [maybe-v] (if (just? maybe-v) (proto/mreturn inner-monad maybe-v) mv')))) proto/MonadTrans (base [_] maybe-monad) (inner [_] inner-monad) (lift [_ mv] (proto/mbind inner-monad mv (fn [v] (proto/mreturn inner-monad (just v)))))))
true
;; Copyright (c) 2014, PI:NAME:<NAME>END_PI ;; Copyright (c) 2014, PI:NAME:<NAME>END_PI ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions ;; are met: ;; ;; 1. Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; 2. Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ;; IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, ;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (ns cats.monad.maybe "The Maybe Monad." (:require [cats.protocols :as proto])) (declare maybe-monad) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Type constructors and functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (deftype Just [v] proto/Context (get-context [_] maybe-monad) (get-value [_] v) #+clj Object #+clj (equals [self other] (if (instance? Just other) (= v (.-v other)) false)) #+clj (toString [self] (with-out-str (print [v]))) #+cljs cljs.core/IEquiv #+cljs (-equiv [_ other] (if (instance? Just other) (= v (.-v other)) false))) (deftype Nothing [] proto/Context (get-context [_] maybe-monad) (get-value [_] nil) #+clj Object #+clj (equals [_ other] (instance? Nothing other)) #+clj (toString [_] (with-out-str (print ""))) #+cljs cljs.core/IEquiv #+cljs (-equiv [_ other] (instance? Nothing other))) (defn maybe? [v] (or (instance? Just v) (instance? Nothing v) (nil? v))) (defn just ([v] (Just. v)) ([] (Just. nil))) (defn nothing [] (Nothing.)) (defn just? [v] (instance? Just v)) (defn nothing? [v] (or (nil? v) (instance? Nothing v))) (defn from-maybe "Return inner value from maybe monad. Accepts an optional default value. Examples: (from-maybe (just 1)) ;=> 1 (from-maybe (just 1) 42) ;=> 1 (from-maybe (nothing)) ;=> nil (from-maybe (nothing) 42) ;=> 42 " ([mv] {:pre [(maybe? mv)]} (when (just? mv) (.-v mv))) ([mv default] {:pre [(maybe? mv)]} (if (just? mv) (.-v mv) default))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Monad definition ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def maybe-monad (reify proto/Functor (fmap [_ f mv] (if (nothing? mv) mv (just (f (from-maybe mv))))) proto/Applicative (pure [_ v] (just v)) (fapply [m af av] (if (nothing? af) af (proto/fmap m (from-maybe af) av))) proto/Monad (mreturn [_ v] (just v)) (mbind [_ mv f] (if (nothing? mv) mv (f (from-maybe mv)))) proto/MonadZero (mzero [_] (nothing)) proto/MonadPlus (mplus [_ mv mv'] (if (just? mv) mv mv')))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Monad transformer definition ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn maybe-transformer [inner-monad] (reify proto/Functor (fmap [_ f fv] (proto/fmap inner-monad #(proto/fmap maybe-monad f %) fv)) proto/Monad (mreturn [m v] (proto/mreturn inner-monad (just v))) (mbind [_ mv f] (proto/mbind inner-monad mv (fn [maybe-v] (if (just? maybe-v) (f (from-maybe maybe-v)) (proto/mreturn inner-monad (nothing)))))) proto/MonadZero (mzero [_] (proto/mreturn inner-monad (nothing))) proto/MonadPlus (mplus [_ mv mv'] (proto/mbind inner-monad mv (fn [maybe-v] (if (just? maybe-v) (proto/mreturn inner-monad maybe-v) mv')))) proto/MonadTrans (base [_] maybe-monad) (inner [_] inner-monad) (lift [_ mv] (proto/mbind inner-monad mv (fn [v] (proto/mreturn inner-monad (just v)))))))
[ { "context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li", "end": 111, "score": 0.9998043179512024, "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.9998161792755127, "start": 113, "tag": "NAME", "value": "Christian Murray" } ]
editor/src/clj/editor/asset_browser.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.asset-browser (:require [clojure.java.io :as io] [clojure.string :as string] [dynamo.graph :as g] [editor.error-reporting :as error-reporting] [editor.fs :as fs] [editor.fxui :as fxui] [editor.handler :as handler] [editor.icons :as icons] [editor.ui :as ui] [editor.prefs :as prefs] [editor.resource :as resource] [editor.resource-watch :as resource-watch] [editor.workspace :as workspace] [editor.dialogs :as dialogs] [editor.disk-availability :as disk-availability] [editor.app-view :as app-view]) (:import [com.defold.editor Start] [editor.resource FileResource] [javafx.application Platform] [javafx.collections FXCollections ObservableList] [javafx.embed.swing SwingFXUtils] [javafx.event ActionEvent Event EventHandler] [javafx.fxml FXMLLoader] [javafx.geometry Insets] [javafx.scene.input Clipboard ClipboardContent] [javafx.scene.input DragEvent TransferMode MouseEvent] [javafx.scene Scene Node Parent] [javafx.scene.control Button ColorPicker Label TextField TitledPane TextArea TreeItem TreeView Menu MenuItem SeparatorMenuItem MenuBar Tab ProgressBar ContextMenu SelectionMode] [javafx.scene.image Image ImageView WritableImage PixelWriter] [javafx.scene.input MouseEvent KeyCombination ContextMenuEvent] [javafx.scene.layout AnchorPane GridPane StackPane HBox Priority] [javafx.scene.paint Color] [javafx.stage Stage FileChooser] [javafx.util Callback] [java.io File] [java.nio.file Path Paths] [java.util.prefs Preferences] [com.jogamp.opengl GL GL2 GLContext GLProfile GLDrawableFactory GLCapabilities] [org.apache.commons.io FilenameUtils] [com.defold.control TreeCell])) (set! *warn-on-reflection* true) (declare tree-item) (def ^:private empty-string-array (into-array String [])) (defn- ->path [s] (Paths/get s empty-string-array)) ; TreeItem creator (defn- ^ObservableList list-children [parent] (let [children (:children parent) items (->> (:children parent) (remove resource/internal?) (map tree-item) (into-array TreeItem))] (if (empty? children) (FXCollections/emptyObservableList) (doto (FXCollections/observableArrayList) (.addAll ^"[Ljavafx.scene.control.TreeItem;" items))))) ; NOTE: Without caching stack-overflow... WHY? (defn tree-item ^TreeItem [parent] (let [cached (atom false)] (proxy [TreeItem] [parent] (isLeaf [] (or (not= :folder (resource/source-type (.getValue ^TreeItem this))) (empty? (:children (.getValue ^TreeItem this))))) (getChildren [] (let [this ^TreeItem this ^ObservableList children (proxy-super getChildren)] (when-not @cached (reset! cached true) (.setAll children (list-children (.getValue this)))) children))))) (handler/register-menu! ::resource-menu [{:label "Open" :icon "icons/32/Icons_S_14_linkarrow.png" :command :open} {:label "Open As" :icon "icons/32/Icons_S_14_linkarrow.png" :command :open-as} {:label :separator} {:label "Copy Project Path" :command :copy-project-path} {:label "Copy Full Path" :command :copy-full-path} {:label "Copy Require Path" :command :copy-require-path} {:label :separator} {:label "Show in Desktop" :icon "icons/32/Icons_S_14_linkarrow.png" :command :show-in-desktop} {:label "Referencing Files..." :command :referencing-files} {:label "Dependencies..." :command :dependencies} {:label :separator} {:label "New" :command :new-file :expand? true :icon "icons/64/Icons_29-AT-Unknown.png"} {:label "New Folder" :command :new-folder :icon "icons/32/Icons_01-Folder-closed.png"} {:label :separator} {:label "Cut" :command :cut} {:label "Copy" :command :copy} {:label "Paste" :command :paste} {:label "Delete" :command :delete :icon "icons/32/Icons_M_06_trash.png"} {:label :separator} {:label "Rename..." :command :rename} {:label :separator :id ::context-menu-end}]) (def fixed-resource-paths #{"/" "/game.project"}) (defn deletable-resource? [x] (and (satisfies? resource/Resource x) (not (resource/read-only? x)) (not (fixed-resource-paths (resource/proj-path x))))) (defn- roots [resources] (let [resources (into {} (map (fn [resource] [(->path (resource/proj-path resource)) resource]) resources)) roots (loop [paths (keys resources) roots []] (if-let [^Path path (first paths)] (let [roots (if (empty? (filter (fn [^Path p] (.startsWith path p)) roots)) (conj roots path) roots)] (recur (rest paths) roots)) roots))] (mapv #(resources %) roots))) (defn- temp-resource-file! [^File dir resource] (let [target (File. dir (resource/resource-name resource))] (if (= :file (resource/source-type resource)) (with-open [in (io/input-stream resource) out (io/output-stream target)] (io/copy in out)) (do (fs/create-directories! target) (doseq [c (:children resource)] (temp-resource-file! target c)))) target)) (defn- fileify-resources! [resources] (let [dnd-directory (fs/create-temp-directory! "asset-dnd")] (mapv (fn [r] (if (resource/file-resource? r) (io/file r) (temp-resource-file! dnd-directory r))) resources))) (defn delete [resources] (when (not (empty? resources)) (let [workspace (resource/workspace (first resources))] (doseq [resource resources] (let [f (File. (resource/abs-path resource))] (fs/delete! f {:fail :silently}))) (workspace/resource-sync! workspace)))) (defn- copy [files] (let [cb (Clipboard/getSystemClipboard) content (ClipboardContent.)] (.putFiles content files) (.setContent cb content))) (handler/defhandler :copy :asset-browser (enabled? [selection] (not (empty? selection))) (run [selection] (copy (-> selection roots fileify-resources!)))) (defn- select-resource! ([asset-browser resource] (select-resource! asset-browser resource nil)) ([asset-browser resource {:keys [scroll?] :or {scroll? false} :as opts}] ;; This is a hack! ;; The reason is that the FileResource 'next' fetched prior to the deletion ;; may have changed after the deletion, due to the 'children' field in the record. ;; This is why we can't use ui/select! directly, but do our own implementation based on path. (let [^TreeView tree-view (g/node-value asset-browser :tree-view) tree-items (ui/tree-item-seq (.getRoot tree-view)) path (resource/resource->proj-path resource)] (when-let [tree-item (some (fn [^TreeItem tree-item] (and (= path (resource/resource->proj-path (.getValue tree-item))) tree-item)) tree-items)] (doto (.getSelectionModel tree-view) (.clearSelection) (.select tree-item)) (when scroll? (ui/scroll-to-item! tree-view tree-item)))))) (defn delete? [resources] (and (disk-availability/available?) (seq resources) (every? deletable-resource? resources))) (handler/defhandler :cut :asset-browser (enabled? [selection] (delete? selection)) (run [selection selection-provider asset-browser] (let [next (-> (handler/succeeding-selection selection-provider) (handler/adapt-single resource/Resource)) cut-files-directory (fs/create-temp-directory! "asset-cut")] (copy (mapv #(temp-resource-file! cut-files-directory %) (roots selection))) (delete selection) (when next (select-resource! asset-browser next))))) (defn- unique [^File original exists-fn name-fn] (let [original-basename (FilenameUtils/getBaseName (.getAbsolutePath original))] (loop [^File f original] (if (exists-fn f) (let [path (.getAbsolutePath f) ext (FilenameUtils/getExtension path) new-path (str (FilenameUtils/getFullPath path) (name-fn original-basename (FilenameUtils/getBaseName path)) (when (seq ext) (str "." ext)))] (recur (File. new-path))) f)))) (defn- ensure-unique-dest-files [name-fn src-dest-pairs] (loop [[[src dest :as pair] & rest] src-dest-pairs new-names #{} ret []] (if pair (let [new-dest (unique dest #(or (.exists ^File %) (new-names %)) name-fn)] (recur rest (conj new-names new-dest) (conj ret [src new-dest]))) ret))) (defn- numbering-name-fn [original-basename basename] (let [suffix (string/replace basename original-basename "")] (if (.isEmpty suffix) (str original-basename "1") (str original-basename (inc (bigint suffix)))))) (defmulti resolve-conflicts (fn [strategy src-dest-pairs] strategy)) (defmethod resolve-conflicts :overwrite [_ src-dest-pairs] src-dest-pairs) (defmethod resolve-conflicts :rename [_ src-dest-pairs] (ensure-unique-dest-files numbering-name-fn src-dest-pairs)) (defn- resolve-any-conflicts [src-dest-pairs] (let [files-by-existence (group-by (fn [[src ^File dest]] (.exists dest)) src-dest-pairs) conflicts (get files-by-existence true) non-conflicts (get files-by-existence false [])] (if (seq conflicts) (when-let [strategy (dialogs/make-resolve-file-conflicts-dialog conflicts)] (into non-conflicts (resolve-conflicts strategy conflicts))) non-conflicts))) (defn- select-files! [workspace tree-view files] (let [selected-paths (mapv (partial resource/file->proj-path (workspace/project-path workspace)) files)] (ui/user-data! tree-view ::pending-selection selected-paths))) (defn- reserved-project-file [^File project-path ^File f] (resource-watch/reserved-proj-path? project-path (resource/file->proj-path project-path f))) (defn- illegal-copy-move-pairs [^File project-path prospect-pairs] (seq (filter (comp (partial reserved-project-file project-path) second) prospect-pairs))) (defn allow-resource-move? "Returns true if it is legal to move all the supplied source files to the specified target resource. Disallows moves that would place a parent below one of its own children, moves to a readonly destination, moves to the same path the file already resides in, and moves to reserved directories." [tgt-resource src-files] (and (disk-availability/available?) (not (resource/read-only? tgt-resource)) (let [^Path tgt-path (-> tgt-resource resource/abs-path File. fs/to-folder .getAbsolutePath ->path) src-paths (map (fn [^File f] (-> f .getAbsolutePath ->path)) src-files) descendant (some (fn [^Path p] (or (.equals tgt-path (.getParent p)) (.startsWith tgt-path p))) src-paths) ;; Below is a bit of a hack to only perform the reserved paths check if the target ;; is the project root. possibly-reserved-tgt-files (when (= (resource/proj-path tgt-resource) "/") (map #(.toFile (.resolve tgt-path (.getName ^File %))) src-files)) project-path (workspace/project-path (resource/workspace tgt-resource))] (and (nil? descendant) (nil? (some (partial reserved-project-file project-path) possibly-reserved-tgt-files)))))) (defn paste? [files-on-clipboard? target-resources] (and files-on-clipboard? (disk-availability/available?) (= 1 (count target-resources)) (not (resource/read-only? (first target-resources))))) (defn paste! [workspace target-resource src-files select-files!] (let [^File tgt-dir (reduce (fn [^File tgt ^File src] (if (= tgt src) (.getParentFile ^File tgt) tgt)) (fs/to-folder (File. (resource/abs-path target-resource))) src-files) prospect-pairs (map (fn [^File f] [f (File. tgt-dir (FilenameUtils/getName (.toString f)))]) src-files) project-path (workspace/project-path workspace)] (if-let [illegal (illegal-copy-move-pairs project-path prospect-pairs)] (dialogs/make-info-dialog {:title "Cannot Paste" :icon :icon/triangle-error :header "There are reserved target directories" :content (str "Following target directories are reserved:\n" (string/join "\n" (map (comp (partial resource/file->proj-path project-path) second) illegal)))}) (let [pairs (ensure-unique-dest-files (fn [_ basename] (str basename "_copy")) prospect-pairs)] (doseq [[^File src-file ^File tgt-file] pairs] (fs/copy! src-file tgt-file {:target :merge})) (select-files! (mapv second pairs)) (workspace/resource-sync! workspace))))) (handler/defhandler :paste :asset-browser (enabled? [selection] (paste? (.hasFiles (Clipboard/getSystemClipboard)) selection)) (run [selection workspace asset-browser] (let [tree-view (g/node-value asset-browser :tree-view) resource (first selection) src-files (.getFiles (Clipboard/getSystemClipboard))] (paste! workspace resource src-files (partial select-files! workspace tree-view))))) (defn- moved-files [^File src-file ^File dest-file files] (let [src-path (.toPath src-file) dest-path (.toPath dest-file)] (mapv (fn [^File f] ;; (.relativize "foo" "foo") == "" so a plain file rename foo.clj -> bar.clj call of ;; of (moved-files "foo.clj" "bar.clj" ["foo.clj"]) will (.resolve "bar.clj" "") == "bar.clj" ;; just as we want. (let [dest-file (.toFile (.resolve dest-path (.relativize src-path (.toPath f))))] [f dest-file])) files))) (defn rename [resource ^String new-name] (assert (and new-name (not (string/blank? new-name)))) (let [workspace (resource/workspace resource) src-file (io/file resource) dest-file (File. (.getParent src-file) new-name) project-directory-file (workspace/project-path workspace) dest-proj-path (resource/file->proj-path project-directory-file dest-file)] (when-not (resource-watch/reserved-proj-path? project-directory-file dest-proj-path) (let [[[^File src-file ^File dest-file]] ;; plain case change causes irrelevant conflict on case insensitive fs ;; fs/move handles this, no need to resolve (if (fs/same-file? src-file dest-file) [[src-file dest-file]] (resolve-any-conflicts [[src-file dest-file]]))] (when dest-file (let [src-files (doall (file-seq src-file))] (fs/move! src-file dest-file) (workspace/resource-sync! workspace (moved-files src-file dest-file src-files)))))))) (defn rename? [resources] (and (disk-availability/available?) (= 1 (count resources)) (not (resource/read-only? (first resources))) (not (fixed-resource-paths (resource/resource->proj-path (first resources)))))) (defn validate-new-resource-name [^File project-directory-file parent-path new-name] (let [prospect-path (str parent-path "/" new-name)] (when (resource-watch/reserved-proj-path? project-directory-file prospect-path) (format "The name %s is reserved" new-name)))) (handler/defhandler :rename :asset-browser (enabled? [selection] (rename? selection)) (run [selection workspace] (let [resource (first selection) dir? (= :folder (resource/source-type resource)) extension (resource/ext resource) name (if dir? (resource/resource-name resource) (if (seq extension) (string/replace (resource/resource-name resource) (re-pattern (str "\\." extension "$")) "") (resource/resource-name resource))) parent-path (resource/parent-proj-path (resource/proj-path resource)) project-directory-file (workspace/project-path workspace) options {:title (if dir? "Rename Folder" "Rename File") :label (if dir? "New Folder Name" "New File Name") :sanitize (if dir? dialogs/sanitize-folder-name (partial dialogs/sanitize-file-name extension)) :validate (partial validate-new-resource-name project-directory-file parent-path)} new-name (dialogs/make-rename-dialog name options)] (when-let [sane-new-name (some-> new-name not-empty)] (rename resource sane-new-name))))) (handler/defhandler :delete :asset-browser (enabled? [selection] (delete? selection)) (run [selection asset-browser selection-provider] (let [next (-> (handler/succeeding-selection selection-provider) (handler/adapt-single resource/Resource))] (when (if (= 1 (count selection)) (dialogs/make-confirmation-dialog {:title "Delete File?" :icon :icon/circle-question :header (format "Are you sure you want to delete %s?" (resource/resource-name (first selection))) :buttons [{:text "Cancel" :cancel-button true :default-button true :result false} {:text "Delete" :variant :danger :result true}]}) (dialogs/make-info-dialog {:title "Delete Files?" :icon :icon/circle-question :header "Are you sure you want to delete these files?" :content {:text (str "You are about to delete:\n" (->> selection (map #(str "\u00A0\u00A0\u2022\u00A0" (resource/resource-name %))) (string/join "\n")))} :buttons [{:text "Cancel" :cancel-button true :default-button true :result false} {:text "Delete" :variant :danger :result true}]})) (when (and (delete selection) next) (select-resource! asset-browser next)))))) (handler/defhandler :new-file :global (label [user-data] (if-not user-data "New..." (let [rt (:resource-type user-data)] (or (:label rt) (:ext rt))))) (active? [selection selection-context] (or (= :global selection-context) (and (= :asset-browser selection-context) (= (count selection) 1) (not= nil (some-> (handler/adapt-single selection resource/Resource) resource/abs-path))))) (enabled? [] (disk-availability/available?)) (run [selection user-data asset-browser app-view prefs workspace project] (let [project-path (workspace/project-path workspace) base-folder (-> (or (some-> (handler/adapt-every selection resource/Resource) first resource/abs-path (File.)) project-path) fs/to-folder) rt (:resource-type user-data)] (when-let [desired-file (dialogs/make-new-file-dialog project-path base-folder (or (:label rt) (:ext rt)) (:ext rt))] (when-let [[[_ new-file]] (resolve-any-conflicts [[nil desired-file]])] (spit new-file (workspace/template workspace rt)) (workspace/resource-sync! workspace) (let [resource-map (g/node-value workspace :resource-map) new-resource-path (resource/file->proj-path project-path new-file) resource (resource-map new-resource-path)] (app-view/open-resource app-view prefs workspace project resource) (select-resource! asset-browser resource)))))) (options [workspace selection user-data] (when (not user-data) (let [resource-types (filter (fn [rt] (workspace/template workspace rt)) (workspace/get-resource-types workspace))] (sort-by (fn [rt] (string/lower-case (:label rt))) (map (fn [res-type] {:label (or (:label res-type) (:ext res-type)) :icon (:icon res-type) :style (resource/ext-style-classes (:ext res-type)) :command :new-file :user-data {:resource-type res-type}}) resource-types)))))) (defn- resolve-sub-folder [^File base-folder ^String new-folder-name] (.toFile (.resolve (.toPath base-folder) new-folder-name))) (defn validate-new-folder-name [^File project-directory-file parent-path new-name] (let [prospect-path (str parent-path "/" new-name)] (when (resource-watch/reserved-proj-path? project-directory-file prospect-path) (format "The name %s is reserved" new-name)))) (defn new-folder? [resources] (and (disk-availability/available?) (= (count resources) 1) (not (resource/read-only? (first resources))) (not= nil (resource/abs-path (first resources))))) (handler/defhandler :new-folder :asset-browser (enabled? [selection] (new-folder? selection)) (run [selection workspace asset-browser] (let [parent-resource (first selection) parent-path (resource/proj-path parent-resource) parent-path (if (= parent-path "/") "" parent-path) ; special case because the project root dir ends in / base-folder (fs/to-folder (File. (resource/abs-path parent-resource))) project-directory-file (workspace/project-path workspace) options {:validate (partial validate-new-folder-name project-directory-file parent-path)}] (when-let [new-folder-name (dialogs/make-new-folder-dialog base-folder options)] (let [^File folder (resolve-sub-folder base-folder new-folder-name)] (do (fs/create-directories! folder) (workspace/resource-sync! workspace) (select-resource! asset-browser (workspace/file-resource workspace folder)))))))) (defn- selected-or-active-resource [selection active-resource] (or (handler/adapt-single selection resource/Resource) active-resource)) (handler/defhandler :show-in-asset-browser :global (active? [active-resource selection] (selected-or-active-resource selection active-resource)) (enabled? [active-resource selection] (when-let [r (selected-or-active-resource selection active-resource)] (resource/exists? r))) (run [active-resource asset-browser selection main-stage] (when-let [r (selected-or-active-resource selection active-resource)] (app-view/show-asset-browser! (.getScene ^Stage main-stage)) (select-resource! asset-browser r {:scroll? true})))) (defn- item->path [^TreeItem item] (-> item (.getValue) (resource/proj-path))) (defn- sync-tree! [old-root new-root] (let [item-seq (ui/tree-item-seq old-root) expanded (zipmap (map item->path item-seq) (map #(.isExpanded ^TreeItem %) item-seq))] (doseq [^TreeItem item (ui/tree-item-seq new-root)] (when (get expanded (item->path item)) (.setExpanded item true)))) new-root) (g/defnk produce-tree-root [^TreeView raw-tree-view resource-tree] (let [old-root (.getRoot raw-tree-view) new-root (tree-item resource-tree)] (when new-root (sync-tree! old-root new-root) (.setExpanded new-root true) new-root))) (defn- auto-expand [items selected-paths] (not-every? false? (map (fn [^TreeItem item] (let [path (item->path item) selected (boolean (selected-paths path)) expanded (auto-expand (.getChildren item) selected-paths)] (when expanded (.setExpanded item expanded)) (or selected expanded))) items))) (defn- sync-selection! [^TreeView tree-view selected-paths] (let [root (.getRoot tree-view) selection-model (.getSelectionModel tree-view)] (.clearSelection selection-model) (when (and root (seq selected-paths)) (let [selected-paths (set selected-paths)] (auto-expand (.getChildren root) selected-paths) (let [count (.getExpandedItemCount tree-view) selected-indices (filter #(selected-paths (item->path (.getTreeItem tree-view %))) (range count))] (when (not (empty? selected-indices)) (ui/select-indices! tree-view selected-indices)) (when-some [first-item (first (.getSelectedItems selection-model))] (ui/scroll-to-item! tree-view first-item))))))) (defn- update-tree-view-selection! [^TreeView tree-view selected-paths] (sync-selection! tree-view selected-paths) tree-view) (defn- update-tree-view-root! [^TreeView tree-view ^TreeItem root selected-paths] (when root (.setExpanded root true) (.setRoot tree-view root)) (sync-selection! tree-view selected-paths) tree-view) (defn track-active-tab? [prefs] (prefs/get-prefs prefs "asset-browser-track-active-tab?" false)) (g/defnk produce-tree-view [^TreeView raw-tree-view ^TreeItem root active-resource prefs] (let [selected-paths (or (ui/user-data raw-tree-view ::pending-selection) (when (and (track-active-tab? prefs) active-resource) [(resource/proj-path active-resource)]) (mapv resource/proj-path (ui/selection raw-tree-view)))] (ui/user-data! raw-tree-view ::pending-selection nil) (cond ;; different roots? (not (identical? (.getRoot raw-tree-view) root)) (update-tree-view-root! raw-tree-view root selected-paths) ;; same root, different selection? (not (= (set selected-paths) (set (map resource/proj-path (ui/selection raw-tree-view))))) (update-tree-view-selection! raw-tree-view selected-paths) :else raw-tree-view))) (defn- drag-detected [^MouseEvent e selection] (let [resources (roots selection) files (fileify-resources! resources) ;; Note: It would seem we should use the TransferMode/COPY_OR_MOVE mode ;; here in order to support making copies of non-readonly files, but ;; that results in every drag operation becoming a copy on macOS due to ;; https://bugs.openjdk.java.net/browse/JDK-8148025 mode (if (empty? (filter resource/read-only? resources)) TransferMode/MOVE TransferMode/COPY) db (.startDragAndDrop ^Node (.getSource e) (into-array TransferMode [mode])) content (ClipboardContent.)] (when (= 1 (count resources)) (.setDragView db (icons/get-image (workspace/resource-icon (first resources)) 16) 0 16)) (.putFiles content files) (.setContent db content) (.consume e))) (defn- target [^Node node] (when node (if (instance? TreeCell node) node (target (.getParent node))))) (defn- drag-entered [^DragEvent e] (let [^TreeCell cell (target (.getTarget e))] (when (and cell (not (.isEmpty cell))) (let [resource (.getValue (.getTreeItem cell))] (when (and (= :folder (resource/source-type resource)) (not (resource/read-only? resource))) (ui/add-style! cell "drop-target")))))) (defn- drag-exited [^DragEvent e] (when-let [cell (target (.getTarget e))] (ui/remove-style! cell "drop-target"))) (defn- drag-over [^DragEvent e] (let [db (.getDragboard e)] (when-let [^TreeCell cell (target (.getTarget e))] (when (and (not (.isEmpty cell)) (.hasFiles db)) ;; Auto scrolling (let [view (.getTreeView cell) view-y (.getY (.sceneToLocal view (.getSceneX e) (.getSceneY e))) height (.getHeight (.getBoundsInLocal view))] (when (< view-y 15) (.scrollTo view (dec (.getIndex cell)))) (when (> view-y (- height 15)) (.scrollTo view (inc (.getIndex cell))))) (let [tgt-resource (-> cell (.getTreeItem) (.getValue))] (when (allow-resource-move? tgt-resource (.getFiles db)) ;; Allow move only if the drag source was also the tree view. (if (= (.getTreeView cell) (.getGestureSource e)) (.acceptTransferModes e TransferMode/COPY_OR_MOVE) (.acceptTransferModes e (into-array TransferMode [TransferMode/COPY]))) (.consume e))))))) (defn- drag-move-files [dragged-pairs] (into [] (mapcat (fn [[src tgt]] (let [src-files (doall (file-seq src))] (fs/move! src tgt) (moved-files src tgt src-files))) dragged-pairs))) (defn- drag-copy-files [dragged-pairs] (doseq [[^File src ^File tgt] dragged-pairs] (fs/copy! src tgt {:fail :silently})) []) (defn- fixed-move-source [^File project-path [^File src ^File _tgt]] (contains? fixed-resource-paths (resource/file->proj-path project-path src))) (defn drop-files! [workspace dragged-pairs move?] (let [project-path (workspace/project-path workspace)] (when (seq dragged-pairs) (let [moved (if move? (let [{move-pairs false copy-pairs true} (group-by (partial fixed-move-source project-path) dragged-pairs)] (drag-copy-files copy-pairs) (drag-move-files move-pairs)) (drag-copy-files dragged-pairs))] moved)))) (defn- drag-dropped [^DragEvent e] (let [db (.getDragboard e)] (when (.hasFiles db) (let [target (-> e (.getTarget) ^TreeCell (target)) tree-view (.getTreeView target) resource (-> target (.getTreeItem) (.getValue)) ^Path tgt-dir-path (.toPath (fs/to-folder (File. (resource/abs-path resource)))) move? (and (= (.getGestureSource e) tree-view) (= (.getTransferMode e) TransferMode/MOVE)) pairs (->> (.getFiles db) (mapv (fn [^File f] [f (.toFile (.resolve tgt-dir-path (.getName f)))])) (resolve-any-conflicts) (vec)) workspace (resource/workspace resource) project-path (workspace/project-path workspace)] (when (seq pairs) (let [moved (drop-files! workspace pairs move?)] (select-files! workspace tree-view (mapv second pairs)) (workspace/resource-sync! workspace moved)))))) (.setDropCompleted e true) (.consume e)) (defrecord SelectionProvider [asset-browser] handler/SelectionProvider (selection [this] (ui/selection (g/node-value asset-browser :tree-view))) (succeeding-selection [this] (let [tree-view (g/node-value asset-browser :tree-view) path-fn (comp #(string/split % #"/") item->path)] (->> (ui/selection-root-items tree-view path-fn item->path) (ui/succeeding-selection tree-view)))) (alt-selection [this] [])) (defn- setup-asset-browser [asset-browser workspace ^TreeView tree-view] (.setSelectionMode (.getSelectionModel tree-view) SelectionMode/MULTIPLE) (let [selection-provider (SelectionProvider. asset-browser) over-handler (ui/event-handler e (drag-over e)) dropped-handler (ui/event-handler e (error-reporting/catch-all! (drag-dropped e))) detected-handler (ui/event-handler e (drag-detected e (handler/selection selection-provider))) entered-handler (ui/event-handler e (drag-entered e)) exited-handler (ui/event-handler e (drag-exited e))] (doto tree-view (ui/customize-tree-view! {:double-click-expand? true}) (ui/bind-double-click! :open) (ui/bind-key-commands! {"Enter" :open "F2" :rename}) (.setOnDragDetected detected-handler) (ui/cell-factory! (fn [resource] (if (nil? resource) {} {:text (resource/resource-name resource) :icon (workspace/resource-icon resource) :style (resource/style-classes resource) :over-handler over-handler :dropped-handler dropped-handler :entered-handler entered-handler :exited-handler exited-handler}))) (ui/register-context-menu ::resource-menu) (ui/context! :asset-browser {:workspace workspace :asset-browser asset-browser} selection-provider)))) (g/defnode AssetBrowser (property raw-tree-view TreeView) (property prefs g/Any) (input resource-tree FileResource) (input active-resource resource/Resource :substitute nil) (output root TreeItem :cached produce-tree-root) (output tree-view TreeView :cached produce-tree-view)) (defn make-asset-browser [graph workspace tree-view prefs] (let [asset-browser (first (g/tx-nodes-added (g/transact (g/make-nodes graph [asset-browser [AssetBrowser :raw-tree-view tree-view :prefs prefs]] (g/connect workspace :resource-tree asset-browser :resource-tree)))))] (setup-asset-browser asset-browser workspace tree-view) asset-browser))
35039
;; 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.asset-browser (:require [clojure.java.io :as io] [clojure.string :as string] [dynamo.graph :as g] [editor.error-reporting :as error-reporting] [editor.fs :as fs] [editor.fxui :as fxui] [editor.handler :as handler] [editor.icons :as icons] [editor.ui :as ui] [editor.prefs :as prefs] [editor.resource :as resource] [editor.resource-watch :as resource-watch] [editor.workspace :as workspace] [editor.dialogs :as dialogs] [editor.disk-availability :as disk-availability] [editor.app-view :as app-view]) (:import [com.defold.editor Start] [editor.resource FileResource] [javafx.application Platform] [javafx.collections FXCollections ObservableList] [javafx.embed.swing SwingFXUtils] [javafx.event ActionEvent Event EventHandler] [javafx.fxml FXMLLoader] [javafx.geometry Insets] [javafx.scene.input Clipboard ClipboardContent] [javafx.scene.input DragEvent TransferMode MouseEvent] [javafx.scene Scene Node Parent] [javafx.scene.control Button ColorPicker Label TextField TitledPane TextArea TreeItem TreeView Menu MenuItem SeparatorMenuItem MenuBar Tab ProgressBar ContextMenu SelectionMode] [javafx.scene.image Image ImageView WritableImage PixelWriter] [javafx.scene.input MouseEvent KeyCombination ContextMenuEvent] [javafx.scene.layout AnchorPane GridPane StackPane HBox Priority] [javafx.scene.paint Color] [javafx.stage Stage FileChooser] [javafx.util Callback] [java.io File] [java.nio.file Path Paths] [java.util.prefs Preferences] [com.jogamp.opengl GL GL2 GLContext GLProfile GLDrawableFactory GLCapabilities] [org.apache.commons.io FilenameUtils] [com.defold.control TreeCell])) (set! *warn-on-reflection* true) (declare tree-item) (def ^:private empty-string-array (into-array String [])) (defn- ->path [s] (Paths/get s empty-string-array)) ; TreeItem creator (defn- ^ObservableList list-children [parent] (let [children (:children parent) items (->> (:children parent) (remove resource/internal?) (map tree-item) (into-array TreeItem))] (if (empty? children) (FXCollections/emptyObservableList) (doto (FXCollections/observableArrayList) (.addAll ^"[Ljavafx.scene.control.TreeItem;" items))))) ; NOTE: Without caching stack-overflow... WHY? (defn tree-item ^TreeItem [parent] (let [cached (atom false)] (proxy [TreeItem] [parent] (isLeaf [] (or (not= :folder (resource/source-type (.getValue ^TreeItem this))) (empty? (:children (.getValue ^TreeItem this))))) (getChildren [] (let [this ^TreeItem this ^ObservableList children (proxy-super getChildren)] (when-not @cached (reset! cached true) (.setAll children (list-children (.getValue this)))) children))))) (handler/register-menu! ::resource-menu [{:label "Open" :icon "icons/32/Icons_S_14_linkarrow.png" :command :open} {:label "Open As" :icon "icons/32/Icons_S_14_linkarrow.png" :command :open-as} {:label :separator} {:label "Copy Project Path" :command :copy-project-path} {:label "Copy Full Path" :command :copy-full-path} {:label "Copy Require Path" :command :copy-require-path} {:label :separator} {:label "Show in Desktop" :icon "icons/32/Icons_S_14_linkarrow.png" :command :show-in-desktop} {:label "Referencing Files..." :command :referencing-files} {:label "Dependencies..." :command :dependencies} {:label :separator} {:label "New" :command :new-file :expand? true :icon "icons/64/Icons_29-AT-Unknown.png"} {:label "New Folder" :command :new-folder :icon "icons/32/Icons_01-Folder-closed.png"} {:label :separator} {:label "Cut" :command :cut} {:label "Copy" :command :copy} {:label "Paste" :command :paste} {:label "Delete" :command :delete :icon "icons/32/Icons_M_06_trash.png"} {:label :separator} {:label "Rename..." :command :rename} {:label :separator :id ::context-menu-end}]) (def fixed-resource-paths #{"/" "/game.project"}) (defn deletable-resource? [x] (and (satisfies? resource/Resource x) (not (resource/read-only? x)) (not (fixed-resource-paths (resource/proj-path x))))) (defn- roots [resources] (let [resources (into {} (map (fn [resource] [(->path (resource/proj-path resource)) resource]) resources)) roots (loop [paths (keys resources) roots []] (if-let [^Path path (first paths)] (let [roots (if (empty? (filter (fn [^Path p] (.startsWith path p)) roots)) (conj roots path) roots)] (recur (rest paths) roots)) roots))] (mapv #(resources %) roots))) (defn- temp-resource-file! [^File dir resource] (let [target (File. dir (resource/resource-name resource))] (if (= :file (resource/source-type resource)) (with-open [in (io/input-stream resource) out (io/output-stream target)] (io/copy in out)) (do (fs/create-directories! target) (doseq [c (:children resource)] (temp-resource-file! target c)))) target)) (defn- fileify-resources! [resources] (let [dnd-directory (fs/create-temp-directory! "asset-dnd")] (mapv (fn [r] (if (resource/file-resource? r) (io/file r) (temp-resource-file! dnd-directory r))) resources))) (defn delete [resources] (when (not (empty? resources)) (let [workspace (resource/workspace (first resources))] (doseq [resource resources] (let [f (File. (resource/abs-path resource))] (fs/delete! f {:fail :silently}))) (workspace/resource-sync! workspace)))) (defn- copy [files] (let [cb (Clipboard/getSystemClipboard) content (ClipboardContent.)] (.putFiles content files) (.setContent cb content))) (handler/defhandler :copy :asset-browser (enabled? [selection] (not (empty? selection))) (run [selection] (copy (-> selection roots fileify-resources!)))) (defn- select-resource! ([asset-browser resource] (select-resource! asset-browser resource nil)) ([asset-browser resource {:keys [scroll?] :or {scroll? false} :as opts}] ;; This is a hack! ;; The reason is that the FileResource 'next' fetched prior to the deletion ;; may have changed after the deletion, due to the 'children' field in the record. ;; This is why we can't use ui/select! directly, but do our own implementation based on path. (let [^TreeView tree-view (g/node-value asset-browser :tree-view) tree-items (ui/tree-item-seq (.getRoot tree-view)) path (resource/resource->proj-path resource)] (when-let [tree-item (some (fn [^TreeItem tree-item] (and (= path (resource/resource->proj-path (.getValue tree-item))) tree-item)) tree-items)] (doto (.getSelectionModel tree-view) (.clearSelection) (.select tree-item)) (when scroll? (ui/scroll-to-item! tree-view tree-item)))))) (defn delete? [resources] (and (disk-availability/available?) (seq resources) (every? deletable-resource? resources))) (handler/defhandler :cut :asset-browser (enabled? [selection] (delete? selection)) (run [selection selection-provider asset-browser] (let [next (-> (handler/succeeding-selection selection-provider) (handler/adapt-single resource/Resource)) cut-files-directory (fs/create-temp-directory! "asset-cut")] (copy (mapv #(temp-resource-file! cut-files-directory %) (roots selection))) (delete selection) (when next (select-resource! asset-browser next))))) (defn- unique [^File original exists-fn name-fn] (let [original-basename (FilenameUtils/getBaseName (.getAbsolutePath original))] (loop [^File f original] (if (exists-fn f) (let [path (.getAbsolutePath f) ext (FilenameUtils/getExtension path) new-path (str (FilenameUtils/getFullPath path) (name-fn original-basename (FilenameUtils/getBaseName path)) (when (seq ext) (str "." ext)))] (recur (File. new-path))) f)))) (defn- ensure-unique-dest-files [name-fn src-dest-pairs] (loop [[[src dest :as pair] & rest] src-dest-pairs new-names #{} ret []] (if pair (let [new-dest (unique dest #(or (.exists ^File %) (new-names %)) name-fn)] (recur rest (conj new-names new-dest) (conj ret [src new-dest]))) ret))) (defn- numbering-name-fn [original-basename basename] (let [suffix (string/replace basename original-basename "")] (if (.isEmpty suffix) (str original-basename "1") (str original-basename (inc (bigint suffix)))))) (defmulti resolve-conflicts (fn [strategy src-dest-pairs] strategy)) (defmethod resolve-conflicts :overwrite [_ src-dest-pairs] src-dest-pairs) (defmethod resolve-conflicts :rename [_ src-dest-pairs] (ensure-unique-dest-files numbering-name-fn src-dest-pairs)) (defn- resolve-any-conflicts [src-dest-pairs] (let [files-by-existence (group-by (fn [[src ^File dest]] (.exists dest)) src-dest-pairs) conflicts (get files-by-existence true) non-conflicts (get files-by-existence false [])] (if (seq conflicts) (when-let [strategy (dialogs/make-resolve-file-conflicts-dialog conflicts)] (into non-conflicts (resolve-conflicts strategy conflicts))) non-conflicts))) (defn- select-files! [workspace tree-view files] (let [selected-paths (mapv (partial resource/file->proj-path (workspace/project-path workspace)) files)] (ui/user-data! tree-view ::pending-selection selected-paths))) (defn- reserved-project-file [^File project-path ^File f] (resource-watch/reserved-proj-path? project-path (resource/file->proj-path project-path f))) (defn- illegal-copy-move-pairs [^File project-path prospect-pairs] (seq (filter (comp (partial reserved-project-file project-path) second) prospect-pairs))) (defn allow-resource-move? "Returns true if it is legal to move all the supplied source files to the specified target resource. Disallows moves that would place a parent below one of its own children, moves to a readonly destination, moves to the same path the file already resides in, and moves to reserved directories." [tgt-resource src-files] (and (disk-availability/available?) (not (resource/read-only? tgt-resource)) (let [^Path tgt-path (-> tgt-resource resource/abs-path File. fs/to-folder .getAbsolutePath ->path) src-paths (map (fn [^File f] (-> f .getAbsolutePath ->path)) src-files) descendant (some (fn [^Path p] (or (.equals tgt-path (.getParent p)) (.startsWith tgt-path p))) src-paths) ;; Below is a bit of a hack to only perform the reserved paths check if the target ;; is the project root. possibly-reserved-tgt-files (when (= (resource/proj-path tgt-resource) "/") (map #(.toFile (.resolve tgt-path (.getName ^File %))) src-files)) project-path (workspace/project-path (resource/workspace tgt-resource))] (and (nil? descendant) (nil? (some (partial reserved-project-file project-path) possibly-reserved-tgt-files)))))) (defn paste? [files-on-clipboard? target-resources] (and files-on-clipboard? (disk-availability/available?) (= 1 (count target-resources)) (not (resource/read-only? (first target-resources))))) (defn paste! [workspace target-resource src-files select-files!] (let [^File tgt-dir (reduce (fn [^File tgt ^File src] (if (= tgt src) (.getParentFile ^File tgt) tgt)) (fs/to-folder (File. (resource/abs-path target-resource))) src-files) prospect-pairs (map (fn [^File f] [f (File. tgt-dir (FilenameUtils/getName (.toString f)))]) src-files) project-path (workspace/project-path workspace)] (if-let [illegal (illegal-copy-move-pairs project-path prospect-pairs)] (dialogs/make-info-dialog {:title "Cannot Paste" :icon :icon/triangle-error :header "There are reserved target directories" :content (str "Following target directories are reserved:\n" (string/join "\n" (map (comp (partial resource/file->proj-path project-path) second) illegal)))}) (let [pairs (ensure-unique-dest-files (fn [_ basename] (str basename "_copy")) prospect-pairs)] (doseq [[^File src-file ^File tgt-file] pairs] (fs/copy! src-file tgt-file {:target :merge})) (select-files! (mapv second pairs)) (workspace/resource-sync! workspace))))) (handler/defhandler :paste :asset-browser (enabled? [selection] (paste? (.hasFiles (Clipboard/getSystemClipboard)) selection)) (run [selection workspace asset-browser] (let [tree-view (g/node-value asset-browser :tree-view) resource (first selection) src-files (.getFiles (Clipboard/getSystemClipboard))] (paste! workspace resource src-files (partial select-files! workspace tree-view))))) (defn- moved-files [^File src-file ^File dest-file files] (let [src-path (.toPath src-file) dest-path (.toPath dest-file)] (mapv (fn [^File f] ;; (.relativize "foo" "foo") == "" so a plain file rename foo.clj -> bar.clj call of ;; of (moved-files "foo.clj" "bar.clj" ["foo.clj"]) will (.resolve "bar.clj" "") == "bar.clj" ;; just as we want. (let [dest-file (.toFile (.resolve dest-path (.relativize src-path (.toPath f))))] [f dest-file])) files))) (defn rename [resource ^String new-name] (assert (and new-name (not (string/blank? new-name)))) (let [workspace (resource/workspace resource) src-file (io/file resource) dest-file (File. (.getParent src-file) new-name) project-directory-file (workspace/project-path workspace) dest-proj-path (resource/file->proj-path project-directory-file dest-file)] (when-not (resource-watch/reserved-proj-path? project-directory-file dest-proj-path) (let [[[^File src-file ^File dest-file]] ;; plain case change causes irrelevant conflict on case insensitive fs ;; fs/move handles this, no need to resolve (if (fs/same-file? src-file dest-file) [[src-file dest-file]] (resolve-any-conflicts [[src-file dest-file]]))] (when dest-file (let [src-files (doall (file-seq src-file))] (fs/move! src-file dest-file) (workspace/resource-sync! workspace (moved-files src-file dest-file src-files)))))))) (defn rename? [resources] (and (disk-availability/available?) (= 1 (count resources)) (not (resource/read-only? (first resources))) (not (fixed-resource-paths (resource/resource->proj-path (first resources)))))) (defn validate-new-resource-name [^File project-directory-file parent-path new-name] (let [prospect-path (str parent-path "/" new-name)] (when (resource-watch/reserved-proj-path? project-directory-file prospect-path) (format "The name %s is reserved" new-name)))) (handler/defhandler :rename :asset-browser (enabled? [selection] (rename? selection)) (run [selection workspace] (let [resource (first selection) dir? (= :folder (resource/source-type resource)) extension (resource/ext resource) name (if dir? (resource/resource-name resource) (if (seq extension) (string/replace (resource/resource-name resource) (re-pattern (str "\\." extension "$")) "") (resource/resource-name resource))) parent-path (resource/parent-proj-path (resource/proj-path resource)) project-directory-file (workspace/project-path workspace) options {:title (if dir? "Rename Folder" "Rename File") :label (if dir? "New Folder Name" "New File Name") :sanitize (if dir? dialogs/sanitize-folder-name (partial dialogs/sanitize-file-name extension)) :validate (partial validate-new-resource-name project-directory-file parent-path)} new-name (dialogs/make-rename-dialog name options)] (when-let [sane-new-name (some-> new-name not-empty)] (rename resource sane-new-name))))) (handler/defhandler :delete :asset-browser (enabled? [selection] (delete? selection)) (run [selection asset-browser selection-provider] (let [next (-> (handler/succeeding-selection selection-provider) (handler/adapt-single resource/Resource))] (when (if (= 1 (count selection)) (dialogs/make-confirmation-dialog {:title "Delete File?" :icon :icon/circle-question :header (format "Are you sure you want to delete %s?" (resource/resource-name (first selection))) :buttons [{:text "Cancel" :cancel-button true :default-button true :result false} {:text "Delete" :variant :danger :result true}]}) (dialogs/make-info-dialog {:title "Delete Files?" :icon :icon/circle-question :header "Are you sure you want to delete these files?" :content {:text (str "You are about to delete:\n" (->> selection (map #(str "\u00A0\u00A0\u2022\u00A0" (resource/resource-name %))) (string/join "\n")))} :buttons [{:text "Cancel" :cancel-button true :default-button true :result false} {:text "Delete" :variant :danger :result true}]})) (when (and (delete selection) next) (select-resource! asset-browser next)))))) (handler/defhandler :new-file :global (label [user-data] (if-not user-data "New..." (let [rt (:resource-type user-data)] (or (:label rt) (:ext rt))))) (active? [selection selection-context] (or (= :global selection-context) (and (= :asset-browser selection-context) (= (count selection) 1) (not= nil (some-> (handler/adapt-single selection resource/Resource) resource/abs-path))))) (enabled? [] (disk-availability/available?)) (run [selection user-data asset-browser app-view prefs workspace project] (let [project-path (workspace/project-path workspace) base-folder (-> (or (some-> (handler/adapt-every selection resource/Resource) first resource/abs-path (File.)) project-path) fs/to-folder) rt (:resource-type user-data)] (when-let [desired-file (dialogs/make-new-file-dialog project-path base-folder (or (:label rt) (:ext rt)) (:ext rt))] (when-let [[[_ new-file]] (resolve-any-conflicts [[nil desired-file]])] (spit new-file (workspace/template workspace rt)) (workspace/resource-sync! workspace) (let [resource-map (g/node-value workspace :resource-map) new-resource-path (resource/file->proj-path project-path new-file) resource (resource-map new-resource-path)] (app-view/open-resource app-view prefs workspace project resource) (select-resource! asset-browser resource)))))) (options [workspace selection user-data] (when (not user-data) (let [resource-types (filter (fn [rt] (workspace/template workspace rt)) (workspace/get-resource-types workspace))] (sort-by (fn [rt] (string/lower-case (:label rt))) (map (fn [res-type] {:label (or (:label res-type) (:ext res-type)) :icon (:icon res-type) :style (resource/ext-style-classes (:ext res-type)) :command :new-file :user-data {:resource-type res-type}}) resource-types)))))) (defn- resolve-sub-folder [^File base-folder ^String new-folder-name] (.toFile (.resolve (.toPath base-folder) new-folder-name))) (defn validate-new-folder-name [^File project-directory-file parent-path new-name] (let [prospect-path (str parent-path "/" new-name)] (when (resource-watch/reserved-proj-path? project-directory-file prospect-path) (format "The name %s is reserved" new-name)))) (defn new-folder? [resources] (and (disk-availability/available?) (= (count resources) 1) (not (resource/read-only? (first resources))) (not= nil (resource/abs-path (first resources))))) (handler/defhandler :new-folder :asset-browser (enabled? [selection] (new-folder? selection)) (run [selection workspace asset-browser] (let [parent-resource (first selection) parent-path (resource/proj-path parent-resource) parent-path (if (= parent-path "/") "" parent-path) ; special case because the project root dir ends in / base-folder (fs/to-folder (File. (resource/abs-path parent-resource))) project-directory-file (workspace/project-path workspace) options {:validate (partial validate-new-folder-name project-directory-file parent-path)}] (when-let [new-folder-name (dialogs/make-new-folder-dialog base-folder options)] (let [^File folder (resolve-sub-folder base-folder new-folder-name)] (do (fs/create-directories! folder) (workspace/resource-sync! workspace) (select-resource! asset-browser (workspace/file-resource workspace folder)))))))) (defn- selected-or-active-resource [selection active-resource] (or (handler/adapt-single selection resource/Resource) active-resource)) (handler/defhandler :show-in-asset-browser :global (active? [active-resource selection] (selected-or-active-resource selection active-resource)) (enabled? [active-resource selection] (when-let [r (selected-or-active-resource selection active-resource)] (resource/exists? r))) (run [active-resource asset-browser selection main-stage] (when-let [r (selected-or-active-resource selection active-resource)] (app-view/show-asset-browser! (.getScene ^Stage main-stage)) (select-resource! asset-browser r {:scroll? true})))) (defn- item->path [^TreeItem item] (-> item (.getValue) (resource/proj-path))) (defn- sync-tree! [old-root new-root] (let [item-seq (ui/tree-item-seq old-root) expanded (zipmap (map item->path item-seq) (map #(.isExpanded ^TreeItem %) item-seq))] (doseq [^TreeItem item (ui/tree-item-seq new-root)] (when (get expanded (item->path item)) (.setExpanded item true)))) new-root) (g/defnk produce-tree-root [^TreeView raw-tree-view resource-tree] (let [old-root (.getRoot raw-tree-view) new-root (tree-item resource-tree)] (when new-root (sync-tree! old-root new-root) (.setExpanded new-root true) new-root))) (defn- auto-expand [items selected-paths] (not-every? false? (map (fn [^TreeItem item] (let [path (item->path item) selected (boolean (selected-paths path)) expanded (auto-expand (.getChildren item) selected-paths)] (when expanded (.setExpanded item expanded)) (or selected expanded))) items))) (defn- sync-selection! [^TreeView tree-view selected-paths] (let [root (.getRoot tree-view) selection-model (.getSelectionModel tree-view)] (.clearSelection selection-model) (when (and root (seq selected-paths)) (let [selected-paths (set selected-paths)] (auto-expand (.getChildren root) selected-paths) (let [count (.getExpandedItemCount tree-view) selected-indices (filter #(selected-paths (item->path (.getTreeItem tree-view %))) (range count))] (when (not (empty? selected-indices)) (ui/select-indices! tree-view selected-indices)) (when-some [first-item (first (.getSelectedItems selection-model))] (ui/scroll-to-item! tree-view first-item))))))) (defn- update-tree-view-selection! [^TreeView tree-view selected-paths] (sync-selection! tree-view selected-paths) tree-view) (defn- update-tree-view-root! [^TreeView tree-view ^TreeItem root selected-paths] (when root (.setExpanded root true) (.setRoot tree-view root)) (sync-selection! tree-view selected-paths) tree-view) (defn track-active-tab? [prefs] (prefs/get-prefs prefs "asset-browser-track-active-tab?" false)) (g/defnk produce-tree-view [^TreeView raw-tree-view ^TreeItem root active-resource prefs] (let [selected-paths (or (ui/user-data raw-tree-view ::pending-selection) (when (and (track-active-tab? prefs) active-resource) [(resource/proj-path active-resource)]) (mapv resource/proj-path (ui/selection raw-tree-view)))] (ui/user-data! raw-tree-view ::pending-selection nil) (cond ;; different roots? (not (identical? (.getRoot raw-tree-view) root)) (update-tree-view-root! raw-tree-view root selected-paths) ;; same root, different selection? (not (= (set selected-paths) (set (map resource/proj-path (ui/selection raw-tree-view))))) (update-tree-view-selection! raw-tree-view selected-paths) :else raw-tree-view))) (defn- drag-detected [^MouseEvent e selection] (let [resources (roots selection) files (fileify-resources! resources) ;; Note: It would seem we should use the TransferMode/COPY_OR_MOVE mode ;; here in order to support making copies of non-readonly files, but ;; that results in every drag operation becoming a copy on macOS due to ;; https://bugs.openjdk.java.net/browse/JDK-8148025 mode (if (empty? (filter resource/read-only? resources)) TransferMode/MOVE TransferMode/COPY) db (.startDragAndDrop ^Node (.getSource e) (into-array TransferMode [mode])) content (ClipboardContent.)] (when (= 1 (count resources)) (.setDragView db (icons/get-image (workspace/resource-icon (first resources)) 16) 0 16)) (.putFiles content files) (.setContent db content) (.consume e))) (defn- target [^Node node] (when node (if (instance? TreeCell node) node (target (.getParent node))))) (defn- drag-entered [^DragEvent e] (let [^TreeCell cell (target (.getTarget e))] (when (and cell (not (.isEmpty cell))) (let [resource (.getValue (.getTreeItem cell))] (when (and (= :folder (resource/source-type resource)) (not (resource/read-only? resource))) (ui/add-style! cell "drop-target")))))) (defn- drag-exited [^DragEvent e] (when-let [cell (target (.getTarget e))] (ui/remove-style! cell "drop-target"))) (defn- drag-over [^DragEvent e] (let [db (.getDragboard e)] (when-let [^TreeCell cell (target (.getTarget e))] (when (and (not (.isEmpty cell)) (.hasFiles db)) ;; Auto scrolling (let [view (.getTreeView cell) view-y (.getY (.sceneToLocal view (.getSceneX e) (.getSceneY e))) height (.getHeight (.getBoundsInLocal view))] (when (< view-y 15) (.scrollTo view (dec (.getIndex cell)))) (when (> view-y (- height 15)) (.scrollTo view (inc (.getIndex cell))))) (let [tgt-resource (-> cell (.getTreeItem) (.getValue))] (when (allow-resource-move? tgt-resource (.getFiles db)) ;; Allow move only if the drag source was also the tree view. (if (= (.getTreeView cell) (.getGestureSource e)) (.acceptTransferModes e TransferMode/COPY_OR_MOVE) (.acceptTransferModes e (into-array TransferMode [TransferMode/COPY]))) (.consume e))))))) (defn- drag-move-files [dragged-pairs] (into [] (mapcat (fn [[src tgt]] (let [src-files (doall (file-seq src))] (fs/move! src tgt) (moved-files src tgt src-files))) dragged-pairs))) (defn- drag-copy-files [dragged-pairs] (doseq [[^File src ^File tgt] dragged-pairs] (fs/copy! src tgt {:fail :silently})) []) (defn- fixed-move-source [^File project-path [^File src ^File _tgt]] (contains? fixed-resource-paths (resource/file->proj-path project-path src))) (defn drop-files! [workspace dragged-pairs move?] (let [project-path (workspace/project-path workspace)] (when (seq dragged-pairs) (let [moved (if move? (let [{move-pairs false copy-pairs true} (group-by (partial fixed-move-source project-path) dragged-pairs)] (drag-copy-files copy-pairs) (drag-move-files move-pairs)) (drag-copy-files dragged-pairs))] moved)))) (defn- drag-dropped [^DragEvent e] (let [db (.getDragboard e)] (when (.hasFiles db) (let [target (-> e (.getTarget) ^TreeCell (target)) tree-view (.getTreeView target) resource (-> target (.getTreeItem) (.getValue)) ^Path tgt-dir-path (.toPath (fs/to-folder (File. (resource/abs-path resource)))) move? (and (= (.getGestureSource e) tree-view) (= (.getTransferMode e) TransferMode/MOVE)) pairs (->> (.getFiles db) (mapv (fn [^File f] [f (.toFile (.resolve tgt-dir-path (.getName f)))])) (resolve-any-conflicts) (vec)) workspace (resource/workspace resource) project-path (workspace/project-path workspace)] (when (seq pairs) (let [moved (drop-files! workspace pairs move?)] (select-files! workspace tree-view (mapv second pairs)) (workspace/resource-sync! workspace moved)))))) (.setDropCompleted e true) (.consume e)) (defrecord SelectionProvider [asset-browser] handler/SelectionProvider (selection [this] (ui/selection (g/node-value asset-browser :tree-view))) (succeeding-selection [this] (let [tree-view (g/node-value asset-browser :tree-view) path-fn (comp #(string/split % #"/") item->path)] (->> (ui/selection-root-items tree-view path-fn item->path) (ui/succeeding-selection tree-view)))) (alt-selection [this] [])) (defn- setup-asset-browser [asset-browser workspace ^TreeView tree-view] (.setSelectionMode (.getSelectionModel tree-view) SelectionMode/MULTIPLE) (let [selection-provider (SelectionProvider. asset-browser) over-handler (ui/event-handler e (drag-over e)) dropped-handler (ui/event-handler e (error-reporting/catch-all! (drag-dropped e))) detected-handler (ui/event-handler e (drag-detected e (handler/selection selection-provider))) entered-handler (ui/event-handler e (drag-entered e)) exited-handler (ui/event-handler e (drag-exited e))] (doto tree-view (ui/customize-tree-view! {:double-click-expand? true}) (ui/bind-double-click! :open) (ui/bind-key-commands! {"Enter" :open "F2" :rename}) (.setOnDragDetected detected-handler) (ui/cell-factory! (fn [resource] (if (nil? resource) {} {:text (resource/resource-name resource) :icon (workspace/resource-icon resource) :style (resource/style-classes resource) :over-handler over-handler :dropped-handler dropped-handler :entered-handler entered-handler :exited-handler exited-handler}))) (ui/register-context-menu ::resource-menu) (ui/context! :asset-browser {:workspace workspace :asset-browser asset-browser} selection-provider)))) (g/defnode AssetBrowser (property raw-tree-view TreeView) (property prefs g/Any) (input resource-tree FileResource) (input active-resource resource/Resource :substitute nil) (output root TreeItem :cached produce-tree-root) (output tree-view TreeView :cached produce-tree-view)) (defn make-asset-browser [graph workspace tree-view prefs] (let [asset-browser (first (g/tx-nodes-added (g/transact (g/make-nodes graph [asset-browser [AssetBrowser :raw-tree-view tree-view :prefs prefs]] (g/connect workspace :resource-tree asset-browser :resource-tree)))))] (setup-asset-browser asset-browser workspace tree-view) asset-browser))
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.asset-browser (:require [clojure.java.io :as io] [clojure.string :as string] [dynamo.graph :as g] [editor.error-reporting :as error-reporting] [editor.fs :as fs] [editor.fxui :as fxui] [editor.handler :as handler] [editor.icons :as icons] [editor.ui :as ui] [editor.prefs :as prefs] [editor.resource :as resource] [editor.resource-watch :as resource-watch] [editor.workspace :as workspace] [editor.dialogs :as dialogs] [editor.disk-availability :as disk-availability] [editor.app-view :as app-view]) (:import [com.defold.editor Start] [editor.resource FileResource] [javafx.application Platform] [javafx.collections FXCollections ObservableList] [javafx.embed.swing SwingFXUtils] [javafx.event ActionEvent Event EventHandler] [javafx.fxml FXMLLoader] [javafx.geometry Insets] [javafx.scene.input Clipboard ClipboardContent] [javafx.scene.input DragEvent TransferMode MouseEvent] [javafx.scene Scene Node Parent] [javafx.scene.control Button ColorPicker Label TextField TitledPane TextArea TreeItem TreeView Menu MenuItem SeparatorMenuItem MenuBar Tab ProgressBar ContextMenu SelectionMode] [javafx.scene.image Image ImageView WritableImage PixelWriter] [javafx.scene.input MouseEvent KeyCombination ContextMenuEvent] [javafx.scene.layout AnchorPane GridPane StackPane HBox Priority] [javafx.scene.paint Color] [javafx.stage Stage FileChooser] [javafx.util Callback] [java.io File] [java.nio.file Path Paths] [java.util.prefs Preferences] [com.jogamp.opengl GL GL2 GLContext GLProfile GLDrawableFactory GLCapabilities] [org.apache.commons.io FilenameUtils] [com.defold.control TreeCell])) (set! *warn-on-reflection* true) (declare tree-item) (def ^:private empty-string-array (into-array String [])) (defn- ->path [s] (Paths/get s empty-string-array)) ; TreeItem creator (defn- ^ObservableList list-children [parent] (let [children (:children parent) items (->> (:children parent) (remove resource/internal?) (map tree-item) (into-array TreeItem))] (if (empty? children) (FXCollections/emptyObservableList) (doto (FXCollections/observableArrayList) (.addAll ^"[Ljavafx.scene.control.TreeItem;" items))))) ; NOTE: Without caching stack-overflow... WHY? (defn tree-item ^TreeItem [parent] (let [cached (atom false)] (proxy [TreeItem] [parent] (isLeaf [] (or (not= :folder (resource/source-type (.getValue ^TreeItem this))) (empty? (:children (.getValue ^TreeItem this))))) (getChildren [] (let [this ^TreeItem this ^ObservableList children (proxy-super getChildren)] (when-not @cached (reset! cached true) (.setAll children (list-children (.getValue this)))) children))))) (handler/register-menu! ::resource-menu [{:label "Open" :icon "icons/32/Icons_S_14_linkarrow.png" :command :open} {:label "Open As" :icon "icons/32/Icons_S_14_linkarrow.png" :command :open-as} {:label :separator} {:label "Copy Project Path" :command :copy-project-path} {:label "Copy Full Path" :command :copy-full-path} {:label "Copy Require Path" :command :copy-require-path} {:label :separator} {:label "Show in Desktop" :icon "icons/32/Icons_S_14_linkarrow.png" :command :show-in-desktop} {:label "Referencing Files..." :command :referencing-files} {:label "Dependencies..." :command :dependencies} {:label :separator} {:label "New" :command :new-file :expand? true :icon "icons/64/Icons_29-AT-Unknown.png"} {:label "New Folder" :command :new-folder :icon "icons/32/Icons_01-Folder-closed.png"} {:label :separator} {:label "Cut" :command :cut} {:label "Copy" :command :copy} {:label "Paste" :command :paste} {:label "Delete" :command :delete :icon "icons/32/Icons_M_06_trash.png"} {:label :separator} {:label "Rename..." :command :rename} {:label :separator :id ::context-menu-end}]) (def fixed-resource-paths #{"/" "/game.project"}) (defn deletable-resource? [x] (and (satisfies? resource/Resource x) (not (resource/read-only? x)) (not (fixed-resource-paths (resource/proj-path x))))) (defn- roots [resources] (let [resources (into {} (map (fn [resource] [(->path (resource/proj-path resource)) resource]) resources)) roots (loop [paths (keys resources) roots []] (if-let [^Path path (first paths)] (let [roots (if (empty? (filter (fn [^Path p] (.startsWith path p)) roots)) (conj roots path) roots)] (recur (rest paths) roots)) roots))] (mapv #(resources %) roots))) (defn- temp-resource-file! [^File dir resource] (let [target (File. dir (resource/resource-name resource))] (if (= :file (resource/source-type resource)) (with-open [in (io/input-stream resource) out (io/output-stream target)] (io/copy in out)) (do (fs/create-directories! target) (doseq [c (:children resource)] (temp-resource-file! target c)))) target)) (defn- fileify-resources! [resources] (let [dnd-directory (fs/create-temp-directory! "asset-dnd")] (mapv (fn [r] (if (resource/file-resource? r) (io/file r) (temp-resource-file! dnd-directory r))) resources))) (defn delete [resources] (when (not (empty? resources)) (let [workspace (resource/workspace (first resources))] (doseq [resource resources] (let [f (File. (resource/abs-path resource))] (fs/delete! f {:fail :silently}))) (workspace/resource-sync! workspace)))) (defn- copy [files] (let [cb (Clipboard/getSystemClipboard) content (ClipboardContent.)] (.putFiles content files) (.setContent cb content))) (handler/defhandler :copy :asset-browser (enabled? [selection] (not (empty? selection))) (run [selection] (copy (-> selection roots fileify-resources!)))) (defn- select-resource! ([asset-browser resource] (select-resource! asset-browser resource nil)) ([asset-browser resource {:keys [scroll?] :or {scroll? false} :as opts}] ;; This is a hack! ;; The reason is that the FileResource 'next' fetched prior to the deletion ;; may have changed after the deletion, due to the 'children' field in the record. ;; This is why we can't use ui/select! directly, but do our own implementation based on path. (let [^TreeView tree-view (g/node-value asset-browser :tree-view) tree-items (ui/tree-item-seq (.getRoot tree-view)) path (resource/resource->proj-path resource)] (when-let [tree-item (some (fn [^TreeItem tree-item] (and (= path (resource/resource->proj-path (.getValue tree-item))) tree-item)) tree-items)] (doto (.getSelectionModel tree-view) (.clearSelection) (.select tree-item)) (when scroll? (ui/scroll-to-item! tree-view tree-item)))))) (defn delete? [resources] (and (disk-availability/available?) (seq resources) (every? deletable-resource? resources))) (handler/defhandler :cut :asset-browser (enabled? [selection] (delete? selection)) (run [selection selection-provider asset-browser] (let [next (-> (handler/succeeding-selection selection-provider) (handler/adapt-single resource/Resource)) cut-files-directory (fs/create-temp-directory! "asset-cut")] (copy (mapv #(temp-resource-file! cut-files-directory %) (roots selection))) (delete selection) (when next (select-resource! asset-browser next))))) (defn- unique [^File original exists-fn name-fn] (let [original-basename (FilenameUtils/getBaseName (.getAbsolutePath original))] (loop [^File f original] (if (exists-fn f) (let [path (.getAbsolutePath f) ext (FilenameUtils/getExtension path) new-path (str (FilenameUtils/getFullPath path) (name-fn original-basename (FilenameUtils/getBaseName path)) (when (seq ext) (str "." ext)))] (recur (File. new-path))) f)))) (defn- ensure-unique-dest-files [name-fn src-dest-pairs] (loop [[[src dest :as pair] & rest] src-dest-pairs new-names #{} ret []] (if pair (let [new-dest (unique dest #(or (.exists ^File %) (new-names %)) name-fn)] (recur rest (conj new-names new-dest) (conj ret [src new-dest]))) ret))) (defn- numbering-name-fn [original-basename basename] (let [suffix (string/replace basename original-basename "")] (if (.isEmpty suffix) (str original-basename "1") (str original-basename (inc (bigint suffix)))))) (defmulti resolve-conflicts (fn [strategy src-dest-pairs] strategy)) (defmethod resolve-conflicts :overwrite [_ src-dest-pairs] src-dest-pairs) (defmethod resolve-conflicts :rename [_ src-dest-pairs] (ensure-unique-dest-files numbering-name-fn src-dest-pairs)) (defn- resolve-any-conflicts [src-dest-pairs] (let [files-by-existence (group-by (fn [[src ^File dest]] (.exists dest)) src-dest-pairs) conflicts (get files-by-existence true) non-conflicts (get files-by-existence false [])] (if (seq conflicts) (when-let [strategy (dialogs/make-resolve-file-conflicts-dialog conflicts)] (into non-conflicts (resolve-conflicts strategy conflicts))) non-conflicts))) (defn- select-files! [workspace tree-view files] (let [selected-paths (mapv (partial resource/file->proj-path (workspace/project-path workspace)) files)] (ui/user-data! tree-view ::pending-selection selected-paths))) (defn- reserved-project-file [^File project-path ^File f] (resource-watch/reserved-proj-path? project-path (resource/file->proj-path project-path f))) (defn- illegal-copy-move-pairs [^File project-path prospect-pairs] (seq (filter (comp (partial reserved-project-file project-path) second) prospect-pairs))) (defn allow-resource-move? "Returns true if it is legal to move all the supplied source files to the specified target resource. Disallows moves that would place a parent below one of its own children, moves to a readonly destination, moves to the same path the file already resides in, and moves to reserved directories." [tgt-resource src-files] (and (disk-availability/available?) (not (resource/read-only? tgt-resource)) (let [^Path tgt-path (-> tgt-resource resource/abs-path File. fs/to-folder .getAbsolutePath ->path) src-paths (map (fn [^File f] (-> f .getAbsolutePath ->path)) src-files) descendant (some (fn [^Path p] (or (.equals tgt-path (.getParent p)) (.startsWith tgt-path p))) src-paths) ;; Below is a bit of a hack to only perform the reserved paths check if the target ;; is the project root. possibly-reserved-tgt-files (when (= (resource/proj-path tgt-resource) "/") (map #(.toFile (.resolve tgt-path (.getName ^File %))) src-files)) project-path (workspace/project-path (resource/workspace tgt-resource))] (and (nil? descendant) (nil? (some (partial reserved-project-file project-path) possibly-reserved-tgt-files)))))) (defn paste? [files-on-clipboard? target-resources] (and files-on-clipboard? (disk-availability/available?) (= 1 (count target-resources)) (not (resource/read-only? (first target-resources))))) (defn paste! [workspace target-resource src-files select-files!] (let [^File tgt-dir (reduce (fn [^File tgt ^File src] (if (= tgt src) (.getParentFile ^File tgt) tgt)) (fs/to-folder (File. (resource/abs-path target-resource))) src-files) prospect-pairs (map (fn [^File f] [f (File. tgt-dir (FilenameUtils/getName (.toString f)))]) src-files) project-path (workspace/project-path workspace)] (if-let [illegal (illegal-copy-move-pairs project-path prospect-pairs)] (dialogs/make-info-dialog {:title "Cannot Paste" :icon :icon/triangle-error :header "There are reserved target directories" :content (str "Following target directories are reserved:\n" (string/join "\n" (map (comp (partial resource/file->proj-path project-path) second) illegal)))}) (let [pairs (ensure-unique-dest-files (fn [_ basename] (str basename "_copy")) prospect-pairs)] (doseq [[^File src-file ^File tgt-file] pairs] (fs/copy! src-file tgt-file {:target :merge})) (select-files! (mapv second pairs)) (workspace/resource-sync! workspace))))) (handler/defhandler :paste :asset-browser (enabled? [selection] (paste? (.hasFiles (Clipboard/getSystemClipboard)) selection)) (run [selection workspace asset-browser] (let [tree-view (g/node-value asset-browser :tree-view) resource (first selection) src-files (.getFiles (Clipboard/getSystemClipboard))] (paste! workspace resource src-files (partial select-files! workspace tree-view))))) (defn- moved-files [^File src-file ^File dest-file files] (let [src-path (.toPath src-file) dest-path (.toPath dest-file)] (mapv (fn [^File f] ;; (.relativize "foo" "foo") == "" so a plain file rename foo.clj -> bar.clj call of ;; of (moved-files "foo.clj" "bar.clj" ["foo.clj"]) will (.resolve "bar.clj" "") == "bar.clj" ;; just as we want. (let [dest-file (.toFile (.resolve dest-path (.relativize src-path (.toPath f))))] [f dest-file])) files))) (defn rename [resource ^String new-name] (assert (and new-name (not (string/blank? new-name)))) (let [workspace (resource/workspace resource) src-file (io/file resource) dest-file (File. (.getParent src-file) new-name) project-directory-file (workspace/project-path workspace) dest-proj-path (resource/file->proj-path project-directory-file dest-file)] (when-not (resource-watch/reserved-proj-path? project-directory-file dest-proj-path) (let [[[^File src-file ^File dest-file]] ;; plain case change causes irrelevant conflict on case insensitive fs ;; fs/move handles this, no need to resolve (if (fs/same-file? src-file dest-file) [[src-file dest-file]] (resolve-any-conflicts [[src-file dest-file]]))] (when dest-file (let [src-files (doall (file-seq src-file))] (fs/move! src-file dest-file) (workspace/resource-sync! workspace (moved-files src-file dest-file src-files)))))))) (defn rename? [resources] (and (disk-availability/available?) (= 1 (count resources)) (not (resource/read-only? (first resources))) (not (fixed-resource-paths (resource/resource->proj-path (first resources)))))) (defn validate-new-resource-name [^File project-directory-file parent-path new-name] (let [prospect-path (str parent-path "/" new-name)] (when (resource-watch/reserved-proj-path? project-directory-file prospect-path) (format "The name %s is reserved" new-name)))) (handler/defhandler :rename :asset-browser (enabled? [selection] (rename? selection)) (run [selection workspace] (let [resource (first selection) dir? (= :folder (resource/source-type resource)) extension (resource/ext resource) name (if dir? (resource/resource-name resource) (if (seq extension) (string/replace (resource/resource-name resource) (re-pattern (str "\\." extension "$")) "") (resource/resource-name resource))) parent-path (resource/parent-proj-path (resource/proj-path resource)) project-directory-file (workspace/project-path workspace) options {:title (if dir? "Rename Folder" "Rename File") :label (if dir? "New Folder Name" "New File Name") :sanitize (if dir? dialogs/sanitize-folder-name (partial dialogs/sanitize-file-name extension)) :validate (partial validate-new-resource-name project-directory-file parent-path)} new-name (dialogs/make-rename-dialog name options)] (when-let [sane-new-name (some-> new-name not-empty)] (rename resource sane-new-name))))) (handler/defhandler :delete :asset-browser (enabled? [selection] (delete? selection)) (run [selection asset-browser selection-provider] (let [next (-> (handler/succeeding-selection selection-provider) (handler/adapt-single resource/Resource))] (when (if (= 1 (count selection)) (dialogs/make-confirmation-dialog {:title "Delete File?" :icon :icon/circle-question :header (format "Are you sure you want to delete %s?" (resource/resource-name (first selection))) :buttons [{:text "Cancel" :cancel-button true :default-button true :result false} {:text "Delete" :variant :danger :result true}]}) (dialogs/make-info-dialog {:title "Delete Files?" :icon :icon/circle-question :header "Are you sure you want to delete these files?" :content {:text (str "You are about to delete:\n" (->> selection (map #(str "\u00A0\u00A0\u2022\u00A0" (resource/resource-name %))) (string/join "\n")))} :buttons [{:text "Cancel" :cancel-button true :default-button true :result false} {:text "Delete" :variant :danger :result true}]})) (when (and (delete selection) next) (select-resource! asset-browser next)))))) (handler/defhandler :new-file :global (label [user-data] (if-not user-data "New..." (let [rt (:resource-type user-data)] (or (:label rt) (:ext rt))))) (active? [selection selection-context] (or (= :global selection-context) (and (= :asset-browser selection-context) (= (count selection) 1) (not= nil (some-> (handler/adapt-single selection resource/Resource) resource/abs-path))))) (enabled? [] (disk-availability/available?)) (run [selection user-data asset-browser app-view prefs workspace project] (let [project-path (workspace/project-path workspace) base-folder (-> (or (some-> (handler/adapt-every selection resource/Resource) first resource/abs-path (File.)) project-path) fs/to-folder) rt (:resource-type user-data)] (when-let [desired-file (dialogs/make-new-file-dialog project-path base-folder (or (:label rt) (:ext rt)) (:ext rt))] (when-let [[[_ new-file]] (resolve-any-conflicts [[nil desired-file]])] (spit new-file (workspace/template workspace rt)) (workspace/resource-sync! workspace) (let [resource-map (g/node-value workspace :resource-map) new-resource-path (resource/file->proj-path project-path new-file) resource (resource-map new-resource-path)] (app-view/open-resource app-view prefs workspace project resource) (select-resource! asset-browser resource)))))) (options [workspace selection user-data] (when (not user-data) (let [resource-types (filter (fn [rt] (workspace/template workspace rt)) (workspace/get-resource-types workspace))] (sort-by (fn [rt] (string/lower-case (:label rt))) (map (fn [res-type] {:label (or (:label res-type) (:ext res-type)) :icon (:icon res-type) :style (resource/ext-style-classes (:ext res-type)) :command :new-file :user-data {:resource-type res-type}}) resource-types)))))) (defn- resolve-sub-folder [^File base-folder ^String new-folder-name] (.toFile (.resolve (.toPath base-folder) new-folder-name))) (defn validate-new-folder-name [^File project-directory-file parent-path new-name] (let [prospect-path (str parent-path "/" new-name)] (when (resource-watch/reserved-proj-path? project-directory-file prospect-path) (format "The name %s is reserved" new-name)))) (defn new-folder? [resources] (and (disk-availability/available?) (= (count resources) 1) (not (resource/read-only? (first resources))) (not= nil (resource/abs-path (first resources))))) (handler/defhandler :new-folder :asset-browser (enabled? [selection] (new-folder? selection)) (run [selection workspace asset-browser] (let [parent-resource (first selection) parent-path (resource/proj-path parent-resource) parent-path (if (= parent-path "/") "" parent-path) ; special case because the project root dir ends in / base-folder (fs/to-folder (File. (resource/abs-path parent-resource))) project-directory-file (workspace/project-path workspace) options {:validate (partial validate-new-folder-name project-directory-file parent-path)}] (when-let [new-folder-name (dialogs/make-new-folder-dialog base-folder options)] (let [^File folder (resolve-sub-folder base-folder new-folder-name)] (do (fs/create-directories! folder) (workspace/resource-sync! workspace) (select-resource! asset-browser (workspace/file-resource workspace folder)))))))) (defn- selected-or-active-resource [selection active-resource] (or (handler/adapt-single selection resource/Resource) active-resource)) (handler/defhandler :show-in-asset-browser :global (active? [active-resource selection] (selected-or-active-resource selection active-resource)) (enabled? [active-resource selection] (when-let [r (selected-or-active-resource selection active-resource)] (resource/exists? r))) (run [active-resource asset-browser selection main-stage] (when-let [r (selected-or-active-resource selection active-resource)] (app-view/show-asset-browser! (.getScene ^Stage main-stage)) (select-resource! asset-browser r {:scroll? true})))) (defn- item->path [^TreeItem item] (-> item (.getValue) (resource/proj-path))) (defn- sync-tree! [old-root new-root] (let [item-seq (ui/tree-item-seq old-root) expanded (zipmap (map item->path item-seq) (map #(.isExpanded ^TreeItem %) item-seq))] (doseq [^TreeItem item (ui/tree-item-seq new-root)] (when (get expanded (item->path item)) (.setExpanded item true)))) new-root) (g/defnk produce-tree-root [^TreeView raw-tree-view resource-tree] (let [old-root (.getRoot raw-tree-view) new-root (tree-item resource-tree)] (when new-root (sync-tree! old-root new-root) (.setExpanded new-root true) new-root))) (defn- auto-expand [items selected-paths] (not-every? false? (map (fn [^TreeItem item] (let [path (item->path item) selected (boolean (selected-paths path)) expanded (auto-expand (.getChildren item) selected-paths)] (when expanded (.setExpanded item expanded)) (or selected expanded))) items))) (defn- sync-selection! [^TreeView tree-view selected-paths] (let [root (.getRoot tree-view) selection-model (.getSelectionModel tree-view)] (.clearSelection selection-model) (when (and root (seq selected-paths)) (let [selected-paths (set selected-paths)] (auto-expand (.getChildren root) selected-paths) (let [count (.getExpandedItemCount tree-view) selected-indices (filter #(selected-paths (item->path (.getTreeItem tree-view %))) (range count))] (when (not (empty? selected-indices)) (ui/select-indices! tree-view selected-indices)) (when-some [first-item (first (.getSelectedItems selection-model))] (ui/scroll-to-item! tree-view first-item))))))) (defn- update-tree-view-selection! [^TreeView tree-view selected-paths] (sync-selection! tree-view selected-paths) tree-view) (defn- update-tree-view-root! [^TreeView tree-view ^TreeItem root selected-paths] (when root (.setExpanded root true) (.setRoot tree-view root)) (sync-selection! tree-view selected-paths) tree-view) (defn track-active-tab? [prefs] (prefs/get-prefs prefs "asset-browser-track-active-tab?" false)) (g/defnk produce-tree-view [^TreeView raw-tree-view ^TreeItem root active-resource prefs] (let [selected-paths (or (ui/user-data raw-tree-view ::pending-selection) (when (and (track-active-tab? prefs) active-resource) [(resource/proj-path active-resource)]) (mapv resource/proj-path (ui/selection raw-tree-view)))] (ui/user-data! raw-tree-view ::pending-selection nil) (cond ;; different roots? (not (identical? (.getRoot raw-tree-view) root)) (update-tree-view-root! raw-tree-view root selected-paths) ;; same root, different selection? (not (= (set selected-paths) (set (map resource/proj-path (ui/selection raw-tree-view))))) (update-tree-view-selection! raw-tree-view selected-paths) :else raw-tree-view))) (defn- drag-detected [^MouseEvent e selection] (let [resources (roots selection) files (fileify-resources! resources) ;; Note: It would seem we should use the TransferMode/COPY_OR_MOVE mode ;; here in order to support making copies of non-readonly files, but ;; that results in every drag operation becoming a copy on macOS due to ;; https://bugs.openjdk.java.net/browse/JDK-8148025 mode (if (empty? (filter resource/read-only? resources)) TransferMode/MOVE TransferMode/COPY) db (.startDragAndDrop ^Node (.getSource e) (into-array TransferMode [mode])) content (ClipboardContent.)] (when (= 1 (count resources)) (.setDragView db (icons/get-image (workspace/resource-icon (first resources)) 16) 0 16)) (.putFiles content files) (.setContent db content) (.consume e))) (defn- target [^Node node] (when node (if (instance? TreeCell node) node (target (.getParent node))))) (defn- drag-entered [^DragEvent e] (let [^TreeCell cell (target (.getTarget e))] (when (and cell (not (.isEmpty cell))) (let [resource (.getValue (.getTreeItem cell))] (when (and (= :folder (resource/source-type resource)) (not (resource/read-only? resource))) (ui/add-style! cell "drop-target")))))) (defn- drag-exited [^DragEvent e] (when-let [cell (target (.getTarget e))] (ui/remove-style! cell "drop-target"))) (defn- drag-over [^DragEvent e] (let [db (.getDragboard e)] (when-let [^TreeCell cell (target (.getTarget e))] (when (and (not (.isEmpty cell)) (.hasFiles db)) ;; Auto scrolling (let [view (.getTreeView cell) view-y (.getY (.sceneToLocal view (.getSceneX e) (.getSceneY e))) height (.getHeight (.getBoundsInLocal view))] (when (< view-y 15) (.scrollTo view (dec (.getIndex cell)))) (when (> view-y (- height 15)) (.scrollTo view (inc (.getIndex cell))))) (let [tgt-resource (-> cell (.getTreeItem) (.getValue))] (when (allow-resource-move? tgt-resource (.getFiles db)) ;; Allow move only if the drag source was also the tree view. (if (= (.getTreeView cell) (.getGestureSource e)) (.acceptTransferModes e TransferMode/COPY_OR_MOVE) (.acceptTransferModes e (into-array TransferMode [TransferMode/COPY]))) (.consume e))))))) (defn- drag-move-files [dragged-pairs] (into [] (mapcat (fn [[src tgt]] (let [src-files (doall (file-seq src))] (fs/move! src tgt) (moved-files src tgt src-files))) dragged-pairs))) (defn- drag-copy-files [dragged-pairs] (doseq [[^File src ^File tgt] dragged-pairs] (fs/copy! src tgt {:fail :silently})) []) (defn- fixed-move-source [^File project-path [^File src ^File _tgt]] (contains? fixed-resource-paths (resource/file->proj-path project-path src))) (defn drop-files! [workspace dragged-pairs move?] (let [project-path (workspace/project-path workspace)] (when (seq dragged-pairs) (let [moved (if move? (let [{move-pairs false copy-pairs true} (group-by (partial fixed-move-source project-path) dragged-pairs)] (drag-copy-files copy-pairs) (drag-move-files move-pairs)) (drag-copy-files dragged-pairs))] moved)))) (defn- drag-dropped [^DragEvent e] (let [db (.getDragboard e)] (when (.hasFiles db) (let [target (-> e (.getTarget) ^TreeCell (target)) tree-view (.getTreeView target) resource (-> target (.getTreeItem) (.getValue)) ^Path tgt-dir-path (.toPath (fs/to-folder (File. (resource/abs-path resource)))) move? (and (= (.getGestureSource e) tree-view) (= (.getTransferMode e) TransferMode/MOVE)) pairs (->> (.getFiles db) (mapv (fn [^File f] [f (.toFile (.resolve tgt-dir-path (.getName f)))])) (resolve-any-conflicts) (vec)) workspace (resource/workspace resource) project-path (workspace/project-path workspace)] (when (seq pairs) (let [moved (drop-files! workspace pairs move?)] (select-files! workspace tree-view (mapv second pairs)) (workspace/resource-sync! workspace moved)))))) (.setDropCompleted e true) (.consume e)) (defrecord SelectionProvider [asset-browser] handler/SelectionProvider (selection [this] (ui/selection (g/node-value asset-browser :tree-view))) (succeeding-selection [this] (let [tree-view (g/node-value asset-browser :tree-view) path-fn (comp #(string/split % #"/") item->path)] (->> (ui/selection-root-items tree-view path-fn item->path) (ui/succeeding-selection tree-view)))) (alt-selection [this] [])) (defn- setup-asset-browser [asset-browser workspace ^TreeView tree-view] (.setSelectionMode (.getSelectionModel tree-view) SelectionMode/MULTIPLE) (let [selection-provider (SelectionProvider. asset-browser) over-handler (ui/event-handler e (drag-over e)) dropped-handler (ui/event-handler e (error-reporting/catch-all! (drag-dropped e))) detected-handler (ui/event-handler e (drag-detected e (handler/selection selection-provider))) entered-handler (ui/event-handler e (drag-entered e)) exited-handler (ui/event-handler e (drag-exited e))] (doto tree-view (ui/customize-tree-view! {:double-click-expand? true}) (ui/bind-double-click! :open) (ui/bind-key-commands! {"Enter" :open "F2" :rename}) (.setOnDragDetected detected-handler) (ui/cell-factory! (fn [resource] (if (nil? resource) {} {:text (resource/resource-name resource) :icon (workspace/resource-icon resource) :style (resource/style-classes resource) :over-handler over-handler :dropped-handler dropped-handler :entered-handler entered-handler :exited-handler exited-handler}))) (ui/register-context-menu ::resource-menu) (ui/context! :asset-browser {:workspace workspace :asset-browser asset-browser} selection-provider)))) (g/defnode AssetBrowser (property raw-tree-view TreeView) (property prefs g/Any) (input resource-tree FileResource) (input active-resource resource/Resource :substitute nil) (output root TreeItem :cached produce-tree-root) (output tree-view TreeView :cached produce-tree-view)) (defn make-asset-browser [graph workspace tree-view prefs] (let [asset-browser (first (g/tx-nodes-added (g/transact (g/make-nodes graph [asset-browser [AssetBrowser :raw-tree-view tree-view :prefs prefs]] (g/connect workspace :resource-tree asset-browser :resource-tree)))))] (setup-asset-browser asset-browser workspace tree-view) asset-browser))
[ { "context": "/config/jetty/\")\n\n(def default-keystore-pass \"Kq8lG9LkISky9cDIYysiadxRx\")\n\n(def default-options-fo", "end": 961, "score": 0.5684463381767273, "start": 959, "tag": "PASSWORD", "value": "Kq" }, { "context": "onfig/jetty/\")\n\n(def default-keystore-pass \"Kq8lG9LkISky9cDIYysiadxRx\")\n\n(def default-options-for-https\n {:keystore ", "end": 984, "score": 0.7322136163711548, "start": 961, "tag": "KEY", "value": "8lG9LkISky9cDIYysiadxRx" }, { "context": "\")\n :keystore-type \"JKS\"\n :keystore-pass default-keystore-pass\n :trust-store (str test-reso", "end": 1146, "score": 0.8575344085693359, "start": 1139, "tag": "PASSWORD", "value": "default" } ]
test/clj/puppetlabs/trapperkeeper/services/webserver/jetty7_service_test.clj
puppetlabs/trapperkeeper-webserver-jetty7
1
(ns puppetlabs.trapperkeeper.services.webserver.jetty7-service-test (:import (java.net ConnectException) (javax.net.ssl SSLPeerUnverifiedException) [servlet SimpleServlet]) (:require [clojure.test :refer :all] [clj-http.client :as http-client] [puppetlabs.trapperkeeper.app :refer [get-service]] [puppetlabs.trapperkeeper.services :refer [stop service-context]] [puppetlabs.trapperkeeper.services.webserver.jetty7-service :refer :all] [puppetlabs.trapperkeeper.testutils.bootstrap :refer [bootstrap-services-with-empty-config bootstrap-services-with-cli-data]] [puppetlabs.kitchensink.testutils.fixtures :refer [with-no-jvm-shutdown-hooks]])) (use-fixtures :once with-no-jvm-shutdown-hooks) (def test-resources-config-dir "./dev-resources/config/jetty/") (def default-keystore-pass "Kq8lG9LkISky9cDIYysiadxRx") (def default-options-for-https {:keystore (str test-resources-config-dir "ssl/keystore.jks") :keystore-type "JKS" :keystore-pass default-keystore-pass :trust-store (str test-resources-config-dir "ssl/truststore.jks") :trust-store-type "JKS" :trust-store-pass default-keystore-pass ; The default server's certificate in this case uses a CN of ; "localhost-puppetdb" whereas the URL being reached is "localhost". The ; insecure? value of true directs the client to ignore the mismatch. :insecure? true}) (defn bootstrap-and-validate-ring-handler ([base-url config-file-name] (bootstrap-and-validate-ring-handler base-url config-file-name {})) ([base-url config-file-name http-get-options] (let [app (bootstrap-services-with-cli-data [jetty7-service] {:config (str test-resources-config-dir config-file-name)}) s (get-service app :WebserverService) add-ring-handler (partial add-ring-handler s) shutdown (partial stop s (service-context s)) body "Hi World" path "/hi_world" ring-handler (fn [req] {:status 200 :body body})] (try (add-ring-handler ring-handler path) (let [response (http-client/get (format "%s/%s/" base-url path) http-get-options)] (is (= (:status response) 200)) (is (= (:body response) body))) (finally (shutdown)))))) (deftest jetty-jetty7-service (testing "ring request over http succeeds") (bootstrap-and-validate-ring-handler "http://localhost:8080" "jetty-plaintext-http.ini") (testing "request to servlet over http succeeds" (let [app (bootstrap-services-with-cli-data [jetty7-service] {:config (str test-resources-config-dir "jetty-plaintext-http.ini")}) s (get-service app :WebserverService) add-servlet-handler (partial add-servlet-handler s) shutdown (partial stop s (service-context s)) body "Hey there" path "/hey" servlet (SimpleServlet. body)] (try (add-servlet-handler servlet path) (let [response (http-client/get (format "http://localhost:8080/%s" path))] (is (= (:status response) 200)) (is (= (:body response) body))) (finally (shutdown))))) (testing "request to servlet initialized with empty param succeeds" (let [app (bootstrap-services-with-cli-data [jetty7-service] {:config (str test-resources-config-dir "jetty-plaintext-http.ini")}) s (get-service app :WebserverService) add-servlet-handler (partial add-servlet-handler s) shutdown (partial stop s (service-context s)) body "Hey there" path "/hey" servlet (SimpleServlet. body)] (try (add-servlet-handler servlet path {}) (let [response (http-client/get (format "http://localhost:8080/%s" path))] (is (= (:status response) 200)) (is (= (:body response) body))) (finally (shutdown))))) (testing "request to servlet initialized with non-empty params succeeds" (let [app (bootstrap-services-with-cli-data [jetty7-service] {:config (str test-resources-config-dir "jetty-plaintext-http.ini")}) s (get-service app :WebserverService) add-servlet-handler (partial add-servlet-handler s) shutdown (partial stop s (service-context s)) body "Hey there" path "/hey" init-param-one "value of init param one" init-param-two "value of init param two" servlet (SimpleServlet. body)] (try (add-servlet-handler servlet path {"init-param-one" init-param-one "init-param-two" init-param-two}) (let [response (http-client/get (format "http://localhost:8080/%s/init-param-one" path))] (is (= (:status response) 200)) (is (= (:body response) init-param-one))) (let [response (http-client/get (format "http://localhost:8080/%s/init-param-two" path))] (is (= (:status response) 200)) (is (= (:body response) init-param-two))) (finally (shutdown))))) (testing "webserver bootstrap throws IllegalArgumentException when neither port nor ssl-port specified in the config" (is (thrown-with-msg? IllegalArgumentException #"Either port or ssl-port must be specified on the config in order for a port binding to be opened" (bootstrap-services-with-empty-config [jetty7-service])) "Did not encounter expected exception when no port specified in config")) (testing "ring request over SSL successful for both .jks and .pem implementations with the server's client-auth setting not set and the client configured provide a certificate which the CA can validate" ; Note that if the 'client-auth' setting is not set that the server ; should default to 'need' to validate the client certificate. In this ; case, the validation should be successful because the client is ; providing a certificate which the CA can validate. (doseq [config ["jetty-ssl-jks.ini" "jetty-ssl-pem.ini"]] (bootstrap-and-validate-ring-handler "https://localhost:8081" config default-options-for-https))) (testing "ring request over SSL fails with the server's client-auth setting not set and the client configured to provide a certificate which the CA cannot validate" ; Note that if the 'client-auth' setting is not set that the server ; should default to 'need' to validate the client certificate. In this ; case, the validation should fail because the client is providing a ; certificate which the CA cannot validate. (is (thrown? SSLPeerUnverifiedException (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem.ini" (assoc default-options-for-https :keystore (str test-resources-config-dir "ssl/unauthorized_keystore.jks")))))) (testing "ring request over SSL fails with the server's client-auth setting not set and the client configured to not provide a certificate" ; Note that if the 'client-auth' setting is not set that the server ; should default to 'need' to validate the client certificate. In this ; case, the validation should fail because the client is providing a ; certificate which the CA cannot validate. (is (thrown? SSLPeerUnverifiedException (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem.ini" (assoc default-options-for-https :keystore nil))))) (testing "ring request over SSL succeeds with a server client-auth setting of 'need' and the client configured to provide a certificate which the CA can validate" (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem-client-auth-need.ini" default-options-for-https)) (testing "ring request over SSL fails with a server client-auth setting of 'need' and the client configured to provide a certificate which the CA cannot validate" (is (thrown? SSLPeerUnverifiedException (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem-client-auth-need.ini" (assoc default-options-for-https :keystore (str test-resources-config-dir "ssl/unauthorized_keystore.jks")))))) (testing "ring request over SSL fails with a server client-auth setting of 'need' and the client configured to not provide a certificate" (is (thrown? SSLPeerUnverifiedException (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem-client-auth-need.ini")))) (testing "ring request over SSL succeeds with a server client-auth setting of 'want' and the client configured to provide a certificate which the CA can validate" (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem-client-auth-want.ini" default-options-for-https)) (testing "ring request over SSL fails with a server client-auth setting of 'want' and the client configured to provide a certificate which the CA cannot validate" (is (thrown? SSLPeerUnverifiedException (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem-client-auth-need.ini" (assoc default-options-for-https :keystore (str test-resources-config-dir "ssl/unauthorized_keystore.jks")))))) (testing "ring request over SSL succeeds with a server client-auth setting of 'want' and the client configured to not provide a certificate" (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem-client-auth-want.ini" (assoc default-options-for-https :keystore nil))) (testing "ring request over SSL succeeds with a server client-auth setting of 'none' and the client configured to provide a certificate which the CA can validate" (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem-client-auth-none.ini" default-options-for-https)) (testing "ring request over SSL fails with a server client-auth setting of 'none' and the client configured to provide a certificate which the CA cannot validate" (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem-client-auth-none.ini" (assoc default-options-for-https :keystore (str test-resources-config-dir "ssl/unauthorized_keystore.jks")))) (testing "ring request over SSL succeeds with a server client-auth setting of 'none' and the client configured to not provide a certificate" (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem-client-auth-none.ini" (assoc default-options-for-https :keystore nil))))
107371
(ns puppetlabs.trapperkeeper.services.webserver.jetty7-service-test (:import (java.net ConnectException) (javax.net.ssl SSLPeerUnverifiedException) [servlet SimpleServlet]) (:require [clojure.test :refer :all] [clj-http.client :as http-client] [puppetlabs.trapperkeeper.app :refer [get-service]] [puppetlabs.trapperkeeper.services :refer [stop service-context]] [puppetlabs.trapperkeeper.services.webserver.jetty7-service :refer :all] [puppetlabs.trapperkeeper.testutils.bootstrap :refer [bootstrap-services-with-empty-config bootstrap-services-with-cli-data]] [puppetlabs.kitchensink.testutils.fixtures :refer [with-no-jvm-shutdown-hooks]])) (use-fixtures :once with-no-jvm-shutdown-hooks) (def test-resources-config-dir "./dev-resources/config/jetty/") (def default-keystore-pass "<PASSWORD> <KEY>") (def default-options-for-https {:keystore (str test-resources-config-dir "ssl/keystore.jks") :keystore-type "JKS" :keystore-pass <PASSWORD>-keystore-pass :trust-store (str test-resources-config-dir "ssl/truststore.jks") :trust-store-type "JKS" :trust-store-pass default-keystore-pass ; The default server's certificate in this case uses a CN of ; "localhost-puppetdb" whereas the URL being reached is "localhost". The ; insecure? value of true directs the client to ignore the mismatch. :insecure? true}) (defn bootstrap-and-validate-ring-handler ([base-url config-file-name] (bootstrap-and-validate-ring-handler base-url config-file-name {})) ([base-url config-file-name http-get-options] (let [app (bootstrap-services-with-cli-data [jetty7-service] {:config (str test-resources-config-dir config-file-name)}) s (get-service app :WebserverService) add-ring-handler (partial add-ring-handler s) shutdown (partial stop s (service-context s)) body "Hi World" path "/hi_world" ring-handler (fn [req] {:status 200 :body body})] (try (add-ring-handler ring-handler path) (let [response (http-client/get (format "%s/%s/" base-url path) http-get-options)] (is (= (:status response) 200)) (is (= (:body response) body))) (finally (shutdown)))))) (deftest jetty-jetty7-service (testing "ring request over http succeeds") (bootstrap-and-validate-ring-handler "http://localhost:8080" "jetty-plaintext-http.ini") (testing "request to servlet over http succeeds" (let [app (bootstrap-services-with-cli-data [jetty7-service] {:config (str test-resources-config-dir "jetty-plaintext-http.ini")}) s (get-service app :WebserverService) add-servlet-handler (partial add-servlet-handler s) shutdown (partial stop s (service-context s)) body "Hey there" path "/hey" servlet (SimpleServlet. body)] (try (add-servlet-handler servlet path) (let [response (http-client/get (format "http://localhost:8080/%s" path))] (is (= (:status response) 200)) (is (= (:body response) body))) (finally (shutdown))))) (testing "request to servlet initialized with empty param succeeds" (let [app (bootstrap-services-with-cli-data [jetty7-service] {:config (str test-resources-config-dir "jetty-plaintext-http.ini")}) s (get-service app :WebserverService) add-servlet-handler (partial add-servlet-handler s) shutdown (partial stop s (service-context s)) body "Hey there" path "/hey" servlet (SimpleServlet. body)] (try (add-servlet-handler servlet path {}) (let [response (http-client/get (format "http://localhost:8080/%s" path))] (is (= (:status response) 200)) (is (= (:body response) body))) (finally (shutdown))))) (testing "request to servlet initialized with non-empty params succeeds" (let [app (bootstrap-services-with-cli-data [jetty7-service] {:config (str test-resources-config-dir "jetty-plaintext-http.ini")}) s (get-service app :WebserverService) add-servlet-handler (partial add-servlet-handler s) shutdown (partial stop s (service-context s)) body "Hey there" path "/hey" init-param-one "value of init param one" init-param-two "value of init param two" servlet (SimpleServlet. body)] (try (add-servlet-handler servlet path {"init-param-one" init-param-one "init-param-two" init-param-two}) (let [response (http-client/get (format "http://localhost:8080/%s/init-param-one" path))] (is (= (:status response) 200)) (is (= (:body response) init-param-one))) (let [response (http-client/get (format "http://localhost:8080/%s/init-param-two" path))] (is (= (:status response) 200)) (is (= (:body response) init-param-two))) (finally (shutdown))))) (testing "webserver bootstrap throws IllegalArgumentException when neither port nor ssl-port specified in the config" (is (thrown-with-msg? IllegalArgumentException #"Either port or ssl-port must be specified on the config in order for a port binding to be opened" (bootstrap-services-with-empty-config [jetty7-service])) "Did not encounter expected exception when no port specified in config")) (testing "ring request over SSL successful for both .jks and .pem implementations with the server's client-auth setting not set and the client configured provide a certificate which the CA can validate" ; Note that if the 'client-auth' setting is not set that the server ; should default to 'need' to validate the client certificate. In this ; case, the validation should be successful because the client is ; providing a certificate which the CA can validate. (doseq [config ["jetty-ssl-jks.ini" "jetty-ssl-pem.ini"]] (bootstrap-and-validate-ring-handler "https://localhost:8081" config default-options-for-https))) (testing "ring request over SSL fails with the server's client-auth setting not set and the client configured to provide a certificate which the CA cannot validate" ; Note that if the 'client-auth' setting is not set that the server ; should default to 'need' to validate the client certificate. In this ; case, the validation should fail because the client is providing a ; certificate which the CA cannot validate. (is (thrown? SSLPeerUnverifiedException (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem.ini" (assoc default-options-for-https :keystore (str test-resources-config-dir "ssl/unauthorized_keystore.jks")))))) (testing "ring request over SSL fails with the server's client-auth setting not set and the client configured to not provide a certificate" ; Note that if the 'client-auth' setting is not set that the server ; should default to 'need' to validate the client certificate. In this ; case, the validation should fail because the client is providing a ; certificate which the CA cannot validate. (is (thrown? SSLPeerUnverifiedException (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem.ini" (assoc default-options-for-https :keystore nil))))) (testing "ring request over SSL succeeds with a server client-auth setting of 'need' and the client configured to provide a certificate which the CA can validate" (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem-client-auth-need.ini" default-options-for-https)) (testing "ring request over SSL fails with a server client-auth setting of 'need' and the client configured to provide a certificate which the CA cannot validate" (is (thrown? SSLPeerUnverifiedException (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem-client-auth-need.ini" (assoc default-options-for-https :keystore (str test-resources-config-dir "ssl/unauthorized_keystore.jks")))))) (testing "ring request over SSL fails with a server client-auth setting of 'need' and the client configured to not provide a certificate" (is (thrown? SSLPeerUnverifiedException (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem-client-auth-need.ini")))) (testing "ring request over SSL succeeds with a server client-auth setting of 'want' and the client configured to provide a certificate which the CA can validate" (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem-client-auth-want.ini" default-options-for-https)) (testing "ring request over SSL fails with a server client-auth setting of 'want' and the client configured to provide a certificate which the CA cannot validate" (is (thrown? SSLPeerUnverifiedException (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem-client-auth-need.ini" (assoc default-options-for-https :keystore (str test-resources-config-dir "ssl/unauthorized_keystore.jks")))))) (testing "ring request over SSL succeeds with a server client-auth setting of 'want' and the client configured to not provide a certificate" (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem-client-auth-want.ini" (assoc default-options-for-https :keystore nil))) (testing "ring request over SSL succeeds with a server client-auth setting of 'none' and the client configured to provide a certificate which the CA can validate" (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem-client-auth-none.ini" default-options-for-https)) (testing "ring request over SSL fails with a server client-auth setting of 'none' and the client configured to provide a certificate which the CA cannot validate" (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem-client-auth-none.ini" (assoc default-options-for-https :keystore (str test-resources-config-dir "ssl/unauthorized_keystore.jks")))) (testing "ring request over SSL succeeds with a server client-auth setting of 'none' and the client configured to not provide a certificate" (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem-client-auth-none.ini" (assoc default-options-for-https :keystore nil))))
true
(ns puppetlabs.trapperkeeper.services.webserver.jetty7-service-test (:import (java.net ConnectException) (javax.net.ssl SSLPeerUnverifiedException) [servlet SimpleServlet]) (:require [clojure.test :refer :all] [clj-http.client :as http-client] [puppetlabs.trapperkeeper.app :refer [get-service]] [puppetlabs.trapperkeeper.services :refer [stop service-context]] [puppetlabs.trapperkeeper.services.webserver.jetty7-service :refer :all] [puppetlabs.trapperkeeper.testutils.bootstrap :refer [bootstrap-services-with-empty-config bootstrap-services-with-cli-data]] [puppetlabs.kitchensink.testutils.fixtures :refer [with-no-jvm-shutdown-hooks]])) (use-fixtures :once with-no-jvm-shutdown-hooks) (def test-resources-config-dir "./dev-resources/config/jetty/") (def default-keystore-pass "PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI") (def default-options-for-https {:keystore (str test-resources-config-dir "ssl/keystore.jks") :keystore-type "JKS" :keystore-pass PI:PASSWORD:<PASSWORD>END_PI-keystore-pass :trust-store (str test-resources-config-dir "ssl/truststore.jks") :trust-store-type "JKS" :trust-store-pass default-keystore-pass ; The default server's certificate in this case uses a CN of ; "localhost-puppetdb" whereas the URL being reached is "localhost". The ; insecure? value of true directs the client to ignore the mismatch. :insecure? true}) (defn bootstrap-and-validate-ring-handler ([base-url config-file-name] (bootstrap-and-validate-ring-handler base-url config-file-name {})) ([base-url config-file-name http-get-options] (let [app (bootstrap-services-with-cli-data [jetty7-service] {:config (str test-resources-config-dir config-file-name)}) s (get-service app :WebserverService) add-ring-handler (partial add-ring-handler s) shutdown (partial stop s (service-context s)) body "Hi World" path "/hi_world" ring-handler (fn [req] {:status 200 :body body})] (try (add-ring-handler ring-handler path) (let [response (http-client/get (format "%s/%s/" base-url path) http-get-options)] (is (= (:status response) 200)) (is (= (:body response) body))) (finally (shutdown)))))) (deftest jetty-jetty7-service (testing "ring request over http succeeds") (bootstrap-and-validate-ring-handler "http://localhost:8080" "jetty-plaintext-http.ini") (testing "request to servlet over http succeeds" (let [app (bootstrap-services-with-cli-data [jetty7-service] {:config (str test-resources-config-dir "jetty-plaintext-http.ini")}) s (get-service app :WebserverService) add-servlet-handler (partial add-servlet-handler s) shutdown (partial stop s (service-context s)) body "Hey there" path "/hey" servlet (SimpleServlet. body)] (try (add-servlet-handler servlet path) (let [response (http-client/get (format "http://localhost:8080/%s" path))] (is (= (:status response) 200)) (is (= (:body response) body))) (finally (shutdown))))) (testing "request to servlet initialized with empty param succeeds" (let [app (bootstrap-services-with-cli-data [jetty7-service] {:config (str test-resources-config-dir "jetty-plaintext-http.ini")}) s (get-service app :WebserverService) add-servlet-handler (partial add-servlet-handler s) shutdown (partial stop s (service-context s)) body "Hey there" path "/hey" servlet (SimpleServlet. body)] (try (add-servlet-handler servlet path {}) (let [response (http-client/get (format "http://localhost:8080/%s" path))] (is (= (:status response) 200)) (is (= (:body response) body))) (finally (shutdown))))) (testing "request to servlet initialized with non-empty params succeeds" (let [app (bootstrap-services-with-cli-data [jetty7-service] {:config (str test-resources-config-dir "jetty-plaintext-http.ini")}) s (get-service app :WebserverService) add-servlet-handler (partial add-servlet-handler s) shutdown (partial stop s (service-context s)) body "Hey there" path "/hey" init-param-one "value of init param one" init-param-two "value of init param two" servlet (SimpleServlet. body)] (try (add-servlet-handler servlet path {"init-param-one" init-param-one "init-param-two" init-param-two}) (let [response (http-client/get (format "http://localhost:8080/%s/init-param-one" path))] (is (= (:status response) 200)) (is (= (:body response) init-param-one))) (let [response (http-client/get (format "http://localhost:8080/%s/init-param-two" path))] (is (= (:status response) 200)) (is (= (:body response) init-param-two))) (finally (shutdown))))) (testing "webserver bootstrap throws IllegalArgumentException when neither port nor ssl-port specified in the config" (is (thrown-with-msg? IllegalArgumentException #"Either port or ssl-port must be specified on the config in order for a port binding to be opened" (bootstrap-services-with-empty-config [jetty7-service])) "Did not encounter expected exception when no port specified in config")) (testing "ring request over SSL successful for both .jks and .pem implementations with the server's client-auth setting not set and the client configured provide a certificate which the CA can validate" ; Note that if the 'client-auth' setting is not set that the server ; should default to 'need' to validate the client certificate. In this ; case, the validation should be successful because the client is ; providing a certificate which the CA can validate. (doseq [config ["jetty-ssl-jks.ini" "jetty-ssl-pem.ini"]] (bootstrap-and-validate-ring-handler "https://localhost:8081" config default-options-for-https))) (testing "ring request over SSL fails with the server's client-auth setting not set and the client configured to provide a certificate which the CA cannot validate" ; Note that if the 'client-auth' setting is not set that the server ; should default to 'need' to validate the client certificate. In this ; case, the validation should fail because the client is providing a ; certificate which the CA cannot validate. (is (thrown? SSLPeerUnverifiedException (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem.ini" (assoc default-options-for-https :keystore (str test-resources-config-dir "ssl/unauthorized_keystore.jks")))))) (testing "ring request over SSL fails with the server's client-auth setting not set and the client configured to not provide a certificate" ; Note that if the 'client-auth' setting is not set that the server ; should default to 'need' to validate the client certificate. In this ; case, the validation should fail because the client is providing a ; certificate which the CA cannot validate. (is (thrown? SSLPeerUnverifiedException (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem.ini" (assoc default-options-for-https :keystore nil))))) (testing "ring request over SSL succeeds with a server client-auth setting of 'need' and the client configured to provide a certificate which the CA can validate" (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem-client-auth-need.ini" default-options-for-https)) (testing "ring request over SSL fails with a server client-auth setting of 'need' and the client configured to provide a certificate which the CA cannot validate" (is (thrown? SSLPeerUnverifiedException (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem-client-auth-need.ini" (assoc default-options-for-https :keystore (str test-resources-config-dir "ssl/unauthorized_keystore.jks")))))) (testing "ring request over SSL fails with a server client-auth setting of 'need' and the client configured to not provide a certificate" (is (thrown? SSLPeerUnverifiedException (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem-client-auth-need.ini")))) (testing "ring request over SSL succeeds with a server client-auth setting of 'want' and the client configured to provide a certificate which the CA can validate" (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem-client-auth-want.ini" default-options-for-https)) (testing "ring request over SSL fails with a server client-auth setting of 'want' and the client configured to provide a certificate which the CA cannot validate" (is (thrown? SSLPeerUnverifiedException (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem-client-auth-need.ini" (assoc default-options-for-https :keystore (str test-resources-config-dir "ssl/unauthorized_keystore.jks")))))) (testing "ring request over SSL succeeds with a server client-auth setting of 'want' and the client configured to not provide a certificate" (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem-client-auth-want.ini" (assoc default-options-for-https :keystore nil))) (testing "ring request over SSL succeeds with a server client-auth setting of 'none' and the client configured to provide a certificate which the CA can validate" (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem-client-auth-none.ini" default-options-for-https)) (testing "ring request over SSL fails with a server client-auth setting of 'none' and the client configured to provide a certificate which the CA cannot validate" (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem-client-auth-none.ini" (assoc default-options-for-https :keystore (str test-resources-config-dir "ssl/unauthorized_keystore.jks")))) (testing "ring request over SSL succeeds with a server client-auth setting of 'none' and the client configured to not provide a certificate" (bootstrap-and-validate-ring-handler "https://localhost:8081" "jetty-ssl-pem-client-auth-none.ini" (assoc default-options-for-https :keystore nil))))
[ { "context": "-of-speech Ontology\n;;;;\n;;;; @copyright 2019-2020 Dennis Drown et l'Université du Québec à Montréal\n;;;; -------", "end": 388, "score": 0.9998742938041687, "start": 376, "tag": "NAME", "value": "Dennis Drown" } ]
apps/say_sila/priv/fnode/say/src/say/cmu_pos.clj
dendrown/say_sila
0
;;;; ------------------------------------------------------------------------- ;;;; ;;;; _/_/_/ _/_/_/ _/ _/_/ ;;;; _/ _/ _/ _/ _/ ;;;; _/_/ _/ _/ _/_/_/_/ ;;;; _/ _/ _/ _/ _/ ;;;; _/_/_/ _/_/_/ _/_/_/_/ _/ _/ ;;;; ;;;; CMU Part-of-speech Ontology ;;;; ;;;; @copyright 2019-2020 Dennis Drown et l'Université du Québec à Montréal ;;;; ------------------------------------------------------------------------- (ns say.cmu-pos (:require [say.genie :refer :all] [say.ontology :refer :all] [say.config :as cfg] [say.dllearner :as dll] [say.dolce :as dul] [say.log :as log] [say.social :as soc] [clojure.string :as str] [clojure.pprint :refer [pp pprint]] [tawny.reasoner :as rsn] [tawny.repl :as repl] ; <= DEBUG [tawny.owl :refer :all])) ;;; -------------------------------------------------------------------------- (set! *warn-on-reflection* true) (def ^:const ONT-IRI "http://www.dendrown.net/uqam/cmu-pos.owl#") (def ^:const ONT-FPATH "resources/KB/cmu-pos.owl") ;;; -------------------------------------------------------------------------- (defontology cmu-pos :iri ONT-IRI :prefix "pos" :versioninfo "0.1.1") (dul/access) (defclass Token :super dul/InformationObject :label "Token" :comment (str "An Information Object consisting of a single linguistic element of meaning, " "generally in textual or verbal form. A Token very often corresponds to a word, " "but in may also represent punctuation, an emoji, or any other output element from " "the CMU POS tagger.")) (defclass PartOfSpeech :super dul/Quality :label "Part of Speech" :comment (str "A quality describing an appropriate Information Object's part-of-speech" " according to the CMU POS tagging system.")) (defdproperty hasPartOfSpeechTag :domain PartOfSpeech :range :XSD_STRING :label "has part of speech tag" :comment "Defines a descriptive tag used to designate the part of speech of an Information Object." :characteristic :functional) ;;; Specialized object properties? (defoproperty-per (cfg/?? :cmu-pos :oproperties?) isPartOfSpeech :super dul/hasQuality :label "is part of speech" :domain Token :range PartOfSpeech) ;;; -------------------------------------------------------------------------- ;; CMU POS tags are described in \cite{gimpel2011} (defmacro defpos "Adds a PartOfSpeech subclass to the cmu-pos ontology" [pos tag descr] ;; NOTE: We have multiple evaluations of pos, but it is valid here ;; because pos must be a symbol or the defclass will fail. `(do (defclass ~pos :super PartOfSpeech :label (str/join " " (soc/tokenize (name '~pos))) :comment (str "A Part-of-Speech representing " ~descr)) (defpun ~pos) (refine (individual (str '~pos)) :fact (is hasPartOfSpeechTag ~tag)) ;; Are we keeping track of POS data tags in the ontology? (when (cfg/?? :cmu-pos :dproperties?) (refine ~pos :equivalent (has-value hasPartOfSpeechTag ~tag))))) ; !QL and !used ; Nominal, Nominal + Verbal (defpos CommonNoun "N" "a common noun (NN,NNS)") (defpos Pronoun "O" "a pronoun (personal/WH, not possessive; PRP,WP)") (defpos NominalPossessive "S" "a nominal + possessive") (defpos ProperNoun "^" "a proper noun (NNP,NNPS)") (defpos ProperNounPlusPossessive "Z" "a proper noun + possessive") (defpos NominalVerbal "L" "a nominal + verbal") (defpos ProperNounPlusVerbal "M" "a proper noun + verbal") ; Open-class words (defpos Verb "V" "a verb including copula and auxiliaries (V*,MD)") (defpos Adjective "A" "an adjective (J*)") (defpos Adverb "R" "an adverb (R*,WRB)") (defpos Interjection "!" "an interjection (UH)") ; Closed-class words (defpos Determiner "D" "a determiner (WDT,DT,WP$,PRP$)") (defpos CoordinatingConjunction "&" "a coordinating conjunction (CC)") (defpos VerbParticle "T" "a verb particle (RP)") (defpos ExistentialThere "X" "an existential there, predeterminers (EX,PDT)") (defpos ExistentialPlusVerbal "Y" "X+ a verbal") (defpos Preposition "P" "a pre- or postposition, or subordinating conjunction (IN,TO)") ; Twitter/social media (defpos Hashtag "#" "a hashtag (indicates a topic/category for a tweet)") (defpos Address "U" "a URL or email address") (defpos Emoticon "E" "an emoticon") (defpos AtMention "@" "an at-mention (indicating another use as a recipient of a tweet)") (defpos Continuation "~" "an indicator that the message continues across multiple tweets") ; Miscellaneous (defpos Numeral "$" "a numeral (CD)") (defpos Punctuation "," "punctuation") (defpos Other "G" (str "abbreviations, foreign words, possessive endings, " "symbols, or garbage (FW,POS,SYM,LS)")) ;;; Tell DL-Learner about our ontology elements (dll/register-ns) ;;; -------------------------------------------------------------------------- (rsn/reasoner-factory :hermit) (defonce POS (rsn/instances PartOfSpeech)) ; Collect for lookup (defonce POS-Fragments (into {} (map #(vector (:literal (check-fact % hasPartOfSpeechTag)) (iri-fragment %)) POS))) (defonce POS-Codes (into #{} (keys POS-Fragments))) (defonce POS-Names (into #{} (vals POS-Fragments))) ;;; -------------------------------------------------------------------------- (defn lookup "Returns the PartOfSpeech entity corresponding to the specified tag. NOTES: - You probably want to use the (equivalent) memoized lookup# function. - The precomputed POS-Fragments map is an option if you need the POS name." [tag] (when-not (contains? (cfg/?? :cmu-pos :ignore) tag) ;; The caller may be in another namespace, but we need this namespace's ontology (binding [*ns* (find-ns 'say.cmu-pos)] ;; Run through the set of POS enitities until we find a matching tag (reduce #(when (= tag (:literal (check-fact %2 hasPartOfSpeechTag))) (reduced %2)) nil POS)))) (def lookup# (memoize lookup))
109389
;;;; ------------------------------------------------------------------------- ;;;; ;;;; _/_/_/ _/_/_/ _/ _/_/ ;;;; _/ _/ _/ _/ _/ ;;;; _/_/ _/ _/ _/_/_/_/ ;;;; _/ _/ _/ _/ _/ ;;;; _/_/_/ _/_/_/ _/_/_/_/ _/ _/ ;;;; ;;;; CMU Part-of-speech Ontology ;;;; ;;;; @copyright 2019-2020 <NAME> et l'Université du Québec à Montréal ;;;; ------------------------------------------------------------------------- (ns say.cmu-pos (:require [say.genie :refer :all] [say.ontology :refer :all] [say.config :as cfg] [say.dllearner :as dll] [say.dolce :as dul] [say.log :as log] [say.social :as soc] [clojure.string :as str] [clojure.pprint :refer [pp pprint]] [tawny.reasoner :as rsn] [tawny.repl :as repl] ; <= DEBUG [tawny.owl :refer :all])) ;;; -------------------------------------------------------------------------- (set! *warn-on-reflection* true) (def ^:const ONT-IRI "http://www.dendrown.net/uqam/cmu-pos.owl#") (def ^:const ONT-FPATH "resources/KB/cmu-pos.owl") ;;; -------------------------------------------------------------------------- (defontology cmu-pos :iri ONT-IRI :prefix "pos" :versioninfo "0.1.1") (dul/access) (defclass Token :super dul/InformationObject :label "Token" :comment (str "An Information Object consisting of a single linguistic element of meaning, " "generally in textual or verbal form. A Token very often corresponds to a word, " "but in may also represent punctuation, an emoji, or any other output element from " "the CMU POS tagger.")) (defclass PartOfSpeech :super dul/Quality :label "Part of Speech" :comment (str "A quality describing an appropriate Information Object's part-of-speech" " according to the CMU POS tagging system.")) (defdproperty hasPartOfSpeechTag :domain PartOfSpeech :range :XSD_STRING :label "has part of speech tag" :comment "Defines a descriptive tag used to designate the part of speech of an Information Object." :characteristic :functional) ;;; Specialized object properties? (defoproperty-per (cfg/?? :cmu-pos :oproperties?) isPartOfSpeech :super dul/hasQuality :label "is part of speech" :domain Token :range PartOfSpeech) ;;; -------------------------------------------------------------------------- ;; CMU POS tags are described in \cite{gimpel2011} (defmacro defpos "Adds a PartOfSpeech subclass to the cmu-pos ontology" [pos tag descr] ;; NOTE: We have multiple evaluations of pos, but it is valid here ;; because pos must be a symbol or the defclass will fail. `(do (defclass ~pos :super PartOfSpeech :label (str/join " " (soc/tokenize (name '~pos))) :comment (str "A Part-of-Speech representing " ~descr)) (defpun ~pos) (refine (individual (str '~pos)) :fact (is hasPartOfSpeechTag ~tag)) ;; Are we keeping track of POS data tags in the ontology? (when (cfg/?? :cmu-pos :dproperties?) (refine ~pos :equivalent (has-value hasPartOfSpeechTag ~tag))))) ; !QL and !used ; Nominal, Nominal + Verbal (defpos CommonNoun "N" "a common noun (NN,NNS)") (defpos Pronoun "O" "a pronoun (personal/WH, not possessive; PRP,WP)") (defpos NominalPossessive "S" "a nominal + possessive") (defpos ProperNoun "^" "a proper noun (NNP,NNPS)") (defpos ProperNounPlusPossessive "Z" "a proper noun + possessive") (defpos NominalVerbal "L" "a nominal + verbal") (defpos ProperNounPlusVerbal "M" "a proper noun + verbal") ; Open-class words (defpos Verb "V" "a verb including copula and auxiliaries (V*,MD)") (defpos Adjective "A" "an adjective (J*)") (defpos Adverb "R" "an adverb (R*,WRB)") (defpos Interjection "!" "an interjection (UH)") ; Closed-class words (defpos Determiner "D" "a determiner (WDT,DT,WP$,PRP$)") (defpos CoordinatingConjunction "&" "a coordinating conjunction (CC)") (defpos VerbParticle "T" "a verb particle (RP)") (defpos ExistentialThere "X" "an existential there, predeterminers (EX,PDT)") (defpos ExistentialPlusVerbal "Y" "X+ a verbal") (defpos Preposition "P" "a pre- or postposition, or subordinating conjunction (IN,TO)") ; Twitter/social media (defpos Hashtag "#" "a hashtag (indicates a topic/category for a tweet)") (defpos Address "U" "a URL or email address") (defpos Emoticon "E" "an emoticon") (defpos AtMention "@" "an at-mention (indicating another use as a recipient of a tweet)") (defpos Continuation "~" "an indicator that the message continues across multiple tweets") ; Miscellaneous (defpos Numeral "$" "a numeral (CD)") (defpos Punctuation "," "punctuation") (defpos Other "G" (str "abbreviations, foreign words, possessive endings, " "symbols, or garbage (FW,POS,SYM,LS)")) ;;; Tell DL-Learner about our ontology elements (dll/register-ns) ;;; -------------------------------------------------------------------------- (rsn/reasoner-factory :hermit) (defonce POS (rsn/instances PartOfSpeech)) ; Collect for lookup (defonce POS-Fragments (into {} (map #(vector (:literal (check-fact % hasPartOfSpeechTag)) (iri-fragment %)) POS))) (defonce POS-Codes (into #{} (keys POS-Fragments))) (defonce POS-Names (into #{} (vals POS-Fragments))) ;;; -------------------------------------------------------------------------- (defn lookup "Returns the PartOfSpeech entity corresponding to the specified tag. NOTES: - You probably want to use the (equivalent) memoized lookup# function. - The precomputed POS-Fragments map is an option if you need the POS name." [tag] (when-not (contains? (cfg/?? :cmu-pos :ignore) tag) ;; The caller may be in another namespace, but we need this namespace's ontology (binding [*ns* (find-ns 'say.cmu-pos)] ;; Run through the set of POS enitities until we find a matching tag (reduce #(when (= tag (:literal (check-fact %2 hasPartOfSpeechTag))) (reduced %2)) nil POS)))) (def lookup# (memoize lookup))
true
;;;; ------------------------------------------------------------------------- ;;;; ;;;; _/_/_/ _/_/_/ _/ _/_/ ;;;; _/ _/ _/ _/ _/ ;;;; _/_/ _/ _/ _/_/_/_/ ;;;; _/ _/ _/ _/ _/ ;;;; _/_/_/ _/_/_/ _/_/_/_/ _/ _/ ;;;; ;;;; CMU Part-of-speech Ontology ;;;; ;;;; @copyright 2019-2020 PI:NAME:<NAME>END_PI et l'Université du Québec à Montréal ;;;; ------------------------------------------------------------------------- (ns say.cmu-pos (:require [say.genie :refer :all] [say.ontology :refer :all] [say.config :as cfg] [say.dllearner :as dll] [say.dolce :as dul] [say.log :as log] [say.social :as soc] [clojure.string :as str] [clojure.pprint :refer [pp pprint]] [tawny.reasoner :as rsn] [tawny.repl :as repl] ; <= DEBUG [tawny.owl :refer :all])) ;;; -------------------------------------------------------------------------- (set! *warn-on-reflection* true) (def ^:const ONT-IRI "http://www.dendrown.net/uqam/cmu-pos.owl#") (def ^:const ONT-FPATH "resources/KB/cmu-pos.owl") ;;; -------------------------------------------------------------------------- (defontology cmu-pos :iri ONT-IRI :prefix "pos" :versioninfo "0.1.1") (dul/access) (defclass Token :super dul/InformationObject :label "Token" :comment (str "An Information Object consisting of a single linguistic element of meaning, " "generally in textual or verbal form. A Token very often corresponds to a word, " "but in may also represent punctuation, an emoji, or any other output element from " "the CMU POS tagger.")) (defclass PartOfSpeech :super dul/Quality :label "Part of Speech" :comment (str "A quality describing an appropriate Information Object's part-of-speech" " according to the CMU POS tagging system.")) (defdproperty hasPartOfSpeechTag :domain PartOfSpeech :range :XSD_STRING :label "has part of speech tag" :comment "Defines a descriptive tag used to designate the part of speech of an Information Object." :characteristic :functional) ;;; Specialized object properties? (defoproperty-per (cfg/?? :cmu-pos :oproperties?) isPartOfSpeech :super dul/hasQuality :label "is part of speech" :domain Token :range PartOfSpeech) ;;; -------------------------------------------------------------------------- ;; CMU POS tags are described in \cite{gimpel2011} (defmacro defpos "Adds a PartOfSpeech subclass to the cmu-pos ontology" [pos tag descr] ;; NOTE: We have multiple evaluations of pos, but it is valid here ;; because pos must be a symbol or the defclass will fail. `(do (defclass ~pos :super PartOfSpeech :label (str/join " " (soc/tokenize (name '~pos))) :comment (str "A Part-of-Speech representing " ~descr)) (defpun ~pos) (refine (individual (str '~pos)) :fact (is hasPartOfSpeechTag ~tag)) ;; Are we keeping track of POS data tags in the ontology? (when (cfg/?? :cmu-pos :dproperties?) (refine ~pos :equivalent (has-value hasPartOfSpeechTag ~tag))))) ; !QL and !used ; Nominal, Nominal + Verbal (defpos CommonNoun "N" "a common noun (NN,NNS)") (defpos Pronoun "O" "a pronoun (personal/WH, not possessive; PRP,WP)") (defpos NominalPossessive "S" "a nominal + possessive") (defpos ProperNoun "^" "a proper noun (NNP,NNPS)") (defpos ProperNounPlusPossessive "Z" "a proper noun + possessive") (defpos NominalVerbal "L" "a nominal + verbal") (defpos ProperNounPlusVerbal "M" "a proper noun + verbal") ; Open-class words (defpos Verb "V" "a verb including copula and auxiliaries (V*,MD)") (defpos Adjective "A" "an adjective (J*)") (defpos Adverb "R" "an adverb (R*,WRB)") (defpos Interjection "!" "an interjection (UH)") ; Closed-class words (defpos Determiner "D" "a determiner (WDT,DT,WP$,PRP$)") (defpos CoordinatingConjunction "&" "a coordinating conjunction (CC)") (defpos VerbParticle "T" "a verb particle (RP)") (defpos ExistentialThere "X" "an existential there, predeterminers (EX,PDT)") (defpos ExistentialPlusVerbal "Y" "X+ a verbal") (defpos Preposition "P" "a pre- or postposition, or subordinating conjunction (IN,TO)") ; Twitter/social media (defpos Hashtag "#" "a hashtag (indicates a topic/category for a tweet)") (defpos Address "U" "a URL or email address") (defpos Emoticon "E" "an emoticon") (defpos AtMention "@" "an at-mention (indicating another use as a recipient of a tweet)") (defpos Continuation "~" "an indicator that the message continues across multiple tweets") ; Miscellaneous (defpos Numeral "$" "a numeral (CD)") (defpos Punctuation "," "punctuation") (defpos Other "G" (str "abbreviations, foreign words, possessive endings, " "symbols, or garbage (FW,POS,SYM,LS)")) ;;; Tell DL-Learner about our ontology elements (dll/register-ns) ;;; -------------------------------------------------------------------------- (rsn/reasoner-factory :hermit) (defonce POS (rsn/instances PartOfSpeech)) ; Collect for lookup (defonce POS-Fragments (into {} (map #(vector (:literal (check-fact % hasPartOfSpeechTag)) (iri-fragment %)) POS))) (defonce POS-Codes (into #{} (keys POS-Fragments))) (defonce POS-Names (into #{} (vals POS-Fragments))) ;;; -------------------------------------------------------------------------- (defn lookup "Returns the PartOfSpeech entity corresponding to the specified tag. NOTES: - You probably want to use the (equivalent) memoized lookup# function. - The precomputed POS-Fragments map is an option if you need the POS name." [tag] (when-not (contains? (cfg/?? :cmu-pos :ignore) tag) ;; The caller may be in another namespace, but we need this namespace's ontology (binding [*ns* (find-ns 'say.cmu-pos)] ;; Run through the set of POS enitities until we find a matching tag (reduce #(when (= tag (:literal (check-fact %2 hasPartOfSpeechTag))) (reduced %2)) nil POS)))) (def lookup# (memoize lookup))
[ { "context": ";;\n;;\n;; Copyright 2013-2015 Netflix, Inc.\n;;\n;; Licensed under the Apache Lic", "end": 33, "score": 0.8333535194396973, "start": 30, "tag": "NAME", "value": "Net" } ]
pigpen-core/src/main/clojure/pigpen/raw.clj
ombagus/Netflix
327
;; ;; ;; Copyright 2013-2015 Netflix, Inc. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns pigpen.raw "Contains functions that create basic commands. These are the primitive building blocks for more complex operations." (:require [pigpen.model :as m] [schema.core :as s])) (set! *warn-on-reflection* true) (defn pigsym "Wraps gensym to facilitate easier mocking" [prefix-string] (gensym prefix-string)) (defn update-ns [ns sym] (symbol (name ns) (name sym))) (defn update-ns+ [ns sym] (if (or (namespace sym) (nil? ns)) sym (update-ns ns sym))) ;; ********** (s/defn ^:private command ([type opts] ^:pig {:type type :id (pigsym (name type)) :description (:description opts) :field-type (get opts :field-type :frozen) :opts (-> opts (assoc :type (-> type name (str "-opts") keyword)) (dissoc :description :field-type))}) ([type relation opts] {:pre [(map? relation)]} (let [{id :id, :as c} (command type opts)] (assoc c :ancestors [relation] :fields (mapv (partial update-ns id) (:fields relation))))) ([type ancestors fields opts] {:pre [(sequential? ancestors) (sequential? fields)]} (let [{id :id, :as c} (command type opts)] (assoc c :ancestors (vec ancestors) :fields (mapv (partial update-ns+ id) fields))))) ;; ********** Util ********** (s/defn code$ :- m/CodeExpr "Encapsulation for user code. Used with projection-func$ and project$. You probably want bind$ instead of this. The parameter `udf` should be one of: :seq - returns zero or more values :fold - apply a fold aggregation The parameter `init` is code to be executed once before the user code, `func` is the user code to execute, and `args` specifies which fields should be passed to `func`. `args` can also contain strings, which are passed through as constants to the user code. The result of `func` should be in the same format as bind$. Example: (code$ :seq '(require my-ns.core) '(fn [args] ...) ['c 'd]) See also: pigpen.core.op/project$, pigpen.core.op/projection-func$ " {:added "0.3.0"} [udf init func args] ^:pig {:type :code :init init :func func :udf udf :args (vec args)}) ;; ********** IO ********** (s/defn load$ :- m/Load$ "Load the data specified by `location`, a string. The parameter `storage` is a keyword such as :string, :parquet, or :avro that specifies the type of storage to use. Each platform is responsible for dispatching on storage as appropriate. The parameters `fields` and `opts` specify what fields this will produce and any options to the command. Example: (load$ \"input.tsv\" :string '[value] {}) See also: pigpen.core.op/store$ " {:added "0.3.0"} [location storage fields opts] (let [id (pigsym "load")] ^:pig {:type :load :id id :description location :location location :fields (mapv (partial update-ns+ id) fields) :field-type (get opts :field-type :native) :storage storage :opts (assoc opts :type :load-opts)})) (s/defn store$ :- m/Store$ "Store the data specified by `location`, a string. The parameter `storage` is a keyword such as :string, :parquet, or :avro that specifies the type of storage to use. Each platform is responsible for dispatching on storage as appropriate. The parameter `opts` specify any options to the command. This command can only be passed to store-many$ commands or to platform generation commands. Example: (store$ \"output.tsv\" :string {} relation) See also: pigpen.core.op/load$ " {:added "0.3.0"} [location storage opts relation] (-> (command :store relation opts) (dissoc :field-type :fields) (assoc :location location :storage storage :description location :args (:fields relation)))) (s/defn store-many$ :- m/StoreMany$ "Combines multiple store$ commands into a single command. This command can only be passed to other store-many$ commands or to platform generation commands. Example: (store-many$ [(store$ \"output1.tsv\" :string {} relation1) (store$ \"output2.tsv\" :string {} relation2)]) See also: pigpen.core.op/store$ " [outputs] ^:pig {:type :store-many :id (pigsym "store-many") :ancestors (vec outputs)}) (s/defn return$ :- m/Return$ "Return the data as a PigPen relation. The parameter `fields` specifies what fields the data will contain. Example: (return$ ['value] [{'value 42} {'value 37}]) See also: pigpen.core.op/load$ " {:added "0.3.0"} [fields data] (let [id (pigsym "return")] ^:pig {:type :return :id id :field-type :frozen :fields (mapv (partial update-ns+ id) fields) :data (for [m data] (->> m (map (fn [[f v]] [(update-ns+ id f) v])) (into {})))})) ;; ********** Map ********** (defn projection-field$ "Project a single field into another, optionally providing an alias for the new field. If an alias is not specified, the input field name is used. If the field represents a collection, specify `flatten` as true to flatten the values of the field into individual records. Examples: (projection-field$ 'a) ;; copy the field a as a (projection-field$ 'a 'b) ;; copy the field a as b (projection-field$ 'a 'b true) ;; copy the field a as b and flatten a See also: pigpen.core.op/project$, pigpen.core.op/projection-func$ " {:added "0.3.0"} ([field] (projection-field$ field [(symbol (name field))] false)) ([field alias] (projection-field$ field alias false)) ([field alias flatten] ^:pig {:type :projection :expr {:type :field :field field} :flatten flatten :alias alias})) (s/defn projection-func$ "Apply code to a set of fields, optionally flattening the result. See code$ for details regarding how to express user code. Examples: (projection-func$ 'a (code$ ...)) ;; scalar result (projection-func$ 'a (code$ ...) true) ;; flatten the result collection See also: pigpen.core.op/code$, pigpen.core.op/project$, pigpen.core.op/projection-field$ " {:added "0.3.0"} ([alias code :- m/CodeExpr] (projection-func$ alias true code)) ([alias flatten code :- m/CodeExpr] ^:pig {:type :projection :expr code :flatten flatten :alias alias})) (defn ^:private update-alias-ns [id projection] (update-in projection [:alias] (partial mapv (partial update-ns id)))) (s/defn project$* :- m/Project "Used to make a post-bake project" [projections opts relation] (let [{id :id, :as c} (command :project opts)] (-> c (assoc :projections (mapv (partial update-alias-ns id) projections) :ancestors [relation] :fields (mapv (partial update-ns id) (mapcat :alias projections)))))) (s/defn project$ :- m/Project$ "Used to manipulate the fields of a relation, either by aliasing them or applying functions to them. Usually you want bind$ instead of project$, as PigPen will compile many of the former into one of the latter. Example: (project$ [(projection-field$ 'a 'b) (projection-func$ 'e (code$ :seq '(require my-ns.core) '(fn [args] ...) ['c 'd]))] {} relation) In the example above, we apply two operations to the input relation. First, we alias the input field 'a as 'b. Second, we apply the user code specified by code$ to the fields 'c and 'd to produce the field 'e. This implies that the input relation has three fields, 'a, 'c, and 'd, and that the output fields of this relation are 'b and 'e. If multiple projections are provided that flatten results, the cross product of those is returned. See also: pigpen.core.op/projection-field$, pigpen.core.op/projection-func$, pigpen.core.op/code$ " {:added "0.3.0"} [projections opts relation] (let [{id :id, :as c} (command :project relation opts)] (-> c (assoc :projections (mapv (partial update-alias-ns id) projections) :fields (mapv (partial update-ns id) (mapcat :alias projections)))))) (s/defn bind$ :- m/Bind$ "The way to apply user code to a relation. `func` should be a function that takes a collection of arguments, and returns a collection of result tuples. Optionally takes a collection of namespaces to require before executing user code. Example: (bind$ (fn [args] ;; do stuff to args, return a value like this: [[foo-value bar-value] ;; result 1 [foo-value bar-value] ;; result 2 ... [foo-value bar-value]]) ;; result N {:args '[x y] :alias '[foo bar]} relation) In this example, our function takes `args` which is a tuple of argument values from the previous relation. Here, this selects the fields x and y. The function then returns 0-to-many result tuples. Each of those tuples maps to the fields specified by the alias option. If not specified, args defaults to the fields of the input relation and alias defaults to a single field `value`. All field names should be symbols. There are many provided bind helper functions, such as map->bind, that take a normal map function of one arg to one result, and convert it to a bind function. (bind$ (map->bind (fn [x] (* x x))) {} data) See also: pigpen.core.fn/map->bind, pigpen.core.fn/mapcat->bind, pigpen.core.fn/filter->bind, pigpen.core.fn/process->bind, pigpen.core.fn/key-selector->bind, pigpen.core.fn/keyword-field-selector->bind, pigpen.core.fn/indexed-field-selector->bind " {:added "0.3.0"} ([func opts relation] (bind$ [] func opts relation)) ([requires func opts relation] (let [opts' (dissoc opts :args :requires :alias :types :field-type-in :field-type) {id :id, :as c} (command :bind relation opts')] (-> c (dissoc :field-type) (assoc :func func :args (vec (or (->> (get opts :args) (map (fn [a] (if (string? a) a (update-ns+ (:id relation) a)))) seq) (get relation :fields))) :requires (vec (concat requires (:requires opts))) :fields (mapv (partial update-ns+ id) (get opts :alias ['value])) :field-type-in (get opts :field-type-in :frozen) :field-type (get opts :field-type :frozen) :types (get opts :types)))))) (s/defn sort$ :- m/Sort$ "Sort the data in relation. The parameter `key` specifies the field that should be used to sort the data. The sort field should be a native type; not serialized. `comp` is either :asc or :desc. Example: (sort$ 'key :asc {} relation) " {:added "0.3.0"} [key comp opts relation] (let [{id :id, :as c} (command :sort relation opts)] (-> c (assoc :key (update-ns+ (:id relation) key)) (assoc :comp comp) (update-in [:fields] (partial remove #{(update-ns+ id key)}))))) (s/defn rank$ :- m/Rank$ "Rank the input relation. Adds a new field ('index), a long, to the fields of the input relation. Example: (rank$ {} relation) See also: pigpen.core.op/sort$ " {:added "0.3.0"} [opts relation] (let [{id :id, :as c} (command :rank relation opts)] (-> c (update-in [:fields] (partial cons (update-ns+ id 'index)))))) ;; ********** Filter ********** (s/defn filter$* :- m/Filter "Used to make a post-bake filter" [fields expr opts relation] {:pre [(symbol? relation)]} (-> (command :filter opts) (assoc :expr expr :fields (vec fields) :ancestors [relation] :field-type :native))) (s/defn filter$ :- m/Filter$ [expr opts relation] (-> (command :filter relation opts) (assoc :expr expr :field-type :native))) (s/defn take$ :- m/Take$ "Returns the first n records from relation. Example: (take$ 100 {} relation) See also: pigpen.core.op/sample$ " {:added "0.3.0"} [n opts relation] (-> (command :take relation opts) (assoc :n n))) (s/defn sample$ :- m/Sample$ "Samples the input relation at percentage p, where (<= 0.0 p 1.0). Example: (sample$ 0.5 {} relation) See also: pigpen.core.op/take$ " {:added "0.3.0"} [p opts relation] (-> (command :sample relation opts) (assoc :p p))) ;; ********** Set ********** (s/defn distinct$ :- m/Distinct$ "Returns the distinct values in relation. Example: (distinct$ {} relation) See also: pigpen.core.op/concat$ " {:added "0.3.0"} [opts relation] (command :distinct relation opts)) (s/defn concat$ :- (s/either m/Concat$ m/Op) "Concatenates the set of ancestor relations together. The fields produced by the concat operation are the fields of the first relation. Example: (concat$ {} [relation1 relation2]) See also: pigpen.core.op/distinct$ " {:added "0.3.0"} [opts ancestors] (if-not (next ancestors) (first ancestors) (command :concat ancestors (->> ancestors first :fields (map (comp symbol name))) opts))) ;; ********** Join ********** (s/defn reduce$ :- m/Reduce$ "Reduce the entire relation into a single recrod that is the collection of all records. Example: (reduce$ {} relation) See also: pigpen.core.op/group$ " {:added "0.3.0"} [opts relation] (-> (command :reduce relation opts) (assoc :fields [(-> relation :fields first)]) (assoc :arg (-> relation :fields first)))) (defmulti ancestors->fields "Get the set of fields produced by the ancestors and this command." (fn [type id ancestors] type)) (defmulti fields->keys "Determine which fields are the keys to be used for grouping/joining." (fn [type fields] type)) (s/defn group$ :- m/Group$ "Performs a cogroup on the ancestors provided. The parameter `field-dispatch` should be one of the following, and produces the following output fields: :group - [group r0/key r0/value ... rN/key rN/value] :join - [r0/key r0/value ... rN/key rN/value] :set - [r0/value ... rN/value] The parameter `join-types` is a vector of keywords (:required or :optional) specifying if each relation is required or optional. The length of join-types must match the number of relations passed. Example: (group$ :group [:required :optional] {} [relation1 relation2]) In this example, the operation performs a cogroup on relation1 and relation2. The `:group` field-dispatch means that both of those relations will provide a field with fields `key` and `value`, and the operation will add a `group` field. The first relation is marked as required and the second is optional. See also: pigpen.core.op/join$ " {:added "0.3.0"} [field-dispatch join-types opts ancestors] (let [{id :id, :as c} (command :group ancestors [] opts) fields (ancestors->fields field-dispatch id ancestors)] (-> c (assoc :field-dispatch field-dispatch :fields fields :keys (fields->keys field-dispatch fields) :join-types (vec join-types))))) (s/defn join$ :- m/Join$ "Performs a join on the ancestors provided. The parameter `field-dispatch` should be one of the following, and produces the following output fields: :group - [group r0/key r0/value ... rN/key rN/value] :join - [r0/key r0/value ... rN/key rN/value] :set - [r0/value ... rN/value] The parameter `join-types` is a vector of keywords (:required or :optional) specifying if each relation is required or optional. The length of join-types must match the number of relations passed. Example: (join$ :join [:required :optional] {} [relation1 relation2]) In this example, the operation performs a join on relation1 and relation2. The `:join` field-dispatch means that both of those relations will provide a field with fields `key` and `value`. The first relation is marked as required and the second is optional. See also: pigpen.core.op/group$ " {:added "0.3.0"} [field-dispatch join-types opts ancestors] {:pre [(< 1 (count ancestors)) (or (every? #{:required} join-types) (= 2 (count ancestors))) (sequential? ancestors) (sequential? join-types) (= (count ancestors) (count join-types))]} (let [{id :id, :as c} (command :join ancestors [] opts) fields (ancestors->fields field-dispatch nil ancestors)] (-> c (assoc :field-dispatch field-dispatch :fields fields :keys (fields->keys field-dispatch fields) :join-types (vec join-types))))) ;; ********** Script ********** (s/defn noop$ :- m/NoOp$ "A no-op command. This is used to introduce a unique id for a command. Example: (noop$ {} relation) " {:added "0.3.0"} [opts relation] (-> (command :noop relation opts) (assoc :args (:fields relation))))
114488
;; ;; ;; Copyright 2013-2015 <NAME>flix, Inc. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns pigpen.raw "Contains functions that create basic commands. These are the primitive building blocks for more complex operations." (:require [pigpen.model :as m] [schema.core :as s])) (set! *warn-on-reflection* true) (defn pigsym "Wraps gensym to facilitate easier mocking" [prefix-string] (gensym prefix-string)) (defn update-ns [ns sym] (symbol (name ns) (name sym))) (defn update-ns+ [ns sym] (if (or (namespace sym) (nil? ns)) sym (update-ns ns sym))) ;; ********** (s/defn ^:private command ([type opts] ^:pig {:type type :id (pigsym (name type)) :description (:description opts) :field-type (get opts :field-type :frozen) :opts (-> opts (assoc :type (-> type name (str "-opts") keyword)) (dissoc :description :field-type))}) ([type relation opts] {:pre [(map? relation)]} (let [{id :id, :as c} (command type opts)] (assoc c :ancestors [relation] :fields (mapv (partial update-ns id) (:fields relation))))) ([type ancestors fields opts] {:pre [(sequential? ancestors) (sequential? fields)]} (let [{id :id, :as c} (command type opts)] (assoc c :ancestors (vec ancestors) :fields (mapv (partial update-ns+ id) fields))))) ;; ********** Util ********** (s/defn code$ :- m/CodeExpr "Encapsulation for user code. Used with projection-func$ and project$. You probably want bind$ instead of this. The parameter `udf` should be one of: :seq - returns zero or more values :fold - apply a fold aggregation The parameter `init` is code to be executed once before the user code, `func` is the user code to execute, and `args` specifies which fields should be passed to `func`. `args` can also contain strings, which are passed through as constants to the user code. The result of `func` should be in the same format as bind$. Example: (code$ :seq '(require my-ns.core) '(fn [args] ...) ['c 'd]) See also: pigpen.core.op/project$, pigpen.core.op/projection-func$ " {:added "0.3.0"} [udf init func args] ^:pig {:type :code :init init :func func :udf udf :args (vec args)}) ;; ********** IO ********** (s/defn load$ :- m/Load$ "Load the data specified by `location`, a string. The parameter `storage` is a keyword such as :string, :parquet, or :avro that specifies the type of storage to use. Each platform is responsible for dispatching on storage as appropriate. The parameters `fields` and `opts` specify what fields this will produce and any options to the command. Example: (load$ \"input.tsv\" :string '[value] {}) See also: pigpen.core.op/store$ " {:added "0.3.0"} [location storage fields opts] (let [id (pigsym "load")] ^:pig {:type :load :id id :description location :location location :fields (mapv (partial update-ns+ id) fields) :field-type (get opts :field-type :native) :storage storage :opts (assoc opts :type :load-opts)})) (s/defn store$ :- m/Store$ "Store the data specified by `location`, a string. The parameter `storage` is a keyword such as :string, :parquet, or :avro that specifies the type of storage to use. Each platform is responsible for dispatching on storage as appropriate. The parameter `opts` specify any options to the command. This command can only be passed to store-many$ commands or to platform generation commands. Example: (store$ \"output.tsv\" :string {} relation) See also: pigpen.core.op/load$ " {:added "0.3.0"} [location storage opts relation] (-> (command :store relation opts) (dissoc :field-type :fields) (assoc :location location :storage storage :description location :args (:fields relation)))) (s/defn store-many$ :- m/StoreMany$ "Combines multiple store$ commands into a single command. This command can only be passed to other store-many$ commands or to platform generation commands. Example: (store-many$ [(store$ \"output1.tsv\" :string {} relation1) (store$ \"output2.tsv\" :string {} relation2)]) See also: pigpen.core.op/store$ " [outputs] ^:pig {:type :store-many :id (pigsym "store-many") :ancestors (vec outputs)}) (s/defn return$ :- m/Return$ "Return the data as a PigPen relation. The parameter `fields` specifies what fields the data will contain. Example: (return$ ['value] [{'value 42} {'value 37}]) See also: pigpen.core.op/load$ " {:added "0.3.0"} [fields data] (let [id (pigsym "return")] ^:pig {:type :return :id id :field-type :frozen :fields (mapv (partial update-ns+ id) fields) :data (for [m data] (->> m (map (fn [[f v]] [(update-ns+ id f) v])) (into {})))})) ;; ********** Map ********** (defn projection-field$ "Project a single field into another, optionally providing an alias for the new field. If an alias is not specified, the input field name is used. If the field represents a collection, specify `flatten` as true to flatten the values of the field into individual records. Examples: (projection-field$ 'a) ;; copy the field a as a (projection-field$ 'a 'b) ;; copy the field a as b (projection-field$ 'a 'b true) ;; copy the field a as b and flatten a See also: pigpen.core.op/project$, pigpen.core.op/projection-func$ " {:added "0.3.0"} ([field] (projection-field$ field [(symbol (name field))] false)) ([field alias] (projection-field$ field alias false)) ([field alias flatten] ^:pig {:type :projection :expr {:type :field :field field} :flatten flatten :alias alias})) (s/defn projection-func$ "Apply code to a set of fields, optionally flattening the result. See code$ for details regarding how to express user code. Examples: (projection-func$ 'a (code$ ...)) ;; scalar result (projection-func$ 'a (code$ ...) true) ;; flatten the result collection See also: pigpen.core.op/code$, pigpen.core.op/project$, pigpen.core.op/projection-field$ " {:added "0.3.0"} ([alias code :- m/CodeExpr] (projection-func$ alias true code)) ([alias flatten code :- m/CodeExpr] ^:pig {:type :projection :expr code :flatten flatten :alias alias})) (defn ^:private update-alias-ns [id projection] (update-in projection [:alias] (partial mapv (partial update-ns id)))) (s/defn project$* :- m/Project "Used to make a post-bake project" [projections opts relation] (let [{id :id, :as c} (command :project opts)] (-> c (assoc :projections (mapv (partial update-alias-ns id) projections) :ancestors [relation] :fields (mapv (partial update-ns id) (mapcat :alias projections)))))) (s/defn project$ :- m/Project$ "Used to manipulate the fields of a relation, either by aliasing them or applying functions to them. Usually you want bind$ instead of project$, as PigPen will compile many of the former into one of the latter. Example: (project$ [(projection-field$ 'a 'b) (projection-func$ 'e (code$ :seq '(require my-ns.core) '(fn [args] ...) ['c 'd]))] {} relation) In the example above, we apply two operations to the input relation. First, we alias the input field 'a as 'b. Second, we apply the user code specified by code$ to the fields 'c and 'd to produce the field 'e. This implies that the input relation has three fields, 'a, 'c, and 'd, and that the output fields of this relation are 'b and 'e. If multiple projections are provided that flatten results, the cross product of those is returned. See also: pigpen.core.op/projection-field$, pigpen.core.op/projection-func$, pigpen.core.op/code$ " {:added "0.3.0"} [projections opts relation] (let [{id :id, :as c} (command :project relation opts)] (-> c (assoc :projections (mapv (partial update-alias-ns id) projections) :fields (mapv (partial update-ns id) (mapcat :alias projections)))))) (s/defn bind$ :- m/Bind$ "The way to apply user code to a relation. `func` should be a function that takes a collection of arguments, and returns a collection of result tuples. Optionally takes a collection of namespaces to require before executing user code. Example: (bind$ (fn [args] ;; do stuff to args, return a value like this: [[foo-value bar-value] ;; result 1 [foo-value bar-value] ;; result 2 ... [foo-value bar-value]]) ;; result N {:args '[x y] :alias '[foo bar]} relation) In this example, our function takes `args` which is a tuple of argument values from the previous relation. Here, this selects the fields x and y. The function then returns 0-to-many result tuples. Each of those tuples maps to the fields specified by the alias option. If not specified, args defaults to the fields of the input relation and alias defaults to a single field `value`. All field names should be symbols. There are many provided bind helper functions, such as map->bind, that take a normal map function of one arg to one result, and convert it to a bind function. (bind$ (map->bind (fn [x] (* x x))) {} data) See also: pigpen.core.fn/map->bind, pigpen.core.fn/mapcat->bind, pigpen.core.fn/filter->bind, pigpen.core.fn/process->bind, pigpen.core.fn/key-selector->bind, pigpen.core.fn/keyword-field-selector->bind, pigpen.core.fn/indexed-field-selector->bind " {:added "0.3.0"} ([func opts relation] (bind$ [] func opts relation)) ([requires func opts relation] (let [opts' (dissoc opts :args :requires :alias :types :field-type-in :field-type) {id :id, :as c} (command :bind relation opts')] (-> c (dissoc :field-type) (assoc :func func :args (vec (or (->> (get opts :args) (map (fn [a] (if (string? a) a (update-ns+ (:id relation) a)))) seq) (get relation :fields))) :requires (vec (concat requires (:requires opts))) :fields (mapv (partial update-ns+ id) (get opts :alias ['value])) :field-type-in (get opts :field-type-in :frozen) :field-type (get opts :field-type :frozen) :types (get opts :types)))))) (s/defn sort$ :- m/Sort$ "Sort the data in relation. The parameter `key` specifies the field that should be used to sort the data. The sort field should be a native type; not serialized. `comp` is either :asc or :desc. Example: (sort$ 'key :asc {} relation) " {:added "0.3.0"} [key comp opts relation] (let [{id :id, :as c} (command :sort relation opts)] (-> c (assoc :key (update-ns+ (:id relation) key)) (assoc :comp comp) (update-in [:fields] (partial remove #{(update-ns+ id key)}))))) (s/defn rank$ :- m/Rank$ "Rank the input relation. Adds a new field ('index), a long, to the fields of the input relation. Example: (rank$ {} relation) See also: pigpen.core.op/sort$ " {:added "0.3.0"} [opts relation] (let [{id :id, :as c} (command :rank relation opts)] (-> c (update-in [:fields] (partial cons (update-ns+ id 'index)))))) ;; ********** Filter ********** (s/defn filter$* :- m/Filter "Used to make a post-bake filter" [fields expr opts relation] {:pre [(symbol? relation)]} (-> (command :filter opts) (assoc :expr expr :fields (vec fields) :ancestors [relation] :field-type :native))) (s/defn filter$ :- m/Filter$ [expr opts relation] (-> (command :filter relation opts) (assoc :expr expr :field-type :native))) (s/defn take$ :- m/Take$ "Returns the first n records from relation. Example: (take$ 100 {} relation) See also: pigpen.core.op/sample$ " {:added "0.3.0"} [n opts relation] (-> (command :take relation opts) (assoc :n n))) (s/defn sample$ :- m/Sample$ "Samples the input relation at percentage p, where (<= 0.0 p 1.0). Example: (sample$ 0.5 {} relation) See also: pigpen.core.op/take$ " {:added "0.3.0"} [p opts relation] (-> (command :sample relation opts) (assoc :p p))) ;; ********** Set ********** (s/defn distinct$ :- m/Distinct$ "Returns the distinct values in relation. Example: (distinct$ {} relation) See also: pigpen.core.op/concat$ " {:added "0.3.0"} [opts relation] (command :distinct relation opts)) (s/defn concat$ :- (s/either m/Concat$ m/Op) "Concatenates the set of ancestor relations together. The fields produced by the concat operation are the fields of the first relation. Example: (concat$ {} [relation1 relation2]) See also: pigpen.core.op/distinct$ " {:added "0.3.0"} [opts ancestors] (if-not (next ancestors) (first ancestors) (command :concat ancestors (->> ancestors first :fields (map (comp symbol name))) opts))) ;; ********** Join ********** (s/defn reduce$ :- m/Reduce$ "Reduce the entire relation into a single recrod that is the collection of all records. Example: (reduce$ {} relation) See also: pigpen.core.op/group$ " {:added "0.3.0"} [opts relation] (-> (command :reduce relation opts) (assoc :fields [(-> relation :fields first)]) (assoc :arg (-> relation :fields first)))) (defmulti ancestors->fields "Get the set of fields produced by the ancestors and this command." (fn [type id ancestors] type)) (defmulti fields->keys "Determine which fields are the keys to be used for grouping/joining." (fn [type fields] type)) (s/defn group$ :- m/Group$ "Performs a cogroup on the ancestors provided. The parameter `field-dispatch` should be one of the following, and produces the following output fields: :group - [group r0/key r0/value ... rN/key rN/value] :join - [r0/key r0/value ... rN/key rN/value] :set - [r0/value ... rN/value] The parameter `join-types` is a vector of keywords (:required or :optional) specifying if each relation is required or optional. The length of join-types must match the number of relations passed. Example: (group$ :group [:required :optional] {} [relation1 relation2]) In this example, the operation performs a cogroup on relation1 and relation2. The `:group` field-dispatch means that both of those relations will provide a field with fields `key` and `value`, and the operation will add a `group` field. The first relation is marked as required and the second is optional. See also: pigpen.core.op/join$ " {:added "0.3.0"} [field-dispatch join-types opts ancestors] (let [{id :id, :as c} (command :group ancestors [] opts) fields (ancestors->fields field-dispatch id ancestors)] (-> c (assoc :field-dispatch field-dispatch :fields fields :keys (fields->keys field-dispatch fields) :join-types (vec join-types))))) (s/defn join$ :- m/Join$ "Performs a join on the ancestors provided. The parameter `field-dispatch` should be one of the following, and produces the following output fields: :group - [group r0/key r0/value ... rN/key rN/value] :join - [r0/key r0/value ... rN/key rN/value] :set - [r0/value ... rN/value] The parameter `join-types` is a vector of keywords (:required or :optional) specifying if each relation is required or optional. The length of join-types must match the number of relations passed. Example: (join$ :join [:required :optional] {} [relation1 relation2]) In this example, the operation performs a join on relation1 and relation2. The `:join` field-dispatch means that both of those relations will provide a field with fields `key` and `value`. The first relation is marked as required and the second is optional. See also: pigpen.core.op/group$ " {:added "0.3.0"} [field-dispatch join-types opts ancestors] {:pre [(< 1 (count ancestors)) (or (every? #{:required} join-types) (= 2 (count ancestors))) (sequential? ancestors) (sequential? join-types) (= (count ancestors) (count join-types))]} (let [{id :id, :as c} (command :join ancestors [] opts) fields (ancestors->fields field-dispatch nil ancestors)] (-> c (assoc :field-dispatch field-dispatch :fields fields :keys (fields->keys field-dispatch fields) :join-types (vec join-types))))) ;; ********** Script ********** (s/defn noop$ :- m/NoOp$ "A no-op command. This is used to introduce a unique id for a command. Example: (noop$ {} relation) " {:added "0.3.0"} [opts relation] (-> (command :noop relation opts) (assoc :args (:fields relation))))
true
;; ;; ;; Copyright 2013-2015 PI:NAME:<NAME>END_PIflix, Inc. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns pigpen.raw "Contains functions that create basic commands. These are the primitive building blocks for more complex operations." (:require [pigpen.model :as m] [schema.core :as s])) (set! *warn-on-reflection* true) (defn pigsym "Wraps gensym to facilitate easier mocking" [prefix-string] (gensym prefix-string)) (defn update-ns [ns sym] (symbol (name ns) (name sym))) (defn update-ns+ [ns sym] (if (or (namespace sym) (nil? ns)) sym (update-ns ns sym))) ;; ********** (s/defn ^:private command ([type opts] ^:pig {:type type :id (pigsym (name type)) :description (:description opts) :field-type (get opts :field-type :frozen) :opts (-> opts (assoc :type (-> type name (str "-opts") keyword)) (dissoc :description :field-type))}) ([type relation opts] {:pre [(map? relation)]} (let [{id :id, :as c} (command type opts)] (assoc c :ancestors [relation] :fields (mapv (partial update-ns id) (:fields relation))))) ([type ancestors fields opts] {:pre [(sequential? ancestors) (sequential? fields)]} (let [{id :id, :as c} (command type opts)] (assoc c :ancestors (vec ancestors) :fields (mapv (partial update-ns+ id) fields))))) ;; ********** Util ********** (s/defn code$ :- m/CodeExpr "Encapsulation for user code. Used with projection-func$ and project$. You probably want bind$ instead of this. The parameter `udf` should be one of: :seq - returns zero or more values :fold - apply a fold aggregation The parameter `init` is code to be executed once before the user code, `func` is the user code to execute, and `args` specifies which fields should be passed to `func`. `args` can also contain strings, which are passed through as constants to the user code. The result of `func` should be in the same format as bind$. Example: (code$ :seq '(require my-ns.core) '(fn [args] ...) ['c 'd]) See also: pigpen.core.op/project$, pigpen.core.op/projection-func$ " {:added "0.3.0"} [udf init func args] ^:pig {:type :code :init init :func func :udf udf :args (vec args)}) ;; ********** IO ********** (s/defn load$ :- m/Load$ "Load the data specified by `location`, a string. The parameter `storage` is a keyword such as :string, :parquet, or :avro that specifies the type of storage to use. Each platform is responsible for dispatching on storage as appropriate. The parameters `fields` and `opts` specify what fields this will produce and any options to the command. Example: (load$ \"input.tsv\" :string '[value] {}) See also: pigpen.core.op/store$ " {:added "0.3.0"} [location storage fields opts] (let [id (pigsym "load")] ^:pig {:type :load :id id :description location :location location :fields (mapv (partial update-ns+ id) fields) :field-type (get opts :field-type :native) :storage storage :opts (assoc opts :type :load-opts)})) (s/defn store$ :- m/Store$ "Store the data specified by `location`, a string. The parameter `storage` is a keyword such as :string, :parquet, or :avro that specifies the type of storage to use. Each platform is responsible for dispatching on storage as appropriate. The parameter `opts` specify any options to the command. This command can only be passed to store-many$ commands or to platform generation commands. Example: (store$ \"output.tsv\" :string {} relation) See also: pigpen.core.op/load$ " {:added "0.3.0"} [location storage opts relation] (-> (command :store relation opts) (dissoc :field-type :fields) (assoc :location location :storage storage :description location :args (:fields relation)))) (s/defn store-many$ :- m/StoreMany$ "Combines multiple store$ commands into a single command. This command can only be passed to other store-many$ commands or to platform generation commands. Example: (store-many$ [(store$ \"output1.tsv\" :string {} relation1) (store$ \"output2.tsv\" :string {} relation2)]) See also: pigpen.core.op/store$ " [outputs] ^:pig {:type :store-many :id (pigsym "store-many") :ancestors (vec outputs)}) (s/defn return$ :- m/Return$ "Return the data as a PigPen relation. The parameter `fields` specifies what fields the data will contain. Example: (return$ ['value] [{'value 42} {'value 37}]) See also: pigpen.core.op/load$ " {:added "0.3.0"} [fields data] (let [id (pigsym "return")] ^:pig {:type :return :id id :field-type :frozen :fields (mapv (partial update-ns+ id) fields) :data (for [m data] (->> m (map (fn [[f v]] [(update-ns+ id f) v])) (into {})))})) ;; ********** Map ********** (defn projection-field$ "Project a single field into another, optionally providing an alias for the new field. If an alias is not specified, the input field name is used. If the field represents a collection, specify `flatten` as true to flatten the values of the field into individual records. Examples: (projection-field$ 'a) ;; copy the field a as a (projection-field$ 'a 'b) ;; copy the field a as b (projection-field$ 'a 'b true) ;; copy the field a as b and flatten a See also: pigpen.core.op/project$, pigpen.core.op/projection-func$ " {:added "0.3.0"} ([field] (projection-field$ field [(symbol (name field))] false)) ([field alias] (projection-field$ field alias false)) ([field alias flatten] ^:pig {:type :projection :expr {:type :field :field field} :flatten flatten :alias alias})) (s/defn projection-func$ "Apply code to a set of fields, optionally flattening the result. See code$ for details regarding how to express user code. Examples: (projection-func$ 'a (code$ ...)) ;; scalar result (projection-func$ 'a (code$ ...) true) ;; flatten the result collection See also: pigpen.core.op/code$, pigpen.core.op/project$, pigpen.core.op/projection-field$ " {:added "0.3.0"} ([alias code :- m/CodeExpr] (projection-func$ alias true code)) ([alias flatten code :- m/CodeExpr] ^:pig {:type :projection :expr code :flatten flatten :alias alias})) (defn ^:private update-alias-ns [id projection] (update-in projection [:alias] (partial mapv (partial update-ns id)))) (s/defn project$* :- m/Project "Used to make a post-bake project" [projections opts relation] (let [{id :id, :as c} (command :project opts)] (-> c (assoc :projections (mapv (partial update-alias-ns id) projections) :ancestors [relation] :fields (mapv (partial update-ns id) (mapcat :alias projections)))))) (s/defn project$ :- m/Project$ "Used to manipulate the fields of a relation, either by aliasing them or applying functions to them. Usually you want bind$ instead of project$, as PigPen will compile many of the former into one of the latter. Example: (project$ [(projection-field$ 'a 'b) (projection-func$ 'e (code$ :seq '(require my-ns.core) '(fn [args] ...) ['c 'd]))] {} relation) In the example above, we apply two operations to the input relation. First, we alias the input field 'a as 'b. Second, we apply the user code specified by code$ to the fields 'c and 'd to produce the field 'e. This implies that the input relation has three fields, 'a, 'c, and 'd, and that the output fields of this relation are 'b and 'e. If multiple projections are provided that flatten results, the cross product of those is returned. See also: pigpen.core.op/projection-field$, pigpen.core.op/projection-func$, pigpen.core.op/code$ " {:added "0.3.0"} [projections opts relation] (let [{id :id, :as c} (command :project relation opts)] (-> c (assoc :projections (mapv (partial update-alias-ns id) projections) :fields (mapv (partial update-ns id) (mapcat :alias projections)))))) (s/defn bind$ :- m/Bind$ "The way to apply user code to a relation. `func` should be a function that takes a collection of arguments, and returns a collection of result tuples. Optionally takes a collection of namespaces to require before executing user code. Example: (bind$ (fn [args] ;; do stuff to args, return a value like this: [[foo-value bar-value] ;; result 1 [foo-value bar-value] ;; result 2 ... [foo-value bar-value]]) ;; result N {:args '[x y] :alias '[foo bar]} relation) In this example, our function takes `args` which is a tuple of argument values from the previous relation. Here, this selects the fields x and y. The function then returns 0-to-many result tuples. Each of those tuples maps to the fields specified by the alias option. If not specified, args defaults to the fields of the input relation and alias defaults to a single field `value`. All field names should be symbols. There are many provided bind helper functions, such as map->bind, that take a normal map function of one arg to one result, and convert it to a bind function. (bind$ (map->bind (fn [x] (* x x))) {} data) See also: pigpen.core.fn/map->bind, pigpen.core.fn/mapcat->bind, pigpen.core.fn/filter->bind, pigpen.core.fn/process->bind, pigpen.core.fn/key-selector->bind, pigpen.core.fn/keyword-field-selector->bind, pigpen.core.fn/indexed-field-selector->bind " {:added "0.3.0"} ([func opts relation] (bind$ [] func opts relation)) ([requires func opts relation] (let [opts' (dissoc opts :args :requires :alias :types :field-type-in :field-type) {id :id, :as c} (command :bind relation opts')] (-> c (dissoc :field-type) (assoc :func func :args (vec (or (->> (get opts :args) (map (fn [a] (if (string? a) a (update-ns+ (:id relation) a)))) seq) (get relation :fields))) :requires (vec (concat requires (:requires opts))) :fields (mapv (partial update-ns+ id) (get opts :alias ['value])) :field-type-in (get opts :field-type-in :frozen) :field-type (get opts :field-type :frozen) :types (get opts :types)))))) (s/defn sort$ :- m/Sort$ "Sort the data in relation. The parameter `key` specifies the field that should be used to sort the data. The sort field should be a native type; not serialized. `comp` is either :asc or :desc. Example: (sort$ 'key :asc {} relation) " {:added "0.3.0"} [key comp opts relation] (let [{id :id, :as c} (command :sort relation opts)] (-> c (assoc :key (update-ns+ (:id relation) key)) (assoc :comp comp) (update-in [:fields] (partial remove #{(update-ns+ id key)}))))) (s/defn rank$ :- m/Rank$ "Rank the input relation. Adds a new field ('index), a long, to the fields of the input relation. Example: (rank$ {} relation) See also: pigpen.core.op/sort$ " {:added "0.3.0"} [opts relation] (let [{id :id, :as c} (command :rank relation opts)] (-> c (update-in [:fields] (partial cons (update-ns+ id 'index)))))) ;; ********** Filter ********** (s/defn filter$* :- m/Filter "Used to make a post-bake filter" [fields expr opts relation] {:pre [(symbol? relation)]} (-> (command :filter opts) (assoc :expr expr :fields (vec fields) :ancestors [relation] :field-type :native))) (s/defn filter$ :- m/Filter$ [expr opts relation] (-> (command :filter relation opts) (assoc :expr expr :field-type :native))) (s/defn take$ :- m/Take$ "Returns the first n records from relation. Example: (take$ 100 {} relation) See also: pigpen.core.op/sample$ " {:added "0.3.0"} [n opts relation] (-> (command :take relation opts) (assoc :n n))) (s/defn sample$ :- m/Sample$ "Samples the input relation at percentage p, where (<= 0.0 p 1.0). Example: (sample$ 0.5 {} relation) See also: pigpen.core.op/take$ " {:added "0.3.0"} [p opts relation] (-> (command :sample relation opts) (assoc :p p))) ;; ********** Set ********** (s/defn distinct$ :- m/Distinct$ "Returns the distinct values in relation. Example: (distinct$ {} relation) See also: pigpen.core.op/concat$ " {:added "0.3.0"} [opts relation] (command :distinct relation opts)) (s/defn concat$ :- (s/either m/Concat$ m/Op) "Concatenates the set of ancestor relations together. The fields produced by the concat operation are the fields of the first relation. Example: (concat$ {} [relation1 relation2]) See also: pigpen.core.op/distinct$ " {:added "0.3.0"} [opts ancestors] (if-not (next ancestors) (first ancestors) (command :concat ancestors (->> ancestors first :fields (map (comp symbol name))) opts))) ;; ********** Join ********** (s/defn reduce$ :- m/Reduce$ "Reduce the entire relation into a single recrod that is the collection of all records. Example: (reduce$ {} relation) See also: pigpen.core.op/group$ " {:added "0.3.0"} [opts relation] (-> (command :reduce relation opts) (assoc :fields [(-> relation :fields first)]) (assoc :arg (-> relation :fields first)))) (defmulti ancestors->fields "Get the set of fields produced by the ancestors and this command." (fn [type id ancestors] type)) (defmulti fields->keys "Determine which fields are the keys to be used for grouping/joining." (fn [type fields] type)) (s/defn group$ :- m/Group$ "Performs a cogroup on the ancestors provided. The parameter `field-dispatch` should be one of the following, and produces the following output fields: :group - [group r0/key r0/value ... rN/key rN/value] :join - [r0/key r0/value ... rN/key rN/value] :set - [r0/value ... rN/value] The parameter `join-types` is a vector of keywords (:required or :optional) specifying if each relation is required or optional. The length of join-types must match the number of relations passed. Example: (group$ :group [:required :optional] {} [relation1 relation2]) In this example, the operation performs a cogroup on relation1 and relation2. The `:group` field-dispatch means that both of those relations will provide a field with fields `key` and `value`, and the operation will add a `group` field. The first relation is marked as required and the second is optional. See also: pigpen.core.op/join$ " {:added "0.3.0"} [field-dispatch join-types opts ancestors] (let [{id :id, :as c} (command :group ancestors [] opts) fields (ancestors->fields field-dispatch id ancestors)] (-> c (assoc :field-dispatch field-dispatch :fields fields :keys (fields->keys field-dispatch fields) :join-types (vec join-types))))) (s/defn join$ :- m/Join$ "Performs a join on the ancestors provided. The parameter `field-dispatch` should be one of the following, and produces the following output fields: :group - [group r0/key r0/value ... rN/key rN/value] :join - [r0/key r0/value ... rN/key rN/value] :set - [r0/value ... rN/value] The parameter `join-types` is a vector of keywords (:required or :optional) specifying if each relation is required or optional. The length of join-types must match the number of relations passed. Example: (join$ :join [:required :optional] {} [relation1 relation2]) In this example, the operation performs a join on relation1 and relation2. The `:join` field-dispatch means that both of those relations will provide a field with fields `key` and `value`. The first relation is marked as required and the second is optional. See also: pigpen.core.op/group$ " {:added "0.3.0"} [field-dispatch join-types opts ancestors] {:pre [(< 1 (count ancestors)) (or (every? #{:required} join-types) (= 2 (count ancestors))) (sequential? ancestors) (sequential? join-types) (= (count ancestors) (count join-types))]} (let [{id :id, :as c} (command :join ancestors [] opts) fields (ancestors->fields field-dispatch nil ancestors)] (-> c (assoc :field-dispatch field-dispatch :fields fields :keys (fields->keys field-dispatch fields) :join-types (vec join-types))))) ;; ********** Script ********** (s/defn noop$ :- m/NoOp$ "A no-op command. This is used to introduce a unique id for a command. Example: (noop$ {} relation) " {:added "0.3.0"} [opts relation] (-> (command :noop relation opts) (assoc :args (:fields relation))))
[ { "context": "nce app-state\n (atom\n {:contacts\n [{:first \"Ben\" :last \"Bitdiddle\" :email \"benb@mit.edu\"}\n {:", "end": 291, "score": 0.9998524188995361, "start": 288, "tag": "NAME", "value": "Ben" }, { "context": "e\n (atom\n {:contacts\n [{:first \"Ben\" :last \"Bitdiddle\" :email \"benb@mit.edu\"}\n {:first \"Alyssa\" :mi", "end": 309, "score": 0.99912029504776, "start": 300, "tag": "NAME", "value": "Bitdiddle" }, { "context": "acts\n [{:first \"Ben\" :last \"Bitdiddle\" :email \"benb@mit.edu\"}\n {:first \"Alyssa\" :middle-initial \"P\" :last", "end": 331, "score": 0.9999298453330994, "start": 319, "tag": "EMAIL", "value": "benb@mit.edu" }, { "context": " \"Bitdiddle\" :email \"benb@mit.edu\"}\n {:first \"Alyssa\" :middle-initial \"P\" :last \"Hacker\" :email \"aphac", "end": 354, "score": 0.9997629523277283, "start": 348, "tag": "NAME", "value": "Alyssa" }, { "context": "@mit.edu\"}\n {:first \"Alyssa\" :middle-initial \"P\" :last \"Hacker\" :email \"aphacker@mit.edu\"}\n {", "end": 374, "score": 0.9471811056137085, "start": 373, "tag": "NAME", "value": "P" }, { "context": "\n {:first \"Alyssa\" :middle-initial \"P\" :last \"Hacker\" :email \"aphacker@mit.edu\"}\n {:first \"Eva\" :m", "end": 389, "score": 0.9881863594055176, "start": 383, "tag": "NAME", "value": "Hacker" }, { "context": "lyssa\" :middle-initial \"P\" :last \"Hacker\" :email \"aphacker@mit.edu\"}\n {:first \"Eva\" :middle \"Lu\" :last \"Ator\" :e", "end": 415, "score": 0.9999229907989502, "start": 399, "tag": "EMAIL", "value": "aphacker@mit.edu" }, { "context": "\"Hacker\" :email \"aphacker@mit.edu\"}\n {:first \"Eva\" :middle \"Lu\" :last \"Ator\" :email \"eval@mit.edu\"}", "end": 435, "score": 0.9997012615203857, "start": 432, "tag": "NAME", "value": "Eva" }, { "context": "@mit.edu\"}\n {:first \"Eva\" :middle \"Lu\" :last \"Ator\" :email \"eval@mit.edu\"}\n {:first \"Louis\" :las", "end": 461, "score": 0.9981837272644043, "start": 457, "tag": "NAME", "value": "Ator" }, { "context": " {:first \"Eva\" :middle \"Lu\" :last \"Ator\" :email \"eval@mit.edu\"}\n {:first \"Louis\" :last \"Reasoner\" :email \"p", "end": 483, "score": 0.9998953938484192, "start": 471, "tag": "EMAIL", "value": "eval@mit.edu" }, { "context": ":last \"Ator\" :email \"eval@mit.edu\"}\n {:first \"Louis\" :last \"Reasoner\" :email \"prolog@mit.edu\"}\n {", "end": 505, "score": 0.9997405409812927, "start": 500, "tag": "NAME", "value": "Louis" }, { "context": "email \"eval@mit.edu\"}\n {:first \"Louis\" :last \"Reasoner\" :email \"prolog@mit.edu\"}\n {:first \"Cy\" :midd", "end": 522, "score": 0.9980247020721436, "start": 514, "tag": "NAME", "value": "Reasoner" }, { "context": "u\"}\n {:first \"Louis\" :last \"Reasoner\" :email \"prolog@mit.edu\"}\n {:first \"Cy\" :middle-inital \"D\" :last \"Eff", "end": 546, "score": 0.9999240040779114, "start": 532, "tag": "EMAIL", "value": "prolog@mit.edu" }, { "context": "\"Reasoner\" :email \"prolog@mit.edu\"}\n {:first \"Cy\" :middle-inital \"D\" :last \"Effect\" :email \"bugs@m", "end": 565, "score": 0.9992007613182068, "start": 563, "tag": "NAME", "value": "Cy" }, { "context": "rolog@mit.edu\"}\n {:first \"Cy\" :middle-inital \"D\" :last \"Effect\" :email \"bugs@mit.edu\"}\n {:fir", "end": 584, "score": 0.6583537459373474, "start": 583, "tag": "NAME", "value": "D" }, { "context": "edu\"}\n {:first \"Cy\" :middle-inital \"D\" :last \"Effect\" :email \"bugs@mit.edu\"}\n {:first \"Lem\" :middl", "end": 599, "score": 0.6098253726959229, "start": 593, "tag": "NAME", "value": "Effect" }, { "context": "st \"Cy\" :middle-inital \"D\" :last \"Effect\" :email \"bugs@mit.edu\"}\n {:first \"Lem\" :middle-initial \"E\" :last \"T", "end": 621, "score": 0.9999192953109741, "start": 609, "tag": "EMAIL", "value": "bugs@mit.edu" }, { "context": "ast \"Effect\" :email \"bugs@mit.edu\"}\n {:first \"Lem\" :middle-initial \"E\" :last \"Tweakit\" :email \"more", "end": 641, "score": 0.9992971420288086, "start": 638, "tag": "NAME", "value": "Lem" }, { "context": "ugs@mit.edu\"}\n {:first \"Lem\" :middle-initial \"E\" :last \"Tweakit\" :email \"morebugs@mit.edu\"}]}))\n\n", "end": 661, "score": 0.6383330821990967, "start": 660, "tag": "NAME", "value": "E" }, { "context": "u\"}\n {:first \"Lem\" :middle-initial \"E\" :last \"Tweakit\" :email \"morebugs@mit.edu\"}]}))\n\n(defn middle-nam", "end": 677, "score": 0.9755120873451233, "start": 670, "tag": "NAME", "value": "Tweakit" }, { "context": "\"Lem\" :middle-initial \"E\" :last \"Tweakit\" :email \"morebugs@mit.edu\"}]}))\n\n(defn middle-name [{:keys [middle middle-i", "end": 703, "score": 0.9999232292175293, "start": 687, "tag": "EMAIL", "value": "morebugs@mit.edu" } ]
cljs/om-template/src/cljs/om_template/core.cljs
afronski/playground-web
1
(ns om-template.core (:require-macros [cljs.core.async.macros :refer [go]]) (:require [om.core :as om :include-macros true] [om.dom :as dom :include-macros true] [cljs.core.async :refer [put! chan <!]])) (defonce app-state (atom {:contacts [{:first "Ben" :last "Bitdiddle" :email "benb@mit.edu"} {:first "Alyssa" :middle-initial "P" :last "Hacker" :email "aphacker@mit.edu"} {:first "Eva" :middle "Lu" :last "Ator" :email "eval@mit.edu"} {:first "Louis" :last "Reasoner" :email "prolog@mit.edu"} {:first "Cy" :middle-inital "D" :last "Effect" :email "bugs@mit.edu"} {:first "Lem" :middle-initial "E" :last "Tweakit" :email "morebugs@mit.edu"}]})) (defn middle-name [{:keys [middle middle-initial]}] (cond middle (str " " middle) middle-initial (str " " middle-initial ".") :else "")) (defn display-name [{:keys [first last] :as contact}] (str last ", " first (middle-name contact))) (defn contact-view [contact owner] (reify om/IRenderState (render-state [this {:keys [delete]}] (dom/li nil (dom/span nil (display-name contact)) (dom/button #js {:onClick (fn [e] (put! delete @contact))} "Delete"))))) (defn contacts-view [app owner] (reify om/IInitState (init-state [_] {:delete (chan)}) om/IWillMount (will-mount [_] (let [delete (om/get-state owner :delete)] (go (loop [] (let [contact (<! delete)] (om/transact! app :contacts (fn [xs] (vec (remove #(= contact %) xs)))) (recur)))))) om/IRenderState (render-state [this {:keys [delete]}] (dom/div nil (dom/h2 nil "Contact list") (apply dom/ul nil (om/build-all contact-view (:contacts app) {:init-state {:delete delete}})))))) (defn main [] (om/root contacts-view app-state {:target (. js/document (getElementById "contacts"))}))
54770
(ns om-template.core (:require-macros [cljs.core.async.macros :refer [go]]) (:require [om.core :as om :include-macros true] [om.dom :as dom :include-macros true] [cljs.core.async :refer [put! chan <!]])) (defonce app-state (atom {:contacts [{:first "<NAME>" :last "<NAME>" :email "<EMAIL>"} {:first "<NAME>" :middle-initial "<NAME>" :last "<NAME>" :email "<EMAIL>"} {:first "<NAME>" :middle "Lu" :last "<NAME>" :email "<EMAIL>"} {:first "<NAME>" :last "<NAME>" :email "<EMAIL>"} {:first "<NAME>" :middle-inital "<NAME>" :last "<NAME>" :email "<EMAIL>"} {:first "<NAME>" :middle-initial "<NAME>" :last "<NAME>" :email "<EMAIL>"}]})) (defn middle-name [{:keys [middle middle-initial]}] (cond middle (str " " middle) middle-initial (str " " middle-initial ".") :else "")) (defn display-name [{:keys [first last] :as contact}] (str last ", " first (middle-name contact))) (defn contact-view [contact owner] (reify om/IRenderState (render-state [this {:keys [delete]}] (dom/li nil (dom/span nil (display-name contact)) (dom/button #js {:onClick (fn [e] (put! delete @contact))} "Delete"))))) (defn contacts-view [app owner] (reify om/IInitState (init-state [_] {:delete (chan)}) om/IWillMount (will-mount [_] (let [delete (om/get-state owner :delete)] (go (loop [] (let [contact (<! delete)] (om/transact! app :contacts (fn [xs] (vec (remove #(= contact %) xs)))) (recur)))))) om/IRenderState (render-state [this {:keys [delete]}] (dom/div nil (dom/h2 nil "Contact list") (apply dom/ul nil (om/build-all contact-view (:contacts app) {:init-state {:delete delete}})))))) (defn main [] (om/root contacts-view app-state {:target (. js/document (getElementById "contacts"))}))
true
(ns om-template.core (:require-macros [cljs.core.async.macros :refer [go]]) (:require [om.core :as om :include-macros true] [om.dom :as dom :include-macros true] [cljs.core.async :refer [put! chan <!]])) (defonce app-state (atom {:contacts [{:first "PI:NAME:<NAME>END_PI" :last "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"} {: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"} {:first "PI:NAME:<NAME>END_PI" :middle "Lu" :last "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"} {:first "PI:NAME:<NAME>END_PI" :last "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"} {:first "PI:NAME:<NAME>END_PI" :middle-inital "PI:NAME:<NAME>END_PI" :last "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"} {: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"}]})) (defn middle-name [{:keys [middle middle-initial]}] (cond middle (str " " middle) middle-initial (str " " middle-initial ".") :else "")) (defn display-name [{:keys [first last] :as contact}] (str last ", " first (middle-name contact))) (defn contact-view [contact owner] (reify om/IRenderState (render-state [this {:keys [delete]}] (dom/li nil (dom/span nil (display-name contact)) (dom/button #js {:onClick (fn [e] (put! delete @contact))} "Delete"))))) (defn contacts-view [app owner] (reify om/IInitState (init-state [_] {:delete (chan)}) om/IWillMount (will-mount [_] (let [delete (om/get-state owner :delete)] (go (loop [] (let [contact (<! delete)] (om/transact! app :contacts (fn [xs] (vec (remove #(= contact %) xs)))) (recur)))))) om/IRenderState (render-state [this {:keys [delete]}] (dom/div nil (dom/h2 nil "Contact list") (apply dom/ul nil (om/build-all contact-view (:contacts app) {:init-state {:delete delete}})))))) (defn main [] (om/root contacts-view app-state {:target (. js/document (getElementById "contacts"))}))
[ { "context": " and GRPC applications\"\n :url \"http://github.com/protojure/library\"\n :license {:name \"Apache License 2.0\"\n ", "end": 214, "score": 0.9990048408508301, "start": 205, "tag": "USERNAME", "value": "protojure" }, { "context": "NSE-2.0\"\n :year 2019\n :key \"apache-2.0\"}\n :plugins [[lein-codox \"0.10.4\"]\n [", "end": 377, "score": 0.9821335673332214, "start": 367, "tag": "KEY", "value": "apache-2.0" }, { "context": "\"]\n [lein-cljfmt \"0.5.7\"]\n [jonase/eastwood \"0.2.6\"]\n [lein-kibit \"0.1.6\"", "end": 467, "score": 0.9915721416473389, "start": 461, "tag": "USERNAME", "value": "jonase" } ]
project.clj
ghaskins/protojure-lib
0
(defproject protojure "1.0.1-SNAPSHOT" :description "Support library for protoc-gen-clojure, providing native Clojure support for Google Protocol Buffers and GRPC applications" :url "http://github.com/protojure/library" :license {:name "Apache License 2.0" :url "https://www.apache.org/licenses/LICENSE-2.0" :year 2019 :key "apache-2.0"} :plugins [[lein-codox "0.10.4"] [lein-cljfmt "0.5.7"] [jonase/eastwood "0.2.6"] [lein-kibit "0.1.6"] [lein-bikeshed "0.5.1"] [lein-cloverage "1.0.13"]] :dependencies [[org.clojure/clojure "1.10.0" :scope "provided"] [org.clojure/core.async "0.4.490" :scope "provided"] [com.google.protobuf/protobuf-java "3.7.1" :scope "provided"] [io.undertow/undertow-core "2.0.20.Final" :scope "provided"] [io.undertow/undertow-servlet "2.0.20.Final" :scope "provided"] [org.eclipse.jetty.http2/http2-client "9.4.17.v20190418" :scope "provided"] [io.pedestal/pedestal.log "0.5.5" :scope "provided"] [io.pedestal/pedestal.service "0.5.5" :scope "provided"] [org.clojure/tools.logging "0.4.1"] [org.apache.commons/commons-compress "1.18"] [commons-io/commons-io "2.6"] [funcool/promesa "2.0.1"] [lambdaisland/uri "1.1.0"]] :aot [protojure.internal.grpc.codec.io protojure.internal.pedestal.io] :codox {:metadata {:doc/format :markdown} :namespaces [#"^(?!protojure.internal)"]} :eastwood {:debug [:none] :exclude-linters [:constant-test] :add-linters [:unused-namespaces] :config-files [".eastwood-overrides"] :exclude-namespaces [example.hello protojure.grpc-test]} :profiles {:dev {:dependencies [[org.clojure/tools.namespace "0.2.11"] [clj-http "3.9.1"] [com.taoensso/timbre "4.10.0"] [org.clojure/data.codec "0.1.1"]] :resource-paths ["test/resources"]}})
49029
(defproject protojure "1.0.1-SNAPSHOT" :description "Support library for protoc-gen-clojure, providing native Clojure support for Google Protocol Buffers and GRPC applications" :url "http://github.com/protojure/library" :license {:name "Apache License 2.0" :url "https://www.apache.org/licenses/LICENSE-2.0" :year 2019 :key "<KEY>"} :plugins [[lein-codox "0.10.4"] [lein-cljfmt "0.5.7"] [jonase/eastwood "0.2.6"] [lein-kibit "0.1.6"] [lein-bikeshed "0.5.1"] [lein-cloverage "1.0.13"]] :dependencies [[org.clojure/clojure "1.10.0" :scope "provided"] [org.clojure/core.async "0.4.490" :scope "provided"] [com.google.protobuf/protobuf-java "3.7.1" :scope "provided"] [io.undertow/undertow-core "2.0.20.Final" :scope "provided"] [io.undertow/undertow-servlet "2.0.20.Final" :scope "provided"] [org.eclipse.jetty.http2/http2-client "9.4.17.v20190418" :scope "provided"] [io.pedestal/pedestal.log "0.5.5" :scope "provided"] [io.pedestal/pedestal.service "0.5.5" :scope "provided"] [org.clojure/tools.logging "0.4.1"] [org.apache.commons/commons-compress "1.18"] [commons-io/commons-io "2.6"] [funcool/promesa "2.0.1"] [lambdaisland/uri "1.1.0"]] :aot [protojure.internal.grpc.codec.io protojure.internal.pedestal.io] :codox {:metadata {:doc/format :markdown} :namespaces [#"^(?!protojure.internal)"]} :eastwood {:debug [:none] :exclude-linters [:constant-test] :add-linters [:unused-namespaces] :config-files [".eastwood-overrides"] :exclude-namespaces [example.hello protojure.grpc-test]} :profiles {:dev {:dependencies [[org.clojure/tools.namespace "0.2.11"] [clj-http "3.9.1"] [com.taoensso/timbre "4.10.0"] [org.clojure/data.codec "0.1.1"]] :resource-paths ["test/resources"]}})
true
(defproject protojure "1.0.1-SNAPSHOT" :description "Support library for protoc-gen-clojure, providing native Clojure support for Google Protocol Buffers and GRPC applications" :url "http://github.com/protojure/library" :license {:name "Apache License 2.0" :url "https://www.apache.org/licenses/LICENSE-2.0" :year 2019 :key "PI:KEY:<KEY>END_PI"} :plugins [[lein-codox "0.10.4"] [lein-cljfmt "0.5.7"] [jonase/eastwood "0.2.6"] [lein-kibit "0.1.6"] [lein-bikeshed "0.5.1"] [lein-cloverage "1.0.13"]] :dependencies [[org.clojure/clojure "1.10.0" :scope "provided"] [org.clojure/core.async "0.4.490" :scope "provided"] [com.google.protobuf/protobuf-java "3.7.1" :scope "provided"] [io.undertow/undertow-core "2.0.20.Final" :scope "provided"] [io.undertow/undertow-servlet "2.0.20.Final" :scope "provided"] [org.eclipse.jetty.http2/http2-client "9.4.17.v20190418" :scope "provided"] [io.pedestal/pedestal.log "0.5.5" :scope "provided"] [io.pedestal/pedestal.service "0.5.5" :scope "provided"] [org.clojure/tools.logging "0.4.1"] [org.apache.commons/commons-compress "1.18"] [commons-io/commons-io "2.6"] [funcool/promesa "2.0.1"] [lambdaisland/uri "1.1.0"]] :aot [protojure.internal.grpc.codec.io protojure.internal.pedestal.io] :codox {:metadata {:doc/format :markdown} :namespaces [#"^(?!protojure.internal)"]} :eastwood {:debug [:none] :exclude-linters [:constant-test] :add-linters [:unused-namespaces] :config-files [".eastwood-overrides"] :exclude-namespaces [example.hello protojure.grpc-test]} :profiles {:dev {:dependencies [[org.clojure/tools.namespace "0.2.11"] [clj-http "3.9.1"] [com.taoensso/timbre "4.10.0"] [org.clojure/data.codec "0.1.1"]] :resource-paths ["test/resources"]}})
[ { "context": "; The breakthrough idea, unanimously attributed to Georg Cantor,\n;; relies on the notion of an **injective functi", "end": 1605, "score": 0.9962931275367737, "start": 1593, "tag": "NAME", "value": "Georg Cantor" } ]
src/cantor_bernstein/theorem.clj
latte-central/cantor-bernstein
1
(ns cantor-bernstein.theorem "A proof of the Cantor-Bernstein(-Schroeder) theorem in LaTTe" (:refer-clojure :exclude [and or not set]) (:require ;; for notebook presentation [nextjournal.clerk :as clerk] [nextjournal.clerk.viewer :as v] ;; latte dependencies [latte.core :as latte :refer [definition defthm defaxiom defnotation forall lambda defimplicit deflemma qed assume have pose proof try-proof lambda forall]] ;; propositional logic [latte-prelude.prop :as p :refer [and and* or not]] ;; basic sets [latte-sets.set :as s :refer [set]] ;; basic relations [latte-sets.rel :as rel :refer [rel]] ;; relations as partial functions [latte-sets.pfun :as pfun :refer [functional serial injective]] ;; quantifying relations [latte-sets.powerrel :as prel :refer [powerrel rel-ex]] )) ;; # The Cantor-Bernstein theorem ;; In this (Clojure) program *slash* document we formalize a proof of the infamous ;; [Cantor-Bernstein](https://en.wikipedia.org/wiki/Schr%C3%B6der%E2%80%93Bernstein_theorem) ;; theorem, which is an important result of (infinite) set theory. ;; ;; ;; ## Comparing sets ;; ;; The starting question is: how do you compare the sizes of sets? ;; For finite sets, this sounds like a straightforward question: ;; simply compare their number of elements. Since these are finite ;; quantities - namely *cardinalities* - it is a "simple" matter ;; of comparing numbers. ;; For infinite sets, there are simply no numbers to compare. ;; The breakthrough idea, unanimously attributed to Georg Cantor, ;; relies on the notion of an **injective function**. ;; ;; Here is the definition proposed by the [[latte-prelude]]: ;; (comment (definition injective "An injective function." [[?T ?U :type], f (==> T U)] (forall [x y T] (==> (equal (f x) (f y)) (equal x y)))) ) ;; Using a more classical notation, we say that a function $f$ is injective ;; *iff*: $$∀x,y ∈ T,~f(x) = f(y) \implies x = y$$ ;; ;; The problem with the above `definition` is that it is ;; *type-theoretic*, i.e. the $T$ and $U$ in the definition above are ;; types and not sets. One important difference is that type "membership" ;; (called *inhabitation*) is decidable (at least in LaTTe) whereas ;; it is not in the theory of sets. ;; ## A relational detour ;; Thankfully, it is possible to formalize sets in type theory, ;; in various ways. LaTTe uses the so-called *predicative* approach, ;; which considers sets as predicates: the set of elements satisfiying ;; some predicate $P$ is the predicate $P$ itself. ;; A set of element of type `T` uses the type `(set T)` as a shortcut to `(==> T :type)` ;; which is the type of predicates over `T`. ;; Moreover, instead of considering relations as sets of pairs, which ;; is possible, LaTTe favors the privileded type-theoretic approach ;; of considering the type `(rel T U)` of relation $T\times U$ as a shortcut ;; to `(==> T U =type)` i.e. binary predicates over `T` and `U`. ;; This leads to the following relational interpretation of injectivity: (comment (definition injective [[?T ?U :type] [f (rel T U)] [from (set T)] [to (set U)]] (forall-in [x1 from] (forall-in [x2 from] (forall-in [y1 to] (forall-in [y2 to] (==> (f x1 y1) (f x2 y2) (equal y1 y2) (equal x1 x2))))))) ) ;; One important difference with the relational approach is that ;; we need to write `(f x y)` as a replacement for the ;; classical mathematic notation $y=f(x)$ ;; I a more traditional proof of the theorem, one would use ;; the set-theoretic interpretation of functions, i.e. something ;; like $(x,y) \in f$ rather than a relational notation. ;; Hence, the former definition explains what it is for a *relation* to be ;; injective, or rather to possess the property of injectivity. ;; To be *injective* (or an *injection*) we must also ensure that ;; $f$ is *also* a function, hence we need also the following: (comment (definition functional [[?T ?U :type], f (rel T U), from (set T), to (set U)] (forall-in [x from] (forall-in [y1 to] (forall-in [y2 to] (==> (f x y1) (f x y2) (equal y1 y2)))))) ) ;; This says that the relation we call `f` is, indeed, a *function* ;; in the sense that it is deterministic: if $f(x)=y1$ and $f(y)=y2$ ;; then $y1=y_2$. ;; We also need the relation/function to be *serial* (or *total*), i.e. that ;; it is defined on its while domain, which is the set calle `from`. (comment (definition serial "The relation `f` covers all of (is total wrt.) the provided `from` domain set." [[?T ?U :type], f (rel T U), from (set T), to (set U)] (forall-in [x from] (exists-in [y to] (f x y))) ) ) ;; In a more classical notation, we would write: ;; $$\forall x \in from,~\exists y \in to,~y=f(x)$$ ;; ## Comparing sets (take 2) ;; We have now everything we need to give a formal definition ;; for a set to be *smaller* than another set, which is valid ;; even in the infinite case. ;; First, we formalize the set of (relational) functions ;; that are injective from domain $e_1$ and range $e_2$. (definition ≲-prop [[?T ?U :type], e1 (set T), e2 (set U)] (lambda [f (rel T U)] (and* (functional f e1 e2) (serial f e1 e2) (injective f e1 e2)))) ;; In the traditional notation we would write this set as: ;; $$\{f \in e_1 \rightarrow e_2 \mid ∀x ∈ e_1, \forall y ∈ e_2,~f(x) = f(y) \implies x = y \}$$ ;; (keeping implicit the details of what makes $f$ a total function) ;; This gives our definition of the *smaller-than* comparator for sets ;; as follows: (definition ≲ "Set `e1` is *smaller* than set `e2` (according to Cantor)." [[?T ?U :type], e1 (set T), e2 (set U)] (rel-ex (≲-prop e1 e2))) ;; The informal meaning is that $e_1$ is *smaller than* $e_2$, ;; which is denoted by $e_1 ≲ e_2$ (or `(≲ e1 e2)` in the Clojure notation) ;; iff there exists a relation $f$ in the set defined by `≲-prop`, i.e. ;; iff there exist an injection $f$ between $e_1$ and $e_2$.
102344
(ns cantor-bernstein.theorem "A proof of the Cantor-Bernstein(-Schroeder) theorem in LaTTe" (:refer-clojure :exclude [and or not set]) (:require ;; for notebook presentation [nextjournal.clerk :as clerk] [nextjournal.clerk.viewer :as v] ;; latte dependencies [latte.core :as latte :refer [definition defthm defaxiom defnotation forall lambda defimplicit deflemma qed assume have pose proof try-proof lambda forall]] ;; propositional logic [latte-prelude.prop :as p :refer [and and* or not]] ;; basic sets [latte-sets.set :as s :refer [set]] ;; basic relations [latte-sets.rel :as rel :refer [rel]] ;; relations as partial functions [latte-sets.pfun :as pfun :refer [functional serial injective]] ;; quantifying relations [latte-sets.powerrel :as prel :refer [powerrel rel-ex]] )) ;; # The Cantor-Bernstein theorem ;; In this (Clojure) program *slash* document we formalize a proof of the infamous ;; [Cantor-Bernstein](https://en.wikipedia.org/wiki/Schr%C3%B6der%E2%80%93Bernstein_theorem) ;; theorem, which is an important result of (infinite) set theory. ;; ;; ;; ## Comparing sets ;; ;; The starting question is: how do you compare the sizes of sets? ;; For finite sets, this sounds like a straightforward question: ;; simply compare their number of elements. Since these are finite ;; quantities - namely *cardinalities* - it is a "simple" matter ;; of comparing numbers. ;; For infinite sets, there are simply no numbers to compare. ;; The breakthrough idea, unanimously attributed to <NAME>, ;; relies on the notion of an **injective function**. ;; ;; Here is the definition proposed by the [[latte-prelude]]: ;; (comment (definition injective "An injective function." [[?T ?U :type], f (==> T U)] (forall [x y T] (==> (equal (f x) (f y)) (equal x y)))) ) ;; Using a more classical notation, we say that a function $f$ is injective ;; *iff*: $$∀x,y ∈ T,~f(x) = f(y) \implies x = y$$ ;; ;; The problem with the above `definition` is that it is ;; *type-theoretic*, i.e. the $T$ and $U$ in the definition above are ;; types and not sets. One important difference is that type "membership" ;; (called *inhabitation*) is decidable (at least in LaTTe) whereas ;; it is not in the theory of sets. ;; ## A relational detour ;; Thankfully, it is possible to formalize sets in type theory, ;; in various ways. LaTTe uses the so-called *predicative* approach, ;; which considers sets as predicates: the set of elements satisfiying ;; some predicate $P$ is the predicate $P$ itself. ;; A set of element of type `T` uses the type `(set T)` as a shortcut to `(==> T :type)` ;; which is the type of predicates over `T`. ;; Moreover, instead of considering relations as sets of pairs, which ;; is possible, LaTTe favors the privileded type-theoretic approach ;; of considering the type `(rel T U)` of relation $T\times U$ as a shortcut ;; to `(==> T U =type)` i.e. binary predicates over `T` and `U`. ;; This leads to the following relational interpretation of injectivity: (comment (definition injective [[?T ?U :type] [f (rel T U)] [from (set T)] [to (set U)]] (forall-in [x1 from] (forall-in [x2 from] (forall-in [y1 to] (forall-in [y2 to] (==> (f x1 y1) (f x2 y2) (equal y1 y2) (equal x1 x2))))))) ) ;; One important difference with the relational approach is that ;; we need to write `(f x y)` as a replacement for the ;; classical mathematic notation $y=f(x)$ ;; I a more traditional proof of the theorem, one would use ;; the set-theoretic interpretation of functions, i.e. something ;; like $(x,y) \in f$ rather than a relational notation. ;; Hence, the former definition explains what it is for a *relation* to be ;; injective, or rather to possess the property of injectivity. ;; To be *injective* (or an *injection*) we must also ensure that ;; $f$ is *also* a function, hence we need also the following: (comment (definition functional [[?T ?U :type], f (rel T U), from (set T), to (set U)] (forall-in [x from] (forall-in [y1 to] (forall-in [y2 to] (==> (f x y1) (f x y2) (equal y1 y2)))))) ) ;; This says that the relation we call `f` is, indeed, a *function* ;; in the sense that it is deterministic: if $f(x)=y1$ and $f(y)=y2$ ;; then $y1=y_2$. ;; We also need the relation/function to be *serial* (or *total*), i.e. that ;; it is defined on its while domain, which is the set calle `from`. (comment (definition serial "The relation `f` covers all of (is total wrt.) the provided `from` domain set." [[?T ?U :type], f (rel T U), from (set T), to (set U)] (forall-in [x from] (exists-in [y to] (f x y))) ) ) ;; In a more classical notation, we would write: ;; $$\forall x \in from,~\exists y \in to,~y=f(x)$$ ;; ## Comparing sets (take 2) ;; We have now everything we need to give a formal definition ;; for a set to be *smaller* than another set, which is valid ;; even in the infinite case. ;; First, we formalize the set of (relational) functions ;; that are injective from domain $e_1$ and range $e_2$. (definition ≲-prop [[?T ?U :type], e1 (set T), e2 (set U)] (lambda [f (rel T U)] (and* (functional f e1 e2) (serial f e1 e2) (injective f e1 e2)))) ;; In the traditional notation we would write this set as: ;; $$\{f \in e_1 \rightarrow e_2 \mid ∀x ∈ e_1, \forall y ∈ e_2,~f(x) = f(y) \implies x = y \}$$ ;; (keeping implicit the details of what makes $f$ a total function) ;; This gives our definition of the *smaller-than* comparator for sets ;; as follows: (definition ≲ "Set `e1` is *smaller* than set `e2` (according to Cantor)." [[?T ?U :type], e1 (set T), e2 (set U)] (rel-ex (≲-prop e1 e2))) ;; The informal meaning is that $e_1$ is *smaller than* $e_2$, ;; which is denoted by $e_1 ≲ e_2$ (or `(≲ e1 e2)` in the Clojure notation) ;; iff there exists a relation $f$ in the set defined by `≲-prop`, i.e. ;; iff there exist an injection $f$ between $e_1$ and $e_2$.
true
(ns cantor-bernstein.theorem "A proof of the Cantor-Bernstein(-Schroeder) theorem in LaTTe" (:refer-clojure :exclude [and or not set]) (:require ;; for notebook presentation [nextjournal.clerk :as clerk] [nextjournal.clerk.viewer :as v] ;; latte dependencies [latte.core :as latte :refer [definition defthm defaxiom defnotation forall lambda defimplicit deflemma qed assume have pose proof try-proof lambda forall]] ;; propositional logic [latte-prelude.prop :as p :refer [and and* or not]] ;; basic sets [latte-sets.set :as s :refer [set]] ;; basic relations [latte-sets.rel :as rel :refer [rel]] ;; relations as partial functions [latte-sets.pfun :as pfun :refer [functional serial injective]] ;; quantifying relations [latte-sets.powerrel :as prel :refer [powerrel rel-ex]] )) ;; # The Cantor-Bernstein theorem ;; In this (Clojure) program *slash* document we formalize a proof of the infamous ;; [Cantor-Bernstein](https://en.wikipedia.org/wiki/Schr%C3%B6der%E2%80%93Bernstein_theorem) ;; theorem, which is an important result of (infinite) set theory. ;; ;; ;; ## Comparing sets ;; ;; The starting question is: how do you compare the sizes of sets? ;; For finite sets, this sounds like a straightforward question: ;; simply compare their number of elements. Since these are finite ;; quantities - namely *cardinalities* - it is a "simple" matter ;; of comparing numbers. ;; For infinite sets, there are simply no numbers to compare. ;; The breakthrough idea, unanimously attributed to PI:NAME:<NAME>END_PI, ;; relies on the notion of an **injective function**. ;; ;; Here is the definition proposed by the [[latte-prelude]]: ;; (comment (definition injective "An injective function." [[?T ?U :type], f (==> T U)] (forall [x y T] (==> (equal (f x) (f y)) (equal x y)))) ) ;; Using a more classical notation, we say that a function $f$ is injective ;; *iff*: $$∀x,y ∈ T,~f(x) = f(y) \implies x = y$$ ;; ;; The problem with the above `definition` is that it is ;; *type-theoretic*, i.e. the $T$ and $U$ in the definition above are ;; types and not sets. One important difference is that type "membership" ;; (called *inhabitation*) is decidable (at least in LaTTe) whereas ;; it is not in the theory of sets. ;; ## A relational detour ;; Thankfully, it is possible to formalize sets in type theory, ;; in various ways. LaTTe uses the so-called *predicative* approach, ;; which considers sets as predicates: the set of elements satisfiying ;; some predicate $P$ is the predicate $P$ itself. ;; A set of element of type `T` uses the type `(set T)` as a shortcut to `(==> T :type)` ;; which is the type of predicates over `T`. ;; Moreover, instead of considering relations as sets of pairs, which ;; is possible, LaTTe favors the privileded type-theoretic approach ;; of considering the type `(rel T U)` of relation $T\times U$ as a shortcut ;; to `(==> T U =type)` i.e. binary predicates over `T` and `U`. ;; This leads to the following relational interpretation of injectivity: (comment (definition injective [[?T ?U :type] [f (rel T U)] [from (set T)] [to (set U)]] (forall-in [x1 from] (forall-in [x2 from] (forall-in [y1 to] (forall-in [y2 to] (==> (f x1 y1) (f x2 y2) (equal y1 y2) (equal x1 x2))))))) ) ;; One important difference with the relational approach is that ;; we need to write `(f x y)` as a replacement for the ;; classical mathematic notation $y=f(x)$ ;; I a more traditional proof of the theorem, one would use ;; the set-theoretic interpretation of functions, i.e. something ;; like $(x,y) \in f$ rather than a relational notation. ;; Hence, the former definition explains what it is for a *relation* to be ;; injective, or rather to possess the property of injectivity. ;; To be *injective* (or an *injection*) we must also ensure that ;; $f$ is *also* a function, hence we need also the following: (comment (definition functional [[?T ?U :type], f (rel T U), from (set T), to (set U)] (forall-in [x from] (forall-in [y1 to] (forall-in [y2 to] (==> (f x y1) (f x y2) (equal y1 y2)))))) ) ;; This says that the relation we call `f` is, indeed, a *function* ;; in the sense that it is deterministic: if $f(x)=y1$ and $f(y)=y2$ ;; then $y1=y_2$. ;; We also need the relation/function to be *serial* (or *total*), i.e. that ;; it is defined on its while domain, which is the set calle `from`. (comment (definition serial "The relation `f` covers all of (is total wrt.) the provided `from` domain set." [[?T ?U :type], f (rel T U), from (set T), to (set U)] (forall-in [x from] (exists-in [y to] (f x y))) ) ) ;; In a more classical notation, we would write: ;; $$\forall x \in from,~\exists y \in to,~y=f(x)$$ ;; ## Comparing sets (take 2) ;; We have now everything we need to give a formal definition ;; for a set to be *smaller* than another set, which is valid ;; even in the infinite case. ;; First, we formalize the set of (relational) functions ;; that are injective from domain $e_1$ and range $e_2$. (definition ≲-prop [[?T ?U :type], e1 (set T), e2 (set U)] (lambda [f (rel T U)] (and* (functional f e1 e2) (serial f e1 e2) (injective f e1 e2)))) ;; In the traditional notation we would write this set as: ;; $$\{f \in e_1 \rightarrow e_2 \mid ∀x ∈ e_1, \forall y ∈ e_2,~f(x) = f(y) \implies x = y \}$$ ;; (keeping implicit the details of what makes $f$ a total function) ;; This gives our definition of the *smaller-than* comparator for sets ;; as follows: (definition ≲ "Set `e1` is *smaller* than set `e2` (according to Cantor)." [[?T ?U :type], e1 (set T), e2 (set U)] (rel-ex (≲-prop e1 e2))) ;; The informal meaning is that $e_1$ is *smaller than* $e_2$, ;; which is denoted by $e_1 ≲ e_2$ (or `(≲ e1 e2)` in the Clojure notation) ;; iff there exists a relation $f$ in the set defined by `≲-prop`, i.e. ;; iff there exist an injection $f$ between $e_1$ and $e_2$.
[ { "context": " :href \"https://github.com/jsa-aerial/saite\"\n :target \"_blank", "end": 10118, "score": 0.9992438554763794, "start": 10108, "tag": "USERNAME", "value": "jsa-aerial" }, { "context": ":LEFT left :RIGHT right)]\n hmi/sv!))\n\n\n\n\n;;; Rachel and Abhisheks tRNA experiment results - raw ", "end": 13552, "score": 0.5740875005722046, "start": 13551, "tag": "NAME", "value": "R" }, { "context": "GHT right)]\n hmi/sv!))\n\n\n\n\n;;; Rachel and Abhisheks tRNA experiment results - raw counts\n;;;\n;;; **", "end": 13569, "score": 0.526528000831604, "start": 13564, "tag": "NAME", "value": "hishe" } ]
examples/bostonclojure.clj
devurandom/saite
108
(ns bostonclj.examples (:require [clojure.string :as cljstr] [clojure.data.csv :as csv] [clojure.data.json :as json] [clojure.pprint :as pp :refer [pprint]] [aerial.fs :as fs] [aerial.utils.string :as str] [aerial.utils.io :refer [letio] :as io] [aerial.utils.coll :refer [vfold] :as coll] [aerial.utils.math :as m] [aerial.utils.math.probs-stats :as p] [aerial.utils.math.infoth :as it] [aerial.bio.utils.files :as bufiles] [aerial.bio.utils.aligners :as aln] [aerial.hanami.common :as hc :refer [RMV]] [aerial.hanami.templates :as ht] [aerial.hanami.core :as hmi] [aerial.saite.core :as saite])) (saite/start 3000) ;;; The ubiquitous simple car scatter plot via template (-> (hc/xform ht/point-chart :UDATA "data/cars.json" :X "Horsepower" :Y "Miles_per_Gallon" :COLOR "Origin") hmi/sv!) ;;; Another simple one right from IDL examples (-> (hc/xform ht/bar-chart :UDATA "data/seattle-weather.csv" :TOOLTIP RMV :X "date" :XTYPE "ordinal" :XUNIT "month" :Y "precipitation" :YAGG "mean") hmi/sv!) ;;; Simple barchart with slider instrument ;;; (->> (let [data [{:a "A", :b 28 }, {:a "B", :b 55 }, {:a "C", :b 43 }, {:a "D", :b 91 }, {:a "E", :b 81 }, {:a "F", :b 53 }, {:a "G", :b 19 }, {:a "H", :b 87 }, {:a "I", :b 52 }] min -10.0 minstr (-> min str (cljstr/split #"\.") first) max 10.0 maxstr (-> max str (cljstr/split #"\.") first (#(str "+" %))) bottom `[[gap :size "50px"] [v-box :children [[p "some text to test, default 14px"] [p {:style {:font-size "16px"}} "some tex \\(f(x) = x^2\\), 16px"] [p {:style {:font-size "18px"}} "\\(f(x) = \\sqrt x\\), 18px"] [p {:style {:font-size "20px"}} "\\(ax^2 + bx + c = 0\\), 20px"]]]]] (hc/xform ht/bar-chart :USERDATA (merge (hc/get-default :USERDATA) {:slider `[[gap :size "10px"] [label :label "Add Bar"] [label :label ~minstr] [slider :model :m1 :min ~min, :max ~max, :step 1.0 :width "200px" :on-change :oc1] [label :label ~maxstr] [input-text :model :m1 :width "60px", :height "26px" :on-change :oc2]]}) :HEIGHT 300, :WIDTH 350 :VID :bc1 ;:BOTTOM bottom :X "a" :XTYPE "ordinal" :XTITLE "Foo" :Y "b" :YTITLE "Bar" :DATA data)) hmi/sv!) ;;; Overview + Detail ;;; (hc/update-defaults :WIDTH 480 :HEIGHT 200) ;;; (hc/update-defaults :HEIGHT 400 :WIDTH 450) (->> (hc/xform ht/vconcat-chart :UDATA "data/sp500.csv", :VCONCAT [(hc/xform ht/area-chart :X :date, :XTYPE :temporal, :XSCALE {:domain {:selection :brush}} :Y :price) (hc/xform ht/area-chart :HEIGHT 60, :SELECTION {:brush {:type :interval, :encodings [:x]}}, :X :date :XTYPE :temporal :Y :price, :YAXIS {:tickCount 3, :grid false})]) hmi/sv!) ;;; Area Chart (-> (hc/xform ht/area-chart :UDATA "data/unemployment-across-industries.json" :TOOLTIP RMV :X :date, :XTYPE :temporal, :XUNIT :yearmonth, :XFORMAT "%Y" :Y "count" :AGG "sum" :COLOR {:field "series", :type "nominal", :scale {:scheme "category20b"}}) hmi/sv!) ;;; Grid example ;;; (hc/get-default :TOOLTIP) ;;; (hc/xform {:tt :TOOLTIP}) ;;; (hc/update-defaults :HEIGHT 200 :WIDTH 250) ;;; (hc/update-defaults :HEIGHT 400 :WIDTH 450) (->> (mapv #(apply hc/xform %) [[ht/point-chart :UDATA "data/cars.json" ; :TOPTS {:order :col :size "none"} :X "Horsepower" :Y "Miles_per_Gallon" :COLOR "Origin"] (let [data (->> (range 0.005 0.999 0.001) (mapv (fn[p] {:x p, :y (- (m/log2 p)) :col "SI"})))] [ht/layer-chart :TITLE "Self Information (unexpectedness)" :LAYER [(hc/xform ht/xrule-layer :AGG "mean") (hc/xform ht/line-layer :XTITLE "Probability of event" :YTITLE "-log(p)")] :DATA data]) [ht/bar-chart :UDATA "data/seattle-weather.csv" :TOOLTIP RMV :X "date" :XTYPE "ordinal" :XUNIT "month" :Y "precipitation" :YAGG "mean"] [ht/layer-chart :UDATA "data/seattle-weather.csv" :LAYER [(hc/xform ht/bar-layer :TOOLTIP RMV :X "date" :XTYPE "ordinal" :XUNIT "month" :Y "precipitation" :YAGG "mean" :SELECTION {:brush {:type "interval", :encodings ["x"]}} :OPACITY {:condition {:selection "brush", :value 1}, :value 0.7}) (hc/xform ht/yrule-layer :TRANSFORM [{:filter {:selection "brush"}}] :Y "precipitation" :AGG "mean" :YRL-COLOR "firebrick")]]]) hmi/sv!) ;;; Some Tree Layouts. Note the mode is Vega! ;;; (->> [(hc/xform ht/tree-layout :OPTS (merge (hc/default-opts :vgl) {:mode "vega"}) :WIDTH 650, :HEIGHT 1600 :UDATA "data/flare.json" :LINKSHAPE "diagonal" :LAYOUT "tidy" :FONTSIZE 11 :CFIELD "depth") (hc/xform ht/tree-layout :OPTS (merge (hc/default-opts :vgl) {:mode "vega"}) :WIDTH 650, :HEIGHT 1600 :UDATA "data/flare.json" :LINKSHAPE "line" :LAYOUT "tidy" :FONTSIZE 11 :CFIELD "depth") (hc/xform ht/tree-layout :OPTS (merge (hc/default-opts :vgl) {:mode "vega"}) :WIDTH 650, :HEIGHT 1600 :UDATA "data/flare.json" :LINKSHAPE "orthogonal" :LAYOUT "cluster" :CFIELD "depth") (hc/xform ht/tree-layout :OPTS (merge (hc/default-opts :vgl) {:mode "vega"}) :WIDTH 650, :HEIGHT 1600 :UDATA "data/flare.json" :LINKSHAPE "curve" :LAYOUT "tidy" :CFIELD "depth")] hmi/sv!) ;;; Picture frames, hiccup, re-com, markdown, and LaTex ;;; ;;; With Mark Down and LaTex (let [data (->> (range 0.001 100.0 0.1) (mapv #(do {:x (ac/roundit %) :y (-> % Math/sqrt ac/roundit)})))] (->> (hc/xform ht/line-chart :VID :sqrt :TID :picframes :BOTTOM `[[gap :size "230px"] [p {:style {:font-size "18px"}} "\\(f(x) = \\sqrt x\\)"]] :RIGHT `[[gap :size "10px"] [v-box :children [(md "#### The square root function") (md "* \\\\(f(x) = \\\\sqrt x\\\\)") (md "* _two_\n* **three**")]]] :DATA data) hmi/sv!)) ;;; Each element on different chart ;;; (let [_ (hc/add-defaults :FMNM #(-> :SIDE % name cljstr/capitalize) :STYLE hc/RMV) frame-template {:frame {:SIDE `[[gap :size :GAP] [p {:style :STYLE} "This is the " [:span.bold :FMNM] " 'board' of a picture " [:span.italic.bold "frame."]]]}} frame-top (hc/xform frame-template :SIDE :top :GAP "10px") frame-left (hc/xform frame-template :SIDE :left :GAP "10px" :STYLE {:width "100px" :min-width "50px"}) frame-right (merge-with merge (hc/xform frame-template :SIDE :right :GAP "2px" :STYLE {:width "100px" :min-width "50px"}) (hc/xform frame-template :SIDE :left :GAP "2px" :STYLE {:width "100px" :min-width "50px" :color "white"})) frame-bot (hc/xform frame-template :SIDE :bottom :GAP "10px")] (->> (mapv #(hc/xform ht/point-chart :HEIGHT 200 :WIDTH 250 :TID :picframes :USERDATA (merge (hc/get-default :USERDATA) %) :UDATA "data/cars.json" :X "Horsepower" :Y "Miles_per_Gallon" :COLOR "Origin") [frame-top frame-left frame-bot frame-right]) hmi/sv!)) ;;; Picture frame - 4 elements (let [text "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quod si ita est, sequitur id ipsum, quod te velle video, omnes semper beatos esse sapientes. Tamen a proposito, inquam, aberramus." top `[[gap :size "150px"] [p "An example showing a " [:span.bold "picture "] [:span.italic.bold "frame"] ". This is the top 'board'" [:br] ~text]] left `[[gap :size "10px"] [p {:style {:width "100px" :min-width "50px"}} "Some text on the " [:span.bold "left:"] [:br] ~text]] right `[[gap :size "2px"] [p {:style {:width "200px" :min-width "50px" :font-size "20px" :color "red"}} "Some large text on the " [:span.bold "right:"] [:br] ~(.substring text 0 180)]] bottom `[[gap :size "200px"] [title :level :level3 :label [p {:style {:font-size "large"}} "Some text on the " [:span.bold "bottom"] [:br] "With a cool info button " [info-button :position :right-center :info [:p "Check out Saite Visualizer!" [:br] "Built with Hanami!" [:br] [hyperlink-href :label "Saite " :href "https://github.com/jsa-aerial/saite" :target "_blank"]]]]]]] (->> [(hc/xform ht/point-chart :TID :picframes :TOP top :BOTTOM bottom :LEFT left :RIGHT right :UDATA "data/cars.json" :X "Horsepower" :Y "Miles_per_Gallon" :COLOR "Origin")] hmi/sv!)) ;;; Empty picture frame - 4 elements ;;; (let [text "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quod si ita est, sequitur id ipsum, quod te velle video, omnes semper beatos esse sapientes. Tamen a proposito, inquam, aberramus." top `[[gap :size "50px"] [p {:style {:width "600px" :min-width "50px"}} "An example empty picture frame showing all four areas." " This is the " [:span.bold "top"] " area. " ~text ~text ~text]] left `[[gap :size "50px"] [p {:style {:width "300px" :min-width "50px"}} "The " [:span.bold "left "] "area as a column of text. " ~text ~text ~text ~text]] right `[[gap :size "70px"] [p {:style {:width "300px" :min-width "50px"}} "The " [:span.bold "right "] "area as a column of text. " ~text ~text ~text ~text]] bottom `[[gap :size "50px"] [v-box :children [[p {:style {:width "600px" :min-width "50px"}} "The " [:span.bold "bottom "] "area showing a variety of text. " [:span.italic ~text] [:span.bold ~text]] [p {:style {:width "400px" :min-width "50px" :font-size "20px"}} "some TeX: " "\\(f(x) = \\sqrt x\\)"] [md {:style {:font-size "16px" :color "blue"}} "#### Some Markup * **Item 1** Lorem ipsum dolor sit amet, consectetur adipiscing elit. * **Item 2** Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quod si ita est, sequitur id ipsum, quod te velle video, omnes semper beatos esse sapientes. Tamen a proposito, inquam, aberramus."] [p {:style {:width "600px" :min-width "50px" :color "red"}} ~text]]]]] (->> (hc/xform ht/empty-chart :TID :picframes :TOP top :BOTTOM bottom :LEFT left :RIGHT right) hmi/sv!)) ;;; With and without chart ;;; (let [text "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quod si ita est, sequitur id ipsum, quod te velle video, omnes semper beatos esse sapientes. Tamen a proposito, inquam, aberramus." top `[[gap :size "50px"] [p "Here's a 'typical' chart/plot filled picture frame." "It only has the top area" [:br] ~text]] left `[[gap :size "20px"] [p {:style {:width "200px" :min-width "50px"}} "This is an empty frame with a " [:span.bold "left "] "column of text" [:br] ~text ~text ~text ~text]] right `[[gap :size "30px"] [p {:style {:width "200px" :min-width "50px"}} "And a " [:span.bold "right "] "column of text" [:br] ~text ~text ~text ~text]]] (->> [(hc/xform ht/point-chart :TID :picframes :UDATA "data/cars.json" :TOP top :X "Horsepower" :Y "Miles_per_Gallon" :COLOR "Origin") (hc/xform ht/empty-chart :TID :picframes :LEFT left :RIGHT right)] hmi/sv!)) ;;; Rachel and Abhisheks tRNA experiment results - raw counts ;;; ;;; ***NOTE: this won't work for outside users as the data is not available!! ;;; (->> (let [data (->> "~/Bio/Rachel-Abhishek/lib-sq-counts.clj" fs/fullpath slurp read-string (coll/dropv 3) ;5 (coll/takev 3) ;5 (mapcat #(->> % (sort-by :cnt >) (coll/takev 50))) vec)] (hc/xform ht/grouped-bar-chart :TID :dists :TOPTS {:order :row :size "auto"} :WIDTH (-> 550 (/ 9) double Math/round (- 15)) :TITLE (format "Counts for %s" (->> data first :nm (str/split #"-") first)) :TOFFSET 40 :DATA data :X "nm" :XTYPE "nominal" :XTITLE "" :Y "cnt" :YTITLE "Count" :COLOR ht/default-color :COLUMN "sq" :COLTYPE "nominal" )) hmi/sv!)
27896
(ns bostonclj.examples (:require [clojure.string :as cljstr] [clojure.data.csv :as csv] [clojure.data.json :as json] [clojure.pprint :as pp :refer [pprint]] [aerial.fs :as fs] [aerial.utils.string :as str] [aerial.utils.io :refer [letio] :as io] [aerial.utils.coll :refer [vfold] :as coll] [aerial.utils.math :as m] [aerial.utils.math.probs-stats :as p] [aerial.utils.math.infoth :as it] [aerial.bio.utils.files :as bufiles] [aerial.bio.utils.aligners :as aln] [aerial.hanami.common :as hc :refer [RMV]] [aerial.hanami.templates :as ht] [aerial.hanami.core :as hmi] [aerial.saite.core :as saite])) (saite/start 3000) ;;; The ubiquitous simple car scatter plot via template (-> (hc/xform ht/point-chart :UDATA "data/cars.json" :X "Horsepower" :Y "Miles_per_Gallon" :COLOR "Origin") hmi/sv!) ;;; Another simple one right from IDL examples (-> (hc/xform ht/bar-chart :UDATA "data/seattle-weather.csv" :TOOLTIP RMV :X "date" :XTYPE "ordinal" :XUNIT "month" :Y "precipitation" :YAGG "mean") hmi/sv!) ;;; Simple barchart with slider instrument ;;; (->> (let [data [{:a "A", :b 28 }, {:a "B", :b 55 }, {:a "C", :b 43 }, {:a "D", :b 91 }, {:a "E", :b 81 }, {:a "F", :b 53 }, {:a "G", :b 19 }, {:a "H", :b 87 }, {:a "I", :b 52 }] min -10.0 minstr (-> min str (cljstr/split #"\.") first) max 10.0 maxstr (-> max str (cljstr/split #"\.") first (#(str "+" %))) bottom `[[gap :size "50px"] [v-box :children [[p "some text to test, default 14px"] [p {:style {:font-size "16px"}} "some tex \\(f(x) = x^2\\), 16px"] [p {:style {:font-size "18px"}} "\\(f(x) = \\sqrt x\\), 18px"] [p {:style {:font-size "20px"}} "\\(ax^2 + bx + c = 0\\), 20px"]]]]] (hc/xform ht/bar-chart :USERDATA (merge (hc/get-default :USERDATA) {:slider `[[gap :size "10px"] [label :label "Add Bar"] [label :label ~minstr] [slider :model :m1 :min ~min, :max ~max, :step 1.0 :width "200px" :on-change :oc1] [label :label ~maxstr] [input-text :model :m1 :width "60px", :height "26px" :on-change :oc2]]}) :HEIGHT 300, :WIDTH 350 :VID :bc1 ;:BOTTOM bottom :X "a" :XTYPE "ordinal" :XTITLE "Foo" :Y "b" :YTITLE "Bar" :DATA data)) hmi/sv!) ;;; Overview + Detail ;;; (hc/update-defaults :WIDTH 480 :HEIGHT 200) ;;; (hc/update-defaults :HEIGHT 400 :WIDTH 450) (->> (hc/xform ht/vconcat-chart :UDATA "data/sp500.csv", :VCONCAT [(hc/xform ht/area-chart :X :date, :XTYPE :temporal, :XSCALE {:domain {:selection :brush}} :Y :price) (hc/xform ht/area-chart :HEIGHT 60, :SELECTION {:brush {:type :interval, :encodings [:x]}}, :X :date :XTYPE :temporal :Y :price, :YAXIS {:tickCount 3, :grid false})]) hmi/sv!) ;;; Area Chart (-> (hc/xform ht/area-chart :UDATA "data/unemployment-across-industries.json" :TOOLTIP RMV :X :date, :XTYPE :temporal, :XUNIT :yearmonth, :XFORMAT "%Y" :Y "count" :AGG "sum" :COLOR {:field "series", :type "nominal", :scale {:scheme "category20b"}}) hmi/sv!) ;;; Grid example ;;; (hc/get-default :TOOLTIP) ;;; (hc/xform {:tt :TOOLTIP}) ;;; (hc/update-defaults :HEIGHT 200 :WIDTH 250) ;;; (hc/update-defaults :HEIGHT 400 :WIDTH 450) (->> (mapv #(apply hc/xform %) [[ht/point-chart :UDATA "data/cars.json" ; :TOPTS {:order :col :size "none"} :X "Horsepower" :Y "Miles_per_Gallon" :COLOR "Origin"] (let [data (->> (range 0.005 0.999 0.001) (mapv (fn[p] {:x p, :y (- (m/log2 p)) :col "SI"})))] [ht/layer-chart :TITLE "Self Information (unexpectedness)" :LAYER [(hc/xform ht/xrule-layer :AGG "mean") (hc/xform ht/line-layer :XTITLE "Probability of event" :YTITLE "-log(p)")] :DATA data]) [ht/bar-chart :UDATA "data/seattle-weather.csv" :TOOLTIP RMV :X "date" :XTYPE "ordinal" :XUNIT "month" :Y "precipitation" :YAGG "mean"] [ht/layer-chart :UDATA "data/seattle-weather.csv" :LAYER [(hc/xform ht/bar-layer :TOOLTIP RMV :X "date" :XTYPE "ordinal" :XUNIT "month" :Y "precipitation" :YAGG "mean" :SELECTION {:brush {:type "interval", :encodings ["x"]}} :OPACITY {:condition {:selection "brush", :value 1}, :value 0.7}) (hc/xform ht/yrule-layer :TRANSFORM [{:filter {:selection "brush"}}] :Y "precipitation" :AGG "mean" :YRL-COLOR "firebrick")]]]) hmi/sv!) ;;; Some Tree Layouts. Note the mode is Vega! ;;; (->> [(hc/xform ht/tree-layout :OPTS (merge (hc/default-opts :vgl) {:mode "vega"}) :WIDTH 650, :HEIGHT 1600 :UDATA "data/flare.json" :LINKSHAPE "diagonal" :LAYOUT "tidy" :FONTSIZE 11 :CFIELD "depth") (hc/xform ht/tree-layout :OPTS (merge (hc/default-opts :vgl) {:mode "vega"}) :WIDTH 650, :HEIGHT 1600 :UDATA "data/flare.json" :LINKSHAPE "line" :LAYOUT "tidy" :FONTSIZE 11 :CFIELD "depth") (hc/xform ht/tree-layout :OPTS (merge (hc/default-opts :vgl) {:mode "vega"}) :WIDTH 650, :HEIGHT 1600 :UDATA "data/flare.json" :LINKSHAPE "orthogonal" :LAYOUT "cluster" :CFIELD "depth") (hc/xform ht/tree-layout :OPTS (merge (hc/default-opts :vgl) {:mode "vega"}) :WIDTH 650, :HEIGHT 1600 :UDATA "data/flare.json" :LINKSHAPE "curve" :LAYOUT "tidy" :CFIELD "depth")] hmi/sv!) ;;; Picture frames, hiccup, re-com, markdown, and LaTex ;;; ;;; With Mark Down and LaTex (let [data (->> (range 0.001 100.0 0.1) (mapv #(do {:x (ac/roundit %) :y (-> % Math/sqrt ac/roundit)})))] (->> (hc/xform ht/line-chart :VID :sqrt :TID :picframes :BOTTOM `[[gap :size "230px"] [p {:style {:font-size "18px"}} "\\(f(x) = \\sqrt x\\)"]] :RIGHT `[[gap :size "10px"] [v-box :children [(md "#### The square root function") (md "* \\\\(f(x) = \\\\sqrt x\\\\)") (md "* _two_\n* **three**")]]] :DATA data) hmi/sv!)) ;;; Each element on different chart ;;; (let [_ (hc/add-defaults :FMNM #(-> :SIDE % name cljstr/capitalize) :STYLE hc/RMV) frame-template {:frame {:SIDE `[[gap :size :GAP] [p {:style :STYLE} "This is the " [:span.bold :FMNM] " 'board' of a picture " [:span.italic.bold "frame."]]]}} frame-top (hc/xform frame-template :SIDE :top :GAP "10px") frame-left (hc/xform frame-template :SIDE :left :GAP "10px" :STYLE {:width "100px" :min-width "50px"}) frame-right (merge-with merge (hc/xform frame-template :SIDE :right :GAP "2px" :STYLE {:width "100px" :min-width "50px"}) (hc/xform frame-template :SIDE :left :GAP "2px" :STYLE {:width "100px" :min-width "50px" :color "white"})) frame-bot (hc/xform frame-template :SIDE :bottom :GAP "10px")] (->> (mapv #(hc/xform ht/point-chart :HEIGHT 200 :WIDTH 250 :TID :picframes :USERDATA (merge (hc/get-default :USERDATA) %) :UDATA "data/cars.json" :X "Horsepower" :Y "Miles_per_Gallon" :COLOR "Origin") [frame-top frame-left frame-bot frame-right]) hmi/sv!)) ;;; Picture frame - 4 elements (let [text "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quod si ita est, sequitur id ipsum, quod te velle video, omnes semper beatos esse sapientes. Tamen a proposito, inquam, aberramus." top `[[gap :size "150px"] [p "An example showing a " [:span.bold "picture "] [:span.italic.bold "frame"] ". This is the top 'board'" [:br] ~text]] left `[[gap :size "10px"] [p {:style {:width "100px" :min-width "50px"}} "Some text on the " [:span.bold "left:"] [:br] ~text]] right `[[gap :size "2px"] [p {:style {:width "200px" :min-width "50px" :font-size "20px" :color "red"}} "Some large text on the " [:span.bold "right:"] [:br] ~(.substring text 0 180)]] bottom `[[gap :size "200px"] [title :level :level3 :label [p {:style {:font-size "large"}} "Some text on the " [:span.bold "bottom"] [:br] "With a cool info button " [info-button :position :right-center :info [:p "Check out Saite Visualizer!" [:br] "Built with Hanami!" [:br] [hyperlink-href :label "Saite " :href "https://github.com/jsa-aerial/saite" :target "_blank"]]]]]]] (->> [(hc/xform ht/point-chart :TID :picframes :TOP top :BOTTOM bottom :LEFT left :RIGHT right :UDATA "data/cars.json" :X "Horsepower" :Y "Miles_per_Gallon" :COLOR "Origin")] hmi/sv!)) ;;; Empty picture frame - 4 elements ;;; (let [text "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quod si ita est, sequitur id ipsum, quod te velle video, omnes semper beatos esse sapientes. Tamen a proposito, inquam, aberramus." top `[[gap :size "50px"] [p {:style {:width "600px" :min-width "50px"}} "An example empty picture frame showing all four areas." " This is the " [:span.bold "top"] " area. " ~text ~text ~text]] left `[[gap :size "50px"] [p {:style {:width "300px" :min-width "50px"}} "The " [:span.bold "left "] "area as a column of text. " ~text ~text ~text ~text]] right `[[gap :size "70px"] [p {:style {:width "300px" :min-width "50px"}} "The " [:span.bold "right "] "area as a column of text. " ~text ~text ~text ~text]] bottom `[[gap :size "50px"] [v-box :children [[p {:style {:width "600px" :min-width "50px"}} "The " [:span.bold "bottom "] "area showing a variety of text. " [:span.italic ~text] [:span.bold ~text]] [p {:style {:width "400px" :min-width "50px" :font-size "20px"}} "some TeX: " "\\(f(x) = \\sqrt x\\)"] [md {:style {:font-size "16px" :color "blue"}} "#### Some Markup * **Item 1** Lorem ipsum dolor sit amet, consectetur adipiscing elit. * **Item 2** Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quod si ita est, sequitur id ipsum, quod te velle video, omnes semper beatos esse sapientes. Tamen a proposito, inquam, aberramus."] [p {:style {:width "600px" :min-width "50px" :color "red"}} ~text]]]]] (->> (hc/xform ht/empty-chart :TID :picframes :TOP top :BOTTOM bottom :LEFT left :RIGHT right) hmi/sv!)) ;;; With and without chart ;;; (let [text "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quod si ita est, sequitur id ipsum, quod te velle video, omnes semper beatos esse sapientes. Tamen a proposito, inquam, aberramus." top `[[gap :size "50px"] [p "Here's a 'typical' chart/plot filled picture frame." "It only has the top area" [:br] ~text]] left `[[gap :size "20px"] [p {:style {:width "200px" :min-width "50px"}} "This is an empty frame with a " [:span.bold "left "] "column of text" [:br] ~text ~text ~text ~text]] right `[[gap :size "30px"] [p {:style {:width "200px" :min-width "50px"}} "And a " [:span.bold "right "] "column of text" [:br] ~text ~text ~text ~text]]] (->> [(hc/xform ht/point-chart :TID :picframes :UDATA "data/cars.json" :TOP top :X "Horsepower" :Y "Miles_per_Gallon" :COLOR "Origin") (hc/xform ht/empty-chart :TID :picframes :LEFT left :RIGHT right)] hmi/sv!)) ;;; <NAME>achel and Ab<NAME>ks tRNA experiment results - raw counts ;;; ;;; ***NOTE: this won't work for outside users as the data is not available!! ;;; (->> (let [data (->> "~/Bio/Rachel-Abhishek/lib-sq-counts.clj" fs/fullpath slurp read-string (coll/dropv 3) ;5 (coll/takev 3) ;5 (mapcat #(->> % (sort-by :cnt >) (coll/takev 50))) vec)] (hc/xform ht/grouped-bar-chart :TID :dists :TOPTS {:order :row :size "auto"} :WIDTH (-> 550 (/ 9) double Math/round (- 15)) :TITLE (format "Counts for %s" (->> data first :nm (str/split #"-") first)) :TOFFSET 40 :DATA data :X "nm" :XTYPE "nominal" :XTITLE "" :Y "cnt" :YTITLE "Count" :COLOR ht/default-color :COLUMN "sq" :COLTYPE "nominal" )) hmi/sv!)
true
(ns bostonclj.examples (:require [clojure.string :as cljstr] [clojure.data.csv :as csv] [clojure.data.json :as json] [clojure.pprint :as pp :refer [pprint]] [aerial.fs :as fs] [aerial.utils.string :as str] [aerial.utils.io :refer [letio] :as io] [aerial.utils.coll :refer [vfold] :as coll] [aerial.utils.math :as m] [aerial.utils.math.probs-stats :as p] [aerial.utils.math.infoth :as it] [aerial.bio.utils.files :as bufiles] [aerial.bio.utils.aligners :as aln] [aerial.hanami.common :as hc :refer [RMV]] [aerial.hanami.templates :as ht] [aerial.hanami.core :as hmi] [aerial.saite.core :as saite])) (saite/start 3000) ;;; The ubiquitous simple car scatter plot via template (-> (hc/xform ht/point-chart :UDATA "data/cars.json" :X "Horsepower" :Y "Miles_per_Gallon" :COLOR "Origin") hmi/sv!) ;;; Another simple one right from IDL examples (-> (hc/xform ht/bar-chart :UDATA "data/seattle-weather.csv" :TOOLTIP RMV :X "date" :XTYPE "ordinal" :XUNIT "month" :Y "precipitation" :YAGG "mean") hmi/sv!) ;;; Simple barchart with slider instrument ;;; (->> (let [data [{:a "A", :b 28 }, {:a "B", :b 55 }, {:a "C", :b 43 }, {:a "D", :b 91 }, {:a "E", :b 81 }, {:a "F", :b 53 }, {:a "G", :b 19 }, {:a "H", :b 87 }, {:a "I", :b 52 }] min -10.0 minstr (-> min str (cljstr/split #"\.") first) max 10.0 maxstr (-> max str (cljstr/split #"\.") first (#(str "+" %))) bottom `[[gap :size "50px"] [v-box :children [[p "some text to test, default 14px"] [p {:style {:font-size "16px"}} "some tex \\(f(x) = x^2\\), 16px"] [p {:style {:font-size "18px"}} "\\(f(x) = \\sqrt x\\), 18px"] [p {:style {:font-size "20px"}} "\\(ax^2 + bx + c = 0\\), 20px"]]]]] (hc/xform ht/bar-chart :USERDATA (merge (hc/get-default :USERDATA) {:slider `[[gap :size "10px"] [label :label "Add Bar"] [label :label ~minstr] [slider :model :m1 :min ~min, :max ~max, :step 1.0 :width "200px" :on-change :oc1] [label :label ~maxstr] [input-text :model :m1 :width "60px", :height "26px" :on-change :oc2]]}) :HEIGHT 300, :WIDTH 350 :VID :bc1 ;:BOTTOM bottom :X "a" :XTYPE "ordinal" :XTITLE "Foo" :Y "b" :YTITLE "Bar" :DATA data)) hmi/sv!) ;;; Overview + Detail ;;; (hc/update-defaults :WIDTH 480 :HEIGHT 200) ;;; (hc/update-defaults :HEIGHT 400 :WIDTH 450) (->> (hc/xform ht/vconcat-chart :UDATA "data/sp500.csv", :VCONCAT [(hc/xform ht/area-chart :X :date, :XTYPE :temporal, :XSCALE {:domain {:selection :brush}} :Y :price) (hc/xform ht/area-chart :HEIGHT 60, :SELECTION {:brush {:type :interval, :encodings [:x]}}, :X :date :XTYPE :temporal :Y :price, :YAXIS {:tickCount 3, :grid false})]) hmi/sv!) ;;; Area Chart (-> (hc/xform ht/area-chart :UDATA "data/unemployment-across-industries.json" :TOOLTIP RMV :X :date, :XTYPE :temporal, :XUNIT :yearmonth, :XFORMAT "%Y" :Y "count" :AGG "sum" :COLOR {:field "series", :type "nominal", :scale {:scheme "category20b"}}) hmi/sv!) ;;; Grid example ;;; (hc/get-default :TOOLTIP) ;;; (hc/xform {:tt :TOOLTIP}) ;;; (hc/update-defaults :HEIGHT 200 :WIDTH 250) ;;; (hc/update-defaults :HEIGHT 400 :WIDTH 450) (->> (mapv #(apply hc/xform %) [[ht/point-chart :UDATA "data/cars.json" ; :TOPTS {:order :col :size "none"} :X "Horsepower" :Y "Miles_per_Gallon" :COLOR "Origin"] (let [data (->> (range 0.005 0.999 0.001) (mapv (fn[p] {:x p, :y (- (m/log2 p)) :col "SI"})))] [ht/layer-chart :TITLE "Self Information (unexpectedness)" :LAYER [(hc/xform ht/xrule-layer :AGG "mean") (hc/xform ht/line-layer :XTITLE "Probability of event" :YTITLE "-log(p)")] :DATA data]) [ht/bar-chart :UDATA "data/seattle-weather.csv" :TOOLTIP RMV :X "date" :XTYPE "ordinal" :XUNIT "month" :Y "precipitation" :YAGG "mean"] [ht/layer-chart :UDATA "data/seattle-weather.csv" :LAYER [(hc/xform ht/bar-layer :TOOLTIP RMV :X "date" :XTYPE "ordinal" :XUNIT "month" :Y "precipitation" :YAGG "mean" :SELECTION {:brush {:type "interval", :encodings ["x"]}} :OPACITY {:condition {:selection "brush", :value 1}, :value 0.7}) (hc/xform ht/yrule-layer :TRANSFORM [{:filter {:selection "brush"}}] :Y "precipitation" :AGG "mean" :YRL-COLOR "firebrick")]]]) hmi/sv!) ;;; Some Tree Layouts. Note the mode is Vega! ;;; (->> [(hc/xform ht/tree-layout :OPTS (merge (hc/default-opts :vgl) {:mode "vega"}) :WIDTH 650, :HEIGHT 1600 :UDATA "data/flare.json" :LINKSHAPE "diagonal" :LAYOUT "tidy" :FONTSIZE 11 :CFIELD "depth") (hc/xform ht/tree-layout :OPTS (merge (hc/default-opts :vgl) {:mode "vega"}) :WIDTH 650, :HEIGHT 1600 :UDATA "data/flare.json" :LINKSHAPE "line" :LAYOUT "tidy" :FONTSIZE 11 :CFIELD "depth") (hc/xform ht/tree-layout :OPTS (merge (hc/default-opts :vgl) {:mode "vega"}) :WIDTH 650, :HEIGHT 1600 :UDATA "data/flare.json" :LINKSHAPE "orthogonal" :LAYOUT "cluster" :CFIELD "depth") (hc/xform ht/tree-layout :OPTS (merge (hc/default-opts :vgl) {:mode "vega"}) :WIDTH 650, :HEIGHT 1600 :UDATA "data/flare.json" :LINKSHAPE "curve" :LAYOUT "tidy" :CFIELD "depth")] hmi/sv!) ;;; Picture frames, hiccup, re-com, markdown, and LaTex ;;; ;;; With Mark Down and LaTex (let [data (->> (range 0.001 100.0 0.1) (mapv #(do {:x (ac/roundit %) :y (-> % Math/sqrt ac/roundit)})))] (->> (hc/xform ht/line-chart :VID :sqrt :TID :picframes :BOTTOM `[[gap :size "230px"] [p {:style {:font-size "18px"}} "\\(f(x) = \\sqrt x\\)"]] :RIGHT `[[gap :size "10px"] [v-box :children [(md "#### The square root function") (md "* \\\\(f(x) = \\\\sqrt x\\\\)") (md "* _two_\n* **three**")]]] :DATA data) hmi/sv!)) ;;; Each element on different chart ;;; (let [_ (hc/add-defaults :FMNM #(-> :SIDE % name cljstr/capitalize) :STYLE hc/RMV) frame-template {:frame {:SIDE `[[gap :size :GAP] [p {:style :STYLE} "This is the " [:span.bold :FMNM] " 'board' of a picture " [:span.italic.bold "frame."]]]}} frame-top (hc/xform frame-template :SIDE :top :GAP "10px") frame-left (hc/xform frame-template :SIDE :left :GAP "10px" :STYLE {:width "100px" :min-width "50px"}) frame-right (merge-with merge (hc/xform frame-template :SIDE :right :GAP "2px" :STYLE {:width "100px" :min-width "50px"}) (hc/xform frame-template :SIDE :left :GAP "2px" :STYLE {:width "100px" :min-width "50px" :color "white"})) frame-bot (hc/xform frame-template :SIDE :bottom :GAP "10px")] (->> (mapv #(hc/xform ht/point-chart :HEIGHT 200 :WIDTH 250 :TID :picframes :USERDATA (merge (hc/get-default :USERDATA) %) :UDATA "data/cars.json" :X "Horsepower" :Y "Miles_per_Gallon" :COLOR "Origin") [frame-top frame-left frame-bot frame-right]) hmi/sv!)) ;;; Picture frame - 4 elements (let [text "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quod si ita est, sequitur id ipsum, quod te velle video, omnes semper beatos esse sapientes. Tamen a proposito, inquam, aberramus." top `[[gap :size "150px"] [p "An example showing a " [:span.bold "picture "] [:span.italic.bold "frame"] ". This is the top 'board'" [:br] ~text]] left `[[gap :size "10px"] [p {:style {:width "100px" :min-width "50px"}} "Some text on the " [:span.bold "left:"] [:br] ~text]] right `[[gap :size "2px"] [p {:style {:width "200px" :min-width "50px" :font-size "20px" :color "red"}} "Some large text on the " [:span.bold "right:"] [:br] ~(.substring text 0 180)]] bottom `[[gap :size "200px"] [title :level :level3 :label [p {:style {:font-size "large"}} "Some text on the " [:span.bold "bottom"] [:br] "With a cool info button " [info-button :position :right-center :info [:p "Check out Saite Visualizer!" [:br] "Built with Hanami!" [:br] [hyperlink-href :label "Saite " :href "https://github.com/jsa-aerial/saite" :target "_blank"]]]]]]] (->> [(hc/xform ht/point-chart :TID :picframes :TOP top :BOTTOM bottom :LEFT left :RIGHT right :UDATA "data/cars.json" :X "Horsepower" :Y "Miles_per_Gallon" :COLOR "Origin")] hmi/sv!)) ;;; Empty picture frame - 4 elements ;;; (let [text "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quod si ita est, sequitur id ipsum, quod te velle video, omnes semper beatos esse sapientes. Tamen a proposito, inquam, aberramus." top `[[gap :size "50px"] [p {:style {:width "600px" :min-width "50px"}} "An example empty picture frame showing all four areas." " This is the " [:span.bold "top"] " area. " ~text ~text ~text]] left `[[gap :size "50px"] [p {:style {:width "300px" :min-width "50px"}} "The " [:span.bold "left "] "area as a column of text. " ~text ~text ~text ~text]] right `[[gap :size "70px"] [p {:style {:width "300px" :min-width "50px"}} "The " [:span.bold "right "] "area as a column of text. " ~text ~text ~text ~text]] bottom `[[gap :size "50px"] [v-box :children [[p {:style {:width "600px" :min-width "50px"}} "The " [:span.bold "bottom "] "area showing a variety of text. " [:span.italic ~text] [:span.bold ~text]] [p {:style {:width "400px" :min-width "50px" :font-size "20px"}} "some TeX: " "\\(f(x) = \\sqrt x\\)"] [md {:style {:font-size "16px" :color "blue"}} "#### Some Markup * **Item 1** Lorem ipsum dolor sit amet, consectetur adipiscing elit. * **Item 2** Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quod si ita est, sequitur id ipsum, quod te velle video, omnes semper beatos esse sapientes. Tamen a proposito, inquam, aberramus."] [p {:style {:width "600px" :min-width "50px" :color "red"}} ~text]]]]] (->> (hc/xform ht/empty-chart :TID :picframes :TOP top :BOTTOM bottom :LEFT left :RIGHT right) hmi/sv!)) ;;; With and without chart ;;; (let [text "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quod si ita est, sequitur id ipsum, quod te velle video, omnes semper beatos esse sapientes. Tamen a proposito, inquam, aberramus." top `[[gap :size "50px"] [p "Here's a 'typical' chart/plot filled picture frame." "It only has the top area" [:br] ~text]] left `[[gap :size "20px"] [p {:style {:width "200px" :min-width "50px"}} "This is an empty frame with a " [:span.bold "left "] "column of text" [:br] ~text ~text ~text ~text]] right `[[gap :size "30px"] [p {:style {:width "200px" :min-width "50px"}} "And a " [:span.bold "right "] "column of text" [:br] ~text ~text ~text ~text]]] (->> [(hc/xform ht/point-chart :TID :picframes :UDATA "data/cars.json" :TOP top :X "Horsepower" :Y "Miles_per_Gallon" :COLOR "Origin") (hc/xform ht/empty-chart :TID :picframes :LEFT left :RIGHT right)] hmi/sv!)) ;;; PI:NAME:<NAME>END_PIachel and AbPI:NAME:<NAME>END_PIks tRNA experiment results - raw counts ;;; ;;; ***NOTE: this won't work for outside users as the data is not available!! ;;; (->> (let [data (->> "~/Bio/Rachel-Abhishek/lib-sq-counts.clj" fs/fullpath slurp read-string (coll/dropv 3) ;5 (coll/takev 3) ;5 (mapcat #(->> % (sort-by :cnt >) (coll/takev 50))) vec)] (hc/xform ht/grouped-bar-chart :TID :dists :TOPTS {:order :row :size "auto"} :WIDTH (-> 550 (/ 9) double Math/round (- 15)) :TITLE (format "Counts for %s" (->> data first :nm (str/split #"-") first)) :TOFFSET 40 :DATA data :X "nm" :XTYPE "nominal" :XTITLE "" :Y "cnt" :YTITLE "Count" :COLOR ht/default-color :COLUMN "sq" :COLTYPE "nominal" )) hmi/sv!)
[ { "context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"John Alan McDonald\" :date \"2016-12-22\"\n :doc \"Spikes function p", "end": 105, "score": 0.9998790621757507, "start": 87, "tag": "NAME", "value": "John Alan McDonald" } ]
src/test/clojure/taiga/test/classify/spikes/positive_fraction_probability.clj
wahpenayo/taiga
4
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "John Alan McDonald" :date "2016-12-22" :doc "Spikes function probability forest example." } taiga.test.classify.spikes.positive-fraction-probability (:require [clojure.pprint :as pp] [clojure.test :as test] [zana.api :as z] [taiga.api :as taiga] [taiga.test.tree :as tree] [taiga.test.classify.data.record :as record] [taiga.test.classify.data.defs :as defs])) ;; mvn -Dtest=taiga.test.classify.spikes.positive-fraction-probability clojure:test > tests.txt ;;------------------------------------------------------------------------------ (def nss (str *ns*)) (test/deftest spikes-positive-fraction-probability (z/seconds nss (z/reset-mersenne-twister-seeds) (let [options (defs/options (record/make-spikes-function 1.0)) train-freqs (z/frequencies record/true-class (:data options)) _ (println "train" train-freqs (/ (double (z/get train-freqs 1.0)) (z/count (:data options)))) test-freqs (z/frequencies record/true-class (:test-data options)) _ (println "test" test-freqs (/ (double (z/get test-freqs 1.0) ) (z/count (:test-data options)))) forest (taiga/positive-fraction-probability options) _ (z/mapc #(tree/check-mincount options %) (taiga/terms forest)) ;;_ (defs/serialization-test nss options forest) attributes (assoc record/attributes :ground-truth record/true-probability :prediction record/predicted-probability) predictors (into (sorted-map) (dissoc attributes :ground-truth :prediction)) ^clojure.lang.IFn$OD p record/true-probability ^clojure.lang.IFn$OD phat (fn phat ^double [datum] (.invokePrim forest predictors datum)) ^clojure.lang.IFn$OD chat (fn chat ^double [datum] (if (< (.invokePrim phat datum) 0.5) 0.0 1.0)) train-confusion (defs/confusion record/true-class chat (:data options)) train-confusion-rate (defs/confusion-rate train-confusion) train-mad (z/mean-absolute-difference p phat (:data options)) test-confusion (defs/confusion record/true-class chat (:test-data options)) test-confusion-rate (defs/confusion-rate test-confusion) test-mad (z/mean-absolute-difference p phat (:test-data options)) metrics {:mad taiga/mean-absolute-error :rmse taiga/rms-error}] (println "train:") (println train-confusion-rate) (println train-confusion) (test/is (== (float train-confusion-rate) (float 0.045867919921875))) (test/is (= [31265 1503 0 0] train-confusion)) (test/is (== (z/count (:data options)) (reduce + train-confusion))) (println "test:") (println test-confusion-rate) (println test-confusion) (test/is (== (float test-confusion-rate) (float 0.04827880859375))) (test/is (= [31186 1582 0 0] test-confusion)) (test/is (== (z/count (:test-data options)) (reduce + test-confusion))) (test/is (= (mapv taiga/node-height (taiga/terms forest)) [18 16 13 16 15 13 15 14 14 15 14 15 14 15 15 14 16 13 14 15 13 17 16 14 15 15 14 15 15 13 15 14 12 16 15 15 16 14 15 15 15 15 15 16 14 14 15 16 13 14 16 16 15 16 17 14 15 18 16 14 16 13 14 14 17 13 15 14 15 15 14 16 17 14 17 17 14 14 20 15 13 14 14 14 17 13 14 16 13 18 15 14 12 16 14 14 17 18 14 14 15 14 14 14 14 18 20 15 14 16 13 15 15 14 13 15 13 16 12 15 13 15 14 13 17 19 16 15] )) (test/is (= (mapv taiga/count-children (taiga/terms forest)) [183 187 197 211 209 191 197 175 191 233 191 185 205 209 209 203 227 203 189 197 195 197 195 187 213 205 227 225 199 217 205 209 199 201 225 215 207 207 217 219 227 213 189 195 221 209 227 195 213 193 235 215 207 231 215 213 233 201 195 225 227 191 193 217 213 197 203 213 205 189 211 195 211 197 227 213 201 227 215 223 209 207 215 203 207 195 217 205 211 233 221 185 169 233 191 217 207 225 201 179 201 237 211 205 205 243 211 183 193 201 219 215 207 217 197 211 209 209 207 231 203 229 193 193 199 215 211 201] )) (test/is (= (mapv taiga/count-leaves (taiga/terms forest)) [92 94 99 106 105 96 99 88 96 117 96 93 103 105 105 102 114 102 95 99 98 99 98 94 107 103 114 113 100 109 103 105 100 101 113 108 104 104 109 110 114 107 95 98 111 105 114 98 107 97 118 108 104 116 108 107 117 101 98 113 114 96 97 109 107 99 102 107 103 95 106 98 106 99 114 107 101 114 108 112 105 104 108 102 104 98 109 103 106 117 111 93 85 117 96 109 104 113 101 90 101 119 106 103 103 122 106 92 97 101 110 108 104 109 99 106 105 105 104 116 102 115 97 97 100 108 106 101] )) (println "train" train-mad) (test/is (== (float train-mad) (float 0.03144772226810712))) (println "test" test-mad) (test/is (== (float test-mad) (float 0.033051658940432944))) (println "train importance:") (pp/pprint (taiga/permutation-statistics metrics forest attributes (:data options))) (println "test importance:") (pp/pprint (taiga/permutation-statistics metrics forest attributes (:test-data options))) (defs/write-predictions nss options "train" forest (defs/predictions phat (:data options) :predicted-probability)) (defs/write-predictions nss options "test" forest (defs/predictions phat (:test-data options) :predicted-probability)) #_(defs/by-nterms nss options forest predictors)))) ;;------------------------------------------------------------------------------
97646
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "<NAME>" :date "2016-12-22" :doc "Spikes function probability forest example." } taiga.test.classify.spikes.positive-fraction-probability (:require [clojure.pprint :as pp] [clojure.test :as test] [zana.api :as z] [taiga.api :as taiga] [taiga.test.tree :as tree] [taiga.test.classify.data.record :as record] [taiga.test.classify.data.defs :as defs])) ;; mvn -Dtest=taiga.test.classify.spikes.positive-fraction-probability clojure:test > tests.txt ;;------------------------------------------------------------------------------ (def nss (str *ns*)) (test/deftest spikes-positive-fraction-probability (z/seconds nss (z/reset-mersenne-twister-seeds) (let [options (defs/options (record/make-spikes-function 1.0)) train-freqs (z/frequencies record/true-class (:data options)) _ (println "train" train-freqs (/ (double (z/get train-freqs 1.0)) (z/count (:data options)))) test-freqs (z/frequencies record/true-class (:test-data options)) _ (println "test" test-freqs (/ (double (z/get test-freqs 1.0) ) (z/count (:test-data options)))) forest (taiga/positive-fraction-probability options) _ (z/mapc #(tree/check-mincount options %) (taiga/terms forest)) ;;_ (defs/serialization-test nss options forest) attributes (assoc record/attributes :ground-truth record/true-probability :prediction record/predicted-probability) predictors (into (sorted-map) (dissoc attributes :ground-truth :prediction)) ^clojure.lang.IFn$OD p record/true-probability ^clojure.lang.IFn$OD phat (fn phat ^double [datum] (.invokePrim forest predictors datum)) ^clojure.lang.IFn$OD chat (fn chat ^double [datum] (if (< (.invokePrim phat datum) 0.5) 0.0 1.0)) train-confusion (defs/confusion record/true-class chat (:data options)) train-confusion-rate (defs/confusion-rate train-confusion) train-mad (z/mean-absolute-difference p phat (:data options)) test-confusion (defs/confusion record/true-class chat (:test-data options)) test-confusion-rate (defs/confusion-rate test-confusion) test-mad (z/mean-absolute-difference p phat (:test-data options)) metrics {:mad taiga/mean-absolute-error :rmse taiga/rms-error}] (println "train:") (println train-confusion-rate) (println train-confusion) (test/is (== (float train-confusion-rate) (float 0.045867919921875))) (test/is (= [31265 1503 0 0] train-confusion)) (test/is (== (z/count (:data options)) (reduce + train-confusion))) (println "test:") (println test-confusion-rate) (println test-confusion) (test/is (== (float test-confusion-rate) (float 0.04827880859375))) (test/is (= [31186 1582 0 0] test-confusion)) (test/is (== (z/count (:test-data options)) (reduce + test-confusion))) (test/is (= (mapv taiga/node-height (taiga/terms forest)) [18 16 13 16 15 13 15 14 14 15 14 15 14 15 15 14 16 13 14 15 13 17 16 14 15 15 14 15 15 13 15 14 12 16 15 15 16 14 15 15 15 15 15 16 14 14 15 16 13 14 16 16 15 16 17 14 15 18 16 14 16 13 14 14 17 13 15 14 15 15 14 16 17 14 17 17 14 14 20 15 13 14 14 14 17 13 14 16 13 18 15 14 12 16 14 14 17 18 14 14 15 14 14 14 14 18 20 15 14 16 13 15 15 14 13 15 13 16 12 15 13 15 14 13 17 19 16 15] )) (test/is (= (mapv taiga/count-children (taiga/terms forest)) [183 187 197 211 209 191 197 175 191 233 191 185 205 209 209 203 227 203 189 197 195 197 195 187 213 205 227 225 199 217 205 209 199 201 225 215 207 207 217 219 227 213 189 195 221 209 227 195 213 193 235 215 207 231 215 213 233 201 195 225 227 191 193 217 213 197 203 213 205 189 211 195 211 197 227 213 201 227 215 223 209 207 215 203 207 195 217 205 211 233 221 185 169 233 191 217 207 225 201 179 201 237 211 205 205 243 211 183 193 201 219 215 207 217 197 211 209 209 207 231 203 229 193 193 199 215 211 201] )) (test/is (= (mapv taiga/count-leaves (taiga/terms forest)) [92 94 99 106 105 96 99 88 96 117 96 93 103 105 105 102 114 102 95 99 98 99 98 94 107 103 114 113 100 109 103 105 100 101 113 108 104 104 109 110 114 107 95 98 111 105 114 98 107 97 118 108 104 116 108 107 117 101 98 113 114 96 97 109 107 99 102 107 103 95 106 98 106 99 114 107 101 114 108 112 105 104 108 102 104 98 109 103 106 117 111 93 85 117 96 109 104 113 101 90 101 119 106 103 103 122 106 92 97 101 110 108 104 109 99 106 105 105 104 116 102 115 97 97 100 108 106 101] )) (println "train" train-mad) (test/is (== (float train-mad) (float 0.03144772226810712))) (println "test" test-mad) (test/is (== (float test-mad) (float 0.033051658940432944))) (println "train importance:") (pp/pprint (taiga/permutation-statistics metrics forest attributes (:data options))) (println "test importance:") (pp/pprint (taiga/permutation-statistics metrics forest attributes (:test-data options))) (defs/write-predictions nss options "train" forest (defs/predictions phat (:data options) :predicted-probability)) (defs/write-predictions nss options "test" forest (defs/predictions phat (:test-data options) :predicted-probability)) #_(defs/by-nterms nss options forest predictors)))) ;;------------------------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "PI:NAME:<NAME>END_PI" :date "2016-12-22" :doc "Spikes function probability forest example." } taiga.test.classify.spikes.positive-fraction-probability (:require [clojure.pprint :as pp] [clojure.test :as test] [zana.api :as z] [taiga.api :as taiga] [taiga.test.tree :as tree] [taiga.test.classify.data.record :as record] [taiga.test.classify.data.defs :as defs])) ;; mvn -Dtest=taiga.test.classify.spikes.positive-fraction-probability clojure:test > tests.txt ;;------------------------------------------------------------------------------ (def nss (str *ns*)) (test/deftest spikes-positive-fraction-probability (z/seconds nss (z/reset-mersenne-twister-seeds) (let [options (defs/options (record/make-spikes-function 1.0)) train-freqs (z/frequencies record/true-class (:data options)) _ (println "train" train-freqs (/ (double (z/get train-freqs 1.0)) (z/count (:data options)))) test-freqs (z/frequencies record/true-class (:test-data options)) _ (println "test" test-freqs (/ (double (z/get test-freqs 1.0) ) (z/count (:test-data options)))) forest (taiga/positive-fraction-probability options) _ (z/mapc #(tree/check-mincount options %) (taiga/terms forest)) ;;_ (defs/serialization-test nss options forest) attributes (assoc record/attributes :ground-truth record/true-probability :prediction record/predicted-probability) predictors (into (sorted-map) (dissoc attributes :ground-truth :prediction)) ^clojure.lang.IFn$OD p record/true-probability ^clojure.lang.IFn$OD phat (fn phat ^double [datum] (.invokePrim forest predictors datum)) ^clojure.lang.IFn$OD chat (fn chat ^double [datum] (if (< (.invokePrim phat datum) 0.5) 0.0 1.0)) train-confusion (defs/confusion record/true-class chat (:data options)) train-confusion-rate (defs/confusion-rate train-confusion) train-mad (z/mean-absolute-difference p phat (:data options)) test-confusion (defs/confusion record/true-class chat (:test-data options)) test-confusion-rate (defs/confusion-rate test-confusion) test-mad (z/mean-absolute-difference p phat (:test-data options)) metrics {:mad taiga/mean-absolute-error :rmse taiga/rms-error}] (println "train:") (println train-confusion-rate) (println train-confusion) (test/is (== (float train-confusion-rate) (float 0.045867919921875))) (test/is (= [31265 1503 0 0] train-confusion)) (test/is (== (z/count (:data options)) (reduce + train-confusion))) (println "test:") (println test-confusion-rate) (println test-confusion) (test/is (== (float test-confusion-rate) (float 0.04827880859375))) (test/is (= [31186 1582 0 0] test-confusion)) (test/is (== (z/count (:test-data options)) (reduce + test-confusion))) (test/is (= (mapv taiga/node-height (taiga/terms forest)) [18 16 13 16 15 13 15 14 14 15 14 15 14 15 15 14 16 13 14 15 13 17 16 14 15 15 14 15 15 13 15 14 12 16 15 15 16 14 15 15 15 15 15 16 14 14 15 16 13 14 16 16 15 16 17 14 15 18 16 14 16 13 14 14 17 13 15 14 15 15 14 16 17 14 17 17 14 14 20 15 13 14 14 14 17 13 14 16 13 18 15 14 12 16 14 14 17 18 14 14 15 14 14 14 14 18 20 15 14 16 13 15 15 14 13 15 13 16 12 15 13 15 14 13 17 19 16 15] )) (test/is (= (mapv taiga/count-children (taiga/terms forest)) [183 187 197 211 209 191 197 175 191 233 191 185 205 209 209 203 227 203 189 197 195 197 195 187 213 205 227 225 199 217 205 209 199 201 225 215 207 207 217 219 227 213 189 195 221 209 227 195 213 193 235 215 207 231 215 213 233 201 195 225 227 191 193 217 213 197 203 213 205 189 211 195 211 197 227 213 201 227 215 223 209 207 215 203 207 195 217 205 211 233 221 185 169 233 191 217 207 225 201 179 201 237 211 205 205 243 211 183 193 201 219 215 207 217 197 211 209 209 207 231 203 229 193 193 199 215 211 201] )) (test/is (= (mapv taiga/count-leaves (taiga/terms forest)) [92 94 99 106 105 96 99 88 96 117 96 93 103 105 105 102 114 102 95 99 98 99 98 94 107 103 114 113 100 109 103 105 100 101 113 108 104 104 109 110 114 107 95 98 111 105 114 98 107 97 118 108 104 116 108 107 117 101 98 113 114 96 97 109 107 99 102 107 103 95 106 98 106 99 114 107 101 114 108 112 105 104 108 102 104 98 109 103 106 117 111 93 85 117 96 109 104 113 101 90 101 119 106 103 103 122 106 92 97 101 110 108 104 109 99 106 105 105 104 116 102 115 97 97 100 108 106 101] )) (println "train" train-mad) (test/is (== (float train-mad) (float 0.03144772226810712))) (println "test" test-mad) (test/is (== (float test-mad) (float 0.033051658940432944))) (println "train importance:") (pp/pprint (taiga/permutation-statistics metrics forest attributes (:data options))) (println "test importance:") (pp/pprint (taiga/permutation-statistics metrics forest attributes (:test-data options))) (defs/write-predictions nss options "train" forest (defs/predictions phat (:data options) :predicted-probability)) (defs/write-predictions nss options "test" forest (defs/predictions phat (:test-data options) :predicted-probability)) #_(defs/by-nterms nss options forest predictors)))) ;;------------------------------------------------------------------------------
[ { "context": " [:= [:field (mt/id table-kw field-kw) nil] \"Krua Siri\"]}}})\n\n(defn- mbql-card-referencing-venue-n", "end": 34378, "score": 0.7008533477783203, "start": 34375, "tag": "NAME", "value": "Kru" }, { "context": "aram)\n\n(deftest should-parse-string\n (is (= [10 \"Fred 62\"]\n (#'public-api/field-remapped-values", "end": 50356, "score": 0.9886537790298462, "start": 50352, "tag": "NAME", "value": "Fred" }, { "context": "rd-referencing :venues :id [card]\n (is (= [10 \"Fred 62\"]\n (http/client :get 200 (field-remappi", "end": 51312, "score": 0.9564272165298462, "start": 51305, "tag": "NAME", "value": "Fred 62" }, { "context": "ferencing :venues :id [dashboard]\n (is (= [10 \"Fred 62\"]\n (http/client :get 200 (field-remappi", "end": 52759, "score": 0.9744061231613159, "start": 52752, "tag": "NAME", "value": "Fred 62" } ]
c#-metabase/test/metabase/api/public_test.clj
hanakhry/Crime_Admin
0
(ns metabase.api.public-test "Tests for `api/public/` (public links) endpoints." (:require [cheshire.core :as json] [clojure.string :as str] [clojure.test :refer :all] [dk.ative.docjure.spreadsheet :as spreadsheet] [metabase.api.dashboard-test :as dashboard-api-test] [metabase.api.pivots :as pivots] [metabase.api.public :as public-api] [metabase.http-client :as http] [metabase.models :refer [Card Collection Dashboard DashboardCard DashboardCardSeries Dimension Field FieldValues]] [metabase.models.permissions :as perms] [metabase.models.permissions-group :as group] [metabase.test :as mt] [metabase.util :as u] [toucan.db :as db]) (:import java.io.ByteArrayInputStream java.util.UUID)) ;;; --------------------------------------------------- Helper Fns --------------------------------------------------- (defn count-of-venues-card [] {:dataset_query (mt/mbql-query venues {:aggregation [[:count]]})}) (defn shared-obj [] {:public_uuid (str (UUID/randomUUID)) :made_public_by_id (mt/user->id :crowberto)}) (defmacro with-temp-public-card {:style/indent 1} [[binding & [card]] & body] `(let [card-defaults# ~card card-settings# (merge (when-not (:dataset_query card-defaults#) (count-of-venues-card)) (shared-obj) card-defaults#)] (mt/with-temp Card [card# card-settings#] ;; add :public_uuid back in to the value that gets bound because it might not come back from post-select if ;; public sharing is disabled; but we still want to test it (let [~binding (assoc card# :public_uuid (:public_uuid card-settings#))] ~@body)))) (defmacro with-temp-public-dashboard {:style/indent 1} [[binding & [dashboard]] & body] `(let [dashboard-defaults# ~dashboard dashboard-settings# (merge (when-not (:parameters dashboard-defaults#) {:parameters [{:id "_VENUE_ID_" :name "Venue ID" :slug "venue_id" :type "id" :target [:dimension (mt/id :venues :id)] :default nil}]}) (shared-obj) dashboard-defaults#)] (mt/with-temp Dashboard [dashboard# dashboard-settings#] (let [~binding (assoc dashboard# :public_uuid (:public_uuid dashboard-settings#))] ~@body)))) (defn add-card-to-dashboard! {:style/indent 2} [card dashboard & {:as kvs}] (db/insert! DashboardCard (merge {:dashboard_id (u/the-id dashboard), :card_id (u/the-id card)} kvs))) (defmacro ^:private with-temp-public-dashboard-and-card {:style/indent 1} [[dashboard-binding card-binding & [dashcard-binding]] & body] `(with-temp-public-dashboard [dash#] (with-temp-public-card [card#] (let [~dashboard-binding dash# ~card-binding card# ~(or dashcard-binding (gensym "dashcard")) (add-card-to-dashboard! card# dash#)] ~@body)))) ;;; ------------------------------------------- GET /api/public/card/:uuid ------------------------------------------- (deftest check-that-we--cannot--fetch-a-publiccard-if-the-setting-is-disabled (mt/with-temporary-setting-values [enable-public-sharing false] (with-temp-public-card [{uuid :public_uuid}] (is (= "An error occurred." (http/client :get 400 (str "public/card/" uuid))))))) (deftest check-that-we-get-a-400-if-the-publiccard-doesn-t-exist (mt/with-temporary-setting-values [enable-public-sharing true] (is (= "An error occurred." (http/client :get 400 (str "public/card/" (UUID/randomUUID))))))) (deftest check-that-we--cannot--fetch-a-publiccard-if-the-card-has-been-archived (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-card [{uuid :public_uuid} {:archived true}] (is (= "An error occurred." (http/client :get 400 (str "public/card/" uuid))))))) (deftest check-that-we-can-fetch-a-publiccard (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-card [{uuid :public_uuid}] (is (= #{:dataset_query :description :display :id :name :visualization_settings :param_values :param_fields} (set (keys (http/client :get 200 (str "public/card/" uuid))))))))) (deftest make-sure--param-values-get-returned-as-expected (mt/with-temp Card [card {:dataset_query {:database (mt/id) :type :native :native {:query (str "SELECT COUNT(*) " "FROM venues " "LEFT JOIN categories ON venues.category_id = categories.id " "WHERE {{category}}") :collection "CATEGORIES" :template-tags {:category {:name "category" :display-name "Category" :type "dimension" :dimension ["field" (mt/id :categories :name) nil] :widget-type "category" :required true}}}}}] (is (= {(mt/id :categories :name) {:values 75 :human_readable_values [] :field_id (mt/id :categories :name)}} (-> (:param_values (#'public-api/public-card :id (u/the-id card))) (update-in [(mt/id :categories :name) :values] count) (update (mt/id :categories :name) #(into {} %))))))) ;;; ------------------------- GET /api/public/card/:uuid/query (and JSON/CSV/XSLX versions) -------------------------- (deftest check-that-we--cannot--execute-a-publiccard-if-the-setting-is-disabled (mt/with-temporary-setting-values [enable-public-sharing false] (with-temp-public-card [{uuid :public_uuid}] (is (= "An error occurred." (http/client :get 400 (str "public/card/" uuid "/query"))))))) (deftest check-that-we-get-a-400-if-the-publiccard-doesn-t-exist-query (mt/with-temporary-setting-values [enable-public-sharing true] (is (= "An error occurred." (http/client :get 400 (str "public/card/" (UUID/randomUUID) "/query")))))) (deftest check-that-we--cannot--execute-a-publiccard-if-the-card-has-been-archived (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-card [{uuid :public_uuid} {:archived true}] (is (= "An error occurred." (http/client :get 400 (str "public/card/" uuid "/query"))))))) (defn- parse-xlsx-response [response] (->> (ByteArrayInputStream. response) spreadsheet/load-workbook (spreadsheet/select-sheet "Query result") (spreadsheet/select-columns {:A :col}))) (deftest execute-public-card-test (testing "GET /api/public/card/:uuid/query" (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-card [{uuid :public_uuid}] (testing "Default :api response format" (is (= [[100]] (mt/rows (http/client :get 202 (str "public/card/" uuid "/query")))))) (testing ":json download response format" (is (= [{:Count 100}] (http/client :get 200 (str "public/card/" uuid "/query/json"))))) (testing ":csv download response format" (is (= "Count\n100\n" (http/client :get 200 (str "public/card/" uuid "/query/csv"), :format :csv)))) (testing ":xlsx download response format" (is (= [{:col "Count"} {:col 100.0}] (parse-xlsx-response (http/client :get 200 (str "public/card/" uuid "/query/xlsx") {:request-options {:as :byte-array}}))))))))) (deftest execute-public-card-as-user-without-perms-test (testing "A user that doesn't have permissions to run the query normally should still be able to run a public Card as if they weren't logged in" (mt/with-temporary-setting-values [enable-public-sharing true] (mt/with-temp Collection [{collection-id :id}] (perms/revoke-collection-permissions! (group/all-users) collection-id) (with-temp-public-card [{card-id :id, uuid :public_uuid} {:collection_id collection-id}] (is (= "You don't have permissions to do that." ((mt/user->client :rasta) :post 403 (format "card/%d/query" card-id))) "Sanity check: shouldn't be allowed to run the query normally") (is (= [[100]] (mt/rows ((mt/user->client :rasta) :get 202 (str "public/card/" uuid "/query")))))))))) (deftest check-that-we-can-exec-a-publiccard-with---parameters- (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-card [{uuid :public_uuid}] (is (= [{:id "_VENUE_ID_", :name "Venue ID", :slug "venue_id", :type "id", :value 2}] (get-in (http/client :get 202 (str "public/card/" uuid "/query") :parameters (json/encode [{:id "_VENUE_ID_" :name "Venue ID" :slug "venue_id" :type "id" :value 2}])) [:json_query :parameters])))))) ;; Cards with required params (defn- do-with-required-param-card [f] (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-card [{uuid :public_uuid} {:dataset_query {:database (mt/id) :type :native :native {:query "SELECT count(*) FROM venues v WHERE price = {{price}}" :template-tags {"price" {:name "price" :display-name "Price" :type :number :required true}}}}}] (f uuid)))) (defmacro ^:private with-required-param-card [[uuid-binding] & body] `(do-with-required-param-card (fn [~uuid-binding] ~@body))) (deftest should-be-able-to-run-a-card-with-a-required-param (with-required-param-card [uuid] (is (= [[22]] (mt/rows (http/client :get 202 (str "public/card/" uuid "/query") :parameters (json/encode [{:type "category" :target [:variable [:template-tag "price"]] :value 1}]))))))) (deftest missing-required-param-error-message-test (testing (str "If you're missing a required param, the error message should get passed thru, rather than the normal " "generic 'Query Failed' message that we show for most embedding errors") (with-required-param-card [uuid] (is (= {:status "failed" :error "You'll need to pick a value for 'Price' before this query can run." :error_type "missing-required-parameter"} (mt/suppress-output (http/client :get 202 (str "public/card/" uuid "/query")))))))) (defn- card-with-date-field-filter [] (assoc (shared-obj) :dataset_query {:database (mt/id) :type :native :native {:query "SELECT COUNT(*) AS \"count\" FROM CHECKINS WHERE {{date}}" :template-tags {:date {:name "date" :display-name "Date" :type "dimension" :dimension [:field (mt/id :checkins :date) nil] :widget-type "date/quarter-year"}}}})) (deftest make-sure-csv--etc---downloads-take-editable-params-into-account---6407---- (mt/with-temporary-setting-values [enable-public-sharing true] (mt/with-temp Card [{uuid :public_uuid} (card-with-date-field-filter)] (is (= "count\n107\n" (http/client :get 200 (str "public/card/" uuid "/query/csv") :parameters (json/encode [{:id "_DATE_" :type :date/quarter-year :target [:dimension [:template-tag :date]] :value "Q1-2014"}]))))))) (deftest make-sure-it-also-works-with-the-forwarded-url (mt/with-temporary-setting-values [enable-public-sharing true] (mt/with-temp Card [{uuid :public_uuid} (card-with-date-field-filter)] ;; make sure the URL doesn't include /api/ at the beginning like it normally would (binding [http/*url-prefix* (str/replace http/*url-prefix* #"/api/$" "/")] (mt/with-temporary-setting-values [site-url http/*url-prefix*] (is (= "count\n107\n" (http/client :get 200 (str "public/question/" uuid ".csv") :parameters (json/encode [{:id "_DATE_" :type :date/quarter-year :target [:dimension [:template-tag :date]] :value "Q1-2014"}]))))))))) (defn- card-with-trendline [] (assoc (shared-obj) :dataset_query {:database (mt/id) :type :query :query {:source-table (mt/id :checkins) :breakout [[:datetime-field [:field (mt/id :checkins :date) nil] :month]] :aggregation [[:count]]}})) (deftest make-sure-we-include-all-the-relevant-fields-like-insights (mt/with-temporary-setting-values [enable-public-sharing true] (mt/with-temp Card [{uuid :public_uuid} (card-with-trendline)] (is (= #{:cols :rows :insights :results_timezone} (-> (http/client :get 202 (str "public/card/" uuid "/query")) :data keys set)))))) ;;; ---------------------------------------- GET /api/public/dashboard/:uuid ----------------------------------------- (deftest get-public-dashboard-errors-test (testing "GET /api/public/dashboard/:uuid" (testing "Shouldn't be able to fetch a public Dashboard if public sharing is disabled" (mt/with-temporary-setting-values [enable-public-sharing false] (with-temp-public-dashboard [{uuid :public_uuid}] (is (= "An error occurred." (http/client :get 400 (str "public/dashboard/" uuid))))))) (testing "Should get a 400 if the Dashboard doesn't exist" (mt/with-temporary-setting-values [enable-public-sharing true] (is (= "An error occurred." (http/client :get 400 (str "public/dashboard/" (UUID/randomUUID))))))))) (defn- fetch-public-dashboard [{uuid :public_uuid}] (-> (http/client :get 200 (str "public/dashboard/" uuid)) (select-keys [:name :ordered_cards]) (update :name boolean) (update :ordered_cards count))) (deftest get-public-dashboard-test (testing "GET /api/public/dashboard/:uuid" (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-dashboard-and-card [dash card] (is (= {:name true, :ordered_cards 1} (fetch-public-dashboard dash))) (testing "We shouldn't see Cards that have been archived" (db/update! Card (u/the-id card), :archived true) (is (= {:name true, :ordered_cards 0} (fetch-public-dashboard dash)))))))) ;;; --------------------------------- GET /api/public/dashboard/:uuid/card/:card-id ---------------------------------- (defn- dashcard-url "URL for fetching results of a public DashCard." [dash card] (str "public/dashboard/" (:public_uuid dash) "/card/" (u/the-id card))) (deftest execute-public-dashcard-errors-test (testing "GET /api/public/dashboard/:uuid/card/:card-id" (testing "Shouldn't be able to execute a public DashCard if public sharing is disabled" (mt/with-temporary-setting-values [enable-public-sharing false] (with-temp-public-dashboard-and-card [dash card] (is (= "An error occurred." (http/client :get 400 (dashcard-url dash card))))))) (testing "Should get a 400" (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-dashboard-and-card [dash card] (testing "if the Dashboard doesn't exist" (is (= "An error occurred." (http/client :get 400 (dashcard-url {:public_uuid (UUID/randomUUID)} card))))) (testing "if the Card doesn't exist" (is (= "An error occurred." (http/client :get 400 (dashcard-url dash Integer/MAX_VALUE))))) (testing "if the Card exists, but it's not part of this Dashboard" (mt/with-temp Card [card] (is (= "An error occurred." (http/client :get 400 (dashcard-url dash card)))))) (testing "if the Card has been archived." (db/update! Card (u/the-id card), :archived true) (is (= "An error occurred." (http/client :get 400 (dashcard-url dash card)))))))))) (deftest execute-public-dashcard-test (testing "GET /api/public/dashboard/:uuid/card/:card-id" (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-dashboard-and-card [dash card] (is (= [[100]] (mt/rows (http/client :get 202 (dashcard-url dash card))))) (testing "with parameters" (is (= [{:id "_VENUE_ID_" :name "Venue ID" :slug "venue_id" :target ["dimension" (mt/id :venues :id)] :value [10] :default nil :type "id"}] (get-in (http/client :get 202 (dashcard-url dash card) :parameters (json/encode [{:name "Venue ID" :slug :venue_id :target [:dimension (mt/id :venues :id)] :value [10]}])) [:json_query :parameters])))))))) (deftest execute-public-dashcard-as-user-without-perms-test (testing "GET /api/public/dashboard/:uuid/card/:card-id" (testing "A user that doesn't have permissions to run the query normally should still be able to run a public DashCard" (mt/with-temporary-setting-values [enable-public-sharing true] (mt/with-temp Collection [{collection-id :id}] (perms/revoke-collection-permissions! (group/all-users) collection-id) (with-temp-public-dashboard-and-card [dash {card-id :id, :as card}] (db/update! Card card-id :collection_id collection-id) (is (= "You don't have permissions to do that." ((mt/user->client :rasta) :post 403 (format "card/%d/query" card-id))) "Sanity check: shouldn't be allowed to run the query normally") (is (= [[100]] (mt/rows ((mt/user->client :rasta) :get 202 (dashcard-url dash card))))))))))) (deftest execute-public-dashcard-params-validation-test (testing "GET /api/public/dashboard/:uuid/card/:card-id" (testing "Make sure params are validated" (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-dashboard-and-card [dash card] (testing "Should work correctly with a valid parameter" (is (= [[1]] (mt/rows (http/client :get 202 (dashcard-url dash card) :parameters (json/encode [{:name "Venue ID" :slug :venue_id :target [:dimension (mt/id :venues :id)] :value [10]}])))) "This should pass because venue_id *is* one of the Dashboard's :parameters")) (testing "should fail if" (testing "a parameter is passed that is not one of the Dashboard's parameters" (is (= "An error occurred." (http/client :get 400 (dashcard-url dash card) :parameters (json/encode [{:name "Venue Name" :slug :venue_name :target [:dimension (mt/id :venues :name)] :value ["PizzaHacker"]}]))))))))))) (deftest execute-public-dashcard-additional-series-test (testing "GET /api/public/dashboard/:uuid/card/:card-id" (testing "should work with an additional Card series" (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-dashboard-and-card [dash card] (with-temp-public-card [card-2] (mt/with-temp DashboardCardSeries [_ {:dashboardcard_id (db/select-one-id DashboardCard :card_id (u/the-id card) :dashboard_id (u/the-id dash)) :card_id (u/the-id card-2)}] (is (= [[100]] (mt/rows (http/client :get 202 (dashcard-url dash card-2)))))))))))) (deftest execute-public-dashcard-parameters-test (testing "GET /api/public/dashboard/:uuid/card/:card-id" (testing "Make sure parameters work correctly (#7212)" (mt/with-temporary-setting-values [enable-public-sharing true] (testing "with native queries and template tag params" (mt/with-temp Card [card {:dataset_query {:database (mt/id) :type :native :native {:query "SELECT {{num}} AS num" :template-tags {:num {:name "num" :display-name "Num" :type "number" :required true :default "1"}}}}}] (with-temp-public-dashboard [dash {:parameters [{:name "Num" :slug "num" :id "537e37b4" :type "category"}]}] (add-card-to-dashboard! card dash :parameter_mappings [{:card_id (u/the-id card) :target [:variable [:template-tag :num]] :parameter_id "537e37b4"}]) (is (= [[50]] (-> ((mt/user->client :crowberto) :get (str (dashcard-url dash card) "?parameters=" (json/generate-string [{:type :category :target [:variable [:template-tag :num]] :value "50"}]))) mt/rows)))))) (testing "with MBQL queries" (testing "`:id` parameters" (mt/with-temp Card [card {:dataset_query {:database (mt/id) :type :query :query {:source-table (mt/id :venues) :aggregation [:count]}}}] (with-temp-public-dashboard [dash {:parameters [{:name "Venue ID" :slug "venue_id" :id "22486e00" :type "id"}]}] (add-card-to-dashboard! card dash :parameter_mappings [{:parameter_id "22486e00" :card_id (u/the-id card) :target [:dimension [:field (mt/id :venues :id) nil]]}]) (is (= [[1]] (-> ((mt/user->client :crowberto) :get (str (dashcard-url dash card) "?parameters=" (json/generate-string [{:type :id :target [:dimension [:field (mt/id :venues :id) nil]] :value "50"}]))) mt/rows)))))) (testing "temporal parameters" (mt/with-temporary-setting-values [enable-public-sharing true] (mt/with-temp Card [card {:dataset_query {:database (mt/id) :type :query :query {:source-table (mt/id :checkins) :aggregation [:count]}}}] (with-temp-public-dashboard [dash {:parameters [{:name "Date Filter" :slug "date_filter" :id "18a036ec" :type "date/all-options"}]}] (add-card-to-dashboard! card dash :parameter_mappings [{:parameter_id "18a036ec" :card_id (u/the-id card) :target [:dimension [:field (mt/id :checkins :date) nil]]}]) (is (= [[733]] (-> ((mt/user->client :crowberto) :get (str (dashcard-url dash card) "?parameters=" (json/generate-string [{:type "date/all-options" :target [:dimension [:field (mt/id :checkins :date) nil]] :value "~2015-01-01"}]))) mt/rows)))))))))))) (deftest execute-public-dashcard-dimension-value-params-test (testing "GET /api/public/dashboard/:uuid/card/:card-id" (testing (str "make sure DimensionValue params also work if they have a default value, even if some is passed in " "for some reason as part of the query (#7253) If passed in as part of the query however make sure it " "doesn't override what's actually in the DB") (mt/with-temporary-setting-values [enable-public-sharing true] (mt/with-temp Card [card {:dataset_query {:database (mt/id) :type :native :native {:query "SELECT {{msg}} AS message" :template-tags {:msg {:id "181da7c5" :name "msg" :display-name "Message" :type "text" :required true :default "Wow"}}}}}] (with-temp-public-dashboard [dash {:parameters [{:name "Message" :slug "msg" :id "181da7c5" :type "category"}]}] (add-card-to-dashboard! card dash :parameter_mappings [{:card_id (u/the-id card) :target [:variable [:template-tag :msg]] :parameter_id "181da7c5"}]) (is (= [["Wow"]] (-> ((mt/user->client :crowberto) :get (str (dashcard-url dash card) "?parameters=" (json/generate-string [{:type :category :target [:variable [:template-tag :msg]] :value nil :default "Hello"}]))) mt/rows))))))))) ;;; --------------------------- Check that parameter information comes back with Dashboard --------------------------- (deftest double-check-that-the-field-has-fieldvalues (is (= [1 2 3 4] (db/select-one-field :values FieldValues :field_id (mt/id :venues :price))))) (defn- price-param-values [] {(keyword (str (mt/id :venues :price))) {:values [1 2 3 4] :human_readable_values [] :field_id (mt/id :venues :price)}}) (defn- add-price-param-to-dashboard! [dashboard] (db/update! Dashboard (u/the-id dashboard) :parameters [{:name "Price", :type "category", :slug "price", :id "_PRICE_"}])) (defn- add-dimension-param-mapping-to-dashcard! [dashcard card dimension] (db/update! DashboardCard (u/the-id dashcard) :parameter_mappings [{:card_id (u/the-id card) :target ["dimension" dimension]}])) (defn- GET-param-values [dashboard] (mt/with-temporary-setting-values [enable-public-sharing true] (:param_values (http/client :get 200 (str "public/dashboard/" (:public_uuid dashboard)))))) (deftest check-that-param-info-comes-back-for-sql-cards (with-temp-public-dashboard-and-card [dash card dashcard] (db/update! Card (u/the-id card) :dataset_query {:database (mt/id) :type :native :native {:template-tags {:price {:name "price" :display-name "Price" :type "dimension" :dimension ["field" (mt/id :venues :price) nil]}}}}) (add-price-param-to-dashboard! dash) (add-dimension-param-mapping-to-dashcard! dashcard card ["template-tag" "price"]) (is (= (price-param-values) (GET-param-values dash))))) (deftest check-that-param-info-comes-back-for-mbql-cards--field-id- (with-temp-public-dashboard-and-card [dash card dashcard] (add-price-param-to-dashboard! dash) (add-dimension-param-mapping-to-dashcard! dashcard card ["field" (mt/id :venues :price) nil]) (is (= (price-param-values) (GET-param-values dash))))) (deftest check-that-param-info-comes-back-for-mbql-cards--fk--- (with-temp-public-dashboard-and-card [dash card dashcard] (add-price-param-to-dashboard! dash) (add-dimension-param-mapping-to-dashcard! dashcard card [:field (mt/id :venues :price) {:source-field (mt/id :checkins :venue_id)}]) (is (= (price-param-values) (GET-param-values dash))))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | New FieldValues search endpoints | ;;; +----------------------------------------------------------------------------------------------------------------+ (defn- mbql-card-referencing-nothing [] {:dataset_query {:database (mt/id) :type :query :query {:source-table (mt/id :venues)}}}) (defn mbql-card-referencing [table-kw field-kw] {:dataset_query {:database (mt/id) :type :query :query {:source-table (mt/id table-kw) :filter [:= [:field (mt/id table-kw field-kw) nil] "Krua Siri"]}}}) (defn- mbql-card-referencing-venue-name [] (mbql-card-referencing :venues :name)) (defn- sql-card-referencing-venue-name [] {:dataset_query {:database (mt/id) :type :native :native {:query "SELECT COUNT(*) FROM VENUES WHERE {{x}}" :template-tags {:x {:name :x :display-name "X" :type :dimension :dimension [:field (mt/id :venues :name) nil]}}}}}) ;;; ------------------------------------------- card->referenced-field-ids ------------------------------------------- (deftest card-referencing-nothing (mt/with-temp Card [card (mbql-card-referencing-nothing)] (is (= #{} (#'public-api/card->referenced-field-ids card))))) (deftest it-should-pick-up-on-fields-referenced-in-the-mbql-query-itself (mt/with-temp Card [card (mbql-card-referencing-venue-name)] (is (= #{(mt/id :venues :name)} (#'public-api/card->referenced-field-ids card))))) (deftest ---as-well-as-template-tag--implict--params-for-sql-queries (mt/with-temp Card [card (sql-card-referencing-venue-name)] (is (= #{(mt/id :venues :name)} (#'public-api/card->referenced-field-ids card))))) ;;; --------------------------------------- check-field-is-referenced-by-card ---------------------------------------- (deftest check-that-the-check-succeeds-when-field-is-referenced (mt/with-temp Card [card (mbql-card-referencing-venue-name)] (#'public-api/check-field-is-referenced-by-card (mt/id :venues :name) (u/the-id card)))) (deftest check-that-exception-is-thrown-if-the-field-isn-t-referenced (is (thrown? Exception (mt/with-temp Card [card (mbql-card-referencing-venue-name)] (#'public-api/check-field-is-referenced-by-card (mt/id :venues :category_id) (u/the-id card)))))) ;;; ----------------------------------------- check-search-field-is-allowed ------------------------------------------ ;; search field is allowed IF: ;; A) search-field is the same field as the other one (deftest search-field-allowed-if-same-field-as-other-one (#'public-api/check-search-field-is-allowed (mt/id :venues :id) (mt/id :venues :id)) (is (thrown? Exception (#'public-api/check-search-field-is-allowed (mt/id :venues :id) (mt/id :venues :category_id))))) ;; B) there's a Dimension that lists search field as the human_readable_field for the other field (deftest search-field-allowed-with-dimension (is (mt/with-temp Dimension [_ {:field_id (mt/id :venues :id), :human_readable_field_id (mt/id :venues :category_id)}] (#'public-api/check-search-field-is-allowed (mt/id :venues :id) (mt/id :venues :category_id))))) ;; C) search-field is a Name Field belonging to the same table as the other field, which is a PK (deftest search-field-allowed-with-name-field (is (#'public-api/check-search-field-is-allowed (mt/id :venues :id) (mt/id :venues :name)))) ;; not allowed if search field isn't a NAME (deftest search-field-not-allowed-if-search-field-isnt-a-name (is (thrown? Exception (mt/with-temp-vals-in-db Field (mt/id :venues :name) {:semantic_type "type/Latitude"} (#'public-api/check-search-field-is-allowed (mt/id :venues :id) (mt/id :venues :name)))))) (deftest not-allowed-if-search-field-belongs-to-a-different-table (is (thrown? Exception (mt/with-temp-vals-in-db Field (mt/id :categories :name) {:semantic_type "type/Name"} (#'public-api/check-search-field-is-allowed (mt/id :venues :id) (mt/id :categories :name)))))) ;;; ------------------------------------- check-field-is-referenced-by-dashboard ------------------------------------- (defn- dashcard-with-param-mapping-to-venue-id [dashboard card] {:dashboard_id (u/the-id dashboard) :card_id (u/the-id card) :parameter_mappings [{:card_id (u/the-id card) :target [:dimension [:field (mt/id :venues :id) nil]]}]}) (deftest field-is--referenced--by-dashboard-if-it-s-one-of-the-dashboard-s-params--- (is (mt/with-temp* [Dashboard [dashboard] Card [card] DashboardCard [_ (dashcard-with-param-mapping-to-venue-id dashboard card)]] (#'public-api/check-field-is-referenced-by-dashboard (mt/id :venues :id) (u/the-id dashboard))))) (deftest TODO-name-this-exception (is (thrown? Exception (mt/with-temp* [Dashboard [dashboard] Card [card] DashboardCard [_ (dashcard-with-param-mapping-to-venue-id dashboard card)]] (#'public-api/check-field-is-referenced-by-dashboard (mt/id :venues :name) (u/the-id dashboard)))))) ;; ...*or* if it's a so-called "implicit" param (a Field Filter Template Tag (FFTT) in a SQL Card) (deftest implicit-param (is (mt/with-temp* [Dashboard [dashboard] Card [card (sql-card-referencing-venue-name)] DashboardCard [_ {:dashboard_id (u/the-id dashboard), :card_id (u/the-id card)}]] (#'public-api/check-field-is-referenced-by-dashboard (mt/id :venues :name) (u/the-id dashboard)))) (is (thrown? Exception (mt/with-temp* [Dashboard [dashboard] Card [card (sql-card-referencing-venue-name)] DashboardCard [_ {:dashboard_id (u/the-id dashboard), :card_id (u/the-id card)}]] (#'public-api/check-field-is-referenced-by-dashboard (mt/id :venues :id) (u/the-id dashboard)))))) ;;; ------------------------------------------- card-and-field-id->values -------------------------------------------- (deftest we-should-be-able-to-get-values-for-a-field-referenced-by-a-card (mt/with-temp Card [card (mbql-card-referencing :venues :name)] (is (= {:values [["20th Century Cafe"] ["25°"] ["33 Taps"] ["800 Degrees Neapolitan Pizzeria"] ["BCD Tofu House"]] :field_id (mt/id :venues :name)} (mt/derecordize (-> (public-api/card-and-field-id->values (u/the-id card) (mt/id :venues :name)) (update :values (partial take 5)))))))) (deftest sql-param-field-references-should-work-just-as-well-as-mbql-field-referenced (mt/with-temp Card [card (sql-card-referencing-venue-name)] (is (= {:values [["20th Century Cafe"] ["25°"] ["33 Taps"] ["800 Degrees Neapolitan Pizzeria"] ["BCD Tofu House"]] :field_id (mt/id :venues :name)} (mt/derecordize (-> (public-api/card-and-field-id->values (u/the-id card) (mt/id :venues :name)) (update :values (partial take 5)))))))) (deftest but-if-the-field-is-not-referenced-we-should-get-an-exception (mt/with-temp Card [card (mbql-card-referencing :venues :price)] (is (thrown? Exception (public-api/card-and-field-id->values (u/the-id card) (mt/id :venues :name)))))) ;;; ------------------------------- GET /api/public/card/:uuid/field/:field/values nil -------------------------------- (defn- field-values-url [card-or-dashboard field-or-id] (str "public/" (condp instance? card-or-dashboard (class Card) "card" (class Dashboard) "dashboard") "/" (or (:public_uuid card-or-dashboard) (throw (Exception. (str "Missing public UUID: " card-or-dashboard)))) "/field/" (u/the-id field-or-id) "/values")) (defn- do-with-sharing-enabled-and-temp-card-referencing {:style/indent 2} [table-kw field-kw f] (mt/with-temporary-setting-values [enable-public-sharing true] (mt/with-temp Card [card (merge (shared-obj) (mbql-card-referencing table-kw field-kw))] (f card)))) (defmacro ^:private with-sharing-enabled-and-temp-card-referencing {:style/indent 3} [table-kw field-kw [card-binding] & body] `(do-with-sharing-enabled-and-temp-card-referencing ~table-kw ~field-kw (fn [~card-binding] ~@body))) (deftest should-be-able-to-fetch-values-for-a-field-referenced-by-a-public-card (is (= {:values [["20th Century Cafe"] ["25°"] ["33 Taps"] ["800 Degrees Neapolitan Pizzeria"] ["BCD Tofu House"]] :field_id (mt/id :venues :name)} (with-sharing-enabled-and-temp-card-referencing :venues :name [card] (-> (http/client :get 200 (field-values-url card (mt/id :venues :name))) (update :values (partial take 5))))))) (deftest but-for-fields-that-are-not-referenced-we-should-get-an-exception (is (= "An error occurred." (with-sharing-enabled-and-temp-card-referencing :venues :name [card] (http/client :get 400 (field-values-url card (mt/id :venues :price))))))) (deftest field-value-endpoint-should-fail-if-public-sharing-is-disabled (is (= "An error occurred." (with-sharing-enabled-and-temp-card-referencing :venues :name [card] (mt/with-temporary-setting-values [enable-public-sharing false] (http/client :get 400 (field-values-url card (mt/id :venues :name)))))))) ;;; ----------------------------- GET /api/public/dashboard/:uuid/field/:field/values nil ----------------------------- (defn do-with-sharing-enabled-and-temp-dashcard-referencing {:style/indent 2} [table-kw field-kw f] (mt/with-temporary-setting-values [enable-public-sharing true] (mt/with-temp* [Dashboard [dashboard (shared-obj)] Card [card (mbql-card-referencing table-kw field-kw)] DashboardCard [dashcard {:dashboard_id (u/the-id dashboard) :card_id (u/the-id card) :parameter_mappings [{:card_id (u/the-id card) :target [:dimension [:field (mt/id table-kw field-kw) nil]]}]}]] (f dashboard card dashcard)))) (defmacro with-sharing-enabled-and-temp-dashcard-referencing {:style/indent 3} [table-kw field-kw [dashboard-binding card-binding dashcard-binding] & body] `(do-with-sharing-enabled-and-temp-dashcard-referencing ~table-kw ~field-kw (fn [~(or dashboard-binding '_) ~(or card-binding '_) ~(or dashcard-binding '_)] ~@body))) (deftest should-be-able-to-use-it-when-everything-is-g2g (with-sharing-enabled-and-temp-dashcard-referencing :venues :name [dashboard] (is (= {:values [["20th Century Cafe"] ["25°"] ["33 Taps"] ["800 Degrees Neapolitan Pizzeria"] ["BCD Tofu House"]] :field_id (mt/id :venues :name)} (-> (http/client :get 200 (field-values-url dashboard (mt/id :venues :name))) (update :values (partial take 5))))))) (deftest shound-not-be-able-to-use-the-endpoint-with-a-field-not-referenced-by-the-dashboard (with-sharing-enabled-and-temp-dashcard-referencing :venues :name [dashboard] (is (= "An error occurred." (http/client :get 400 (field-values-url dashboard (mt/id :venues :price))))))) (deftest endpoint-should-fail-if-public-sharing-is-disabled (with-sharing-enabled-and-temp-dashcard-referencing :venues :name [dashboard] (mt/with-temporary-setting-values [enable-public-sharing false] (is (= "An error occurred." (http/client :get 400 (field-values-url dashboard (mt/id :venues :name)))))))) ;;; ----------------------------------------------- search-card-fields ----------------------------------------------- (deftest search-card-fields (with-sharing-enabled-and-temp-card-referencing :venues :id [card] (is (= [[93 "33 Taps"]] (public-api/search-card-fields (u/the-id card) (mt/id :venues :id) (mt/id :venues :name) "33 T" 10))))) (deftest shouldn-t-work-if-the-search-field-isn-t-allowed-to-be-used-in-combination-with-the-other-field (with-sharing-enabled-and-temp-card-referencing :venues :id [card] (is (thrown? Exception (public-api/search-card-fields (u/the-id card) (mt/id :venues :id) (mt/id :venues :price) "33 T" 10))))) (deftest shouldn-t-work-if-the-field-isn-t-referenced-by-card (with-sharing-enabled-and-temp-card-referencing :venues :name [card] (is (thrown? Exception (public-api/search-card-fields (u/the-id card) (mt/id :venues :id) (mt/id :venues :id) "33 T" 10))))) ;;; ----------------------- GET /api/public/card/:uuid/field/:field/search/:search-field-id nil ----------------------- (defn- field-search-url [card-or-dashboard field-or-id search-field-or-id] (str "public/" (condp instance? card-or-dashboard (class Card) "card" (class Dashboard) "dashboard") "/" (:public_uuid card-or-dashboard) "/field/" (u/the-id field-or-id) "/search/" (u/the-id search-field-or-id))) (deftest field-search-with-venue (is (= [[93 "33 Taps"]] (with-sharing-enabled-and-temp-card-referencing :venues :id [card] (http/client :get 200 (field-search-url card (mt/id :venues :id) (mt/id :venues :name)) :value "33 T"))))) (deftest if-search-field-isn-t-allowed-to-be-used-with-the-other-field-endpoint-should-return-exception (is (= "An error occurred." (with-sharing-enabled-and-temp-card-referencing :venues :id [card] (http/client :get 400 (field-search-url card (mt/id :venues :id) (mt/id :venues :price)) :value "33 T"))))) (deftest search-endpoint-should-fail-if-public-sharing-is-disabled (is (= "An error occurred." (with-sharing-enabled-and-temp-card-referencing :venues :id [card] (mt/with-temporary-setting-values [enable-public-sharing false] (http/client :get 400 (field-search-url card (mt/id :venues :id) (mt/id :venues :name)) :value "33 T")))))) ;;; -------------------- GET /api/public/dashboard/:uuid/field/:field/search/:search-field-id nil --------------------- (deftest dashboard (with-sharing-enabled-and-temp-dashcard-referencing :venues :id [dashboard] (is (= [[93 "33 Taps"]] (http/client :get (field-search-url dashboard (mt/id :venues :id) (mt/id :venues :name)) :value "33 T"))))) (deftest dashboard-if-search-field-isn-t-allowed-to-be-used-with-the-other-field-endpoint-should-return-exception (with-sharing-enabled-and-temp-dashcard-referencing :venues :id [dashboard] (is (= "An error occurred." (http/client :get 400 (field-search-url dashboard (mt/id :venues :id) (mt/id :venues :price)) :value "33 T"))))) (deftest dashboard-endpoint-should-fail-if-public-sharing-is-disabled (with-sharing-enabled-and-temp-dashcard-referencing :venues :id [dashboard] (mt/with-temporary-setting-values [enable-public-sharing false] (is (= "An error occurred." (http/client :get 400 (field-search-url dashboard (mt/id :venues :name) (mt/id :venues :name)) :value "33 T")))))) ;;; --------------------------------------------- field-remapped-values ---------------------------------------------- ;; `field-remapped-values` should return remappings in the expected format when the combination of Fields is allowed. ;; It should parse the value string (it comes back from the API as a string since it is a query param) (deftest should-parse-string (is (= [10 "Fred 62"] (#'public-api/field-remapped-values (mt/id :venues :id) (mt/id :venues :name) "10")))) (deftest if-the-field-isn-t-allowed (is (thrown? Exception (#'public-api/field-remapped-values (mt/id :venues :id) (mt/id :venues :price) "10")))) ;;; ----------------------- GET /api/public/card/:uuid/field/:field/remapping/:remapped-id nil ------------------------ (defn- field-remapping-url [card-or-dashboard field-or-id remapped-field-or-id] (str "public/" (condp instance? card-or-dashboard (class Card) "card" (class Dashboard) "dashboard") "/" (:public_uuid card-or-dashboard) "/field/" (u/the-id field-or-id) "/remapping/" (u/the-id remapped-field-or-id))) (deftest we-should-be-able-to-use-the-api-endpoint-and-get-the-same-results-we-get-by-calling-the-function-above-directly (with-sharing-enabled-and-temp-card-referencing :venues :id [card] (is (= [10 "Fred 62"] (http/client :get 200 (field-remapping-url card (mt/id :venues :id) (mt/id :venues :name)) :value "10"))))) (deftest shouldn-t-work-if-card-doesn-t-reference-the-field-in-question (with-sharing-enabled-and-temp-card-referencing :venues :price [card] (is (= "An error occurred." (http/client :get 400 (field-remapping-url card (mt/id :venues :id) (mt/id :venues :name)) :value "10"))))) (deftest ---or-if-the-remapping-field-isn-t-allowed-to-be-used-with-the-other-field (with-sharing-enabled-and-temp-card-referencing :venues :id [card] (is (= "An error occurred." (http/client :get 400 (field-remapping-url card (mt/id :venues :id) (mt/id :venues :price)) :value "10"))))) (deftest ---or-if-public-sharing-is-disabled (with-sharing-enabled-and-temp-card-referencing :venues :id [card] (mt/with-temporary-setting-values [enable-public-sharing false] (is (= "An error occurred." (http/client :get 400 (field-remapping-url card (mt/id :venues :id) (mt/id :venues :name)) :value "10")))))) ;;; --------------------- GET /api/public/dashboard/:uuid/field/:field/remapping/:remapped-id nil --------------------- (deftest api-endpoint-should-return-same-results-as-function (with-sharing-enabled-and-temp-dashcard-referencing :venues :id [dashboard] (is (= [10 "Fred 62"] (http/client :get 200 (field-remapping-url dashboard (mt/id :venues :id) (mt/id :venues :name)) :value "10"))))) (deftest field-remapping-shouldn-t-work-if-card-doesn-t-reference-the-field-in-question (with-sharing-enabled-and-temp-dashcard-referencing :venues :price [dashboard] (is (= "An error occurred." (http/client :get 400 (field-remapping-url dashboard (mt/id :venues :id) (mt/id :venues :name)) :value "10"))))) (deftest remapping-or-if-the-remapping-field-isn-t-allowed-to-be-used-with-the-other-field (with-sharing-enabled-and-temp-dashcard-referencing :venues :id [dashboard] (is (= "An error occurred." (http/client :get 400 (field-remapping-url dashboard (mt/id :venues :id) (mt/id :venues :price)) :value "10"))))) (deftest remapping-or-if-public-sharing-is-disabled (with-sharing-enabled-and-temp-dashcard-referencing :venues :id [dashboard] (mt/with-temporary-setting-values [enable-public-sharing false] (is (= "An error occurred." (http/client :get 400 (field-remapping-url dashboard (mt/id :venues :id) (mt/id :venues :name)) :value "10")))))) ;;; --------------------------------------------- Chain filter endpoints --------------------------------------------- (deftest chain-filter-test (mt/with-temporary-setting-values [enable-public-sharing true] (dashboard-api-test/with-chain-filter-fixtures [{:keys [dashboard param-keys]}] (let [uuid (str (UUID/randomUUID))] (is (= true (db/update! Dashboard (u/the-id dashboard) :public_uuid uuid))) (testing "GET /api/public/dashboard/:uuid/params/:param-key/values" (let [url (format "public/dashboard/%s/params/%s/values" uuid (:category-id param-keys))] (is (= [2 3 4 5 6] (take 5 (http/client :get 200 url)))))) (testing "GET /api/public/dashboard/:uuid/params/:param-key/search/:query" (let [url (format "public/dashboard/%s/params/%s/search/food" uuid (:category-name param-keys))] (is (= ["Fast Food" "Food Truck" "Seafood"] (take 3 (http/client :get 200 url)))))))))) (deftest chain-filter-ignore-current-user-permissions-test (testing "Should not fail if request is authenticated but current user does not have data permissions" (mt/with-temp-copy-of-db (perms/revoke-permissions! (group/all-users) (mt/db)) (mt/with-temporary-setting-values [enable-public-sharing true] (dashboard-api-test/with-chain-filter-fixtures [{:keys [dashboard param-keys]}] (let [uuid (str (UUID/randomUUID))] (is (= true (db/update! Dashboard (u/the-id dashboard) :public_uuid uuid))) (testing "GET /api/public/dashboard/:uuid/params/:param-key/values" (let [url (format "public/dashboard/%s/params/%s/values" uuid (:category-id param-keys))] (is (= [2 3 4 5 6] (take 5 (mt/user-http-request :rasta :get 200 url)))))) (testing "GET /api/public/dashboard/:uuid/params/:param-key/search/:prefix" (let [url (format "public/dashboard/%s/params/%s/search/food" uuid (:category-name param-keys))] (is (= ["Fast Food" "Food Truck" "Seafood"] (take 3 (mt/user-http-request :rasta :get 200 url)))))))))))) ;; Pivot tables (deftest pivot-public-card-test (mt/test-drivers (pivots/applicable-drivers) (mt/dataset sample-dataset (testing "GET /api/public/pivot/card/:uuid/query" (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-card [{uuid :public_uuid} (pivots/pivot-card)] (let [result (http/client :get 202 (format "public/pivot/card/%s/query" uuid)) rows (mt/rows result)] (is (nil? (:row_count result))) ;; row_count isn't included in public endpoints (is (= "completed" (:status result))) (is (= 6 (count (get-in result [:data :cols])))) (is (= 1144 (count rows))) (is (= ["AK" "Affiliate" "Doohickey" 0 18 81] (first rows))) (is (= ["CO" "Affiliate" "Gadget" 0 62 211] (nth rows 100))) (is (= [nil nil nil 7 18760 69540] (last rows)))))))))) (defn- pivot-dashcard-url "URL for fetching results of a public DashCard." [dash card] (str "public/pivot/dashboard/" (:public_uuid dash) "/card/" (u/the-id card))) (deftest pivot-public-dashcard-test (mt/test-drivers (pivots/applicable-drivers) (mt/dataset sample-dataset (let [dashboard-defaults {:parameters [{:id "_STATE_" :name "State" :slug "state" :type "string" :target [:dimension [:fk-> (mt/$ids $orders.user_id) (mt/$ids $people.state)]] :default nil}]}] (testing "GET /api/public/pivot/dashboard/:uuid/card/:card-id" (testing "without parameters" (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-dashboard [dash dashboard-defaults] (with-temp-public-card [card (pivots/pivot-card)] (add-card-to-dashboard! card dash) (let [result (http/client :get 202 (pivot-dashcard-url dash card)) rows (mt/rows result)] (is (nil? (:row_count result))) ;; row_count isn't included in public endpoints (is (= "completed" (:status result))) (is (= 6 (count (get-in result [:data :cols])))) (is (= 1144 (count rows))) (is (= ["AK" "Affiliate" "Doohickey" 0 18 81] (first rows))) (is (= ["CO" "Affiliate" "Gadget" 0 62 211] (nth rows 100))) (is (= [nil nil nil 7 18760 69540] (last rows)))))))) (testing "with parameters" (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-dashboard [dash dashboard-defaults] (with-temp-public-card [card (pivots/pivot-card)] (add-card-to-dashboard! card dash) (let [result (http/client :get 202 (pivot-dashcard-url dash card) :parameters (json/encode [{:name "State" :slug :state :target [:dimension [:fk-> (mt/$ids $orders.user_id) (mt/$ids $people.state)]] :value ["CA" "WA"]}])) rows (mt/rows result)] (is (nil? (:row_count result))) ;; row_count isn't included in public endpoints (is (= "completed" (:status result))) (is (= 6 (count (get-in result [:data :cols])))) (is (= 80 (count rows))) (is (= ["CA" "Affiliate" "Doohickey" 0 16 48] (first rows))) (is (= [nil "Google" "Gizmo" 1 52 186] (nth rows 50))) (is (= [nil nil nil 7 1015 3758] (last rows)))))))))))))
21009
(ns metabase.api.public-test "Tests for `api/public/` (public links) endpoints." (:require [cheshire.core :as json] [clojure.string :as str] [clojure.test :refer :all] [dk.ative.docjure.spreadsheet :as spreadsheet] [metabase.api.dashboard-test :as dashboard-api-test] [metabase.api.pivots :as pivots] [metabase.api.public :as public-api] [metabase.http-client :as http] [metabase.models :refer [Card Collection Dashboard DashboardCard DashboardCardSeries Dimension Field FieldValues]] [metabase.models.permissions :as perms] [metabase.models.permissions-group :as group] [metabase.test :as mt] [metabase.util :as u] [toucan.db :as db]) (:import java.io.ByteArrayInputStream java.util.UUID)) ;;; --------------------------------------------------- Helper Fns --------------------------------------------------- (defn count-of-venues-card [] {:dataset_query (mt/mbql-query venues {:aggregation [[:count]]})}) (defn shared-obj [] {:public_uuid (str (UUID/randomUUID)) :made_public_by_id (mt/user->id :crowberto)}) (defmacro with-temp-public-card {:style/indent 1} [[binding & [card]] & body] `(let [card-defaults# ~card card-settings# (merge (when-not (:dataset_query card-defaults#) (count-of-venues-card)) (shared-obj) card-defaults#)] (mt/with-temp Card [card# card-settings#] ;; add :public_uuid back in to the value that gets bound because it might not come back from post-select if ;; public sharing is disabled; but we still want to test it (let [~binding (assoc card# :public_uuid (:public_uuid card-settings#))] ~@body)))) (defmacro with-temp-public-dashboard {:style/indent 1} [[binding & [dashboard]] & body] `(let [dashboard-defaults# ~dashboard dashboard-settings# (merge (when-not (:parameters dashboard-defaults#) {:parameters [{:id "_VENUE_ID_" :name "Venue ID" :slug "venue_id" :type "id" :target [:dimension (mt/id :venues :id)] :default nil}]}) (shared-obj) dashboard-defaults#)] (mt/with-temp Dashboard [dashboard# dashboard-settings#] (let [~binding (assoc dashboard# :public_uuid (:public_uuid dashboard-settings#))] ~@body)))) (defn add-card-to-dashboard! {:style/indent 2} [card dashboard & {:as kvs}] (db/insert! DashboardCard (merge {:dashboard_id (u/the-id dashboard), :card_id (u/the-id card)} kvs))) (defmacro ^:private with-temp-public-dashboard-and-card {:style/indent 1} [[dashboard-binding card-binding & [dashcard-binding]] & body] `(with-temp-public-dashboard [dash#] (with-temp-public-card [card#] (let [~dashboard-binding dash# ~card-binding card# ~(or dashcard-binding (gensym "dashcard")) (add-card-to-dashboard! card# dash#)] ~@body)))) ;;; ------------------------------------------- GET /api/public/card/:uuid ------------------------------------------- (deftest check-that-we--cannot--fetch-a-publiccard-if-the-setting-is-disabled (mt/with-temporary-setting-values [enable-public-sharing false] (with-temp-public-card [{uuid :public_uuid}] (is (= "An error occurred." (http/client :get 400 (str "public/card/" uuid))))))) (deftest check-that-we-get-a-400-if-the-publiccard-doesn-t-exist (mt/with-temporary-setting-values [enable-public-sharing true] (is (= "An error occurred." (http/client :get 400 (str "public/card/" (UUID/randomUUID))))))) (deftest check-that-we--cannot--fetch-a-publiccard-if-the-card-has-been-archived (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-card [{uuid :public_uuid} {:archived true}] (is (= "An error occurred." (http/client :get 400 (str "public/card/" uuid))))))) (deftest check-that-we-can-fetch-a-publiccard (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-card [{uuid :public_uuid}] (is (= #{:dataset_query :description :display :id :name :visualization_settings :param_values :param_fields} (set (keys (http/client :get 200 (str "public/card/" uuid))))))))) (deftest make-sure--param-values-get-returned-as-expected (mt/with-temp Card [card {:dataset_query {:database (mt/id) :type :native :native {:query (str "SELECT COUNT(*) " "FROM venues " "LEFT JOIN categories ON venues.category_id = categories.id " "WHERE {{category}}") :collection "CATEGORIES" :template-tags {:category {:name "category" :display-name "Category" :type "dimension" :dimension ["field" (mt/id :categories :name) nil] :widget-type "category" :required true}}}}}] (is (= {(mt/id :categories :name) {:values 75 :human_readable_values [] :field_id (mt/id :categories :name)}} (-> (:param_values (#'public-api/public-card :id (u/the-id card))) (update-in [(mt/id :categories :name) :values] count) (update (mt/id :categories :name) #(into {} %))))))) ;;; ------------------------- GET /api/public/card/:uuid/query (and JSON/CSV/XSLX versions) -------------------------- (deftest check-that-we--cannot--execute-a-publiccard-if-the-setting-is-disabled (mt/with-temporary-setting-values [enable-public-sharing false] (with-temp-public-card [{uuid :public_uuid}] (is (= "An error occurred." (http/client :get 400 (str "public/card/" uuid "/query"))))))) (deftest check-that-we-get-a-400-if-the-publiccard-doesn-t-exist-query (mt/with-temporary-setting-values [enable-public-sharing true] (is (= "An error occurred." (http/client :get 400 (str "public/card/" (UUID/randomUUID) "/query")))))) (deftest check-that-we--cannot--execute-a-publiccard-if-the-card-has-been-archived (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-card [{uuid :public_uuid} {:archived true}] (is (= "An error occurred." (http/client :get 400 (str "public/card/" uuid "/query"))))))) (defn- parse-xlsx-response [response] (->> (ByteArrayInputStream. response) spreadsheet/load-workbook (spreadsheet/select-sheet "Query result") (spreadsheet/select-columns {:A :col}))) (deftest execute-public-card-test (testing "GET /api/public/card/:uuid/query" (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-card [{uuid :public_uuid}] (testing "Default :api response format" (is (= [[100]] (mt/rows (http/client :get 202 (str "public/card/" uuid "/query")))))) (testing ":json download response format" (is (= [{:Count 100}] (http/client :get 200 (str "public/card/" uuid "/query/json"))))) (testing ":csv download response format" (is (= "Count\n100\n" (http/client :get 200 (str "public/card/" uuid "/query/csv"), :format :csv)))) (testing ":xlsx download response format" (is (= [{:col "Count"} {:col 100.0}] (parse-xlsx-response (http/client :get 200 (str "public/card/" uuid "/query/xlsx") {:request-options {:as :byte-array}}))))))))) (deftest execute-public-card-as-user-without-perms-test (testing "A user that doesn't have permissions to run the query normally should still be able to run a public Card as if they weren't logged in" (mt/with-temporary-setting-values [enable-public-sharing true] (mt/with-temp Collection [{collection-id :id}] (perms/revoke-collection-permissions! (group/all-users) collection-id) (with-temp-public-card [{card-id :id, uuid :public_uuid} {:collection_id collection-id}] (is (= "You don't have permissions to do that." ((mt/user->client :rasta) :post 403 (format "card/%d/query" card-id))) "Sanity check: shouldn't be allowed to run the query normally") (is (= [[100]] (mt/rows ((mt/user->client :rasta) :get 202 (str "public/card/" uuid "/query")))))))))) (deftest check-that-we-can-exec-a-publiccard-with---parameters- (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-card [{uuid :public_uuid}] (is (= [{:id "_VENUE_ID_", :name "Venue ID", :slug "venue_id", :type "id", :value 2}] (get-in (http/client :get 202 (str "public/card/" uuid "/query") :parameters (json/encode [{:id "_VENUE_ID_" :name "Venue ID" :slug "venue_id" :type "id" :value 2}])) [:json_query :parameters])))))) ;; Cards with required params (defn- do-with-required-param-card [f] (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-card [{uuid :public_uuid} {:dataset_query {:database (mt/id) :type :native :native {:query "SELECT count(*) FROM venues v WHERE price = {{price}}" :template-tags {"price" {:name "price" :display-name "Price" :type :number :required true}}}}}] (f uuid)))) (defmacro ^:private with-required-param-card [[uuid-binding] & body] `(do-with-required-param-card (fn [~uuid-binding] ~@body))) (deftest should-be-able-to-run-a-card-with-a-required-param (with-required-param-card [uuid] (is (= [[22]] (mt/rows (http/client :get 202 (str "public/card/" uuid "/query") :parameters (json/encode [{:type "category" :target [:variable [:template-tag "price"]] :value 1}]))))))) (deftest missing-required-param-error-message-test (testing (str "If you're missing a required param, the error message should get passed thru, rather than the normal " "generic 'Query Failed' message that we show for most embedding errors") (with-required-param-card [uuid] (is (= {:status "failed" :error "You'll need to pick a value for 'Price' before this query can run." :error_type "missing-required-parameter"} (mt/suppress-output (http/client :get 202 (str "public/card/" uuid "/query")))))))) (defn- card-with-date-field-filter [] (assoc (shared-obj) :dataset_query {:database (mt/id) :type :native :native {:query "SELECT COUNT(*) AS \"count\" FROM CHECKINS WHERE {{date}}" :template-tags {:date {:name "date" :display-name "Date" :type "dimension" :dimension [:field (mt/id :checkins :date) nil] :widget-type "date/quarter-year"}}}})) (deftest make-sure-csv--etc---downloads-take-editable-params-into-account---6407---- (mt/with-temporary-setting-values [enable-public-sharing true] (mt/with-temp Card [{uuid :public_uuid} (card-with-date-field-filter)] (is (= "count\n107\n" (http/client :get 200 (str "public/card/" uuid "/query/csv") :parameters (json/encode [{:id "_DATE_" :type :date/quarter-year :target [:dimension [:template-tag :date]] :value "Q1-2014"}]))))))) (deftest make-sure-it-also-works-with-the-forwarded-url (mt/with-temporary-setting-values [enable-public-sharing true] (mt/with-temp Card [{uuid :public_uuid} (card-with-date-field-filter)] ;; make sure the URL doesn't include /api/ at the beginning like it normally would (binding [http/*url-prefix* (str/replace http/*url-prefix* #"/api/$" "/")] (mt/with-temporary-setting-values [site-url http/*url-prefix*] (is (= "count\n107\n" (http/client :get 200 (str "public/question/" uuid ".csv") :parameters (json/encode [{:id "_DATE_" :type :date/quarter-year :target [:dimension [:template-tag :date]] :value "Q1-2014"}]))))))))) (defn- card-with-trendline [] (assoc (shared-obj) :dataset_query {:database (mt/id) :type :query :query {:source-table (mt/id :checkins) :breakout [[:datetime-field [:field (mt/id :checkins :date) nil] :month]] :aggregation [[:count]]}})) (deftest make-sure-we-include-all-the-relevant-fields-like-insights (mt/with-temporary-setting-values [enable-public-sharing true] (mt/with-temp Card [{uuid :public_uuid} (card-with-trendline)] (is (= #{:cols :rows :insights :results_timezone} (-> (http/client :get 202 (str "public/card/" uuid "/query")) :data keys set)))))) ;;; ---------------------------------------- GET /api/public/dashboard/:uuid ----------------------------------------- (deftest get-public-dashboard-errors-test (testing "GET /api/public/dashboard/:uuid" (testing "Shouldn't be able to fetch a public Dashboard if public sharing is disabled" (mt/with-temporary-setting-values [enable-public-sharing false] (with-temp-public-dashboard [{uuid :public_uuid}] (is (= "An error occurred." (http/client :get 400 (str "public/dashboard/" uuid))))))) (testing "Should get a 400 if the Dashboard doesn't exist" (mt/with-temporary-setting-values [enable-public-sharing true] (is (= "An error occurred." (http/client :get 400 (str "public/dashboard/" (UUID/randomUUID))))))))) (defn- fetch-public-dashboard [{uuid :public_uuid}] (-> (http/client :get 200 (str "public/dashboard/" uuid)) (select-keys [:name :ordered_cards]) (update :name boolean) (update :ordered_cards count))) (deftest get-public-dashboard-test (testing "GET /api/public/dashboard/:uuid" (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-dashboard-and-card [dash card] (is (= {:name true, :ordered_cards 1} (fetch-public-dashboard dash))) (testing "We shouldn't see Cards that have been archived" (db/update! Card (u/the-id card), :archived true) (is (= {:name true, :ordered_cards 0} (fetch-public-dashboard dash)))))))) ;;; --------------------------------- GET /api/public/dashboard/:uuid/card/:card-id ---------------------------------- (defn- dashcard-url "URL for fetching results of a public DashCard." [dash card] (str "public/dashboard/" (:public_uuid dash) "/card/" (u/the-id card))) (deftest execute-public-dashcard-errors-test (testing "GET /api/public/dashboard/:uuid/card/:card-id" (testing "Shouldn't be able to execute a public DashCard if public sharing is disabled" (mt/with-temporary-setting-values [enable-public-sharing false] (with-temp-public-dashboard-and-card [dash card] (is (= "An error occurred." (http/client :get 400 (dashcard-url dash card))))))) (testing "Should get a 400" (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-dashboard-and-card [dash card] (testing "if the Dashboard doesn't exist" (is (= "An error occurred." (http/client :get 400 (dashcard-url {:public_uuid (UUID/randomUUID)} card))))) (testing "if the Card doesn't exist" (is (= "An error occurred." (http/client :get 400 (dashcard-url dash Integer/MAX_VALUE))))) (testing "if the Card exists, but it's not part of this Dashboard" (mt/with-temp Card [card] (is (= "An error occurred." (http/client :get 400 (dashcard-url dash card)))))) (testing "if the Card has been archived." (db/update! Card (u/the-id card), :archived true) (is (= "An error occurred." (http/client :get 400 (dashcard-url dash card)))))))))) (deftest execute-public-dashcard-test (testing "GET /api/public/dashboard/:uuid/card/:card-id" (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-dashboard-and-card [dash card] (is (= [[100]] (mt/rows (http/client :get 202 (dashcard-url dash card))))) (testing "with parameters" (is (= [{:id "_VENUE_ID_" :name "Venue ID" :slug "venue_id" :target ["dimension" (mt/id :venues :id)] :value [10] :default nil :type "id"}] (get-in (http/client :get 202 (dashcard-url dash card) :parameters (json/encode [{:name "Venue ID" :slug :venue_id :target [:dimension (mt/id :venues :id)] :value [10]}])) [:json_query :parameters])))))))) (deftest execute-public-dashcard-as-user-without-perms-test (testing "GET /api/public/dashboard/:uuid/card/:card-id" (testing "A user that doesn't have permissions to run the query normally should still be able to run a public DashCard" (mt/with-temporary-setting-values [enable-public-sharing true] (mt/with-temp Collection [{collection-id :id}] (perms/revoke-collection-permissions! (group/all-users) collection-id) (with-temp-public-dashboard-and-card [dash {card-id :id, :as card}] (db/update! Card card-id :collection_id collection-id) (is (= "You don't have permissions to do that." ((mt/user->client :rasta) :post 403 (format "card/%d/query" card-id))) "Sanity check: shouldn't be allowed to run the query normally") (is (= [[100]] (mt/rows ((mt/user->client :rasta) :get 202 (dashcard-url dash card))))))))))) (deftest execute-public-dashcard-params-validation-test (testing "GET /api/public/dashboard/:uuid/card/:card-id" (testing "Make sure params are validated" (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-dashboard-and-card [dash card] (testing "Should work correctly with a valid parameter" (is (= [[1]] (mt/rows (http/client :get 202 (dashcard-url dash card) :parameters (json/encode [{:name "Venue ID" :slug :venue_id :target [:dimension (mt/id :venues :id)] :value [10]}])))) "This should pass because venue_id *is* one of the Dashboard's :parameters")) (testing "should fail if" (testing "a parameter is passed that is not one of the Dashboard's parameters" (is (= "An error occurred." (http/client :get 400 (dashcard-url dash card) :parameters (json/encode [{:name "Venue Name" :slug :venue_name :target [:dimension (mt/id :venues :name)] :value ["PizzaHacker"]}]))))))))))) (deftest execute-public-dashcard-additional-series-test (testing "GET /api/public/dashboard/:uuid/card/:card-id" (testing "should work with an additional Card series" (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-dashboard-and-card [dash card] (with-temp-public-card [card-2] (mt/with-temp DashboardCardSeries [_ {:dashboardcard_id (db/select-one-id DashboardCard :card_id (u/the-id card) :dashboard_id (u/the-id dash)) :card_id (u/the-id card-2)}] (is (= [[100]] (mt/rows (http/client :get 202 (dashcard-url dash card-2)))))))))))) (deftest execute-public-dashcard-parameters-test (testing "GET /api/public/dashboard/:uuid/card/:card-id" (testing "Make sure parameters work correctly (#7212)" (mt/with-temporary-setting-values [enable-public-sharing true] (testing "with native queries and template tag params" (mt/with-temp Card [card {:dataset_query {:database (mt/id) :type :native :native {:query "SELECT {{num}} AS num" :template-tags {:num {:name "num" :display-name "Num" :type "number" :required true :default "1"}}}}}] (with-temp-public-dashboard [dash {:parameters [{:name "Num" :slug "num" :id "537e37b4" :type "category"}]}] (add-card-to-dashboard! card dash :parameter_mappings [{:card_id (u/the-id card) :target [:variable [:template-tag :num]] :parameter_id "537e37b4"}]) (is (= [[50]] (-> ((mt/user->client :crowberto) :get (str (dashcard-url dash card) "?parameters=" (json/generate-string [{:type :category :target [:variable [:template-tag :num]] :value "50"}]))) mt/rows)))))) (testing "with MBQL queries" (testing "`:id` parameters" (mt/with-temp Card [card {:dataset_query {:database (mt/id) :type :query :query {:source-table (mt/id :venues) :aggregation [:count]}}}] (with-temp-public-dashboard [dash {:parameters [{:name "Venue ID" :slug "venue_id" :id "22486e00" :type "id"}]}] (add-card-to-dashboard! card dash :parameter_mappings [{:parameter_id "22486e00" :card_id (u/the-id card) :target [:dimension [:field (mt/id :venues :id) nil]]}]) (is (= [[1]] (-> ((mt/user->client :crowberto) :get (str (dashcard-url dash card) "?parameters=" (json/generate-string [{:type :id :target [:dimension [:field (mt/id :venues :id) nil]] :value "50"}]))) mt/rows)))))) (testing "temporal parameters" (mt/with-temporary-setting-values [enable-public-sharing true] (mt/with-temp Card [card {:dataset_query {:database (mt/id) :type :query :query {:source-table (mt/id :checkins) :aggregation [:count]}}}] (with-temp-public-dashboard [dash {:parameters [{:name "Date Filter" :slug "date_filter" :id "18a036ec" :type "date/all-options"}]}] (add-card-to-dashboard! card dash :parameter_mappings [{:parameter_id "18a036ec" :card_id (u/the-id card) :target [:dimension [:field (mt/id :checkins :date) nil]]}]) (is (= [[733]] (-> ((mt/user->client :crowberto) :get (str (dashcard-url dash card) "?parameters=" (json/generate-string [{:type "date/all-options" :target [:dimension [:field (mt/id :checkins :date) nil]] :value "~2015-01-01"}]))) mt/rows)))))))))))) (deftest execute-public-dashcard-dimension-value-params-test (testing "GET /api/public/dashboard/:uuid/card/:card-id" (testing (str "make sure DimensionValue params also work if they have a default value, even if some is passed in " "for some reason as part of the query (#7253) If passed in as part of the query however make sure it " "doesn't override what's actually in the DB") (mt/with-temporary-setting-values [enable-public-sharing true] (mt/with-temp Card [card {:dataset_query {:database (mt/id) :type :native :native {:query "SELECT {{msg}} AS message" :template-tags {:msg {:id "181da7c5" :name "msg" :display-name "Message" :type "text" :required true :default "Wow"}}}}}] (with-temp-public-dashboard [dash {:parameters [{:name "Message" :slug "msg" :id "181da7c5" :type "category"}]}] (add-card-to-dashboard! card dash :parameter_mappings [{:card_id (u/the-id card) :target [:variable [:template-tag :msg]] :parameter_id "181da7c5"}]) (is (= [["Wow"]] (-> ((mt/user->client :crowberto) :get (str (dashcard-url dash card) "?parameters=" (json/generate-string [{:type :category :target [:variable [:template-tag :msg]] :value nil :default "Hello"}]))) mt/rows))))))))) ;;; --------------------------- Check that parameter information comes back with Dashboard --------------------------- (deftest double-check-that-the-field-has-fieldvalues (is (= [1 2 3 4] (db/select-one-field :values FieldValues :field_id (mt/id :venues :price))))) (defn- price-param-values [] {(keyword (str (mt/id :venues :price))) {:values [1 2 3 4] :human_readable_values [] :field_id (mt/id :venues :price)}}) (defn- add-price-param-to-dashboard! [dashboard] (db/update! Dashboard (u/the-id dashboard) :parameters [{:name "Price", :type "category", :slug "price", :id "_PRICE_"}])) (defn- add-dimension-param-mapping-to-dashcard! [dashcard card dimension] (db/update! DashboardCard (u/the-id dashcard) :parameter_mappings [{:card_id (u/the-id card) :target ["dimension" dimension]}])) (defn- GET-param-values [dashboard] (mt/with-temporary-setting-values [enable-public-sharing true] (:param_values (http/client :get 200 (str "public/dashboard/" (:public_uuid dashboard)))))) (deftest check-that-param-info-comes-back-for-sql-cards (with-temp-public-dashboard-and-card [dash card dashcard] (db/update! Card (u/the-id card) :dataset_query {:database (mt/id) :type :native :native {:template-tags {:price {:name "price" :display-name "Price" :type "dimension" :dimension ["field" (mt/id :venues :price) nil]}}}}) (add-price-param-to-dashboard! dash) (add-dimension-param-mapping-to-dashcard! dashcard card ["template-tag" "price"]) (is (= (price-param-values) (GET-param-values dash))))) (deftest check-that-param-info-comes-back-for-mbql-cards--field-id- (with-temp-public-dashboard-and-card [dash card dashcard] (add-price-param-to-dashboard! dash) (add-dimension-param-mapping-to-dashcard! dashcard card ["field" (mt/id :venues :price) nil]) (is (= (price-param-values) (GET-param-values dash))))) (deftest check-that-param-info-comes-back-for-mbql-cards--fk--- (with-temp-public-dashboard-and-card [dash card dashcard] (add-price-param-to-dashboard! dash) (add-dimension-param-mapping-to-dashcard! dashcard card [:field (mt/id :venues :price) {:source-field (mt/id :checkins :venue_id)}]) (is (= (price-param-values) (GET-param-values dash))))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | New FieldValues search endpoints | ;;; +----------------------------------------------------------------------------------------------------------------+ (defn- mbql-card-referencing-nothing [] {:dataset_query {:database (mt/id) :type :query :query {:source-table (mt/id :venues)}}}) (defn mbql-card-referencing [table-kw field-kw] {:dataset_query {:database (mt/id) :type :query :query {:source-table (mt/id table-kw) :filter [:= [:field (mt/id table-kw field-kw) nil] "<NAME>a Siri"]}}}) (defn- mbql-card-referencing-venue-name [] (mbql-card-referencing :venues :name)) (defn- sql-card-referencing-venue-name [] {:dataset_query {:database (mt/id) :type :native :native {:query "SELECT COUNT(*) FROM VENUES WHERE {{x}}" :template-tags {:x {:name :x :display-name "X" :type :dimension :dimension [:field (mt/id :venues :name) nil]}}}}}) ;;; ------------------------------------------- card->referenced-field-ids ------------------------------------------- (deftest card-referencing-nothing (mt/with-temp Card [card (mbql-card-referencing-nothing)] (is (= #{} (#'public-api/card->referenced-field-ids card))))) (deftest it-should-pick-up-on-fields-referenced-in-the-mbql-query-itself (mt/with-temp Card [card (mbql-card-referencing-venue-name)] (is (= #{(mt/id :venues :name)} (#'public-api/card->referenced-field-ids card))))) (deftest ---as-well-as-template-tag--implict--params-for-sql-queries (mt/with-temp Card [card (sql-card-referencing-venue-name)] (is (= #{(mt/id :venues :name)} (#'public-api/card->referenced-field-ids card))))) ;;; --------------------------------------- check-field-is-referenced-by-card ---------------------------------------- (deftest check-that-the-check-succeeds-when-field-is-referenced (mt/with-temp Card [card (mbql-card-referencing-venue-name)] (#'public-api/check-field-is-referenced-by-card (mt/id :venues :name) (u/the-id card)))) (deftest check-that-exception-is-thrown-if-the-field-isn-t-referenced (is (thrown? Exception (mt/with-temp Card [card (mbql-card-referencing-venue-name)] (#'public-api/check-field-is-referenced-by-card (mt/id :venues :category_id) (u/the-id card)))))) ;;; ----------------------------------------- check-search-field-is-allowed ------------------------------------------ ;; search field is allowed IF: ;; A) search-field is the same field as the other one (deftest search-field-allowed-if-same-field-as-other-one (#'public-api/check-search-field-is-allowed (mt/id :venues :id) (mt/id :venues :id)) (is (thrown? Exception (#'public-api/check-search-field-is-allowed (mt/id :venues :id) (mt/id :venues :category_id))))) ;; B) there's a Dimension that lists search field as the human_readable_field for the other field (deftest search-field-allowed-with-dimension (is (mt/with-temp Dimension [_ {:field_id (mt/id :venues :id), :human_readable_field_id (mt/id :venues :category_id)}] (#'public-api/check-search-field-is-allowed (mt/id :venues :id) (mt/id :venues :category_id))))) ;; C) search-field is a Name Field belonging to the same table as the other field, which is a PK (deftest search-field-allowed-with-name-field (is (#'public-api/check-search-field-is-allowed (mt/id :venues :id) (mt/id :venues :name)))) ;; not allowed if search field isn't a NAME (deftest search-field-not-allowed-if-search-field-isnt-a-name (is (thrown? Exception (mt/with-temp-vals-in-db Field (mt/id :venues :name) {:semantic_type "type/Latitude"} (#'public-api/check-search-field-is-allowed (mt/id :venues :id) (mt/id :venues :name)))))) (deftest not-allowed-if-search-field-belongs-to-a-different-table (is (thrown? Exception (mt/with-temp-vals-in-db Field (mt/id :categories :name) {:semantic_type "type/Name"} (#'public-api/check-search-field-is-allowed (mt/id :venues :id) (mt/id :categories :name)))))) ;;; ------------------------------------- check-field-is-referenced-by-dashboard ------------------------------------- (defn- dashcard-with-param-mapping-to-venue-id [dashboard card] {:dashboard_id (u/the-id dashboard) :card_id (u/the-id card) :parameter_mappings [{:card_id (u/the-id card) :target [:dimension [:field (mt/id :venues :id) nil]]}]}) (deftest field-is--referenced--by-dashboard-if-it-s-one-of-the-dashboard-s-params--- (is (mt/with-temp* [Dashboard [dashboard] Card [card] DashboardCard [_ (dashcard-with-param-mapping-to-venue-id dashboard card)]] (#'public-api/check-field-is-referenced-by-dashboard (mt/id :venues :id) (u/the-id dashboard))))) (deftest TODO-name-this-exception (is (thrown? Exception (mt/with-temp* [Dashboard [dashboard] Card [card] DashboardCard [_ (dashcard-with-param-mapping-to-venue-id dashboard card)]] (#'public-api/check-field-is-referenced-by-dashboard (mt/id :venues :name) (u/the-id dashboard)))))) ;; ...*or* if it's a so-called "implicit" param (a Field Filter Template Tag (FFTT) in a SQL Card) (deftest implicit-param (is (mt/with-temp* [Dashboard [dashboard] Card [card (sql-card-referencing-venue-name)] DashboardCard [_ {:dashboard_id (u/the-id dashboard), :card_id (u/the-id card)}]] (#'public-api/check-field-is-referenced-by-dashboard (mt/id :venues :name) (u/the-id dashboard)))) (is (thrown? Exception (mt/with-temp* [Dashboard [dashboard] Card [card (sql-card-referencing-venue-name)] DashboardCard [_ {:dashboard_id (u/the-id dashboard), :card_id (u/the-id card)}]] (#'public-api/check-field-is-referenced-by-dashboard (mt/id :venues :id) (u/the-id dashboard)))))) ;;; ------------------------------------------- card-and-field-id->values -------------------------------------------- (deftest we-should-be-able-to-get-values-for-a-field-referenced-by-a-card (mt/with-temp Card [card (mbql-card-referencing :venues :name)] (is (= {:values [["20th Century Cafe"] ["25°"] ["33 Taps"] ["800 Degrees Neapolitan Pizzeria"] ["BCD Tofu House"]] :field_id (mt/id :venues :name)} (mt/derecordize (-> (public-api/card-and-field-id->values (u/the-id card) (mt/id :venues :name)) (update :values (partial take 5)))))))) (deftest sql-param-field-references-should-work-just-as-well-as-mbql-field-referenced (mt/with-temp Card [card (sql-card-referencing-venue-name)] (is (= {:values [["20th Century Cafe"] ["25°"] ["33 Taps"] ["800 Degrees Neapolitan Pizzeria"] ["BCD Tofu House"]] :field_id (mt/id :venues :name)} (mt/derecordize (-> (public-api/card-and-field-id->values (u/the-id card) (mt/id :venues :name)) (update :values (partial take 5)))))))) (deftest but-if-the-field-is-not-referenced-we-should-get-an-exception (mt/with-temp Card [card (mbql-card-referencing :venues :price)] (is (thrown? Exception (public-api/card-and-field-id->values (u/the-id card) (mt/id :venues :name)))))) ;;; ------------------------------- GET /api/public/card/:uuid/field/:field/values nil -------------------------------- (defn- field-values-url [card-or-dashboard field-or-id] (str "public/" (condp instance? card-or-dashboard (class Card) "card" (class Dashboard) "dashboard") "/" (or (:public_uuid card-or-dashboard) (throw (Exception. (str "Missing public UUID: " card-or-dashboard)))) "/field/" (u/the-id field-or-id) "/values")) (defn- do-with-sharing-enabled-and-temp-card-referencing {:style/indent 2} [table-kw field-kw f] (mt/with-temporary-setting-values [enable-public-sharing true] (mt/with-temp Card [card (merge (shared-obj) (mbql-card-referencing table-kw field-kw))] (f card)))) (defmacro ^:private with-sharing-enabled-and-temp-card-referencing {:style/indent 3} [table-kw field-kw [card-binding] & body] `(do-with-sharing-enabled-and-temp-card-referencing ~table-kw ~field-kw (fn [~card-binding] ~@body))) (deftest should-be-able-to-fetch-values-for-a-field-referenced-by-a-public-card (is (= {:values [["20th Century Cafe"] ["25°"] ["33 Taps"] ["800 Degrees Neapolitan Pizzeria"] ["BCD Tofu House"]] :field_id (mt/id :venues :name)} (with-sharing-enabled-and-temp-card-referencing :venues :name [card] (-> (http/client :get 200 (field-values-url card (mt/id :venues :name))) (update :values (partial take 5))))))) (deftest but-for-fields-that-are-not-referenced-we-should-get-an-exception (is (= "An error occurred." (with-sharing-enabled-and-temp-card-referencing :venues :name [card] (http/client :get 400 (field-values-url card (mt/id :venues :price))))))) (deftest field-value-endpoint-should-fail-if-public-sharing-is-disabled (is (= "An error occurred." (with-sharing-enabled-and-temp-card-referencing :venues :name [card] (mt/with-temporary-setting-values [enable-public-sharing false] (http/client :get 400 (field-values-url card (mt/id :venues :name)))))))) ;;; ----------------------------- GET /api/public/dashboard/:uuid/field/:field/values nil ----------------------------- (defn do-with-sharing-enabled-and-temp-dashcard-referencing {:style/indent 2} [table-kw field-kw f] (mt/with-temporary-setting-values [enable-public-sharing true] (mt/with-temp* [Dashboard [dashboard (shared-obj)] Card [card (mbql-card-referencing table-kw field-kw)] DashboardCard [dashcard {:dashboard_id (u/the-id dashboard) :card_id (u/the-id card) :parameter_mappings [{:card_id (u/the-id card) :target [:dimension [:field (mt/id table-kw field-kw) nil]]}]}]] (f dashboard card dashcard)))) (defmacro with-sharing-enabled-and-temp-dashcard-referencing {:style/indent 3} [table-kw field-kw [dashboard-binding card-binding dashcard-binding] & body] `(do-with-sharing-enabled-and-temp-dashcard-referencing ~table-kw ~field-kw (fn [~(or dashboard-binding '_) ~(or card-binding '_) ~(or dashcard-binding '_)] ~@body))) (deftest should-be-able-to-use-it-when-everything-is-g2g (with-sharing-enabled-and-temp-dashcard-referencing :venues :name [dashboard] (is (= {:values [["20th Century Cafe"] ["25°"] ["33 Taps"] ["800 Degrees Neapolitan Pizzeria"] ["BCD Tofu House"]] :field_id (mt/id :venues :name)} (-> (http/client :get 200 (field-values-url dashboard (mt/id :venues :name))) (update :values (partial take 5))))))) (deftest shound-not-be-able-to-use-the-endpoint-with-a-field-not-referenced-by-the-dashboard (with-sharing-enabled-and-temp-dashcard-referencing :venues :name [dashboard] (is (= "An error occurred." (http/client :get 400 (field-values-url dashboard (mt/id :venues :price))))))) (deftest endpoint-should-fail-if-public-sharing-is-disabled (with-sharing-enabled-and-temp-dashcard-referencing :venues :name [dashboard] (mt/with-temporary-setting-values [enable-public-sharing false] (is (= "An error occurred." (http/client :get 400 (field-values-url dashboard (mt/id :venues :name)))))))) ;;; ----------------------------------------------- search-card-fields ----------------------------------------------- (deftest search-card-fields (with-sharing-enabled-and-temp-card-referencing :venues :id [card] (is (= [[93 "33 Taps"]] (public-api/search-card-fields (u/the-id card) (mt/id :venues :id) (mt/id :venues :name) "33 T" 10))))) (deftest shouldn-t-work-if-the-search-field-isn-t-allowed-to-be-used-in-combination-with-the-other-field (with-sharing-enabled-and-temp-card-referencing :venues :id [card] (is (thrown? Exception (public-api/search-card-fields (u/the-id card) (mt/id :venues :id) (mt/id :venues :price) "33 T" 10))))) (deftest shouldn-t-work-if-the-field-isn-t-referenced-by-card (with-sharing-enabled-and-temp-card-referencing :venues :name [card] (is (thrown? Exception (public-api/search-card-fields (u/the-id card) (mt/id :venues :id) (mt/id :venues :id) "33 T" 10))))) ;;; ----------------------- GET /api/public/card/:uuid/field/:field/search/:search-field-id nil ----------------------- (defn- field-search-url [card-or-dashboard field-or-id search-field-or-id] (str "public/" (condp instance? card-or-dashboard (class Card) "card" (class Dashboard) "dashboard") "/" (:public_uuid card-or-dashboard) "/field/" (u/the-id field-or-id) "/search/" (u/the-id search-field-or-id))) (deftest field-search-with-venue (is (= [[93 "33 Taps"]] (with-sharing-enabled-and-temp-card-referencing :venues :id [card] (http/client :get 200 (field-search-url card (mt/id :venues :id) (mt/id :venues :name)) :value "33 T"))))) (deftest if-search-field-isn-t-allowed-to-be-used-with-the-other-field-endpoint-should-return-exception (is (= "An error occurred." (with-sharing-enabled-and-temp-card-referencing :venues :id [card] (http/client :get 400 (field-search-url card (mt/id :venues :id) (mt/id :venues :price)) :value "33 T"))))) (deftest search-endpoint-should-fail-if-public-sharing-is-disabled (is (= "An error occurred." (with-sharing-enabled-and-temp-card-referencing :venues :id [card] (mt/with-temporary-setting-values [enable-public-sharing false] (http/client :get 400 (field-search-url card (mt/id :venues :id) (mt/id :venues :name)) :value "33 T")))))) ;;; -------------------- GET /api/public/dashboard/:uuid/field/:field/search/:search-field-id nil --------------------- (deftest dashboard (with-sharing-enabled-and-temp-dashcard-referencing :venues :id [dashboard] (is (= [[93 "33 Taps"]] (http/client :get (field-search-url dashboard (mt/id :venues :id) (mt/id :venues :name)) :value "33 T"))))) (deftest dashboard-if-search-field-isn-t-allowed-to-be-used-with-the-other-field-endpoint-should-return-exception (with-sharing-enabled-and-temp-dashcard-referencing :venues :id [dashboard] (is (= "An error occurred." (http/client :get 400 (field-search-url dashboard (mt/id :venues :id) (mt/id :venues :price)) :value "33 T"))))) (deftest dashboard-endpoint-should-fail-if-public-sharing-is-disabled (with-sharing-enabled-and-temp-dashcard-referencing :venues :id [dashboard] (mt/with-temporary-setting-values [enable-public-sharing false] (is (= "An error occurred." (http/client :get 400 (field-search-url dashboard (mt/id :venues :name) (mt/id :venues :name)) :value "33 T")))))) ;;; --------------------------------------------- field-remapped-values ---------------------------------------------- ;; `field-remapped-values` should return remappings in the expected format when the combination of Fields is allowed. ;; It should parse the value string (it comes back from the API as a string since it is a query param) (deftest should-parse-string (is (= [10 "<NAME> 62"] (#'public-api/field-remapped-values (mt/id :venues :id) (mt/id :venues :name) "10")))) (deftest if-the-field-isn-t-allowed (is (thrown? Exception (#'public-api/field-remapped-values (mt/id :venues :id) (mt/id :venues :price) "10")))) ;;; ----------------------- GET /api/public/card/:uuid/field/:field/remapping/:remapped-id nil ------------------------ (defn- field-remapping-url [card-or-dashboard field-or-id remapped-field-or-id] (str "public/" (condp instance? card-or-dashboard (class Card) "card" (class Dashboard) "dashboard") "/" (:public_uuid card-or-dashboard) "/field/" (u/the-id field-or-id) "/remapping/" (u/the-id remapped-field-or-id))) (deftest we-should-be-able-to-use-the-api-endpoint-and-get-the-same-results-we-get-by-calling-the-function-above-directly (with-sharing-enabled-and-temp-card-referencing :venues :id [card] (is (= [10 "<NAME>"] (http/client :get 200 (field-remapping-url card (mt/id :venues :id) (mt/id :venues :name)) :value "10"))))) (deftest shouldn-t-work-if-card-doesn-t-reference-the-field-in-question (with-sharing-enabled-and-temp-card-referencing :venues :price [card] (is (= "An error occurred." (http/client :get 400 (field-remapping-url card (mt/id :venues :id) (mt/id :venues :name)) :value "10"))))) (deftest ---or-if-the-remapping-field-isn-t-allowed-to-be-used-with-the-other-field (with-sharing-enabled-and-temp-card-referencing :venues :id [card] (is (= "An error occurred." (http/client :get 400 (field-remapping-url card (mt/id :venues :id) (mt/id :venues :price)) :value "10"))))) (deftest ---or-if-public-sharing-is-disabled (with-sharing-enabled-and-temp-card-referencing :venues :id [card] (mt/with-temporary-setting-values [enable-public-sharing false] (is (= "An error occurred." (http/client :get 400 (field-remapping-url card (mt/id :venues :id) (mt/id :venues :name)) :value "10")))))) ;;; --------------------- GET /api/public/dashboard/:uuid/field/:field/remapping/:remapped-id nil --------------------- (deftest api-endpoint-should-return-same-results-as-function (with-sharing-enabled-and-temp-dashcard-referencing :venues :id [dashboard] (is (= [10 "<NAME>"] (http/client :get 200 (field-remapping-url dashboard (mt/id :venues :id) (mt/id :venues :name)) :value "10"))))) (deftest field-remapping-shouldn-t-work-if-card-doesn-t-reference-the-field-in-question (with-sharing-enabled-and-temp-dashcard-referencing :venues :price [dashboard] (is (= "An error occurred." (http/client :get 400 (field-remapping-url dashboard (mt/id :venues :id) (mt/id :venues :name)) :value "10"))))) (deftest remapping-or-if-the-remapping-field-isn-t-allowed-to-be-used-with-the-other-field (with-sharing-enabled-and-temp-dashcard-referencing :venues :id [dashboard] (is (= "An error occurred." (http/client :get 400 (field-remapping-url dashboard (mt/id :venues :id) (mt/id :venues :price)) :value "10"))))) (deftest remapping-or-if-public-sharing-is-disabled (with-sharing-enabled-and-temp-dashcard-referencing :venues :id [dashboard] (mt/with-temporary-setting-values [enable-public-sharing false] (is (= "An error occurred." (http/client :get 400 (field-remapping-url dashboard (mt/id :venues :id) (mt/id :venues :name)) :value "10")))))) ;;; --------------------------------------------- Chain filter endpoints --------------------------------------------- (deftest chain-filter-test (mt/with-temporary-setting-values [enable-public-sharing true] (dashboard-api-test/with-chain-filter-fixtures [{:keys [dashboard param-keys]}] (let [uuid (str (UUID/randomUUID))] (is (= true (db/update! Dashboard (u/the-id dashboard) :public_uuid uuid))) (testing "GET /api/public/dashboard/:uuid/params/:param-key/values" (let [url (format "public/dashboard/%s/params/%s/values" uuid (:category-id param-keys))] (is (= [2 3 4 5 6] (take 5 (http/client :get 200 url)))))) (testing "GET /api/public/dashboard/:uuid/params/:param-key/search/:query" (let [url (format "public/dashboard/%s/params/%s/search/food" uuid (:category-name param-keys))] (is (= ["Fast Food" "Food Truck" "Seafood"] (take 3 (http/client :get 200 url)))))))))) (deftest chain-filter-ignore-current-user-permissions-test (testing "Should not fail if request is authenticated but current user does not have data permissions" (mt/with-temp-copy-of-db (perms/revoke-permissions! (group/all-users) (mt/db)) (mt/with-temporary-setting-values [enable-public-sharing true] (dashboard-api-test/with-chain-filter-fixtures [{:keys [dashboard param-keys]}] (let [uuid (str (UUID/randomUUID))] (is (= true (db/update! Dashboard (u/the-id dashboard) :public_uuid uuid))) (testing "GET /api/public/dashboard/:uuid/params/:param-key/values" (let [url (format "public/dashboard/%s/params/%s/values" uuid (:category-id param-keys))] (is (= [2 3 4 5 6] (take 5 (mt/user-http-request :rasta :get 200 url)))))) (testing "GET /api/public/dashboard/:uuid/params/:param-key/search/:prefix" (let [url (format "public/dashboard/%s/params/%s/search/food" uuid (:category-name param-keys))] (is (= ["Fast Food" "Food Truck" "Seafood"] (take 3 (mt/user-http-request :rasta :get 200 url)))))))))))) ;; Pivot tables (deftest pivot-public-card-test (mt/test-drivers (pivots/applicable-drivers) (mt/dataset sample-dataset (testing "GET /api/public/pivot/card/:uuid/query" (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-card [{uuid :public_uuid} (pivots/pivot-card)] (let [result (http/client :get 202 (format "public/pivot/card/%s/query" uuid)) rows (mt/rows result)] (is (nil? (:row_count result))) ;; row_count isn't included in public endpoints (is (= "completed" (:status result))) (is (= 6 (count (get-in result [:data :cols])))) (is (= 1144 (count rows))) (is (= ["AK" "Affiliate" "Doohickey" 0 18 81] (first rows))) (is (= ["CO" "Affiliate" "Gadget" 0 62 211] (nth rows 100))) (is (= [nil nil nil 7 18760 69540] (last rows)))))))))) (defn- pivot-dashcard-url "URL for fetching results of a public DashCard." [dash card] (str "public/pivot/dashboard/" (:public_uuid dash) "/card/" (u/the-id card))) (deftest pivot-public-dashcard-test (mt/test-drivers (pivots/applicable-drivers) (mt/dataset sample-dataset (let [dashboard-defaults {:parameters [{:id "_STATE_" :name "State" :slug "state" :type "string" :target [:dimension [:fk-> (mt/$ids $orders.user_id) (mt/$ids $people.state)]] :default nil}]}] (testing "GET /api/public/pivot/dashboard/:uuid/card/:card-id" (testing "without parameters" (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-dashboard [dash dashboard-defaults] (with-temp-public-card [card (pivots/pivot-card)] (add-card-to-dashboard! card dash) (let [result (http/client :get 202 (pivot-dashcard-url dash card)) rows (mt/rows result)] (is (nil? (:row_count result))) ;; row_count isn't included in public endpoints (is (= "completed" (:status result))) (is (= 6 (count (get-in result [:data :cols])))) (is (= 1144 (count rows))) (is (= ["AK" "Affiliate" "Doohickey" 0 18 81] (first rows))) (is (= ["CO" "Affiliate" "Gadget" 0 62 211] (nth rows 100))) (is (= [nil nil nil 7 18760 69540] (last rows)))))))) (testing "with parameters" (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-dashboard [dash dashboard-defaults] (with-temp-public-card [card (pivots/pivot-card)] (add-card-to-dashboard! card dash) (let [result (http/client :get 202 (pivot-dashcard-url dash card) :parameters (json/encode [{:name "State" :slug :state :target [:dimension [:fk-> (mt/$ids $orders.user_id) (mt/$ids $people.state)]] :value ["CA" "WA"]}])) rows (mt/rows result)] (is (nil? (:row_count result))) ;; row_count isn't included in public endpoints (is (= "completed" (:status result))) (is (= 6 (count (get-in result [:data :cols])))) (is (= 80 (count rows))) (is (= ["CA" "Affiliate" "Doohickey" 0 16 48] (first rows))) (is (= [nil "Google" "Gizmo" 1 52 186] (nth rows 50))) (is (= [nil nil nil 7 1015 3758] (last rows)))))))))))))
true
(ns metabase.api.public-test "Tests for `api/public/` (public links) endpoints." (:require [cheshire.core :as json] [clojure.string :as str] [clojure.test :refer :all] [dk.ative.docjure.spreadsheet :as spreadsheet] [metabase.api.dashboard-test :as dashboard-api-test] [metabase.api.pivots :as pivots] [metabase.api.public :as public-api] [metabase.http-client :as http] [metabase.models :refer [Card Collection Dashboard DashboardCard DashboardCardSeries Dimension Field FieldValues]] [metabase.models.permissions :as perms] [metabase.models.permissions-group :as group] [metabase.test :as mt] [metabase.util :as u] [toucan.db :as db]) (:import java.io.ByteArrayInputStream java.util.UUID)) ;;; --------------------------------------------------- Helper Fns --------------------------------------------------- (defn count-of-venues-card [] {:dataset_query (mt/mbql-query venues {:aggregation [[:count]]})}) (defn shared-obj [] {:public_uuid (str (UUID/randomUUID)) :made_public_by_id (mt/user->id :crowberto)}) (defmacro with-temp-public-card {:style/indent 1} [[binding & [card]] & body] `(let [card-defaults# ~card card-settings# (merge (when-not (:dataset_query card-defaults#) (count-of-venues-card)) (shared-obj) card-defaults#)] (mt/with-temp Card [card# card-settings#] ;; add :public_uuid back in to the value that gets bound because it might not come back from post-select if ;; public sharing is disabled; but we still want to test it (let [~binding (assoc card# :public_uuid (:public_uuid card-settings#))] ~@body)))) (defmacro with-temp-public-dashboard {:style/indent 1} [[binding & [dashboard]] & body] `(let [dashboard-defaults# ~dashboard dashboard-settings# (merge (when-not (:parameters dashboard-defaults#) {:parameters [{:id "_VENUE_ID_" :name "Venue ID" :slug "venue_id" :type "id" :target [:dimension (mt/id :venues :id)] :default nil}]}) (shared-obj) dashboard-defaults#)] (mt/with-temp Dashboard [dashboard# dashboard-settings#] (let [~binding (assoc dashboard# :public_uuid (:public_uuid dashboard-settings#))] ~@body)))) (defn add-card-to-dashboard! {:style/indent 2} [card dashboard & {:as kvs}] (db/insert! DashboardCard (merge {:dashboard_id (u/the-id dashboard), :card_id (u/the-id card)} kvs))) (defmacro ^:private with-temp-public-dashboard-and-card {:style/indent 1} [[dashboard-binding card-binding & [dashcard-binding]] & body] `(with-temp-public-dashboard [dash#] (with-temp-public-card [card#] (let [~dashboard-binding dash# ~card-binding card# ~(or dashcard-binding (gensym "dashcard")) (add-card-to-dashboard! card# dash#)] ~@body)))) ;;; ------------------------------------------- GET /api/public/card/:uuid ------------------------------------------- (deftest check-that-we--cannot--fetch-a-publiccard-if-the-setting-is-disabled (mt/with-temporary-setting-values [enable-public-sharing false] (with-temp-public-card [{uuid :public_uuid}] (is (= "An error occurred." (http/client :get 400 (str "public/card/" uuid))))))) (deftest check-that-we-get-a-400-if-the-publiccard-doesn-t-exist (mt/with-temporary-setting-values [enable-public-sharing true] (is (= "An error occurred." (http/client :get 400 (str "public/card/" (UUID/randomUUID))))))) (deftest check-that-we--cannot--fetch-a-publiccard-if-the-card-has-been-archived (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-card [{uuid :public_uuid} {:archived true}] (is (= "An error occurred." (http/client :get 400 (str "public/card/" uuid))))))) (deftest check-that-we-can-fetch-a-publiccard (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-card [{uuid :public_uuid}] (is (= #{:dataset_query :description :display :id :name :visualization_settings :param_values :param_fields} (set (keys (http/client :get 200 (str "public/card/" uuid))))))))) (deftest make-sure--param-values-get-returned-as-expected (mt/with-temp Card [card {:dataset_query {:database (mt/id) :type :native :native {:query (str "SELECT COUNT(*) " "FROM venues " "LEFT JOIN categories ON venues.category_id = categories.id " "WHERE {{category}}") :collection "CATEGORIES" :template-tags {:category {:name "category" :display-name "Category" :type "dimension" :dimension ["field" (mt/id :categories :name) nil] :widget-type "category" :required true}}}}}] (is (= {(mt/id :categories :name) {:values 75 :human_readable_values [] :field_id (mt/id :categories :name)}} (-> (:param_values (#'public-api/public-card :id (u/the-id card))) (update-in [(mt/id :categories :name) :values] count) (update (mt/id :categories :name) #(into {} %))))))) ;;; ------------------------- GET /api/public/card/:uuid/query (and JSON/CSV/XSLX versions) -------------------------- (deftest check-that-we--cannot--execute-a-publiccard-if-the-setting-is-disabled (mt/with-temporary-setting-values [enable-public-sharing false] (with-temp-public-card [{uuid :public_uuid}] (is (= "An error occurred." (http/client :get 400 (str "public/card/" uuid "/query"))))))) (deftest check-that-we-get-a-400-if-the-publiccard-doesn-t-exist-query (mt/with-temporary-setting-values [enable-public-sharing true] (is (= "An error occurred." (http/client :get 400 (str "public/card/" (UUID/randomUUID) "/query")))))) (deftest check-that-we--cannot--execute-a-publiccard-if-the-card-has-been-archived (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-card [{uuid :public_uuid} {:archived true}] (is (= "An error occurred." (http/client :get 400 (str "public/card/" uuid "/query"))))))) (defn- parse-xlsx-response [response] (->> (ByteArrayInputStream. response) spreadsheet/load-workbook (spreadsheet/select-sheet "Query result") (spreadsheet/select-columns {:A :col}))) (deftest execute-public-card-test (testing "GET /api/public/card/:uuid/query" (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-card [{uuid :public_uuid}] (testing "Default :api response format" (is (= [[100]] (mt/rows (http/client :get 202 (str "public/card/" uuid "/query")))))) (testing ":json download response format" (is (= [{:Count 100}] (http/client :get 200 (str "public/card/" uuid "/query/json"))))) (testing ":csv download response format" (is (= "Count\n100\n" (http/client :get 200 (str "public/card/" uuid "/query/csv"), :format :csv)))) (testing ":xlsx download response format" (is (= [{:col "Count"} {:col 100.0}] (parse-xlsx-response (http/client :get 200 (str "public/card/" uuid "/query/xlsx") {:request-options {:as :byte-array}}))))))))) (deftest execute-public-card-as-user-without-perms-test (testing "A user that doesn't have permissions to run the query normally should still be able to run a public Card as if they weren't logged in" (mt/with-temporary-setting-values [enable-public-sharing true] (mt/with-temp Collection [{collection-id :id}] (perms/revoke-collection-permissions! (group/all-users) collection-id) (with-temp-public-card [{card-id :id, uuid :public_uuid} {:collection_id collection-id}] (is (= "You don't have permissions to do that." ((mt/user->client :rasta) :post 403 (format "card/%d/query" card-id))) "Sanity check: shouldn't be allowed to run the query normally") (is (= [[100]] (mt/rows ((mt/user->client :rasta) :get 202 (str "public/card/" uuid "/query")))))))))) (deftest check-that-we-can-exec-a-publiccard-with---parameters- (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-card [{uuid :public_uuid}] (is (= [{:id "_VENUE_ID_", :name "Venue ID", :slug "venue_id", :type "id", :value 2}] (get-in (http/client :get 202 (str "public/card/" uuid "/query") :parameters (json/encode [{:id "_VENUE_ID_" :name "Venue ID" :slug "venue_id" :type "id" :value 2}])) [:json_query :parameters])))))) ;; Cards with required params (defn- do-with-required-param-card [f] (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-card [{uuid :public_uuid} {:dataset_query {:database (mt/id) :type :native :native {:query "SELECT count(*) FROM venues v WHERE price = {{price}}" :template-tags {"price" {:name "price" :display-name "Price" :type :number :required true}}}}}] (f uuid)))) (defmacro ^:private with-required-param-card [[uuid-binding] & body] `(do-with-required-param-card (fn [~uuid-binding] ~@body))) (deftest should-be-able-to-run-a-card-with-a-required-param (with-required-param-card [uuid] (is (= [[22]] (mt/rows (http/client :get 202 (str "public/card/" uuid "/query") :parameters (json/encode [{:type "category" :target [:variable [:template-tag "price"]] :value 1}]))))))) (deftest missing-required-param-error-message-test (testing (str "If you're missing a required param, the error message should get passed thru, rather than the normal " "generic 'Query Failed' message that we show for most embedding errors") (with-required-param-card [uuid] (is (= {:status "failed" :error "You'll need to pick a value for 'Price' before this query can run." :error_type "missing-required-parameter"} (mt/suppress-output (http/client :get 202 (str "public/card/" uuid "/query")))))))) (defn- card-with-date-field-filter [] (assoc (shared-obj) :dataset_query {:database (mt/id) :type :native :native {:query "SELECT COUNT(*) AS \"count\" FROM CHECKINS WHERE {{date}}" :template-tags {:date {:name "date" :display-name "Date" :type "dimension" :dimension [:field (mt/id :checkins :date) nil] :widget-type "date/quarter-year"}}}})) (deftest make-sure-csv--etc---downloads-take-editable-params-into-account---6407---- (mt/with-temporary-setting-values [enable-public-sharing true] (mt/with-temp Card [{uuid :public_uuid} (card-with-date-field-filter)] (is (= "count\n107\n" (http/client :get 200 (str "public/card/" uuid "/query/csv") :parameters (json/encode [{:id "_DATE_" :type :date/quarter-year :target [:dimension [:template-tag :date]] :value "Q1-2014"}]))))))) (deftest make-sure-it-also-works-with-the-forwarded-url (mt/with-temporary-setting-values [enable-public-sharing true] (mt/with-temp Card [{uuid :public_uuid} (card-with-date-field-filter)] ;; make sure the URL doesn't include /api/ at the beginning like it normally would (binding [http/*url-prefix* (str/replace http/*url-prefix* #"/api/$" "/")] (mt/with-temporary-setting-values [site-url http/*url-prefix*] (is (= "count\n107\n" (http/client :get 200 (str "public/question/" uuid ".csv") :parameters (json/encode [{:id "_DATE_" :type :date/quarter-year :target [:dimension [:template-tag :date]] :value "Q1-2014"}]))))))))) (defn- card-with-trendline [] (assoc (shared-obj) :dataset_query {:database (mt/id) :type :query :query {:source-table (mt/id :checkins) :breakout [[:datetime-field [:field (mt/id :checkins :date) nil] :month]] :aggregation [[:count]]}})) (deftest make-sure-we-include-all-the-relevant-fields-like-insights (mt/with-temporary-setting-values [enable-public-sharing true] (mt/with-temp Card [{uuid :public_uuid} (card-with-trendline)] (is (= #{:cols :rows :insights :results_timezone} (-> (http/client :get 202 (str "public/card/" uuid "/query")) :data keys set)))))) ;;; ---------------------------------------- GET /api/public/dashboard/:uuid ----------------------------------------- (deftest get-public-dashboard-errors-test (testing "GET /api/public/dashboard/:uuid" (testing "Shouldn't be able to fetch a public Dashboard if public sharing is disabled" (mt/with-temporary-setting-values [enable-public-sharing false] (with-temp-public-dashboard [{uuid :public_uuid}] (is (= "An error occurred." (http/client :get 400 (str "public/dashboard/" uuid))))))) (testing "Should get a 400 if the Dashboard doesn't exist" (mt/with-temporary-setting-values [enable-public-sharing true] (is (= "An error occurred." (http/client :get 400 (str "public/dashboard/" (UUID/randomUUID))))))))) (defn- fetch-public-dashboard [{uuid :public_uuid}] (-> (http/client :get 200 (str "public/dashboard/" uuid)) (select-keys [:name :ordered_cards]) (update :name boolean) (update :ordered_cards count))) (deftest get-public-dashboard-test (testing "GET /api/public/dashboard/:uuid" (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-dashboard-and-card [dash card] (is (= {:name true, :ordered_cards 1} (fetch-public-dashboard dash))) (testing "We shouldn't see Cards that have been archived" (db/update! Card (u/the-id card), :archived true) (is (= {:name true, :ordered_cards 0} (fetch-public-dashboard dash)))))))) ;;; --------------------------------- GET /api/public/dashboard/:uuid/card/:card-id ---------------------------------- (defn- dashcard-url "URL for fetching results of a public DashCard." [dash card] (str "public/dashboard/" (:public_uuid dash) "/card/" (u/the-id card))) (deftest execute-public-dashcard-errors-test (testing "GET /api/public/dashboard/:uuid/card/:card-id" (testing "Shouldn't be able to execute a public DashCard if public sharing is disabled" (mt/with-temporary-setting-values [enable-public-sharing false] (with-temp-public-dashboard-and-card [dash card] (is (= "An error occurred." (http/client :get 400 (dashcard-url dash card))))))) (testing "Should get a 400" (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-dashboard-and-card [dash card] (testing "if the Dashboard doesn't exist" (is (= "An error occurred." (http/client :get 400 (dashcard-url {:public_uuid (UUID/randomUUID)} card))))) (testing "if the Card doesn't exist" (is (= "An error occurred." (http/client :get 400 (dashcard-url dash Integer/MAX_VALUE))))) (testing "if the Card exists, but it's not part of this Dashboard" (mt/with-temp Card [card] (is (= "An error occurred." (http/client :get 400 (dashcard-url dash card)))))) (testing "if the Card has been archived." (db/update! Card (u/the-id card), :archived true) (is (= "An error occurred." (http/client :get 400 (dashcard-url dash card)))))))))) (deftest execute-public-dashcard-test (testing "GET /api/public/dashboard/:uuid/card/:card-id" (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-dashboard-and-card [dash card] (is (= [[100]] (mt/rows (http/client :get 202 (dashcard-url dash card))))) (testing "with parameters" (is (= [{:id "_VENUE_ID_" :name "Venue ID" :slug "venue_id" :target ["dimension" (mt/id :venues :id)] :value [10] :default nil :type "id"}] (get-in (http/client :get 202 (dashcard-url dash card) :parameters (json/encode [{:name "Venue ID" :slug :venue_id :target [:dimension (mt/id :venues :id)] :value [10]}])) [:json_query :parameters])))))))) (deftest execute-public-dashcard-as-user-without-perms-test (testing "GET /api/public/dashboard/:uuid/card/:card-id" (testing "A user that doesn't have permissions to run the query normally should still be able to run a public DashCard" (mt/with-temporary-setting-values [enable-public-sharing true] (mt/with-temp Collection [{collection-id :id}] (perms/revoke-collection-permissions! (group/all-users) collection-id) (with-temp-public-dashboard-and-card [dash {card-id :id, :as card}] (db/update! Card card-id :collection_id collection-id) (is (= "You don't have permissions to do that." ((mt/user->client :rasta) :post 403 (format "card/%d/query" card-id))) "Sanity check: shouldn't be allowed to run the query normally") (is (= [[100]] (mt/rows ((mt/user->client :rasta) :get 202 (dashcard-url dash card))))))))))) (deftest execute-public-dashcard-params-validation-test (testing "GET /api/public/dashboard/:uuid/card/:card-id" (testing "Make sure params are validated" (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-dashboard-and-card [dash card] (testing "Should work correctly with a valid parameter" (is (= [[1]] (mt/rows (http/client :get 202 (dashcard-url dash card) :parameters (json/encode [{:name "Venue ID" :slug :venue_id :target [:dimension (mt/id :venues :id)] :value [10]}])))) "This should pass because venue_id *is* one of the Dashboard's :parameters")) (testing "should fail if" (testing "a parameter is passed that is not one of the Dashboard's parameters" (is (= "An error occurred." (http/client :get 400 (dashcard-url dash card) :parameters (json/encode [{:name "Venue Name" :slug :venue_name :target [:dimension (mt/id :venues :name)] :value ["PizzaHacker"]}]))))))))))) (deftest execute-public-dashcard-additional-series-test (testing "GET /api/public/dashboard/:uuid/card/:card-id" (testing "should work with an additional Card series" (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-dashboard-and-card [dash card] (with-temp-public-card [card-2] (mt/with-temp DashboardCardSeries [_ {:dashboardcard_id (db/select-one-id DashboardCard :card_id (u/the-id card) :dashboard_id (u/the-id dash)) :card_id (u/the-id card-2)}] (is (= [[100]] (mt/rows (http/client :get 202 (dashcard-url dash card-2)))))))))))) (deftest execute-public-dashcard-parameters-test (testing "GET /api/public/dashboard/:uuid/card/:card-id" (testing "Make sure parameters work correctly (#7212)" (mt/with-temporary-setting-values [enable-public-sharing true] (testing "with native queries and template tag params" (mt/with-temp Card [card {:dataset_query {:database (mt/id) :type :native :native {:query "SELECT {{num}} AS num" :template-tags {:num {:name "num" :display-name "Num" :type "number" :required true :default "1"}}}}}] (with-temp-public-dashboard [dash {:parameters [{:name "Num" :slug "num" :id "537e37b4" :type "category"}]}] (add-card-to-dashboard! card dash :parameter_mappings [{:card_id (u/the-id card) :target [:variable [:template-tag :num]] :parameter_id "537e37b4"}]) (is (= [[50]] (-> ((mt/user->client :crowberto) :get (str (dashcard-url dash card) "?parameters=" (json/generate-string [{:type :category :target [:variable [:template-tag :num]] :value "50"}]))) mt/rows)))))) (testing "with MBQL queries" (testing "`:id` parameters" (mt/with-temp Card [card {:dataset_query {:database (mt/id) :type :query :query {:source-table (mt/id :venues) :aggregation [:count]}}}] (with-temp-public-dashboard [dash {:parameters [{:name "Venue ID" :slug "venue_id" :id "22486e00" :type "id"}]}] (add-card-to-dashboard! card dash :parameter_mappings [{:parameter_id "22486e00" :card_id (u/the-id card) :target [:dimension [:field (mt/id :venues :id) nil]]}]) (is (= [[1]] (-> ((mt/user->client :crowberto) :get (str (dashcard-url dash card) "?parameters=" (json/generate-string [{:type :id :target [:dimension [:field (mt/id :venues :id) nil]] :value "50"}]))) mt/rows)))))) (testing "temporal parameters" (mt/with-temporary-setting-values [enable-public-sharing true] (mt/with-temp Card [card {:dataset_query {:database (mt/id) :type :query :query {:source-table (mt/id :checkins) :aggregation [:count]}}}] (with-temp-public-dashboard [dash {:parameters [{:name "Date Filter" :slug "date_filter" :id "18a036ec" :type "date/all-options"}]}] (add-card-to-dashboard! card dash :parameter_mappings [{:parameter_id "18a036ec" :card_id (u/the-id card) :target [:dimension [:field (mt/id :checkins :date) nil]]}]) (is (= [[733]] (-> ((mt/user->client :crowberto) :get (str (dashcard-url dash card) "?parameters=" (json/generate-string [{:type "date/all-options" :target [:dimension [:field (mt/id :checkins :date) nil]] :value "~2015-01-01"}]))) mt/rows)))))))))))) (deftest execute-public-dashcard-dimension-value-params-test (testing "GET /api/public/dashboard/:uuid/card/:card-id" (testing (str "make sure DimensionValue params also work if they have a default value, even if some is passed in " "for some reason as part of the query (#7253) If passed in as part of the query however make sure it " "doesn't override what's actually in the DB") (mt/with-temporary-setting-values [enable-public-sharing true] (mt/with-temp Card [card {:dataset_query {:database (mt/id) :type :native :native {:query "SELECT {{msg}} AS message" :template-tags {:msg {:id "181da7c5" :name "msg" :display-name "Message" :type "text" :required true :default "Wow"}}}}}] (with-temp-public-dashboard [dash {:parameters [{:name "Message" :slug "msg" :id "181da7c5" :type "category"}]}] (add-card-to-dashboard! card dash :parameter_mappings [{:card_id (u/the-id card) :target [:variable [:template-tag :msg]] :parameter_id "181da7c5"}]) (is (= [["Wow"]] (-> ((mt/user->client :crowberto) :get (str (dashcard-url dash card) "?parameters=" (json/generate-string [{:type :category :target [:variable [:template-tag :msg]] :value nil :default "Hello"}]))) mt/rows))))))))) ;;; --------------------------- Check that parameter information comes back with Dashboard --------------------------- (deftest double-check-that-the-field-has-fieldvalues (is (= [1 2 3 4] (db/select-one-field :values FieldValues :field_id (mt/id :venues :price))))) (defn- price-param-values [] {(keyword (str (mt/id :venues :price))) {:values [1 2 3 4] :human_readable_values [] :field_id (mt/id :venues :price)}}) (defn- add-price-param-to-dashboard! [dashboard] (db/update! Dashboard (u/the-id dashboard) :parameters [{:name "Price", :type "category", :slug "price", :id "_PRICE_"}])) (defn- add-dimension-param-mapping-to-dashcard! [dashcard card dimension] (db/update! DashboardCard (u/the-id dashcard) :parameter_mappings [{:card_id (u/the-id card) :target ["dimension" dimension]}])) (defn- GET-param-values [dashboard] (mt/with-temporary-setting-values [enable-public-sharing true] (:param_values (http/client :get 200 (str "public/dashboard/" (:public_uuid dashboard)))))) (deftest check-that-param-info-comes-back-for-sql-cards (with-temp-public-dashboard-and-card [dash card dashcard] (db/update! Card (u/the-id card) :dataset_query {:database (mt/id) :type :native :native {:template-tags {:price {:name "price" :display-name "Price" :type "dimension" :dimension ["field" (mt/id :venues :price) nil]}}}}) (add-price-param-to-dashboard! dash) (add-dimension-param-mapping-to-dashcard! dashcard card ["template-tag" "price"]) (is (= (price-param-values) (GET-param-values dash))))) (deftest check-that-param-info-comes-back-for-mbql-cards--field-id- (with-temp-public-dashboard-and-card [dash card dashcard] (add-price-param-to-dashboard! dash) (add-dimension-param-mapping-to-dashcard! dashcard card ["field" (mt/id :venues :price) nil]) (is (= (price-param-values) (GET-param-values dash))))) (deftest check-that-param-info-comes-back-for-mbql-cards--fk--- (with-temp-public-dashboard-and-card [dash card dashcard] (add-price-param-to-dashboard! dash) (add-dimension-param-mapping-to-dashcard! dashcard card [:field (mt/id :venues :price) {:source-field (mt/id :checkins :venue_id)}]) (is (= (price-param-values) (GET-param-values dash))))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | New FieldValues search endpoints | ;;; +----------------------------------------------------------------------------------------------------------------+ (defn- mbql-card-referencing-nothing [] {:dataset_query {:database (mt/id) :type :query :query {:source-table (mt/id :venues)}}}) (defn mbql-card-referencing [table-kw field-kw] {:dataset_query {:database (mt/id) :type :query :query {:source-table (mt/id table-kw) :filter [:= [:field (mt/id table-kw field-kw) nil] "PI:NAME:<NAME>END_PIa Siri"]}}}) (defn- mbql-card-referencing-venue-name [] (mbql-card-referencing :venues :name)) (defn- sql-card-referencing-venue-name [] {:dataset_query {:database (mt/id) :type :native :native {:query "SELECT COUNT(*) FROM VENUES WHERE {{x}}" :template-tags {:x {:name :x :display-name "X" :type :dimension :dimension [:field (mt/id :venues :name) nil]}}}}}) ;;; ------------------------------------------- card->referenced-field-ids ------------------------------------------- (deftest card-referencing-nothing (mt/with-temp Card [card (mbql-card-referencing-nothing)] (is (= #{} (#'public-api/card->referenced-field-ids card))))) (deftest it-should-pick-up-on-fields-referenced-in-the-mbql-query-itself (mt/with-temp Card [card (mbql-card-referencing-venue-name)] (is (= #{(mt/id :venues :name)} (#'public-api/card->referenced-field-ids card))))) (deftest ---as-well-as-template-tag--implict--params-for-sql-queries (mt/with-temp Card [card (sql-card-referencing-venue-name)] (is (= #{(mt/id :venues :name)} (#'public-api/card->referenced-field-ids card))))) ;;; --------------------------------------- check-field-is-referenced-by-card ---------------------------------------- (deftest check-that-the-check-succeeds-when-field-is-referenced (mt/with-temp Card [card (mbql-card-referencing-venue-name)] (#'public-api/check-field-is-referenced-by-card (mt/id :venues :name) (u/the-id card)))) (deftest check-that-exception-is-thrown-if-the-field-isn-t-referenced (is (thrown? Exception (mt/with-temp Card [card (mbql-card-referencing-venue-name)] (#'public-api/check-field-is-referenced-by-card (mt/id :venues :category_id) (u/the-id card)))))) ;;; ----------------------------------------- check-search-field-is-allowed ------------------------------------------ ;; search field is allowed IF: ;; A) search-field is the same field as the other one (deftest search-field-allowed-if-same-field-as-other-one (#'public-api/check-search-field-is-allowed (mt/id :venues :id) (mt/id :venues :id)) (is (thrown? Exception (#'public-api/check-search-field-is-allowed (mt/id :venues :id) (mt/id :venues :category_id))))) ;; B) there's a Dimension that lists search field as the human_readable_field for the other field (deftest search-field-allowed-with-dimension (is (mt/with-temp Dimension [_ {:field_id (mt/id :venues :id), :human_readable_field_id (mt/id :venues :category_id)}] (#'public-api/check-search-field-is-allowed (mt/id :venues :id) (mt/id :venues :category_id))))) ;; C) search-field is a Name Field belonging to the same table as the other field, which is a PK (deftest search-field-allowed-with-name-field (is (#'public-api/check-search-field-is-allowed (mt/id :venues :id) (mt/id :venues :name)))) ;; not allowed if search field isn't a NAME (deftest search-field-not-allowed-if-search-field-isnt-a-name (is (thrown? Exception (mt/with-temp-vals-in-db Field (mt/id :venues :name) {:semantic_type "type/Latitude"} (#'public-api/check-search-field-is-allowed (mt/id :venues :id) (mt/id :venues :name)))))) (deftest not-allowed-if-search-field-belongs-to-a-different-table (is (thrown? Exception (mt/with-temp-vals-in-db Field (mt/id :categories :name) {:semantic_type "type/Name"} (#'public-api/check-search-field-is-allowed (mt/id :venues :id) (mt/id :categories :name)))))) ;;; ------------------------------------- check-field-is-referenced-by-dashboard ------------------------------------- (defn- dashcard-with-param-mapping-to-venue-id [dashboard card] {:dashboard_id (u/the-id dashboard) :card_id (u/the-id card) :parameter_mappings [{:card_id (u/the-id card) :target [:dimension [:field (mt/id :venues :id) nil]]}]}) (deftest field-is--referenced--by-dashboard-if-it-s-one-of-the-dashboard-s-params--- (is (mt/with-temp* [Dashboard [dashboard] Card [card] DashboardCard [_ (dashcard-with-param-mapping-to-venue-id dashboard card)]] (#'public-api/check-field-is-referenced-by-dashboard (mt/id :venues :id) (u/the-id dashboard))))) (deftest TODO-name-this-exception (is (thrown? Exception (mt/with-temp* [Dashboard [dashboard] Card [card] DashboardCard [_ (dashcard-with-param-mapping-to-venue-id dashboard card)]] (#'public-api/check-field-is-referenced-by-dashboard (mt/id :venues :name) (u/the-id dashboard)))))) ;; ...*or* if it's a so-called "implicit" param (a Field Filter Template Tag (FFTT) in a SQL Card) (deftest implicit-param (is (mt/with-temp* [Dashboard [dashboard] Card [card (sql-card-referencing-venue-name)] DashboardCard [_ {:dashboard_id (u/the-id dashboard), :card_id (u/the-id card)}]] (#'public-api/check-field-is-referenced-by-dashboard (mt/id :venues :name) (u/the-id dashboard)))) (is (thrown? Exception (mt/with-temp* [Dashboard [dashboard] Card [card (sql-card-referencing-venue-name)] DashboardCard [_ {:dashboard_id (u/the-id dashboard), :card_id (u/the-id card)}]] (#'public-api/check-field-is-referenced-by-dashboard (mt/id :venues :id) (u/the-id dashboard)))))) ;;; ------------------------------------------- card-and-field-id->values -------------------------------------------- (deftest we-should-be-able-to-get-values-for-a-field-referenced-by-a-card (mt/with-temp Card [card (mbql-card-referencing :venues :name)] (is (= {:values [["20th Century Cafe"] ["25°"] ["33 Taps"] ["800 Degrees Neapolitan Pizzeria"] ["BCD Tofu House"]] :field_id (mt/id :venues :name)} (mt/derecordize (-> (public-api/card-and-field-id->values (u/the-id card) (mt/id :venues :name)) (update :values (partial take 5)))))))) (deftest sql-param-field-references-should-work-just-as-well-as-mbql-field-referenced (mt/with-temp Card [card (sql-card-referencing-venue-name)] (is (= {:values [["20th Century Cafe"] ["25°"] ["33 Taps"] ["800 Degrees Neapolitan Pizzeria"] ["BCD Tofu House"]] :field_id (mt/id :venues :name)} (mt/derecordize (-> (public-api/card-and-field-id->values (u/the-id card) (mt/id :venues :name)) (update :values (partial take 5)))))))) (deftest but-if-the-field-is-not-referenced-we-should-get-an-exception (mt/with-temp Card [card (mbql-card-referencing :venues :price)] (is (thrown? Exception (public-api/card-and-field-id->values (u/the-id card) (mt/id :venues :name)))))) ;;; ------------------------------- GET /api/public/card/:uuid/field/:field/values nil -------------------------------- (defn- field-values-url [card-or-dashboard field-or-id] (str "public/" (condp instance? card-or-dashboard (class Card) "card" (class Dashboard) "dashboard") "/" (or (:public_uuid card-or-dashboard) (throw (Exception. (str "Missing public UUID: " card-or-dashboard)))) "/field/" (u/the-id field-or-id) "/values")) (defn- do-with-sharing-enabled-and-temp-card-referencing {:style/indent 2} [table-kw field-kw f] (mt/with-temporary-setting-values [enable-public-sharing true] (mt/with-temp Card [card (merge (shared-obj) (mbql-card-referencing table-kw field-kw))] (f card)))) (defmacro ^:private with-sharing-enabled-and-temp-card-referencing {:style/indent 3} [table-kw field-kw [card-binding] & body] `(do-with-sharing-enabled-and-temp-card-referencing ~table-kw ~field-kw (fn [~card-binding] ~@body))) (deftest should-be-able-to-fetch-values-for-a-field-referenced-by-a-public-card (is (= {:values [["20th Century Cafe"] ["25°"] ["33 Taps"] ["800 Degrees Neapolitan Pizzeria"] ["BCD Tofu House"]] :field_id (mt/id :venues :name)} (with-sharing-enabled-and-temp-card-referencing :venues :name [card] (-> (http/client :get 200 (field-values-url card (mt/id :venues :name))) (update :values (partial take 5))))))) (deftest but-for-fields-that-are-not-referenced-we-should-get-an-exception (is (= "An error occurred." (with-sharing-enabled-and-temp-card-referencing :venues :name [card] (http/client :get 400 (field-values-url card (mt/id :venues :price))))))) (deftest field-value-endpoint-should-fail-if-public-sharing-is-disabled (is (= "An error occurred." (with-sharing-enabled-and-temp-card-referencing :venues :name [card] (mt/with-temporary-setting-values [enable-public-sharing false] (http/client :get 400 (field-values-url card (mt/id :venues :name)))))))) ;;; ----------------------------- GET /api/public/dashboard/:uuid/field/:field/values nil ----------------------------- (defn do-with-sharing-enabled-and-temp-dashcard-referencing {:style/indent 2} [table-kw field-kw f] (mt/with-temporary-setting-values [enable-public-sharing true] (mt/with-temp* [Dashboard [dashboard (shared-obj)] Card [card (mbql-card-referencing table-kw field-kw)] DashboardCard [dashcard {:dashboard_id (u/the-id dashboard) :card_id (u/the-id card) :parameter_mappings [{:card_id (u/the-id card) :target [:dimension [:field (mt/id table-kw field-kw) nil]]}]}]] (f dashboard card dashcard)))) (defmacro with-sharing-enabled-and-temp-dashcard-referencing {:style/indent 3} [table-kw field-kw [dashboard-binding card-binding dashcard-binding] & body] `(do-with-sharing-enabled-and-temp-dashcard-referencing ~table-kw ~field-kw (fn [~(or dashboard-binding '_) ~(or card-binding '_) ~(or dashcard-binding '_)] ~@body))) (deftest should-be-able-to-use-it-when-everything-is-g2g (with-sharing-enabled-and-temp-dashcard-referencing :venues :name [dashboard] (is (= {:values [["20th Century Cafe"] ["25°"] ["33 Taps"] ["800 Degrees Neapolitan Pizzeria"] ["BCD Tofu House"]] :field_id (mt/id :venues :name)} (-> (http/client :get 200 (field-values-url dashboard (mt/id :venues :name))) (update :values (partial take 5))))))) (deftest shound-not-be-able-to-use-the-endpoint-with-a-field-not-referenced-by-the-dashboard (with-sharing-enabled-and-temp-dashcard-referencing :venues :name [dashboard] (is (= "An error occurred." (http/client :get 400 (field-values-url dashboard (mt/id :venues :price))))))) (deftest endpoint-should-fail-if-public-sharing-is-disabled (with-sharing-enabled-and-temp-dashcard-referencing :venues :name [dashboard] (mt/with-temporary-setting-values [enable-public-sharing false] (is (= "An error occurred." (http/client :get 400 (field-values-url dashboard (mt/id :venues :name)))))))) ;;; ----------------------------------------------- search-card-fields ----------------------------------------------- (deftest search-card-fields (with-sharing-enabled-and-temp-card-referencing :venues :id [card] (is (= [[93 "33 Taps"]] (public-api/search-card-fields (u/the-id card) (mt/id :venues :id) (mt/id :venues :name) "33 T" 10))))) (deftest shouldn-t-work-if-the-search-field-isn-t-allowed-to-be-used-in-combination-with-the-other-field (with-sharing-enabled-and-temp-card-referencing :venues :id [card] (is (thrown? Exception (public-api/search-card-fields (u/the-id card) (mt/id :venues :id) (mt/id :venues :price) "33 T" 10))))) (deftest shouldn-t-work-if-the-field-isn-t-referenced-by-card (with-sharing-enabled-and-temp-card-referencing :venues :name [card] (is (thrown? Exception (public-api/search-card-fields (u/the-id card) (mt/id :venues :id) (mt/id :venues :id) "33 T" 10))))) ;;; ----------------------- GET /api/public/card/:uuid/field/:field/search/:search-field-id nil ----------------------- (defn- field-search-url [card-or-dashboard field-or-id search-field-or-id] (str "public/" (condp instance? card-or-dashboard (class Card) "card" (class Dashboard) "dashboard") "/" (:public_uuid card-or-dashboard) "/field/" (u/the-id field-or-id) "/search/" (u/the-id search-field-or-id))) (deftest field-search-with-venue (is (= [[93 "33 Taps"]] (with-sharing-enabled-and-temp-card-referencing :venues :id [card] (http/client :get 200 (field-search-url card (mt/id :venues :id) (mt/id :venues :name)) :value "33 T"))))) (deftest if-search-field-isn-t-allowed-to-be-used-with-the-other-field-endpoint-should-return-exception (is (= "An error occurred." (with-sharing-enabled-and-temp-card-referencing :venues :id [card] (http/client :get 400 (field-search-url card (mt/id :venues :id) (mt/id :venues :price)) :value "33 T"))))) (deftest search-endpoint-should-fail-if-public-sharing-is-disabled (is (= "An error occurred." (with-sharing-enabled-and-temp-card-referencing :venues :id [card] (mt/with-temporary-setting-values [enable-public-sharing false] (http/client :get 400 (field-search-url card (mt/id :venues :id) (mt/id :venues :name)) :value "33 T")))))) ;;; -------------------- GET /api/public/dashboard/:uuid/field/:field/search/:search-field-id nil --------------------- (deftest dashboard (with-sharing-enabled-and-temp-dashcard-referencing :venues :id [dashboard] (is (= [[93 "33 Taps"]] (http/client :get (field-search-url dashboard (mt/id :venues :id) (mt/id :venues :name)) :value "33 T"))))) (deftest dashboard-if-search-field-isn-t-allowed-to-be-used-with-the-other-field-endpoint-should-return-exception (with-sharing-enabled-and-temp-dashcard-referencing :venues :id [dashboard] (is (= "An error occurred." (http/client :get 400 (field-search-url dashboard (mt/id :venues :id) (mt/id :venues :price)) :value "33 T"))))) (deftest dashboard-endpoint-should-fail-if-public-sharing-is-disabled (with-sharing-enabled-and-temp-dashcard-referencing :venues :id [dashboard] (mt/with-temporary-setting-values [enable-public-sharing false] (is (= "An error occurred." (http/client :get 400 (field-search-url dashboard (mt/id :venues :name) (mt/id :venues :name)) :value "33 T")))))) ;;; --------------------------------------------- field-remapped-values ---------------------------------------------- ;; `field-remapped-values` should return remappings in the expected format when the combination of Fields is allowed. ;; It should parse the value string (it comes back from the API as a string since it is a query param) (deftest should-parse-string (is (= [10 "PI:NAME:<NAME>END_PI 62"] (#'public-api/field-remapped-values (mt/id :venues :id) (mt/id :venues :name) "10")))) (deftest if-the-field-isn-t-allowed (is (thrown? Exception (#'public-api/field-remapped-values (mt/id :venues :id) (mt/id :venues :price) "10")))) ;;; ----------------------- GET /api/public/card/:uuid/field/:field/remapping/:remapped-id nil ------------------------ (defn- field-remapping-url [card-or-dashboard field-or-id remapped-field-or-id] (str "public/" (condp instance? card-or-dashboard (class Card) "card" (class Dashboard) "dashboard") "/" (:public_uuid card-or-dashboard) "/field/" (u/the-id field-or-id) "/remapping/" (u/the-id remapped-field-or-id))) (deftest we-should-be-able-to-use-the-api-endpoint-and-get-the-same-results-we-get-by-calling-the-function-above-directly (with-sharing-enabled-and-temp-card-referencing :venues :id [card] (is (= [10 "PI:NAME:<NAME>END_PI"] (http/client :get 200 (field-remapping-url card (mt/id :venues :id) (mt/id :venues :name)) :value "10"))))) (deftest shouldn-t-work-if-card-doesn-t-reference-the-field-in-question (with-sharing-enabled-and-temp-card-referencing :venues :price [card] (is (= "An error occurred." (http/client :get 400 (field-remapping-url card (mt/id :venues :id) (mt/id :venues :name)) :value "10"))))) (deftest ---or-if-the-remapping-field-isn-t-allowed-to-be-used-with-the-other-field (with-sharing-enabled-and-temp-card-referencing :venues :id [card] (is (= "An error occurred." (http/client :get 400 (field-remapping-url card (mt/id :venues :id) (mt/id :venues :price)) :value "10"))))) (deftest ---or-if-public-sharing-is-disabled (with-sharing-enabled-and-temp-card-referencing :venues :id [card] (mt/with-temporary-setting-values [enable-public-sharing false] (is (= "An error occurred." (http/client :get 400 (field-remapping-url card (mt/id :venues :id) (mt/id :venues :name)) :value "10")))))) ;;; --------------------- GET /api/public/dashboard/:uuid/field/:field/remapping/:remapped-id nil --------------------- (deftest api-endpoint-should-return-same-results-as-function (with-sharing-enabled-and-temp-dashcard-referencing :venues :id [dashboard] (is (= [10 "PI:NAME:<NAME>END_PI"] (http/client :get 200 (field-remapping-url dashboard (mt/id :venues :id) (mt/id :venues :name)) :value "10"))))) (deftest field-remapping-shouldn-t-work-if-card-doesn-t-reference-the-field-in-question (with-sharing-enabled-and-temp-dashcard-referencing :venues :price [dashboard] (is (= "An error occurred." (http/client :get 400 (field-remapping-url dashboard (mt/id :venues :id) (mt/id :venues :name)) :value "10"))))) (deftest remapping-or-if-the-remapping-field-isn-t-allowed-to-be-used-with-the-other-field (with-sharing-enabled-and-temp-dashcard-referencing :venues :id [dashboard] (is (= "An error occurred." (http/client :get 400 (field-remapping-url dashboard (mt/id :venues :id) (mt/id :venues :price)) :value "10"))))) (deftest remapping-or-if-public-sharing-is-disabled (with-sharing-enabled-and-temp-dashcard-referencing :venues :id [dashboard] (mt/with-temporary-setting-values [enable-public-sharing false] (is (= "An error occurred." (http/client :get 400 (field-remapping-url dashboard (mt/id :venues :id) (mt/id :venues :name)) :value "10")))))) ;;; --------------------------------------------- Chain filter endpoints --------------------------------------------- (deftest chain-filter-test (mt/with-temporary-setting-values [enable-public-sharing true] (dashboard-api-test/with-chain-filter-fixtures [{:keys [dashboard param-keys]}] (let [uuid (str (UUID/randomUUID))] (is (= true (db/update! Dashboard (u/the-id dashboard) :public_uuid uuid))) (testing "GET /api/public/dashboard/:uuid/params/:param-key/values" (let [url (format "public/dashboard/%s/params/%s/values" uuid (:category-id param-keys))] (is (= [2 3 4 5 6] (take 5 (http/client :get 200 url)))))) (testing "GET /api/public/dashboard/:uuid/params/:param-key/search/:query" (let [url (format "public/dashboard/%s/params/%s/search/food" uuid (:category-name param-keys))] (is (= ["Fast Food" "Food Truck" "Seafood"] (take 3 (http/client :get 200 url)))))))))) (deftest chain-filter-ignore-current-user-permissions-test (testing "Should not fail if request is authenticated but current user does not have data permissions" (mt/with-temp-copy-of-db (perms/revoke-permissions! (group/all-users) (mt/db)) (mt/with-temporary-setting-values [enable-public-sharing true] (dashboard-api-test/with-chain-filter-fixtures [{:keys [dashboard param-keys]}] (let [uuid (str (UUID/randomUUID))] (is (= true (db/update! Dashboard (u/the-id dashboard) :public_uuid uuid))) (testing "GET /api/public/dashboard/:uuid/params/:param-key/values" (let [url (format "public/dashboard/%s/params/%s/values" uuid (:category-id param-keys))] (is (= [2 3 4 5 6] (take 5 (mt/user-http-request :rasta :get 200 url)))))) (testing "GET /api/public/dashboard/:uuid/params/:param-key/search/:prefix" (let [url (format "public/dashboard/%s/params/%s/search/food" uuid (:category-name param-keys))] (is (= ["Fast Food" "Food Truck" "Seafood"] (take 3 (mt/user-http-request :rasta :get 200 url)))))))))))) ;; Pivot tables (deftest pivot-public-card-test (mt/test-drivers (pivots/applicable-drivers) (mt/dataset sample-dataset (testing "GET /api/public/pivot/card/:uuid/query" (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-card [{uuid :public_uuid} (pivots/pivot-card)] (let [result (http/client :get 202 (format "public/pivot/card/%s/query" uuid)) rows (mt/rows result)] (is (nil? (:row_count result))) ;; row_count isn't included in public endpoints (is (= "completed" (:status result))) (is (= 6 (count (get-in result [:data :cols])))) (is (= 1144 (count rows))) (is (= ["AK" "Affiliate" "Doohickey" 0 18 81] (first rows))) (is (= ["CO" "Affiliate" "Gadget" 0 62 211] (nth rows 100))) (is (= [nil nil nil 7 18760 69540] (last rows)))))))))) (defn- pivot-dashcard-url "URL for fetching results of a public DashCard." [dash card] (str "public/pivot/dashboard/" (:public_uuid dash) "/card/" (u/the-id card))) (deftest pivot-public-dashcard-test (mt/test-drivers (pivots/applicable-drivers) (mt/dataset sample-dataset (let [dashboard-defaults {:parameters [{:id "_STATE_" :name "State" :slug "state" :type "string" :target [:dimension [:fk-> (mt/$ids $orders.user_id) (mt/$ids $people.state)]] :default nil}]}] (testing "GET /api/public/pivot/dashboard/:uuid/card/:card-id" (testing "without parameters" (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-dashboard [dash dashboard-defaults] (with-temp-public-card [card (pivots/pivot-card)] (add-card-to-dashboard! card dash) (let [result (http/client :get 202 (pivot-dashcard-url dash card)) rows (mt/rows result)] (is (nil? (:row_count result))) ;; row_count isn't included in public endpoints (is (= "completed" (:status result))) (is (= 6 (count (get-in result [:data :cols])))) (is (= 1144 (count rows))) (is (= ["AK" "Affiliate" "Doohickey" 0 18 81] (first rows))) (is (= ["CO" "Affiliate" "Gadget" 0 62 211] (nth rows 100))) (is (= [nil nil nil 7 18760 69540] (last rows)))))))) (testing "with parameters" (mt/with-temporary-setting-values [enable-public-sharing true] (with-temp-public-dashboard [dash dashboard-defaults] (with-temp-public-card [card (pivots/pivot-card)] (add-card-to-dashboard! card dash) (let [result (http/client :get 202 (pivot-dashcard-url dash card) :parameters (json/encode [{:name "State" :slug :state :target [:dimension [:fk-> (mt/$ids $orders.user_id) (mt/$ids $people.state)]] :value ["CA" "WA"]}])) rows (mt/rows result)] (is (nil? (:row_count result))) ;; row_count isn't included in public endpoints (is (= "completed" (:status result))) (is (= 6 (count (get-in result [:data :cols])))) (is (= 80 (count rows))) (is (= ["CA" "Affiliate" "Doohickey" 0 16 48] (first rows))) (is (= [nil "Google" "Gizmo" 1 52 186] (nth rows 50))) (is (= [nil nil nil 7 1015 3758] (last rows)))))))))))))
[ { "context": "(comment \n re-core, Copyright 2012 Ronen Narkis, narkisr.com\n Licensed under the Apache License", "end": 49, "score": 0.9998815655708313, "start": 37, "tag": "NAME", "value": "Ronen Narkis" }, { "context": "(comment \n re-core, Copyright 2012 Ronen Narkis, narkisr.com\n Licensed under the Apache License,\n Version ", "end": 62, "score": 0.8992821574211121, "start": 51, "tag": "EMAIL", "value": "narkisr.com" } ]
src/openstack/provider.clj
celestial-ops/core
1
(comment re-core, Copyright 2012 Ronen Narkis, narkisr.com Licensed under the Apache License, Version 2.0 (the "License") you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.) (ns openstack.provider (:require [slingshot.slingshot :refer [throw+]] [re-core.persistency.systems :as s :refer (system-val)] [re-core.common :refer (import-logging)] [openstack.networking :refer (first-ip update-ip assoc-floating dissoc-floating allocate-floating update-floating)] [clojure.java.data :refer [from-java]] [re-core.provider :refer (wait-for wait-for-ssh wait-for-stop running? wait-for-start)] [openstack.validations :refer (provider-validation)] [re-core.core :refer (Vm)] [openstack.volumes :as v] [openstack.common :refer (openstack servers compute)] [re-core.model :refer (hypervisor translate vconstruct)]) (:import org.openstack4j.model.compute.Server$Status org.openstack4j.model.compute.Action org.openstack4j.api.Builders)) (import-logging) (defn image-id [machine] (hypervisor :openstack :ostemplates (machine :os) :id)) (defn flavor-id [f] (hypervisor :openstack :flavors f)) (defn network-ids [nets] (mapv #(hypervisor :openstack :networks %) nets)) (defn floating-ips [tenant] (-> (compute tenant) (.floatingIps))) (defn add-security-groups [b groups] (doseq [g groups] (.addSecurityGroup b g)) b) (defn base-model "Creating base model" [{:keys [machine openstack] :as spec}] (-> (Builders/server) (.name (machine :hostname)) (.flavor (openstack :flavor)) (.image (image-id machine)) (.keypairName (openstack :key-name)) (.networks (openstack :network-ids)) (add-security-groups (openstack :security-groups)) )) (defn add-hints "add hints if available" [base openstack] (reduce (fn [acc [k v]] (debug k v acc) (.addSchedulerHint acc k v)) base (:hints openstack))) (defn model [{:keys [machine openstack] :as spec}] (.build (add-hints (base-model spec) openstack))) (defn wait-for-ip [servers' id network timeout] "Wait for an ip to be avilable" (wait-for {:timeout timeout} #(not (nil? (first-ip (.get servers' id) network))) {:type ::openstack:status-failed :timeout timeout} "Timed out on waiting for ip to be available")) (defn instance-id* [spec] (system-val spec [:openstack :instance-id])) (defmacro with-instance-id [& body] `(if-let [~'instance-id (instance-id* ~'spec)] (do ~@body) (throw+ {:type ::openstack:missing-id} "Instance id not found"))) (defn update-id [spec id] "update instance id" (when (s/system-exists? (spec :system-id)) (s/partial-system (spec :system-id) {:openstack {:instance-id id}}))) (defrecord Instance [tenant spec user] Vm (create [this] (let [servers' (servers tenant) server (.boot servers' (model spec)) instance-id (:id (from-java server)) network (first (get-in spec [:openstack :networks]))] (update-id spec instance-id) (debug "waiting for" instance-id "to get an ip on" network) (wait-for-ip servers' instance-id network [5 :minute]) (update-ip spec (first-ip (.get servers' instance-id) network)) (if-let [ip (get-in spec [:openstack :floating-ip])] (assoc-floating (floating-ips tenant) server ip) (when-let [pool (get-in spec [:openstack :floating-ip-pool])] (let [ip (allocate-floating (floating-ips tenant) pool)] (assoc-floating (floating-ips tenant) server ip) (update-floating spec ip)))) (debug "waiting for ssh to be available at" (.ip this)) (wait-for-ssh (.ip this) (get-in spec [:machine :user]) [5 :minute]) (when-let [volumes (get-in spec [:openstack :volumes])] (doseq [{:keys [device] :as v} volumes :let [vid (v/create spec v tenant)]] (v/attach instance-id vid device tenant))) this)) (start [this] (with-instance-id (when-not (running? this) (debug "starting" instance-id ) (.action (servers tenant) instance-id Action/START) (wait-for-start this [5 :minute] ::openstack:start-failed) (wait-for-ssh (.ip this) (get-in spec [:machine :user]) [5 :minute])))) (delete [this] (with-instance-id (debug "deleting" instance-id) (when-let [volumes (get-in spec [:openstack :volumes])] (doseq [v volumes] (v/destroy instance-id v tenant))) (let [servers' (servers tenant)] (when-let [ip (get-in spec [:openstack :floating-ip])] (dissoc-floating (floating-ips tenant) (.get servers' instance-id) ip)) (.delete servers' instance-id)))) (stop [this] (with-instance-id (debug "stopping" instance-id) (.action (servers tenant) instance-id Action/STOP) (wait-for-stop this [5 :minute] ::openstack:stop-failed))) (status [this] (if-let [instance-id (instance-id* spec)] (let [server (.get (servers tenant) instance-id) value (.toLowerCase (str (.getStatus server)))] (if (= value "active") "running" value)) (do (debug "no instance id found, instance not created") false))) (ip [this] (case (hypervisor :openstack :managment-interface) :floating (system-val spec [:openstack :floating-ip]) :network (system-val spec [:machine :ip]) ))) (defn openstack-spec [spec] (-> spec (assoc-in [:openstack :network-ids] (network-ids (get-in spec [:openstack :networks]))) (update-in [:openstack :flavor] flavor-id))) (defn validate [[tenant spec user :as args]] (provider-validation spec) args) (defmethod translate :openstack [{:keys [openstack machine] :as spec}] [(openstack :tenant) (openstack-spec spec) (or (machine :user) "root")]) (defmethod vconstruct :openstack [spec] (apply ->Instance (validate (translate spec))))
75155
(comment re-core, Copyright 2012 <NAME>, <EMAIL> Licensed under the Apache License, Version 2.0 (the "License") you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.) (ns openstack.provider (:require [slingshot.slingshot :refer [throw+]] [re-core.persistency.systems :as s :refer (system-val)] [re-core.common :refer (import-logging)] [openstack.networking :refer (first-ip update-ip assoc-floating dissoc-floating allocate-floating update-floating)] [clojure.java.data :refer [from-java]] [re-core.provider :refer (wait-for wait-for-ssh wait-for-stop running? wait-for-start)] [openstack.validations :refer (provider-validation)] [re-core.core :refer (Vm)] [openstack.volumes :as v] [openstack.common :refer (openstack servers compute)] [re-core.model :refer (hypervisor translate vconstruct)]) (:import org.openstack4j.model.compute.Server$Status org.openstack4j.model.compute.Action org.openstack4j.api.Builders)) (import-logging) (defn image-id [machine] (hypervisor :openstack :ostemplates (machine :os) :id)) (defn flavor-id [f] (hypervisor :openstack :flavors f)) (defn network-ids [nets] (mapv #(hypervisor :openstack :networks %) nets)) (defn floating-ips [tenant] (-> (compute tenant) (.floatingIps))) (defn add-security-groups [b groups] (doseq [g groups] (.addSecurityGroup b g)) b) (defn base-model "Creating base model" [{:keys [machine openstack] :as spec}] (-> (Builders/server) (.name (machine :hostname)) (.flavor (openstack :flavor)) (.image (image-id machine)) (.keypairName (openstack :key-name)) (.networks (openstack :network-ids)) (add-security-groups (openstack :security-groups)) )) (defn add-hints "add hints if available" [base openstack] (reduce (fn [acc [k v]] (debug k v acc) (.addSchedulerHint acc k v)) base (:hints openstack))) (defn model [{:keys [machine openstack] :as spec}] (.build (add-hints (base-model spec) openstack))) (defn wait-for-ip [servers' id network timeout] "Wait for an ip to be avilable" (wait-for {:timeout timeout} #(not (nil? (first-ip (.get servers' id) network))) {:type ::openstack:status-failed :timeout timeout} "Timed out on waiting for ip to be available")) (defn instance-id* [spec] (system-val spec [:openstack :instance-id])) (defmacro with-instance-id [& body] `(if-let [~'instance-id (instance-id* ~'spec)] (do ~@body) (throw+ {:type ::openstack:missing-id} "Instance id not found"))) (defn update-id [spec id] "update instance id" (when (s/system-exists? (spec :system-id)) (s/partial-system (spec :system-id) {:openstack {:instance-id id}}))) (defrecord Instance [tenant spec user] Vm (create [this] (let [servers' (servers tenant) server (.boot servers' (model spec)) instance-id (:id (from-java server)) network (first (get-in spec [:openstack :networks]))] (update-id spec instance-id) (debug "waiting for" instance-id "to get an ip on" network) (wait-for-ip servers' instance-id network [5 :minute]) (update-ip spec (first-ip (.get servers' instance-id) network)) (if-let [ip (get-in spec [:openstack :floating-ip])] (assoc-floating (floating-ips tenant) server ip) (when-let [pool (get-in spec [:openstack :floating-ip-pool])] (let [ip (allocate-floating (floating-ips tenant) pool)] (assoc-floating (floating-ips tenant) server ip) (update-floating spec ip)))) (debug "waiting for ssh to be available at" (.ip this)) (wait-for-ssh (.ip this) (get-in spec [:machine :user]) [5 :minute]) (when-let [volumes (get-in spec [:openstack :volumes])] (doseq [{:keys [device] :as v} volumes :let [vid (v/create spec v tenant)]] (v/attach instance-id vid device tenant))) this)) (start [this] (with-instance-id (when-not (running? this) (debug "starting" instance-id ) (.action (servers tenant) instance-id Action/START) (wait-for-start this [5 :minute] ::openstack:start-failed) (wait-for-ssh (.ip this) (get-in spec [:machine :user]) [5 :minute])))) (delete [this] (with-instance-id (debug "deleting" instance-id) (when-let [volumes (get-in spec [:openstack :volumes])] (doseq [v volumes] (v/destroy instance-id v tenant))) (let [servers' (servers tenant)] (when-let [ip (get-in spec [:openstack :floating-ip])] (dissoc-floating (floating-ips tenant) (.get servers' instance-id) ip)) (.delete servers' instance-id)))) (stop [this] (with-instance-id (debug "stopping" instance-id) (.action (servers tenant) instance-id Action/STOP) (wait-for-stop this [5 :minute] ::openstack:stop-failed))) (status [this] (if-let [instance-id (instance-id* spec)] (let [server (.get (servers tenant) instance-id) value (.toLowerCase (str (.getStatus server)))] (if (= value "active") "running" value)) (do (debug "no instance id found, instance not created") false))) (ip [this] (case (hypervisor :openstack :managment-interface) :floating (system-val spec [:openstack :floating-ip]) :network (system-val spec [:machine :ip]) ))) (defn openstack-spec [spec] (-> spec (assoc-in [:openstack :network-ids] (network-ids (get-in spec [:openstack :networks]))) (update-in [:openstack :flavor] flavor-id))) (defn validate [[tenant spec user :as args]] (provider-validation spec) args) (defmethod translate :openstack [{:keys [openstack machine] :as spec}] [(openstack :tenant) (openstack-spec spec) (or (machine :user) "root")]) (defmethod vconstruct :openstack [spec] (apply ->Instance (validate (translate spec))))
true
(comment re-core, Copyright 2012 PI:NAME:<NAME>END_PI, PI:EMAIL:<EMAIL>END_PI Licensed under the Apache License, Version 2.0 (the "License") you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.) (ns openstack.provider (:require [slingshot.slingshot :refer [throw+]] [re-core.persistency.systems :as s :refer (system-val)] [re-core.common :refer (import-logging)] [openstack.networking :refer (first-ip update-ip assoc-floating dissoc-floating allocate-floating update-floating)] [clojure.java.data :refer [from-java]] [re-core.provider :refer (wait-for wait-for-ssh wait-for-stop running? wait-for-start)] [openstack.validations :refer (provider-validation)] [re-core.core :refer (Vm)] [openstack.volumes :as v] [openstack.common :refer (openstack servers compute)] [re-core.model :refer (hypervisor translate vconstruct)]) (:import org.openstack4j.model.compute.Server$Status org.openstack4j.model.compute.Action org.openstack4j.api.Builders)) (import-logging) (defn image-id [machine] (hypervisor :openstack :ostemplates (machine :os) :id)) (defn flavor-id [f] (hypervisor :openstack :flavors f)) (defn network-ids [nets] (mapv #(hypervisor :openstack :networks %) nets)) (defn floating-ips [tenant] (-> (compute tenant) (.floatingIps))) (defn add-security-groups [b groups] (doseq [g groups] (.addSecurityGroup b g)) b) (defn base-model "Creating base model" [{:keys [machine openstack] :as spec}] (-> (Builders/server) (.name (machine :hostname)) (.flavor (openstack :flavor)) (.image (image-id machine)) (.keypairName (openstack :key-name)) (.networks (openstack :network-ids)) (add-security-groups (openstack :security-groups)) )) (defn add-hints "add hints if available" [base openstack] (reduce (fn [acc [k v]] (debug k v acc) (.addSchedulerHint acc k v)) base (:hints openstack))) (defn model [{:keys [machine openstack] :as spec}] (.build (add-hints (base-model spec) openstack))) (defn wait-for-ip [servers' id network timeout] "Wait for an ip to be avilable" (wait-for {:timeout timeout} #(not (nil? (first-ip (.get servers' id) network))) {:type ::openstack:status-failed :timeout timeout} "Timed out on waiting for ip to be available")) (defn instance-id* [spec] (system-val spec [:openstack :instance-id])) (defmacro with-instance-id [& body] `(if-let [~'instance-id (instance-id* ~'spec)] (do ~@body) (throw+ {:type ::openstack:missing-id} "Instance id not found"))) (defn update-id [spec id] "update instance id" (when (s/system-exists? (spec :system-id)) (s/partial-system (spec :system-id) {:openstack {:instance-id id}}))) (defrecord Instance [tenant spec user] Vm (create [this] (let [servers' (servers tenant) server (.boot servers' (model spec)) instance-id (:id (from-java server)) network (first (get-in spec [:openstack :networks]))] (update-id spec instance-id) (debug "waiting for" instance-id "to get an ip on" network) (wait-for-ip servers' instance-id network [5 :minute]) (update-ip spec (first-ip (.get servers' instance-id) network)) (if-let [ip (get-in spec [:openstack :floating-ip])] (assoc-floating (floating-ips tenant) server ip) (when-let [pool (get-in spec [:openstack :floating-ip-pool])] (let [ip (allocate-floating (floating-ips tenant) pool)] (assoc-floating (floating-ips tenant) server ip) (update-floating spec ip)))) (debug "waiting for ssh to be available at" (.ip this)) (wait-for-ssh (.ip this) (get-in spec [:machine :user]) [5 :minute]) (when-let [volumes (get-in spec [:openstack :volumes])] (doseq [{:keys [device] :as v} volumes :let [vid (v/create spec v tenant)]] (v/attach instance-id vid device tenant))) this)) (start [this] (with-instance-id (when-not (running? this) (debug "starting" instance-id ) (.action (servers tenant) instance-id Action/START) (wait-for-start this [5 :minute] ::openstack:start-failed) (wait-for-ssh (.ip this) (get-in spec [:machine :user]) [5 :minute])))) (delete [this] (with-instance-id (debug "deleting" instance-id) (when-let [volumes (get-in spec [:openstack :volumes])] (doseq [v volumes] (v/destroy instance-id v tenant))) (let [servers' (servers tenant)] (when-let [ip (get-in spec [:openstack :floating-ip])] (dissoc-floating (floating-ips tenant) (.get servers' instance-id) ip)) (.delete servers' instance-id)))) (stop [this] (with-instance-id (debug "stopping" instance-id) (.action (servers tenant) instance-id Action/STOP) (wait-for-stop this [5 :minute] ::openstack:stop-failed))) (status [this] (if-let [instance-id (instance-id* spec)] (let [server (.get (servers tenant) instance-id) value (.toLowerCase (str (.getStatus server)))] (if (= value "active") "running" value)) (do (debug "no instance id found, instance not created") false))) (ip [this] (case (hypervisor :openstack :managment-interface) :floating (system-val spec [:openstack :floating-ip]) :network (system-val spec [:machine :ip]) ))) (defn openstack-spec [spec] (-> spec (assoc-in [:openstack :network-ids] (network-ids (get-in spec [:openstack :networks]))) (update-in [:openstack :flavor] flavor-id))) (defn validate [[tenant spec user :as args]] (provider-validation spec) args) (defmethod translate :openstack [{:keys [openstack machine] :as spec}] [(openstack :tenant) (openstack-spec spec) (or (machine :user) "root")]) (defmethod vconstruct :openstack [spec] (apply ->Instance (validate (translate spec))))
[ { "context": "s {1 {:player/id 1\n :player/name \"Bela2\"\n :player/game {:game/id 1}}\n", "end": 430, "score": 0.884857177734375, "start": 429, "tag": "NAME", "value": "B" }, { "context": " {1 {:player/id 1\n :player/name \"Bela2\"\n :player/game {:game/id 1}}\n ", "end": 434, "score": 0.9746077060699463, "start": 430, "tag": "USERNAME", "value": "ela2" }, { "context": " 2 {:player/id 2\n :player/name \"Pistidsa\"\n :player/game [{:game/id 2}\n ", "end": 549, "score": 0.9997848272323608, "start": 541, "tag": "NAME", "value": "Pistidsa" }, { "context": " 3 {:player/id 3\n :player/name \"Magus\"\n :player/game {:game/id 3}}})\n\n(", "end": 707, "score": 0.9997523427009583, "start": 702, "tag": "NAME", "value": "Magus" }, { "context": "n/id 1\n :game-station/name \"Crusader\"\n :game-station/game {:game", "end": 849, "score": 0.9002377986907959, "start": 841, "tag": "NAME", "value": "Crusader" }, { "context": "n/id 2\n :game-station/name \"Zelda\"\n :game-station/game {:game", "end": 1056, "score": 0.985988438129425, "start": 1051, "tag": "NAME", "value": "Zelda" }, { "context": "n/id 3\n :game-station/name \"Magus\"\n :game-station/game {:game", "end": 1263, "score": 0.9835100173950195, "start": 1258, "tag": "NAME", "value": "Magus" }, { "context": "n/id 4\n :game-station/name \"Rubick\"\n :game-station/game {:game", "end": 1471, "score": 0.9980623722076416, "start": 1465, "tag": "NAME", "value": "Rubick" } ]
src/main/app/model/lvlup.clj
paul931224/simple-fulcro
0
(ns app.model.lvlup (:require [com.wsscode.pathom.connect :as pc :refer [defresolver defmutation]] ;[taoensso.timbre :as log] [clojure.spec.alpha :as s])) (def games {1 {:game/id 1 :game/name "Overwatch"} 2 {:game/id 2 :game/name "Fallout 2"} 3 {:game/id 3 :game/name "Fallout 3"}}) (def players {1 {:player/id 1 :player/name "Bela2" :player/game {:game/id 1}} 2 {:player/id 2 :player/name "Pistidsa" :player/game [{:game/id 2} {:game/id 1}]} 3 {:player/id 3 :player/name "Magus" :player/game {:game/id 3}}}) (def game-stations {1 {:game-station/id 1 :game-station/name "Crusader" :game-station/game {:game/id 1} :game-station/player {:player/id 1}} 2 {:game-station/id 2 :game-station/name "Zelda" :game-station/game {:game/id 2} :game-station/player {:player/id 2}} 3 {:game-station/id 3 :game-station/name "Magus" :game-station/game {:game/id 3} :game-station/player {:player/id 3}} 4 {:game-station/id 4 :game-station/name "Rubick" :game-station/game {:game/id 2}}}) (defresolver player-resolver [{:keys [db]} {:player/keys [id]}] {::pc/input #{:player/id} ::pc/output [:player/id :player/name :player/game]} (get players id)) (defresolver game-station-resolver [{:keys [db]} {:game-station/keys [id]}] {::pc/input #{:game-station/id} ::pc/output [:game-station/id :game-station/name :game-station/player]} (get game-stations id)) (defresolver game-resolver [{:keys [db]} {:game/keys [id]}] {::pc/input #{:game/id} ::pc/output [:game/id :game/name]} (get games id)) (defresolver time-resolver [{:keys [db]} {:server/keys [time]}] {::pc/output [:server/time]} {:server/time (java.util.Date.)}) (defresolver all-players-resolver [{:keys [db]} input] {::pc/output [{:all-players [:player/id]}]} {:all-players (vec (vals players))}) (defresolver all-games-resolver [{:keys [db]} input] {::pc/output [{:all-games [:game/id :game/name]}]} {:all-games (mapv second games)}) (defresolver all-game-stations-resolver [{:keys [db]} input] {::pc/output [{:all-game-stations [:game-station/id :game-station/name]}]} {:all-game-stations (mapv second game-stations)}) (defmutation make-older [env {::keys [id]}] {::pc/params [:person/id] ::pc/output [:person/id :person/age]}) (def resolvers [ time-resolver all-players-resolver all-games-resolver all-game-stations-resolver player-resolver game-station-resolver game-resolver])
20586
(ns app.model.lvlup (:require [com.wsscode.pathom.connect :as pc :refer [defresolver defmutation]] ;[taoensso.timbre :as log] [clojure.spec.alpha :as s])) (def games {1 {:game/id 1 :game/name "Overwatch"} 2 {:game/id 2 :game/name "Fallout 2"} 3 {:game/id 3 :game/name "Fallout 3"}}) (def players {1 {:player/id 1 :player/name "<NAME>ela2" :player/game {:game/id 1}} 2 {:player/id 2 :player/name "<NAME>" :player/game [{:game/id 2} {:game/id 1}]} 3 {:player/id 3 :player/name "<NAME>" :player/game {:game/id 3}}}) (def game-stations {1 {:game-station/id 1 :game-station/name "<NAME>" :game-station/game {:game/id 1} :game-station/player {:player/id 1}} 2 {:game-station/id 2 :game-station/name "<NAME>" :game-station/game {:game/id 2} :game-station/player {:player/id 2}} 3 {:game-station/id 3 :game-station/name "<NAME>" :game-station/game {:game/id 3} :game-station/player {:player/id 3}} 4 {:game-station/id 4 :game-station/name "<NAME>" :game-station/game {:game/id 2}}}) (defresolver player-resolver [{:keys [db]} {:player/keys [id]}] {::pc/input #{:player/id} ::pc/output [:player/id :player/name :player/game]} (get players id)) (defresolver game-station-resolver [{:keys [db]} {:game-station/keys [id]}] {::pc/input #{:game-station/id} ::pc/output [:game-station/id :game-station/name :game-station/player]} (get game-stations id)) (defresolver game-resolver [{:keys [db]} {:game/keys [id]}] {::pc/input #{:game/id} ::pc/output [:game/id :game/name]} (get games id)) (defresolver time-resolver [{:keys [db]} {:server/keys [time]}] {::pc/output [:server/time]} {:server/time (java.util.Date.)}) (defresolver all-players-resolver [{:keys [db]} input] {::pc/output [{:all-players [:player/id]}]} {:all-players (vec (vals players))}) (defresolver all-games-resolver [{:keys [db]} input] {::pc/output [{:all-games [:game/id :game/name]}]} {:all-games (mapv second games)}) (defresolver all-game-stations-resolver [{:keys [db]} input] {::pc/output [{:all-game-stations [:game-station/id :game-station/name]}]} {:all-game-stations (mapv second game-stations)}) (defmutation make-older [env {::keys [id]}] {::pc/params [:person/id] ::pc/output [:person/id :person/age]}) (def resolvers [ time-resolver all-players-resolver all-games-resolver all-game-stations-resolver player-resolver game-station-resolver game-resolver])
true
(ns app.model.lvlup (:require [com.wsscode.pathom.connect :as pc :refer [defresolver defmutation]] ;[taoensso.timbre :as log] [clojure.spec.alpha :as s])) (def games {1 {:game/id 1 :game/name "Overwatch"} 2 {:game/id 2 :game/name "Fallout 2"} 3 {:game/id 3 :game/name "Fallout 3"}}) (def players {1 {:player/id 1 :player/name "PI:NAME:<NAME>END_PIela2" :player/game {:game/id 1}} 2 {:player/id 2 :player/name "PI:NAME:<NAME>END_PI" :player/game [{:game/id 2} {:game/id 1}]} 3 {:player/id 3 :player/name "PI:NAME:<NAME>END_PI" :player/game {:game/id 3}}}) (def game-stations {1 {:game-station/id 1 :game-station/name "PI:NAME:<NAME>END_PI" :game-station/game {:game/id 1} :game-station/player {:player/id 1}} 2 {:game-station/id 2 :game-station/name "PI:NAME:<NAME>END_PI" :game-station/game {:game/id 2} :game-station/player {:player/id 2}} 3 {:game-station/id 3 :game-station/name "PI:NAME:<NAME>END_PI" :game-station/game {:game/id 3} :game-station/player {:player/id 3}} 4 {:game-station/id 4 :game-station/name "PI:NAME:<NAME>END_PI" :game-station/game {:game/id 2}}}) (defresolver player-resolver [{:keys [db]} {:player/keys [id]}] {::pc/input #{:player/id} ::pc/output [:player/id :player/name :player/game]} (get players id)) (defresolver game-station-resolver [{:keys [db]} {:game-station/keys [id]}] {::pc/input #{:game-station/id} ::pc/output [:game-station/id :game-station/name :game-station/player]} (get game-stations id)) (defresolver game-resolver [{:keys [db]} {:game/keys [id]}] {::pc/input #{:game/id} ::pc/output [:game/id :game/name]} (get games id)) (defresolver time-resolver [{:keys [db]} {:server/keys [time]}] {::pc/output [:server/time]} {:server/time (java.util.Date.)}) (defresolver all-players-resolver [{:keys [db]} input] {::pc/output [{:all-players [:player/id]}]} {:all-players (vec (vals players))}) (defresolver all-games-resolver [{:keys [db]} input] {::pc/output [{:all-games [:game/id :game/name]}]} {:all-games (mapv second games)}) (defresolver all-game-stations-resolver [{:keys [db]} input] {::pc/output [{:all-game-stations [:game-station/id :game-station/name]}]} {:all-game-stations (mapv second game-stations)}) (defmutation make-older [env {::keys [id]}] {::pc/params [:person/id] ::pc/output [:person/id :person/age]}) (def resolvers [ time-resolver all-players-resolver all-games-resolver all-game-stations-resolver player-resolver game-station-resolver game-resolver])
[ { "context": "epository \\\"deb https://raw.githubusercontent.com/narkisr/fpm-barbecue/repo/packages/ubuntu/ xenial main\\\" ", "end": 1738, "score": 0.9996708035469055, "start": 1731, "tag": "USERNAME", "value": "narkisr" }, { "context": "epository \\\"deb https://raw.githubusercontent.com/narkisr/fpm-barbecue/repo/packages/ubuntu/ xenial main\\\" ", "end": 1861, "score": 0.9996510148048401, "start": 1854, "tag": "USERNAME", "value": "narkisr" }, { "context": "urce:\n (key-server \\\"keyserver.ubuntu.com\\\" \\\"42ED3C30B8C9F76BC85AC1EC8B095396E29035F0\\\")\n \"\n [server id]\n (case (os)\n :Ubuntu (sh \"", "end": 2777, "score": 0.9913355112075806, "start": 2734, "tag": "KEY", "value": "42ED3C30B8C9F76BC85AC1EC8B095396E29035F0\\\")" } ]
src/re_cog/resources/package.clj
re-ops/re-cog
5
(ns re-cog.resources.package (:require [re-cog.resources.download :refer (download)] [re-cog.common.resources :refer (run-)] [re-cog.common.functions :refer (require-functions)] [re-cog.common.defs :refer (def-serial def-inline)] [re-cog.common.constants :refer (require-constants)])) (require-functions) (require-constants) (def-serial installed? "Check is package is installed" [pkg] (case (os) :Ubuntu (sh "sudo" "/usr/bin/dpkg" "-s" pkg) :default (throw (ex-info (<< "No matching package provider found for ~(os)") {})))) ; consumers (def-serial package "Package resource with optional provider and state parameters: (package \"ghc\" :present) (package \"/tmp/foo.deb\" deb :present) ; using deb provider (package \"ghc\" :absent) ; remove package " [pkg state] (letfn [(install [pkg] (sh "sudo" "/usr/bin/env" "DEBIAN_FRONTEND=noninteractive" apt-bin "install" pkg "-y")) (uninstall [pkg] (if (.endsWith pkg "deb") (sh "sudo" dpkg-bin "-r" pkg) (sh "sudo" apt-bin "remove" pkg "-y")))] (let [fns {:present install :absent uninstall}] (debug "installing") ((fns state) pkg)))) (def-serial update- "Update package repository index resource: (update)" [] (letfn [(update-script [] (script ("sudo" ~apt-bin "update")))] (run- update-script))) (def-serial upgrade "Upgrade installed packages: (upgrade) " [] (letfn [(upgrade-script [] (script ("sudo" ~apt-bin "upgrade" "-y")))] (run- upgrade-script))) (def-serial repository "Package repository resource: (repository \"deb https://raw.githubusercontent.com/narkisr/fpm-barbecue/repo/packages/ubuntu/ xenial main\" :present) (repository \"deb https://raw.githubusercontent.com/narkisr/fpm-barbecue/repo/packages/ubuntu/ xenial main\" :absent) (repository \"ppa:neovim-ppa/stable\" :present) (repository \"ppa:neovim-ppa/stable\" :absent) " [repo state] (letfn [(add-repo [repo] (sh "sudo" "/usr/bin/add-apt-repository" repo "-y")) (rm-repo [repo] (sh "sudo" "/usr/bin/add-apt-repository" "--remove" repo "-y"))] (let [fns {:present add-repo :absent rm-repo}] ((fns state) repo)))) (def-serial key-file "Import a gpg apt key from a file resource: (key-file \"key.gpg\") " [file] (case (os) :Ubuntu (sh "sudo" "/usr/bin/apt-key" "add" file) :Raspbian_GNU/Linux (sh "sudo" "/usr/bin/apt-key" "add" file) :default (throw (ex-info (<< "cant import apt key under os ~(os)") {})))) (def-serial key-server "Import a gpg apt key from a gpg server resource: (key-server \"keyserver.ubuntu.com\" \"42ED3C30B8C9F76BC85AC1EC8B095396E29035F0\") " [server id] (case (os) :Ubuntu (sh "sudo" "/usr/bin/apt-key" "adv" "--keyserver" server "--recv" id) :default (throw (ex-info (<< "cant import apt key under ~(os)") {})))) (def-serial fingerprint "Verify a apt-key gpg key signature with id" [id] (sh "/usr/bin/apt-key" "fingerprint" id)) (def-serial set-selection "Set debconf selection for setting package options during headless installation" [package k t value] (letfn [(set-selection [option] (fn [] (script (pipe ("echo" ~option) ("sudo" "debconf-set-selections")))))] (run- (set-selection (<< "~{package} ~{package}/~{k} ~{t} ~{value}")))))
24860
(ns re-cog.resources.package (:require [re-cog.resources.download :refer (download)] [re-cog.common.resources :refer (run-)] [re-cog.common.functions :refer (require-functions)] [re-cog.common.defs :refer (def-serial def-inline)] [re-cog.common.constants :refer (require-constants)])) (require-functions) (require-constants) (def-serial installed? "Check is package is installed" [pkg] (case (os) :Ubuntu (sh "sudo" "/usr/bin/dpkg" "-s" pkg) :default (throw (ex-info (<< "No matching package provider found for ~(os)") {})))) ; consumers (def-serial package "Package resource with optional provider and state parameters: (package \"ghc\" :present) (package \"/tmp/foo.deb\" deb :present) ; using deb provider (package \"ghc\" :absent) ; remove package " [pkg state] (letfn [(install [pkg] (sh "sudo" "/usr/bin/env" "DEBIAN_FRONTEND=noninteractive" apt-bin "install" pkg "-y")) (uninstall [pkg] (if (.endsWith pkg "deb") (sh "sudo" dpkg-bin "-r" pkg) (sh "sudo" apt-bin "remove" pkg "-y")))] (let [fns {:present install :absent uninstall}] (debug "installing") ((fns state) pkg)))) (def-serial update- "Update package repository index resource: (update)" [] (letfn [(update-script [] (script ("sudo" ~apt-bin "update")))] (run- update-script))) (def-serial upgrade "Upgrade installed packages: (upgrade) " [] (letfn [(upgrade-script [] (script ("sudo" ~apt-bin "upgrade" "-y")))] (run- upgrade-script))) (def-serial repository "Package repository resource: (repository \"deb https://raw.githubusercontent.com/narkisr/fpm-barbecue/repo/packages/ubuntu/ xenial main\" :present) (repository \"deb https://raw.githubusercontent.com/narkisr/fpm-barbecue/repo/packages/ubuntu/ xenial main\" :absent) (repository \"ppa:neovim-ppa/stable\" :present) (repository \"ppa:neovim-ppa/stable\" :absent) " [repo state] (letfn [(add-repo [repo] (sh "sudo" "/usr/bin/add-apt-repository" repo "-y")) (rm-repo [repo] (sh "sudo" "/usr/bin/add-apt-repository" "--remove" repo "-y"))] (let [fns {:present add-repo :absent rm-repo}] ((fns state) repo)))) (def-serial key-file "Import a gpg apt key from a file resource: (key-file \"key.gpg\") " [file] (case (os) :Ubuntu (sh "sudo" "/usr/bin/apt-key" "add" file) :Raspbian_GNU/Linux (sh "sudo" "/usr/bin/apt-key" "add" file) :default (throw (ex-info (<< "cant import apt key under os ~(os)") {})))) (def-serial key-server "Import a gpg apt key from a gpg server resource: (key-server \"keyserver.ubuntu.com\" \"<KEY> " [server id] (case (os) :Ubuntu (sh "sudo" "/usr/bin/apt-key" "adv" "--keyserver" server "--recv" id) :default (throw (ex-info (<< "cant import apt key under ~(os)") {})))) (def-serial fingerprint "Verify a apt-key gpg key signature with id" [id] (sh "/usr/bin/apt-key" "fingerprint" id)) (def-serial set-selection "Set debconf selection for setting package options during headless installation" [package k t value] (letfn [(set-selection [option] (fn [] (script (pipe ("echo" ~option) ("sudo" "debconf-set-selections")))))] (run- (set-selection (<< "~{package} ~{package}/~{k} ~{t} ~{value}")))))
true
(ns re-cog.resources.package (:require [re-cog.resources.download :refer (download)] [re-cog.common.resources :refer (run-)] [re-cog.common.functions :refer (require-functions)] [re-cog.common.defs :refer (def-serial def-inline)] [re-cog.common.constants :refer (require-constants)])) (require-functions) (require-constants) (def-serial installed? "Check is package is installed" [pkg] (case (os) :Ubuntu (sh "sudo" "/usr/bin/dpkg" "-s" pkg) :default (throw (ex-info (<< "No matching package provider found for ~(os)") {})))) ; consumers (def-serial package "Package resource with optional provider and state parameters: (package \"ghc\" :present) (package \"/tmp/foo.deb\" deb :present) ; using deb provider (package \"ghc\" :absent) ; remove package " [pkg state] (letfn [(install [pkg] (sh "sudo" "/usr/bin/env" "DEBIAN_FRONTEND=noninteractive" apt-bin "install" pkg "-y")) (uninstall [pkg] (if (.endsWith pkg "deb") (sh "sudo" dpkg-bin "-r" pkg) (sh "sudo" apt-bin "remove" pkg "-y")))] (let [fns {:present install :absent uninstall}] (debug "installing") ((fns state) pkg)))) (def-serial update- "Update package repository index resource: (update)" [] (letfn [(update-script [] (script ("sudo" ~apt-bin "update")))] (run- update-script))) (def-serial upgrade "Upgrade installed packages: (upgrade) " [] (letfn [(upgrade-script [] (script ("sudo" ~apt-bin "upgrade" "-y")))] (run- upgrade-script))) (def-serial repository "Package repository resource: (repository \"deb https://raw.githubusercontent.com/narkisr/fpm-barbecue/repo/packages/ubuntu/ xenial main\" :present) (repository \"deb https://raw.githubusercontent.com/narkisr/fpm-barbecue/repo/packages/ubuntu/ xenial main\" :absent) (repository \"ppa:neovim-ppa/stable\" :present) (repository \"ppa:neovim-ppa/stable\" :absent) " [repo state] (letfn [(add-repo [repo] (sh "sudo" "/usr/bin/add-apt-repository" repo "-y")) (rm-repo [repo] (sh "sudo" "/usr/bin/add-apt-repository" "--remove" repo "-y"))] (let [fns {:present add-repo :absent rm-repo}] ((fns state) repo)))) (def-serial key-file "Import a gpg apt key from a file resource: (key-file \"key.gpg\") " [file] (case (os) :Ubuntu (sh "sudo" "/usr/bin/apt-key" "add" file) :Raspbian_GNU/Linux (sh "sudo" "/usr/bin/apt-key" "add" file) :default (throw (ex-info (<< "cant import apt key under os ~(os)") {})))) (def-serial key-server "Import a gpg apt key from a gpg server resource: (key-server \"keyserver.ubuntu.com\" \"PI:KEY:<KEY>END_PI " [server id] (case (os) :Ubuntu (sh "sudo" "/usr/bin/apt-key" "adv" "--keyserver" server "--recv" id) :default (throw (ex-info (<< "cant import apt key under ~(os)") {})))) (def-serial fingerprint "Verify a apt-key gpg key signature with id" [id] (sh "/usr/bin/apt-key" "fingerprint" id)) (def-serial set-selection "Set debconf selection for setting package options during headless installation" [package k t value] (letfn [(set-selection [option] (fn [] (script (pipe ("echo" ~option) ("sudo" "debconf-set-selections")))))] (run- (set-selection (<< "~{package} ~{package}/~{k} ~{t} ~{value}")))))